diff --git a/.obsidian/graph.json b/.obsidian/graph.json index 7629ef08..001c2395 100644 --- a/.obsidian/graph.json +++ b/.obsidian/graph.json @@ -1,6 +1,6 @@ { "collapse-filter": false, - "search": "", + "search": "tag:#s/politique ", "showTags": false, "showAttachments": false, "hideUnresolved": false, @@ -130,6 +130,6 @@ "repelStrength": 5.263671875, "linkStrength": 1, "linkDistance": 30, - "scale": 0.08412936276539293, - "close": true + "scale": 0.6928227602701377, + "close": false } \ No newline at end of file diff --git a/.obsidian/plugins/better-export-pdf/main.js b/.obsidian/plugins/better-export-pdf/main.js index d9dcd6a7..cf0f7dba 100644 --- a/.obsidian/plugins/better-export-pdf/main.js +++ b/.obsidian/plugins/better-export-pdf/main.js @@ -1,5 +1,11 @@ -var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`obsidian`),u=require(`electron`);u=c(u);let d=require(`path`);d=c(d);let f=require(`os`);f=c(f);var p=c(o(((e,t)=>{var n=function(e){return r(e)&&!i(e)};function r(e){return!!e&&typeof e==`object`}function i(e){var t=Object.prototype.toString.call(e);return t===`[object RegExp]`||t===`[object Date]`||o(e)}var a=typeof Symbol==`function`&&Symbol.for?Symbol.for(`react.element`):60103;function o(e){return e.$$typeof===a}function s(e){return Array.isArray(e)?[]:{}}function c(e,t){return t.clone!==!1&&t.isMergeableObject(e)?g(s(e),e,t):e}function l(e,t,n){return e.concat(t).map(function(e){return c(e,n)})}function u(e,t){if(!t.customMerge)return g;var n=t.customMerge(e);return typeof n==`function`?n:g}function d(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function f(e){return Object.keys(e).concat(d(e))}function p(e,t){try{return t in e}catch{return!1}}function m(e,t){return p(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function h(e,t,n){var r={};return n.isMergeableObject(e)&&f(e).forEach(function(t){r[t]=c(e[t],n)}),f(t).forEach(function(i){m(e,i)||(p(e,i)&&n.isMergeableObject(t[i])?r[i]=u(i,n)(e[i],t[i],n):r[i]=c(t[i],n))}),r}function g(e,t,r){r=r||{},r.arrayMerge=r.arrayMerge||l,r.isMergeableObject=r.isMergeableObject||n,r.cloneUnlessOtherwiseSpecified=c;var i=Array.isArray(t);return i===Array.isArray(e)?i?r.arrayMerge(e,t,r):h(e,t,r):c(t,r)}g.all=function(e,t){if(!Array.isArray(e))throw Error(`first argument should be an array`);return e.reduce(function(e,n){return g(e,n,t)},{})},t.exports=g}))()),m={i18n:{en:{exportCurrentFile:`Export current file to PDF`,exportCurrentFileWithPrevious:`Export to PDF with previous Settings`,exportDialog:{filenameAsTitle:`Include file name as title`,pageSize:`Page Size`,margin:`Margin`,downscalePercent:`Downscale Percent`,landscape:`Landscape`,displayHeader:`Display Header`,displayFooter:`Display Footer`,openAfterExport:`Open after export`,cssSnippets:`CSS snippets`},settings:{showTitle:`Add file name as title`,displayHeader:`Display headers`,displayFooter:`Display footer`,printBackground:`Print background`,maxLevel:`Max headings level of the outline`,displayMetadata:`PDF metadata`,headerTemplate:`Header Template`,footerTemplate:`Footer Template`,isTimestamp:`Add timestamp`,enabledCss:`Enable select css snippets`,concurrency:`Limit concurrency`,debugMode:`Debug Mode`,version:`Engine Version`}},zh:{exportCurrentFile:`导出当前文件为PDF`,exportCurrentFileWithPrevious:`使用上一次设置导出为PDF`,exportDialog:{filenameAsTitle:`将笔记名作为标题`,pageSize:`纸张尺寸`,margin:`页边距`,downscalePercent:`缩放`,landscape:`横向打印`,displayHeader:`页眉`,displayFooter:`页脚`,openAfterExport:`导出后打开`,cssSnippets:`CSS代码片段`},settings:{showTitle:`将笔记名作为标题`,displayHeader:`显示页眉`,displayFooter:`显示页脚`,printBackground:`打印背景`,maxLevel:`最大标题级别`,displayMetadata:`PDF元数据`,headerTemplate:`页眉模板`,footerTemplate:`页脚模板`,isTimestamp:`文件名添加时间戳`,enabledCss:`启用CSS片段选择`,concurrency:`限制并发数`,debugMode:`调试模式`,version:`引擎版本`}}},get current(){let e=window.localStorage.getItem(`language`)??`en`;return(0,p.default)(this.i18n.en,this.i18n[e]??{})}},h=Array.isArray,g=Array.prototype.indexOf,_=Array.prototype.includes,v=Array.from,y=Object.defineProperty,b=Object.getOwnPropertyDescriptor,x=Object.getOwnPropertyDescriptors,S=Object.prototype,C=Array.prototype,w=Object.getPrototypeOf,T=Object.isExtensible,E=()=>{};function D(e){for(var t=0;t{e=n,t=r}),resolve:e,reject:t}}function k(e){"@babel/helpers - typeof";return k=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},k(e)}function ee(e,t){if(k(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(k(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function A(e){var t=ee(e,`string`);return k(t)==`symbol`?t:t+``}function j(e,t,n){return(t=A(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var te=1024,ne=2048,re=4096,ie=8192,ae=16384,oe=32768,se=1<<25,ce=65536,le=1<<19,ue=1<<20,M=1<<25,N=65536,de=1<<21,fe=1<<22,pe=1<<23,me=Symbol(`$state`),he=Symbol(`legacy props`),ge=Symbol(``),_e=Symbol(`attributes`),ve=Symbol(`class`),P=Symbol(`style`),ye=Symbol(`text`),be=new class extends Error{constructor(...e){super(...e),j(this,`name`,`StaleReactionError`),j(this,`message`,"The reaction that called `getAbortSignal()` was re-run or destroyed")}},xe=!!globalThis.document?.contentType&&globalThis.document.contentType.includes(`xml`);function F(e){throw Error(`https://svelte.dev/e/lifecycle_outside_component`)}function Se(){throw Error(`https://svelte.dev/e/async_derived_orphan`)}function I(e,t,n){throw Error(`https://svelte.dev/e/each_key_duplicate`)}function Ce(e){throw Error(`https://svelte.dev/e/effect_in_teardown`)}function L(){throw Error(`https://svelte.dev/e/effect_in_unowned_derived`)}function R(e){throw Error(`https://svelte.dev/e/effect_orphan`)}function we(){throw Error(`https://svelte.dev/e/effect_update_depth_exceeded`)}function Te(e){throw Error(`https://svelte.dev/e/props_invalid_value`)}function Ee(){throw Error(`https://svelte.dev/e/state_descriptors_fixed`)}function De(){throw Error(`https://svelte.dev/e/state_prototype_fixed`)}function z(){throw Error(`https://svelte.dev/e/state_unsafe_mutation`)}function Oe(){throw Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`)}var ke={},Ae=Symbol(`uninitialized`);function je(){console.warn(`https://svelte.dev/e/derived_inert`)}function Me(e){console.warn(`https://svelte.dev/e/hydration_mismatch`)}function Ne(){console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`)}var Pe=!1;function Fe(e){Pe=e}var Ie;function Le(e){if(e===null)throw Me(),ke;return Ie=e}function Re(){return Le(br(Ie))}function ze(e){if(Pe){if(br(Ie)!==null)throw Me(),ke;Ie=e}}function Be(e=1){if(Pe){for(var t=e,n=Ie;t--;)n=br(n);Ie=n}}function Ve(e=!0){for(var t=0,n=Ie;;){if(n.nodeType===8){var r=n.data;if(r===`]`){if(t===0)return n;--t}else (r===`[`||r===`[!`||r[0]===`[`&&!isNaN(Number(r.slice(1))))&&(t+=1)}var i=br(n);e&&n.remove(),n=i}}function He(e){if(!e||e.nodeType!==8)throw Me(),ke;return e.data}function Ue(e){return e===this.v}function We(e,t){return e==e?e!==t||typeof e==`object`&&!!e||typeof e==`function`:t==t}function Ge(e){return!We(e,this.v)}var Ke=!1,qe=!1,Je=[];function Ye(e,t=!1,n=!1){return Xe(e,new Map,``,Je,null,n)}function Xe(e,t,n,r,i=null,a=!1){if(typeof e==`object`&&e){var o=t.get(e);if(o!==void 0)return o;if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);if(h(e)){var s=Array(e.length);t.set(e,s),i!==null&&t.set(i,s);for(var c=0;c{t===nt&&rt()})}nt.push(e)}function at(e){var t=si;if(t===null)return ii.f|=pe,e;if(!(t.f&32768)&&!(t.f&4))throw e;ot(e,t)}function ot(e,t){for(;t!==null;){if(t.f&128){if(!(t.f&32768))throw e;try{t.b.error(e);return}catch(t){e=t}}t=t.parent}throw e}var st=~(ne|re|te);function ct(e,t){e.f=e.f&st|t}function lt(e){e.f&512||e.deps===null?ct(e,te):ct(e,re)}function ut(e){if(e!==null)for(let t of e)!(t.f&2)||!(t.f&65536)||(t.f^=N,ut(t.deps))}function dt(e,t,n){e.f&2048?t.add(e):e.f&4096&&n.add(e),ut(e.deps),ct(e,te)}var ft=!1,pt=!1;function mt(e){var t=pt;try{return pt=!1,[e(),pt]}finally{pt=t}}function ht(e){let t=0,n=ir(0),r;return()=>{Mr()&&(H(n),zr(()=>(t===0&&(r=Oi(()=>e(()=>ur(n)))),t+=1,()=>{it(()=>{--t,t===0&&(r?.(),r=void 0,ur(n))})})))}}function gt(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function _t(e,t){gt(e,t),t.add(e)}function vt(e,t,n){gt(e,t),t.set(e,n)}function yt(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function B(e,t,n){return e.set(yt(e,t),n),n}function V(e,t){return e.get(yt(e,t))}var bt=ce|le;function xt(e,t,n,r){new zt(e,t,n,r)}var St=new WeakMap,Ct=new WeakMap,wt=new WeakMap,Tt=new WeakMap,Et=new WeakMap,Dt=new WeakMap,Ot=new WeakMap,kt=new WeakMap,At=new WeakMap,jt=new WeakMap,Mt=new WeakMap,Nt=new WeakMap,Pt=new WeakMap,Ft=new WeakMap,It=new WeakMap,Lt=new WeakMap,Rt=new WeakSet,zt=class{constructor(e,t,n,r){_t(this,Rt),j(this,`parent`,void 0),j(this,`is_pending`,!1),j(this,`transform_error`,void 0),vt(this,St,void 0),vt(this,Ct,Pe?Ie:null),vt(this,wt,void 0),vt(this,Tt,void 0),vt(this,Et,void 0),vt(this,Dt,null),vt(this,Ot,null),vt(this,kt,null),vt(this,At,null),vt(this,jt,0),vt(this,Mt,0),vt(this,Nt,!1),vt(this,Pt,new Set),vt(this,Ft,new Set),vt(this,It,null),vt(this,Lt,ht(()=>(B(It,this,ir(V(jt,this))),()=>{B(It,this,null)}))),B(St,this,e),B(wt,this,t),B(Tt,this,e=>{var t=si;t.b=this,t.f|=128,n(e)}),this.parent=si.b,this.transform_error=r??this.parent?.transform_error??(e=>e),B(Et,this,Vr(()=>{if(Pe){let e=V(Ct,this);Re();let t=e.data===`[!`;if(e.data.startsWith(`[?`)){let t=JSON.parse(e.data.slice(2));yt(Rt,this,Vt).call(this,t)}else t?yt(Rt,this,Ht).call(this):yt(Rt,this,Bt).call(this)}else yt(Rt,this,Ut).call(this)},bt)),Pe&&B(St,this,Ie)}defer_effect(e){dt(e,V(Pt,this),V(Ft,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!V(wt,this).pending}update_pending_count(e,t){yt(Rt,this,Kt).call(this,e,t),B(jt,this,V(jt,this)+e),!(!V(It,this)||V(Nt,this))&&(B(Nt,this,!0),it(()=>{B(Nt,this,!1),V(It,this)&&cr(V(It,this),V(jt,this))}))}get_effect_pending(){return V(Lt,this).call(this),H(V(It,this))}error(e){if(!V(wt,this).onerror&&!V(wt,this).failed)throw e;fn?.is_fork?(V(Dt,this)&&fn.skip_effect(V(Dt,this)),V(Ot,this)&&fn.skip_effect(V(Ot,this)),V(kt,this)&&fn.skip_effect(V(kt,this)),fn.oncommit(()=>{yt(Rt,this,qt).call(this,e)})):yt(Rt,this,qt).call(this,e)}};function Bt(){try{B(Dt,this,Hr(()=>V(Tt,this).call(this,V(St,this))))}catch(e){this.error(e)}}function Vt(e){let t=V(wt,this).failed;t&&B(kt,this,Hr(()=>{t(V(St,this),()=>e,()=>()=>{})}))}function Ht(){let e=V(wt,this).pending;e&&(this.is_pending=!0,B(Ot,this,Hr(()=>e(V(St,this)))),it(()=>{var e=B(At,this,document.createDocumentFragment()),t=vr();e.append(t),B(Dt,this,yt(Rt,this,Gt).call(this,()=>Hr(()=>V(Tt,this).call(this,t)))),V(Mt,this)===0&&(V(St,this).before(e),B(At,this,null),Yr(V(Ot,this),()=>{B(Ot,this,null)}),yt(Rt,this,Wt).call(this,fn))}))}function Ut(){try{if(this.is_pending=this.has_pending_snippet(),B(Mt,this,0),B(jt,this,0),B(Dt,this,Hr(()=>{V(Tt,this).call(this,V(St,this))})),V(Mt,this)>0){var e=B(At,this,document.createDocumentFragment());$r(V(Dt,this),e);let t=V(wt,this).pending;B(Ot,this,Hr(()=>t(V(St,this))))}else yt(Rt,this,Wt).call(this,fn)}catch(e){this.error(e)}}function Wt(e){this.is_pending=!1,e.transfer_effects(V(Pt,this),V(Ft,this))}function Gt(e){var t=si,n=ii,r=Ze;ci(V(Et,this)),oi(V(Et,this)),Qe(V(Et,this).ctx);try{return Rn.ensure(),e()}catch(e){return at(e),null}finally{ci(t),oi(n),Qe(r)}}function Kt(e,t){if(!this.has_pending_snippet()){if(this.parent){var n;yt(Rt,n=this.parent,Kt).call(n,e,t)}return}B(Mt,this,V(Mt,this)+e),V(Mt,this)===0&&(yt(Rt,this,Wt).call(this,t),V(Ot,this)&&Yr(V(Ot,this),()=>{B(Ot,this,null)}),V(At,this)&&(V(St,this).before(V(At,this)),B(At,this,null)))}function qt(e){V(Dt,this)&&(Kr(V(Dt,this)),B(Dt,this,null)),V(Ot,this)&&(Kr(V(Ot,this)),B(Ot,this,null)),V(kt,this)&&(Kr(V(kt,this)),B(kt,this,null)),Pe&&(Le(V(Ct,this)),Be(),Le(Ve()));var t=V(wt,this).onerror;let n=V(wt,this).failed;var r=!1,i=!1;let a=()=>{if(r){Ne();return}r=!0,i&&Oe(),V(kt,this)!==null&&Yr(V(kt,this),()=>{B(kt,this,null)}),yt(Rt,this,Gt).call(this,()=>{yt(Rt,this,Ut).call(this)})},o=e=>{try{i=!0,t?.(e,a),i=!1}catch(e){ot(e,V(Et,this)&&V(Et,this).parent)}n&&B(kt,this,yt(Rt,this,Gt).call(this,()=>{try{return Hr(()=>{var t=si;t.b=this,t.f|=128,n(V(St,this),()=>e,()=>a)})}catch(e){return ot(e,V(Et,this).parent),null}}))};it(()=>{var t;try{t=this.transform_error(e)}catch(e){ot(e,V(Et,this)&&V(Et,this).parent);return}typeof t==`object`&&t&&typeof t.then==`function`?t.then(o,e=>ot(e,V(Et,this)&&V(Et,this).parent)):o(t)})}function Jt(e,t,n,r){let i=tt()?Qt:nn;var a=e.filter(e=>!e.settled),o=t.map(i);if(n.length===0&&a.length===0){r(o);return}var s=si,c=Yt(),l=a.length===1?a[0].promise:a.length>1?Promise.all(a.map(e=>e.promise)):null;function u(e){if(!(s.f&16384)){c();try{r([...o,...e])}catch(e){ot(e,s)}Xt()}}var d=Zt();if(n.length===0){l.then(()=>u([])).finally(d);return}function f(){Promise.all(n.map(e=>en(e))).then(u).catch(e=>ot(e,s)).finally(d)}l?l.then(()=>{c(),f(),Xt()}):f()}function Yt(){var e=si,t=ii,n=Ze,r=fn;return function(i=!0){ci(e),oi(t),Qe(n),i&&!(e.f&16384)&&(r?.activate(),r?.apply())}}function Xt(e=!0){ci(null),oi(null),Qe(null),e&&fn?.deactivate()}function Zt(){var e=si,t=e.b,n=fn,r=!!t?.is_rendered();return t?.update_pending_count(1,n),n.increment(r,e),()=>{t?.update_pending_count(-1,n),n.decrement(r,e)}}function Qt(e){var t=2|ne;return si!==null&&(si.f|=le),{ctx:Ze,deps:null,effects:null,equals:Ue,f:t,fn:e,reactions:null,rv:0,v:Ae,wv:0,parent:si,ac:null}}var $t=Symbol(`obsolete`);function en(e,t,n){let r=si;r===null&&Se();var i=void 0,a=ir(Ae),o=!ii,s=new Set;return Rr(()=>{var t=si,n=O();i=n.promise;try{Promise.resolve(e()).then(n.resolve,e=>{e!==be&&n.reject(e)}).finally(Xt)}catch(e){n.reject(e),Xt()}var c=fn;if(o){if(t.f&32768)var l=Zt();if(r.b?.is_rendered())c.async_deriveds.get(t)?.reject($t);else for(let e of s.values())e.reject($t);s.add(n),c.async_deriveds.set(t,n)}let u=(e,t=void 0)=>{l?.(),s.delete(n),t!==$t&&(c.activate(),t?(a.f|=pe,cr(a,t)):(a.f&8388608&&(a.f^=pe),cr(a,e)),c.deactivate())};n.promise.then(u,e=>u(null,e||`unknown`))}),Nr(()=>{for(let e of s)e.reject($t)}),new Promise(e=>{function t(n){function r(){n===i?e(a):t(i)}n.then(r,r)}t(i)})}function tn(e){let t=Qt(e);return Ke||ui(t),t}function nn(e){let t=Qt(e);return t.equals=Ge,t}function rn(e){var t=e.effects;if(t!==null){e.effects=null;for(var n=0;nthis.schedule(e)){var n=V(Pn,this).get(e);if(n){V(Pn,this).delete(e);for(var r of n.d)ct(r,ne),t(r);for(r of n.m)ct(r,re),t(r)}V(Fn,this).add(e)}capture(e,t,n=!1){e.v!==Ae&&!this.previous.has(e)&&this.previous.set(e,e.v),e.f&8388608||(this.current.set(e,[t,n]),mn?.set(e,t)),this.is_fork||(e.v=t)}activate(){fn=this}deactivate(){fn=null,mn=null}flush(){try{_n=!0,fn=this,yt(Ln,this,Bn).call(this)}finally{bn=0,hn=null,vn=null,yn=null,_n=!1,fn=null,mn=null,nr.clear()}}discard(){for(let e of V(En,this))e(this);V(En,this).clear();for(let e of this.async_deriveds.values())e.reject($t);yt(Ln,this,Kn).call(this),V(kn,this)?.resolve()}register_created_effect(e){V(jn,this).push(e)}increment(e,t){if(B(Dn,this,V(Dn,this)+1),e){let e=V(On,this).get(t)??0;V(On,this).set(t,e+1)}}decrement(e,t){if(B(Dn,this,V(Dn,this)-1),e){let e=V(On,this).get(t)??0;e===1?V(On,this).delete(t):V(On,this).set(t,e-1)}V(In,this)||(B(In,this,!0),it(()=>{B(In,this,!1),this.linked&&this.flush()}))}transfer_effects(e,t){for(let t of e)V(Mn,this).add(t);for(let e of t)V(Nn,this).add(e);e.clear(),t.clear()}oncommit(e){V(Tn,this).add(e)}ondiscard(e){V(En,this).add(e)}settled(){return(V(kn,this)??B(kn,this,O())).promise}static ensure(){if(fn===null){let t=fn=new e;!_n&&!gn&&it(()=>{V(Sn,t)||t.flush()})}return fn}apply(){if(!Ke||!this.is_fork&&V(Cn,this)===null&&V(wn,this)===null){mn=null;return}mn=new Map;for(let[e,[t]]of this.current)mn.set(e,t);for(let t=un;t!==null;t=V(wn,t))if(!(t===this||t.is_fork)){var e=!1;if(t.id1e3&&(yt(Ln,this,Kn).call(this),qn());for(let e of V(Mn,this))V(Nn,this).delete(e),ct(e,ne),this.schedule(e);for(let e of V(Nn,this))ct(e,re),this.schedule(e);let e=V(An,this);B(An,this,[]),this.apply();var t=vn=[],n=[],r=yn=[];for(let r of e)try{yt(Ln,this,Vn).call(this,r,t,n)}catch(e){throw er(r),yt(Ln,this,zn).call(this)||this.discard(),e}if(fn=null,r.length>0){var i=ln.ensure();for(let e of r)i.schedule(e)}if(vn=null,yn=null,yt(Ln,this,zn).call(this)){yt(Ln,this,Wn).call(this,n),yt(Ln,this,Wn).call(this,t);for(let[e,t]of V(Pn,this))$n(e,t);r.length>0&&yt(Ln,fn,Bn).call(fn);return}let a=yt(Ln,this,Hn).call(this);if(a){yt(Ln,this,Wn).call(this,n),yt(Ln,this,Wn).call(this,t),yt(Ln,a,Un).call(a,this);return}V(Mn,this).clear(),V(Nn,this).clear();for(let e of V(Tn,this))e(this);V(Tn,this).clear(),pn=this,Yn(n),Yn(t),pn=null,V(kn,this)?.resolve();var o=fn;if(V(Dn,this)===0&&(V(An,this).length===0||o!==null)&&(yt(Ln,this,Kn).call(this),Ke&&(yt(Ln,this,Gn).call(this),fn=o)),V(An,this).length>0)if(o!==null){let e=o;V(An,e).push(...V(An,this).filter(t=>!V(An,e).includes(t)))}else o=this;o!==null&&yt(Ln,o,Bn).call(o)}function Vn(e,t,n){e.f^=te;for(var r=e.first;r!==null;){var i=r.f,a=(i&96)!=0;if(!(a&&i&1024||i&8192||V(Pn,this).has(r))&&r.fn!==null){a?r.f^=te:i&4?t.push(r):Ke&&i&16777224?n.push(r):bi(r)&&(i&16&&V(Nn,this).add(r),Ti(r));var o=r.first;if(o!==null){r=o;continue}}for(;r!==null;){var s=r.next;if(s!==null){r=s;break}r=r.parent}}}function Hn(){for(var e=V(Cn,this);e!==null;){if(!e.is_fork){for(let[t,[,n]]of this.current)if(e.current.has(t)&&!n)return e}e=V(Cn,e)}return null}function Un(e){for(let[t,n]of e.current)!this.previous.has(t)&&e.previous.has(t)&&this.previous.set(t,e.previous.get(t)),this.current.set(t,n);for(let[t,n]of e.async_deriveds){let e=this.async_deriveds.get(t);e&&n.promise.then(e.resolve).catch(e.reject)}e.async_deriveds.clear(),this.transfer_effects(V(Mn,e),V(Nn,e));let t=e=>{var n=e.reactions;if(n!==null)for(let e of n){var r=e.f;if(r&2)t(e);else{var i=e;r&4194320&&!this.async_deriveds.has(i)&&(V(Nn,this).delete(i),ct(i,ne),this.schedule(i))}}};for(let e of this.current.keys())t(e);this.oncommit(()=>e.discard()),yt(Ln,e,Kn).call(e),fn=this,yt(Ln,this,Bn).call(this)}function Wn(e){for(var t=0;t!u.current.get(e)[1]);if(!(!V(Sn,u)||r.length===0)){var i=r.filter(e=>!this.current.has(e));if(i.length===0)e&&u.discard();else if(t.length>0){if(e)for(let e of V(Fn,this))u.unskip_effect(e,e=>{e.f&4194320?u.schedule(e):yt(Ln,u,Wn).call(u,[e])});u.activate();var a=new Set,o=new Map;for(var s of t)Xn(s,i,a,o);o=new Map;var c=[...u.current].filter(([e,t])=>{let n=this.current.get(e);return n?n[0]!==t[0]||n[1]!==t[1]:!0}).map(([e])=>e);if(c.length>0)for(let e of V(jn,this))!(e.f&155648)&&Zn(e,c,o)&&(e.f&4194320?(ct(e,ne),u.schedule(e)):V(Mn,u).add(e));if(V(An,u).length>0&&!V(In,u)){u.apply();for(var l of V(An,u))yt(Ln,u,Vn).call(u,l,[],[]);B(An,u,[])}u.deactivate()}}}}function Kn(){if(this.linked){var e=V(Cn,this),t=V(wn,this);e===null?un=t:B(wn,e,t),t===null?dn=e:B(Cn,t,e),this.linked=!1}}function qn(){try{we()}catch(e){ot(e,hn)}}var Jn=null;function Yn(e){var t=e.length;if(t!==0){for(var n=0;n0)){nr.clear();for(let e of Jn){if(e.f&24576)continue;let t=[e],n=e.parent;for(;n!==null;)Jn.has(n)&&(Jn.delete(n),t.push(n)),n=n.parent;for(let e=t.length-1;e>=0;e--){let n=t[e];n.f&24576||Ti(n)}}Jn.clear()}}Jn=null}}function Xn(e,t,n,r){if(!n.has(e)&&(n.add(e),e.reactions!==null))for(let i of e.reactions){let e=i.f;e&2?Xn(i,t,n,r):e&4194320&&!(e&2048)&&Zn(i,t,r)&&(ct(i,ne),Qn(i))}}function Zn(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(e.deps!==null)for(let r of e.deps){if(_.call(t,r))return!0;if(r.f&2&&Zn(r,t,n))return n.set(r,!0),!0}return n.set(e,!1),!1}function Qn(e){fn.schedule(e)}function $n(e,t){if(!(e.f&32&&e.f&1024)){e.f&2048?t.d.push(e):e.f&4096&&t.m.push(e),ct(e,te);for(var n=e.first;n!==null;)$n(n,t),n=n.next}}function er(e){ct(e,te);for(var t=e.first;t!==null;)er(t),t=t.next}var tr=new Set,nr=new Map,rr=!1;function ir(e,t){return{f:0,v:e,reactions:null,equals:Ue,rv:0,wv:0}}function ar(e,t){let n=ir(e,t);return ui(n),n}function or(e,t=!1,n=!0){let r=ir(e);if(t||(r.equals=Ge),qe&&n&&Ze!==null&&Ze.l!==null){var i;((i=Ze.l).s??(i.s=[])).push(r)}return r}function sr(e,t,n=!1){return ii!==null&&(!ai||ii.f&131072)&&tt()&&ii.f&4325394&&(li===null||!li.has(e))&&z(),cr(e,n?fr(t):t,yn)}function cr(e,t,n=null){if(!e.equals(t)){nr.set(e,ni?t:e.v);var r=Rn.ensure();if(r.capture(e,t),e.f&2){let t=e;e.f&2048&&an(t),mn===null&<(t)}e.wv=yi(),dr(e,ne,n),tt()&&si!==null&&si.f&1024&&!(si.f&96)&&(pi===null?mi([e]):pi.push(e)),!r.is_fork&&tr.size>0&&!rr&&lr()}return t}function lr(){rr=!1;for(let e of tr){e.f&1024&&ct(e,re);let t;try{t=bi(e)}catch{t=!0}t&&Ti(e)}tr.clear()}function ur(e){sr(e,e.v+1)}function dr(e,t,n){var r=e.reactions;if(r!==null)for(var i=tt(),a=r.length,o=0;o{if(_i===o)return e();var t=ii,n=_i;oi(null),vi(o);var r=e();return oi(t),vi(n),r};return r&&n.set(`length`,ar(e.length,a)),new Proxy(e,{defineProperty(e,t,r){(!(`value`in r)||r.configurable===!1||r.enumerable===!1||r.writable===!1)&&Ee();var i=n.get(t);return i===void 0?s(()=>{var e=ar(r.value,a);return n.set(t,e),e}):sr(i,r.value,!0),!0},deleteProperty(e,t){var r=n.get(t);if(r===void 0){if(t in e){let e=s(()=>ar(Ae,a));n.set(t,e),ur(i)}}else sr(r,Ae),ur(i);return!0},get(t,r,i){if(r===me)return e;var o=n.get(r),c=r in t;if(o===void 0&&(!c||b(t,r)?.writable)&&(o=s(()=>ar(fr(c?t[r]:Ae),a)),n.set(r,o)),o!==void 0){var l=H(o);return l===Ae?void 0:l}return Reflect.get(t,r,i)},getOwnPropertyDescriptor(e,t){var r=Reflect.getOwnPropertyDescriptor(e,t);if(r&&`value`in r){var i=n.get(t);i&&(r.value=H(i))}else if(r===void 0){var a=n.get(t),o=a?.v;if(a!==void 0&&o!==Ae)return{enumerable:!0,configurable:!0,value:o,writable:!0}}return r},has(e,t){if(t===me)return!0;var r=n.get(t),i=r!==void 0&&r.v!==Ae||Reflect.has(e,t);return(r!==void 0||si!==null&&(!i||b(e,t)?.writable))&&(r===void 0&&(r=s(()=>ar(i?fr(e[t]):Ae,a)),n.set(t,r)),H(r)===Ae)?!1:i},set(e,t,o,c){var l=n.get(t),u=t in e;if(r&&t===`length`)for(var d=o;dar(Ae,a)),n.set(d+``,f)):sr(f,Ae)}if(l===void 0)(!u||b(e,t)?.writable)&&(l=s(()=>ar(void 0,a)),sr(l,fr(o)),n.set(t,l));else{u=l.v!==Ae;var p=s(()=>fr(o));sr(l,p)}var m=Reflect.getOwnPropertyDescriptor(e,t);if(m?.set&&m.set.call(c,o),!u){if(r&&typeof t==`string`){var h=n.get(`length`),g=Number(t);Number.isInteger(g)&&g>=h.v&&sr(h,g+1)}ur(i)}return!0},ownKeys(e){H(i);var t=Reflect.ownKeys(e).filter(e=>{var t=n.get(e);return t===void 0||t.v!==Ae});for(var[r,a]of n)a.v!==Ae&&!(r in e)&&t.push(r);return t},setPrototypeOf(){De()}})}var pr,mr,hr,gr;function _r(){if(pr===void 0){pr=window,mr=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;hr=b(t,`firstChild`).get,gr=b(t,`nextSibling`).get,T(e)&&(e[ve]=void 0,e[_e]=null,e[P]=void 0,e.__e=void 0),T(n)&&(n[ye]=void 0)}}function vr(e=``){return document.createTextNode(e)}function yr(e){return hr.call(e)}function br(e){return gr.call(e)}function xr(e,t){if(!Pe)return yr(e);var n=yr(Ie);if(n===null)n=Ie.appendChild(vr());else if(t&&n.nodeType!==3){var r=vr();return n?.before(r),Le(r),r}return t&&Dr(n),Le(n),n}function Sr(e,t=!1){if(!Pe){var n=yr(e);return n instanceof Comment&&n.data===``?br(n):n}if(t){if(Ie?.nodeType!==3){var r=vr();return Ie?.before(r),Le(r),r}Dr(Ie)}return Ie}function Cr(e,t=1,n=!1){let r=Pe?Ie:e;for(var i;t--;)i=r,r=br(r);if(!Pe)return r;if(n){if(r?.nodeType!==3){var a=vr();return r===null?i?.after(a):r.before(a),Le(a),a}Dr(r)}return Le(r),r}function wr(e){e.textContent=``}function Tr(){return!Ke||Jn!==null?!1:(si.f&oe)!==0}function Er(e,t,n){return t==null||t===`http://www.w3.org/1999/xhtml`?n?document.createElement(e,{is:n}):document.createElement(e):n?document.createElementNS(t,e,{is:n}):document.createElementNS(t,e)}function Dr(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===3;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function Or(e){var t=ii,n=si;oi(null),ci(null);try{return e()}finally{oi(t),ci(n)}}function kr(e){si===null&&(ii===null&&R(e),L()),ni&&Ce(e)}function Ar(e,t){var n=t.last;n===null?t.last=t.first=e:(n.next=e,e.prev=n,t.last=e)}function jr(e,t){var n=si;n!==null&&n.f&8192&&(e|=ie);var r={ctx:Ze,deps:null,nodes:null,f:e|ne|512,first:null,fn:t,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null};fn?.register_created_effect(r);var i=r;if(e&4)vn===null?Rn.ensure().schedule(r):vn.push(r);else if(t!==null){try{Ti(r)}catch(e){throw Kr(r),e}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&!(i.f&524288)&&(i=i.first,e&16&&e&65536&&i!==null&&(i.f|=ce))}if(i!==null&&(i.parent=n,n!==null&&Ar(i,n),ii!==null&&ii.f&2&&!(e&64))){var a=ii;(a.effects??(a.effects=[])).push(i)}return r}function Mr(){return ii!==null&&!ai}function Nr(e){let t=jr(8,null);return ct(t,te),t.teardown=e,t}function Pr(e){kr(`$effect`);var t=si.f;if(!ii&&t&32&&Ze!==null&&!Ze.i){var n=Ze;(n.e??(n.e=[])).push(e)}else return Fr(e)}function Fr(e){return jr(4|ue,e)}function Ir(e){Rn.ensure();let t=jr(64|le,e);return(e={})=>new Promise(n=>{e.outro?Yr(t,()=>{Kr(t),n(void 0)}):(Kr(t),n(void 0))})}function Lr(e){return jr(4,e)}function Rr(e){return jr(fe|le,e)}function zr(e,t=0){return jr(8|t,e)}function Br(e,t=[],n=[],r=[]){Jt(r,t,n,t=>{jr(8,()=>{e(...t.map(H))})})}function Vr(e,t=0){return jr(16|t,e)}function Hr(e){return jr(32|le,e)}function Ur(e){var t=e.teardown;if(t!==null){let e=ni,n=ii;ri(!0),oi(null);try{t.call(null)}finally{ri(e),oi(n)}}}function Wr(e,t=!1){var n=e.first;for(e.first=e.last=null;n!==null;){let e=n.ac;e!==null&&Or(()=>{e.abort(be)});var r=n.next;n.f&64?n.parent=null:Kr(n,t),n=r}}function Gr(e){for(var t=e.first;t!==null;){var n=t.next;t.f&32||Kr(t),t=n}}function Kr(e,t=!0){var n=!1;(t||e.f&262144)&&e.nodes!==null&&e.nodes.end!==null&&(qr(e.nodes.start,e.nodes.end),n=!0),e.f|=se,Wr(e,t&&!n),wi(e,0);var r=e.nodes&&e.nodes.t;if(r!==null)for(let e of r)e.stop();Ur(e),e.f^=se,e.f|=ae;var i=e.parent;i!==null&&i.first!==null&&Jr(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function qr(e,t){for(;e!==null;){var n=e===t?null:br(e);e.remove(),e=n}}function Jr(e){var t=e.parent,n=e.prev,r=e.next;n!==null&&(n.next=r),r!==null&&(r.prev=n),t!==null&&(t.first===e&&(t.first=r),t.last===e&&(t.last=n))}function Yr(e,t,n=!0){var r=[];Xr(e,r,!0);var i=()=>{n&&Kr(e),t&&t()},a=r.length;if(a>0){var o=()=>--a||i();for(var s of r)s.out(o)}else i()}function Xr(e,t,n){if(!(e.f&8192)){e.f^=ie;var r=e.nodes&&e.nodes.t;if(r!==null)for(let e of r)(e.is_global||n)&&t.push(e);for(var i=e.first;i!==null;){var a=i.next;if(!(i.f&64)){var o=(i.f&65536)!=0||(i.f&32)!=0&&(e.f&16)!=0;Xr(i,t,o?n:!1)}i=a}}}function Zr(e){Qr(e,!0)}function Qr(e,t){if(e.f&8192){e.f^=ie,e.f&1024||(ct(e,ne),Rn.ensure().schedule(e));for(var n=e.first;n!==null;){var r=n.next,i=(n.f&65536)!=0||(n.f&32)!=0;Qr(n,i?t:!1),n=r}var a=e.nodes&&e.nodes.t;if(a!==null)for(let e of a)(e.is_global||t)&&e.in()}}function $r(e,t){if(e.nodes)for(var n=e.nodes.start,r=e.nodes.end;n!==null;){var i=n===r?null:br(n);t.append(n),n=i}}var ei=null,ti=!1,ni=!1;function ri(e){ni=e}var ii=null,ai=!1;function oi(e){ii=e}var si=null;function ci(e){si=e}var li=null;function ui(e){ii!==null&&(!Ke||ii.f&2)&&(li??(li=new Set)).add(e)}var di=null,fi=0,pi=null;function mi(e){pi=e}var hi=1,gi=0,_i=gi;function vi(e){_i=e}function yi(){return++hi}function bi(e){var t=e.f;if(t&2048)return!0;if(t&2&&(e.f&=~N),t&4096){for(var n=e.deps,r=n.length,i=0;ie.wv)return!0}t&512&&mn===null&&ct(e,te)}return!1}function xi(e,t,n=!0){var r=e.reactions;if(r!==null&&!(!Ke&&li!==null&&li.has(e)))for(var i=0;i{e.ac.abort(be)}),e.ac=null);try{e.f|=de;var u=e.fn,d=u();e.f|=oe;var f=e.deps,p=fn?.is_fork;if(di!==null){var m;if(p||wi(e,fi),f!==null&&fi>0)for(f.length=fi+di.length,m=0;m{throw e});throw f}}finally{e[Ni]=t,delete e.currentTarget,oi(u),ci(d)}}}var Bi=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy(`svelte-trusted-html`,{createHTML:e=>e});function Vi(e){return Bi?.createHTML(e)??e}function Hi(e){var t=Er(`template`);return t.innerHTML=Vi(e.replaceAll(``,``)),t.content}function Ui(e,t){var n=si;n.nodes===null&&(n.nodes={start:e,end:t,a:null,t:null})}function Wi(e,t){var n=(t&1)!=0,r=(t&2)!=0,i,a=!e.startsWith(``);return()=>{if(Pe)return Ui(Ie,null),Ie;i===void 0&&(i=Hi(a?e:``+e),n||(i=yr(i)));var t=r||mr?document.importNode(i,!0):i.cloneNode(!0);if(n){var o=yr(t),s=t.lastChild;Ui(o,s)}else Ui(t,t);return t}}function Gi(e,t){if(Pe){var n=si;(!(n.f&32768)||n.nodes.end===null)&&(n.nodes.end=Ie),Re();return}e!==null&&e.before(t)}function Ki(e,t){var n,r=t==null?``:typeof t==`object`?`${t}`:t;r!==((n=e)[ye]??(n[ye]=e.nodeValue))&&(e[ye]=r,e.nodeValue=`${r}`)}function qi(e,t){return Yi(e,t)}var Ji=new Map;function Yi(e,{target:t,anchor:n,props:r={},events:i,context:a,intro:o=!0,transformError:s}){_r();var c=void 0,l=Ir(()=>{var o=n??t.appendChild(vr());xt(o,{pending:()=>{}},t=>{$e({});var n=Ze;if(a&&(n.c=a),i&&(r.$$events=i),Pe&&Ui(t,null),c=e(t,r)||{},Pe&&(si.nodes.end=Ie,Ie===null||Ie.nodeType!==8||Ie.data!==`]`))throw Me(),ke;et()},s);var l=new Set,u=e=>{for(var n=0;n{for(var e of l)for(let n of[t,document]){var r=Ji.get(n),i=r.get(e);--i==0?(n.removeEventListener(e,zi),r.delete(e),r.size===0&&Ji.delete(n)):r.set(e,i)}Fi.delete(u),o!==n&&o.parentNode?.removeChild(o)}});return Xi.set(c,l),c}var Xi=new WeakMap;function Zi(e,t){let n=Xi.get(e);return n?(Xi.delete(e),n(t)):Promise.resolve()}var Qi=new WeakMap,$i=new WeakMap,ea=new WeakMap,ta=new WeakMap,na=new WeakMap,ra=new WeakMap,ia=new WeakMap,aa=class{constructor(e,t=!0){j(this,`anchor`,void 0),vt(this,Qi,new Map),vt(this,$i,new Map),vt(this,ea,new Map),vt(this,ta,new Set),vt(this,na,!0),vt(this,ra,e=>{if(V(Qi,this).has(e)){var t=V(Qi,this).get(e),n=V($i,this).get(t);if(n)Zr(n),V(ta,this).delete(t);else{var r=V(ea,this).get(t);r&&(Zr(r.effect),V($i,this).set(t,r.effect),V(ea,this).delete(t),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),n=r.effect)}for(let[t,n]of V(Qi,this)){if(V(Qi,this).delete(t),t===e)break;let r=V(ea,this).get(n);r&&(Kr(r.effect),V(ea,this).delete(n))}for(let[e,r]of V($i,this)){if(e===t||V(ta,this).has(e))continue;let i=()=>{if(Array.from(V(Qi,this).values()).includes(e)){var t=document.createDocumentFragment();$r(r,t),t.append(vr()),V(ea,this).set(e,{effect:r,fragment:t})}else Kr(r);V(ta,this).delete(e),V($i,this).delete(e)};V(na,this)||!n?(V(ta,this).add(e),Yr(r,i,!1)):i()}}}),vt(this,ia,e=>{V(Qi,this).delete(e);let t=Array.from(V(Qi,this).values());for(let[e,n]of V(ea,this))t.includes(e)||(Kr(n.effect),V(ea,this).delete(e))}),this.anchor=e,B(na,this,t)}ensure(e,t){var n=fn,r=Tr();if(t&&!V($i,this).has(e)&&!V(ea,this).has(e))if(r){var i=document.createDocumentFragment(),a=vr();i.append(a),V(ea,this).set(e,{effect:Hr(()=>t(a)),fragment:i})}else V($i,this).set(e,Hr(()=>t(this.anchor)));if(V(Qi,this).set(n,e),r){for(let[t,r]of V($i,this))t===e?n.unskip_effect(r):n.skip_effect(r);for(let[t,r]of V(ea,this))t===e?n.unskip_effect(r.effect):n.skip_effect(r.effect);n.oncommit(V(ra,this)),n.ondiscard(V(ia,this))}else Pe&&(this.anchor=Ie),V(ra,this).call(this,n)}};function oa(e,t,n=!1){var r;Pe&&(r=Ie,Re());var i=new aa(e),a=n?ce:0;function o(e,t){if(Pe){var n=He(r);if(e!==parseInt(n.substring(1))){var a=Ve();Le(a),i.anchor=a,Fe(!1),i.ensure(e,t),Fe(!0);return}}i.ensure(e,t)}Vr(()=>{var e=!1;t((t,n=0)=>{e=!0,o(n,t)}),e||o(-1,null)},a)}function sa(e,t){return t}function ca(e,t,n){for(var r=[],i=t.length,a,o=t.length,s=0;s{if(a){if(a.pending.delete(n),a.done.add(n),a.pending.size===0){var t=e.outrogroups;la(e,v(a.done)),t.delete(a),t.size===0&&(e.outrogroups=null)}}else --o},!1)}if(o===0){var c=r.length===0&&n!==null;if(c){var l=n,u=l.parentNode;wr(u),u.append(l),e.items.clear()}la(e,t,!c)}else a={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(a)}function la(e,t,n=!0){var r;if(e.pending.size>0){r=new Set;for(let t of e.pending.values())for(let n of t)r.add(e.items.get(n).e)}for(var i=0;i{var e=n();return h(e)?e:e==null?[]:v(e)}),d,f=new Map,p=!0;function m(e){_.effect.f&16384||(_.pending.delete(e),_.fallback=l,pa(_,d,o,t,r),l!==null&&(d.length===0?l.f&33554432?(l.f^=M,ha(l,null,o)):Zr(l):Yr(l,()=>{l=null})))}function g(e){_.pending.delete(e)}var _={effect:Vr(()=>{d=H(u);var e=d.length;let c=!1;Pe&&He(o)===`[!`!=(e===0)&&(o=Ve(),Le(o),Fe(!1),c=!0);for(var h=new Set,_=fn,v=Tr(),y=0;ya(o)):(l=Hr(()=>a(ua??(ua=vr()))),l.f|=M)),e>h.size&&I(``,``,``),Pe&&e>0&&Le(Ve()),!p)if(f.set(_,h),v){for(let[e,t]of s)h.has(e)||_.skip_effect(t.e);_.oncommit(m),_.ondiscard(g)}else m(_);c&&Fe(!0),H(u)}),flags:t,items:s,pending:f,outrogroups:null,fallback:l};p=!1,Pe&&(o=Ie)}function fa(e){for(;e!==null&&!(e.f&32);)e=e.next;return e}function pa(e,t,n,r,i){var a=(r&8)!=0,o=t.length,s=e.items,c=fa(e.effect.first),l,u=null,d,f=[],p=[],m,h,g,_;if(a)for(_=0;_0){var E=r&4&&o===0?n:null;if(a){for(_=0;_{if(d!==void 0)for(g of d)g.nodes?.a?.apply()})}function ma(e,t,n,r,i,a,o,s){var c=o&1?o&16?ir(n):or(n,!1,!1):null,l=o&2?ir(i):null;return{v:c,i:l,e:Hr(()=>(a(t,c??n,l??i,s),()=>{e.delete(r)}))}}function ha(e,t,n){if(e.nodes)for(var r=e.nodes.start,i=e.nodes.end,a=t&&!(t.f&33554432)?t.nodes.start:n;r!==null;){var o=br(r);if(a.before(r),r===i)return;r=o}}function ga(e,t,n){t===null?e.effect.first=n:t.next=n,n===null?e.effect.last=t:n.prev=t}function _a(e,t){Lr(()=>{var n=e.getRootNode(),r=n.host?n:n.head??n.ownerDocument.head;if(!r.querySelector(`#`+t.hash)){let e=Er(`style`);e.id=t.hash,e.textContent=t.code,r.appendChild(e)}})}function va(e,t,n){Lr(()=>{var r=Oi(()=>t(e,n?.())||{});if(n&&r?.update){var i=!1,a={};zr(()=>{var e=n();ki(e),i&&We(a,e)&&(a=e,r.update(e))}),i=!0}if(r?.destroy)return()=>r.destroy()})}var ya=[...` -\r\f\xA0\v`];function ba(e,t,n){var r=e==null?``:``+e;if(t&&(r=r?r+` `+t:t),n){for(var i of Object.keys(n))if(n[i])r=r?r+` `+i:i;else if(r.length)for(var a=i.length,o=0;(o=r.indexOf(i,o))>=0;){var s=o+a;(o===0||ya.includes(r[o-1]))&&(s===r.length||ya.includes(r[s]))?r=(o===0?``:r.substring(0,o))+r.substring(s+1):o=s}}return r===``?null:r}function xa(e,t=!1){var n=t?` !important;`:`;`,r=``;for(var i of Object.keys(e)){var a=e[i];a!=null&&a!==``&&(r+=` `+i+`: `+a+n)}return r}function Sa(e){return e[0]!==`-`||e[1]!==`-`?e.toLowerCase():e}function Ca(e,t){if(t){var n=``,r,i;if(Array.isArray(t)?(r=t[0],i=t[1]):r=t,e){e=String(e).replaceAll(/\s*\/\*.*?\*\/\s*/g,``).trim();var a=!1,o=0,s=!1,c=[];r&&c.push(...Object.keys(r).map(Sa)),i&&c.push(...Object.keys(i).map(Sa));var l=0,u=-1;let t=e.length;for(var d=0;d{var n=V(Fa,this).get(e);n.delete(t),n.size===0&&(V(Fa,this).delete(e),V(Ia,this).unobserve(e))}}};Pa=za;function Ba(){return V(Ia,this)??B(Ia,this,new ResizeObserver(e=>{for(var t of e){Pa.entries.set(t.target,t);for(var n of V(Fa,this).get(t.target)||[])n(t)}}))}j(za,`entries`,new WeakMap);function Va(e,t){return e===t||e?.[me]===t}function Ha(e={},t,n,r){var i=Ze.r,a=si;return Lr(()=>{var o,s;return zr(()=>{o=s,s=r?.()||[],Oi(()=>{Va(n(...s),e)||(t(e,...s),o&&Va(n(...o),e)&&t(null,...o))})}),()=>{let r=a;for(;r!==i&&r.parent!==null&&r.parent.f&33554432;)r=r.parent;let o=()=>{s&&Va(n(...s),e)&&t(null,...s)},c=r.teardown;r.teardown=()=>{o(),c?.()}}}),e}function Ua(e,t,n,r){var i=!qe||(n&2)!=0,a=(n&8)!=0,o=(n&16)!=0,s=r,c=!0,l=void 0,u=()=>o&&i?(l??(l=Qt(r)),H(l)):(c&&(c=!1,s=o?Oi(r):r),s);let d;if(a){var f=me in e||he in e;d=b(e,t)?.set??(f&&t in e?n=>e[t]=n:void 0)}var p,m=!1;a?[p,m]=mt(()=>e[t]):p=e[t],p===void 0&&r!==void 0&&(p=u(),d&&(i&&Te(t),d(p)));var h=i?()=>{var n=e[t];return n===void 0?u():(c=!0,n)}:()=>{var n=e[t];return n!==void 0&&(s=void 0),n===void 0?s:n};if(i&&!(n&4))return h;if(d){var g=e.$$legacy;return(function(e,t){return arguments.length>0?((!i||!t||g||m)&&d(t?h():e),e):h()})}var _=!1,v=(n&1?Qt:nn)(()=>(_=!1,h()));a&&H(v);var y=si;return(function(e,t){if(arguments.length>0){let n=t?H(v):i&&a?fr(e):e;return sr(v,n),_=!0,s!==void 0&&(s=n),e}return ni&&_||y.f&16384?v.v:H(v)})}function Wa(e){Ze===null&&F(`onMount`),qe&&Ze.l!==null?Ka(Ze).m.push(e):Pr(()=>{let t=Oi(e);if(typeof t==`function`)return t})}function Ga(e){Ze===null&&F(`onDestroy`),Wa(()=>()=>Oi(e))}function Ka(e){var t=e.l;return t.u??(t.u={a:[],b:[],m:[]})}var qa=class{constructor(e,t,n){this.children=[],this.key=e,this.title=t,this.level=n,this.children=[]}};function Ja(e=document){let t=e.querySelectorAll(`h1, h2, h3, h4, h5, h6`),n=new qa(``,`Root`,0),r=n;return t.forEach(e=>{if(e.style.display==`none`)return;let t=parseInt(e.tagName.slice(1)),n=e.querySelector(`a.md-print-anchor`),i=/^af:\/\/(.+)$/.exec(n?.href??``);if(!i)return;let a=new qa(i[1],e.innerText,t);for(;r.level>=t;)r=r.parent;r.children.push(a),a.parent=r,r=a}),n}function Ya(e){let t=new Map;return e.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach((e,n)=>{let r=document.createElement(`a`),i=`${e.tagName.toLowerCase()}-${n}`;r.href=`af://${i}`,r.className=`md-print-anchor`,e.appendChild(r),e.dataset.heading&&t.set(e.dataset.heading,i);let a=e.textContent?.trim();if(a){t.set(a,i),t.set(encodeURIComponent(a),i),t.set(a.replace(/\s+/g,`-`),i),t.set(a.toLowerCase().replace(/\s+/g,`-`),i);let e=a.replace(/[^\w\s-]/g,``).trim();e&&e!==a&&(t.set(e,i),t.set(e.replace(/\s+/g,`-`),i),t.set(e.toLowerCase().replace(/\s+/g,`-`),i))}e.id&&t.set(e.id,i)}),t}function Xa(e){return new Map(Array.from(e).map(([e,t])=>[e?.toLowerCase(),t]))}function Za(e,t,n){let r=Xa(t);e.querySelectorAll(`a.internal-link`).forEach((e,i)=>{let[a,o]=e.dataset.href?.split(`#`)??[];if(o?.startsWith(`^`)&&(e.href=e.dataset.href?.toLowerCase()),o?.length>0){if(a?.length>0&&a!=n)return;let i=t.get(o)||r.get(o?.toLowerCase());i&&!o.startsWith(`^`)&&(e.href=`an://${i}`)}}),e.querySelectorAll(`a[href^='#']`).forEach(e=>{let n=e.getAttribute(`href`);if(!n)return;let i=n.substring(1);if(!i||e.classList.contains(`internal-link`)||i.startsWith(`^`))return;let a=[i,decodeURIComponent(i),i.replace(/-/g,` `),decodeURIComponent(i).replace(/-/g,` `),i.toLowerCase(),decodeURIComponent(i).toLowerCase(),i.toLowerCase().replace(/-/g,` `),decodeURIComponent(i).toLowerCase().replace(/-/g,` `)],o=null;for(let e of a)if(o=t.get(e)||r.get(e.toLowerCase()),o)break;o&&(e.href=`an://${o}`)})}var Qa=e=>Math.round(e*.26458333333719),$a=e=>Math.round(e*3.779527559);function eo(e){if(e instanceof l.TFile)return e.extension==`md`?[e]:[];let t=[];for(let n of e.children)t.push(...eo(n));return t.sort((e,t)=>e.name.localeCompare(t.name)),t}function to(e,t){Array.from(t).forEach(t=>{e.setAttribute(t.name,t.value)})}function no(e,t){return e.replace(/\{\{(.*?)\}\}/g,(e,n)=>t[n.trim()])}function ro(e){return!isNaN(parseFloat(e))}function io(e,t=0){try{let n=parseInt(String(e));return isNaN(n)?t:n}catch{return t}}function ao(e,t=0){try{let n=parseFloat(String(e));return isNaN(n)?t:n}catch{return t}}function oo(){let e=[];return Array.from(document.styleSheets).forEach(t=>{let n=t.ownerNode?.id;if(n?.startsWith(`svelte-`))return;let r=t.ownerNode?.href,i=`/* ----------${n?`id:${n}`:r?`href:${r}`:``}---------- */`;e.push(i);try{Array.from(t?.cssRules??[]).forEach(t=>{e.push(t.cssText)})}catch(e){console.error(e)}}),e.push(...co()),e}var so=` +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require("obsidian"),u=require("electron");u=c(u);let d=require("path");d=c(d);let f=require("os");f=c(f);var p=c(o(((e,t)=>{var n=function(e){return r(e)&&!i(e)};function r(e){return!!e&&typeof e==`object`}function i(e){var t=Object.prototype.toString.call(e);return t===`[object RegExp]`||t===`[object Date]`||o(e)}var a=typeof Symbol==`function`&&Symbol.for?Symbol.for(`react.element`):60103;function o(e){return e.$$typeof===a}function s(e){return Array.isArray(e)?[]:{}}function c(e,t){return t.clone!==!1&&t.isMergeableObject(e)?g(s(e),e,t):e}function l(e,t,n){return e.concat(t).map(function(e){return c(e,n)})}function u(e,t){if(!t.customMerge)return g;var n=t.customMerge(e);return typeof n==`function`?n:g}function d(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function f(e){return Object.keys(e).concat(d(e))}function p(e,t){try{return t in e}catch{return!1}}function m(e,t){return p(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function h(e,t,n){var r={};return n.isMergeableObject(e)&&f(e).forEach(function(t){r[t]=c(e[t],n)}),f(t).forEach(function(i){m(e,i)||(p(e,i)&&n.isMergeableObject(t[i])?r[i]=u(i,n)(e[i],t[i],n):r[i]=c(t[i],n))}),r}function g(e,t,r){r=r||{},r.arrayMerge=r.arrayMerge||l,r.isMergeableObject=r.isMergeableObject||n,r.cloneUnlessOtherwiseSpecified=c;var i=Array.isArray(t);return i===Array.isArray(e)?i?r.arrayMerge(e,t,r):h(e,t,r):c(t,r)}g.all=function(e,t){if(!Array.isArray(e))throw Error(`first argument should be an array`);return e.reduce(function(e,n){return g(e,n,t)},{})},t.exports=g}))()),m={i18n:{en:{exportCurrentFile:`Export current file to PDF`,exportCurrentFileWithPrevious:`Export to PDF with previous Settings`,exportDialog:{filenameAsTitle:`Include file name as title`,pageSize:`Page Size`,margin:`Margin`,downscalePercent:`Downscale Percent`,landscape:`Landscape`,displayHeader:`Display Header`,displayFooter:`Display Footer`,openAfterExport:`Open after export`,cssSnippets:`CSS snippets`},settings:{showTitle:`Add file name as title`,displayHeader:`Display headers`,displayFooter:`Display footer`,printBackground:`Print background`,maxLevel:`Max headings level of the outline`,displayMetadata:`PDF metadata`,headerTemplate:`Header Template`,footerTemplate:`Footer Template`,isTimestamp:`Add timestamp`,enabledCss:`Enable select css snippets`,concurrency:`Limit concurrency`,debugMode:`Debug Mode`,version:`Engine Version`}},zh:{exportCurrentFile:`导出当前文件为PDF`,exportCurrentFileWithPrevious:`使用上一次设置导出为PDF`,exportDialog:{filenameAsTitle:`将笔记名作为标题`,pageSize:`纸张尺寸`,margin:`页边距`,downscalePercent:`缩放`,landscape:`横向打印`,displayHeader:`页眉`,displayFooter:`页脚`,openAfterExport:`导出后打开`,cssSnippets:`CSS代码片段`},settings:{showTitle:`将笔记名作为标题`,displayHeader:`显示页眉`,displayFooter:`显示页脚`,printBackground:`打印背景`,maxLevel:`最大标题级别`,displayMetadata:`PDF元数据`,headerTemplate:`页眉模板`,footerTemplate:`页脚模板`,isTimestamp:`文件名添加时间戳`,enabledCss:`启用CSS片段选择`,concurrency:`限制并发数`,debugMode:`调试模式`,version:`引擎版本`}}},get current(){let e=window.localStorage.getItem(`language`)??`en`;return(0,p.default)(this.i18n.en,this.i18n[e]??{})}},h=Array.isArray,g=Array.prototype.indexOf,_=Array.prototype.includes,v=Array.from,y=Object.defineProperty,b=Object.getOwnPropertyDescriptor,x=Object.getOwnPropertyDescriptors,S=Object.prototype,C=Array.prototype,w=Object.getPrototypeOf,T=Object.isExtensible,E=()=>{};function D(e){for(var t=0;t{e=n,t=r}),resolve:e,reject:t}}function k(e){"@babel/helpers - typeof";return k=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},k(e)}function ee(e,t){if(k(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(k(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function A(e){var t=ee(e,`string`);return k(t)==`symbol`?t:t+``}function j(e,t,n){return(t=A(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var te=1024,ne=2048,re=4096,ie=8192,ae=16384,oe=32768,se=1<<25,ce=65536,le=1<<19,ue=1<<20,M=1<<25,N=65536,de=1<<21,fe=1<<22,pe=1<<23,me=Symbol(`$state`),he=Symbol(`legacy props`),ge=Symbol(``),_e=Symbol(`attributes`),ve=Symbol(`class`),P=Symbol(`style`),ye=Symbol(`text`),be=new class extends Error{constructor(...e){super(...e),j(this,`name`,`StaleReactionError`),j(this,`message`,"The reaction that called `getAbortSignal()` was re-run or destroyed")}},xe=!!globalThis.document?.contentType&&globalThis.document.contentType.includes(`xml`);function F(e){throw Error(`https://svelte.dev/e/lifecycle_outside_component`)}function Se(){throw Error(`https://svelte.dev/e/async_derived_orphan`)}function I(e,t,n){throw Error(`https://svelte.dev/e/each_key_duplicate`)}function Ce(e){throw Error(`https://svelte.dev/e/effect_in_teardown`)}function L(){throw Error(`https://svelte.dev/e/effect_in_unowned_derived`)}function R(e){throw Error(`https://svelte.dev/e/effect_orphan`)}function we(){throw Error(`https://svelte.dev/e/effect_update_depth_exceeded`)}function Te(e){throw Error(`https://svelte.dev/e/props_invalid_value`)}function Ee(){throw Error(`https://svelte.dev/e/state_descriptors_fixed`)}function De(){throw Error(`https://svelte.dev/e/state_prototype_fixed`)}function z(){throw Error(`https://svelte.dev/e/state_unsafe_mutation`)}function Oe(){throw Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`)}var ke={},Ae=Symbol(`uninitialized`);function je(){console.warn(`https://svelte.dev/e/derived_inert`)}function Me(e){console.warn(`https://svelte.dev/e/hydration_mismatch`)}function Ne(){console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`)}var Pe=!1;function Fe(e){Pe=e}var Ie;function Le(e){if(e===null)throw Me(),ke;return Ie=e}function Re(){return Le(hr(Ie))}function ze(e){if(Pe){if(hr(Ie)!==null)throw Me(),ke;Ie=e}}function Be(e=1){if(Pe){for(var t=e,n=Ie;t--;)n=hr(n);Ie=n}}function Ve(e=!0){for(var t=0,n=Ie;;){if(n.nodeType===8){var r=n.data;if(r===`]`){if(t===0)return n;--t}else(r===`[`||r===`[!`||r[0]===`[`&&!isNaN(Number(r.slice(1))))&&(t+=1)}var i=hr(n);e&&n.remove(),n=i}}function He(e){if(!e||e.nodeType!==8)throw Me(),ke;return e.data}function Ue(e){return e===this.v}function We(e,t){return e==e?e!==t||typeof e==`object`&&!!e||typeof e==`function`:t==t}function Ge(e){return!We(e,this.v)}var Ke=[];function qe(e,t=!1,n=!1){return Je(e,new Map,``,Ke,null,n)}function Je(e,t,n,r,i=null,a=!1){if(typeof e==`object`&&e){var o=t.get(e);if(o!==void 0)return o;if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);if(h(e)){var s=Array(e.length);t.set(e,s),i!==null&&t.set(i,s);for(var c=0;c{t===et&&tt()})}et.push(e)}function rt(e){var t=ni;if(t===null)return $r.f|=pe,e;if(!(t.f&32768)&&!(t.f&4))throw e;it(e,t)}function it(e,t){for(;t!==null;){if(t.f&128){if(!(t.f&32768))throw e;try{t.b.error(e);return}catch(t){e=t}}t=t.parent}throw e}var at=~(ne|re|te);function ot(e,t){e.f=e.f&at|t}function st(e){e.f&512||e.deps===null?ot(e,te):ot(e,re)}function ct(e){if(e!==null)for(let t of e)!(t.f&2)||!(t.f&65536)||(t.f^=N,ct(t.deps))}function lt(e,t,n){e.f&2048?t.add(e):e.f&4096&&n.add(e),ct(e.deps),ot(e,te)}var ut=!1;function dt(e){var t=ut;try{return ut=!1,[e(),ut]}finally{ut=t}}function ft(e){let t=0,n=$n(0),r;return()=>{Dr()&&(H(n),Pr(()=>(t===0&&(r=Ci(()=>e(()=>ar(n)))),t+=1,()=>{nt(()=>{--t,t===0&&(r?.(),r=void 0,ar(n))})})))}}function pt(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function mt(e,t){pt(e,t),t.add(e)}function ht(e,t,n){pt(e,t),t.set(e,n)}function gt(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function B(e,t,n){return e.set(gt(e,t),n),n}function V(e,t){return e.get(gt(e,t))}var _t=ce|le;function vt(e,t,n,r){new It(e,t,n,r)}var yt=new WeakMap,bt=new WeakMap,xt=new WeakMap,St=new WeakMap,Ct=new WeakMap,wt=new WeakMap,Tt=new WeakMap,Et=new WeakMap,Dt=new WeakMap,Ot=new WeakMap,kt=new WeakMap,At=new WeakMap,jt=new WeakMap,Mt=new WeakMap,Nt=new WeakMap,Pt=new WeakMap,Ft=new WeakSet,It=class{constructor(e,t,n,r){mt(this,Ft),j(this,`parent`,void 0),j(this,`is_pending`,!1),j(this,`transform_error`,void 0),ht(this,yt,void 0),ht(this,bt,Pe?Ie:null),ht(this,xt,void 0),ht(this,St,void 0),ht(this,Ct,void 0),ht(this,wt,null),ht(this,Tt,null),ht(this,Et,null),ht(this,Dt,null),ht(this,Ot,0),ht(this,kt,0),ht(this,At,!1),ht(this,jt,new Set),ht(this,Mt,new Set),ht(this,Nt,null),ht(this,Pt,ft(()=>(B(Nt,this,$n(V(Ot,this))),()=>{B(Nt,this,null)}))),B(yt,this,e),B(xt,this,t),B(St,this,e=>{var t=ni;t.b=this,t.f|=128,n(e)}),this.parent=ni.b,this.transform_error=r??this.parent?.transform_error??(e=>e),B(Ct,this,Ir(()=>{if(Pe){let e=V(bt,this);Re();let t=e.data===`[!`;if(e.data.startsWith(`[?`)){let t=JSON.parse(e.data.slice(2));gt(Ft,this,Rt).call(this,t)}else t?gt(Ft,this,zt).call(this):gt(Ft,this,Lt).call(this)}else gt(Ft,this,Bt).call(this)},_t)),Pe&&B(yt,this,Ie)}defer_effect(e){lt(e,V(jt,this),V(Mt,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!V(xt,this).pending}update_pending_count(e,t){gt(Ft,this,Ut).call(this,e,t),B(Ot,this,V(Ot,this)+e),!(!V(Nt,this)||V(At,this))&&(B(At,this,!0),nt(()=>{B(At,this,!1),V(Nt,this)&&rr(V(Nt,this),V(Ot,this))}))}get_effect_pending(){return V(Pt,this).call(this),H(V(Nt,this))}error(e){if(!V(xt,this).onerror&&!V(xt,this).failed)throw e;cn?.is_fork?(V(wt,this)&&cn.skip_effect(V(wt,this)),V(Tt,this)&&cn.skip_effect(V(Tt,this)),V(Et,this)&&cn.skip_effect(V(Et,this)),cn.oncommit(()=>{gt(Ft,this,Wt).call(this,e)})):gt(Ft,this,Wt).call(this,e)}};function Lt(){try{B(wt,this,Lr(()=>V(St,this).call(this,V(yt,this))))}catch(e){this.error(e)}}function Rt(e){let t=V(xt,this).failed;t&&B(Et,this,Lr(()=>{t(V(yt,this),()=>e,()=>()=>{})}))}function zt(){let e=V(xt,this).pending;e&&(this.is_pending=!0,B(Tt,this,Lr(()=>e(V(yt,this)))),nt(()=>{var e=B(Dt,this,document.createDocumentFragment()),t=pr();e.append(t),B(wt,this,gt(Ft,this,Ht).call(this,()=>Lr(()=>V(St,this).call(this,t)))),V(kt,this)===0&&(V(yt,this).before(e),B(Dt,this,null),Wr(V(Tt,this),()=>{B(Tt,this,null)}),gt(Ft,this,Vt).call(this,cn))}))}function Bt(){try{if(this.is_pending=this.has_pending_snippet(),B(kt,this,0),B(Ot,this,0),B(wt,this,Lr(()=>{V(St,this).call(this,V(yt,this))})),V(kt,this)>0){var e=B(Dt,this,document.createDocumentFragment());Jr(V(wt,this),e);let t=V(xt,this).pending;B(Tt,this,Lr(()=>t(V(yt,this))))}else gt(Ft,this,Vt).call(this,cn)}catch(e){this.error(e)}}function Vt(e){this.is_pending=!1,e.transfer_effects(V(jt,this),V(Mt,this))}function Ht(e){var t=ni,n=$r,r=Ye;ri(V(Ct,this)),ti(V(Ct,this)),Xe(V(Ct,this).ctx);try{return Pn.ensure(),e()}catch(e){return rt(e),null}finally{ri(t),ti(n),Xe(r)}}function Ut(e,t){if(!this.has_pending_snippet()){if(this.parent){var n;gt(Ft,n=this.parent,Ut).call(n,e,t)}return}B(kt,this,V(kt,this)+e),V(kt,this)===0&&(gt(Ft,this,Vt).call(this,t),V(Tt,this)&&Wr(V(Tt,this),()=>{B(Tt,this,null)}),V(Dt,this)&&(V(yt,this).before(V(Dt,this)),B(Dt,this,null)))}function Wt(e){V(wt,this)&&(Vr(V(wt,this)),B(wt,this,null)),V(Tt,this)&&(Vr(V(Tt,this)),B(Tt,this,null)),V(Et,this)&&(Vr(V(Et,this)),B(Et,this,null)),Pe&&(Le(V(bt,this)),Be(),Le(Ve()));var t=V(xt,this).onerror;let n=V(xt,this).failed;var r=!1,i=!1;let a=()=>{if(r){Ne();return}r=!0,i&&Oe(),V(Et,this)!==null&&Wr(V(Et,this),()=>{B(Et,this,null)}),gt(Ft,this,Ht).call(this,()=>{gt(Ft,this,Bt).call(this)})},o=e=>{try{i=!0,t?.(e,a),i=!1}catch(e){it(e,V(Ct,this)&&V(Ct,this).parent)}n&&B(Et,this,gt(Ft,this,Ht).call(this,()=>{try{return Lr(()=>{var t=ni;t.b=this,t.f|=128,n(V(yt,this),()=>e,()=>a)})}catch(e){return it(e,V(Ct,this).parent),null}}))};nt(()=>{var t;try{t=this.transform_error(e)}catch(e){it(e,V(Ct,this)&&V(Ct,this).parent);return}typeof t==`object`&&t&&typeof t.then==`function`?t.then(o,e=>it(e,V(Ct,this)&&V(Ct,this).parent)):o(t)})}function Gt(e,t,n,r){let i=$e()?Yt:$t;var a=e.filter(e=>!e.settled),o=t.map(i);if(n.length===0&&a.length===0){r(o);return}var s=ni,c=Kt(),l=a.length===1?a[0].promise:a.length>1?Promise.all(a.map(e=>e.promise)):null;function u(e){if(!(s.f&16384)){c();try{r([...o,...e])}catch(e){it(e,s)}qt()}}var d=Jt();if(n.length===0){l.then(()=>u([])).finally(d);return}function f(){Promise.all(n.map(e=>Zt(e))).then(u).catch(e=>it(e,s)).finally(d)}l?l.then(()=>{c(),f(),qt()}):f()}function Kt(){var e=ni,t=$r,n=Ye,r=cn;return function(i=!0){ri(e),ti(t),Xe(n),i&&!(e.f&16384)&&(r?.activate(),r?.apply())}}function qt(e=!0){ri(null),ti(null),Xe(null),e&&cn?.deactivate()}function Jt(){var e=ni,t=e.b,n=cn,r=!!t?.is_rendered();return t?.update_pending_count(1,n),n.increment(r,e),()=>{t?.update_pending_count(-1,n),n.decrement(r,e)}}function Yt(e){var t=2|ne;return ni!==null&&(ni.f|=le),{ctx:Ye,deps:null,effects:null,equals:Ue,f:t,fn:e,reactions:null,rv:0,v:Ae,wv:0,parent:ni,ac:null}}var Xt=Symbol(`obsolete`);function Zt(e,t,n){let r=ni;r===null&&Se();var i=void 0,a=$n(Ae),o=!$r,s=new Set;return Nr(()=>{var t=ni,n=O();i=n.promise;try{Promise.resolve(e()).then(n.resolve,e=>{e!==be&&n.reject(e)}).finally(qt)}catch(e){n.reject(e),qt()}var c=cn;if(o){if(t.f&32768)var l=Jt();if(r.b?.is_rendered())c.async_deriveds.get(t)?.reject(Xt);else for(let e of s.values())e.reject(Xt);s.add(n),c.async_deriveds.set(t,n)}let u=(e,t=void 0)=>{l?.(),s.delete(n),t!==Xt&&(c.activate(),t?(a.f|=pe,rr(a,t)):(a.f&8388608&&(a.f^=pe),rr(a,e)),c.deactivate())};n.promise.then(u,e=>u(null,e||`unknown`))}),Or(()=>{for(let e of s)e.reject(Xt)}),new Promise(e=>{function t(n){function r(){n===i?e(a):t(i)}n.then(r,r)}t(i)})}function Qt(e){let t=Yt(e);return ai(t),t}function $t(e){let t=Yt(e);return t.equals=Ge,t}function en(e){var t=e.effects;if(t!==null){e.effects=null;for(var n=0;nthis.schedule(e)){var n=V(An,this).get(e);if(n){V(An,this).delete(e);for(var r of n.d)ot(r,ne),t(r);for(r of n.m)ot(r,re),t(r)}V(jn,this).add(e)}capture(e,t,n=!1){e.v!==Ae&&!this.previous.has(e)&&this.previous.set(e,e.v),e.f&8388608||(this.current.set(e,[t,n]),un?.set(e,t)),this.is_fork||(e.v=t)}activate(){cn=this}deactivate(){cn=null,un=null}flush(){try{pn=!0,cn=this,gt(Nn,this,In).call(this)}finally{gn=0,dn=null,mn=null,hn=null,pn=!1,cn=null,un=null,Zn.clear()}}discard(){for(let e of V(Sn,this))e(this);V(Sn,this).clear();for(let e of this.async_deriveds.values())e.reject(Xt);gt(Nn,this,Vn).call(this),V(Tn,this)?.resolve()}register_created_effect(e){V(Dn,this).push(e)}increment(e,t){if(B(Cn,this,V(Cn,this)+1),e){let e=V(wn,this).get(t)??0;V(wn,this).set(t,e+1)}}decrement(e,t){if(B(Cn,this,V(Cn,this)-1),e){let e=V(wn,this).get(t)??0;e===1?V(wn,this).delete(t):V(wn,this).set(t,e-1)}V(Mn,this)||(B(Mn,this,!0),nt(()=>{B(Mn,this,!1),this.linked&&this.flush()}))}transfer_effects(e,t){for(let t of e)V(On,this).add(t);for(let e of t)V(kn,this).add(e);e.clear(),t.clear()}oncommit(e){V(xn,this).add(e)}ondiscard(e){V(Sn,this).add(e)}settled(){return(V(Tn,this)??B(Tn,this,O())).promise}static ensure(){if(cn===null){let t=cn=new e;!pn&&nt(()=>{V(vn,t)||t.flush()})}return cn}apply(){un=null}schedule(e){if(dn=e,e.b?.is_pending&&e.f&16777228&&!(e.f&32768)){e.b.defer_effect(e);return}for(var t=e;t.parent!==null;){t=t.parent;var n=t.f;if(mn!==null&&t===ni&&($r===null||!($r.f&2)))return;if(n&96){if(!(n&1024))return;t.f^=te}}V(En,this).push(t)}};on=Pn;function Fn(){if(this.is_fork)return!0;for(let n of V(wn,this).keys()){for(var e=n,t=!1;e.parent!==null;){if(V(An,this).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1}function In(){B(vn,this,!0),gn++>1e3&&(gt(Nn,this,Vn).call(this),Hn());for(let e of V(On,this))V(kn,this).delete(e),ot(e,ne),this.schedule(e);for(let e of V(kn,this))ot(e,re),this.schedule(e);let e=V(En,this);B(En,this,[]),this.apply();var t=mn=[],n=[],r=hn=[];for(let r of e)try{gt(Nn,this,Ln).call(this,r,t,n)}catch(e){throw Yn(r),gt(Nn,this,Fn).call(this)||this.discard(),e}if(cn=null,r.length>0){var i=on.ensure();for(let e of r)i.schedule(e)}if(mn=null,hn=null,gt(Nn,this,Fn).call(this)){gt(Nn,this,Bn).call(this,n),gt(Nn,this,Bn).call(this,t);for(let[e,t]of V(An,this))Jn(e,t);r.length>0&>(Nn,cn,In).call(cn);return}let a=gt(Nn,this,Rn).call(this);if(a){gt(Nn,this,Bn).call(this,n),gt(Nn,this,Bn).call(this,t),gt(Nn,a,zn).call(a,this);return}V(On,this).clear(),V(kn,this).clear();for(let e of V(xn,this))e(this);V(xn,this).clear(),ln=this,Wn(n),Wn(t),ln=null,V(Tn,this)?.resolve();var o=cn;if(V(Cn,this)===0&&(V(En,this).length===0||o!==null)&>(Nn,this,Vn).call(this),V(En,this).length>0)if(o!==null){let e=o;V(En,e).push(...V(En,this).filter(t=>!V(En,e).includes(t)))}else o=this;o!==null&>(Nn,o,In).call(o)}function Ln(e,t,n){e.f^=te;for(var r=e.first;r!==null;){var i=r.f,a=(i&96)!=0;if(!(a&&i&1024||i&8192||V(An,this).has(r))&&r.fn!==null){a?r.f^=te:i&4?t.push(r):hi(r)&&(i&16&&V(kn,this).add(r),bi(r));var o=r.first;if(o!==null){r=o;continue}}for(;r!==null;){var s=r.next;if(s!==null){r=s;break}r=r.parent}}}function Rn(){for(var e=V(yn,this);e!==null;){if(!e.is_fork){for(let[t,[,n]]of this.current)if(e.current.has(t)&&!n)return e}e=V(yn,e)}return null}function zn(e){for(let[t,n]of e.current)!this.previous.has(t)&&e.previous.has(t)&&this.previous.set(t,e.previous.get(t)),this.current.set(t,n);for(let[t,n]of e.async_deriveds){let e=this.async_deriveds.get(t);e&&n.promise.then(e.resolve).catch(e.reject)}e.async_deriveds.clear(),this.transfer_effects(V(On,e),V(kn,e));let t=e=>{var n=e.reactions;if(n!==null)for(let e of n){var r=e.f;if(r&2)t(e);else{var i=e;r&4194320&&!this.async_deriveds.has(i)&&(V(kn,this).delete(i),ot(i,ne),this.schedule(i))}}};for(let e of this.current.keys())t(e);this.oncommit(()=>e.discard()),gt(Nn,e,Vn).call(e),cn=this,gt(Nn,this,In).call(this)}function Bn(e){for(var t=0;t0)){Zn.clear();for(let e of Un){if(e.f&24576)continue;let t=[e],n=e.parent;for(;n!==null;)Un.has(n)&&(Un.delete(n),t.push(n)),n=n.parent;for(let e=t.length-1;e>=0;e--){let n=t[e];n.f&24576||bi(n)}}Un.clear()}}Un=null}}function Gn(e,t,n,r){if(!n.has(e)&&(n.add(e),e.reactions!==null))for(let i of e.reactions){let e=i.f;e&2?Gn(i,t,n,r):e&4194320&&!(e&2048)&&Kn(i,t,r)&&(ot(i,ne),qn(i))}}function Kn(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(e.deps!==null)for(let r of e.deps){if(_.call(t,r))return!0;if(r.f&2&&Kn(r,t,n))return n.set(r,!0),!0}return n.set(e,!1),!1}function qn(e){cn.schedule(e)}function Jn(e,t){if(!(e.f&32&&e.f&1024)){e.f&2048?t.d.push(e):e.f&4096&&t.m.push(e),ot(e,te);for(var n=e.first;n!==null;)Jn(n,t),n=n.next}}function Yn(e){ot(e,te);for(var t=e.first;t!==null;)Yn(t),t=t.next}var Xn=new Set,Zn=new Map,Qn=!1;function $n(e,t){return{f:0,v:e,reactions:null,equals:Ue,rv:0,wv:0}}function er(e,t){let n=$n(e,t);return ai(n),n}function tr(e,t=!1,n=!0){let r=$n(e);return t||(r.equals=Ge),r}function nr(e,t,n=!1){return $r!==null&&(!ei||$r.f&131072)&&$e()&&$r.f&4325394&&(ii===null||!ii.has(e))&&z(),rr(e,n?sr(t):t,hn)}function rr(e,t,n=null){if(!e.equals(t)){Zn.set(e,Zr?t:e.v);var r=Pn.ensure();if(r.capture(e,t),e.f&2){let t=e;e.f&2048&&tn(t),un===null&&st(t)}e.wv=mi(),or(e,ne,n),$e()&&ni!==null&&ni.f&1024&&!(ni.f&96)&&(ci===null?li([e]):ci.push(e)),!r.is_fork&&Xn.size>0&&!Qn&&ir()}return t}function ir(){Qn=!1;for(let e of Xn){e.f&1024&&ot(e,re);let t;try{t=hi(e)}catch{t=!0}t&&bi(e)}Xn.clear()}function ar(e){nr(e,e.v+1)}function or(e,t,n){var r=e.reactions;if(r!==null)for(var i=$e(),a=r.length,o=0;o{if(fi===o)return e();var t=$r,n=fi;ti(null),pi(o);var r=e();return ti(t),pi(n),r};return r&&n.set(`length`,er(e.length,a)),new Proxy(e,{defineProperty(e,t,r){(!(`value`in r)||r.configurable===!1||r.enumerable===!1||r.writable===!1)&&Ee();var i=n.get(t);return i===void 0?s(()=>{var e=er(r.value,a);return n.set(t,e),e}):nr(i,r.value,!0),!0},deleteProperty(e,t){var r=n.get(t);if(r===void 0){if(t in e){let e=s(()=>er(Ae,a));n.set(t,e),ar(i)}}else nr(r,Ae),ar(i);return!0},get(t,r,i){if(r===me)return e;var o=n.get(r),c=r in t;if(o===void 0&&(!c||b(t,r)?.writable)&&(o=s(()=>er(sr(c?t[r]:Ae),a)),n.set(r,o)),o!==void 0){var l=H(o);return l===Ae?void 0:l}return Reflect.get(t,r,i)},getOwnPropertyDescriptor(e,t){var r=Reflect.getOwnPropertyDescriptor(e,t);if(r&&`value`in r){var i=n.get(t);i&&(r.value=H(i))}else if(r===void 0){var a=n.get(t),o=a?.v;if(a!==void 0&&o!==Ae)return{enumerable:!0,configurable:!0,value:o,writable:!0}}return r},has(e,t){if(t===me)return!0;var r=n.get(t),i=r!==void 0&&r.v!==Ae||Reflect.has(e,t);return(r!==void 0||ni!==null&&(!i||b(e,t)?.writable))&&(r===void 0&&(r=s(()=>er(i?sr(e[t]):Ae,a)),n.set(t,r)),H(r)===Ae)?!1:i},set(e,t,o,c){var l=n.get(t),u=t in e;if(r&&t===`length`)for(var d=o;der(Ae,a)),n.set(d+``,f)):nr(f,Ae)}if(l===void 0)(!u||b(e,t)?.writable)&&(l=s(()=>er(void 0,a)),nr(l,sr(o)),n.set(t,l));else{u=l.v!==Ae;var p=s(()=>sr(o));nr(l,p)}var m=Reflect.getOwnPropertyDescriptor(e,t);if(m?.set&&m.set.call(c,o),!u){if(r&&typeof t==`string`){var h=n.get(`length`),g=Number(t);Number.isInteger(g)&&g>=h.v&&nr(h,g+1)}ar(i)}return!0},ownKeys(e){H(i);var t=Reflect.ownKeys(e).filter(e=>{var t=n.get(e);return t===void 0||t.v!==Ae});for(var[r,a]of n)a.v!==Ae&&!(r in e)&&t.push(r);return t},setPrototypeOf(){De()}})}var cr,lr,ur,dr;function fr(){if(cr===void 0){cr=window,lr=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;ur=b(t,`firstChild`).get,dr=b(t,`nextSibling`).get,T(e)&&(e[ve]=void 0,e[_e]=null,e[P]=void 0,e.__e=void 0),T(n)&&(n[ye]=void 0)}}function pr(e=``){return document.createTextNode(e)}function mr(e){return ur.call(e)}function hr(e){return dr.call(e)}function gr(e,t){if(!Pe)return mr(e);var n=mr(Ie);if(n===null)n=Ie.appendChild(pr());else if(t&&n.nodeType!==3){var r=pr();return n?.before(r),Le(r),r}return t&&Sr(n),Le(n),n}function _r(e,t=!1){if(!Pe){var n=mr(e);return n instanceof Comment&&n.data===``?hr(n):n}if(t){if(Ie?.nodeType!==3){var r=pr();return Ie?.before(r),Le(r),r}Sr(Ie)}return Ie}function vr(e,t=1,n=!1){let r=Pe?Ie:e;for(var i;t--;)i=r,r=hr(r);if(!Pe)return r;if(n){if(r?.nodeType!==3){var a=pr();return r===null?i?.after(a):r.before(a),Le(a),a}Sr(r)}return Le(r),r}function yr(e){e.textContent=``}function br(){return!1}function xr(e,t,n){return t==null||t===`http://www.w3.org/1999/xhtml`?n?document.createElement(e,{is:n}):document.createElement(e):n?document.createElementNS(t,e,{is:n}):document.createElementNS(t,e)}function Sr(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===3;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function Cr(e){var t=$r,n=ni;ti(null),ri(null);try{return e()}finally{ti(t),ri(n)}}function wr(e){ni===null&&($r===null&&R(e),L()),Zr&&Ce(e)}function Tr(e,t){var n=t.last;n===null?t.last=t.first=e:(n.next=e,e.prev=n,t.last=e)}function Er(e,t){var n=ni;n!==null&&n.f&8192&&(e|=ie);var r={ctx:Ye,deps:null,nodes:null,f:e|ne|512,first:null,fn:t,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null};cn?.register_created_effect(r);var i=r;if(e&4)mn===null?Pn.ensure().schedule(r):mn.push(r);else if(t!==null){try{bi(r)}catch(e){throw Vr(r),e}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&!(i.f&524288)&&(i=i.first,e&16&&e&65536&&i!==null&&(i.f|=ce))}if(i!==null&&(i.parent=n,n!==null&&Tr(i,n),$r!==null&&$r.f&2&&!(e&64))){var a=$r;(a.effects??(a.effects=[])).push(i)}return r}function Dr(){return $r!==null&&!ei}function Or(e){let t=Er(8,null);return ot(t,te),t.teardown=e,t}function kr(e){wr(`$effect`);var t=ni.f;if(!$r&&t&32&&Ye!==null&&!Ye.i){var n=Ye;(n.e??(n.e=[])).push(e)}else return Ar(e)}function Ar(e){return Er(4|ue,e)}function jr(e){Pn.ensure();let t=Er(64|le,e);return(e={})=>new Promise(n=>{e.outro?Wr(t,()=>{Vr(t),n(void 0)}):(Vr(t),n(void 0))})}function Mr(e){return Er(4,e)}function Nr(e){return Er(fe|le,e)}function Pr(e,t=0){return Er(8|t,e)}function Fr(e,t=[],n=[],r=[]){Gt(r,t,n,t=>{Er(8,()=>{e(...t.map(H))})})}function Ir(e,t=0){return Er(16|t,e)}function Lr(e){return Er(32|le,e)}function Rr(e){var t=e.teardown;if(t!==null){let e=Zr,n=$r;Qr(!0),ti(null);try{t.call(null)}finally{Qr(e),ti(n)}}}function zr(e,t=!1){var n=e.first;for(e.first=e.last=null;n!==null;){let e=n.ac;e!==null&&Cr(()=>{e.abort(be)});var r=n.next;n.f&64?n.parent=null:Vr(n,t),n=r}}function Br(e){for(var t=e.first;t!==null;){var n=t.next;t.f&32||Vr(t),t=n}}function Vr(e,t=!0){var n=!1;(t||e.f&262144)&&e.nodes!==null&&e.nodes.end!==null&&(Hr(e.nodes.start,e.nodes.end),n=!0),e.f|=se,zr(e,t&&!n),yi(e,0);var r=e.nodes&&e.nodes.t;if(r!==null)for(let e of r)e.stop();Rr(e),e.f^=se,e.f|=ae;var i=e.parent;i!==null&&i.first!==null&&Ur(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function Hr(e,t){for(;e!==null;){var n=e===t?null:hr(e);e.remove(),e=n}}function Ur(e){var t=e.parent,n=e.prev,r=e.next;n!==null&&(n.next=r),r!==null&&(r.prev=n),t!==null&&(t.first===e&&(t.first=r),t.last===e&&(t.last=n))}function Wr(e,t,n=!0){var r=[];Gr(e,r,!0);var i=()=>{n&&Vr(e),t&&t()},a=r.length;if(a>0){var o=()=>--a||i();for(var s of r)s.out(o)}else i()}function Gr(e,t,n){if(!(e.f&8192)){e.f^=ie;var r=e.nodes&&e.nodes.t;if(r!==null)for(let e of r)(e.is_global||n)&&t.push(e);for(var i=e.first;i!==null;){var a=i.next;if(!(i.f&64)){var o=(i.f&65536)!=0||(i.f&32)!=0&&(e.f&16)!=0;Gr(i,t,o?n:!1)}i=a}}}function Kr(e){qr(e,!0)}function qr(e,t){if(e.f&8192){e.f^=ie,e.f&1024||(ot(e,ne),Pn.ensure().schedule(e));for(var n=e.first;n!==null;){var r=n.next,i=(n.f&65536)!=0||(n.f&32)!=0;qr(n,i?t:!1),n=r}var a=e.nodes&&e.nodes.t;if(a!==null)for(let e of a)(e.is_global||t)&&e.in()}}function Jr(e,t){if(e.nodes)for(var n=e.nodes.start,r=e.nodes.end;n!==null;){var i=n===r?null:hr(n);t.append(n),n=i}}var Yr=null,Xr=!1,Zr=!1;function Qr(e){Zr=e}var $r=null,ei=!1;function ti(e){$r=e}var ni=null;function ri(e){ni=e}var ii=null;function ai(e){$r!==null&&(ii??(ii=new Set)).add(e)}var oi=null,si=0,ci=null;function li(e){ci=e}var ui=1,di=0,fi=di;function pi(e){fi=e}function mi(){return++ui}function hi(e){var t=e.f;if(t&2048)return!0;if(t&2&&(e.f&=~N),t&4096){for(var n=e.deps,r=n.length,i=0;ie.wv)return!0}t&512&&un===null&&ot(e,te)}return!1}function gi(e,t,n=!0){var r=e.reactions;if(r!==null&&!(ii!==null&&ii.has(e)))for(var i=0;i{e.ac.abort(be)}),e.ac=null);try{e.f|=de;var u=e.fn,d=u();e.f|=oe;var f=e.deps,p=cn?.is_fork;if(oi!==null){var m;if(p||yi(e,si),f!==null&&si>0)for(f.length=si+oi.length,m=0;m{throw e});throw f}}finally{e[Oi]=t,delete e.currentTarget,ti(u),ri(d)}}}var Fi=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy(`svelte-trusted-html`,{createHTML:e=>e});function Ii(e){return Fi?.createHTML(e)??e}function Li(e){var t=xr(`template`);return t.innerHTML=Ii(e.replaceAll(``,``)),t.content}function Ri(e,t){var n=ni;n.nodes===null&&(n.nodes={start:e,end:t,a:null,t:null})}function zi(e,t){var n=(t&1)!=0,r=(t&2)!=0,i,a=!e.startsWith(``);return()=>{if(Pe)return Ri(Ie,null),Ie;i===void 0&&(i=Li(a?e:``+e),n||(i=mr(i)));var t=r||lr?document.importNode(i,!0):i.cloneNode(!0);if(n){var o=mr(t),s=t.lastChild;Ri(o,s)}else Ri(t,t);return t}}function Bi(e,t){if(Pe){var n=ni;(!(n.f&32768)||n.nodes.end===null)&&(n.nodes.end=Ie),Re();return}e!==null&&e.before(t)}function Vi(e,t){var n=t==null?``:typeof t==`object`?`${t}`:t;n!==(e[ye]??(e[ye]=e.nodeValue))&&(e[ye]=n,e.nodeValue=`${n}`)}function Hi(e,t){return Wi(e,t)}var Ui=new Map;function Wi(e,{target:t,anchor:n,props:r={},events:i,context:a,intro:o=!0,transformError:s}){fr();var c=void 0,l=jr(()=>{var o=n??t.appendChild(pr());vt(o,{pending:()=>{}},t=>{Ze({});var n=Ye;if(a&&(n.c=a),i&&(r.$$events=i),Pe&&Ri(t,null),c=e(t,r)||{},Pe&&(ni.nodes.end=Ie,Ie===null||Ie.nodeType!==8||Ie.data!==`]`))throw Me(),ke;Qe()},s);var l=new Set,u=e=>{for(var n=0;n{for(var e of l)for(let n of[t,document]){var r=Ui.get(n),i=r.get(e);--i==0?(n.removeEventListener(e,Pi),r.delete(e),r.size===0&&Ui.delete(n)):r.set(e,i)}Ai.delete(u),o!==n&&o.parentNode?.removeChild(o)}});return Gi.set(c,l),c}var Gi=new WeakMap;function Ki(e,t){let n=Gi.get(e);return n?(Gi.delete(e),n(t)):Promise.resolve()}var qi=new WeakMap,Ji=new WeakMap,Yi=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,Qi=new WeakMap,$i=new WeakMap,ea=class{constructor(e,t=!0){j(this,`anchor`,void 0),ht(this,qi,new Map),ht(this,Ji,new Map),ht(this,Yi,new Map),ht(this,Xi,new Set),ht(this,Zi,!0),ht(this,Qi,e=>{if(V(qi,this).has(e)){var t=V(qi,this).get(e),n=V(Ji,this).get(t);if(n)Kr(n),V(Xi,this).delete(t);else{var r=V(Yi,this).get(t);r&&(Kr(r.effect),V(Ji,this).set(t,r.effect),V(Yi,this).delete(t),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),n=r.effect)}for(let[t,n]of V(qi,this)){if(V(qi,this).delete(t),t===e)break;let r=V(Yi,this).get(n);r&&(Vr(r.effect),V(Yi,this).delete(n))}for(let[e,r]of V(Ji,this)){if(e===t||V(Xi,this).has(e))continue;let i=()=>{if(Array.from(V(qi,this).values()).includes(e)){var t=document.createDocumentFragment();Jr(r,t),t.append(pr()),V(Yi,this).set(e,{effect:r,fragment:t})}else Vr(r);V(Xi,this).delete(e),V(Ji,this).delete(e)};V(Zi,this)||!n?(V(Xi,this).add(e),Wr(r,i,!1)):i()}}}),ht(this,$i,e=>{V(qi,this).delete(e);let t=Array.from(V(qi,this).values());for(let[e,n]of V(Yi,this))t.includes(e)||(Vr(n.effect),V(Yi,this).delete(e))}),this.anchor=e,B(Zi,this,t)}ensure(e,t){var n=cn,r=br();if(t&&!V(Ji,this).has(e)&&!V(Yi,this).has(e))if(r){var i=document.createDocumentFragment(),a=pr();i.append(a),V(Yi,this).set(e,{effect:Lr(()=>t(a)),fragment:i})}else V(Ji,this).set(e,Lr(()=>t(this.anchor)));if(V(qi,this).set(n,e),r){for(let[t,r]of V(Ji,this))t===e?n.unskip_effect(r):n.skip_effect(r);for(let[t,r]of V(Yi,this))t===e?n.unskip_effect(r.effect):n.skip_effect(r.effect);n.oncommit(V(Qi,this)),n.ondiscard(V($i,this))}else Pe&&(this.anchor=Ie),V(Qi,this).call(this,n)}};function ta(e,t,n=!1){var r;Pe&&(r=Ie,Re());var i=new ea(e),a=n?ce:0;function o(e,t){if(Pe){var n=He(r);if(e!==parseInt(n.substring(1))){var a=Ve();Le(a),i.anchor=a,Fe(!1),i.ensure(e,t),Fe(!0);return}}i.ensure(e,t)}Ir(()=>{var e=!1;t((t,n=0)=>{e=!0,o(n,t)}),e||o(-1,null)},a)}function na(e,t){return t}function ra(e,t,n){for(var r=[],i=t.length,a,o=t.length,s=0;s{if(a){if(a.pending.delete(n),a.done.add(n),a.pending.size===0){var t=e.outrogroups;ia(e,v(a.done)),t.delete(a),t.size===0&&(e.outrogroups=null)}}else--o},!1)}if(o===0){var c=r.length===0&&n!==null;if(c){var l=n,u=l.parentNode;yr(u),u.append(l),e.items.clear()}ia(e,t,!c)}else a={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(a)}function ia(e,t,n=!0){var r;if(e.pending.size>0){r=new Set;for(let t of e.pending.values())for(let n of t)r.add(e.items.get(n).e)}for(var i=0;i{var e=n();return h(e)?e:e==null?[]:v(e)}),d,f=new Map,p=!0;function m(e){_.effect.f&16384||(_.pending.delete(e),_.fallback=l,ca(_,d,o,t,r),l!==null&&(d.length===0?l.f&33554432?(l.f^=M,ua(l,null,o)):Kr(l):Wr(l,()=>{l=null})))}function g(e){_.pending.delete(e)}var _={effect:Ir(()=>{d=H(u);var e=d.length;let c=!1;Pe&&He(o)===`[!`!=(e===0)&&(o=Ve(),Le(o),Fe(!1),c=!0);for(var h=new Set,_=cn,v=br(),y=0;ya(o)):(l=Lr(()=>a(aa??(aa=pr()))),l.f|=M)),e>h.size&&I(``,``,``),Pe&&e>0&&Le(Ve()),!p)if(f.set(_,h),v){for(let[e,t]of s)h.has(e)||_.skip_effect(t.e);_.oncommit(m),_.ondiscard(g)}else m(_);c&&Fe(!0),H(u)}),flags:t,items:s,pending:f,outrogroups:null,fallback:l};p=!1,Pe&&(o=Ie)}function sa(e){for(;e!==null&&!(e.f&32);)e=e.next;return e}function ca(e,t,n,r,i){var a=(r&8)!=0,o=t.length,s=e.items,c=sa(e.effect.first),l,u=null,d,f=[],p=[],m,h,g,_;if(a)for(_=0;_0){var E=r&4&&o===0?n:null;if(a){for(_=0;_{if(d!==void 0)for(g of d)g.nodes?.a?.apply()})}function la(e,t,n,r,i,a,o,s){var c=o&1?o&16?$n(n):tr(n,!1,!1):null,l=o&2?$n(i):null;return{v:c,i:l,e:Lr(()=>(a(t,c??n,l??i,s),()=>{e.delete(r)}))}}function ua(e,t,n){if(e.nodes)for(var r=e.nodes.start,i=e.nodes.end,a=t&&!(t.f&33554432)?t.nodes.start:n;r!==null;){var o=hr(r);if(a.before(r),r===i)return;r=o}}function da(e,t,n){t===null?e.effect.first=n:t.next=n,n===null?e.effect.last=t:n.prev=t}function fa(e,t){Mr(()=>{var n=e.getRootNode(),r=n.host?n:n.head??n.ownerDocument.head;if(!r.querySelector(`#`+t.hash)){let e=xr(`style`);e.id=t.hash,e.textContent=t.code,r.appendChild(e)}})}function pa(e,t,n){Mr(()=>{var r=Ci(()=>t(e,n?.())||{});if(n&&r?.update){var i=!1,a={};Pr(()=>{var e=n();wi(e),i&&We(a,e)&&(a=e,r.update(e))}),i=!0}if(r?.destroy)return()=>r.destroy()})}var ma=[...` +\r\f\xA0\v`];function ha(e,t,n){var r=e==null?``:``+e;if(t&&(r=r?r+` `+t:t),n){for(var i of Object.keys(n))if(n[i])r=r?r+` `+i:i;else if(r.length)for(var a=i.length,o=0;(o=r.indexOf(i,o))>=0;){var s=o+a;(o===0||ma.includes(r[o-1]))&&(s===r.length||ma.includes(r[s]))?r=(o===0?``:r.substring(0,o))+r.substring(s+1):o=s}}return r===``?null:r}function ga(e,t=!1){var n=t?` !important;`:`;`,r=``;for(var i of Object.keys(e)){var a=e[i];a!=null&&a!==``&&(r+=` `+i+`: `+a+n)}return r}function _a(e){return e[0]!==`-`||e[1]!==`-`?e.toLowerCase():e}function va(e,t){if(t){var n=``,r,i;if(Array.isArray(t)?(r=t[0],i=t[1]):r=t,e){e=String(e).replaceAll(/\s*\/\*.*?\*\/\s*/g,``).trim();var a=!1,o=0,s=!1,c=[];r&&c.push(...Object.keys(r).map(_a)),i&&c.push(...Object.keys(i).map(_a));var l=0,u=-1;let t=e.length;for(var d=0;d{var n=V(Aa,this).get(e);n.delete(t),n.size===0&&(V(Aa,this).delete(e),V(ja,this).unobserve(e))}}};ka=Pa;function Fa(){return V(ja,this)??B(ja,this,new ResizeObserver(e=>{for(var t of e){ka.entries.set(t.target,t);for(var n of V(Aa,this).get(t.target)||[])n(t)}}))}j(Pa,`entries`,new WeakMap);function Ia(e,t){return e===t||e?.[me]===t}function La(e={},t,n,r){var i=Ye.r,a=ni;return Mr(()=>{var o,s;return Pr(()=>{o=s,s=r?.()||[],Ci(()=>{Ia(n(...s),e)||(t(e,...s),o&&Ia(n(...o),e)&&t(null,...o))})}),()=>{let r=a;for(;r!==i&&r.parent!==null&&r.parent.f&33554432;)r=r.parent;let o=()=>{s&&Ia(n(...s),e)&&t(null,...s)},c=r.teardown;r.teardown=()=>{o(),c?.()}}}),e}function Ra(e,t,n,r){var i=!0,a=(n&8)!=0,o=(n&16)!=0,s=r,c=!0,l=void 0,u=()=>o&&i?(l??(l=Yt(r)),H(l)):(c&&(c=!1,s=o?Ci(r):r),s);let d;if(a){var f=me in e||he in e;d=b(e,t)?.set??(f&&t in e?n=>e[t]=n:void 0)}var p,m=!1;a?[p,m]=dt(()=>e[t]):p=e[t],p===void 0&&r!==void 0&&(p=u(),d&&(i&&Te(t),d(p)));var h=i?()=>{var n=e[t];return n===void 0?u():(c=!0,n)}:()=>{var n=e[t];return n!==void 0&&(s=void 0),n===void 0?s:n};if(i&&!(n&4))return h;if(d){var g=e.$$legacy;return(function(e,t){return arguments.length>0?((!i||!t||g||m)&&d(t?h():e),e):h()})}var _=!1,v=(n&1?Yt:$t)(()=>(_=!1,h()));a&&H(v);var y=ni;return(function(e,t){if(arguments.length>0){let n=t?H(v):i&&a?sr(e):e;return nr(v,n),_=!0,s!==void 0&&(s=n),e}return Zr&&_||y.f&16384?v.v:H(v)})}function za(e){Ye===null&&F(`onMount`),kr(()=>{let t=Ci(e);if(typeof t==`function`)return t})}function Ba(e){Ye===null&&F(`onDestroy`),za(()=>()=>Ci(e))}var Va=class{constructor(e,t,n){this.children=[],this.key=e,this.title=t,this.level=n,this.children=[]}};function Ha(e=document){let t=e.querySelectorAll(`h1, h2, h3, h4, h5, h6`),n=new Va(``,`Root`,0),r=n;return t.forEach(e=>{if(e.style.display==`none`)return;let t=parseInt(e.tagName.slice(1)),n=e.querySelector(`a.md-print-anchor`),i=/^af:\/\/(.+)$/.exec(n?.href??``);if(!i)return;let a=new Va(i[1],e.innerText,t);for(;r.level>=t;)r=r.parent;r.children.push(a),a.parent=r,r=a}),n}function Ua(e){let t=new Map;return e.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach((e,n)=>{let r=document.createElement(`a`),i=`${e.tagName.toLowerCase()}-${n}`;r.href=`af://${i}`,r.className=`md-print-anchor`,e.appendChild(r),e.dataset.heading&&t.set(e.dataset.heading,i);let a=e.textContent?.trim();if(a){t.set(a,i),t.set(encodeURIComponent(a),i),t.set(a.replace(/\s+/g,`-`),i),t.set(a.toLowerCase().replace(/\s+/g,`-`),i);let e=a.replace(/[^\w\s-]/g,``).trim();e&&e!==a&&(t.set(e,i),t.set(e.replace(/\s+/g,`-`),i),t.set(e.toLowerCase().replace(/\s+/g,`-`),i))}e.id&&t.set(e.id,i)}),t}function Wa(e){return new Map(Array.from(e).map(([e,t])=>[e?.toLowerCase(),t]))}function Ga(e,t,n){let r=Wa(t);e.querySelectorAll(`a.internal-link`).forEach((e,i)=>{let[a,o]=e.dataset.href?.split(`#`)??[];if(o?.startsWith(`^`)&&(e.href=e.dataset.href?.toLowerCase()),o?.length>0){if(a?.length>0&&a!=n)return;let i=t.get(o)||r.get(o?.toLowerCase());i&&!o.startsWith(`^`)&&(e.href=`an://${i}`)}}),e.querySelectorAll(`a[href^='#']`).forEach(e=>{let n=e.getAttribute(`href`);if(!n)return;let i=n.substring(1);if(!i||e.classList.contains(`internal-link`)||i.startsWith(`^`))return;let a=[i,decodeURIComponent(i),i.replace(/-/g,` `),decodeURIComponent(i).replace(/-/g,` `),i.toLowerCase(),decodeURIComponent(i).toLowerCase(),i.toLowerCase().replace(/-/g,` `),decodeURIComponent(i).toLowerCase().replace(/-/g,` `)],o=null;for(let e of a)if(o=t.get(e)||r.get(e.toLowerCase()),o)break;o&&(e.href=`an://${o}`)})}var Ka=e=>Math.round(e*.26458333333719),qa=e=>Math.round(e*3.779527559);function Ja(e){if(e instanceof l.TFile)return e.extension==`md`?[e]:[];let t=[];for(let n of e.children)t.push(...Ja(n));return t.sort((e,t)=>e.name.localeCompare(t.name)),t}function Ya(e,t){Array.from(t).forEach(t=>{e.setAttribute(t.name,t.value)})}function Xa(e,t){return e.replace(/\{\{(.*?)\}\}/g,(e,n)=>t[n.trim()])}function Za(e){return!isNaN(parseFloat(e))}function Qa(e,t=0){try{let n=parseInt(String(e));return isNaN(n)?t:n}catch{return t}}function $a(e,t=0){try{let n=parseFloat(String(e));return isNaN(n)?t:n}catch{return t}}function eo(){let e=new Set,t={};try{for(let n of document.styleSheets)try{let r=n.cssRules||n.rules;if(!r)continue;for(let n of r){if(n.type!==CSSRule.STYLE_RULE)continue;let r=n.selectorText;if(r.includes(`.theme-light`)){let t=n.style;for(let n=0;n{let n=t.ownerNode?.id;if(n?.startsWith(`svelte-`))return;let r=t.ownerNode?.href,i=`/* ----------${n?`id:${n}`:r?`href:${r}`:``}---------- */`;e.push(i);try{Array.from(t?.cssRules??[]).forEach(t=>{e.push(t.cssText)})}catch(e){console.error(e)}}),e.push(...ao()),e}var io=` /* ---------- css patch ---------- */ body { @@ -40,14 +46,14 @@ img.__canvas__ { width: 100% !important; height: 100% !important; } -`;function co(){return[so,...lo()]}function lo(){let e=[];return Array.from(document.styleSheets).forEach(t=>{try{let n=t?.cssRules??[];Array.from(n).forEach(t=>{if(t.constructor.name==`CSSMediaRule`&&t.conditionText===`print`){let n=t.cssText.replace(/@media print\s*\{(.+)\}/gms,`$1`);e.push(n)}})}catch(e){console.error(e)}}),e}function uo(e){return Array.from({length:e},()=>(16*Math.random()|0).toString(16)).join(``)}function fo(e,t){return e.metadataCache.getFileCache(t)?.frontmatter??{}}async function po({app:e,file:t,config:n,extra:r}){let i=new Date().getTime(),a=e.workspace.getLeaf(!0);await a.openFile(t),a.view;let o=await e.vault.cachedRead(t);o||new l.Notice(`data is empty!`);let s=fo(e,t),c=[];for(let[e,t]of Object.entries(s))(e.toLowerCase()==`cssclass`||e.toLowerCase()==`cssclasses`)&&(Array.isArray(t)?c.push(...t):c.push(t));let u=new l.Component;u.load();let d=document.body.createDiv(`print`),f=d.createDiv({cls:`markdown-preview-view markdown-rendered `+c.join(` `)});f.toggleClass(`rtl`,e.vault.getConfig(`rightToLeft`)),f.toggleClass(`show-properties`,e.vault.getConfig(`propertiesInDocument`)!==`hidden`);let p=r?.title??s?.title??t.basename;f.createEl(`h1`,{text:p},e=>{e.addClass(`__title__`),e.style.display=n?.showTitle?`block`:`none`,e.id=r?.id??``});let m=e.metadataCache.getFileCache(t),h=new Map(Object.entries(m?.blocks??{})),g=(o?.split(` +`;function ao(){return[io,...oo()]}function oo(){let e=[];return Array.from(document.styleSheets).forEach(t=>{try{let n=t?.cssRules??[];Array.from(n).forEach(t=>{if(t.constructor.name==`CSSMediaRule`&&t.conditionText===`print`){let n=t.cssText.replace(/@media print\s*\{(.+)\}/gms,`$1`);e.push(n)}})}catch(e){console.error(e)}}),e}function so(e){return Array.from({length:e},()=>(16*Math.random()|0).toString(16)).join(``)}function co(e,t){return e.metadataCache.getFileCache(t)?.frontmatter??{}}async function lo({app:e,file:t,config:n,extra:r}){let i=new Date().getTime(),a=e.workspace.getLeaf(!0);await a.openFile(t),a.view;let o=await e.vault.cachedRead(t);o||new l.Notice(`data is empty!`);let s=co(e,t),c=[];for(let[e,t]of Object.entries(s))(e.toLowerCase()==`cssclass`||e.toLowerCase()==`cssclasses`)&&(Array.isArray(t)?c.push(...t):c.push(t));let u=new l.Component;u.load();let d=document.body.createDiv(`print theme-light`),f=d.createDiv({cls:`markdown-preview-view markdown-rendered`+c.join(` `)});f.toggleClass(`rtl`,e.vault.getConfig(`rightToLeft`)),f.toggleClass(`show-properties`,e.vault.getConfig(`propertiesInDocument`)!==`hidden`);let p=r?.title??s?.title??t.basename;f.createEl(`h1`,{text:p},e=>{e.addClass(`__title__`),e.style.display=n?.showTitle?`block`:`none`,e.id=r?.id??``});let m=e.metadataCache.getFileCache(t),h=new Map(Object.entries(m?.blocks??{})),g=(o?.split(` `)??[]).map((e,t)=>{for(let{id:n,position:{start:r,end:i}}of h.values()){let a=`^${n}`;if(e.includes(a)&&t>=r.line&&t<=i.line)return h.delete(n),e.replace(a,` ${a}`)}return e});[...h.values()].forEach(({id:e,position:{start:t,end:n}})=>{let r=t.line;g[r]=`\n\n`+g[r]});let _={children:void 0,appendChild(e){throw this.children=e?.children,Error(`exit`)}},v=[];try{await l.MarkdownRenderer.render(e,g.join(` -`),_,t.path,u)}catch{}let y=createFragment();Array.from(_.children).forEach(e=>{y.createDiv({},t=>t.appendChild(e))}),f.appendChild(y),await l.MarkdownRenderer.postProcess(e,{docId:uo(16),sourcePath:t.path,frontmatter:{},promises:v,addChild:function(e){return u.addChild(e)},getSectionInfo:function(){return null},containerEl:f,el:f,displayMode:!0}),await Promise.all(v),d.findAll(`a.internal-link`).forEach(e=>{let[n,r]=e.dataset.href?.split(`#`)??[];(!n||n?.length==0||n==t.basename)&&r?.startsWith(`^`)||e.removeAttribute(`href`)});try{await xo(o,f)}catch{console.warn(`wait timeout`)}So(f);let b=document.implementation.createHTMLDocument(`document`);return b.body.appendChild(d.cloneNode(!0)),d.detach(),u.unload(),d.remove(),b.title=p,a.detach(),console.log(`md render time:${new Date().getTime()-i}ms`),{doc:b,frontMatter:s,file:t}}async function mo({app:e,file:t,config:n,extra:r}){let i=new Date().getTime(),a=await e.vault.cachedRead(t);a||new l.Notice(`${t} content is empty!`);let o=new l.Component;o.load();let s=document.body.createDiv({cls:`print`,attr:{id:t.path}}),{viewEl:c,frontMatter:u}=ho({app:e,file:t,extra:r,config:n,printEl:s});return await _o({app:e,markdown:go({app:e,file:t,data:a}),file:t,comp:o,viewEl:c}),console.log(`md render time:${new Date().getTime()-i}ms`),{doc:s,frontMatter:u,file:t,cleanup:()=>{s.detach(),o.unload(),s.remove()}}}function ho({app:e,file:t,printEl:n,extra:r,config:i}){let a=fo(e,t),o=n.createDiv({cls:`markdown-preview-view markdown-rendered`}),s=Eo(a);o.addClasses(s),o.toggleClass(`rtl`,e.vault.getConfig(`rightToLeft`)),o.toggleClass(`show-properties`,e.vault.getConfig(`propertiesInDocument`)!==`hidden`);let c=r?.title??a?.title??t.basename;return o.createEl(`h1`,{text:c},e=>{e.addClass(`__title__`),e.style.display=i?.showTitle?`block`:`none`,e.id=r?.id??``}),{viewEl:o,frontMatter:a}}function go({app:e,file:t,data:n}){let r=e.metadataCache.getFileCache(t),i=new Map(Object.entries(r?.blocks??{})),a=(n?.split(` +`),_,t.path,u)}catch{}let y=createFragment();Array.from(_.children).forEach(e=>{y.createDiv({},t=>t.appendChild(e))}),f.appendChild(y),await l.MarkdownRenderer.postProcess(e,{docId:so(16),sourcePath:t.path,frontmatter:{},promises:v,addChild:function(e){return u.addChild(e)},getSectionInfo:function(){return null},containerEl:f,el:f,displayMode:!0}),await Promise.all(v),d.findAll(`a.internal-link`).forEach(e=>{let[n,r]=e.dataset.href?.split(`#`)??[];(!n||n?.length==0||n==t.basename)&&r?.startsWith(`^`)||e.removeAttribute(`href`)});try{await vo(o,f)}catch{console.warn(`wait timeout`)}yo(f);let b=document.implementation.createHTMLDocument(`document`);return b.body.appendChild(d.cloneNode(!0)),d.detach(),u.unload(),d.remove(),b.title=p,a.detach(),console.debug(`md render time:${new Date().getTime()-i}ms`),{doc:b,frontMatter:s,file:t}}async function uo({app:e,file:t,config:n,extra:r}){let i=new Date().getTime(),a=await e.vault.cachedRead(t);a||new l.Notice(`${t} content is empty!`);let o=new l.Component;o.load();let s=document.body.createDiv({cls:`print theme-light`,attr:{id:t.path}}),{viewEl:c,frontMatter:u}=fo({app:e,file:t,extra:r,config:n,printEl:s});return await mo({app:e,markdown:po({app:e,file:t,data:a}),file:t,comp:o,viewEl:c}),console.debug(`md render time:${new Date().getTime()-i}ms`),{doc:s,frontMatter:u,file:t,cleanup:()=>{s.detach(),o.unload(),s.remove()}}}function fo({app:e,file:t,printEl:n,extra:r,config:i}){let a=co(e,t),o=n.createDiv({cls:`markdown-preview-view markdown-rendered`}),s=Co(a);o.addClasses(s),o.toggleClass(`rtl`,e.vault.getConfig(`rightToLeft`)),o.toggleClass(`show-properties`,e.vault.getConfig(`propertiesInDocument`)!==`hidden`);let c=r?.title??a?.title??t.basename;return o.createEl(`h1`,{text:c},e=>{e.addClass(`__title__`),e.style.display=i?.showTitle?`block`:`none`,e.id=r?.id??``}),{viewEl:o,frontMatter:a}}function po({app:e,file:t,data:n}){let r=e.metadataCache.getFileCache(t),i=new Map(Object.entries(r?.blocks??{})),a=(n?.split(` `)??[]).map((e,t)=>{for(let{id:n,position:{start:r,end:a}}of i.values()){let o=`^${n}`;if(e.includes(o)&&t>=r.line&&t<=a.line)return i.delete(n),e.replace(o,` ${o}`)}return e});return[...i.values()].forEach(({id:e,position:{start:t,end:n}})=>{let r=t.line;a[r]=`\n\n`+a[r]}),a.join(` -`)}async function _o({app:e,markdown:t,file:n,comp:r,viewEl:i}){let a={children:void 0,appendChild(e){throw this.children=e?.children,Error(`exit`)}},o=[];try{await l.MarkdownRenderer.render(e,t,a,n.path,r)}catch{}let s=createFragment();Array.from(a.children).forEach(e=>{s.createDiv({},t=>t.appendChild(e))}),i.appendChild(s),await l.MarkdownRenderer.postProcess(e,{docId:uo(16),sourcePath:n.path,frontmatter:{},promises:o,addChild:function(e){return r.addChild(e)},getSectionInfo:function(){return null},containerEl:i,el:i,displayMode:!0}),await Promise.all(o),i.findAll(`a.internal-link`).forEach(e=>{let[t,r]=e.dataset.href?.split(`#`)??[];(!t||t?.length==0||t==n.basename)&&r?.startsWith(`^`)||e.removeAttribute(`href`)})}function vo(e,t){return Za(e,Ya(e),t),bo(e),e}function yo(e,t){return Za(e,Ya(e),t),e}function bo(e){Array.from(e.querySelectorAll(`span.markdown-embed`)).reverse().forEach(e=>e.innerHTML=encodeURIComponent(e.innerHTML))}async function xo(e,t){(e.includes("```dataview")||e.includes("```gEvent")||e.includes(`![[`))&&await sleep(2e3);try{await wo(t)}catch{await sleep(1e3)}}function So(e){for(let t of Array.from(e.querySelectorAll(`canvas`))){let e=t.toDataURL(),n=document.createElement(`img`);n.src=e,to(n,t.attributes),n.className=`__canvas__`,t.replaceWith(n)}}function Co(e){return` +`)}async function mo({app:e,markdown:t,file:n,comp:r,viewEl:i}){let a={children:void 0,appendChild(e){throw this.children=e?.children,Error(`exit`)}},o=[];try{await l.MarkdownRenderer.render(e,t,a,n.path,r)}catch{}let s=createFragment();Array.from(a.children).forEach(e=>{s.createDiv({},t=>t.appendChild(e))}),i.appendChild(s),await l.MarkdownRenderer.postProcess(e,{docId:so(16),sourcePath:n.path,frontmatter:{},promises:o,addChild:function(e){return r.addChild(e)},getSectionInfo:function(){return null},containerEl:i,el:i,displayMode:!0}),await Promise.all(o),i.findAll(`a.internal-link`).forEach(e=>{let[t,r]=e.dataset.href?.split(`#`)??[];(!t||t?.length==0||t==n.basename)&&r?.startsWith(`^`)||e.removeAttribute(`href`)})}function ho(e,t){return Ga(e,Ua(e),t),_o(e),e}function go(e,t){return Ga(e,Ua(e),t),e}function _o(e){Array.from(e.querySelectorAll(`span.markdown-embed`)).reverse().forEach(e=>e.innerHTML=encodeURIComponent(e.innerHTML))}async function vo(e,t){(e.includes("```dataview")||e.includes("```gEvent")||e.includes(`![[`))&&await sleep(2e3);try{await xo(t)}catch{await sleep(1e3)}}function yo(e){for(let t of Array.from(e.querySelectorAll(`canvas`))){let e=t.toDataURL(),n=document.createElement(`img`);n.src=e,Ya(n,t.attributes),n.className=`__canvas__`,t.replaceWith(n)}}function bo(e){return` document.body.innerHTML = decodeURIComponent(\`${encodeURIComponent(e.body.innerHTML)}\`); document.head.innerHTML = decodeURIComponent(\`${encodeURIComponent(document.head.innerHTML)}\`); - + // Function to recursively decode and replace innerHTML of span.markdown-embed elements function decodeAndReplaceEmbed(element) { // Replace the innerHTML with the decoded content @@ -56,7 +62,7 @@ img.__canvas__ { const newEmbeds = element.querySelectorAll("span.markdown-embed"); newEmbeds.forEach(decodeAndReplaceEmbed); } - + // Start the process with all span.markdown-embed elements in the document document.querySelectorAll("span.markdown-embed").forEach(decodeAndReplaceEmbed); @@ -65,21 +71,21 @@ img.__canvas__ { document.body.addClass("theme-light"); document.body.removeClass("theme-dark"); document.title = \`${e.title}\`; - `}function wo(e,t=2e3,n=200){return new Promise((r,i)=>{let a,o=new MutationObserver(e=>{clearTimeout(a),a=setTimeout(()=>{o.disconnect(),r(!0)},n)});o.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),setTimeout(()=>{o.disconnect(),i(Error(`timeout ${t}ms`))},t)})}async function To(e,t){let n=e.win.electron.ipcRenderer;return new Promise(e=>{n.once(`print-to-pdf`,(t,n)=>{e(n)}),n.send(`print-to-pdf`,t)})}function Eo(e){let t=[];for(let[n,r]of Object.entries(e))(n.toLowerCase()==`cssclass`||n.toLowerCase()==`cssclasses`)&&(Array.isArray(r)?t.push(...r):t.push(r));return t}if(typeof window<`u`){var Do,Oo;((Do=(Oo=window).__svelte??(Oo.__svelte={})).v??(Do.v=new Set)).add(`5`)}function ko(e){e.setAttribute(`style`,`width: 100px;`)}function Ao(e){e.setAttribute(`style`,`margin: 0 auto; width: -webkit-fill-available;`)}function jo(e,t){let n=t.settingEl;for(e.classList.add(...Array.from(n.classList));n.firstChild;)e.appendChild(n.firstChild);n.remove()}var Mo=(e,t)=>{let n=new l.Setting(e).setName(t.name);return t.desc&&n.setDesc(t.desc),n.addToggle(e=>{t.tooltip&&e.setTooltip(t.tooltip),e.setValue(t.value).onChange(t.onChange)}),jo(e,n),{destroy(){e.empty()}}},No=(e,t)=>{let n=new l.Setting(e).setName(t.name);return t.desc&&n.setDesc(t.desc),n.addDropdown(e=>{e.addOptions(t.options).setValue(t.value).onChange(t.onChange)}),jo(e,n),{destroy(){e.empty()}}},Po=(e,t)=>(jo(e,new l.Setting(e).setName(t.name).addSlider(e=>{e.setLimits(t.limits[0],t.limits[1],t.limits[2]).setValue(t.value).onChange(n=>{t.onChange(n),e.showTooltip()})})),{destroy(){e.empty()}}),Fo=(e,t)=>{let n=new l.Setting(e).setHeading().addButton(e=>{e.setButtonText(t.text).onClick(t.onClick),t.cta&&e.setCta(),Ao(e.buttonEl)});return t.hidden&&(e.hidden=!0),jo(e,n),{destroy(){e.empty()}}},Io=(e,t)=>(jo(e,new l.Setting(e).setName(t.name).addText(e=>{ko(e.inputEl),e.setPlaceholder(t.input1.placeholder).setValue(t.input1.value);let n=t.input1.isDebounce?(0,l.debounce)(t.input1.onChange,500,!0):t.input1.onChange;e.onChange(n)}).addText(e=>{ko(e.inputEl),e.setPlaceholder(t.input2.placeholder).setValue(t.input2.value);let n=t.input2.isDebounce?(0,l.debounce)(t.input2.onChange,500,!0):t.input2.onChange;e.onChange(n)})),{destroy(){e.empty()}}),Lo=(e,t)=>(t&&(0,l.setIcon)(e,t),{update(t){e.innerHTML=``,(0,l.setIcon)(e,t)}});function Ro(e,t){let n=t=>{e.innerHTML=``;let n=t.cloneNode(!0);n.style.display=`block`,e.appendChild(n)};return n(t),{update:n,destroy(){e.innerHTML=``}}}function zo(e,t){let n=t=>{e.innerHTML=``,t&&(t.style.width=`100%`,e.appendChild(t))};return n(t),{update:n}}var Bo=Wi(`
`),Vo=Wi(`
`,1),Ho=Wi(`
`);function Uo(e,t){$e(t,!0);let n=Ua(t,`config`,15),r=tn(()=>t.plugin.i18n),i=tn(()=>t.plugin.settings),a=tn(()=>n().pageSize===`Custom`),o=tn(()=>n().marginType===`3`),s=Object.fromEntries([`A0`,`A1`,`A2`,`A3`,`A4`,`A5`,`A6`,`Legal`,`Letter`,`Tabloid`,`Ledger`,`Custom`].map(e=>[e,e])),c={0:`None`,1:`Default`,2:`Small`,3:`Custom`},l=tn(()=>t.modal.cssSnippets()),u=tn(()=>Object.keys(H(l)).length>0&&H(i).enabledCss),d=tn(()=>({0:`Not select`,...H(l)}));function f(e){e.key===`Enter`&&t.handleExport()}var p=Ho(),m=xr(p);va(m,(e,t)=>Mo?.(e,t),()=>({name:H(r).exportDialog.filenameAsTitle,tooltip:`Include file name as title`,value:n().showTitle,onChange:e=>{n(n().showTitle=e,!0),t.pdfPreview?.toggleTitle(e)}}));var h=Cr(m,2);va(h,(e,t)=>No?.(e,t),()=>({name:H(r).exportDialog.pageSize,options:s,value:n().pageSize,onChange:async e=>{n(n().pageSize=e,!0),await t.pdfPreview?.handleChangeSize?.()}}));var g=Cr(h,2),_=e=>{var r=Bo();va(r,(e,t)=>Io?.(e,t),()=>({name:`Width/Height`,input1:{placeholder:`width`,value:n().pageWidth??``,isDebounce:!0,onChange:async e=>{n(n().pageWidth=e,!0),await t.pdfPreview?.handleChangeSize?.()}},input2:{placeholder:`height`,value:n().pageHeight??``,onChange:e=>{n(n().pageHeight=e,!0)}}})),Gi(e,r)};oa(g,e=>{H(a)&&e(_)});var v=Cr(g,2);va(v,(e,t)=>No?.(e,t),()=>({name:H(r).exportDialog.margin,desc:`The unit is millimeters.`,options:c,value:n().marginType,onChange:e=>{n(n().marginType=e,!0)}}));var y=Cr(v,2),b=e=>{var t=Vo(),r=Sr(t);va(r,(e,t)=>Io?.(e,t),()=>({name:`Top/Bottom`,input1:{placeholder:`margin top`,value:n().marginTop??``,onChange:e=>{n(n().marginTop=e,!0)}},input2:{placeholder:`margin bottom`,value:n().marginBottom??``,onChange:e=>{n(n().marginBottom=e,!0)}}})),va(Cr(r,2),(e,t)=>Io?.(e,t),()=>({name:`Left/Right`,input1:{placeholder:`margin left`,value:n().marginLeft??``,onChange:e=>{n(n().marginLeft=e,!0)}},input2:{placeholder:`margin right`,value:n().marginRight??``,onChange:e=>{n(n().marginRight=e,!0)}}})),Gi(e,t)};oa(y,e=>{H(o)&&e(b)});var x=Cr(y,2);va(x,(e,t)=>Po?.(e,t),()=>({name:H(r).exportDialog.downscalePercent,limits:[0,200,1],value:n().scale,onChange:e=>{n(n().scale=e,!0)}}));var S=Cr(x,2);va(S,(e,t)=>Mo?.(e,t),()=>({name:H(r).exportDialog.landscape,tooltip:`landscape`,value:n().landscape,onChange:e=>{n(n().landscape=e,!0)}}));var C=Cr(S,2);va(C,(e,t)=>Mo?.(e,t),()=>({name:H(r).exportDialog.displayHeader,tooltip:`Display header`,value:n().displayHeader,onChange:e=>{n(n().displayHeader=e,!0)}}));var w=Cr(C,2);va(w,(e,t)=>Mo?.(e,t),()=>({name:H(r).exportDialog.displayFooter,tooltip:`Display footer`,value:n().displayFooter,onChange:e=>{n(n().displayFooter=e,!0)}}));var T=Cr(w,2);va(T,(e,t)=>Mo?.(e,t),()=>({name:H(r).exportDialog.openAfterExport,tooltip:`Open the exported file after exporting.`,value:n().open,onChange:e=>{n(n().open=e,!0)}}));var E=Cr(T,2),D=e=>{var i=Bo();va(i,(e,t)=>No?.(e,t),()=>({name:H(r).exportDialog.cssSnippets,options:H(d),value:n().cssSnippet??`0`,onChange:async e=>{n(n().cssSnippet=e,!0),await t.pdfPreview?.renderPreview(!1)}})),Gi(e,i)};oa(E,e=>{H(u)&&H(i).version==`1`&&e(D)});var O=Cr(E,2);va(O,(e,t)=>Fo?.(e,t),()=>({text:`Export`,cta:!0,onClick:()=>t.handleExport()}));var k=Cr(O,2),ee=e=>{var n=Bo();va(n,(e,t)=>Fo?.(e,t),()=>({text:`Refresh`,onClick:()=>t.refreshPreview()})),Gi(e,n)};oa(k,e=>{H(i).version==`1`&&e(ee)}),va(Cr(k,2),(e,t)=>Fo?.(e,t),()=>({text:`Debug`,hidden:!H(i)?.debug,onClick:()=>t.pdfPreview?.handleOpenDevTools()})),ze(p),Ii(`keyup`,p,f),Gi(e,p),et()}Li([`keyup`]);var Wo=function(e,t){return Wo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},Wo(e,t)};function U(e,t){Wo(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var Go=function(){return Go=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1]))&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]>2],t+=Xo[(e[r]&3)<<4|e[r+1]>>4],t+=Xo[(e[r+1]&15)<<2|e[r+2]>>6],t+=Xo[e[r+2]&63];return n%3==2?t=t.substring(0,t.length-1)+`=`:n%3==1&&(t=t.substring(0,t.length-2)+`==`),t},es=function(e){var t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);var l=new Uint8Array(t);for(r=0;r>4,l[i++]=(o&15)<<4|s>>2,l[i++]=(s&3)<<6|c&63;return l},ts=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,ns=function(e){var t=e.trim(),n=t.substring(0,100).match(ts);if(!n)return es(t);var r=n[0];return es(t.substring(r.length))},rs=function(e){return e.charCodeAt(0)},is=function(e){return e.codePointAt(0)},as=function(e,t){return ls(e.toString(16),t,`0`).toUpperCase()},os=function(e){return as(e,2)},ss=function(e){return String.fromCharCode(e)},cs=function(e){return ss(parseInt(e,16))},ls=function(e,t,n){for(var r=``,i=0,a=t-e.length;i=55296&&n<=56319&&e.length>i&&(r=e.charCodeAt(i),r>=56320&&r<=57343&&(a=2)),[e.slice(t,t+a),a]},vs=function(e){for(var t=[],n=0,r=e.length;nn&&l(),o+=f,s+=p}}return l(),c},xs=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,Ss=function(e){var t=e.match(xs);if(t){var n=t[1],r=t[2],i=r===void 0?`01`:r,a=t[3],o=a===void 0?`01`:a,s=t[4],c=s===void 0?`00`:s,l=t[5],u=l===void 0?`00`:l,d=t[6],f=d===void 0?`00`:d,p=t[7],m=p===void 0?`Z`:p,h=t[8],g=h===void 0?`00`:h,_=t[9],v=_===void 0?`00`:_,y=m===`Z`?`Z`:``+m+g+`:`+v;return new Date(n+`-`+i+`-`+o+`T`+c+`:`+u+`:`+f+y)}},Cs=function(e,t){for(var n=0,r;n=0&&e<=65535},Bs=function(e){return e>=65536&&e<=1114111},Vs=function(e){return Math.floor((e-65536)/1024)+55296},Hs=function(e){return(e-65536)%1024+56320},Us;(function(e){e.BigEndian=`BigEndian`,e.LittleEndian=`LittleEndian`})(Us||(Us={}));for(var Ws=`�`.codePointAt(0),Gs=function(e,t){if(t===void 0&&(t=!0),e.length<=1)return String.fromCodePoint(Ws);for(var n=t?Ys(e):Us.BigEndian,r=t?2:0,i=[];e.length-r>=2;){var a=Js(e[r++],e[r++],n);if(Ks(a))if(e.length-r<2)i.push(Ws);else{var o=Js(e[r++],e[r++],n);qs(o)?i.push(a,o):i.push(Ws)}else qs(a)?(r+=2,i.push(Ws)):i.push(a)}return r=55296&&e<=56319},qs=function(e){return e>=56320&&e<=57343},Js=function(e,t,n){if(n===Us.LittleEndian)return t<<8|e;if(n===Us.BigEndian)return e<<8|t;throw Error(`Invalid byteOrder: `+n)},Ys=function(e){return Xs(e)?Us.BigEndian:Zs(e)?Us.LittleEndian:Us.BigEndian},Xs=function(e){return e[0]===254&&e[1]===255},Zs=function(e){return e[0]===255&&e[1]===254},Qs=function(e){return Xs(e)||Zs(e)},$s=function(e){var t=String(e);if(Math.abs(e)<1){var n=parseInt(e.toString().split(`e-`)[1]);if(n){var r=e<0;r&&(e*=-1),e*=10**(n-1),t=`0.`+Array(n).join(`0`)+e.toString().substring(2),r&&(t=`-`+t)}}else{var n=parseInt(e.toString().split(`+`)[1]);n>20&&(n-=20,e/=10**n,t=e.toString()+Array(n+1).join(`0`))}return t},ec=function(e){return Math.ceil(e.toString(2).length/8)},tc=function(e){for(var t=new Uint8Array(ec(e)),n=1;n<=t.length;n++)t[n-1]=e>>(t.length-n)*8;return t},nc=function(e){throw Error(e)},rc=o((e=>{var t=typeof Uint8Array<`u`&&typeof Uint16Array<`u`&&typeof Int32Array<`u`;function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!=`object`)throw TypeError(r+`must be non-object`);for(var i in r)n(r,i)&&(e[i]=r[i])}}return e},e.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var r={arraySet:function(e,t,n,r,i){if(t.subarray&&e.subarray){e.set(t.subarray(n,n+r),i);return}for(var a=0;a{var t=rc(),n=4,r=0,i=1,a=2;function o(e){for(var t=e.length;--t>=0;)e[t]=0}var s=0,c=1,l=2,u=3,d=258,f=29,p=256,m=p+1+f,h=30,g=19,_=2*m+1,v=15,y=16,b=7,x=256,S=16,C=17,w=18,T=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],E=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],D=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],O=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],k=512,ee=Array((m+2)*2);o(ee);var A=Array(h*2);o(A);var j=Array(k);o(j);var te=Array(d-u+1);o(te);var ne=Array(f);o(ne);var re=Array(h);o(re);function ie(e,t,n,r,i){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=e&&e.length}var ae,oe,se;function ce(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function le(e){return e<256?j[e]:j[256+(e>>>7)]}function ue(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function M(e,t,n){e.bi_valid>y-n?(e.bi_buf|=t<>y-e.bi_valid,e.bi_valid+=n-y):(e.bi_buf|=t<>>=1,n<<=1;while(--t>0);return n>>>1}function fe(e){e.bi_valid===16?(ue(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function pe(e,t){var n=t.dyn_tree,r=t.max_code,i=t.stat_desc.static_tree,a=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,c=t.stat_desc.max_length,l,u,d,f,p,m,h=0;for(f=0;f<=v;f++)e.bl_count[f]=0;for(n[e.heap[e.heap_max]*2+1]=0,l=e.heap_max+1;l<_;l++)u=e.heap[l],f=n[n[u*2+1]*2+1]+1,f>c&&(f=c,h++),n[u*2+1]=f,!(u>r)&&(e.bl_count[f]++,p=0,u>=s&&(p=o[u-s]),m=n[u*2],e.opt_len+=m*(f+p),a&&(e.static_len+=m*(i[u*2+1]+p)));if(h!==0){do{for(f=c-1;e.bl_count[f]===0;)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,h-=2}while(h>0);for(f=c;f!==0;f--)for(u=e.bl_count[f];u!==0;)d=e.heap[--l],!(d>r)&&(n[d*2+1]!==f&&(e.opt_len+=(f-n[d*2+1])*n[d*2],n[d*2+1]=f),u--)}}function me(e,t,n){var r=Array(v+1),i=0,a,o;for(a=1;a<=v;a++)r[a]=i=i+n[a-1]<<1;for(o=0;o<=t;o++){var s=e[o*2+1];s!==0&&(e[o*2]=de(r[s]++,s))}}function he(){var e,t,n,r,i,a=Array(v+1);for(n=0,r=0;r>=7;r8?ue(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function ve(e,n,r,i){_e(e),i&&(ue(e,r),ue(e,~r)),t.arraySet(e.pending_buf,e.window,n,r,e.pending),e.pending+=r}function P(e,t,n,r){var i=t*2,a=n*2;return e[i]>1;o>=1;o--)ye(e,n,o);l=a;do o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],ye(e,n,1),s=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=s,n[l*2]=n[o*2]+n[s*2],e.depth[l]=(e.depth[o]>=e.depth[s]?e.depth[o]:e.depth[s])+1,n[o*2+1]=n[s*2+1]=l,e.heap[1]=l++,ye(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],pe(e,t),me(n,c,e.bl_count)}function F(e,t,n){var r,i=-1,a,o=t[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)a=o,o=t[(r+1)*2+1],!(++s=3&&e.bl_tree[O[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function Ce(e,t,n,r){var i;for(M(e,t-257,5),M(e,n-1,5),M(e,r-4,4),i=0;i>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return r;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return i;for(n=32;n0?(e.strm.data_type===a&&(e.strm.data_type=L(e)),xe(e,e.l_desc),xe(e,e.d_desc),u=I(e),o=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=o&&(o=s)):o=s=r+5,r+4<=o&&t!==-1?Te(e,t,r,i):e.strategy===n||s===o?(M(e,(c<<1)+ +!!i,3),be(e,ee,A)):(M(e,(l<<1)+ +!!i,3),Ce(e,e.l_desc.max_code+1,e.d_desc.max_code+1,u+1),be(e,e.dyn_ltree,e.dyn_dtree)),ge(e),i&&_e(e)}function z(e,t,n){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=n&255,e.last_lit++,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(te[n]+p+1)*2]++,e.dyn_dtree[le(t)*2]++),e.last_lit===e.lit_bufsize-1}e._tr_init=we,e._tr_stored_block=Te,e._tr_flush_block=De,e._tr_tally=z,e._tr_align=Ee})),ac=o(((e,t)=>{function n(e,t,n,r){for(var i=e&65535|0,a=e>>>16&65535|0,o=0;n!==0;){o=n>2e3?2e3:n,n-=o;do i=i+t[r++]|0,a=a+i|0;while(--o);i%=65521,a%=65521}return i|a<<16|0}t.exports=n})),oc=o(((e,t)=>{function n(){for(var e,t=[],n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t}var r=n();function i(e,t,n,i){var a=r,o=i+n;e^=-1;for(var s=i;s>>8^a[(e^t[s])&255];return e^-1}t.exports=i})),sc=o(((e,t)=>{t.exports={2:`need dictionary`,1:`stream end`,0:``,"-1":`file error`,"-2":`stream error`,"-3":`data error`,"-4":`insufficient memory`,"-5":`buffer error`,"-6":`incompatible version`}})),cc=o((e=>{var t=rc(),n=ic(),r=ac(),i=oc(),a=sc(),o=0,s=1,c=3,l=4,u=5,d=0,f=1,p=-2,m=-3,h=-5,g=-1,_=1,v=2,y=3,b=4,x=0,S=2,C=8,w=9,T=15,E=8,D=286,O=30,k=19,ee=2*D+1,A=15,j=3,te=258,ne=te+j+1,re=32,ie=42,ae=69,oe=73,se=91,ce=103,le=113,ue=666,M=1,N=2,de=3,fe=4,pe=3;function me(e,t){return e.msg=a[t],t}function he(e){return(e<<1)-(e>4?9:0)}function ge(e){for(var t=e.length;--t>=0;)e[t]=0}function _e(e){var n=e.state,r=n.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(t.arraySet(e.output,n.pending_buf,n.pending_out,r,e.next_out),e.next_out+=r,n.pending_out+=r,e.total_out+=r,e.avail_out-=r,n.pending-=r,n.pending===0&&(n.pending_out=0))}function ve(e,t){n._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_e(e.strm)}function P(e,t){e.pending_buf[e.pending++]=t}function ye(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function be(e,n,a,o){var s=e.avail_in;return s>o&&(s=o),s===0?0:(e.avail_in-=s,t.arraySet(n,e.input,e.next_in,s,a),e.state.wrap===1?e.adler=r(e.adler,n,s,a):e.state.wrap===2&&(e.adler=i(e.adler,n,s,a)),e.next_in+=s,e.total_in+=s,s)}function xe(e,t){var n=e.max_chain_length,r=e.strstart,i,a,o=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-ne?e.strstart-(e.w_size-ne):0,l=e.window,u=e.w_mask,d=e.prev,f=e.strstart+te,p=l[r+o-1],m=l[r+o];e.prev_length>=e.good_match&&(n>>=2),s>e.lookahead&&(s=e.lookahead);do{if(i=t,l[i+o]!==m||l[i+o-1]!==p||l[i]!==l[r]||l[++i]!==l[r+1])continue;r+=2,i++;do;while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&ro){if(e.match_start=t,o=a,a>=s)break;p=l[r+o-1],m=l[r+o]}}while((t=d[t&u])>c&&--n!==0);return o<=e.lookahead?o:e.lookahead}function F(e){var n=e.w_size,r,i,a,o,s;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=n+(n-ne)){t.arraySet(e.window,e.window,n,n,0),e.match_start-=n,e.strstart-=n,e.block_start-=n,i=e.hash_size,r=i;do a=e.head[--r],e.head[r]=a>=n?a-n:0;while(--i);i=n,r=i;do a=e.prev[--r],e.prev[r]=a>=n?a-n:0;while(--i);o+=n}if(e.strm.avail_in===0)break;if(i=be(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=j)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(F(e),e.lookahead===0&&t===o)return M;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+n;if((e.strstart===0||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,ve(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-ne&&(ve(e,!1),e.strm.avail_out===0))return M}return e.insert=0,t===l?(ve(e,!0),e.strm.avail_out===0?de:fe):(e.strstart>e.block_start&&(ve(e,!1),e.strm.avail_out),M)}function I(e,t){for(var r,i;;){if(e.lookahead=j&&(e.ins_h=(e.ins_h<=j)if(i=n._tr_tally(e,e.strstart-e.match_start,e.match_length-j),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=j){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<=j&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=j-1)),e.prev_length>=j&&e.match_length<=e.prev_length){a=e.strstart+e.lookahead-j,i=n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-j),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=a&&(e.ins_h=(e.ins_h<=j&&e.strstart>0&&(a=e.strstart-1,i=c[a],i===c[++a]&&i===c[++a]&&i===c[++a])){s=e.strstart+te;do;while(i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&ae.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=j?(r=n._tr_tally(e,1,e.match_length-j),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(ve(e,!1),e.strm.avail_out===0))return M}return e.insert=0,t===l?(ve(e,!0),e.strm.avail_out===0?de:fe):e.last_lit&&(ve(e,!1),e.strm.avail_out===0)?M:N}function R(e,t){for(var r;;){if(e.lookahead===0&&(F(e),e.lookahead===0)){if(t===o)return M;break}if(e.match_length=0,r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(ve(e,!1),e.strm.avail_out===0))return M}return e.insert=0,t===l?(ve(e,!0),e.strm.avail_out===0?de:fe):e.last_lit&&(ve(e,!1),e.strm.avail_out===0)?M:N}function we(e,t,n,r,i){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=i}var Te=[new we(0,0,0,0,Se),new we(4,4,8,4,I),new we(4,5,16,8,I),new we(4,6,32,32,I),new we(4,4,16,16,Ce),new we(8,16,32,32,Ce),new we(8,16,128,128,Ce),new we(8,32,128,256,Ce),new we(32,128,258,1024,Ce),new we(32,258,258,4096,Ce)];function Ee(e){e.window_size=2*e.w_size,ge(e.head),e.max_lazy_match=Te[e.level].max_lazy,e.good_match=Te[e.level].good_length,e.nice_match=Te[e.level].nice_length,e.max_chain_length=Te[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=j-1,e.match_available=0,e.ins_h=0}function De(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=C,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new t.Buf16(ee*2),this.dyn_dtree=new t.Buf16((2*O+1)*2),this.bl_tree=new t.Buf16((2*k+1)*2),ge(this.dyn_ltree),ge(this.dyn_dtree),ge(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new t.Buf16(A+1),this.heap=new t.Buf16(2*D+1),ge(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new t.Buf16(2*D+1),ge(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function z(e){var t;return!e||!e.state?me(e,p):(e.total_in=e.total_out=0,e.data_type=S,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?ie:le,e.adler=t.wrap===2?0:1,t.last_flush=o,n._tr_init(t),d)}function Oe(e){var t=z(e);return t===d&&Ee(e.state),t}function ke(e,t){return!e||!e.state||e.state.wrap!==2?p:(e.state.gzhead=t,d)}function Ae(e,n,r,i,a,o){if(!e)return p;var s=1;if(n===g&&(n=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),a<1||a>w||r!==C||i<8||i>15||n<0||n>9||o<0||o>b)return me(e,p);i===8&&(i=9);var c=new De;return e.state=c,c.strm=e,c.wrap=s,c.gzhead=null,c.w_bits=i,c.w_size=1<u||t<0)return e?me(e,p):p;if(a=e.state,!e.output||!e.input&&e.avail_in!==0||a.status===ue&&t!==l)return me(e,e.avail_out===0?h:p);if(a.strm=e,r=a.last_flush,a.last_flush=t,a.status===ie)if(a.wrap===2)e.adler=0,P(a,31),P(a,139),P(a,8),a.gzhead?(P(a,+!!a.gzhead.text+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),P(a,a.gzhead.time&255),P(a,a.gzhead.time>>8&255),P(a,a.gzhead.time>>16&255),P(a,a.gzhead.time>>24&255),P(a,a.level===9?2:a.strategy>=v||a.level<2?4:0),P(a,a.gzhead.os&255),a.gzhead.extra&&a.gzhead.extra.length&&(P(a,a.gzhead.extra.length&255),P(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(e.adler=i(e.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=ae):(P(a,0),P(a,0),P(a,0),P(a,0),P(a,0),P(a,a.level===9?2:a.strategy>=v||a.level<2?4:0),P(a,pe),a.status=le);else{var _=C+(a.w_bits-8<<4)<<8,b=-1;b=a.strategy>=v||a.level<2?0:a.level<6?1:a.level===6?2:3,_|=b<<6,a.strstart!==0&&(_|=re),_+=31-_%31,a.status=le,ye(a,_),a.strstart!==0&&(ye(a,e.adler>>>16),ye(a,e.adler&65535)),e.adler=1}if(a.status===ae)if(a.gzhead.extra){for(m=a.pending;a.gzindex<(a.gzhead.extra.length&65535)&&!(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),_e(e),m=a.pending,a.pending===a.pending_buf_size));)P(a,a.gzhead.extra[a.gzindex]&255),a.gzindex++;a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),a.gzindex===a.gzhead.extra.length&&(a.gzindex=0,a.status=oe)}else a.status=oe;if(a.status===oe)if(a.gzhead.name){m=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),_e(e),m=a.pending,a.pending===a.pending_buf_size)){g=1;break}g=a.gzindexm&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),g===0&&(a.gzindex=0,a.status=se)}else a.status=se;if(a.status===se)if(a.gzhead.comment){m=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),_e(e),m=a.pending,a.pending===a.pending_buf_size)){g=1;break}g=a.gzindexm&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),g===0&&(a.status=ce)}else a.status=ce;if(a.status===ce&&(a.gzhead.hcrc?(a.pending+2>a.pending_buf_size&&_e(e),a.pending+2<=a.pending_buf_size&&(P(a,e.adler&255),P(a,e.adler>>8&255),e.adler=0,a.status=le)):a.status=le),a.pending!==0){if(_e(e),e.avail_out===0)return a.last_flush=-1,d}else if(e.avail_in===0&&he(t)<=he(r)&&t!==l)return me(e,h);if(a.status===ue&&e.avail_in!==0)return me(e,h);if(e.avail_in!==0||a.lookahead!==0||t!==o&&a.status!==ue){var x=a.strategy===v?R(a,t):a.strategy===y?L(a,t):Te[a.level].func(a,t);if((x===de||x===fe)&&(a.status=ue),x===M||x===de)return e.avail_out===0&&(a.last_flush=-1),d;if(x===N&&(t===s?n._tr_align(a):t!==u&&(n._tr_stored_block(a,0,0,!1),t===c&&(ge(a.head),a.lookahead===0&&(a.strstart=0,a.block_start=0,a.insert=0))),_e(e),e.avail_out===0))return a.last_flush=-1,d}return t===l?a.wrap<=0?f:(a.wrap===2?(P(a,e.adler&255),P(a,e.adler>>8&255),P(a,e.adler>>16&255),P(a,e.adler>>24&255),P(a,e.total_in&255),P(a,e.total_in>>8&255),P(a,e.total_in>>16&255),P(a,e.total_in>>24&255)):(ye(a,e.adler>>>16),ye(a,e.adler&65535)),_e(e),a.wrap>0&&(a.wrap=-a.wrap),a.pending===0?f:d):d}function Ne(e){var t;return!e||!e.state?p:(t=e.state.status,t!==ie&&t!==ae&&t!==oe&&t!==se&&t!==ce&&t!==le&&t!==ue?me(e,p):(e.state=null,t===le?me(e,m):d))}function Pe(e,n){var i=n.length,a,o,s,c,l,u,f,m;if(!e||!e.state||(a=e.state,c=a.wrap,c===2||c===1&&a.status!==ie||a.lookahead))return p;for(c===1&&(e.adler=r(e.adler,n,i,0)),a.wrap=0,i>=a.w_size&&(c===0&&(ge(a.head),a.strstart=0,a.block_start=0,a.insert=0),m=new t.Buf8(a.w_size),t.arraySet(m,n,i-a.w_size,a.w_size,0),n=m,i=a.w_size),l=e.avail_in,u=e.next_in,f=e.input,e.avail_in=i,e.next_in=0,e.input=n,F(a);a.lookahead>=j;){o=a.strstart,s=a.lookahead-(j-1);do a.ins_h=(a.ins_h<{var t=rc(),n=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch{n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{r=!1}for(var i=new t.Buf8(256),a=0;a<256;a++)i[a]=a>=252?6:a>=248?5:a>=240?4:a>=224?3:a>=192?2:1;i[254]=i[254]=1,e.string2buf=function(e){var n,r,i,a,o,s=e.length,c=0;for(a=0;a>>6,n[o++]=128|r&63):r<65536?(n[o++]=224|r>>>12,n[o++]=128|r>>>6&63,n[o++]=128|r&63):(n[o++]=240|r>>>18,n[o++]=128|r>>>12&63,n[o++]=128|r>>>6&63,n[o++]=128|r&63);return n};function o(e,i){if(i<65534&&(e.subarray&&r||!e.subarray&&n))return String.fromCharCode.apply(null,t.shrinkBuf(e,i));for(var a=``,o=0;o4){l[r++]=65533,n+=s-1;continue}for(a&=s===2?31:s===3?15:7;s>1&&n1){l[r++]=65533;continue}a<65536?l[r++]=a:(a-=65536,l[r++]=55296|a>>10&1023,l[r++]=56320|a&1023)}return o(l,r)},e.utf8border=function(e,t){var n;for(t=t||e.length,t>e.length&&(t=e.length),n=t-1;n>=0&&(e[n]&192)==128;)n--;return n<0||n===0?t:n+i[e[n]]>t?n:t}})),uc=o(((e,t)=>{function n(){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}t.exports=n})),dc=o((e=>{var t=cc(),n=rc(),r=lc(),i=sc(),a=uc(),o=Object.prototype.toString,s=0,c=4,l=0,u=1,d=2,f=-1,p=0,m=8;function h(e){if(!(this instanceof h))return new h(e);this.options=n.assign({level:f,method:m,chunkSize:16384,windowBits:15,memLevel:8,strategy:p,to:``},e||{});var s=this.options;s.raw&&s.windowBits>0?s.windowBits=-s.windowBits:s.gzip&&s.windowBits>0&&s.windowBits<16&&(s.windowBits+=16),this.err=0,this.msg=``,this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var c=t.deflateInit2(this.strm,s.level,s.method,s.windowBits,s.memLevel,s.strategy);if(c!==l)throw Error(i[c]);if(s.header&&t.deflateSetHeader(this.strm,s.header),s.dictionary){var u=typeof s.dictionary==`string`?r.string2buf(s.dictionary):o.call(s.dictionary)===`[object ArrayBuffer]`?new Uint8Array(s.dictionary):s.dictionary;if(c=t.deflateSetDictionary(this.strm,u),c!==l)throw Error(i[c]);this._dict_set=!0}}h.prototype.push=function(e,i){var a=this.strm,f=this.options.chunkSize,p,m;if(this.ended)return!1;m=i===~~i?i:i===!0?c:s,typeof e==`string`?a.input=r.string2buf(e):o.call(e)===`[object ArrayBuffer]`?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(a.avail_out===0&&(a.output=new n.Buf8(f),a.next_out=0,a.avail_out=f),p=t.deflate(a,m),p!==u&&p!==l)return this.onEnd(p),this.ended=!0,!1;(a.avail_out===0||a.avail_in===0&&(m===c||m===d))&&(this.options.to===`string`?this.onData(r.buf2binstring(n.shrinkBuf(a.output,a.next_out))):this.onData(n.shrinkBuf(a.output,a.next_out)))}while((a.avail_in>0||a.avail_out===0)&&p!==u);return m===c?(p=t.deflateEnd(this.strm),this.onEnd(p),this.ended=!0,p===l):m===d?(this.onEnd(l),a.avail_out=0,!0):!0},h.prototype.onData=function(e){this.chunks.push(e)},h.prototype.onEnd=function(e){e===l&&(this.options.to===`string`?this.result=this.chunks.join(``):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function g(e,t){var n=new h(t);if(n.push(e,!0),n.err)throw n.msg||i[n.err];return n.result}function _(e,t){return t=t||{},t.raw=!0,g(e,t)}function v(e,t){return t=t||{},t.gzip=!0,g(e,t)}e.Deflate=h,e.deflate=g,e.deflateRaw=_,e.gzip=v})),fc=o(((e,t)=>{var n=30,r=12;t.exports=function(e,t){var i=e.state,a=e.next_in,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D=e.input,O;o=a+(e.avail_in-5),s=e.next_out,O=e.output,c=s-(t-e.avail_out),l=s+(e.avail_out-257),u=i.dmax,d=i.wsize,f=i.whave,p=i.wnext,m=i.window,h=i.hold,g=i.bits,_=i.lencode,v=i.distcode,y=(1<>>24,h>>>=S,g-=S,S=x>>>16&255,S===0)O[s++]=x&65535;else if(S&16){C=x&65535,S&=15,S&&(g>>=S,g-=S),g<15&&(h+=D[a++]<>>24,h>>>=S,g-=S,S=x>>>16&255,S&16){if(w=x&65535,S&=15,gu){e.msg=`invalid distance too far back`,i.mode=n;break top}if(h>>>=S,g-=S,S=s-c,w>S){if(S=w-S,S>f&&i.sane){e.msg=`invalid distance too far back`,i.mode=n;break top}if(T=0,E=m,p===0){if(T+=d-S,S2;)O[s++]=E[T++],O[s++]=E[T++],O[s++]=E[T++],C-=3;C&&(O[s++]=E[T++],C>1&&(O[s++]=E[T++]))}else{T=s-w;do O[s++]=O[T++],O[s++]=O[T++],O[s++]=O[T++],C-=3;while(C>2);C&&(O[s++]=O[T++],C>1&&(O[s++]=O[T++]))}}else if(S&64){e.msg=`invalid distance code`,i.mode=n;break top}else{x=v[(x&65535)+(h&(1<>3,a-=C,g-=C<<3,h&=(1<{var n=rc(),r=15,i=852,a=592,o=0,s=1,c=2,l=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],u=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],d=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],f=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,p,m,h,g,_,v){var y=v.bits,b=0,x=0,S=0,C=0,w=0,T=0,E=0,D=0,O=0,k=0,ee,A,j,te,ne,re=null,ie=0,ae,oe=new n.Buf16(r+1),se=new n.Buf16(r+1),ce=null,le=0,ue,M,N;for(b=0;b<=r;b++)oe[b]=0;for(x=0;x=1&&oe[C]===0;C--);if(w>C&&(w=C),C===0)return h[g++]=20971520,h[g++]=20971520,v.bits=1,0;for(S=1;S0&&(e===o||C!==1))return-1;for(se[1]=0,b=1;bi||e===c&&O>a)return 1;for(;;){ue=b-E,_[x]ae?(M=ce[le+_[x]],N=re[ie+_[x]]):(M=96,N=0),ee=1<>E)+A]=ue<<24|M<<16|N|0;while(A!==0);for(ee=1<>=1;if(ee===0?k=0:(k&=ee-1,k+=ee),x++,--oe[b]===0){if(b===C)break;b=t[p+_[x]]}if(b>w&&(k&te)!==j){for(E===0&&(E=w),ne+=S,T=b-E,D=1<i||e===c&&O>a)return 1;j=k&te,h[j]=w<<24|T<<16|ne-g|0}}return k!==0&&(h[ne+k]=b-E<<24|4194304),v.bits=w,0}})),mc=o((e=>{var t=rc(),n=ac(),r=oc(),i=fc(),a=pc(),o=0,s=1,c=2,l=4,u=5,d=6,f=0,p=1,m=2,h=-2,g=-3,_=-4,v=-5,y=8,b=1,x=2,S=3,C=4,w=5,T=6,E=7,D=8,O=9,k=10,ee=11,A=12,j=13,te=14,ne=15,re=16,ie=17,ae=18,oe=19,se=20,ce=21,le=22,ue=23,M=24,N=25,de=26,fe=27,pe=28,me=29,he=30,ge=31,_e=32,ve=852,P=592,ye=15;function be(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function xe(){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 t.Buf16(320),this.work=new t.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function F(e){var n;return!e||!e.state?h:(n=e.state,e.total_in=e.total_out=n.total=0,e.msg=``,n.wrap&&(e.adler=n.wrap&1),n.mode=b,n.last=0,n.havedict=0,n.dmax=32768,n.head=null,n.hold=0,n.bits=0,n.lencode=n.lendyn=new t.Buf32(ve),n.distcode=n.distdyn=new t.Buf32(P),n.sane=1,n.back=-1,f)}function Se(e){var t;return!e||!e.state?h:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,F(e))}function I(e,t){var n,r;return!e||!e.state||(r=e.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?h:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Se(e))}function Ce(e,t){var n,r;return e?(r=new xe,e.state=r,r.window=null,n=I(e,t),n!==f&&(e.state=null),n):h}function L(e){return Ce(e,ye)}var R=!0,we,Te;function Ee(e){if(R){var n;for(we=new t.Buf32(512),Te=new t.Buf32(32),n=0;n<144;)e.lens[n++]=8;for(;n<256;)e.lens[n++]=9;for(;n<280;)e.lens[n++]=7;for(;n<288;)e.lens[n++]=8;for(a(s,e.lens,0,288,we,0,e.work,{bits:9}),n=0;n<32;)e.lens[n++]=5;a(c,e.lens,0,32,Te,0,e.work,{bits:5}),R=!1}e.lencode=we,e.lenbits=9,e.distcode=Te,e.distbits=5}function De(e,n,r,i){var a,o=e.state;return o.window===null&&(o.wsize=1<=o.wsize?(t.arraySet(o.window,n,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(a=o.wsize-o.wnext,a>i&&(a=i),t.arraySet(o.window,n,r-i,a,o.wnext),i-=a,i?(t.arraySet(o.window,n,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,P.check=r(P.check,ze,2,0),L=0,R=0,P.mode=x;break}if(P.flags=0,P.head&&(P.head.done=!1),!(P.wrap&1)||(((L&255)<<8)+(L>>8))%31){e.msg=`incorrect header check`,P.mode=he;break}if((L&15)!==y){e.msg=`unknown compression method`,P.mode=he;break}if(L>>>=4,R-=4,Le=(L&15)+8,P.wbits===0)P.wbits=Le;else if(Le>P.wbits){e.msg=`invalid window size`,P.mode=he;break}P.dmax=1<>8&1),P.flags&512&&(ze[0]=L&255,ze[1]=L>>>8&255,P.check=r(P.check,ze,2,0)),L=0,R=0,P.mode=S;case S:for(;R<32;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>8&255,ze[2]=L>>>16&255,ze[3]=L>>>24&255,P.check=r(P.check,ze,4,0)),L=0,R=0,P.mode=C;case C:for(;R<16;){if(I===0)break inf_leave;I--,L+=ye[F++]<>8),P.flags&512&&(ze[0]=L&255,ze[1]=L>>>8&255,P.check=r(P.check,ze,2,0)),L=0,R=0,P.mode=w;case w:if(P.flags&1024){for(;R<16;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>8&255,P.check=r(P.check,ze,2,0)),L=0,R=0}else P.head&&(P.head.extra=null);P.mode=T;case T:if(P.flags&1024&&(z=P.length,z>I&&(z=I),z&&(P.head&&(Le=P.head.extra_len-P.length,P.head.extra||(P.head.extra=Array(P.head.extra_len)),t.arraySet(P.head.extra,ye,F,z,Le)),P.flags&512&&(P.check=r(P.check,ye,z,F)),I-=z,F+=z,P.length-=z),P.length))break inf_leave;P.length=0,P.mode=E;case E:if(P.flags&2048){if(I===0)break inf_leave;z=0;do Le=ye[F+ z++],P.head&&Le&&P.length<65536&&(P.head.name+=String.fromCharCode(Le));while(Le&&z>9&1,P.head.done=!0),e.adler=P.check=0,P.mode=A;break;case k:for(;R<32;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=R&7,R-=R&7,P.mode=fe;break}for(;R<3;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=1,--R,L&3){case 0:P.mode=te;break;case 1:if(Ee(P),P.mode=se,ve===d){L>>>=2,R-=2;break inf_leave}break;case 2:P.mode=ie;break;case 3:e.msg=`invalid block type`,P.mode=he}L>>>=2,R-=2;break;case te:for(L>>>=R&7,R-=R&7;R<32;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>16^65535)){e.msg=`invalid stored block lengths`,P.mode=he;break}if(P.length=L&65535,L=0,R=0,P.mode=ne,ve===d)break inf_leave;case ne:P.mode=re;case re:if(z=P.length,z){if(z>I&&(z=I),z>Ce&&(z=Ce),z===0)break inf_leave;t.arraySet(xe,ye,F,z,Se),I-=z,F+=z,Ce-=z,Se+=z,P.length-=z;break}P.mode=A;break;case ie:for(;R<14;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=5,R-=5,P.ndist=(L&31)+1,L>>>=5,R-=5,P.ncode=(L&15)+4,L>>>=4,R-=4,P.nlen>286||P.ndist>30){e.msg=`too many length or distance symbols`,P.mode=he;break}P.have=0,P.mode=ae;case ae:for(;P.have>>=3,R-=3}for(;P.have<19;)P.lens[He[P.have++]]=0;if(P.lencode=P.lendyn,P.lenbits=7,Be={bits:P.lenbits},Re=a(o,P.lens,0,19,P.lencode,0,P.work,Be),P.lenbits=Be.bits,Re){e.msg=`invalid code lengths set`,P.mode=he;break}P.have=0,P.mode=oe;case oe:for(;P.have>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=je,R-=je,P.lens[P.have++]=Ne;else{if(Ne===16){for(Ve=je+2;R>>=je,R-=je,P.have===0){e.msg=`invalid bit length repeat`,P.mode=he;break}Le=P.lens[P.have-1],z=3+(L&3),L>>>=2,R-=2}else if(Ne===17){for(Ve=je+3;R>>=je,R-=je,Le=0,z=3+(L&7),L>>>=3,R-=3}else{for(Ve=je+7;R>>=je,R-=je,Le=0,z=11+(L&127),L>>>=7,R-=7}if(P.have+z>P.nlen+P.ndist){e.msg=`invalid bit length repeat`,P.mode=he;break}for(;z--;)P.lens[P.have++]=Le}}if(P.mode===he)break;if(P.lens[256]===0){e.msg=`invalid code -- missing end-of-block`,P.mode=he;break}if(P.lenbits=9,Be={bits:P.lenbits},Re=a(s,P.lens,0,P.nlen,P.lencode,0,P.work,Be),P.lenbits=Be.bits,Re){e.msg=`invalid literal/lengths set`,P.mode=he;break}if(P.distbits=6,P.distcode=P.distdyn,Be={bits:P.distbits},Re=a(c,P.lens,P.nlen,P.ndist,P.distcode,0,P.work,Be),P.distbits=Be.bits,Re){e.msg=`invalid distances set`,P.mode=he;break}if(P.mode=se,ve===d)break inf_leave;case se:P.mode=ce;case ce:if(I>=6&&Ce>=258){e.next_out=Se,e.avail_out=Ce,e.next_in=F,e.avail_in=I,P.hold=L,P.bits=R,i(e,Te),Se=e.next_out,xe=e.output,Ce=e.avail_out,F=e.next_in,ye=e.input,I=e.avail_in,L=P.hold,R=P.bits,P.mode===A&&(P.back=-1);break}for(P.back=0;Ae=P.lencode[L&(1<>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>Pe)],je=Ae>>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(Pe+je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=Pe,R-=Pe,P.back+=Pe}if(L>>>=je,R-=je,P.back+=je,P.length=Ne,Me===0){P.mode=de;break}if(Me&32){P.back=-1,P.mode=A;break}if(Me&64){e.msg=`invalid literal/length code`,P.mode=he;break}P.extra=Me&15,P.mode=le;case le:if(P.extra){for(Ve=P.extra;R>>=P.extra,R-=P.extra,P.back+=P.extra}P.was=P.length,P.mode=ue;case ue:for(;Ae=P.distcode[L&(1<>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>Pe)],je=Ae>>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(Pe+je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=Pe,R-=Pe,P.back+=Pe}if(L>>>=je,R-=je,P.back+=je,Me&64){e.msg=`invalid distance code`,P.mode=he;break}P.offset=Ne,P.extra=Me&15,P.mode=M;case M:if(P.extra){for(Ve=P.extra;R>>=P.extra,R-=P.extra,P.back+=P.extra}if(P.offset>P.dmax){e.msg=`invalid distance too far back`,P.mode=he;break}P.mode=N;case N:if(Ce===0)break inf_leave;if(z=Te-Ce,P.offset>z){if(z=P.offset-z,z>P.whave&&P.sane){e.msg=`invalid distance too far back`,P.mode=he;break}z>P.wnext?(z-=P.wnext,Oe=P.wsize-z):Oe=P.wnext-z,z>P.length&&(z=P.length),ke=P.window}else ke=xe,Oe=Se-P.offset,z=P.length;z>Ce&&(z=Ce),Ce-=z,P.length-=z;do xe[Se++]=ke[Oe++];while(--z);P.length===0&&(P.mode=ce);break;case de:if(Ce===0)break inf_leave;xe[Se++]=P.length,Ce--,P.mode=ce;break;case fe:if(P.wrap){for(;R<32;){if(I===0)break inf_leave;I--,L|=ye[F++]<{t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}})),gc=o(((e,t)=>{function n(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=``,this.comment=``,this.hcrc=0,this.done=!1}t.exports=n})),_c=o((e=>{var t=mc(),n=rc(),r=lc(),i=hc(),a=sc(),o=uc(),s=gc(),c=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=n.assign({chunkSize:16384,windowBits:0,to:``},e||{});var u=this.options;u.raw&&u.windowBits>=0&&u.windowBits<16&&(u.windowBits=-u.windowBits,u.windowBits===0&&(u.windowBits=-15)),u.windowBits>=0&&u.windowBits<16&&!(e&&e.windowBits)&&(u.windowBits+=32),u.windowBits>15&&u.windowBits<48&&(u.windowBits&15||(u.windowBits|=15)),this.err=0,this.msg=``,this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var d=t.inflateInit2(this.strm,u.windowBits);if(d!==i.Z_OK||(this.header=new s,t.inflateGetHeader(this.strm,this.header),u.dictionary&&(typeof u.dictionary==`string`?u.dictionary=r.string2buf(u.dictionary):c.call(u.dictionary)===`[object ArrayBuffer]`&&(u.dictionary=new Uint8Array(u.dictionary)),u.raw&&(d=t.inflateSetDictionary(this.strm,u.dictionary),d!==i.Z_OK))))throw Error(a[d])}l.prototype.push=function(e,a){var o=this.strm,s=this.options.chunkSize,l=this.options.dictionary,u,d,f,p,m,h=!1;if(this.ended)return!1;d=a===~~a?a:a===!0?i.Z_FINISH:i.Z_NO_FLUSH,typeof e==`string`?o.input=r.binstring2buf(e):c.call(e)===`[object ArrayBuffer]`?o.input=new Uint8Array(e):o.input=e,o.next_in=0,o.avail_in=o.input.length;do{if(o.avail_out===0&&(o.output=new n.Buf8(s),o.next_out=0,o.avail_out=s),u=t.inflate(o,i.Z_NO_FLUSH),u===i.Z_NEED_DICT&&l&&(u=t.inflateSetDictionary(this.strm,l)),u===i.Z_BUF_ERROR&&h===!0&&(u=i.Z_OK,h=!1),u!==i.Z_STREAM_END&&u!==i.Z_OK)return this.onEnd(u),this.ended=!0,!1;o.next_out&&(o.avail_out===0||u===i.Z_STREAM_END||o.avail_in===0&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&(this.options.to===`string`?(f=r.utf8border(o.output,o.next_out),p=o.next_out-f,m=r.buf2string(o.output,f),o.next_out=p,o.avail_out=s-p,p&&n.arraySet(o.output,o.output,f,p,0),this.onData(m)):this.onData(n.shrinkBuf(o.output,o.next_out))),o.avail_in===0&&o.avail_out===0&&(h=!0)}while((o.avail_in>0||o.avail_out===0)&&u!==i.Z_STREAM_END);return u===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(u=t.inflateEnd(this.strm),this.onEnd(u),this.ended=!0,u===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),o.avail_out=0,!0):!0},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){e===i.Z_OK&&(this.options.to===`string`?this.result=this.chunks.join(``):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function u(e,t){var n=new l(t);if(n.push(e,!0),n.err)throw n.msg||a[n.err];return n.result}function d(e,t){return t=t||{},t.raw=!0,u(e,t)}e.Inflate=l,e.inflate=u,e.inflateRaw=d,e.ungzip=u})),vc=c(o(((e,t)=>{var n=rc().assign,r=dc(),i=_c(),a=hc(),o={};n(o,r,i,a),t.exports=o}))()),yc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,bc=new Uint8Array(256),xc=0;xc>4,l[i++]=(o&15)<<4|s>>2,l[i++]=(s&3)<<6|c&63;return l},Cc=function(e){for(var t=``,n=0;nr)throw Error(Rc(t)+` must be at least `+n+` and at most `+r+`, but was actually `+e)},Xc=function(e,t,n,r){W(e,t,[`number`,`undefined`]),typeof e==`number`&&Yc(e,t,n,r)},Zc=function(e,t,n){if(W(e,t,[`number`]),e%n!==0)throw Error(Rc(t)+` must be a multiple of `+n+`, but was actually `+e)},Qc=function(e,t){if(!Number.isInteger(e))throw Error(Rc(t)+` must be an integer, but was actually `+e)},$c=function(e,t){if(![1,0].includes(Math.sign(e)))throw Error(Rc(t)+` must be a positive number or 0, but was actually `+e)},el=new Uint16Array(256),tl=0;tl<256;tl++)el[tl]=tl;el[22]=rs(``),el[24]=rs(`˘`),el[25]=rs(`ˇ`),el[26]=rs(`ˆ`),el[27]=rs(`˙`),el[28]=rs(`˝`),el[29]=rs(`˛`),el[30]=rs(`˚`),el[31]=rs(`˜`),el[127]=rs(`�`),el[128]=rs(`•`),el[129]=rs(`†`),el[130]=rs(`‡`),el[131]=rs(`…`),el[132]=rs(`—`),el[133]=rs(`–`),el[134]=rs(`ƒ`),el[135]=rs(`⁄`),el[136]=rs(`‹`),el[137]=rs(`›`),el[138]=rs(`−`),el[139]=rs(`‰`),el[140]=rs(`„`),el[141]=rs(`“`),el[142]=rs(`”`),el[143]=rs(`‘`),el[144]=rs(`’`),el[145]=rs(`‚`),el[146]=rs(`™`),el[147]=rs(`fi`),el[148]=rs(`fl`),el[149]=rs(`Ł`),el[150]=rs(`Œ`),el[151]=rs(`Š`),el[152]=rs(`Ÿ`),el[153]=rs(`Ž`),el[154]=rs(`ı`),el[155]=rs(`ł`),el[156]=rs(`œ`),el[157]=rs(`š`),el[158]=rs(`ž`),el[159]=rs(`�`),el[160]=rs(`€`),el[173]=rs(`�`);var nl=function(e){for(var t=Array(e.length),n=0,r=e.length;n=K.ExclamationPoint&&e<=K.Tilde&&!zl[e]},Wl={},Gl=new Map,J=function(e){U(t,e);function t(t,n){var r=this;if(t!==Wl)throw new al(`PDFName`);r=e.call(this)||this;for(var i=`/`,a=0,o=n.length;a=K.Zero&&s<=K.Nine||s>=K.a&&s<=K.f||s>=K.A&&s<=K.F?(t+=o,(t.length===2||!(c>=`0`&&c<=`9`||c>=`a`&&c<=`f`||c>=`A`&&c<=`F`))&&(r(parseInt(t,16)),t=``)):r(s):s===K.Hash?n=!0:r(s)}return new Uint8Array(e)},t.prototype.decodeText=function(){var e=this.asBytes();return String.fromCharCode.apply(String,Array.from(e))},t.prototype.asString=function(){return this.encodedName},t.prototype.value=function(){return this.encodedName},t.prototype.clone=function(){return this},t.prototype.toString=function(){return this.encodedName},t.prototype.sizeInBytes=function(){return this.encodedName.length},t.prototype.copyBytesInto=function(e,t){return t+=us(this.encodedName,e,t),this.encodedName.length},t.of=function(e){var n=Hl(e),r=Gl.get(n);return r||(r=new t(Wl,n),Gl.set(n,r)),r},t.Length=t.of(`Length`),t.FlateDecode=t.of(`FlateDecode`),t.Resources=t.of(`Resources`),t.Font=t.of(`Font`),t.XObject=t.of(`XObject`),t.ExtGState=t.of(`ExtGState`),t.Contents=t.of(`Contents`),t.Type=t.of(`Type`),t.Parent=t.of(`Parent`),t.MediaBox=t.of(`MediaBox`),t.Page=t.of(`Page`),t.Annots=t.of(`Annots`),t.TrimBox=t.of(`TrimBox`),t.ArtBox=t.of(`ArtBox`),t.BleedBox=t.of(`BleedBox`),t.CropBox=t.of(`CropBox`),t.Rotate=t.of(`Rotate`),t.Title=t.of(`Title`),t.Author=t.of(`Author`),t.Subject=t.of(`Subject`),t.Creator=t.of(`Creator`),t.Keywords=t.of(`Keywords`),t.Producer=t.of(`Producer`),t.CreationDate=t.of(`CreationDate`),t.ModDate=t.of(`ModDate`),t}(Nl),Kl=new(function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.asNull=function(){return null},t.prototype.clone=function(){return this},t.prototype.toString=function(){return`null`},t.prototype.sizeInBytes=function(){return 4},t.prototype.copyBytesInto=function(e,t){return e[t++]=K.n,e[t++]=K.u,e[t++]=K.l,e[t++]=K.l,4},t}(Nl)),ql=function(e){U(t,e);function t(t,n){var r=e.call(this)||this;return r.dict=t,r.context=n,r}return t.prototype.keys=function(){return Array.from(this.dict.keys())},t.prototype.values=function(){return Array.from(this.dict.values())},t.prototype.entries=function(){return Array.from(this.dict.entries())},t.prototype.set=function(e,t){this.dict.set(e,t)},t.prototype.get=function(e,t){t===void 0&&(t=!1);var n=this.dict.get(e);if(!(n===Kl&&!t))return n},t.prototype.has=function(e){var t=this.dict.get(e);return t!==void 0&&t!==Kl},t.prototype.lookupMaybe=function(e){for(var t,n=[],r=1;r{let a,o=new MutationObserver(e=>{clearTimeout(a),a=setTimeout(()=>{o.disconnect(),r(!0)},n)});o.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),setTimeout(()=>{o.disconnect(),i(Error(`timeout ${t}ms`))},t)})}async function So(e,t){let n=e.win.electron.ipcRenderer;return new Promise(e=>{n.once(`print-to-pdf`,(t,n)=>{e(n)}),n.send(`print-to-pdf`,t)})}function Co(e){let t=[];for(let[n,r]of Object.entries(e))(n.toLowerCase()==`cssclass`||n.toLowerCase()==`cssclasses`)&&(Array.isArray(r)?t.push(...r):t.push(r));return t}if(typeof window<`u`){var wo,To;((wo=(To=window).__svelte??(To.__svelte={})).v??(wo.v=new Set)).add(`5`)}function Eo(e){e.setAttribute(`style`,`width: 100px;`)}function Do(e){e.setAttribute(`style`,`margin: 0 auto; width: -webkit-fill-available;`)}function Oo(e,t){let n=t.settingEl;for(e.classList.add(...Array.from(n.classList));n.firstChild;)e.appendChild(n.firstChild);n.remove()}var ko=(e,t)=>{let n=new l.Setting(e).setName(t.name);return t.desc&&n.setDesc(t.desc),n.addToggle(e=>{t.tooltip&&e.setTooltip(t.tooltip),e.setValue(t.value).onChange(t.onChange)}),Oo(e,n),{destroy(){e.empty()}}},Ao=(e,t)=>{let n=new l.Setting(e).setName(t.name);return t.desc&&n.setDesc(t.desc),n.addDropdown(e=>{e.addOptions(t.options).setValue(t.value).onChange(t.onChange)}),Oo(e,n),{destroy(){e.empty()}}},jo=(e,t)=>(Oo(e,new l.Setting(e).setName(t.name).addSlider(e=>{e.setLimits(t.limits[0],t.limits[1],t.limits[2]).setValue(t.value).onChange(n=>{t.onChange(n),e.showTooltip()})})),{destroy(){e.empty()}}),Mo=(e,t)=>{let n=new l.Setting(e).setHeading().addButton(e=>{e.setButtonText(t.text).onClick(t.onClick),t.cta&&e.setCta(),Do(e.buttonEl)});return t.hidden&&(e.hidden=!0),Oo(e,n),{destroy(){e.empty()}}},No=(e,t)=>(Oo(e,new l.Setting(e).setName(t.name).addText(e=>{Eo(e.inputEl),e.setPlaceholder(t.input1.placeholder).setValue(t.input1.value);let n=t.input1.isDebounce?(0,l.debounce)(t.input1.onChange,500,!0):t.input1.onChange;e.onChange(n)}).addText(e=>{Eo(e.inputEl),e.setPlaceholder(t.input2.placeholder).setValue(t.input2.value);let n=t.input2.isDebounce?(0,l.debounce)(t.input2.onChange,500,!0):t.input2.onChange;e.onChange(n)})),{destroy(){e.empty()}}),Po=(e,t)=>(t&&(0,l.setIcon)(e,t),{update(t){e.innerHTML=``,(0,l.setIcon)(e,t)}});function Fo(e,t){let n=t=>{e.innerHTML=``;let n=t.cloneNode(!0);n.removeClass(`theme-light`),n.style.display=`block`,e.appendChild(n)};return n(t),{update:n,destroy(){e.innerHTML=``}}}function Io(e,t){let n=t=>{e.innerHTML=``,t&&(t.style.width=`100%`,e.appendChild(t))};return n(t),{update:n}}var Lo=zi(`
`),Ro=zi(`
`,1),zo=zi(`
`);function Bo(e,t){Ze(t,!0);let n=Ra(t,`config`,15),r=Qt(()=>t.plugin.i18n),i=Qt(()=>t.plugin.settings),a=Qt(()=>n().pageSize===`Custom`),o=Qt(()=>n().marginType===`3`),s=Object.fromEntries([`A0`,`A1`,`A2`,`A3`,`A4`,`A5`,`A6`,`Legal`,`Letter`,`Tabloid`,`Ledger`,`Custom`].map(e=>[e,e])),c={0:`None`,1:`Default`,2:`Small`,3:`Custom`},l=Qt(()=>t.modal.cssSnippets()),u=Qt(()=>Object.keys(H(l)).length>0&&H(i).enabledCss),d=Qt(()=>({0:`Not select`,...H(l)}));function f(e){e.key===`Enter`&&t.handleExport()}var p=zo(),m=gr(p);pa(m,(e,t)=>ko?.(e,t),()=>({name:H(r).exportDialog.filenameAsTitle,tooltip:`Include file name as title`,value:n().showTitle,onChange:e=>{n(n().showTitle=e,!0),t.pdfPreview?.toggleTitle(e)}}));var h=vr(m,2);pa(h,(e,t)=>Ao?.(e,t),()=>({name:H(r).exportDialog.pageSize,options:s,value:n().pageSize,onChange:async e=>{n(n().pageSize=e,!0),await t.pdfPreview?.handleChangeSize?.()}}));var g=vr(h,2),_=e=>{var r=Lo();pa(r,(e,t)=>No?.(e,t),()=>({name:`Width/Height`,input1:{placeholder:`width`,value:n().pageWidth??``,isDebounce:!0,onChange:async e=>{n(n().pageWidth=e,!0),await t.pdfPreview?.handleChangeSize?.()}},input2:{placeholder:`height`,value:n().pageHeight??``,onChange:e=>{n(n().pageHeight=e,!0)}}})),Bi(e,r)};ta(g,e=>{H(a)&&e(_)});var v=vr(g,2);pa(v,(e,t)=>Ao?.(e,t),()=>({name:H(r).exportDialog.margin,desc:`The unit is millimeters.`,options:c,value:n().marginType,onChange:e=>{n(n().marginType=e,!0)}}));var y=vr(v,2),b=e=>{var t=Ro(),r=_r(t);pa(r,(e,t)=>No?.(e,t),()=>({name:`Top/Bottom`,input1:{placeholder:`margin top`,value:n().marginTop??``,onChange:e=>{n(n().marginTop=e,!0)}},input2:{placeholder:`margin bottom`,value:n().marginBottom??``,onChange:e=>{n(n().marginBottom=e,!0)}}})),pa(vr(r,2),(e,t)=>No?.(e,t),()=>({name:`Left/Right`,input1:{placeholder:`margin left`,value:n().marginLeft??``,onChange:e=>{n(n().marginLeft=e,!0)}},input2:{placeholder:`margin right`,value:n().marginRight??``,onChange:e=>{n(n().marginRight=e,!0)}}})),Bi(e,t)};ta(y,e=>{H(o)&&e(b)});var x=vr(y,2);pa(x,(e,t)=>jo?.(e,t),()=>({name:H(r).exportDialog.downscalePercent,limits:[0,200,1],value:n().scale,onChange:e=>{n(n().scale=e,!0)}}));var S=vr(x,2);pa(S,(e,t)=>ko?.(e,t),()=>({name:H(r).exportDialog.landscape,tooltip:`landscape`,value:n().landscape,onChange:e=>{n(n().landscape=e,!0)}}));var C=vr(S,2);pa(C,(e,t)=>ko?.(e,t),()=>({name:H(r).exportDialog.displayHeader,tooltip:`Display header`,value:n().displayHeader,onChange:e=>{n(n().displayHeader=e,!0)}}));var w=vr(C,2);pa(w,(e,t)=>ko?.(e,t),()=>({name:H(r).exportDialog.displayFooter,tooltip:`Display footer`,value:n().displayFooter,onChange:e=>{n(n().displayFooter=e,!0)}}));var T=vr(w,2);pa(T,(e,t)=>ko?.(e,t),()=>({name:H(r).exportDialog.openAfterExport,tooltip:`Open the exported file after exporting.`,value:n().open,onChange:e=>{n(n().open=e,!0)}}));var E=vr(T,2),D=e=>{var i=Lo();pa(i,(e,t)=>Ao?.(e,t),()=>({name:H(r).exportDialog.cssSnippets,options:H(d),value:n().cssSnippet??`0`,onChange:async e=>{n(n().cssSnippet=e,!0),await t.pdfPreview?.renderPreview(!1)}})),Bi(e,i)};ta(E,e=>{H(u)&&H(i).version==`1`&&e(D)});var O=vr(E,2);pa(O,(e,t)=>Mo?.(e,t),()=>({text:`Export`,cta:!0,onClick:()=>t.handleExport()}));var k=vr(O,2),ee=e=>{var n=Lo();pa(n,(e,t)=>Mo?.(e,t),()=>({text:`Refresh`,onClick:()=>t.refreshPreview()})),Bi(e,n)};ta(k,e=>{H(i).version==`1`&&e(ee)}),pa(vr(k,2),(e,t)=>Mo?.(e,t),()=>({text:`Debug`,hidden:!H(i)?.debug,onClick:()=>t.pdfPreview?.handleOpenDevTools()})),ze(p),ji(`keyup`,p,f),Bi(e,p),Qe()}Mi([`keyup`]);var Vo=function(e,t){return Vo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},Vo(e,t)};function U(e,t){Vo(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var Ho=function(){return Ho=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&a[a.length-1]))&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]>2],t+=qo[(e[r]&3)<<4|e[r+1]>>4],t+=qo[(e[r+1]&15)<<2|e[r+2]>>6],t+=qo[e[r+2]&63];return n%3==2?t=t.substring(0,t.length-1)+`=`:n%3==1&&(t=t.substring(0,t.length-2)+`==`),t},Zo=function(e){var t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);var l=new Uint8Array(t);for(r=0;r>4,l[i++]=(o&15)<<4|s>>2,l[i++]=(s&3)<<6|c&63;return l},Qo=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,$o=function(e){var t=e.trim(),n=t.substring(0,100).match(Qo);if(!n)return Zo(t);var r=n[0];return Zo(t.substring(r.length))},es=function(e){return e.charCodeAt(0)},ts=function(e){return e.codePointAt(0)},ns=function(e,t){return os(e.toString(16),t,`0`).toUpperCase()},rs=function(e){return ns(e,2)},is=function(e){return String.fromCharCode(e)},as=function(e){return is(parseInt(e,16))},os=function(e,t,n){for(var r=``,i=0,a=t-e.length;i=55296&&n<=56319&&e.length>i&&(r=e.charCodeAt(i),r>=56320&&r<=57343&&(a=2)),[e.slice(t,t+a),a]},hs=function(e){for(var t=[],n=0,r=e.length;nn&&l(),o+=f,s+=p}}return l(),c},vs=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,ys=function(e){var t=e.match(vs);if(t){var n=t[1],r=t[2],i=r===void 0?`01`:r,a=t[3],o=a===void 0?`01`:a,s=t[4],c=s===void 0?`00`:s,l=t[5],u=l===void 0?`00`:l,d=t[6],f=d===void 0?`00`:d,p=t[7],m=p===void 0?`Z`:p,h=t[8],g=h===void 0?`00`:h,_=t[9],v=_===void 0?`00`:_,y=m===`Z`?`Z`:``+m+g+`:`+v;return new Date(n+`-`+i+`-`+o+`T`+c+`:`+u+`:`+f+y)}},bs=function(e,t){for(var n=0,r;n=0&&e<=65535},Ls=function(e){return e>=65536&&e<=1114111},Rs=function(e){return Math.floor((e-65536)/1024)+55296},zs=function(e){return(e-65536)%1024+56320},Bs;(function(e){e.BigEndian=`BigEndian`,e.LittleEndian=`LittleEndian`})(Bs||(Bs={}));for(var Vs=`�`.codePointAt(0),Hs=function(e,t){if(t===void 0&&(t=!0),e.length<=1)return String.fromCodePoint(Vs);for(var n=t?Ks(e):Bs.BigEndian,r=t?2:0,i=[];e.length-r>=2;){var a=Gs(e[r++],e[r++],n);if(Us(a))if(e.length-r<2)i.push(Vs);else{var o=Gs(e[r++],e[r++],n);Ws(o)?i.push(a,o):i.push(Vs)}else Ws(a)?(r+=2,i.push(Vs)):i.push(a)}return r=55296&&e<=56319},Ws=function(e){return e>=56320&&e<=57343},Gs=function(e,t,n){if(n===Bs.LittleEndian)return t<<8|e;if(n===Bs.BigEndian)return e<<8|t;throw Error(`Invalid byteOrder: `+n)},Ks=function(e){return qs(e)?Bs.BigEndian:Js(e)?Bs.LittleEndian:Bs.BigEndian},qs=function(e){return e[0]===254&&e[1]===255},Js=function(e){return e[0]===255&&e[1]===254},Ys=function(e){return qs(e)||Js(e)},Xs=function(e){var t=String(e);if(Math.abs(e)<1){var n=parseInt(e.toString().split(`e-`)[1]);if(n){var r=e<0;r&&(e*=-1),e*=10**(n-1),t=`0.`+Array(n).join(`0`)+e.toString().substring(2),r&&(t=`-`+t)}}else{var n=parseInt(e.toString().split(`+`)[1]);n>20&&(n-=20,e/=10**n,t=e.toString()+Array(n+1).join(`0`))}return t},Zs=function(e){return Math.ceil(e.toString(2).length/8)},Qs=function(e){for(var t=new Uint8Array(Zs(e)),n=1;n<=t.length;n++)t[n-1]=e>>(t.length-n)*8;return t},$s=function(e){throw Error(e)},ec=o((e=>{var t=typeof Uint8Array<`u`&&typeof Uint16Array<`u`&&typeof Int32Array<`u`;function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!=`object`)throw TypeError(r+`must be non-object`);for(var i in r)n(r,i)&&(e[i]=r[i])}}return e},e.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var r={arraySet:function(e,t,n,r,i){if(t.subarray&&e.subarray){e.set(t.subarray(n,n+r),i);return}for(var a=0;a{var t=ec(),n=4,r=0,i=1,a=2;function o(e){for(var t=e.length;--t>=0;)e[t]=0}var s=0,c=1,l=2,u=3,d=258,f=29,p=256,m=p+1+f,h=30,g=19,_=2*m+1,v=15,y=16,b=7,x=256,S=16,C=17,w=18,T=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],E=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],D=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],O=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],k=512,ee=Array((m+2)*2);o(ee);var A=Array(h*2);o(A);var j=Array(k);o(j);var te=Array(d-u+1);o(te);var ne=Array(f);o(ne);var re=Array(h);o(re);function ie(e,t,n,r,i){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=e&&e.length}var ae,oe,se;function ce(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function le(e){return e<256?j[e]:j[256+(e>>>7)]}function ue(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function M(e,t,n){e.bi_valid>y-n?(e.bi_buf|=t<>y-e.bi_valid,e.bi_valid+=n-y):(e.bi_buf|=t<>>=1,n<<=1;while(--t>0);return n>>>1}function fe(e){e.bi_valid===16?(ue(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function pe(e,t){var n=t.dyn_tree,r=t.max_code,i=t.stat_desc.static_tree,a=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,c=t.stat_desc.max_length,l,u,d,f,p,m,h=0;for(f=0;f<=v;f++)e.bl_count[f]=0;for(n[e.heap[e.heap_max]*2+1]=0,l=e.heap_max+1;l<_;l++)u=e.heap[l],f=n[n[u*2+1]*2+1]+1,f>c&&(f=c,h++),n[u*2+1]=f,!(u>r)&&(e.bl_count[f]++,p=0,u>=s&&(p=o[u-s]),m=n[u*2],e.opt_len+=m*(f+p),a&&(e.static_len+=m*(i[u*2+1]+p)));if(h!==0){do{for(f=c-1;e.bl_count[f]===0;)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,h-=2}while(h>0);for(f=c;f!==0;f--)for(u=e.bl_count[f];u!==0;)d=e.heap[--l],!(d>r)&&(n[d*2+1]!==f&&(e.opt_len+=(f-n[d*2+1])*n[d*2],n[d*2+1]=f),u--)}}function me(e,t,n){var r=Array(v+1),i=0,a,o;for(a=1;a<=v;a++)r[a]=i=i+n[a-1]<<1;for(o=0;o<=t;o++){var s=e[o*2+1];s!==0&&(e[o*2]=de(r[s]++,s))}}function he(){var e,t,n,r,i,a=Array(v+1);for(n=0,r=0;r>=7;r8?ue(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function ve(e,n,r,i){_e(e),i&&(ue(e,r),ue(e,~r)),t.arraySet(e.pending_buf,e.window,n,r,e.pending),e.pending+=r}function P(e,t,n,r){var i=t*2,a=n*2;return e[i]>1;o>=1;o--)ye(e,n,o);l=a;do o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],ye(e,n,1),s=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=s,n[l*2]=n[o*2]+n[s*2],e.depth[l]=(e.depth[o]>=e.depth[s]?e.depth[o]:e.depth[s])+1,n[o*2+1]=n[s*2+1]=l,e.heap[1]=l++,ye(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],pe(e,t),me(n,c,e.bl_count)}function F(e,t,n){var r,i=-1,a,o=t[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)a=o,o=t[(r+1)*2+1],!(++s=3&&e.bl_tree[O[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function Ce(e,t,n,r){var i;for(M(e,t-257,5),M(e,n-1,5),M(e,r-4,4),i=0;i>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return r;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return i;for(n=32;n0?(e.strm.data_type===a&&(e.strm.data_type=L(e)),xe(e,e.l_desc),xe(e,e.d_desc),u=I(e),o=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=o&&(o=s)):o=s=r+5,r+4<=o&&t!==-1?Te(e,t,r,i):e.strategy===n||s===o?(M(e,(c<<1)+ +!!i,3),be(e,ee,A)):(M(e,(l<<1)+ +!!i,3),Ce(e,e.l_desc.max_code+1,e.d_desc.max_code+1,u+1),be(e,e.dyn_ltree,e.dyn_dtree)),ge(e),i&&_e(e)}function z(e,t,n){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=n&255,e.last_lit++,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(te[n]+p+1)*2]++,e.dyn_dtree[le(t)*2]++),e.last_lit===e.lit_bufsize-1}e._tr_init=we,e._tr_stored_block=Te,e._tr_flush_block=De,e._tr_tally=z,e._tr_align=Ee})),nc=o(((e,t)=>{function n(e,t,n,r){for(var i=e&65535|0,a=e>>>16&65535|0,o=0;n!==0;){o=n>2e3?2e3:n,n-=o;do i=i+t[r++]|0,a=a+i|0;while(--o);i%=65521,a%=65521}return i|a<<16|0}t.exports=n})),rc=o(((e,t)=>{function n(){for(var e,t=[],n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t}var r=n();function i(e,t,n,i){var a=r,o=i+n;e^=-1;for(var s=i;s>>8^a[(e^t[s])&255];return e^-1}t.exports=i})),ic=o(((e,t)=>{t.exports={2:`need dictionary`,1:`stream end`,0:``,"-1":`file error`,"-2":`stream error`,"-3":`data error`,"-4":`insufficient memory`,"-5":`buffer error`,"-6":`incompatible version`}})),ac=o((e=>{var t=ec(),n=tc(),r=nc(),i=rc(),a=ic(),o=0,s=1,c=3,l=4,u=5,d=0,f=1,p=-2,m=-3,h=-5,g=-1,_=1,v=2,y=3,b=4,x=0,S=2,C=8,w=9,T=15,E=8,D=286,O=30,k=19,ee=2*D+1,A=15,j=3,te=258,ne=te+j+1,re=32,ie=42,ae=69,oe=73,se=91,ce=103,le=113,ue=666,M=1,N=2,de=3,fe=4,pe=3;function me(e,t){return e.msg=a[t],t}function he(e){return(e<<1)-(e>4?9:0)}function ge(e){for(var t=e.length;--t>=0;)e[t]=0}function _e(e){var n=e.state,r=n.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(t.arraySet(e.output,n.pending_buf,n.pending_out,r,e.next_out),e.next_out+=r,n.pending_out+=r,e.total_out+=r,e.avail_out-=r,n.pending-=r,n.pending===0&&(n.pending_out=0))}function ve(e,t){n._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,_e(e.strm)}function P(e,t){e.pending_buf[e.pending++]=t}function ye(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function be(e,n,a,o){var s=e.avail_in;return s>o&&(s=o),s===0?0:(e.avail_in-=s,t.arraySet(n,e.input,e.next_in,s,a),e.state.wrap===1?e.adler=r(e.adler,n,s,a):e.state.wrap===2&&(e.adler=i(e.adler,n,s,a)),e.next_in+=s,e.total_in+=s,s)}function xe(e,t){var n=e.max_chain_length,r=e.strstart,i,a,o=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-ne?e.strstart-(e.w_size-ne):0,l=e.window,u=e.w_mask,d=e.prev,f=e.strstart+te,p=l[r+o-1],m=l[r+o];e.prev_length>=e.good_match&&(n>>=2),s>e.lookahead&&(s=e.lookahead);do{if(i=t,l[i+o]!==m||l[i+o-1]!==p||l[i]!==l[r]||l[++i]!==l[r+1])continue;r+=2,i++;do;while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&ro){if(e.match_start=t,o=a,a>=s)break;p=l[r+o-1],m=l[r+o]}}while((t=d[t&u])>c&&--n!==0);return o<=e.lookahead?o:e.lookahead}function F(e){var n=e.w_size,r,i,a,o,s;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=n+(n-ne)){t.arraySet(e.window,e.window,n,n,0),e.match_start-=n,e.strstart-=n,e.block_start-=n,i=e.hash_size,r=i;do a=e.head[--r],e.head[r]=a>=n?a-n:0;while(--i);i=n,r=i;do a=e.prev[--r],e.prev[r]=a>=n?a-n:0;while(--i);o+=n}if(e.strm.avail_in===0)break;if(i=be(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=j)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(F(e),e.lookahead===0&&t===o)return M;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+n;if((e.strstart===0||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,ve(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-ne&&(ve(e,!1),e.strm.avail_out===0))return M}return e.insert=0,t===l?(ve(e,!0),e.strm.avail_out===0?de:fe):(e.strstart>e.block_start&&(ve(e,!1),e.strm.avail_out),M)}function I(e,t){for(var r,i;;){if(e.lookahead=j&&(e.ins_h=(e.ins_h<=j)if(i=n._tr_tally(e,e.strstart-e.match_start,e.match_length-j),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=j){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<=j&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=j-1)),e.prev_length>=j&&e.match_length<=e.prev_length){a=e.strstart+e.lookahead-j,i=n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-j),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=a&&(e.ins_h=(e.ins_h<=j&&e.strstart>0&&(a=e.strstart-1,i=c[a],i===c[++a]&&i===c[++a]&&i===c[++a])){s=e.strstart+te;do;while(i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&ae.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=j?(r=n._tr_tally(e,1,e.match_length-j),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(ve(e,!1),e.strm.avail_out===0))return M}return e.insert=0,t===l?(ve(e,!0),e.strm.avail_out===0?de:fe):e.last_lit&&(ve(e,!1),e.strm.avail_out===0)?M:N}function R(e,t){for(var r;;){if(e.lookahead===0&&(F(e),e.lookahead===0)){if(t===o)return M;break}if(e.match_length=0,r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(ve(e,!1),e.strm.avail_out===0))return M}return e.insert=0,t===l?(ve(e,!0),e.strm.avail_out===0?de:fe):e.last_lit&&(ve(e,!1),e.strm.avail_out===0)?M:N}function we(e,t,n,r,i){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=i}var Te=[new we(0,0,0,0,Se),new we(4,4,8,4,I),new we(4,5,16,8,I),new we(4,6,32,32,I),new we(4,4,16,16,Ce),new we(8,16,32,32,Ce),new we(8,16,128,128,Ce),new we(8,32,128,256,Ce),new we(32,128,258,1024,Ce),new we(32,258,258,4096,Ce)];function Ee(e){e.window_size=2*e.w_size,ge(e.head),e.max_lazy_match=Te[e.level].max_lazy,e.good_match=Te[e.level].good_length,e.nice_match=Te[e.level].nice_length,e.max_chain_length=Te[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=j-1,e.match_available=0,e.ins_h=0}function De(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=C,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new t.Buf16(ee*2),this.dyn_dtree=new t.Buf16((2*O+1)*2),this.bl_tree=new t.Buf16((2*k+1)*2),ge(this.dyn_ltree),ge(this.dyn_dtree),ge(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new t.Buf16(A+1),this.heap=new t.Buf16(2*D+1),ge(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new t.Buf16(2*D+1),ge(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function z(e){var t;return!e||!e.state?me(e,p):(e.total_in=e.total_out=0,e.data_type=S,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?ie:le,e.adler=t.wrap===2?0:1,t.last_flush=o,n._tr_init(t),d)}function Oe(e){var t=z(e);return t===d&&Ee(e.state),t}function ke(e,t){return!e||!e.state||e.state.wrap!==2?p:(e.state.gzhead=t,d)}function Ae(e,n,r,i,a,o){if(!e)return p;var s=1;if(n===g&&(n=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),a<1||a>w||r!==C||i<8||i>15||n<0||n>9||o<0||o>b)return me(e,p);i===8&&(i=9);var c=new De;return e.state=c,c.strm=e,c.wrap=s,c.gzhead=null,c.w_bits=i,c.w_size=1<u||t<0)return e?me(e,p):p;if(a=e.state,!e.output||!e.input&&e.avail_in!==0||a.status===ue&&t!==l)return me(e,e.avail_out===0?h:p);if(a.strm=e,r=a.last_flush,a.last_flush=t,a.status===ie)if(a.wrap===2)e.adler=0,P(a,31),P(a,139),P(a,8),a.gzhead?(P(a,+!!a.gzhead.text+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),P(a,a.gzhead.time&255),P(a,a.gzhead.time>>8&255),P(a,a.gzhead.time>>16&255),P(a,a.gzhead.time>>24&255),P(a,a.level===9?2:a.strategy>=v||a.level<2?4:0),P(a,a.gzhead.os&255),a.gzhead.extra&&a.gzhead.extra.length&&(P(a,a.gzhead.extra.length&255),P(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(e.adler=i(e.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=ae):(P(a,0),P(a,0),P(a,0),P(a,0),P(a,0),P(a,a.level===9?2:a.strategy>=v||a.level<2?4:0),P(a,pe),a.status=le);else{var _=C+(a.w_bits-8<<4)<<8,b=-1;b=a.strategy>=v||a.level<2?0:a.level<6?1:a.level===6?2:3,_|=b<<6,a.strstart!==0&&(_|=re),_+=31-_%31,a.status=le,ye(a,_),a.strstart!==0&&(ye(a,e.adler>>>16),ye(a,e.adler&65535)),e.adler=1}if(a.status===ae)if(a.gzhead.extra){for(m=a.pending;a.gzindex<(a.gzhead.extra.length&65535)&&!(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),_e(e),m=a.pending,a.pending===a.pending_buf_size));)P(a,a.gzhead.extra[a.gzindex]&255),a.gzindex++;a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),a.gzindex===a.gzhead.extra.length&&(a.gzindex=0,a.status=oe)}else a.status=oe;if(a.status===oe)if(a.gzhead.name){m=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),_e(e),m=a.pending,a.pending===a.pending_buf_size)){g=1;break}g=a.gzindexm&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),g===0&&(a.gzindex=0,a.status=se)}else a.status=se;if(a.status===se)if(a.gzhead.comment){m=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),_e(e),m=a.pending,a.pending===a.pending_buf_size)){g=1;break}g=a.gzindexm&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),g===0&&(a.status=ce)}else a.status=ce;if(a.status===ce&&(a.gzhead.hcrc?(a.pending+2>a.pending_buf_size&&_e(e),a.pending+2<=a.pending_buf_size&&(P(a,e.adler&255),P(a,e.adler>>8&255),e.adler=0,a.status=le)):a.status=le),a.pending!==0){if(_e(e),e.avail_out===0)return a.last_flush=-1,d}else if(e.avail_in===0&&he(t)<=he(r)&&t!==l)return me(e,h);if(a.status===ue&&e.avail_in!==0)return me(e,h);if(e.avail_in!==0||a.lookahead!==0||t!==o&&a.status!==ue){var x=a.strategy===v?R(a,t):a.strategy===y?L(a,t):Te[a.level].func(a,t);if((x===de||x===fe)&&(a.status=ue),x===M||x===de)return e.avail_out===0&&(a.last_flush=-1),d;if(x===N&&(t===s?n._tr_align(a):t!==u&&(n._tr_stored_block(a,0,0,!1),t===c&&(ge(a.head),a.lookahead===0&&(a.strstart=0,a.block_start=0,a.insert=0))),_e(e),e.avail_out===0))return a.last_flush=-1,d}return t===l?a.wrap<=0?f:(a.wrap===2?(P(a,e.adler&255),P(a,e.adler>>8&255),P(a,e.adler>>16&255),P(a,e.adler>>24&255),P(a,e.total_in&255),P(a,e.total_in>>8&255),P(a,e.total_in>>16&255),P(a,e.total_in>>24&255)):(ye(a,e.adler>>>16),ye(a,e.adler&65535)),_e(e),a.wrap>0&&(a.wrap=-a.wrap),a.pending===0?f:d):d}function Ne(e){var t;return!e||!e.state?p:(t=e.state.status,t!==ie&&t!==ae&&t!==oe&&t!==se&&t!==ce&&t!==le&&t!==ue?me(e,p):(e.state=null,t===le?me(e,m):d))}function Pe(e,n){var i=n.length,a,o,s,c,l,u,f,m;if(!e||!e.state||(a=e.state,c=a.wrap,c===2||c===1&&a.status!==ie||a.lookahead))return p;for(c===1&&(e.adler=r(e.adler,n,i,0)),a.wrap=0,i>=a.w_size&&(c===0&&(ge(a.head),a.strstart=0,a.block_start=0,a.insert=0),m=new t.Buf8(a.w_size),t.arraySet(m,n,i-a.w_size,a.w_size,0),n=m,i=a.w_size),l=e.avail_in,u=e.next_in,f=e.input,e.avail_in=i,e.next_in=0,e.input=n,F(a);a.lookahead>=j;){o=a.strstart,s=a.lookahead-(j-1);do a.ins_h=(a.ins_h<{var t=ec(),n=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch{n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{r=!1}for(var i=new t.Buf8(256),a=0;a<256;a++)i[a]=a>=252?6:a>=248?5:a>=240?4:a>=224?3:a>=192?2:1;i[254]=i[254]=1,e.string2buf=function(e){var n,r,i,a,o,s=e.length,c=0;for(a=0;a>>6,n[o++]=128|r&63):r<65536?(n[o++]=224|r>>>12,n[o++]=128|r>>>6&63,n[o++]=128|r&63):(n[o++]=240|r>>>18,n[o++]=128|r>>>12&63,n[o++]=128|r>>>6&63,n[o++]=128|r&63);return n};function o(e,i){if(i<65534&&(e.subarray&&r||!e.subarray&&n))return String.fromCharCode.apply(null,t.shrinkBuf(e,i));for(var a=``,o=0;o4){l[r++]=65533,n+=s-1;continue}for(a&=s===2?31:s===3?15:7;s>1&&n1){l[r++]=65533;continue}a<65536?l[r++]=a:(a-=65536,l[r++]=55296|a>>10&1023,l[r++]=56320|a&1023)}return o(l,r)},e.utf8border=function(e,t){var n;for(t=t||e.length,t>e.length&&(t=e.length),n=t-1;n>=0&&(e[n]&192)==128;)n--;return n<0||n===0?t:n+i[e[n]]>t?n:t}})),sc=o(((e,t)=>{function n(){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}t.exports=n})),cc=o((e=>{var t=ac(),n=ec(),r=oc(),i=ic(),a=sc(),o=Object.prototype.toString,s=0,c=4,l=0,u=1,d=2,f=-1,p=0,m=8;function h(e){if(!(this instanceof h))return new h(e);this.options=n.assign({level:f,method:m,chunkSize:16384,windowBits:15,memLevel:8,strategy:p,to:``},e||{});var s=this.options;s.raw&&s.windowBits>0?s.windowBits=-s.windowBits:s.gzip&&s.windowBits>0&&s.windowBits<16&&(s.windowBits+=16),this.err=0,this.msg=``,this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var c=t.deflateInit2(this.strm,s.level,s.method,s.windowBits,s.memLevel,s.strategy);if(c!==l)throw Error(i[c]);if(s.header&&t.deflateSetHeader(this.strm,s.header),s.dictionary){var u=typeof s.dictionary==`string`?r.string2buf(s.dictionary):o.call(s.dictionary)===`[object ArrayBuffer]`?new Uint8Array(s.dictionary):s.dictionary;if(c=t.deflateSetDictionary(this.strm,u),c!==l)throw Error(i[c]);this._dict_set=!0}}h.prototype.push=function(e,i){var a=this.strm,f=this.options.chunkSize,p,m;if(this.ended)return!1;m=i===~~i?i:i===!0?c:s,typeof e==`string`?a.input=r.string2buf(e):o.call(e)===`[object ArrayBuffer]`?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(a.avail_out===0&&(a.output=new n.Buf8(f),a.next_out=0,a.avail_out=f),p=t.deflate(a,m),p!==u&&p!==l)return this.onEnd(p),this.ended=!0,!1;(a.avail_out===0||a.avail_in===0&&(m===c||m===d))&&(this.options.to===`string`?this.onData(r.buf2binstring(n.shrinkBuf(a.output,a.next_out))):this.onData(n.shrinkBuf(a.output,a.next_out)))}while((a.avail_in>0||a.avail_out===0)&&p!==u);return m===c?(p=t.deflateEnd(this.strm),this.onEnd(p),this.ended=!0,p===l):m===d?(this.onEnd(l),a.avail_out=0,!0):!0},h.prototype.onData=function(e){this.chunks.push(e)},h.prototype.onEnd=function(e){e===l&&(this.options.to===`string`?this.result=this.chunks.join(``):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function g(e,t){var n=new h(t);if(n.push(e,!0),n.err)throw n.msg||i[n.err];return n.result}function _(e,t){return t=t||{},t.raw=!0,g(e,t)}function v(e,t){return t=t||{},t.gzip=!0,g(e,t)}e.Deflate=h,e.deflate=g,e.deflateRaw=_,e.gzip=v})),lc=o(((e,t)=>{t.exports=function(e,t){var n=e.state,r=e.next_in,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T=e.input,E;i=r+(e.avail_in-5),a=e.next_out,E=e.output,o=a-(t-e.avail_out),s=a+(e.avail_out-257),c=n.dmax,l=n.wsize,u=n.whave,d=n.wnext,f=n.window,p=n.hold,m=n.bits,h=n.lencode,g=n.distcode,_=(1<>>24,p>>>=b,m-=b,b=y>>>16&255,b===0)E[a++]=y&65535;else if(b&16){x=y&65535,b&=15,b&&(m>>=b,m-=b),m<15&&(p+=T[r++]<>>24,p>>>=b,m-=b,b=y>>>16&255,b&16){if(S=y&65535,b&=15,mc){e.msg=`invalid distance too far back`,n.mode=30;break top}if(p>>>=b,m-=b,b=a-o,S>b){if(b=S-b,b>u&&n.sane){e.msg=`invalid distance too far back`,n.mode=30;break top}if(C=0,w=f,d===0){if(C+=l-b,b2;)E[a++]=w[C++],E[a++]=w[C++],E[a++]=w[C++],x-=3;x&&(E[a++]=w[C++],x>1&&(E[a++]=w[C++]))}else{C=a-S;do E[a++]=E[C++],E[a++]=E[C++],E[a++]=E[C++],x-=3;while(x>2);x&&(E[a++]=E[C++],x>1&&(E[a++]=E[C++]))}}else if(b&64){e.msg=`invalid distance code`,n.mode=30;break top}else{y=g[(y&65535)+(p&(1<>3,r-=x,m-=x<<3,p&=(1<{var n=ec(),r=15,i=852,a=592,o=0,s=1,c=2,l=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],u=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],d=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],f=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,p,m,h,g,_,v){var y=v.bits,b=0,x=0,S=0,C=0,w=0,T=0,E=0,D=0,O=0,k=0,ee,A,j,te,ne,re=null,ie=0,ae,oe=new n.Buf16(r+1),se=new n.Buf16(r+1),ce=null,le=0,ue,M,N;for(b=0;b<=r;b++)oe[b]=0;for(x=0;x=1&&oe[C]===0;C--);if(w>C&&(w=C),C===0)return h[g++]=20971520,h[g++]=20971520,v.bits=1,0;for(S=1;S0&&(e===o||C!==1))return-1;for(se[1]=0,b=1;bi||e===c&&O>a)return 1;for(;;){ue=b-E,_[x]ae?(M=ce[le+_[x]],N=re[ie+_[x]]):(M=96,N=0),ee=1<>E)+A]=ue<<24|M<<16|N|0;while(A!==0);for(ee=1<>=1;if(ee===0?k=0:(k&=ee-1,k+=ee),x++,--oe[b]===0){if(b===C)break;b=t[p+_[x]]}if(b>w&&(k&te)!==j){for(E===0&&(E=w),ne+=S,T=b-E,D=1<i||e===c&&O>a)return 1;j=k&te,h[j]=w<<24|T<<16|ne-g|0}}return k!==0&&(h[ne+k]=b-E<<24|4194304),v.bits=w,0}})),dc=o((e=>{var t=ec(),n=nc(),r=rc(),i=lc(),a=uc(),o=0,s=1,c=2,l=4,u=5,d=6,f=0,p=1,m=2,h=-2,g=-3,_=-4,v=-5,y=8,b=1,x=2,S=3,C=4,w=5,T=6,E=7,D=8,O=9,k=10,ee=11,A=12,j=13,te=14,ne=15,re=16,ie=17,ae=18,oe=19,se=20,ce=21,le=22,ue=23,M=24,N=25,de=26,fe=27,pe=28,me=29,he=30,ge=31,_e=32,ve=852,P=592,ye=15;function be(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function xe(){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 t.Buf16(320),this.work=new t.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function F(e){var n;return!e||!e.state?h:(n=e.state,e.total_in=e.total_out=n.total=0,e.msg=``,n.wrap&&(e.adler=n.wrap&1),n.mode=b,n.last=0,n.havedict=0,n.dmax=32768,n.head=null,n.hold=0,n.bits=0,n.lencode=n.lendyn=new t.Buf32(ve),n.distcode=n.distdyn=new t.Buf32(P),n.sane=1,n.back=-1,f)}function Se(e){var t;return!e||!e.state?h:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,F(e))}function I(e,t){var n,r;return!e||!e.state||(r=e.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?h:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Se(e))}function Ce(e,t){var n,r;return e?(r=new xe,e.state=r,r.window=null,n=I(e,t),n!==f&&(e.state=null),n):h}function L(e){return Ce(e,ye)}var R=!0,we,Te;function Ee(e){if(R){var n;for(we=new t.Buf32(512),Te=new t.Buf32(32),n=0;n<144;)e.lens[n++]=8;for(;n<256;)e.lens[n++]=9;for(;n<280;)e.lens[n++]=7;for(;n<288;)e.lens[n++]=8;for(a(s,e.lens,0,288,we,0,e.work,{bits:9}),n=0;n<32;)e.lens[n++]=5;a(c,e.lens,0,32,Te,0,e.work,{bits:5}),R=!1}e.lencode=we,e.lenbits=9,e.distcode=Te,e.distbits=5}function De(e,n,r,i){var a,o=e.state;return o.window===null&&(o.wsize=1<=o.wsize?(t.arraySet(o.window,n,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(a=o.wsize-o.wnext,a>i&&(a=i),t.arraySet(o.window,n,r-i,a,o.wnext),i-=a,i?(t.arraySet(o.window,n,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,P.check=r(P.check,ze,2,0),L=0,R=0,P.mode=x;break}if(P.flags=0,P.head&&(P.head.done=!1),!(P.wrap&1)||(((L&255)<<8)+(L>>8))%31){e.msg=`incorrect header check`,P.mode=he;break}if((L&15)!==y){e.msg=`unknown compression method`,P.mode=he;break}if(L>>>=4,R-=4,Le=(L&15)+8,P.wbits===0)P.wbits=Le;else if(Le>P.wbits){e.msg=`invalid window size`,P.mode=he;break}P.dmax=1<>8&1),P.flags&512&&(ze[0]=L&255,ze[1]=L>>>8&255,P.check=r(P.check,ze,2,0)),L=0,R=0,P.mode=S;case S:for(;R<32;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>8&255,ze[2]=L>>>16&255,ze[3]=L>>>24&255,P.check=r(P.check,ze,4,0)),L=0,R=0,P.mode=C;case C:for(;R<16;){if(I===0)break inf_leave;I--,L+=ye[F++]<>8),P.flags&512&&(ze[0]=L&255,ze[1]=L>>>8&255,P.check=r(P.check,ze,2,0)),L=0,R=0,P.mode=w;case w:if(P.flags&1024){for(;R<16;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>8&255,P.check=r(P.check,ze,2,0)),L=0,R=0}else P.head&&(P.head.extra=null);P.mode=T;case T:if(P.flags&1024&&(z=P.length,z>I&&(z=I),z&&(P.head&&(Le=P.head.extra_len-P.length,P.head.extra||(P.head.extra=Array(P.head.extra_len)),t.arraySet(P.head.extra,ye,F,z,Le)),P.flags&512&&(P.check=r(P.check,ye,z,F)),I-=z,F+=z,P.length-=z),P.length))break inf_leave;P.length=0,P.mode=E;case E:if(P.flags&2048){if(I===0)break inf_leave;z=0;do Le=ye[F+z++],P.head&&Le&&P.length<65536&&(P.head.name+=String.fromCharCode(Le));while(Le&&z>9&1,P.head.done=!0),e.adler=P.check=0,P.mode=A;break;case k:for(;R<32;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=R&7,R-=R&7,P.mode=fe;break}for(;R<3;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=1,--R,L&3){case 0:P.mode=te;break;case 1:if(Ee(P),P.mode=se,ve===d){L>>>=2,R-=2;break inf_leave}break;case 2:P.mode=ie;break;case 3:e.msg=`invalid block type`,P.mode=he}L>>>=2,R-=2;break;case te:for(L>>>=R&7,R-=R&7;R<32;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>16^65535)){e.msg=`invalid stored block lengths`,P.mode=he;break}if(P.length=L&65535,L=0,R=0,P.mode=ne,ve===d)break inf_leave;case ne:P.mode=re;case re:if(z=P.length,z){if(z>I&&(z=I),z>Ce&&(z=Ce),z===0)break inf_leave;t.arraySet(xe,ye,F,z,Se),I-=z,F+=z,Ce-=z,Se+=z,P.length-=z;break}P.mode=A;break;case ie:for(;R<14;){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=5,R-=5,P.ndist=(L&31)+1,L>>>=5,R-=5,P.ncode=(L&15)+4,L>>>=4,R-=4,P.nlen>286||P.ndist>30){e.msg=`too many length or distance symbols`,P.mode=he;break}P.have=0,P.mode=ae;case ae:for(;P.have>>=3,R-=3}for(;P.have<19;)P.lens[He[P.have++]]=0;if(P.lencode=P.lendyn,P.lenbits=7,Be={bits:P.lenbits},Re=a(o,P.lens,0,19,P.lencode,0,P.work,Be),P.lenbits=Be.bits,Re){e.msg=`invalid code lengths set`,P.mode=he;break}P.have=0,P.mode=oe;case oe:for(;P.have>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=je,R-=je,P.lens[P.have++]=Ne;else{if(Ne===16){for(Ve=je+2;R>>=je,R-=je,P.have===0){e.msg=`invalid bit length repeat`,P.mode=he;break}Le=P.lens[P.have-1],z=3+(L&3),L>>>=2,R-=2}else if(Ne===17){for(Ve=je+3;R>>=je,R-=je,Le=0,z=3+(L&7),L>>>=3,R-=3}else{for(Ve=je+7;R>>=je,R-=je,Le=0,z=11+(L&127),L>>>=7,R-=7}if(P.have+z>P.nlen+P.ndist){e.msg=`invalid bit length repeat`,P.mode=he;break}for(;z--;)P.lens[P.have++]=Le}}if(P.mode===he)break;if(P.lens[256]===0){e.msg=`invalid code -- missing end-of-block`,P.mode=he;break}if(P.lenbits=9,Be={bits:P.lenbits},Re=a(s,P.lens,0,P.nlen,P.lencode,0,P.work,Be),P.lenbits=Be.bits,Re){e.msg=`invalid literal/lengths set`,P.mode=he;break}if(P.distbits=6,P.distcode=P.distdyn,Be={bits:P.distbits},Re=a(c,P.lens,P.nlen,P.ndist,P.distcode,0,P.work,Be),P.distbits=Be.bits,Re){e.msg=`invalid distances set`,P.mode=he;break}if(P.mode=se,ve===d)break inf_leave;case se:P.mode=ce;case ce:if(I>=6&&Ce>=258){e.next_out=Se,e.avail_out=Ce,e.next_in=F,e.avail_in=I,P.hold=L,P.bits=R,i(e,Te),Se=e.next_out,xe=e.output,Ce=e.avail_out,F=e.next_in,ye=e.input,I=e.avail_in,L=P.hold,R=P.bits,P.mode===A&&(P.back=-1);break}for(P.back=0;Ae=P.lencode[L&(1<>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>Pe)],je=Ae>>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(Pe+je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=Pe,R-=Pe,P.back+=Pe}if(L>>>=je,R-=je,P.back+=je,P.length=Ne,Me===0){P.mode=de;break}if(Me&32){P.back=-1,P.mode=A;break}if(Me&64){e.msg=`invalid literal/length code`,P.mode=he;break}P.extra=Me&15,P.mode=le;case le:if(P.extra){for(Ve=P.extra;R>>=P.extra,R-=P.extra,P.back+=P.extra}P.was=P.length,P.mode=ue;case ue:for(;Ae=P.distcode[L&(1<>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>Pe)],je=Ae>>>24,Me=Ae>>>16&255,Ne=Ae&65535,!(Pe+je<=R);){if(I===0)break inf_leave;I--,L+=ye[F++]<>>=Pe,R-=Pe,P.back+=Pe}if(L>>>=je,R-=je,P.back+=je,Me&64){e.msg=`invalid distance code`,P.mode=he;break}P.offset=Ne,P.extra=Me&15,P.mode=M;case M:if(P.extra){for(Ve=P.extra;R>>=P.extra,R-=P.extra,P.back+=P.extra}if(P.offset>P.dmax){e.msg=`invalid distance too far back`,P.mode=he;break}P.mode=N;case N:if(Ce===0)break inf_leave;if(z=Te-Ce,P.offset>z){if(z=P.offset-z,z>P.whave&&P.sane){e.msg=`invalid distance too far back`,P.mode=he;break}z>P.wnext?(z-=P.wnext,Oe=P.wsize-z):Oe=P.wnext-z,z>P.length&&(z=P.length),ke=P.window}else ke=xe,Oe=Se-P.offset,z=P.length;z>Ce&&(z=Ce),Ce-=z,P.length-=z;do xe[Se++]=ke[Oe++];while(--z);P.length===0&&(P.mode=ce);break;case de:if(Ce===0)break inf_leave;xe[Se++]=P.length,Ce--,P.mode=ce;break;case fe:if(P.wrap){for(;R<32;){if(I===0)break inf_leave;I--,L|=ye[F++]<{t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}})),pc=o(((e,t)=>{function n(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=``,this.comment=``,this.hcrc=0,this.done=!1}t.exports=n})),mc=o((e=>{var t=dc(),n=ec(),r=oc(),i=fc(),a=ic(),o=sc(),s=pc(),c=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=n.assign({chunkSize:16384,windowBits:0,to:``},e||{});var u=this.options;u.raw&&u.windowBits>=0&&u.windowBits<16&&(u.windowBits=-u.windowBits,u.windowBits===0&&(u.windowBits=-15)),u.windowBits>=0&&u.windowBits<16&&!(e&&e.windowBits)&&(u.windowBits+=32),u.windowBits>15&&u.windowBits<48&&(u.windowBits&15||(u.windowBits|=15)),this.err=0,this.msg=``,this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var d=t.inflateInit2(this.strm,u.windowBits);if(d!==i.Z_OK||(this.header=new s,t.inflateGetHeader(this.strm,this.header),u.dictionary&&(typeof u.dictionary==`string`?u.dictionary=r.string2buf(u.dictionary):c.call(u.dictionary)===`[object ArrayBuffer]`&&(u.dictionary=new Uint8Array(u.dictionary)),u.raw&&(d=t.inflateSetDictionary(this.strm,u.dictionary),d!==i.Z_OK))))throw Error(a[d])}l.prototype.push=function(e,a){var o=this.strm,s=this.options.chunkSize,l=this.options.dictionary,u,d,f,p,m,h=!1;if(this.ended)return!1;d=a===~~a?a:a===!0?i.Z_FINISH:i.Z_NO_FLUSH,typeof e==`string`?o.input=r.binstring2buf(e):c.call(e)===`[object ArrayBuffer]`?o.input=new Uint8Array(e):o.input=e,o.next_in=0,o.avail_in=o.input.length;do{if(o.avail_out===0&&(o.output=new n.Buf8(s),o.next_out=0,o.avail_out=s),u=t.inflate(o,i.Z_NO_FLUSH),u===i.Z_NEED_DICT&&l&&(u=t.inflateSetDictionary(this.strm,l)),u===i.Z_BUF_ERROR&&h===!0&&(u=i.Z_OK,h=!1),u!==i.Z_STREAM_END&&u!==i.Z_OK)return this.onEnd(u),this.ended=!0,!1;o.next_out&&(o.avail_out===0||u===i.Z_STREAM_END||o.avail_in===0&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&(this.options.to===`string`?(f=r.utf8border(o.output,o.next_out),p=o.next_out-f,m=r.buf2string(o.output,f),o.next_out=p,o.avail_out=s-p,p&&n.arraySet(o.output,o.output,f,p,0),this.onData(m)):this.onData(n.shrinkBuf(o.output,o.next_out))),o.avail_in===0&&o.avail_out===0&&(h=!0)}while((o.avail_in>0||o.avail_out===0)&&u!==i.Z_STREAM_END);return u===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(u=t.inflateEnd(this.strm),this.onEnd(u),this.ended=!0,u===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),o.avail_out=0,!0):!0},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){e===i.Z_OK&&(this.options.to===`string`?this.result=this.chunks.join(``):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function u(e,t){var n=new l(t);if(n.push(e,!0),n.err)throw n.msg||a[n.err];return n.result}function d(e,t){return t=t||{},t.raw=!0,u(e,t)}e.Inflate=l,e.inflate=u,e.inflateRaw=d,e.ungzip=u})),hc=c(o(((e,t)=>{var n=ec().assign,r=cc(),i=mc(),a=fc(),o={};n(o,r,i,a),t.exports=o}))()),gc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,_c=new Uint8Array(256),vc=0;vc>4,l[i++]=(o&15)<<4|s>>2,l[i++]=(s&3)<<6|c&63;return l},bc=function(e){for(var t=``,n=0;nr)throw Error(Fc(t)+` must be at least `+n+` and at most `+r+`, but was actually `+e)},qc=function(e,t,n,r){W(e,t,[`number`,`undefined`]),typeof e==`number`&&Kc(e,t,n,r)},Jc=function(e,t,n){if(W(e,t,[`number`]),e%n!==0)throw Error(Fc(t)+` must be a multiple of `+n+`, but was actually `+e)},Yc=function(e,t){if(!Number.isInteger(e))throw Error(Fc(t)+` must be an integer, but was actually `+e)},Xc=function(e,t){if(![1,0].includes(Math.sign(e)))throw Error(Fc(t)+` must be a positive number or 0, but was actually `+e)},Zc=new Uint16Array(256),Qc=0;Qc<256;Qc++)Zc[Qc]=Qc;Zc[22]=es(``),Zc[24]=es(`˘`),Zc[25]=es(`ˇ`),Zc[26]=es(`ˆ`),Zc[27]=es(`˙`),Zc[28]=es(`˝`),Zc[29]=es(`˛`),Zc[30]=es(`˚`),Zc[31]=es(`˜`),Zc[127]=es(`�`),Zc[128]=es(`•`),Zc[129]=es(`†`),Zc[130]=es(`‡`),Zc[131]=es(`…`),Zc[132]=es(`—`),Zc[133]=es(`–`),Zc[134]=es(`ƒ`),Zc[135]=es(`⁄`),Zc[136]=es(`‹`),Zc[137]=es(`›`),Zc[138]=es(`−`),Zc[139]=es(`‰`),Zc[140]=es(`„`),Zc[141]=es(`“`),Zc[142]=es(`”`),Zc[143]=es(`‘`),Zc[144]=es(`’`),Zc[145]=es(`‚`),Zc[146]=es(`™`),Zc[147]=es(`fi`),Zc[148]=es(`fl`),Zc[149]=es(`Ł`),Zc[150]=es(`Œ`),Zc[151]=es(`Š`),Zc[152]=es(`Ÿ`),Zc[153]=es(`Ž`),Zc[154]=es(`ı`),Zc[155]=es(`ł`),Zc[156]=es(`œ`),Zc[157]=es(`š`),Zc[158]=es(`ž`),Zc[159]=es(`�`),Zc[160]=es(`€`),Zc[173]=es(`�`);var $c=function(e){for(var t=Array(e.length),n=0,r=e.length;n=K.ExclamationPoint&&e<=K.Tilde&&!Il[e]},Vl={},Hl=new Map,J=function(e){U(t,e);function t(t,n){var r=this;if(t!==Vl)throw new nl(`PDFName`);r=e.call(this)||this;for(var i=`/`,a=0,o=n.length;a=K.Zero&&s<=K.Nine||s>=K.a&&s<=K.f||s>=K.A&&s<=K.F?(t+=o,(t.length===2||!(c>=`0`&&c<=`9`||c>=`a`&&c<=`f`||c>=`A`&&c<=`F`))&&(r(parseInt(t,16)),t=``)):r(s):s===K.Hash?n=!0:r(s)}return new Uint8Array(e)},t.prototype.decodeText=function(){var e=this.asBytes();return String.fromCharCode.apply(String,Array.from(e))},t.prototype.asString=function(){return this.encodedName},t.prototype.value=function(){return this.encodedName},t.prototype.clone=function(){return this},t.prototype.toString=function(){return this.encodedName},t.prototype.sizeInBytes=function(){return this.encodedName.length},t.prototype.copyBytesInto=function(e,t){return t+=ss(this.encodedName,e,t),this.encodedName.length},t.of=function(e){var n=zl(e),r=Hl.get(n);return r||(r=new t(Vl,n),Hl.set(n,r)),r},t.Length=t.of(`Length`),t.FlateDecode=t.of(`FlateDecode`),t.Resources=t.of(`Resources`),t.Font=t.of(`Font`),t.XObject=t.of(`XObject`),t.ExtGState=t.of(`ExtGState`),t.Contents=t.of(`Contents`),t.Type=t.of(`Type`),t.Parent=t.of(`Parent`),t.MediaBox=t.of(`MediaBox`),t.Page=t.of(`Page`),t.Annots=t.of(`Annots`),t.TrimBox=t.of(`TrimBox`),t.ArtBox=t.of(`ArtBox`),t.BleedBox=t.of(`BleedBox`),t.CropBox=t.of(`CropBox`),t.Rotate=t.of(`Rotate`),t.Title=t.of(`Title`),t.Author=t.of(`Author`),t.Subject=t.of(`Subject`),t.Creator=t.of(`Creator`),t.Keywords=t.of(`Keywords`),t.Producer=t.of(`Producer`),t.CreationDate=t.of(`CreationDate`),t.ModDate=t.of(`ModDate`),t}(Al),Ul=new(function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.asNull=function(){return null},t.prototype.clone=function(){return this},t.prototype.toString=function(){return`null`},t.prototype.sizeInBytes=function(){return 4},t.prototype.copyBytesInto=function(e,t){return e[t++]=K.n,e[t++]=K.u,e[t++]=K.l,e[t++]=K.l,4},t}(Al)),Wl=function(e){U(t,e);function t(t,n){var r=e.call(this)||this;return r.dict=t,r.context=n,r}return t.prototype.keys=function(){return Array.from(this.dict.keys())},t.prototype.values=function(){return Array.from(this.dict.values())},t.prototype.entries=function(){return Array.from(this.dict.entries())},t.prototype.set=function(e,t){this.dict.set(e,t)},t.prototype.get=function(e,t){t===void 0&&(t=!1);var n=this.dict.get(e);if(!(n===Ul&&!t))return n},t.prototype.has=function(e){var t=this.dict.get(e);return t!==void 0&&t!==Ul},t.prototype.lookupMaybe=function(e){for(var t,n=[],r=1;r>`,e},t.prototype.sizeInBytes=function(){for(var e=5,t=this.entries(),n=0,r=t.length;n>`,e},t.prototype.sizeInBytes=function(){for(var e=5,t=this.entries(),n=0,r=t.length;nthis.largestObjectNumber&&(this.largestObjectNumber=e.objectNumber)},e.prototype.nextRef=function(){return this.largestObjectNumber+=1,Ql.of(this.largestObjectNumber)},e.prototype.register=function(e){var t=this.nextRef();return this.assign(t,e),t},e.prototype.delete=function(e){return this.indirectObjects.delete(e)},e.prototype.lookupMaybe=function(e){for(var t=[],n=1;nthis.largestObjectNumber&&(this.largestObjectNumber=e.objectNumber)},e.prototype.nextRef=function(){return this.largestObjectNumber+=1,Yl.of(this.largestObjectNumber)},e.prototype.register=function(e){var t=this.nextRef();return this.assign(t,e),t},e.prototype.delete=function(e){return this.indirectObjects.delete(e)},e.prototype.lookupMaybe=function(e){for(var t=[],n=1;n1?(this.subsections.push([e]),this.chunkIdx+=1,this.chunkLength=1):(t.push(e),this.chunkLength+=1)},e.create=function(){return new e({ref:Ql.of(0,65535),offset:0,deleted:!0})},e.createEmpty=function(){return new e},e}(),uu=function(){function e(e){this.lastXRefOffset=String(e)}return e.prototype.toString=function(){return`startxref +`;for(var i=0,a=r.length;i1?(this.subsections.push([e]),this.chunkIdx+=1,this.chunkLength=1):(t.push(e),this.chunkLength+=1)},e.create=function(){return new e({ref:Yl.of(0,65535),offset:0,deleted:!0})},e.createEmpty=function(){return new e},e}(),su=function(){function e(e){this.lastXRefOffset=String(e)}return e.prototype.toString=function(){return`startxref `+this.lastXRefOffset+` -%%EOF`},e.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},e.prototype.copyBytesInto=function(e,t){var n=t;return e[t++]=K.s,e[t++]=K.t,e[t++]=K.a,e[t++]=K.r,e[t++]=K.t,e[t++]=K.x,e[t++]=K.r,e[t++]=K.e,e[t++]=K.f,e[t++]=K.Newline,t+=us(this.lastXRefOffset,e,t),e[t++]=K.Newline,e[t++]=K.Percent,e[t++]=K.Percent,e[t++]=K.E,e[t++]=K.O,e[t++]=K.F,t-n},e.forLastCrossRefSectionOffset=function(t){return new e(t)},e}(),du=function(){function e(e){this.dict=e}return e.prototype.toString=function(){return`trailer -`+this.dict.toString()},e.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},e.prototype.copyBytesInto=function(e,t){var n=t;return e[t++]=K.t,e[t++]=K.r,e[t++]=K.a,e[t++]=K.i,e[t++]=K.l,e[t++]=K.e,e[t++]=K.r,e[t++]=K.Newline,t+=this.dict.copyBytesInto(e,t),t-n},e.of=function(t){return new e(t)},e}(),fu=function(e){U(t,e);function t(t,n,r){r===void 0&&(r=!0);var i=e.call(this,t.obj({}),r)||this;return i.objects=n,i.offsets=i.computeObjectOffsets(),i.offsetsString=i.computeOffsetsString(),i.dict.set(J.of(`Type`),J.of(`ObjStm`)),i.dict.set(J.of(`N`),q.of(i.objects.length)),i.dict.set(J.of(`First`),q.of(i.offsetsString.length)),i}return t.prototype.getObjectsCount=function(){return this.objects.length},t.prototype.clone=function(e){return t.withContextAndObjects(e||this.dict.context,this.objects.slice(),this.encode)},t.prototype.getContentsString=function(){for(var e=this.offsetsString,t=0,n=this.objects.length;t1&&(e.push(t),e.push(a.ref.objectNumber),t=0),t+=1}return e.push(t),e},i.computeEntryTuples=function(){for(var e=Array(i.entries.length),t=0,n=i.entries.length;tt[0]&&(t[0]=l),u>t[1]&&(t[1]=u),d>t[2]&&(t[2]=d)}return t},i.entries=n||[],i.entryTuplesCache=rl.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=rl.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=rl.populatedBy(i.computeIndex),t.set(J.of(`Type`),J.of(`XRef`)),i}return t.prototype.addDeletedEntry=function(e,t){var n=hu.Deleted;this.entries.push({type:n,ref:e,nextFreeObjectNumber:t}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addUncompressedEntry=function(e,t){var n=hu.Uncompressed;this.entries.push({type:n,ref:e,offset:t}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addCompressedEntry=function(e,t,n){var r=hu.Compressed;this.entries.push({type:r,ref:e,objectStreamRef:t,index:n}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.clone=function(e){var n=this,r=n.dict,i=n.entries,a=n.encode;return t.of(r.clone(e),i.slice(),a)},t.prototype.getContentsString=function(){for(var e=this.entryTuplesCache.access(),t=this.maxByteWidthsCache.access(),n=``,r=0,i=e.length;r=0;f--)n+=(l[f]||0).toString(2);for(var f=t[1]-1;f>=0;f--)n+=(u[f]||0).toString(2);for(var f=t[2]-1;f>=0;f--)n+=(d[f]||0).toString(2)}return n},t.prototype.getUnencodedContents=function(){for(var e=this.entryTuplesCache.access(),t=this.maxByteWidthsCache.access(),n=new Uint8Array(this.getUnencodedContentsSize()),r=0,i=0,a=e.length;i=0;p--)n[r++]=u[p]||0;for(var p=t[1]-1;p>=0;p--)n[r++]=d[p]||0;for(var p=t[2]-1;p>=0;p--)n[r++]=f[p]||0}return n},t.prototype.getUnencodedContentsSize=function(){return Ms(this.maxByteWidthsCache.access())*this.entries.length},t.prototype.updateDict=function(){e.prototype.updateDict.call(this);var t=this.maxByteWidthsCache.access(),n=this.indexCache.access(),r=this.dict.context;this.dict.set(J.of(`W`),r.obj(t)),this.dict.set(J.of(`Index`),r.obj(n))},t.create=function(e,n){n===void 0&&(n=!0);var r=new t(e,[],n);return r.addDeletedEntry(Ql.of(0,65535),0),r},t.of=function(e,n,r){return r===void 0&&(r=!0),new t(e,n,r)},t}(nu),_u=function(e){U(t,e);function t(t,n,r,i){var a=e.call(this,t,n)||this;return a.encodeStreams=r,a.objectsPerStream=i,a}return t.prototype.computeBufferSize=function(){return qo(this,void 0,void 0,function(){var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,c,l,m,d,g,_,v,y;return Jo(this,function(b){switch(b.label){case 0:e=this.context.largestObjectNumber+1,t=Ml.forVersion(1,7),n=t.sizeInBytes()+2,r=gu.create(this.createTrailerDict(),this.encodeStreams),i=[],a=[],o=[],s=this.context.enumerateIndirectObjects(),c=0,l=s.length,b.label=1;case 1:return c`},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(e,t){return e[t++]=K.LessThan,t+=us(this.value,e,t),e[t++]=K.GreaterThan,this.value.length+2},t.of=function(e){return new t(e)},t.fromText=function(e){for(var n=Rs(e),r=``,i=0,a=n.length;i1&&(e.push(t),e.push(a.ref.objectNumber),t=0),t+=1}return e.push(t),e},i.computeEntryTuples=function(){for(var e=Array(i.entries.length),t=0,n=i.entries.length;tt[0]&&(t[0]=l),u>t[1]&&(t[1]=u),d>t[2]&&(t[2]=d)}return t},i.entries=n||[],i.entryTuplesCache=el.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=el.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=el.populatedBy(i.computeIndex),t.set(J.of(`Type`),J.of(`XRef`)),i}return t.prototype.addDeletedEntry=function(e,t){var n=fu.Deleted;this.entries.push({type:n,ref:e,nextFreeObjectNumber:t}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addUncompressedEntry=function(e,t){var n=fu.Uncompressed;this.entries.push({type:n,ref:e,offset:t}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addCompressedEntry=function(e,t,n){var r=fu.Compressed;this.entries.push({type:r,ref:e,objectStreamRef:t,index:n}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.clone=function(e){var n=this,r=n.dict,i=n.entries,a=n.encode;return t.of(r.clone(e),i.slice(),a)},t.prototype.getContentsString=function(){for(var e=this.entryTuplesCache.access(),t=this.maxByteWidthsCache.access(),n=``,r=0,i=e.length;r=0;f--)n+=(l[f]||0).toString(2);for(var f=t[1]-1;f>=0;f--)n+=(u[f]||0).toString(2);for(var f=t[2]-1;f>=0;f--)n+=(d[f]||0).toString(2)}return n},t.prototype.getUnencodedContents=function(){for(var e=this.entryTuplesCache.access(),t=this.maxByteWidthsCache.access(),n=new Uint8Array(this.getUnencodedContentsSize()),r=0,i=0,a=e.length;i=0;p--)n[r++]=u[p]||0;for(var p=t[1]-1;p>=0;p--)n[r++]=d[p]||0;for(var p=t[2]-1;p>=0;p--)n[r++]=f[p]||0}return n},t.prototype.getUnencodedContentsSize=function(){return ks(this.maxByteWidthsCache.access())*this.entries.length},t.prototype.updateDict=function(){e.prototype.updateDict.call(this);var t=this.maxByteWidthsCache.access(),n=this.indexCache.access(),r=this.dict.context;this.dict.set(J.of(`W`),r.obj(t)),this.dict.set(J.of(`Index`),r.obj(n))},t.create=function(e,n){n===void 0&&(n=!0);var r=new t(e,[],n);return r.addDeletedEntry(Yl.of(0,65535),0),r},t.of=function(e,n,r){return r===void 0&&(r=!0),new t(e,n,r)},t}($l),mu=function(e){U(t,e);function t(t,n,r,i){var a=e.call(this,t,n)||this;return a.encodeStreams=r,a.objectsPerStream=i,a}return t.prototype.computeBufferSize=function(){return Wo(this,void 0,void 0,function(){var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,c,l,m,d,g,_,v,y;return Go(this,function(b){switch(b.label){case 0:e=this.context.largestObjectNumber+1,t=kl.forVersion(1,7),n=t.sizeInBytes()+2,r=pu.create(this.createTrailerDict(),this.encodeStreams),i=[],a=[],o=[],s=this.context.enumerateIndirectObjects(),c=0,l=s.length,b.label=1;case 1:return c`},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(e,t){return e[t++]=K.LessThan,t+=ss(this.value,e,t),e[t++]=K.GreaterThan,this.value.length+2},t.of=function(e){return new t(e)},t.fromText=function(e){for(var n=Fs(e),r=``,i=0,a=n.length;i`},Su=function(e){return as(e,4)},Cu=function(e){if(zs(e))return Su(e);if(Bs(e)){var t=Vs(e),n=Hs(e);return``+Su(t)+Su(n)}var r=`0x`+os(e)+` is not a valid UTF-8 or UTF-16 codepoint.`;throw Error(r)},wu=function(e){var t=0,n=function(e){t|=1<=K.Zero&&s<=K.Seven?(t+=o,(t.length===3||!(c>=`0`&&c<=`7`))&&(r(parseInt(t,8)),t=``)):r(s):s===K.BackSlash?n=!0:r(s)}return new Uint8Array(e)},t.prototype.decodeText=function(){var e=this.asBytes();return Qs(e)?Gs(e):nl(e)},t.prototype.decodeDate=function(){var e=this.decodeText(),t=Ss(e);if(!t)throw new pl(e);return t},t.prototype.asString=function(){return this.value},t.prototype.clone=function(){return t.of(this.value)},t.prototype.toString=function(){return`(`+this.value+`)`},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(e,t){return e[t++]=K.LeftParen,t+=us(this.value,e,t),e[t++]=K.RightParen,this.value.length+2},t.of=function(e){return new t(e)},t.fromDate=function(e){var n=ls(String(e.getUTCFullYear()),4,`0`),r=ls(String(e.getUTCMonth()+1),2,`0`),i=ls(String(e.getUTCDate()),2,`0`),a=ls(String(e.getUTCHours()),2,`0`),o=ls(String(e.getUTCMinutes()),2,`0`),s=ls(String(e.getUTCSeconds()),2,`0`);return new t(`D:`+n+r+i+a+o+s+`Z`)},t}(Nl),Du=function(){function e(e,t,n,r){var i=this;this.allGlyphsInFontSortedById=function(){for(var e=Array(i.font.characterSet.length),t=0,n=e.length;t>3)]>>7-((p&7)<<0)&1,D=3*E;s[y]=b[D],s[y+1]=b[D+1],s[y+2]=b[D+2],s[y+3]=E>2)]>>6-((p&3)<<1)&3,D=3*E;s[y]=b[D],s[y+1]=b[D+1],s[y+2]=b[D+2],s[y+3]=E>1)]>>4-((p&1)<<2)&15,D=3*E;s[y]=b[D],s[y+1]=b[D+1],s[y+2]=b[D+2],s[y+3]=E>>3)]>>>7-(j&7)&1),te=k==g*255?0:255;c[A+j]=te<<24|k<<16|k<<8|k}else if(u==2)for(var j=0;j>>2)]>>>6-((j&3)<<1)&3),te=k==g*85?0:255;c[A+j]=te<<24|k<<16|k<<8|k}else if(u==4)for(var j=0;j>>1)]>>>4-((j&1)<<2)&15),te=k==g*17?0:255;c[A+j]=te<<24|k<<16|k<<8|k}else if(u==8)for(var j=0;j>>2<<3));i==0;){if(i=g(t,f,1),a=g(t,f+1,2),f+=3,a==0){f&7&&(f+=8-(f&7));var w=(f>>>3)+4,T=t[w-4]|t[w-3]<<8;C&&(n=e.H.W(n,d+T)),n.set(new r(t.buffer,t.byteOffset+w,T),d),f=w+T<<3,d+=T;continue}if(C&&(n=e.H.W(n,d+(1<<17))),a==1&&(p=S.J,m=S.h,l=511,u=31),a==2){o=_(t,f,5)+257,s=_(t,f+5,5)+1,c=_(t,f+10,4)+4,f+=14;for(var E=1,D=0;D<38;D+=2)S.Q[D]=0,S.Q[D+1]=0;for(var D=0;DE&&(E=O)}f+=3*c,y(S.Q,E),b(S.Q,E,S.u),p=S.w,m=S.d,f=v(S.u,(1<>>4;if(!(j>>>8))n[d++]=j;else if(j==256)break;else{var te=d+j-254;if(j>264){var ne=S.q[j-257];te=d+(ne>>>3)+_(t,f,ne&7),f+=ne&7}var re=m[x(t,f)&u];f+=re&15;var ie=re>>>4,ae=S.c[ie],oe=(ae>>>4)+g(t,f,ae&15);for(f+=ae&15;d>>4;if(d<=15)o[l]=d,l++;else{var f=0,p=0;d==16?(p=3+s(i,a,2),a+=2,f=o[l-1]):d==17?(p=3+s(i,a,3),a+=3):d==18&&(p=11+s(i,a,7),a+=7);for(var m=l+p;l>>1;ai&&(i=s),a++}for(;a>1,c=t[o+1],l=s<<4|c,u=n-c,d=t[o]<>>15-n;r[p]=l,d++}},e.H.l=function(t,n){for(var r=e.H.m.r,i=15-n,a=0;a>>i},e.H.M=function(e,t,n){n<<=t&7;var r=t>>>3;e[r]|=n,e[r+1]|=n>>>8},e.H.I=function(e,t,n){n<<=t&7;var r=t>>>3;e[r]|=n,e[r+1]|=n>>>8,e[r+2]|=n>>>16},e.H.e=function(e,t,n){return(e[t>>>3]|e[(t>>>3)+1]<<8)>>>(t&7)&(1<>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)&(1<>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)},e.H.i=function(e,t){return(e[t>>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16|e[(t>>>3)+3]<<24)>>>(t&7)},e.H.m=function(){var e=Uint16Array,t=Uint32Array;return{K:new e(16),j:new e(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new e(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new t(32),J:new e(512),_:[],h:new e(32),$:[],w:new e(32768),C:[],v:[],d:new e(32768),D:[],u:new e(512),Q:[],r:new e(32768),s:new t(286),Y:new t(30),a:new t(19),t:new t(15e3),k:new e(65536),g:new e(32768)}}(),(function(){for(var t=e.H.m,n=32768,r=0;r>>1|(i&1431655765)<<1,i=(i&3435973836)>>>2|(i&858993459)<<2,i=(i&4042322160)>>>4|(i&252645135)<<4,i=(i&4278255360)>>>8|(i&16711935)<<8,t.r[r]=(i>>>16|i<<16)>>>17}function a(e,t,n){for(;t--!=0;)e.push(0,n)}for(var r=0;r<32;r++)t.q[r]=t.S[r]<<3|t.T[r],t.c[r]=t.p[r]<<4|t.z[r];a(t._,144,8),a(t._,112,9),a(t._,24,7),a(t._,8,8),e.H.n(t._,9),e.H.A(t._,9,t.J),e.H.l(t._,9),a(t.$,32,5),e.H.n(t.$,5),e.H.A(t.$,5,t.h),e.H.l(t.$,5),a(t.Q,19,0),a(t.C,286,0),a(t.D,30,0),a(t.v,320,0)})(),e.H.N}(),X.decode._readInterlace=function(e,t){for(var n=t.width,r=t.height,i=X.decode._getBPP(t),a=i>>3,o=Math.ceil(n*i/8),s=new Uint8Array(r*o),c=0,l=[0,0,4,0,2,0,1],u=[0,4,0,2,0,1,0],d=[8,8,8,4,4,2,2],f=[8,8,4,4,2,2,1],p=0;p<7;){for(var m=d[p],h=f[p],g=0,_=0,v=l[p];v>3];T=T>>7-(w&7)&1,s[S*o+(C>>3)]|=T<<7-((C&7)<<0)}if(i==2){var T=e[w>>3];T=T>>6-(w&7)&3,s[S*o+(C>>2)]|=T<<6-((C&3)<<1)}if(i==4){var T=e[w>>3];T=T>>4-(w&7)&15,s[S*o+(C>>1)]|=T<<4-((C&1)<<2)}if(i>=8)for(var E=S*o+C*a,D=0;D>3)+D];w+=i,C+=h}x++,S+=m}g*_!=0&&(c+=_*(1+b)),p+=1}return s},X.decode._getBPP=function(e){return[1,null,3,1,2,null,4][e.ctype]*e.depth},X.decode._filterZero=function(e,t,n,r,i){var a=X.decode._getBPP(t),o=Math.ceil(r*a/8),s=X.decode._paeth;a=Math.ceil(a/8);var c=0,l=1,u=e[n],d=0;if(u>1&&(e[n]=[0,0,1][u-2]),u==3)for(d=a;d>>1)&255;for(var f=0;f>>1);for(;d>>1)}else{for(;d>8&255,e[t+1]=n&255},readUint:function(e,t){return e[t]*(256*256*256)+(e[t+1]<<16|e[t+2]<<8|e[t+3])},writeUint:function(e,t,n){e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255},readASCII:function(e,t,n){for(var r=``,i=0;i=0&&s>=0?(d=p*t+m<<2,f=(s+p)*i+o+m<<2):(d=(-s+p)*t-o+m<<2,f=p*i+m<<2),c==0)r[f]=e[d],r[f+1]=e[d+1],r[f+2]=e[d+2],r[f+3]=e[d+3];else if(c==1){var h=e[d+3]*(1/255),g=e[d]*h,_=e[d+1]*h,v=e[d+2]*h,y=r[f+3]*(1/255),b=r[f]*y,x=r[f+1]*y,S=r[f+2]*y,C=1-h,w=h+y*C,T=w==0?0:1/w;r[f+3]=255*w,r[f+0]=(g+b*C)*T,r[f+1]=(_+x*C)*T,r[f+2]=(v+S*C)*T}else if(c==2){var h=e[d+3],g=e[d],_=e[d+1],v=e[d+2],y=r[f+3],b=r[f],x=r[f+1],S=r[f+2];h==y&&g==b&&_==x&&v==S?(r[f]=0,r[f+1]=0,r[f+2]=0,r[f+3]=0):(r[f]=g,r[f+1]=_,r[f+2]=v,r[f+3]=h)}else if(c==3){var h=e[d+3],g=e[d],_=e[d+1],v=e[d+2],y=r[f+3],b=r[f],x=r[f+1],S=r[f+2];if(h==y&&g==b&&_==x&&v==S)continue;if(h<220&&y>20)return!1}return!0},X.encode=function(e,t,n,r,i,a,o){r??(r=0),o??(o=!1);var s=X.encode.compress(e,t,n,r,[!1,!1,!1,0,o]);return X.encode.compressPNG(s,-1),X.encode._main(s,t,n,i,a)},X.encodeLL=function(e,t,n,r,i,a,o,s){for(var c={ctype:0+(r==1?0:2)+(i==0?0:4),depth:a,frames:[]},l=(r+i)*a,u=l*t,d=0;d1,d=!1,f=33+(u?20:0);if(i.sRGB!=null&&(f+=13),i.pHYs!=null&&(f+=21),e.ctype==3){for(var p=e.plte.length,m=0;m>>24!=255&&(d=!0);f+=8+p*3+4+(d?8+p*1+4:0)}for(var h=0;h>>8&255,C=b>>>16&255;_[l+y+0]=x,_[l+y+1]=S,_[l+y+2]=C}if(l+=p*3,o(_,l,a(_,l-p*3-4,p*3+4)),l+=4,d){o(_,l,p),l+=4,c(_,l,`tRNS`),l+=4;for(var m=0;m>>24&255;l+=p,o(_,l,a(_,l-p-4,p+4)),l+=4}}for(var w=0,h=0;h>2,O>>2));for(var p=0;pA&&te==ee[g-A])j[g]=j[g-A];else{var ne=y[te];if(ne==null&&(y[te]=ne=b.length,b.push(te),b.length>=300))break;j[g]=ne}}}var re=b.length;re<=256&&l==0&&(d=re<=2?1:re<=4?2:re<=16?4:8,d=Math.max(d,c));for(var p=0;p>1)]|=le[M+N]<<4-(N&1)*4;else if(d==2)for(var N=0;N>2)]|=le[M+N]<<6-(N&3)*2;else if(d==1)for(var N=0;N>3)]|=le[M+N]<<7-(N&7)*1}ae=ce,u=3,se=1}else if(_==0&&v.length==1){for(var ce=new Uint8Array(A*ie*3),de=A*ie,g=0;gw&&(w=D),ET&&(T=E))}w==-1&&(S=C=w=T=0),i&&((S&1)==1&&S--,(C&1)==1&&C--);var k=(w-S+1)*(T-C+1);kg&&(g=b),x_&&(_=x))}g==-1&&(m=h=g=_=0),o&&((m&1)==1&&m--,(h&1)==1&&h--),a={x:m,y:h,width:g-m+1,height:_-h+1};var w=r[i];w.rect=a,w.blend=1,w.img=new Uint8Array(a.width*a.height*4),r[i-1].dispose==0?(X._copyTile(l,t,n,w.img,a.width,a.height,-a.x,-a.y,0),X.encode._prepareDiff(f,t,n,w.img,a)):X._copyTile(f,t,n,w.img,a.width,a.height,-a.x,-a.y,0)},X.encode._prepareDiff=function(e,t,n,r,i){X._copyTile(e,t,n,r,i.width,i.height,-i.x,-i.y,2)},X.encode._filterZero=function(e,t,n,r,i,a,o){var s=[],c=[0,1,2,3,4];a==-1?(t*r>5e5||n==1)&&(c=[0]):c=[a];var l;o&&(l={level:0});for(var u=o&&UZIP!=null?UZIP:vc.default,d=0;d>1)+256&255;if(a==4)for(var l=i;l>1)&255;for(var l=i;l>1)&255}if(a==4){for(var l=0;l>>1:n>>>=1;e[t]=n}return e})(),update:function(e,t,n,r){for(var i=0;i>>8;return e},crc:function(e,t,n){return X.crc.update(4294967295,e,t,n)^4294967295}},X.quantize=function(e,t){var n=new Uint8Array(e),r=n.slice(0),i=new Uint32Array(r.buffer),a=X.quantize.getKDtree(r,t),o=a[0],s=a[1];X.quantize.planeDst;for(var c=n,l=i,u=c.length,d=new Uint8Array(n.length>>2),f=0;f>2]=_.ind,l[f>>2]=_.est.rgba}return{abuf:r.buffer,inds:d,plte:s}},X.quantize.getKDtree=function(e,t,n){n??(n=1e-4);var r=new Uint32Array(e.buffer),i={i0:0,i1:e.length,bst:null,est:null,tdst:0,left:null,right:null};i.bst=X.quantize.stats(e,i.i0,i.i1),i.est=X.quantize.estats(i.bst);for(var a=[i];a.lengtho&&(o=a[c].est.L,s=c);if(o=u||l.i1<=u){l.est.L=0;continue}var d={i0:l.i0,i1:u,bst:null,est:null,tdst:0,left:null,right:null};d.bst=X.quantize.stats(e,d.i0,d.i1),d.est=X.quantize.estats(d.bst);var f={i0:u,i1:l.i1,bst:null,est:null,tdst:0,left:null,right:null};f.bst={R:[],m:[],N:l.bst.N-d.bst.N};for(var c=0;c<16;c++)f.bst.R[c]=l.bst.R[c]-d.bst.R[c];for(var c=0;c<4;c++)f.bst.m[c]=l.bst.m[c]-d.bst.m[c];f.est=X.quantize.estats(f.bst),l.left=d,l.right=f,a[s]=d,a.push(f)}a.sort(function(e,t){return t.bst.N-e.bst.N});for(var c=0;c0&&(o=e.right,s=e.left);var c=X.quantize.getNearest(o,t,n,r,i);if(c.tdst<=a*a)return c;var l=X.quantize.getNearest(s,t,n,r,i);return l.tdsta;)r-=4;if(n>=r)break;var s=t[n>>2];t[n>>2]=t[r>>2],t[r>>2]=s,n+=4,r-=4}for(;o(e,n,i)>a;)n-=4;return n+4},X.quantize.vecDot=function(e,t,n){return e[t]*n[0]+e[t+1]*n[1]+e[t+2]*n[2]+e[t+3]*n[3]},X.quantize.stats=function(e,t,n){for(var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],i=[0,0,0,0],a=n-t>>2,o=t;o>>0}},X.M4={multVec:function(e,t){return[e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],e[4]*t[0]+e[5]*t[1]+e[6]*t[2]+e[7]*t[3],e[8]*t[0]+e[9]*t[1]+e[10]*t[2]+e[11]*t[3],e[12]*t[0]+e[13]*t[1]+e[14]*t[2]+e[15]*t[3]]},dot:function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},sml:function(e,t){return[e*t[0],e*t[1],e*t[2],e*t[3]]}},X.encode.concatRGBA=function(e){for(var t=0,n=0;n1)throw Error(`Animated PNGs are not supported`);var r=Iu(new Uint8Array(n[0])),i=r.rgbChannel,a=r.alphaChannel;this.rgbChannel=i,a.some(function(e){return e<255})&&(this.alphaChannel=a),this.type=Fu(t.ctype),this.width=t.width,this.height=t.height,this.bitsPerComponent=8}return e.load=function(t){return new e(t)},e}(),zu=function(){function e(e){this.image=e,this.bitsPerComponent=e.bitsPerComponent,this.width=e.width,this.height=e.height,this.colorSpace=`DeviceRGB`}return e.for=function(t){return qo(this,void 0,void 0,function(){var n;return Jo(this,function(r){return n=Ru.load(t),[2,new e(n)]})})},e.prototype.embedIntoContext=function(e,t){return qo(this,void 0,void 0,function(){var n,r;return Jo(this,function(i){return n=this.embedAlphaChannel(e),r=e.flateStream(this.image.rgbChannel,{Type:`XObject`,Subtype:`Image`,BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:n}),t?(e.assign(t,r),[2,t]):[2,e.register(r)]})})},e.prototype.embedAlphaChannel=function(e){if(this.image.alphaChannel){var t=e.flateStream(this.image.alphaChannel,{Type:`XObject`,Subtype:`Image`,Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:`DeviceGray`,Decode:[0,1]});return e.register(t)}},e}(),Bu=function(){function e(e,t,n){this.bytes=e,this.start=t||0,this.pos=this.start,this.end=t&&n?t+n:this.bytes.length}return Object.defineProperty(e.prototype,`length`,{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,`isEmpty`,{get:function(){return this.length===0},enumerable:!1,configurable:!0}),e.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},e.prototype.getUint16=function(){var e=this.getByte(),t=this.getByte();return e===-1||t===-1?-1:(e<<8)+t},e.prototype.getInt32=function(){var e=this.getByte(),t=this.getByte(),n=this.getByte(),r=this.getByte();return(e<<24)+(t<<16)+(n<<8)+r},e.prototype.getBytes=function(e,t){t===void 0&&(t=!1);var n=this.bytes,r=this.pos,i=this.end;if(e){var a=r+e;a>i&&(a=i),this.pos=a;var o=n.subarray(r,a);return t?new Uint8ClampedArray(o):o}else{var o=n.subarray(r,i);return t?new Uint8ClampedArray(o):o}},e.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},e.prototype.peekBytes=function(e,t){t===void 0&&(t=!1);var n=this.getBytes(e,t);return this.pos-=n.length,n},e.prototype.skip=function(e){e||(e=1),this.pos+=e},e.prototype.reset=function(){this.pos=this.start},e.prototype.moveStart=function(){this.start=this.pos},e.prototype.makeSubStream=function(t,n){return new e(this.bytes,t,n)},e.prototype.decode=function(){return this.bytes},e}(),Vu=new Uint8Array,Hu=function(){function e(e){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=Vu,this.minBufferLength=512,e)for(;this.minBufferLengthi&&(n=i)}else{for(;!this.eof;)this.readBlock();n=this.bufferLength}this.pos=n;var a=this.buffer.subarray(r,n);return t&&!(a instanceof Uint8ClampedArray)?new Uint8ClampedArray(a):a},e.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},e.prototype.peekBytes=function(e,t){t===void 0&&(t=!1);var n=this.getBytes(e,t);return this.pos-=n.length,n},e.prototype.skip=function(e){e||(e=1),this.pos+=e},e.prototype.reset=function(){this.pos=0},e.prototype.makeSubStream=function(e,t){for(var n=e+t;this.bufferLength<=n&&!this.eof;)this.readBlock();return new Bu(this.buffer,e,t)},e.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},e.prototype.readBlock=function(){throw new il(this.constructor.name,`readBlock`)},e.prototype.ensureBuffer=function(e){var t=this.buffer;if(e<=t.byteLength)return t;for(var n=this.minBufferLength;n=0;--s)o[a+s]=l&255,l>>=8}},t}(Hu),Gu=function(e){U(t,e);function t(t,n){var r=e.call(this,n)||this;return r.stream=t,r.firstDigit=-1,n&&(n=.5*n),r}return t.prototype.readBlock=function(){var e=this.stream.getBytes(8e3);if(!e.length){this.eof=!0;return}for(var t=e.length+1>>1,n=this.ensureBuffer(this.bufferLength+t),r=this.bufferLength,i=this.firstDigit,a=0,o=e.length;a=48&&s<=57)c=s&15;else if(s>=65&&s<=70||s>=97&&s<=102)c=(s&15)+9;else if(s===62){this.eof=!0;break}else continue;i<0?i=c:(n[r++]=i<<4|c,i=-1)}i>=0&&this.eof&&(n[r++]=i<<4,i=-1),this.firstDigit=i,this.bufferLength=r},t}(Hu),Ku=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qu=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),Ju=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Yu=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Xu=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],Zu=function(e){U(t,e);function t(t,n){var r=e.call(this,n)||this;r.stream=t;var i=t.getByte(),a=t.getByte();if(i===-1||a===-1)throw Error(`Invalid header in flate stream: `+i+`, `+a);if((i&15)!=8)throw Error(`Unknown compression method in flate stream: `+i+`, `+a);if(((i<<8)+a)%31!=0)throw Error(`Bad FCHECK in flate stream: `+i+`, `+a);if(a&32)throw Error(`FDICT bit set in flate stream: `+i+`, `+a);return r.codeSize=0,r.codeBuf=0,r}return t.prototype.readBlock=function(){var e,t,n=this.stream,r=this.getBits(3);if(r&1&&(this.eof=!0),r>>=1,r===0){var i=void 0;if((i=n.getByte())===-1)throw Error(`Bad block header in flate stream`);var a=i;if((i=n.getByte())===-1||(a|=i<<8,(i=n.getByte())===-1))throw Error(`Bad block header in flate stream`);var o=i;if((i=n.getByte())===-1)throw Error(`Bad block header in flate stream`);if(o|=i<<8,o!==(~a&65535)&&(a!==0||o!==0))throw Error(`Bad uncompressed block length in flate stream`);this.codeBuf=0,this.codeSize=0;var s=this.bufferLength;e=this.ensureBuffer(s+a);var c=s+a;if(this.bufferLength=c,a===0)n.peekByte()===-1&&(this.eof=!0);else for(var l=s;l0;)y[g++]=S}u=this.generateHuffmanTable(y.subarray(0,f)),d=this.generateHuffmanTable(y.subarray(f,v))}else throw Error(`Unknown block type in flate stream`);e=this.buffer;for(var T=e?e.length:0,E=this.bufferLength;;){var D=this.getCode(u);if(D<256){E+1>=T&&(e=this.ensureBuffer(E+1),T=e.length),e[E++]=D;continue}if(D===256){this.bufferLength=E;return}D-=257,D=qu[D];var O=D>>16;O>0&&(O=this.getBits(O)),t=(D&65535)+O,D=this.getCode(d),D=Ju[D],O=D>>16,O>0&&(O=this.getBits(O));var k=(D&65535)+O;E+t>=T&&(e=this.ensureBuffer(E+t),T=e.length);for(var ee=0;ee>e,this.codeSize=n-=e,i},t.prototype.getCode=function(e){for(var t=this.stream,n=e[0],r=e[1],i=this.codeSize,a=this.codeBuf,o;i>16,l=s&65535;if(c<1||i>c,this.codeSize=i-c,l},t.prototype.generateHuffmanTable=function(e){var t=e.length,n=0,r;for(r=0;rn&&(n=e[r]);for(var i=1<>=1;for(r=u;r0;if(!y||y<256)m[0]=y,h=1;else if(y>=258)if(y=0;i--)m[i]=l[a],a=d[a];else m[h++]=m[0];else if(y===256){f=9,c=258,h=0;continue}else{this.eof=!0,delete this.lzwState;break}if(b&&(d[c]=p,u[c]=u[p]+1,l[c]=m[0],c++,f=c+s&c+s-1?f:Math.min(Math.log(c+s)/.6931471805599453+1,12)|0),p=y,g+=h,t>>t&(1<0){var i=this.stream.getBytes(r);t.set(i,n),n+=r}}else{r=257-r;var a=e[1];t=this.ensureBuffer(n+r+1);for(var o=0;ot.size())throw new gl(e,0,t.size());t.remove(e)}else{if(e!==0)throw new gl(e,0,0);this.setKids([])}},t.prototype.normalizedEntries=function(){var e=this.Kids();return e||(e=this.dict.context.obj([this.ref]),this.dict.set(J.of(`Kids`),e)),{Kids:e}},t.fromDict=function(e,n){return new t(e,n)},t}(fd),vd=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.Opt=function(){return this.dict.lookupMaybe(J.of(`Opt`),Eu,Y,Pl)},t.prototype.setOpt=function(e){this.dict.set(J.of(`Opt`),this.dict.context.obj(e))},t.prototype.getExportValues=function(){var e=this.Opt();if(e){if(e instanceof Eu||e instanceof Y)return[e];for(var t=[],n=0,r=e.size();nt.size())throw new gl(e,0,t.size());t.remove(e)}},t.prototype.normalizeExportValues=function(){for(var e=this.getExportValues()??[],t=[],n=this.getWidgets(),r=0,i=n.length;r1){if(!this.hasFlag(wd.MultiSelect))throw new vl;this.dict.set(J.of(`V`),this.dict.context.obj(e))}this.updateSelectedIndices(e)},t.prototype.valuesAreValid=function(e){for(var t=this.getOptions(),n=function(n,r){var i=e[n].decodeText();if(!t.find(function(e){return i===(e.display||e.value).decodeText()}))return{value:!1}},r=0,i=e.length;r1){for(var t=Array(e.length),n=this.getOptions(),r=function(r,i){var a=e[r].decodeText();t[r]=n.findIndex(function(e){return a===(e.display||e.value).decodeText()})},i=0,a=e.length;i0){var a=i.lookup(0,Eu,Y),o=i.lookupMaybe(1,Eu,Y);t.push({value:a,display:o||a})}}return t}return[]},t}(_d),Ed=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.fromDict=function(e,n){return new t(e,n)},t.create=function(e){var n=e.obj({FT:`Ch`,Ff:wd.Combo,Kids:[]});return new t(n,e.register(n))},t}(Td),Dd=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.addField=function(e){this.normalizedEntries().Kids?.push(e)},t.prototype.normalizedEntries=function(){var e=this.Kids();return e||(e=this.dict.context.obj([]),this.dict.set(J.of(`Kids`),e)),{Kids:e}},t.fromDict=function(e,n){return new t(e,n)},t.create=function(e){var n=e.obj({});return new t(n,e.register(n))},t}(fd),Od=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.fromDict=function(e,n){return new t(e,n)},t}(_d),kd=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.MaxLen=function(){var e=this.dict.lookup(J.of(`MaxLen`));if(e instanceof q)return e},t.prototype.Q=function(){var e=this.dict.lookup(J.of(`Q`));if(e instanceof q)return e},t.prototype.setMaxLength=function(e){this.dict.set(J.of(`MaxLen`),q.of(e))},t.prototype.removeMaxLength=function(){this.dict.delete(J.of(`MaxLen`))},t.prototype.getMaxLength=function(){return this.MaxLen()?.asNumber()},t.prototype.setQuadding=function(e){this.dict.set(J.of(`Q`),q.of(e))},t.prototype.getQuadding=function(){return this.Q()?.asNumber()},t.prototype.setValue=function(e){this.dict.set(J.of(`V`),e)},t.prototype.removeValue=function(){this.dict.delete(J.of(`V`))},t.prototype.getValue=function(){var e=this.V();if(e instanceof Eu||e instanceof Y)return e},t.fromDict=function(e,n){return new t(e,n)},t.create=function(e){var n=e.obj({FT:`Tx`,Kids:[]});return new t(n,e.register(n))},t}(_d),Ad=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.fromDict=function(e,n){return new t(e,n)},t.create=function(e){var n=e.obj({FT:`Btn`,Ff:Sd.PushButton,Kids:[]});return new t(n,e.register(n))},t}(vd),jd=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.setValue=function(e){if(!this.getOnValues().includes(e)&&e!==J.of(`Off`))throw new _l;this.dict.set(J.of(`V`),e);for(var t=this.getWidgets(),n=0,r=t.length;ni)throw new ml(n,i);for(var a=n,o=0,s=r.size();oa)return l.insertLeafNode(e,a)||c;a-=l.Count().asNumber()}l instanceof su&&--a}if(a===0){this.insertLeafKid(r.size(),e);return}throw new hl(n,`insertLeafNode`)},t.prototype.removeLeafNode=function(e,n){n===void 0&&(n=!0);var r=this.Kids(),i=this.Count().asNumber();if(e>=i)throw new ml(e,i);for(var a=e,o=0,s=r.size();oa){l.removeLeafNode(a,n),n&&l.Kids().size()===0&&r.remove(o);return}else a-=l.Count().asNumber();if(l instanceof su)if(a===0){this.removeKid(o);return}else --a}throw new hl(e,`removeLeafNode`)},t.prototype.ascend=function(e){e(this);var t=this.Parent();t&&t.ascend(e)},t.prototype.traverse=function(e){for(var n=this.Kids(),r=0,i=n.size();r2**53-1)if(this.capNumbers){var r=`Parsed number that is too large for some PDF readers: `+e+`, using Number.MAX_SAFE_INTEGER instead.`;return console.warn(r),2**53-1}else{var r=`Parsed number that is too large for some PDF readers: `+e+`, not capping.`;console.warn(r)}return n},e.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&Rl[this.bytes.peek()];)this.bytes.next()},e.prototype.skipLine=function(){for(;!this.bytes.done();){var e=this.bytes.peek();if(e===Xd||e===Zd)return;this.bytes.next()}},e.prototype.skipComment=function(){if(this.bytes.peek()!==K.Percent)return!1;for(;!this.bytes.done();){var e=this.bytes.peek();if(e===Xd||e===Zd)return!0;this.bytes.next()}return!0},e.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},e.prototype.matchKeyword=function(e){for(var t=this.bytes.offset(),n=0,r=e.length;n=this.length},e.prototype.offset=function(){return this.idx},e.prototype.slice=function(e,t){return this.bytes.slice(e,t)},e.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},e.of=function(t){return new e(t)},e.fromPDFRawStream=function(t){return e.of(td(t).decode())},e}(),ef=K.Space,tf=K.CarriageReturn,nf=K.Newline,rf=[K.s,K.t,K.r,K.e,K.a,K.m],af=[K.e,K.n,K.d,K.s,K.t,K.r,K.e,K.a,K.m],of={header:[K.Percent,K.P,K.D,K.F,K.Dash],eof:[K.Percent,K.Percent,K.E,K.O,K.F],obj:[K.o,K.b,K.j],endobj:[K.e,K.n,K.d,K.o,K.b,K.j],xref:[K.x,K.r,K.e,K.f],trailer:[K.t,K.r,K.a,K.i,K.l,K.e,K.r],startxref:[K.s,K.t,K.a,K.r,K.t,K.x,K.r,K.e,K.f],true:[K.t,K.r,K.u,K.e],false:[K.f,K.a,K.l,K.s,K.e],null:[K.n,K.u,K.l,K.l],stream:rf,streamEOF1:Yo(rf,[ef,tf,nf]),streamEOF2:Yo(rf,[tf,nf]),streamEOF3:Yo(rf,[tf]),streamEOF4:Yo(rf,[nf]),endstream:af,EOF1endstream:Yo([tf,nf],af),EOF2endstream:Yo([tf],af),EOF3endstream:Yo([nf],af)},sf=function(e){U(t,e);function t(t,n,r){r===void 0&&(r=!1);var i=e.call(this,t,r)||this;return i.context=n,i}return t.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(of.true))return Il.True;if(this.matchKeyword(of.false))return Il.False;if(this.matchKeyword(of.null))return Kl;var e=this.bytes.peek();if(e===K.LessThan&&this.bytes.peekAhead(1)===K.LessThan)return this.parseDictOrStream();if(e===K.LessThan)return this.parseHexString();if(e===K.LeftParen)return this.parseString();if(e===K.ForwardSlash)return this.parseName();if(e===K.LeftSquareBracket)return this.parseArray();if(qd[e])return this.parseNumberOrRef();throw new wl(this.bytes.position(),e)},t.prototype.parseNumberOrRef=function(){var e=this.parseRawNumber();this.skipWhitespaceAndComments();var t=this.bytes.offset();if(Gd[this.bytes.peek()]){var n=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===K.R)return this.bytes.assertNext(K.R),Ql.of(e,n)}return this.bytes.moveTo(t),q.of(e)},t.prototype.parseHexString=function(){var e=``;for(this.bytes.assertNext(K.LessThan);!this.bytes.done()&&this.bytes.peek()!==K.GreaterThan;)e+=ss(this.bytes.next());return this.bytes.assertNext(K.GreaterThan),Y.of(e)},t.prototype.parseString=function(){for(var e=0,t=!1,n=``;!this.bytes.done();){var r=this.bytes.next();if(n+=ss(r),t||(r===K.LeftParen&&(e+=1),r===K.RightParen&&--e),r===K.BackSlash?t=!t:t&&(t=!1),e===0)return Eu.of(n.substring(1,n.length-1))}throw new Dl(this.bytes.position())},t.prototype.parseName=function(){this.bytes.assertNext(K.ForwardSlash);for(var e=``;!this.bytes.done();){var t=this.bytes.peek();if(Rl[t]||Ll[t])break;e+=ss(t),this.bytes.next()}return J.of(e)},t.prototype.parseArray=function(){this.bytes.assertNext(K.LeftSquareBracket),this.skipWhitespaceAndComments();for(var e=Pl.withContext(this.context);this.bytes.peek()!==K.RightSquareBracket;){var t=this.parseObject();e.push(t),this.skipWhitespaceAndComments()}return this.bytes.assertNext(K.RightSquareBracket),e},t.prototype.parseDict=function(){this.bytes.assertNext(K.LessThan),this.bytes.assertNext(K.LessThan),this.skipWhitespaceAndComments();for(var e=new Map;!this.bytes.done()&&this.bytes.peek()!==K.GreaterThan&&this.bytes.peekAhead(1)!==K.GreaterThan;){var t=this.parseName(),n=this.parseObject();e.set(t,n),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(K.GreaterThan),this.bytes.assertNext(K.GreaterThan);var r=e.get(J.of(`Type`));return r===J.of(`Catalog`)?Ud.fromMapWithContext(e,this.context):r===J.of(`Pages`)?Wd.fromMapWithContext(e,this.context):r===J.of(`Page`)?su.fromMapWithContext(e,this.context):ql.fromMapWithContext(e,this.context)},t.prototype.parseDictOrStream=function(){var e=this.bytes.position(),t=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(of.streamEOF1)&&!this.matchKeyword(of.streamEOF2)&&!this.matchKeyword(of.streamEOF3)&&!this.matchKeyword(of.streamEOF4)&&!this.matchKeyword(of.stream))return t;var n=this.bytes.offset(),r,i=t.get(J.of(`Length`));i instanceof q?(r=n+i.asNumber(),this.bytes.moveTo(r),this.skipWhitespaceAndComments(),this.matchKeyword(of.endstream)||(this.bytes.moveTo(n),r=this.findEndOfStreamFallback(e))):r=this.findEndOfStreamFallback(e);var a=this.bytes.slice(n,r);return Yl.of(t,a)},t.prototype.findEndOfStreamFallback=function(e){for(var t=1,n=this.bytes.offset();!this.bytes.done()&&(n=this.bytes.offset(),this.matchKeyword(of.stream)?t+=1:this.matchKeyword(of.EOF1endstream)||this.matchKeyword(of.EOF2endstream)||this.matchKeyword(of.EOF3endstream)||this.matchKeyword(of.endstream)?--t:this.bytes.next(),t!==0););if(t!==0)throw new El(e);return n},t.forBytes=function(e,n,r){return new t($d.of(e),n,r)},t.forByteStream=function(e,n,r){return r===void 0&&(r=!1),new t(e,n,r)},t}(Qd),cf=function(e){U(t,e);function t(t,n){var r=e.call(this,$d.fromPDFRawStream(t),t.dict.context)||this,i=t.dict;return r.alreadyParsed=!1,r.shouldWaitForTick=n||(function(){return!1}),r.firstOffset=i.lookup(J.of(`First`),q).asNumber(),r.objectCount=i.lookup(J.of(`N`),q).asNumber(),r}return t.prototype.parseIntoContext=function(){return qo(this,void 0,void 0,function(){var e,t,n,r,i,a,o,s;return Jo(this,function(c){switch(c.label){case 0:if(this.alreadyParsed)throw new cl(`PDFObjectStreamParser`,`parseIntoContext`);this.alreadyParsed=!0,e=this.parseOffsetsAndObjectNumbers(),t=0,n=e.length,c.label=1;case 1:return t=K.Space&&t<=K.Tilde&&(this.matchKeyword(of.xref)||this.matchKeyword(of.trailer)||this.matchKeyword(of.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(e);break}this.bytes.next()}},t.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var e=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(e)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},t.forBytesWithOptions=function(e,n,r,i){return new t(e,n,r,i)},t}(sf),df=function(e){return 1<0&&(r[r.length]=+i),n[n.length]={cmd:t,args:r},r=[],i=``,a=!1),t=l;else if([` `,`,`].includes(l)||l===`-`&&i.length>0&&i[i.length-1]!==`e`||l===`.`&&a){if(i.length===0)continue;r.length===o?(n[n.length]={cmd:t,args:r},r=[+i],t===`M`&&(t=`L`),t===`m`&&(t=`l`)):r[r.length]=+i,a=l===`.`,i=[`-`,`.`].includes(l)?l:``}else i+=l,l===`.`&&(a=!0)}return i.length>0&&(r.length===o?(n[n.length]={cmd:t,args:r},r=[+i],t===`M`&&(t=`L`),t===`m`&&(t=`l`)):r[r.length]=+i),n[n.length]={cmd:t,args:r},n},Pp=function(e){Q=$=Op=kp=Ap=jp=0;for(var t=[],n=0;n1&&(f=Math.sqrt(f),n*=f,r*=f);var p=d/n,m=u/n,h=-u/r,g=d/r,_=p*s+m*c,v=h*s+g*c,y=p*e+m*t,b=h*e+g*t,x=1/((y-_)*(y-_)+(b-v)*(b-v))-.25;x<0&&(x=0);var S=Math.sqrt(x);a===i&&(S=-S);var C=.5*(_+y)-S*(b-v),w=.5*(v+b)+S*(y-_),T=Math.atan2(v-w,_-C),E=Math.atan2(b-w,y-C)-T;E<0&&a===1?E+=2*Math.PI:E>0&&a===0&&(E-=2*Math.PI);for(var D=Math.ceil(Math.abs(E/(Math.PI*.5+.001))),O=[],k=0;ke.length)return i-1;var m=t.heightAtSize(i);if((m+m*.2)*a>Math.abs(n.height))return i-1;i+=1}return i},bm=function(e,t,n,r){for(var i=n.width/r,a=n.height,o=_m,s=vs(e);oi*.75)return o-1}if(t.heightAtSize(o,{descender:!1})>a)return o-1;o+=1}return o},xm=function(e){for(var t=e.length;t>0;t--)if(/\s/.test(e[t]))return t},Sm=function(e,t,n,r){for(var i=e.length;i>0;){var a=e.substring(0,i),o=n.encodeText(a),s=n.widthOfTextAtSize(a,r);if(sf&&(f=C+x),m+s>p&&(p=m+s),l.push({text:y,encoded:b,width:x,height:s,x:C,y:m}),_=S?.trim()}return{fontSize:r,lineHeight:c,lines:l,bounds:{x:u,y:d,width:f-u,height:p-d}}},wm=function(e,t){var n=t.fontSize,r=t.font,i=t.bounds,a=t.cellCount,o=gs(fs(e));if(o.length>a)throw new pm(o.length,a);(n===void 0||n===0)&&(n=bm(o,r,i,a));for(var s=i.width/a,c=r.heightAtSize(n,{descender:!1}),l=i.y+(i.height/2-c/2),u=[],d=i.x,f=i.y,p=i.x+i.width,m=i.y+i.height,h=0,g=0;hp&&(p=S+x),l+c>m&&(m=l+c),u.push({text:o,encoded:b,width:x,height:c,x:S,y:l}),h+=1,g+=y}return{fontSize:n,cells:u,bounds:{x:d,y:f,width:p-d,height:m-f}}},Tm=function(e,t){var n=t.alignment,r=t.fontSize,i=t.font,a=t.bounds,o=gs(fs(e));(r===void 0||r===0)&&(r=ym([o],i,a));var s=i.encodeText(o),c=i.widthOfTextAtSize(o,r),l=i.heightAtSize(r,{descender:!1}),u=n===gm.Left?a.x:n===gm.Center?a.x+a.width/2-c/2:n===gm.Right?a.x+a.width-c:a.x,d=a.y+(a.height/2-l/2);return{fontSize:r,line:{text:o,encoded:s,width:c,height:l,x:u,y:d},bounds:{x:u,y:d,width:c,height:l}}},Em=function(e){return`normal`in e?e:{normal:e}},Dm=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,Om=function(e){var t=Cs(e.getDefaultAppearance()??``,Dm).match??[],n=Number(t[2]);return isFinite(n)?n:void 0},km=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,Am=function(e){var t=Cs(e.getDefaultAppearance()??``,km).match??[],n=t[1],r=t[2],i=t[3],a=t[4],o=t[5];if(o===`g`&&n)return vp(Number(n));if(o===`rg`&&n&&r&&i)return yp(Number(n),Number(r),Number(i));if(o===`k`&&n&&r&&i&&a)return bp(Number(n),Number(r),Number(i),Number(a))},jm=function(e,t,n,r){r===void 0&&(r=0);var i=[wp(t).toString(),rp(n?.name??`dummy__noop`,r).toString()].join(` -`);e.setDefaultAppearance(i)},Mm=function(e,t){var n=Am(t),r=Am(e.acroField),i=t.getRectangle(),a=t.getAppearanceCharacteristics(),o=t.getBorderStyle()?.getWidth()??0,s=Cf(a?.getRotation()),c=wf(i,s),l=c.width,u=c.height,d=Zp(Go(Go({},i),{rotation:s})),f=yp(0,0,0),p=Ep(a?.getBorderColor())??f,m=Ep(a?.getBackgroundColor()),h=Ep(a?.getBackgroundColor(),.8),g=n??r??f;jm(n?t:e.acroField,g);var _={x:0+o/2,y:0+o/2,width:l-o,height:u-o,thickness:1.5,borderWidth:o,borderColor:p,markColor:g};return{normal:{on:Yo(d,Qp(Go(Go({},_),{color:m,filled:!0}))),off:Yo(d,Qp(Go(Go({},_),{color:m,filled:!1})))},down:{on:Yo(d,Qp(Go(Go({},_),{color:h,filled:!0}))),off:Yo(d,Qp(Go(Go({},_),{color:h,filled:!1})))}}},Nm=function(e,t){var n=Am(t),r=Am(e.acroField),i=t.getRectangle(),a=t.getAppearanceCharacteristics(),o=t.getBorderStyle()?.getWidth()??0,s=Cf(a?.getRotation()),c=wf(i,s),l=c.width,u=c.height,d=Zp(Go(Go({},i),{rotation:s})),f=yp(0,0,0),p=Ep(a?.getBorderColor())??f,m=Ep(a?.getBackgroundColor()),h=Ep(a?.getBackgroundColor(),.8),g=n??r??f;jm(n?t:e.acroField,g);var _={x:l/2,y:u/2,width:l-o,height:u-o,borderWidth:o,borderColor:p,dotColor:g};return{normal:{on:Yo(d,$p(Go(Go({},_),{color:m,filled:!0}))),off:Yo(d,$p(Go(Go({},_),{color:m,filled:!1})))},down:{on:Yo(d,$p(Go(Go({},_),{color:h,filled:!0}))),off:Yo(d,$p(Go(Go({},_),{color:h,filled:!1})))}}},Pm=function(e,t,n){var r=Am(t),i=Am(e.acroField),a=Om(t),o=Om(e.acroField),s=t.getRectangle(),c=t.getAppearanceCharacteristics(),l=t.getBorderStyle(),u=c?.getCaptions(),d=u?.normal??``,f=u?.down??d??``,p=l?.getWidth()??0,m=Cf(c?.getRotation()),h=wf(s,m),g=h.width,_=h.height,v=Zp(Go(Go({},s),{rotation:m})),y=yp(0,0,0),b=Ep(c?.getBorderColor()),x=Ep(c?.getBackgroundColor()),S=Ep(c?.getBackgroundColor(),.8),C={x:p,y:p,width:g-p*2,height:_-p*2},w=Tm(d,{alignment:gm.Center,fontSize:a??o,font:n,bounds:C}),T=Tm(f,{alignment:gm.Center,fontSize:a??o,font:n,bounds:C}),E=Math.min(w.fontSize,T.fontSize),D=r??i??y;jm(r||a!==void 0?t:e.acroField,D,n,E);var O={x:0+p/2,y:0+p/2,width:g-p,height:_-p,borderWidth:p,borderColor:b,textColor:D,font:n.name,fontSize:E};return{normal:Yo(v,em(Go(Go({},O),{color:x,textLines:[w.line]}))),down:Yo(v,em(Go(Go({},O),{color:S,textLines:[T.line]})))}},Fm=function(e,t,n){var r=Am(t),i=Am(e.acroField),a=Om(t),o=Om(e.acroField),s=t.getRectangle(),c=t.getAppearanceCharacteristics(),l=t.getBorderStyle(),u=e.getText()??``,d=l?.getWidth()??0,f=Cf(c?.getRotation()),p=wf(s,f),m=p.width,h=p.height,g=Zp(Go(Go({},s),{rotation:f})),_=yp(0,0,0),v=Ep(c?.getBorderColor()),y=Ep(c?.getBackgroundColor()),b,x,S=+!e.isCombed(),C={x:d+S,y:d+S,width:m-(d+S)*2,height:h-(d+S)*2};if(e.isMultiline()){var w=Cm(u,{alignment:e.getAlignment(),fontSize:a??o,font:n,bounds:C});b=w.lines,x=w.fontSize}else if(e.isCombed()){var w=wm(u,{fontSize:a??o,font:n,bounds:C,cellCount:e.getMaxLength()??0});b=w.cells,x=w.fontSize}else{var w=Tm(u,{alignment:e.getAlignment(),fontSize:a??o,font:n,bounds:C});b=[w.line],x=w.fontSize}var T=r??i??_;return jm(r||a!==void 0?t:e.acroField,T,n,x),Yo(g,nm({x:0+d/2,y:0+d/2,width:m-d,height:h-d,borderWidth:d??0,borderColor:v,textColor:T,font:n.name,fontSize:x,color:y,textLines:b,padding:S}))},Im=function(e,t,n){var r=Am(t),i=Am(e.acroField),a=Om(t),o=Om(e.acroField),s=t.getRectangle(),c=t.getAppearanceCharacteristics(),l=t.getBorderStyle(),u=e.getSelected()[0]??``,d=l?.getWidth()??0,f=Cf(c?.getRotation()),p=wf(s,f),m=p.width,h=p.height,g=Zp(Go(Go({},s),{rotation:f})),_=yp(0,0,0),v=Ep(c?.getBorderColor()),y=Ep(c?.getBackgroundColor()),b=1,x={x:d+b,y:d+b,width:m-(d+b)*2,height:h-(d+b)*2},S=Tm(u,{alignment:gm.Left,fontSize:a??o,font:n,bounds:x}),C=S.line,w=S.fontSize,T=r??i??_;return jm(r||a!==void 0?t:e.acroField,T,n,w),Yo(g,nm({x:0+d/2,y:0+d/2,width:m-d,height:h-d,borderWidth:d??0,borderColor:v,textColor:T,font:n.name,fontSize:w,color:y,textLines:[C],padding:b}))},Lm=function(e,t,n){var r=Am(t),i=Am(e.acroField),a=Om(t),o=Om(e.acroField),s=t.getRectangle(),c=t.getAppearanceCharacteristics(),l=t.getBorderStyle()?.getWidth()??0,u=Cf(c?.getRotation()),d=wf(s,u),f=d.width,p=d.height,m=Zp(Go(Go({},s),{rotation:u})),h=yp(0,0,0),g=Ep(c?.getBorderColor()),_=Ep(c?.getBackgroundColor()),v=e.getOptions(),y=e.getSelected();e.isSorted()&&v.sort();for(var b=``,x=0,S=v.length;x1||n.length===1&&t)&&this.enableMultiselect();for(var i=Array(n.length),a=0,o=n.length;a1||n.length===1&&t)&&this.enableMultiselect();for(var r=Array(n.length),i=0,a=n.length;it)throw new mm(e.length,t,this.getName());this.markAsDirty(),this.disableRichFormatting(),e?this.acroField.setValue(Y.fromText(e)):this.acroField.removeValue()},t.prototype.getAlignment=function(){var e=this.acroField.getQuadding();return e===0?gm.Left:e===1?gm.Center:e===2?gm.Right:gm.Left},t.prototype.setAlignment=function(e){Hc(e,`alignment`,gm),this.markAsDirty(),this.acroField.setQuadding(e)},t.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},t.prototype.setMaxLength=function(e){if(Xc(e,`maxLength`,0,2**53-1),this.markAsDirty(),e===void 0)this.acroField.removeMaxLength();else{var t=this.getText();if(t&&t.length>e)throw new hm(t.length,e,this.getName());this.acroField.setMaxLength(e)}},t.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},t.prototype.setImage=function(e){for(var t=this.getAlignment(),n=t===gm.Center?Vm.Center:t===gm.Right?Vm.Right:Vm.Left,r=this.acroField.getWidgets(),i=0,a=r.length;i{let r=e.node.Annots();if(!r)return;let i=r?.size()??0;for(let e=0;e{let a=r.node.Annots();if(!a)return;let o=a?.size()??0;for(let r=0;r{if(e.level>n)return;let[i,a]=t?.[e.key]??[0,0],o={title:e.title,to:[i,0,a],open:!1,children:[]};if(e.children?.length>0)for(let t of e.children){let e=r(t);e&&o.children.push(e)}return o};return r(e)?.children??[]}var hh=(e,t)=>{for(let n of e){let e=t(n);`children`in n&&e!==!1&&hh(n.children,t)}},gh=e=>{let t=[];return hh(e,e=>void t.push(e)),t},_h=e=>{let t=0;return hh(e,e=>(t+=1,!(`open`in e&&!e.open))),t},vh=async(e,t)=>{let n=e.context.nextRef(),r=new WeakMap;for(let n of gh(t))r.set(n,e.context.nextRef());let i=(()=>{let t=[];return e.catalog.Pages().traverse((e,n)=>{e.get(e.context.obj(`Type`))?.toString()===`/Page`&&t.push(n)}),t})(),a=(t,n)=>{let{length:o}=t;for(let s=0;s0?(a(c.children,l),{First:r.get(c.children[0]),Last:r.get(c.children[c.children.length-1]),Count:_h(c.children)*(c.open?1:-1)}):{};e.context.assign(l,e.context.obj({Title:Y.fromText(c.title),Parent:n,...s>0?{Prev:r.get(t[s-1])}:{},...s0?{First:r.get(t[0]),Last:r.get(t[t.length-1])}:{},Count:o})),e.catalog.set(e.context.obj(`Outlines`),n)};async function yh(e,{headings:t,maxLevel:n,frontMatter:r,displayMetadata:i}){let a=await oh.load(e),o=await fh(a);return ph(a,o),vh(a,mh(t,o,n)),i&&bh(a,r??{}),e=await a.save(),e}function bh(e,{title:t,author:n,keywords:r,subject:i,creator:a,created_at:o,updated_at:s}){t&&e.setTitle(t,{showInWindowTitleBar:!0}),n&&(Array.isArray(n)?e.setAuthor(n.join(`, `)):e.setAuthor(n.toString())),r&&e.setKeywords(typeof r==`string`?[r]:r),i&&e.setSubject(i),e.setCreator(a??`Obsidian`),e.setProducer(`Obsidian`),e.setCreationDate(new Date(o??new Date)),e.setModificationDate(new Date(s??new Date))}function xh(e,t,n){let r={...e};return t&&n.forEach(e=>{let n=t[e];n!=null&&(r[e]=n)}),r}function Sh(e,t){e=xh(e,t,[`headerTemplate`,`footerTemplate`]);let n=e.pageSize;e.pageSize==`Custom`&&e.pageWidth&&e.pageHeight&&(n={width:ao(e.pageWidth,210)/25.4,height:ao(e.pageHeight,297)/25.4});let r=e?.scale??100;(r>200||r<10)&&(r=100);let i={landscape:e?.landscape,printBackground:e?.printBackground,generateTaggedPDF:e?.generateTaggedPDF,pageSize:n,scale:r/100,margins:{marginType:`default`},displayHeaderFooter:e.displayHeader||e.displayFooter,headerTemplate:e.displayHeader?no(e.headerTemplate,t??{}):``,footerTemplate:e.displayFooter?no(e.footerTemplate,t??{}):``};return e.marginType==`0`?i.margins={marginType:`custom`,top:0,bottom:0,left:0,right:0}:e.marginType==`1`?i.margins={marginType:`default`}:e.marginType==`2`?i.margins={marginType:`custom`,top:.1,bottom:.1,left:.1,right:.1}:e.marginType==`3`&&(i.margins={marginType:`custom`,top:ao(e.marginTop,0)/25.4,bottom:ao(e.marginBottom,0)/25.4,left:ao(e.marginLeft,0)/25.4,right:ao(e.marginRight,0)/25.4}),i}async function Ch(e,t,n,{doc:r,frontMatter:i}){console.log(`output pdf:`,e);let a=Sh(t,i);try{let o=await n.printToPDF(a);o=await yh(o,{headings:Ja(r),frontMatter:i,displayMetadata:t?.displayMetadata,maxLevel:io(t?.maxLevel,6)}),await dh.writeFile(e,o),t.open&&u.default.remote.shell.openPath(e)}catch(e){console.error(e)}}async function wh(e,t){let n=await u.default.remote.dialog.showSaveDialog({title:`Export to PDF`,defaultPath:e+(t?`-`+Date.now():``)+`.pdf`,filters:[{name:`All Files`,extensions:[`*`]},{name:`PDF`,extensions:[`pdf`]}],properties:[`showOverwriteConfirmation`,`createDirectory`]});if(!n.canceled)return n.filePath}async function Th(e,t){let n=await u.default.remote.dialog.showOpenDialog({title:`Export to PDF`,defaultPath:e,properties:[`openDirectory`]});if(!n.canceled)return n.filePaths[0]}function Eh(e){return e.map(e=>({status:0,filename:e.file.name}))}function Dh(e,t){return e[t].status=1,[...e]}var Oh={A0:[841,1189],A1:[594,841],A2:[420,594],A3:[297,420],A4:[210,297],A5:[148,210],A6:[105,148],Legal:[216,356],Letter:[216,279],Tabloid:[279,432],Ledger:[432,279]},kh=class{constructor(e,t){this.config=e,this.onResize=t}calc(e){let{pageSize:t,pageWidth:n}=this.config,r=Oh?.[t]?.[0]??ao(n,210);return Math.floor($a(r)/e.offsetWidth*100)/100}startObserver(e){this.observer=new ResizeObserver(()=>{this.onResize?.()}),this.observer.observe(e)}stopObserver(){this.observer?.disconnect()}},Ah,jh=class{constructor(e){j(this,`value`,void 0),j(this,`next`,void 0),this.value=e}},Mh=new WeakMap,Nh=new WeakMap,Ph=new WeakMap;Ah=Symbol.iterator;var Fh=class{constructor(){vt(this,Mh,void 0),vt(this,Nh,void 0),vt(this,Ph,void 0),this.clear()}enqueue(e){var t;let n=new jh(e);V(Mh,this)?(V(Nh,this).next=n,B(Nh,this,n)):(B(Mh,this,n),B(Nh,this,n)),B(Ph,this,(t=V(Ph,this),t++,t))}dequeue(){var e;let t=V(Mh,this);if(t)return B(Mh,this,V(Mh,this).next),B(Ph,this,(e=V(Ph,this),e--,e)),t.value}peek(){if(V(Mh,this))return V(Mh,this).value}clear(){B(Mh,this,void 0),B(Nh,this,void 0),B(Ph,this,0)}get size(){return V(Ph,this)}*[Ah](){let e=V(Mh,this);for(;e;)yield e.value,e=e.next}*drain(){for(;V(Mh,this);)yield this.dequeue()}};function Ih(e){let t=!1;if(typeof e==`object`&&({concurrency:e,rejectOnClear:t=!1}=e),Lh(e),typeof t!=`boolean`)throw TypeError("Expected `rejectOnClear` to be a boolean");let n=new Fh,r=0,i=()=>{r0&&(r++,n.dequeue().run())},a=()=>{r--,i()},o=async(e,t,n)=>{let r=(async()=>e(...n))();t(r);try{await r}catch{}a()},s=(t,a,s,c)=>{let l={reject:s};new Promise(e=>{l.run=e,n.enqueue(l)}).then(o.bind(void 0,t,a,c)),rnew Promise((n,r)=>{s(e,n,r,t)});return Object.defineProperties(c,{activeCount:{get:()=>r},pendingCount:{get:()=>n.size},clearQueue:{value(){if(!t){n.clear();return}let e=AbortSignal.abort().reason;for(;n.size>0;)n.dequeue().reject(e)}},concurrency:{get:()=>e,set(t){Lh(t),e=t,queueMicrotask(()=>{for(;r0;)i()})}},map:{async value(e,t){let n=Array.from(e,(e,n)=>this(t,e,n));return Promise.all(n)}}}),c}function Lh(e){if(!((Number.isInteger(e)||e===1/0)&&e>0))throw TypeError("Expected `concurrency` to be a number from 1 and up")}var Rh=Wi(``),zh=Wi(`
`),Bh=Wi(`
Rendering...
`,1),Vh=Wi(`
`),Hh=Wi(`
`,1),Uh=Wi(``);function Wh(e,t){$e(t,!0);let n=require(`fs`).promises,r=tn(()=>t.plugin.settings),i=ar(!1),a=ar(fr([])),o=ar(fr([])),s=ar(.75),c=ar(void 0),u=ar(fr([])),d=new kh(t.config);function f(){H(c)&&sr(s,d.calc(H(c)),!0)}async function p(){await sleep(500),H(o).forEach(async(e,t)=>{let[n,r]=await e.executeJavaScript(`[document.body.offsetWidth, document.body.offsetHeight]`);H(a)[t]={...H(a)[t],printSize:`${n}×${r}px²\n${Qa(n)}×${Qa(r)}mm²`}})}async function m(){await f(),await p()}async function h(e,n,i){let a=Ih(io(H(r).concurrency)||5),o=Ye(t.config);console.log(`file list data:`,e,o);let s=e.map((e,t)=>a(async()=>{let n=await po({...e,config:o});return i?.(t),n})),c=[...n??[],...await Promise.all(s)];return t.modal.file instanceof l.TFile&&await t.modal.app.workspace.getLeaf().openFile(t.modal.file),t.modal.multiplePdf||(c=t.modal.mergeDoc(c)),c.map(({doc:e,...t})=>({...t,doc:vo(e,e.title)}))}async function g(e=!0){if(e){let{data:e,docs:n}=await t.modal.getAllFiles();sr(u,Eh(e),!0),sr(a,await h(e,n,e=>{sr(u,Dh(H(u),e),!0)}),!0)}sr(o,[],!0);let n=H(a).map(e=>new Promise(t=>{e.resolve=t}));await Promise.all(n),f(),await p()}function _(e){H(o).forEach((t,n)=>{t.executeJavaScript(` +end`},vu=function(){for(var e=[],t=0;t`},yu=function(e){return ns(e,4)},bu=function(e){if(Is(e))return yu(e);if(Ls(e)){var t=Rs(e),n=zs(e);return``+yu(t)+yu(n)}var r=`0x`+rs(e)+` is not a valid UTF-8 or UTF-16 codepoint.`;throw Error(r)},xu=function(e){var t=0,n=function(e){t|=1<=K.Zero&&s<=K.Seven?(t+=o,(t.length===3||!(c>=`0`&&c<=`7`))&&(r(parseInt(t,8)),t=``)):r(s):s===K.BackSlash?n=!0:r(s)}return new Uint8Array(e)},t.prototype.decodeText=function(){var e=this.asBytes();return Ys(e)?Hs(e):$c(e)},t.prototype.decodeDate=function(){var e=this.decodeText(),t=ys(e);if(!t)throw new ul(e);return t},t.prototype.asString=function(){return this.value},t.prototype.clone=function(){return t.of(this.value)},t.prototype.toString=function(){return`(`+this.value+`)`},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(e,t){return e[t++]=K.LeftParen,t+=ss(this.value,e,t),e[t++]=K.RightParen,this.value.length+2},t.of=function(e){return new t(e)},t.fromDate=function(e){var n=os(String(e.getUTCFullYear()),4,`0`),r=os(String(e.getUTCMonth()+1),2,`0`),i=os(String(e.getUTCDate()),2,`0`),a=os(String(e.getUTCHours()),2,`0`),o=os(String(e.getUTCMinutes()),2,`0`),s=os(String(e.getUTCSeconds()),2,`0`);return new t(`D:`+n+r+i+a+o+s+`Z`)},t}(Al),wu=function(){function e(e,t,n,r){var i=this;this.allGlyphsInFontSortedById=function(){for(var e=Array(i.font.characterSet.length),t=0,n=e.length;t>3)]>>7-((p&7)<<0)&1,D=3*E;s[y]=b[D],s[y+1]=b[D+1],s[y+2]=b[D+2],s[y+3]=E>2)]>>6-((p&3)<<1)&3,D=3*E;s[y]=b[D],s[y+1]=b[D+1],s[y+2]=b[D+2],s[y+3]=E>1)]>>4-((p&1)<<2)&15,D=3*E;s[y]=b[D],s[y+1]=b[D+1],s[y+2]=b[D+2],s[y+3]=E>>3)]>>>7-(j&7)&1),te=k==g*255?0:255;c[A+j]=te<<24|k<<16|k<<8|k}else if(u==2)for(var j=0;j>>2)]>>>6-((j&3)<<1)&3),te=k==g*85?0:255;c[A+j]=te<<24|k<<16|k<<8|k}else if(u==4)for(var j=0;j>>1)]>>>4-((j&1)<<2)&15),te=k==g*17?0:255;c[A+j]=te<<24|k<<16|k<<8|k}else if(u==8)for(var j=0;j>>2<<3));i==0;){if(i=g(t,f,1),a=g(t,f+1,2),f+=3,a==0){f&7&&(f+=8-(f&7));var w=(f>>>3)+4,T=t[w-4]|t[w-3]<<8;C&&(n=e.H.W(n,d+T)),n.set(new r(t.buffer,t.byteOffset+w,T),d),f=w+T<<3,d+=T;continue}if(C&&(n=e.H.W(n,d+(1<<17))),a==1&&(p=S.J,m=S.h,l=511,u=31),a==2){o=_(t,f,5)+257,s=_(t,f+5,5)+1,c=_(t,f+10,4)+4,f+=14;for(var E=1,D=0;D<38;D+=2)S.Q[D]=0,S.Q[D+1]=0;for(var D=0;DE&&(E=O)}f+=3*c,y(S.Q,E),b(S.Q,E,S.u),p=S.w,m=S.d,f=v(S.u,(1<>>4;if(!(j>>>8))n[d++]=j;else if(j==256)break;else{var te=d+j-254;if(j>264){var ne=S.q[j-257];te=d+(ne>>>3)+_(t,f,ne&7),f+=ne&7}var re=m[x(t,f)&u];f+=re&15;var ie=re>>>4,ae=S.c[ie],oe=(ae>>>4)+g(t,f,ae&15);for(f+=ae&15;d>>4;if(d<=15)o[l]=d,l++;else{var f=0,p=0;d==16?(p=3+s(i,a,2),a+=2,f=o[l-1]):d==17?(p=3+s(i,a,3),a+=3):d==18&&(p=11+s(i,a,7),a+=7);for(var m=l+p;l>>1;ai&&(i=s),a++}for(;a>1,c=t[o+1],l=s<<4|c,u=n-c,d=t[o]<>>15-n;r[p]=l,d++}},e.H.l=function(t,n){for(var r=e.H.m.r,i=15-n,a=0;a>>i},e.H.M=function(e,t,n){n<<=t&7;var r=t>>>3;e[r]|=n,e[r+1]|=n>>>8},e.H.I=function(e,t,n){n<<=t&7;var r=t>>>3;e[r]|=n,e[r+1]|=n>>>8,e[r+2]|=n>>>16},e.H.e=function(e,t,n){return(e[t>>>3]|e[(t>>>3)+1]<<8)>>>(t&7)&(1<>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)&(1<>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)},e.H.i=function(e,t){return(e[t>>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16|e[(t>>>3)+3]<<24)>>>(t&7)},e.H.m=function(){var e=Uint16Array,t=Uint32Array;return{K:new e(16),j:new e(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new e(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new t(32),J:new e(512),_:[],h:new e(32),$:[],w:new e(32768),C:[],v:[],d:new e(32768),D:[],u:new e(512),Q:[],r:new e(32768),s:new t(286),Y:new t(30),a:new t(19),t:new t(15e3),k:new e(65536),g:new e(32768)}}(),(function(){for(var t=e.H.m,n=32768,r=0;r>>1|(i&1431655765)<<1,i=(i&3435973836)>>>2|(i&858993459)<<2,i=(i&4042322160)>>>4|(i&252645135)<<4,i=(i&4278255360)>>>8|(i&16711935)<<8,t.r[r]=(i>>>16|i<<16)>>>17}function a(e,t,n){for(;t--!=0;)e.push(0,n)}for(var r=0;r<32;r++)t.q[r]=t.S[r]<<3|t.T[r],t.c[r]=t.p[r]<<4|t.z[r];a(t._,144,8),a(t._,112,9),a(t._,24,7),a(t._,8,8),e.H.n(t._,9),e.H.A(t._,9,t.J),e.H.l(t._,9),a(t.$,32,5),e.H.n(t.$,5),e.H.A(t.$,5,t.h),e.H.l(t.$,5),a(t.Q,19,0),a(t.C,286,0),a(t.D,30,0),a(t.v,320,0)})(),e.H.N}(),X.decode._readInterlace=function(e,t){for(var n=t.width,r=t.height,i=X.decode._getBPP(t),a=i>>3,o=Math.ceil(n*i/8),s=new Uint8Array(r*o),c=0,l=[0,0,4,0,2,0,1],u=[0,4,0,2,0,1,0],d=[8,8,8,4,4,2,2],f=[8,8,4,4,2,2,1],p=0;p<7;){for(var m=d[p],h=f[p],g=0,_=0,v=l[p];v>3];T=T>>7-(w&7)&1,s[S*o+(C>>3)]|=T<<7-((C&7)<<0)}if(i==2){var T=e[w>>3];T=T>>6-(w&7)&3,s[S*o+(C>>2)]|=T<<6-((C&3)<<1)}if(i==4){var T=e[w>>3];T=T>>4-(w&7)&15,s[S*o+(C>>1)]|=T<<4-((C&1)<<2)}if(i>=8)for(var E=S*o+C*a,D=0;D>3)+D];w+=i,C+=h}x++,S+=m}g*_!=0&&(c+=_*(1+b)),p+=1}return s},X.decode._getBPP=function(e){return[1,null,3,1,2,null,4][e.ctype]*e.depth},X.decode._filterZero=function(e,t,n,r,i){var a=X.decode._getBPP(t),o=Math.ceil(r*a/8),s=X.decode._paeth;a=Math.ceil(a/8);var c=0,l=1,u=e[n],d=0;if(u>1&&(e[n]=[0,0,1][u-2]),u==3)for(d=a;d>>1)&255;for(var f=0;f>>1);for(;d>>1)}else{for(;d>8&255,e[t+1]=n&255},readUint:function(e,t){return e[t]*(256*256*256)+(e[t+1]<<16|e[t+2]<<8|e[t+3])},writeUint:function(e,t,n){e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255},readASCII:function(e,t,n){for(var r=``,i=0;i=0&&s>=0?(d=p*t+m<<2,f=(s+p)*i+o+m<<2):(d=(-s+p)*t-o+m<<2,f=p*i+m<<2),c==0)r[f]=e[d],r[f+1]=e[d+1],r[f+2]=e[d+2],r[f+3]=e[d+3];else if(c==1){var h=e[d+3]*(1/255),g=e[d]*h,_=e[d+1]*h,v=e[d+2]*h,y=r[f+3]*(1/255),b=r[f]*y,x=r[f+1]*y,S=r[f+2]*y,C=1-h,w=h+y*C,T=w==0?0:1/w;r[f+3]=255*w,r[f+0]=(g+b*C)*T,r[f+1]=(_+x*C)*T,r[f+2]=(v+S*C)*T}else if(c==2){var h=e[d+3],g=e[d],_=e[d+1],v=e[d+2],y=r[f+3],b=r[f],x=r[f+1],S=r[f+2];h==y&&g==b&&_==x&&v==S?(r[f]=0,r[f+1]=0,r[f+2]=0,r[f+3]=0):(r[f]=g,r[f+1]=_,r[f+2]=v,r[f+3]=h)}else if(c==3){var h=e[d+3],g=e[d],_=e[d+1],v=e[d+2],y=r[f+3],b=r[f],x=r[f+1],S=r[f+2];if(h==y&&g==b&&_==x&&v==S)continue;if(h<220&&y>20)return!1}return!0},X.encode=function(e,t,n,r,i,a,o){r??(r=0),o??(o=!1);var s=X.encode.compress(e,t,n,r,[!1,!1,!1,0,o]);return X.encode.compressPNG(s,-1),X.encode._main(s,t,n,i,a)},X.encodeLL=function(e,t,n,r,i,a,o,s){for(var c={ctype:0+(r==1?0:2)+(i==0?0:4),depth:a,frames:[]},l=(r+i)*a,u=l*t,d=0;d1,d=!1,f=33+(u?20:0);if(i.sRGB!=null&&(f+=13),i.pHYs!=null&&(f+=21),e.ctype==3){for(var p=e.plte.length,m=0;m>>24!=255&&(d=!0);f+=8+p*3+4+(d?8+p*1+4:0)}for(var h=0;h>>8&255,C=b>>>16&255;_[l+y+0]=x,_[l+y+1]=S,_[l+y+2]=C}if(l+=p*3,o(_,l,a(_,l-p*3-4,p*3+4)),l+=4,d){o(_,l,p),l+=4,c(_,l,`tRNS`),l+=4;for(var m=0;m>>24&255;l+=p,o(_,l,a(_,l-p-4,p+4)),l+=4}}for(var w=0,h=0;h>2,O>>2));for(var p=0;pA&&te==ee[g-A])j[g]=j[g-A];else{var ne=y[te];if(ne==null&&(y[te]=ne=b.length,b.push(te),b.length>=300))break;j[g]=ne}}}var re=b.length;re<=256&&l==0&&(d=re<=2?1:re<=4?2:re<=16?4:8,d=Math.max(d,c));for(var p=0;p>1)]|=le[M+N]<<4-(N&1)*4;else if(d==2)for(var N=0;N>2)]|=le[M+N]<<6-(N&3)*2;else if(d==1)for(var N=0;N>3)]|=le[M+N]<<7-(N&7)*1}ae=ce,u=3,se=1}else if(_==0&&v.length==1){for(var ce=new Uint8Array(A*ie*3),de=A*ie,g=0;gw&&(w=D),ET&&(T=E))}w==-1&&(S=C=w=T=0),i&&((S&1)==1&&S--,(C&1)==1&&C--);var k=(w-S+1)*(T-C+1);kg&&(g=b),x_&&(_=x))}g==-1&&(m=h=g=_=0),o&&((m&1)==1&&m--,(h&1)==1&&h--),a={x:m,y:h,width:g-m+1,height:_-h+1};var w=r[i];w.rect=a,w.blend=1,w.img=new Uint8Array(a.width*a.height*4),r[i-1].dispose==0?(X._copyTile(l,t,n,w.img,a.width,a.height,-a.x,-a.y,0),X.encode._prepareDiff(f,t,n,w.img,a)):X._copyTile(f,t,n,w.img,a.width,a.height,-a.x,-a.y,0)},X.encode._prepareDiff=function(e,t,n,r,i){X._copyTile(e,t,n,r,i.width,i.height,-i.x,-i.y,2)},X.encode._filterZero=function(e,t,n,r,i,a,o){var s=[],c=[0,1,2,3,4];a==-1?(t*r>5e5||n==1)&&(c=[0]):c=[a];var l;o&&(l={level:0});for(var u=o&&UZIP!=null?UZIP:hc.default,d=0;d>1)+256&255;if(a==4)for(var l=i;l>1)&255;for(var l=i;l>1)&255}if(a==4){for(var l=0;l>>1:n>>>=1;e[t]=n}return e})(),update:function(e,t,n,r){for(var i=0;i>>8;return e},crc:function(e,t,n){return X.crc.update(4294967295,e,t,n)^4294967295}},X.quantize=function(e,t){var n=new Uint8Array(e),r=n.slice(0),i=new Uint32Array(r.buffer),a=X.quantize.getKDtree(r,t),o=a[0],s=a[1];X.quantize.planeDst;for(var c=n,l=i,u=c.length,d=new Uint8Array(n.length>>2),f=0;f>2]=_.ind,l[f>>2]=_.est.rgba}return{abuf:r.buffer,inds:d,plte:s}},X.quantize.getKDtree=function(e,t,n){n??(n=1e-4);var r=new Uint32Array(e.buffer),i={i0:0,i1:e.length,bst:null,est:null,tdst:0,left:null,right:null};i.bst=X.quantize.stats(e,i.i0,i.i1),i.est=X.quantize.estats(i.bst);for(var a=[i];a.lengtho&&(o=a[c].est.L,s=c);if(o=u||l.i1<=u){l.est.L=0;continue}var d={i0:l.i0,i1:u,bst:null,est:null,tdst:0,left:null,right:null};d.bst=X.quantize.stats(e,d.i0,d.i1),d.est=X.quantize.estats(d.bst);var f={i0:u,i1:l.i1,bst:null,est:null,tdst:0,left:null,right:null};f.bst={R:[],m:[],N:l.bst.N-d.bst.N};for(var c=0;c<16;c++)f.bst.R[c]=l.bst.R[c]-d.bst.R[c];for(var c=0;c<4;c++)f.bst.m[c]=l.bst.m[c]-d.bst.m[c];f.est=X.quantize.estats(f.bst),l.left=d,l.right=f,a[s]=d,a.push(f)}a.sort(function(e,t){return t.bst.N-e.bst.N});for(var c=0;c0&&(o=e.right,s=e.left);var c=X.quantize.getNearest(o,t,n,r,i);if(c.tdst<=a*a)return c;var l=X.quantize.getNearest(s,t,n,r,i);return l.tdsta;)r-=4;if(n>=r)break;var s=t[n>>2];t[n>>2]=t[r>>2],t[r>>2]=s,n+=4,r-=4}for(;o(e,n,i)>a;)n-=4;return n+4},X.quantize.vecDot=function(e,t,n){return e[t]*n[0]+e[t+1]*n[1]+e[t+2]*n[2]+e[t+3]*n[3]},X.quantize.stats=function(e,t,n){for(var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],i=[0,0,0,0],a=n-t>>2,o=t;o>>0}},X.M4={multVec:function(e,t){return[e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],e[4]*t[0]+e[5]*t[1]+e[6]*t[2]+e[7]*t[3],e[8]*t[0]+e[9]*t[1]+e[10]*t[2]+e[11]*t[3],e[12]*t[0]+e[13]*t[1]+e[14]*t[2]+e[15]*t[3]]},dot:function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},sml:function(e,t){return[e*t[0],e*t[1],e*t[2],e*t[3]]}},X.encode.concatRGBA=function(e){for(var t=0,n=0;n1)throw Error(`Animated PNGs are not supported`);var r=Nu(new Uint8Array(n[0])),i=r.rgbChannel,a=r.alphaChannel;this.rgbChannel=i,a.some(function(e){return e<255})&&(this.alphaChannel=a),this.type=Mu(t.ctype),this.width=t.width,this.height=t.height,this.bitsPerComponent=8}return e.load=function(t){return new e(t)},e}(),Iu=function(){function e(e){this.image=e,this.bitsPerComponent=e.bitsPerComponent,this.width=e.width,this.height=e.height,this.colorSpace=`DeviceRGB`}return e.for=function(t){return Wo(this,void 0,void 0,function(){var n;return Go(this,function(r){return n=Fu.load(t),[2,new e(n)]})})},e.prototype.embedIntoContext=function(e,t){return Wo(this,void 0,void 0,function(){var n,r;return Go(this,function(i){return n=this.embedAlphaChannel(e),r=e.flateStream(this.image.rgbChannel,{Type:`XObject`,Subtype:`Image`,BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:n}),t?(e.assign(t,r),[2,t]):[2,e.register(r)]})})},e.prototype.embedAlphaChannel=function(e){if(this.image.alphaChannel){var t=e.flateStream(this.image.alphaChannel,{Type:`XObject`,Subtype:`Image`,Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:`DeviceGray`,Decode:[0,1]});return e.register(t)}},e}(),Lu=function(){function e(e,t,n){this.bytes=e,this.start=t||0,this.pos=this.start,this.end=t&&n?t+n:this.bytes.length}return Object.defineProperty(e.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),e.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},e.prototype.getUint16=function(){var e=this.getByte(),t=this.getByte();return e===-1||t===-1?-1:(e<<8)+t},e.prototype.getInt32=function(){var e=this.getByte(),t=this.getByte(),n=this.getByte(),r=this.getByte();return(e<<24)+(t<<16)+(n<<8)+r},e.prototype.getBytes=function(e,t){t===void 0&&(t=!1);var n=this.bytes,r=this.pos,i=this.end;if(e){var a=r+e;a>i&&(a=i),this.pos=a;var o=n.subarray(r,a);return t?new Uint8ClampedArray(o):o}else{var o=n.subarray(r,i);return t?new Uint8ClampedArray(o):o}},e.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},e.prototype.peekBytes=function(e,t){t===void 0&&(t=!1);var n=this.getBytes(e,t);return this.pos-=n.length,n},e.prototype.skip=function(e){e||(e=1),this.pos+=e},e.prototype.reset=function(){this.pos=this.start},e.prototype.moveStart=function(){this.start=this.pos},e.prototype.makeSubStream=function(t,n){return new e(this.bytes,t,n)},e.prototype.decode=function(){return this.bytes},e}(),Ru=new Uint8Array,zu=function(){function e(e){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=Ru,this.minBufferLength=512,e)for(;this.minBufferLengthi&&(n=i)}else{for(;!this.eof;)this.readBlock();n=this.bufferLength}this.pos=n;var a=this.buffer.subarray(r,n);return t&&!(a instanceof Uint8ClampedArray)?new Uint8ClampedArray(a):a},e.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},e.prototype.peekBytes=function(e,t){t===void 0&&(t=!1);var n=this.getBytes(e,t);return this.pos-=n.length,n},e.prototype.skip=function(e){e||(e=1),this.pos+=e},e.prototype.reset=function(){this.pos=0},e.prototype.makeSubStream=function(e,t){for(var n=e+t;this.bufferLength<=n&&!this.eof;)this.readBlock();return new Lu(this.buffer,e,t)},e.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},e.prototype.readBlock=function(){throw new tl(this.constructor.name,`readBlock`)},e.prototype.ensureBuffer=function(e){var t=this.buffer;if(e<=t.byteLength)return t;for(var n=this.minBufferLength;n=0;--s)o[a+s]=l&255,l>>=8}},t}(zu),Hu=function(e){U(t,e);function t(t,n){var r=e.call(this,n)||this;return r.stream=t,r.firstDigit=-1,n&&(n=.5*n),r}return t.prototype.readBlock=function(){var e=this.stream.getBytes(8e3);if(!e.length){this.eof=!0;return}for(var t=e.length+1>>1,n=this.ensureBuffer(this.bufferLength+t),r=this.bufferLength,i=this.firstDigit,a=0,o=e.length;a=48&&s<=57)c=s&15;else if(s>=65&&s<=70||s>=97&&s<=102)c=(s&15)+9;else if(s===62){this.eof=!0;break}else continue;i<0?i=c:(n[r++]=i<<4|c,i=-1)}i>=0&&this.eof&&(n[r++]=i<<4,i=-1),this.firstDigit=i,this.bufferLength=r},t}(zu),Uu=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Wu=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),Gu=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Ku=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],qu=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],Ju=function(e){U(t,e);function t(t,n){var r=e.call(this,n)||this;r.stream=t;var i=t.getByte(),a=t.getByte();if(i===-1||a===-1)throw Error(`Invalid header in flate stream: `+i+`, `+a);if((i&15)!=8)throw Error(`Unknown compression method in flate stream: `+i+`, `+a);if(((i<<8)+a)%31!=0)throw Error(`Bad FCHECK in flate stream: `+i+`, `+a);if(a&32)throw Error(`FDICT bit set in flate stream: `+i+`, `+a);return r.codeSize=0,r.codeBuf=0,r}return t.prototype.readBlock=function(){var e,t,n=this.stream,r=this.getBits(3);if(r&1&&(this.eof=!0),r>>=1,r===0){var i=void 0;if((i=n.getByte())===-1)throw Error(`Bad block header in flate stream`);var a=i;if((i=n.getByte())===-1||(a|=i<<8,(i=n.getByte())===-1))throw Error(`Bad block header in flate stream`);var o=i;if((i=n.getByte())===-1)throw Error(`Bad block header in flate stream`);if(o|=i<<8,o!==(~a&65535)&&(a!==0||o!==0))throw Error(`Bad uncompressed block length in flate stream`);this.codeBuf=0,this.codeSize=0;var s=this.bufferLength;e=this.ensureBuffer(s+a);var c=s+a;if(this.bufferLength=c,a===0)n.peekByte()===-1&&(this.eof=!0);else for(var l=s;l0;)y[g++]=S}u=this.generateHuffmanTable(y.subarray(0,f)),d=this.generateHuffmanTable(y.subarray(f,v))}else throw Error(`Unknown block type in flate stream`);e=this.buffer;for(var T=e?e.length:0,E=this.bufferLength;;){var D=this.getCode(u);if(D<256){E+1>=T&&(e=this.ensureBuffer(E+1),T=e.length),e[E++]=D;continue}if(D===256){this.bufferLength=E;return}D-=257,D=Wu[D];var O=D>>16;O>0&&(O=this.getBits(O)),t=(D&65535)+O,D=this.getCode(d),D=Gu[D],O=D>>16,O>0&&(O=this.getBits(O));var k=(D&65535)+O;E+t>=T&&(e=this.ensureBuffer(E+t),T=e.length);for(var ee=0;ee>e,this.codeSize=n-=e,i},t.prototype.getCode=function(e){for(var t=this.stream,n=e[0],r=e[1],i=this.codeSize,a=this.codeBuf,o;i>16,l=s&65535;if(c<1||i>c,this.codeSize=i-c,l},t.prototype.generateHuffmanTable=function(e){var t=e.length,n=0,r;for(r=0;rn&&(n=e[r]);for(var i=1<>=1;for(r=u;r0;if(!y||y<256)m[0]=y,h=1;else if(y>=258)if(y=0;i--)m[i]=l[a],a=d[a];else m[h++]=m[0];else if(y===256){f=9,c=258,h=0;continue}else{this.eof=!0,delete this.lzwState;break}if(b&&(d[c]=p,u[c]=u[p]+1,l[c]=m[0],c++,f=c+s&c+s-1?f:Math.min(Math.log(c+s)/.6931471805599453+1,12)|0),p=y,g+=h,t>>t&(1<0){var i=this.stream.getBytes(r);t.set(i,n),n+=r}}else{r=257-r;var a=e[1];t=this.ensureBuffer(n+r+1);for(var o=0;ot.size())throw new pl(e,0,t.size());t.remove(e)}else{if(e!==0)throw new pl(e,0,0);this.setKids([])}},t.prototype.normalizedEntries=function(){var e=this.Kids();return e||(e=this.dict.context.obj([this.ref]),this.dict.set(J.of(`Kids`),e)),{Kids:e}},t.fromDict=function(e,n){return new t(e,n)},t}(ld),hd=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.Opt=function(){return this.dict.lookupMaybe(J.of(`Opt`),Cu,Y,jl)},t.prototype.setOpt=function(e){this.dict.set(J.of(`Opt`),this.dict.context.obj(e))},t.prototype.getExportValues=function(){var e=this.Opt();if(e){if(e instanceof Cu||e instanceof Y)return[e];for(var t=[],n=0,r=e.size();nt.size())throw new pl(e,0,t.size());t.remove(e)}},t.prototype.normalizeExportValues=function(){for(var e=this.getExportValues()??[],t=[],n=this.getWidgets(),r=0,i=n.length;r1){if(!this.hasFlag(xd.MultiSelect))throw new hl;this.dict.set(J.of(`V`),this.dict.context.obj(e))}this.updateSelectedIndices(e)},t.prototype.valuesAreValid=function(e){for(var t=this.getOptions(),n=function(n,r){var i=e[n].decodeText();if(!t.find(function(e){return i===(e.display||e.value).decodeText()}))return{value:!1}},r=0,i=e.length;r1){for(var t=Array(e.length),n=this.getOptions(),r=function(r,i){var a=e[r].decodeText();t[r]=n.findIndex(function(e){return a===(e.display||e.value).decodeText()})},i=0,a=e.length;i0){var a=i.lookup(0,Cu,Y),o=i.lookupMaybe(1,Cu,Y);t.push({value:a,display:o||a})}}return t}return[]},t}(md),Cd=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.fromDict=function(e,n){return new t(e,n)},t.create=function(e){var n=e.obj({FT:`Ch`,Ff:xd.Combo,Kids:[]});return new t(n,e.register(n))},t}(Sd),wd=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.addField=function(e){this.normalizedEntries().Kids?.push(e)},t.prototype.normalizedEntries=function(){var e=this.Kids();return e||(e=this.dict.context.obj([]),this.dict.set(J.of(`Kids`),e)),{Kids:e}},t.fromDict=function(e,n){return new t(e,n)},t.create=function(e){var n=e.obj({});return new t(n,e.register(n))},t}(ld),Td=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.fromDict=function(e,n){return new t(e,n)},t}(md),Ed=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.MaxLen=function(){var e=this.dict.lookup(J.of(`MaxLen`));if(e instanceof q)return e},t.prototype.Q=function(){var e=this.dict.lookup(J.of(`Q`));if(e instanceof q)return e},t.prototype.setMaxLength=function(e){this.dict.set(J.of(`MaxLen`),q.of(e))},t.prototype.removeMaxLength=function(){this.dict.delete(J.of(`MaxLen`))},t.prototype.getMaxLength=function(){return this.MaxLen()?.asNumber()},t.prototype.setQuadding=function(e){this.dict.set(J.of(`Q`),q.of(e))},t.prototype.getQuadding=function(){return this.Q()?.asNumber()},t.prototype.setValue=function(e){this.dict.set(J.of(`V`),e)},t.prototype.removeValue=function(){this.dict.delete(J.of(`V`))},t.prototype.getValue=function(){var e=this.V();if(e instanceof Cu||e instanceof Y)return e},t.fromDict=function(e,n){return new t(e,n)},t.create=function(e){var n=e.obj({FT:`Tx`,Kids:[]});return new t(n,e.register(n))},t}(md),Dd=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.fromDict=function(e,n){return new t(e,n)},t.create=function(e){var n=e.obj({FT:`Btn`,Ff:yd.PushButton,Kids:[]});return new t(n,e.register(n))},t}(hd),Od=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.setValue=function(e){if(!this.getOnValues().includes(e)&&e!==J.of(`Off`))throw new ml;this.dict.set(J.of(`V`),e);for(var t=this.getWidgets(),n=0,r=t.length;ni)throw new dl(n,i);for(var a=n,o=0,s=r.size();oa)return l.insertLeafNode(e,a)||c;a-=l.Count().asNumber()}l instanceof iu&&--a}if(a===0){this.insertLeafKid(r.size(),e);return}throw new fl(n,`insertLeafNode`)},t.prototype.removeLeafNode=function(e,n){n===void 0&&(n=!0);var r=this.Kids(),i=this.Count().asNumber();if(e>=i)throw new dl(e,i);for(var a=e,o=0,s=r.size();oa){l.removeLeafNode(a,n),n&&l.Kids().size()===0&&r.remove(o);return}else a-=l.Count().asNumber();if(l instanceof iu)if(a===0){this.removeKid(o);return}else--a}throw new fl(e,`removeLeafNode`)},t.prototype.ascend=function(e){e(this);var t=this.Parent();t&&t.ascend(e)},t.prototype.traverse=function(e){for(var n=this.Kids(),r=0,i=n.size();r2**53-1)if(this.capNumbers){var r=`Parsed number that is too large for some PDF readers: `+e+`, using Number.MAX_SAFE_INTEGER instead.`;return console.warn(r),2**53-1}else{var r=`Parsed number that is too large for some PDF readers: `+e+`, not capping.`;console.warn(r)}return n},e.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&Fl[this.bytes.peek()];)this.bytes.next()},e.prototype.skipLine=function(){for(;!this.bytes.done();){var e=this.bytes.peek();if(e===qd||e===Jd)return;this.bytes.next()}},e.prototype.skipComment=function(){if(this.bytes.peek()!==K.Percent)return!1;for(;!this.bytes.done();){var e=this.bytes.peek();if(e===qd||e===Jd)return!0;this.bytes.next()}return!0},e.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},e.prototype.matchKeyword=function(e){for(var t=this.bytes.offset(),n=0,r=e.length;n=this.length},e.prototype.offset=function(){return this.idx},e.prototype.slice=function(e,t){return this.bytes.slice(e,t)},e.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},e.of=function(t){return new e(t)},e.fromPDFRawStream=function(t){return e.of(Qu(t).decode())},e}(),Zd=K.Space,Qd=K.CarriageReturn,$d=K.Newline,ef=[K.s,K.t,K.r,K.e,K.a,K.m],tf=[K.e,K.n,K.d,K.s,K.t,K.r,K.e,K.a,K.m],nf={header:[K.Percent,K.P,K.D,K.F,K.Dash],eof:[K.Percent,K.Percent,K.E,K.O,K.F],obj:[K.o,K.b,K.j],endobj:[K.e,K.n,K.d,K.o,K.b,K.j],xref:[K.x,K.r,K.e,K.f],trailer:[K.t,K.r,K.a,K.i,K.l,K.e,K.r],startxref:[K.s,K.t,K.a,K.r,K.t,K.x,K.r,K.e,K.f],true:[K.t,K.r,K.u,K.e],false:[K.f,K.a,K.l,K.s,K.e],null:[K.n,K.u,K.l,K.l],stream:ef,streamEOF1:Ko(ef,[Zd,Qd,$d]),streamEOF2:Ko(ef,[Qd,$d]),streamEOF3:Ko(ef,[Qd]),streamEOF4:Ko(ef,[$d]),endstream:tf,EOF1endstream:Ko([Qd,$d],tf),EOF2endstream:Ko([Qd],tf),EOF3endstream:Ko([$d],tf)},rf=function(e){U(t,e);function t(t,n,r){r===void 0&&(r=!1);var i=e.call(this,t,r)||this;return i.context=n,i}return t.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(nf.true))return Nl.True;if(this.matchKeyword(nf.false))return Nl.False;if(this.matchKeyword(nf.null))return Ul;var e=this.bytes.peek();if(e===K.LessThan&&this.bytes.peekAhead(1)===K.LessThan)return this.parseDictOrStream();if(e===K.LessThan)return this.parseHexString();if(e===K.LeftParen)return this.parseString();if(e===K.ForwardSlash)return this.parseName();if(e===K.LeftSquareBracket)return this.parseArray();if(Wd[e])return this.parseNumberOrRef();throw new xl(this.bytes.position(),e)},t.prototype.parseNumberOrRef=function(){var e=this.parseRawNumber();this.skipWhitespaceAndComments();var t=this.bytes.offset();if(Hd[this.bytes.peek()]){var n=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===K.R)return this.bytes.assertNext(K.R),Yl.of(e,n)}return this.bytes.moveTo(t),q.of(e)},t.prototype.parseHexString=function(){var e=``;for(this.bytes.assertNext(K.LessThan);!this.bytes.done()&&this.bytes.peek()!==K.GreaterThan;)e+=is(this.bytes.next());return this.bytes.assertNext(K.GreaterThan),Y.of(e)},t.prototype.parseString=function(){for(var e=0,t=!1,n=``;!this.bytes.done();){var r=this.bytes.next();if(n+=is(r),t||(r===K.LeftParen&&(e+=1),r===K.RightParen&&--e),r===K.BackSlash?t=!t:t&&(t=!1),e===0)return Cu.of(n.substring(1,n.length-1))}throw new wl(this.bytes.position())},t.prototype.parseName=function(){this.bytes.assertNext(K.ForwardSlash);for(var e=``;!this.bytes.done();){var t=this.bytes.peek();if(Fl[t]||Pl[t])break;e+=is(t),this.bytes.next()}return J.of(e)},t.prototype.parseArray=function(){this.bytes.assertNext(K.LeftSquareBracket),this.skipWhitespaceAndComments();for(var e=jl.withContext(this.context);this.bytes.peek()!==K.RightSquareBracket;){var t=this.parseObject();e.push(t),this.skipWhitespaceAndComments()}return this.bytes.assertNext(K.RightSquareBracket),e},t.prototype.parseDict=function(){this.bytes.assertNext(K.LessThan),this.bytes.assertNext(K.LessThan),this.skipWhitespaceAndComments();for(var e=new Map;!this.bytes.done()&&this.bytes.peek()!==K.GreaterThan&&this.bytes.peekAhead(1)!==K.GreaterThan;){var t=this.parseName(),n=this.parseObject();e.set(t,n),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(K.GreaterThan),this.bytes.assertNext(K.GreaterThan);var r=e.get(J.of(`Type`));return r===J.of(`Catalog`)?Bd.fromMapWithContext(e,this.context):r===J.of(`Pages`)?Vd.fromMapWithContext(e,this.context):r===J.of(`Page`)?iu.fromMapWithContext(e,this.context):Wl.fromMapWithContext(e,this.context)},t.prototype.parseDictOrStream=function(){var e=this.bytes.position(),t=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(nf.streamEOF1)&&!this.matchKeyword(nf.streamEOF2)&&!this.matchKeyword(nf.streamEOF3)&&!this.matchKeyword(nf.streamEOF4)&&!this.matchKeyword(nf.stream))return t;var n=this.bytes.offset(),r,i=t.get(J.of(`Length`));i instanceof q?(r=n+i.asNumber(),this.bytes.moveTo(r),this.skipWhitespaceAndComments(),this.matchKeyword(nf.endstream)||(this.bytes.moveTo(n),r=this.findEndOfStreamFallback(e))):r=this.findEndOfStreamFallback(e);var a=this.bytes.slice(n,r);return Kl.of(t,a)},t.prototype.findEndOfStreamFallback=function(e){for(var t=1,n=this.bytes.offset();!this.bytes.done()&&(n=this.bytes.offset(),this.matchKeyword(nf.stream)?t+=1:this.matchKeyword(nf.EOF1endstream)||this.matchKeyword(nf.EOF2endstream)||this.matchKeyword(nf.EOF3endstream)||this.matchKeyword(nf.endstream)?--t:this.bytes.next(),t!==0););if(t!==0)throw new Cl(e);return n},t.forBytes=function(e,n,r){return new t(Xd.of(e),n,r)},t.forByteStream=function(e,n,r){return r===void 0&&(r=!1),new t(e,n,r)},t}(Yd),af=function(e){U(t,e);function t(t,n){var r=e.call(this,Xd.fromPDFRawStream(t),t.dict.context)||this,i=t.dict;return r.alreadyParsed=!1,r.shouldWaitForTick=n||(function(){return!1}),r.firstOffset=i.lookup(J.of(`First`),q).asNumber(),r.objectCount=i.lookup(J.of(`N`),q).asNumber(),r}return t.prototype.parseIntoContext=function(){return Wo(this,void 0,void 0,function(){var e,t,n,r,i,a,o,s;return Go(this,function(c){switch(c.label){case 0:if(this.alreadyParsed)throw new al(`PDFObjectStreamParser`,`parseIntoContext`);this.alreadyParsed=!0,e=this.parseOffsetsAndObjectNumbers(),t=0,n=e.length,c.label=1;case 1:return t=K.Space&&t<=K.Tilde&&(this.matchKeyword(nf.xref)||this.matchKeyword(nf.trailer)||this.matchKeyword(nf.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(e);break}this.bytes.next()}},t.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var e=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(e)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},t.forBytesWithOptions=function(e,n,r,i){return new t(e,n,r,i)},t}(rf),cf=function(e){return 1<0&&(r[r.length]=+i),n[n.length]={cmd:t,args:r},r=[],i=``,a=!1),t=l;else if([` `,`,`].includes(l)||l===`-`&&i.length>0&&i[i.length-1]!==`e`||l===`.`&&a){if(i.length===0)continue;r.length===o?(n[n.length]={cmd:t,args:r},r=[+i],t===`M`&&(t=`L`),t===`m`&&(t=`l`)):r[r.length]=+i,a=l===`.`,i=[`-`,`.`].includes(l)?l:``}else i+=l,l===`.`&&(a=!0)}return i.length>0&&(r.length===o?(n[n.length]={cmd:t,args:r},r=[+i],t===`M`&&(t=`L`),t===`m`&&(t=`l`)):r[r.length]=+i),n[n.length]={cmd:t,args:r},n},jp=function(e){Q=$=Tp=Ep=Dp=Op=0;for(var t=[],n=0;n1&&(f=Math.sqrt(f),n*=f,r*=f);var p=d/n,m=u/n,h=-u/r,g=d/r,_=p*s+m*c,v=h*s+g*c,y=p*e+m*t,b=h*e+g*t,x=1/((y-_)*(y-_)+(b-v)*(b-v))-.25;x<0&&(x=0);var S=Math.sqrt(x);a===i&&(S=-S);var C=.5*(_+y)-S*(b-v),w=.5*(v+b)+S*(y-_),T=Math.atan2(v-w,_-C),E=Math.atan2(b-w,y-C)-T;E<0&&a===1?E+=2*Math.PI:E>0&&a===0&&(E-=2*Math.PI);for(var D=Math.ceil(Math.abs(E/(Math.PI*.5+.001))),O=[],k=0;ke.length)return i-1;var m=t.heightAtSize(i);if((m+m*.2)*a>Math.abs(n.height))return i-1;i+=1}return i},_m=function(e,t,n,r){for(var i=n.width/r,a=n.height,o=mm,s=hs(e);oi*.75)return o-1}if(t.heightAtSize(o,{descender:!1})>a)return o-1;o+=1}return o},vm=function(e){for(var t=e.length;t>0;t--)if(/\s/.test(e[t]))return t},ym=function(e,t,n,r){for(var i=e.length;i>0;){var a=e.substring(0,i),o=n.encodeText(a),s=n.widthOfTextAtSize(a,r);if(sf&&(f=C+x),m+s>p&&(p=m+s),l.push({text:y,encoded:b,width:x,height:s,x:C,y:m}),_=S?.trim()}return{fontSize:r,lineHeight:c,lines:l,bounds:{x:u,y:d,width:f-u,height:p-d}}},xm=function(e,t){var n=t.fontSize,r=t.font,i=t.bounds,a=t.cellCount,o=ps(ls(e));if(o.length>a)throw new um(o.length,a);(n===void 0||n===0)&&(n=_m(o,r,i,a));for(var s=i.width/a,c=r.heightAtSize(n,{descender:!1}),l=i.y+(i.height/2-c/2),u=[],d=i.x,f=i.y,p=i.x+i.width,m=i.y+i.height,h=0,g=0;hp&&(p=S+x),l+c>m&&(m=l+c),u.push({text:o,encoded:b,width:x,height:c,x:S,y:l}),h+=1,g+=y}return{fontSize:n,cells:u,bounds:{x:d,y:f,width:p-d,height:m-f}}},Sm=function(e,t){var n=t.alignment,r=t.fontSize,i=t.font,a=t.bounds,o=ps(ls(e));(r===void 0||r===0)&&(r=gm([o],i,a));var s=i.encodeText(o),c=i.widthOfTextAtSize(o,r),l=i.heightAtSize(r,{descender:!1}),u=n===pm.Left?a.x:n===pm.Center?a.x+a.width/2-c/2:n===pm.Right?a.x+a.width-c:a.x,d=a.y+(a.height/2-l/2);return{fontSize:r,line:{text:o,encoded:s,width:c,height:l,x:u,y:d},bounds:{x:u,y:d,width:c,height:l}}},Cm=function(e){return`normal`in e?e:{normal:e}},wm=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,Tm=function(e){var t=bs(e.getDefaultAppearance()??``,wm).match??[],n=Number(t[2]);return isFinite(n)?n:void 0},Em=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,Dm=function(e){var t=bs(e.getDefaultAppearance()??``,Em).match??[],n=t[1],r=t[2],i=t[3],a=t[4],o=t[5];if(o===`g`&&n)return hp(Number(n));if(o===`rg`&&n&&r&&i)return gp(Number(n),Number(r),Number(i));if(o===`k`&&n&&r&&i&&a)return _p(Number(n),Number(r),Number(i),Number(a))},Om=function(e,t,n,r){r===void 0&&(r=0);var i=[xp(t).toString(),ep(n?.name??`dummy__noop`,r).toString()].join(` +`);e.setDefaultAppearance(i)},km=function(e,t){var n=Dm(t),r=Dm(e.acroField),i=t.getRectangle(),a=t.getAppearanceCharacteristics(),o=t.getBorderStyle()?.getWidth()??0,s=bf(a?.getRotation()),c=xf(i,s),l=c.width,u=c.height,d=Jp(Ho(Ho({},i),{rotation:s})),f=gp(0,0,0),p=Cp(a?.getBorderColor())??f,m=Cp(a?.getBackgroundColor()),h=Cp(a?.getBackgroundColor(),.8),g=n??r??f;Om(n?t:e.acroField,g);var _={x:0+o/2,y:0+o/2,width:l-o,height:u-o,thickness:1.5,borderWidth:o,borderColor:p,markColor:g};return{normal:{on:Ko(d,Yp(Ho(Ho({},_),{color:m,filled:!0}))),off:Ko(d,Yp(Ho(Ho({},_),{color:m,filled:!1})))},down:{on:Ko(d,Yp(Ho(Ho({},_),{color:h,filled:!0}))),off:Ko(d,Yp(Ho(Ho({},_),{color:h,filled:!1})))}}},Am=function(e,t){var n=Dm(t),r=Dm(e.acroField),i=t.getRectangle(),a=t.getAppearanceCharacteristics(),o=t.getBorderStyle()?.getWidth()??0,s=bf(a?.getRotation()),c=xf(i,s),l=c.width,u=c.height,d=Jp(Ho(Ho({},i),{rotation:s})),f=gp(0,0,0),p=Cp(a?.getBorderColor())??f,m=Cp(a?.getBackgroundColor()),h=Cp(a?.getBackgroundColor(),.8),g=n??r??f;Om(n?t:e.acroField,g);var _={x:l/2,y:u/2,width:l-o,height:u-o,borderWidth:o,borderColor:p,dotColor:g};return{normal:{on:Ko(d,Xp(Ho(Ho({},_),{color:m,filled:!0}))),off:Ko(d,Xp(Ho(Ho({},_),{color:m,filled:!1})))},down:{on:Ko(d,Xp(Ho(Ho({},_),{color:h,filled:!0}))),off:Ko(d,Xp(Ho(Ho({},_),{color:h,filled:!1})))}}},jm=function(e,t,n){var r=Dm(t),i=Dm(e.acroField),a=Tm(t),o=Tm(e.acroField),s=t.getRectangle(),c=t.getAppearanceCharacteristics(),l=t.getBorderStyle(),u=c?.getCaptions(),d=u?.normal??``,f=u?.down??d??``,p=l?.getWidth()??0,m=bf(c?.getRotation()),h=xf(s,m),g=h.width,_=h.height,v=Jp(Ho(Ho({},s),{rotation:m})),y=gp(0,0,0),b=Cp(c?.getBorderColor()),x=Cp(c?.getBackgroundColor()),S=Cp(c?.getBackgroundColor(),.8),C={x:p,y:p,width:g-p*2,height:_-p*2},w=Sm(d,{alignment:pm.Center,fontSize:a??o,font:n,bounds:C}),T=Sm(f,{alignment:pm.Center,fontSize:a??o,font:n,bounds:C}),E=Math.min(w.fontSize,T.fontSize),D=r??i??y;Om(r||a!==void 0?t:e.acroField,D,n,E);var O={x:0+p/2,y:0+p/2,width:g-p,height:_-p,borderWidth:p,borderColor:b,textColor:D,font:n.name,fontSize:E};return{normal:Ko(v,Zp(Ho(Ho({},O),{color:x,textLines:[w.line]}))),down:Ko(v,Zp(Ho(Ho({},O),{color:S,textLines:[T.line]})))}},Mm=function(e,t,n){var r=Dm(t),i=Dm(e.acroField),a=Tm(t),o=Tm(e.acroField),s=t.getRectangle(),c=t.getAppearanceCharacteristics(),l=t.getBorderStyle(),u=e.getText()??``,d=l?.getWidth()??0,f=bf(c?.getRotation()),p=xf(s,f),m=p.width,h=p.height,g=Jp(Ho(Ho({},s),{rotation:f})),_=gp(0,0,0),v=Cp(c?.getBorderColor()),y=Cp(c?.getBackgroundColor()),b,x,S=+!e.isCombed(),C={x:d+S,y:d+S,width:m-(d+S)*2,height:h-(d+S)*2};if(e.isMultiline()){var w=bm(u,{alignment:e.getAlignment(),fontSize:a??o,font:n,bounds:C});b=w.lines,x=w.fontSize}else if(e.isCombed()){var w=xm(u,{fontSize:a??o,font:n,bounds:C,cellCount:e.getMaxLength()??0});b=w.cells,x=w.fontSize}else{var w=Sm(u,{alignment:e.getAlignment(),fontSize:a??o,font:n,bounds:C});b=[w.line],x=w.fontSize}var T=r??i??_;return Om(r||a!==void 0?t:e.acroField,T,n,x),Ko(g,$p({x:0+d/2,y:0+d/2,width:m-d,height:h-d,borderWidth:d??0,borderColor:v,textColor:T,font:n.name,fontSize:x,color:y,textLines:b,padding:S}))},Nm=function(e,t,n){var r=Dm(t),i=Dm(e.acroField),a=Tm(t),o=Tm(e.acroField),s=t.getRectangle(),c=t.getAppearanceCharacteristics(),l=t.getBorderStyle(),u=e.getSelected()[0]??``,d=l?.getWidth()??0,f=bf(c?.getRotation()),p=xf(s,f),m=p.width,h=p.height,g=Jp(Ho(Ho({},s),{rotation:f})),_=gp(0,0,0),v=Cp(c?.getBorderColor()),y=Cp(c?.getBackgroundColor()),b=1,x={x:d+b,y:d+b,width:m-(d+b)*2,height:h-(d+b)*2},S=Sm(u,{alignment:pm.Left,fontSize:a??o,font:n,bounds:x}),C=S.line,w=S.fontSize,T=r??i??_;return Om(r||a!==void 0?t:e.acroField,T,n,w),Ko(g,$p({x:0+d/2,y:0+d/2,width:m-d,height:h-d,borderWidth:d??0,borderColor:v,textColor:T,font:n.name,fontSize:w,color:y,textLines:[C],padding:b}))},Pm=function(e,t,n){var r=Dm(t),i=Dm(e.acroField),a=Tm(t),o=Tm(e.acroField),s=t.getRectangle(),c=t.getAppearanceCharacteristics(),l=t.getBorderStyle()?.getWidth()??0,u=bf(c?.getRotation()),d=xf(s,u),f=d.width,p=d.height,m=Jp(Ho(Ho({},s),{rotation:u})),h=gp(0,0,0),g=Cp(c?.getBorderColor()),_=Cp(c?.getBackgroundColor()),v=e.getOptions(),y=e.getSelected();e.isSorted()&&v.sort();for(var b=``,x=0,S=v.length;x1||n.length===1&&t)&&this.enableMultiselect();for(var i=Array(n.length),a=0,o=n.length;a1||n.length===1&&t)&&this.enableMultiselect();for(var r=Array(n.length),i=0,a=n.length;it)throw new dm(e.length,t,this.getName());this.markAsDirty(),this.disableRichFormatting(),e?this.acroField.setValue(Y.fromText(e)):this.acroField.removeValue()},t.prototype.getAlignment=function(){var e=this.acroField.getQuadding();return e===0?pm.Left:e===1?pm.Center:e===2?pm.Right:pm.Left},t.prototype.setAlignment=function(e){zc(e,`alignment`,pm),this.markAsDirty(),this.acroField.setQuadding(e)},t.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},t.prototype.setMaxLength=function(e){if(qc(e,`maxLength`,0,2**53-1),this.markAsDirty(),e===void 0)this.acroField.removeMaxLength();else{var t=this.getText();if(t&&t.length>e)throw new fm(t.length,e,this.getName());this.acroField.setMaxLength(e)}},t.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},t.prototype.setImage=function(e){for(var t=this.getAlignment(),n=t===pm.Center?Rm.Center:t===pm.Right?Rm.Right:Rm.Left,r=this.acroField.getWidgets(),i=0,a=r.length;i{let r=e.node.Annots();if(!r)return;let i=r?.size()??0;for(let e=0;e{let a=r.node.Annots();if(!a)return;let o=a?.size()??0;for(let r=0;r{if(e.level>n)return;let[i,a]=t?.[e.key]??[0,0],o={title:e.title,to:[i,0,a],open:!1,children:[]};if(e.children?.length>0)for(let t of e.children){let e=r(t);e&&o.children.push(e)}return o};return r(e)?.children??[]}var fh=(e,t)=>{for(let n of e){let e=t(n);`children`in n&&e!==!1&&fh(n.children,t)}},ph=e=>{let t=[];return fh(e,e=>void t.push(e)),t},mh=e=>{let t=0;return fh(e,e=>(t+=1,!(`open`in e&&!e.open))),t},hh=async(e,t)=>{let n=e.context.nextRef(),r=new WeakMap;for(let n of ph(t))r.set(n,e.context.nextRef());let i=(()=>{let t=[];return e.catalog.Pages().traverse((e,n)=>{e.get(e.context.obj(`Type`))?.toString()===`/Page`&&t.push(n)}),t})(),a=(t,n)=>{let{length:o}=t;for(let s=0;s0?(a(c.children,l),{First:r.get(c.children[0]),Last:r.get(c.children[c.children.length-1]),Count:mh(c.children)*(c.open?1:-1)}):{};e.context.assign(l,e.context.obj({Title:Y.fromText(c.title),Parent:n,...s>0?{Prev:r.get(t[s-1])}:{},...s0?{First:r.get(t[0]),Last:r.get(t[t.length-1])}:{},Count:o})),e.catalog.set(e.context.obj(`Outlines`),n)};async function gh(e,{headings:t,maxLevel:n,frontMatter:r,displayMetadata:i}){let a=await rh.load(e),o=await lh(a);return uh(a,o),hh(a,dh(t,o,n)),i&&_h(a,r??{}),e=await a.save(),e}function _h(e,{title:t,author:n,keywords:r,subject:i,creator:a,created_at:o,updated_at:s}){t&&e.setTitle(t,{showInWindowTitleBar:!0}),n&&(Array.isArray(n)?e.setAuthor(n.join(`, `)):e.setAuthor(n.toString())),r&&e.setKeywords(typeof r==`string`?[r]:r),i&&e.setSubject(i),e.setCreator(a??`Obsidian`),e.setProducer(`Obsidian`),e.setCreationDate(new Date(o??new Date)),e.setModificationDate(new Date(s??new Date))}function vh(e,t,n){let r={...e};return t&&n.forEach(e=>{let n=t[e];n!=null&&(r[e]=n)}),r}function yh(e,t){e=vh(e,t,[`headerTemplate`,`footerTemplate`]);let n=e.pageSize;e.pageSize==`Custom`&&e.pageWidth&&e.pageHeight&&(n={width:$a(e.pageWidth,210)/25.4,height:$a(e.pageHeight,297)/25.4});let r=e?.scale??100;(r>200||r<10)&&(r=100);let i={landscape:e?.landscape,printBackground:e?.printBackground,generateTaggedPDF:e?.generateTaggedPDF,pageSize:n,scale:r/100,margins:{marginType:`default`},displayHeaderFooter:e.displayHeader||e.displayFooter,headerTemplate:e.displayHeader?Xa(e.headerTemplate,t??{}):``,footerTemplate:e.displayFooter?Xa(e.footerTemplate,t??{}):``};return e.marginType==`0`?i.margins={marginType:`custom`,top:0,bottom:0,left:0,right:0}:e.marginType==`1`?i.margins={marginType:`default`}:e.marginType==`2`?i.margins={marginType:`custom`,top:.1,bottom:.1,left:.1,right:.1}:e.marginType==`3`&&(i.margins={marginType:`custom`,top:$a(e.marginTop,0)/25.4,bottom:$a(e.marginBottom,0)/25.4,left:$a(e.marginLeft,0)/25.4,right:$a(e.marginRight,0)/25.4}),i}async function bh(e,t,n,{doc:r,frontMatter:i}){console.debug(`output pdf:`,e);let a=yh(t,i);try{let o=await n.printToPDF(a);o=await gh(o,{headings:Ha(r),frontMatter:i,displayMetadata:t?.displayMetadata,maxLevel:Qa(t?.maxLevel,6)}),await ch.writeFile(e,o),t.open&&u.default.remote.shell.openPath(e)}catch(e){console.error(e)}}async function xh(e,t){let n=await u.default.remote.dialog.showSaveDialog({title:`Export to PDF`,defaultPath:e+(t?`-`+Date.now():``)+`.pdf`,filters:[{name:`All Files`,extensions:[`*`]},{name:`PDF`,extensions:[`pdf`]}],properties:[`showOverwriteConfirmation`,`createDirectory`]});if(!n.canceled)return n.filePath}async function Sh(e,t){let n=await u.default.remote.dialog.showOpenDialog({title:`Export to PDF`,defaultPath:e,properties:[`openDirectory`]});if(!n.canceled)return n.filePaths[0]}function Ch(e){return e.map(e=>({status:0,filename:e.file.name}))}function wh(e,t){return e[t].status=1,[...e]}var Th={A0:[841,1189],A1:[594,841],A2:[420,594],A3:[297,420],A4:[210,297],A5:[148,210],A6:[105,148],Legal:[216,356],Letter:[216,279],Tabloid:[279,432],Ledger:[432,279]},Eh=class{constructor(e,t){this.config=e,this.onResize=t}calc(e){let{pageSize:t,pageWidth:n}=this.config,r=Th?.[t]?.[0]??$a(n,210);return Math.floor(qa(r)/e.offsetWidth*100)/100}startObserver(e){this.observer=new ResizeObserver(()=>{this.onResize?.()}),this.observer.observe(e)}stopObserver(){this.observer?.disconnect()}},Dh,Oh=class{constructor(e){j(this,`value`,void 0),j(this,`next`,void 0),this.value=e}},kh=new WeakMap,Ah=new WeakMap,jh=new WeakMap;Dh=Symbol.iterator;var Mh=class{constructor(){ht(this,kh,void 0),ht(this,Ah,void 0),ht(this,jh,void 0),this.clear()}enqueue(e){var t;let n=new Oh(e);V(kh,this)?(V(Ah,this).next=n,B(Ah,this,n)):(B(kh,this,n),B(Ah,this,n)),B(jh,this,(t=V(jh,this),t++,t))}dequeue(){var e;let t=V(kh,this);if(t)return B(kh,this,V(kh,this).next),B(jh,this,(e=V(jh,this),e--,e)),t.value}peek(){if(V(kh,this))return V(kh,this).value}clear(){B(kh,this,void 0),B(Ah,this,void 0),B(jh,this,0)}get size(){return V(jh,this)}*[Dh](){let e=V(kh,this);for(;e;)yield e.value,e=e.next}*drain(){for(;V(kh,this);)yield this.dequeue()}};function Nh(e){let t=!1;if(typeof e==`object`&&({concurrency:e,rejectOnClear:t=!1}=e),Ph(e),typeof t!=`boolean`)throw TypeError("Expected `rejectOnClear` to be a boolean");let n=new Mh,r=0,i=()=>{r0&&(r++,n.dequeue().run())},a=()=>{r--,i()},o=async(e,t,n)=>{let r=(async()=>e(...n))();t(r);try{await r}catch{}a()},s=(t,a,s,c)=>{let l={reject:s};new Promise(e=>{l.run=e,n.enqueue(l)}).then(o.bind(void 0,t,a,c)),rnew Promise((n,r)=>{s(e,n,r,t)});return Object.defineProperties(c,{activeCount:{get:()=>r},pendingCount:{get:()=>n.size},clearQueue:{value(){if(!t){n.clear();return}let e=AbortSignal.abort().reason;for(;n.size>0;)n.dequeue().reject(e)}},concurrency:{get:()=>e,set(t){Ph(t),e=t,queueMicrotask(()=>{for(;r0;)i()})}},map:{async value(e,t){let n=Array.from(e,(e,n)=>this(t,e,n));return Promise.all(n)}}}),c}function Ph(e){if(!((Number.isInteger(e)||e===1/0)&&e>0))throw TypeError("Expected `concurrency` to be a number from 1 and up")}var Fh=zi(``),Ih=zi(`
`),Lh=zi(`
Rendering...
`,1),Rh=zi(`
`),zh=zi(`
`,1),Bh=zi(``);function Vh(e,t){Ze(t,!0);let n=require("fs").promises,r=Qt(()=>t.plugin.settings),i=er(!1),a=er(sr([])),o=er(sr([])),s=er(.75),c=er(void 0),u=er(sr([])),d=new Eh(t.config);function f(){H(c)&&nr(s,d.calc(H(c)),!0)}async function p(){await sleep(500),H(o).forEach(async(e,t)=>{let[n,r]=await e.executeJavaScript(`[document.body.offsetWidth, document.body.offsetHeight]`);H(a)[t]={...H(a)[t],printSize:`${n}×${r}px²\n${Ka(n)}×${Ka(r)}mm²`}})}async function m(){await f(),await p()}async function h(e,n,i){let a=Nh(Qa(H(r).concurrency)||5),o=qe(t.config);console.debug(`file list data:`,e,o);let s=e.map((e,t)=>a(async()=>{let n=await lo({...e,config:o});return i?.(t),n})),c=[...n??[],...await Promise.all(s)];return t.modal.file instanceof l.TFile&&await t.modal.app.workspace.getLeaf().openFile(t.modal.file),t.modal.multiplePdf||(c=t.modal.mergeDoc(c)),c.map(({doc:e,...t})=>({...t,doc:ho(e,e.title)}))}async function g(e=!0){if(e){let{data:e,docs:n}=await t.modal.getAllFiles();nr(u,Ch(e),!0),nr(a,await h(e,n,e=>{nr(u,wh(H(u),e),!0)}),!0)}nr(o,[],!0);let n=H(a).map(e=>new Promise(t=>{e.resolve=t}));await Promise.all(n),f(),await p()}function _(e){H(o).forEach((t,n)=>{t.executeJavaScript(` var _title = document.querySelector("h1.__title__"); if (_title) { _title.style.display = "${e?`block`:`none`}"; } - `);let r=H(a)[n]?.doc?.querySelector(`h1.__title__`);r&&(r.style.display=e?`block`:`none`)})}async function v(){let e=t.modal.file?.basename??t.modal.file?.name;if(t.modal.multiplePdf){let n=await Th(e);n&&await Promise.all(H(o).map(async(e,i)=>{await Ch(`${n}/${H(a)[i].file.basename}.pdf`,{...H(r),...t.config},e,H(a)[i])}))}else{let n=await wh(e,H(r).isTimestamp);n&&await Ch(n,{...H(r),...t.config},H(o)[0],H(a)[0])}}function y(){H(o)?.[-1]?.openDevTools()}function b(e,r){H(o).push(e);let a=async()=>{if(sr(i,!0),oo().forEach(async t=>{await e.insertCSS(t)}),t.config.cssSnippet&&t.config.cssSnippet!=`0`)try{let r=await n.readFile(t.config.cssSnippet,{encoding:`utf8`}),i=r.replaceAll(/@media print\s*{([^}]+)}/g,`$1`);await e.insertCSS(i),await e.insertCSS(r)}catch(e){console.warn(e)}await e.executeJavaScript(Co(r.doc)),co().forEach(async t=>{await e.insertCSS(t)}),r.resolve&&r.resolve()};return e.addEventListener(`dom-ready`,a),{destroy(){e.removeEventListener(`dom-ready`,a)}}}Wa(()=>{if(H(c))return d.startObserver(H(c)),g(!0),()=>{d.stopObserver()}});var x={calcPageSize:f,calcWebviewSize:p,handleChangeSize:m,renderPreview:g,toggleTitle:_,handlePrintToPDF:v,handleOpenDevTools:y},S=Uh(),C=xr(S),w=xr(C),T=e=>{var t=Bh();da(Cr(Sr(t),2),17,()=>H(u),sa,(e,t)=>{var n=zh(),r=xr(n),i=e=>{var t=Rh();va(t,(e,t)=>Lo?.(e,t),()=>`check`),Gi(e,t)},a=e=>{var t=Rh();va(t,(e,t)=>Lo?.(e,t),()=>`loader`),Gi(e,t)};oa(r,e=>{H(t).status?e(i):e(a,-1)});var o=Cr(r);ze(n),Br(()=>Ki(o,` ${H(t).filename??``}`)),Gi(e,n)}),Gi(e,t)},E=tn(()=>H(u).length>0&&!H(u).every(e=>e.status));oa(w,e=>{H(E)&&e(T)}),ze(C);var D=Cr(C,2);return da(D,21,()=>H(a),sa,(e,n,r)=>{var i=Hh(),a=Sr(i),o=e=>{var t=Vh(),i=xr(t);ze(t),Br(()=>Ki(i,`${r+1}-${H(n).doc.title??``}`)),Gi(e,t)};oa(a,e=>{t.modal.multiplePdf&&e(o)});var c=Cr(a,2),l=xr(c);let u;var d=xr(l,!0);ze(l);var f=Cr(l,2);Aa(f,`nodeintegration`,!0),va(f,(e,t)=>b?.(e,t),()=>H(n)),ze(c),Br(()=>{u=Ea(l,``,u,{visibility:t.config.pageSize===`Custom`?`visible`:`hidden`}),Ki(d,H(n).printSize??``),Ea(f,`--modal-scale: ${H(s)??``};`)}),Gi(e,i)}),ze(D),Ha(D,e=>sr(c,e),()=>H(c)),ze(S),Gi(e,S),et(x)}var Gh=Wi(`
`),Kh={hash:`svelte-184lr04`,code:`.toggle-container.svelte-184lr04 {display:flex;gap:0px;text-align:right;justify-content:right;position:absolute;top:0;right:0;z-index:99;}button.svelte-184lr04 {height:24px;width:56px;padding:2px 4px;border:1px solid var(--background-modifier-border);background:var(--background-primary);color:var(--text-normal);cursor:pointer;border-radius:0px;display:flex;justify-content:center;line-height:14px;gap:2px;font-size:12px;}button.svelte-184lr04:hover {background:var(--background-modifier-hover);}button.active.svelte-184lr04 {background:var(--interactive-accent);color:var(--text-on-accent);border-color:var(--interactive-accent);}`};function qh(e,t){$e(t,!0),_a(e,Kh);let n=Ua(t,`initialMode`,3,`html`),r=ar(fr(Oi(()=>Ye(n()))));function i(e){H(r)!==e&&(sr(r,e,!0),t.onChange?.(H(r)))}var a=Gh(),o=xr(a);let s;var c=xr(o);va(c,(e,t)=>Lo?.(e,t),()=>`globe`),Ea(Cr(c,2),``,{},{"margin-left":`2px`}),ze(o);var l=Cr(o,2);let u;var d=xr(l);va(d,(e,t)=>Lo?.(e,t),()=>`notebook`),Ea(Cr(d,2),``,{},{"margin-left":`2px`}),ze(l),ze(a),Br(()=>{s=wa(o,1,`svelte-184lr04`,null,s,{active:H(r)===`html`}),u=wa(l,1,`svelte-184lr04`,null,u,{active:H(r)===`pdf`})}),Ii(`click`,o,()=>i(`html`)),Ii(`click`,l,()=>i(`pdf`)),Gi(e,a),et()}Li([`click`]);var Jh=class{constructor(){this.queue=Promise.resolve()}async run(e){let t=this.queue.then(()=>e());return this.queue=t.catch(()=>{}),t}},Yh=Wi(``),Xh=Wi(`
`),Zh=Wi(`
Rendering...
`,1),Qh=Wi(`
Rendering
`),$h=Wi(`
`),eg=Wi(` `,1),tg=Wi(`
`),ng=Wi(``),rg={hash:`svelte-1czt1i6`,code:`.rendering.svelte-1czt1i6 {position:absolute;display:flex;flex-direction:row;align-items:center;justify-content:center;}`};function ig(e,t){$e(t,!0),_a(e,rg);let n=require(`fs`).promises,r=tn(()=>t.plugin.settings),i=ar(!1),a=ar(!1),o=ar(fr([])),s=ar(.75),c=ar(void 0),p=ar(fr([])),m=fr([]),h=fr([]),g=fr({}),_=Ye(t.config),v=tn(()=>Sh({...H(r),...t.config})),y=new kh(t.config);function b(){H(c)&&sr(s,y.calc(H(c)),!0)}async function x(){await b()}async function S(e,n){let i=Ih(io(H(r).concurrency)||5);console.log(`file list data:`,e);let a=e.map((e,r)=>i(async()=>{let i=await mo({app:t.modal.app,file:e.file,config:t.config});return n?.(r),i})),o=[...await Promise.all(a)];return console.log(o,t.modal.multiplePdf),!t.modal.multiplePdf&&o.length>1&&(o=t.modal.mergeDocV2(o)),o.map(({doc:e,...t})=>({...t,doc:yo(e,e.title)}))}async function C(e=!0){if(e){let{data:e}=await t.modal.getAllFilesV2();sr(o,Eh(e),!0),sr(p,await S(e,e=>{sr(o,Dh(H(o),e),!0)}),!0)}b()}async function w(e){sr(p,H(p).map(({doc:t,...n})=>{let r=t?.querySelector(`h1.__title__`);return r&&(r.style.display=e?`block`:`none`),{doc:t,...n}}),!0),H(c)?.querySelectorAll(`h1.__title__`).forEach(t=>{t.style.display=e?`block`:`none`})}function T(e,t){let n=()=>{m[t]={width:e.offsetWidth,height:e.offsetHeight}};n();let r=new ResizeObserver(n);return r.observe(e),{destroy:()=>r.disconnect()}}Wa(()=>{if(H(c))return y.startObserver(H(c)),C(!0),()=>{y.stopObserver()}}),Ga(()=>{document.querySelectorAll(`.print`).forEach(e=>e.remove())}),Pr(()=>{console.log(`config:`,Ye(t.config))});let E=new Jh;async function D({el:e,outputFile:i,title:a,onlyPreview:o=!1}){console.log(`printOptions:`,H(v));let s={...H(v),filepath:i};if(await E.run(async()=>{document.title=a,await To(e,s)}),o)return;let c=await n.readFile(i);c=await yh(c,{headings:Ja(e),frontMatter:H(p)[0].frontMatter,displayMetadata:H(r)?.displayMetadata,maxLevel:io(H(r)?.maxLevel,6)}),await n.writeFile(i,c),t.config.open&&u.remote.shell.openPath(i)}async function O({docs:e,outfiles:t,cb:n,onlyPreview:r}){let i=document.title;e.forEach(({doc:e})=>{e.style.display=`none`});for(let[i,a]of t.entries()){let{doc:t,file:o}=e[i],s=o.basename;t.style.display=`block`,await sleep(200),await D({el:t,outputFile:a,title:s,onlyPreview:r}),t.style.display=`none`,n&&await n(a)}document.title=i}async function k(){let e=t.modal.file?.basename??t.modal.file?.name,n=[];if(t.modal.multiplePdf){let t=await Th(e);if(!t)return!1;n.push(...H(p).map(e=>`${t}/${e.file.basename}.pdf`))}else{let t=await wh(e,H(r).isTimestamp);if(!t)return!1;n.push(t)}return await O({docs:H(p),outfiles:n}),!0}async function ee(){sr(a,!0);let e=await(0,l.loadPdfJs)(),r=f.tmpdir(),i=0;async function o(t){let r=await n.readFile(t),a=await e.getDocument({data:r}).promise;console.log(`loading tmp file`,a.numPages);for(let e=1;e<=a.numPages;e++){let t=await a.getPage(e),n=document.createElement(`canvas`),r=n.getContext(`2d`),o=t.getViewport({scale:5});n.height=o.height,n.width=o.width,await t.render({canvasContext:r,viewport:o}).promise,id.join(r,`obsidian-temp-${e.path.replace(/[/\\]/g,`_`)}-${Date.now()}.pdf`));console.log(`tempFiles`,e),await O({docs:H(p),outfiles:e,cb:o,onlyPreview:!0}),g[s]=e}h.length=i,sr(a,!1),console.log(`loaded tmp canvas pages:`,i)}function A(){document.win.electron.remote.getCurrentWebContents().openDevTools()}async function j(e){e===`pdf`?(sr(i,!0),await ee(),sr(a,!1)):sr(i,!1)}Pr(()=>{let e=Ye(t.config),n=[];console.log(`config changed:`,_,e);for(let t of[`pageSize`,`scale`,`landscape`,`marginBottom`,`marginLeft`,`marginRight`,`marginTop`,`marginType`,`displayHeader`,`displayFooter`,`showTitle`]){let r=t;e?.[r]!=_?.[r]&&n.push({key:r,oldValue:_[r],newValue:e[r]})}if(n.length==0||(_=e,!H(i)))return;sr(a,!0);let r=setTimeout(async()=>{await ee(),sr(a,!1)},300);return()=>clearTimeout(r)});var te={calcPageSize:b,handleChangeSize:x,renderPreview:C,toggleTitle:w,exportToPDF:D,printDocs:O,handlePrintToPDF:k,handleOpenDevTools:A},ne=ng(),re=xr(ne),ie=xr(re),ae=e=>{var t=Zh();da(Cr(Sr(t),2),17,()=>H(o),sa,(e,t)=>{var n=Xh(),r=xr(n),i=e=>{var t=Yh();va(t,(e,t)=>Lo?.(e,t),()=>`check`),Gi(e,t)},a=e=>{var t=Yh();va(t,(e,t)=>Lo?.(e,t),()=>`loader`),Gi(e,t)};oa(r,e=>{H(t).status?e(i):e(a,-1)});var o=Cr(r);ze(n),Br(()=>Ki(o,` ${H(t).filename??``}`)),Gi(e,n)}),Gi(e,t)},oe=tn(()=>H(o).length>0&&!H(o).every(e=>e.status));oa(ie,e=>{H(oe)&&e(ae)}),ze(re);var se=Cr(re,2),ce=e=>{var t=Qh();va(xr(t),(e,t)=>Lo?.(e,t),()=>`loader`),Be(2),ze(t),Gi(e,t)};oa(se,e=>{H(a)&&e(ce)});var le=Cr(se,2);qh(le,{initialMode:`html`,onChange:j});var ue=Cr(le,2),M=xr(ue),N=xr(M);let de;da(N,21,()=>H(p),sa,(e,n,r)=>{var i=eg(),a=Sr(i);let o;var s=xr(a,!0);ze(a);var c=Cr(a,2),l=e=>{var t=$h(),r=xr(t,!0);ze(t),Br(()=>Ki(r,H(n).file.name)),Gi(e,t)};oa(c,e=>{t.modal.multiplePdf&&e(l)});var u=Cr(c,2);va(u,(e,t)=>Ro?.(e,t),()=>H(n).doc),va(u,(e,t)=>T?.(e,t),()=>r),Br(e=>{o=Ea(a,``,o,{visibility:t.config.pageSize===`Custom`?`visible`:`hidden`}),Ki(s,e)},[()=>m[r]?`${m[r].width}×${m[r].height}px\n${Qa(m[r].width)}×${Qa(m[r].height)}mm`:``]),Gi(e,i)}),ze(N);var fe=Cr(N,2);let pe;return da(fe,20,()=>h,e=>e,(e,t)=>{var n=tg();va(n,(e,t)=>zo?.(e,t),()=>t),Gi(e,n)}),ze(fe),ze(M),ze(ue),Ha(ue,e=>sr(c,e),()=>H(c)),ze(ne),Br(()=>{de=Ea(N,`--modal-scale: ${H(s)??``};`,de,{display:H(i)?`none`:`block`}),pe=Ea(fe,``,pe,{display:H(i)?`block`:`none`})}),Gi(e,ne),et(te)}var ag=Wi(`
`);function og(e,t){$e(t,!0);let n=Ua(t,`plugin`,7),r=ar(fr(Oi(()=>Ye(t.modal.defaultConfig)))),i=ar(null);async function a(){await H(i)?.renderPreview(!1)}async function o(){await H(i)?.renderPreview(!0)}async function s(){await H(i)?.handleOpenDevTools()}async function c(){if(n().settings.prevConfig=H(r),await n().saveSettings(),H(r).pageSize==`Custom`&&(!ro(H(r).pageWidth??``)||!ro(H(r).pageHeight??``))){alert(`When the page size is Custom, the Width/Height cannot be empty.`);return}await H(i)?.handlePrintToPDF(),t.modal.close()}var l={onCssSnippetChange:a,refreshPreview:o,handleOpenDevTools:s,handleExport:c},u=ag(),d=xr(u),f=e=>{Ha(Wh(e,{get modal(){return t.modal},get plugin(){return n()},get config(){return H(r)}}),e=>sr(i,e,!0),()=>H(i))},p=e=>{Ha(ig(e,{get modal(){return t.modal},get plugin(){return n()},get config(){return H(r)}}),e=>sr(i,e,!0),()=>H(i))};return oa(d,e=>{n().settings?.version==`1`?e(f):e(p,-1)}),Uo(Cr(d,2),{get modal(){return t.modal},get plugin(){return n()},get pdfPreview(){return H(i)},handleExport:c,refreshPreview:o,get config(){return H(r)},set config(e){sr(r,e,!0)}}),ze(u),Gi(e,u),et(l)}require(`fs`).promises;var sg=class extends l.Modal{constructor(e,t,n){super(e.app),this.plugin=e,this.file=t,this.i18n=m.current,this.multiplePdf=n,this.defaultConfig={pageSize:`A4`,marginType:`1`,showTitle:e.settings.showTitle??!0,open:!0,scale:100,landscape:!1,marginTop:`10`,marginBottom:`10`,marginLeft:`10`,marginRight:`10`,displayHeader:e.settings.displayHeader??!0,displayFooter:e.settings.displayHeader??!0,cssSnippet:`0`,...e.settings.prevConfig??{}}}onOpen(){this.contentEl.empty(),this.containerEl.style.setProperty(`--dialog-width`,`60vw`),this.titleEl.setText(`Export to PDF`),this.component=qi(og,{target:this.contentEl,props:{modal:this,plugin:this.plugin}})}onClose(){this.component&&(Zi(this.component),this.component=void 0),this.contentEl.empty(),document.querySelectorAll(`.print`).forEach(e=>e.remove())}getFileCache(e){return this.app.metadataCache.getFileCache(e)}async getAllFiles(){let e=this.plugin.app,t=[],n=[];if(this.file instanceof l.TFolder){let n=eo(this.file);for(let r of n)t.push({app:e,file:r})}else{let{doc:r,frontMatter:i,file:a}=await po({app:e,file:this.file,config:this.defaultConfig});if(n.push({doc:r,frontMatter:i,file:a}),i.toc){let n=this.parseToc(r);for(let r of n)t.push({app:e,file:r.file,extra:r})}}return{data:t,docs:n}}async getAllFilesV2(){let e=[];if(this.file instanceof l.TFolder){let t=eo(this.file);for(let n of t)e.push({file:n})}else{let{frontmatter:t,links:n}=this.getFileCache(this.file)??{};if(e.push({file:this.file,toc:t?.toc}),t?.toc&&n)for(let t of n){let n=this.app.metadataCache.getFirstLinkpathDest(t.link,this.file.path);n instanceof l.TFile&&e.push({file:n})}}return{data:e,multiplePdf:this.multiplePdf}}parseToc(e){return this.getFileCache(this.file)?.links?.map(({link:t,displayText:n})=>{let r=crypto.randomUUID(),i=e.querySelector(`a[data-href="${t}"]`);return i&&(i.href=`#${r}`),{title:n,file:this.app.metadataCache.getFirstLinkpathDest(t,this.file.path),id:r}}).filter(e=>e.file instanceof l.TFile)??[]}mergeDoc(e){let{doc:t,frontMatter:n,file:r}=e[0],i=[];for(let{doc:n}of e){let e=n.querySelector(`.markdown-preview-view`);if(e){let n=t.createElement(`section`);Array.from(e.children).forEach(e=>{n.appendChild(t.importNode(e,!0))}),i.push(n)}}let a=t.querySelector(`.markdown-preview-view`);return a&&(a.innerHTML=``),i.forEach(e=>{a?.appendChild(e)}),[{doc:t,frontMatter:n,file:r,node:a}]}mergeDocV2(e){let t=document.body.createDiv(`print`);for(let{doc:n}of e){let e=n.querySelector(`.markdown-preview-view`);e&&t.appendChild(e),document.body.removeChild(n)}return[{...e[0],doc:t}]}cssSnippets(){let{snippets:e,enabledSnippets:t}=this.app?.customCss??{},n=this.app.vault.adapter.basePath;return Object.fromEntries(e?.filter(e=>!t.has(e)).map(e=>[d.default.join(n,`.obsidian/snippets`,e+`.css`),e]))}};function cg(e,t){for(let n in t)e.setAttribute(n,t[n])}var lg=(e,t=175)=>{let n=e.createEl(`a`,{href:`https://www.buymeacoffee.com/l1xnan`}).createEl(`img`);n.src=`https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=nathangeorge&button_colour=6a8696&font_colour=ffffff&font_family=Poppins&outline_colour=000000&coffee_colour=FFDD00`,n.alt=`Buy me a coffee`,n.width=t},ug=class extends l.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t,this.i18n=m.current}display(){let{containerEl:e}=this;e.empty();let t=new DocumentFragment;t.createDiv({text:`Support the continued development of this plugin.`}),new l.Setting(e).setDesc(t),lg(e),new l.Setting(e).setName(this.i18n.settings.version).addDropdown(e=>{e.addOptions(Object.fromEntries([`1`,`2`].map(e=>[e,`v${e}`]))).setValue(this.plugin.settings.version).onChange(async e=>{this.plugin.settings.version=e,this.plugin.saveSettings(),s(e)})}),new l.Setting(e).setName(this.i18n.settings.showTitle).addToggle(e=>e.setTooltip(this.i18n.settings.showTitle).setValue(this.plugin.settings.showTitle).onChange(async e=>{this.plugin.settings.showTitle=e,this.plugin.saveSettings()})),new l.Setting(e).setName(this.i18n.settings.displayHeader).addToggle(e=>e.setTooltip(`Display header`).setValue(this.plugin.settings.displayHeader).onChange(async e=>{this.plugin.settings.displayHeader=e,this.plugin.saveSettings()})),new l.Setting(e).setName(this.i18n.settings.displayFooter).addToggle(e=>e.setTooltip(`Display footer`).setValue(this.plugin.settings.displayFooter).onChange(async e=>{this.plugin.settings.displayFooter=e,this.plugin.saveSettings()})),new l.Setting(e).setName(this.i18n.settings.printBackground).setDesc(`Whether to print background graphics`).addToggle(e=>e.setValue(this.plugin.settings.printBackground).onChange(async e=>{this.plugin.settings.printBackground=e,this.plugin.saveSettings()})),new l.Setting(e).setName(`Generate tagged PDF`).setDesc(`Whether or not to generate a tagged (accessible) PDF. Defaults to false. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards.`).addToggle(e=>e.setValue(this.plugin.settings.generateTaggedPDF).onChange(async e=>{this.plugin.settings.generateTaggedPDF=e,this.plugin.saveSettings()})),new l.Setting(e).setName(this.i18n.settings.maxLevel).addDropdown(e=>{e.addOptions(Object.fromEntries([`1`,`2`,`3`,`4`,`5`,`6`].map(e=>[e,`h${e}`]))).setValue(this.plugin.settings.maxLevel).onChange(async e=>{this.plugin.settings.maxLevel=e,this.plugin.saveSettings()})}),new l.Setting(e).setName(this.i18n.settings.displayMetadata).setDesc(`Add frontMatter(title, author, keywords, subject creator, etc) to pdf metadata`).addToggle(e=>e.setValue(this.plugin.settings.displayMetadata).onChange(async e=>{this.plugin.settings.displayMetadata=e,this.plugin.saveSettings()})),new l.Setting(e).setName(`Advanced`).setHeading();let n=new l.Setting(e);n.settingEl.setAttribute(`style`,`display: grid; grid-template-columns: 1fr;`),n.setName(this.i18n.settings.headerTemplate).setDesc(`HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: date (formatted print date), title (document title), url (document location), pageNumber (current page number) and totalPages (total pages in the document). For example, would generate span containing the title.`);let r=new l.TextAreaComponent(n.controlEl);cg(r.inputEl,{style:`margin-top: 12px; width: 100%; height: 6vh;`}),r.setValue(this.plugin.settings.headerTemplate).onChange(async e=>{this.plugin.settings.headerTemplate=e,this.plugin.saveSettings()});let i=new l.Setting(e);i.settingEl.setAttribute(`style`,`display: grid; grid-template-columns: 1fr;`),i.setName(this.i18n.settings.footerTemplate).setDesc(`HTML template for the print footer. Should use the same format as the headerTemplate.`);let a=new l.TextAreaComponent(i.controlEl);cg(a.inputEl,{style:`margin-top: 12px; width: 100%; height: 6vh;`}),a.setValue(this.plugin.settings.footerTemplate).onChange(async e=>{this.plugin.settings.footerTemplate=e,this.plugin.saveSettings()}),new l.Setting(e).setName(this.i18n.settings.isTimestamp).setDesc(`Add timestamp to output file name`).addToggle(e=>{e.setValue(this.plugin.settings.isTimestamp).onChange(async e=>{this.plugin.settings.isTimestamp=e,await this.plugin.saveSettings()})});let o=new l.Setting(e).setName(this.i18n.settings.enabledCss).setDesc(`Select the css snippet that are not enabled`).addToggle(e=>{e.setValue(this.plugin.settings.enabledCss).onChange(async e=>{this.plugin.settings.enabledCss=e,await this.plugin.saveSettings()})}),s=e=>{o.settingEl.hidden=e!==`1`};s(this.plugin.settings.version),new l.Setting(e).setName(this.i18n.settings.concurrency).setDesc(`Limit the number of concurrent renders`).addText(e=>{let t=this.plugin.settings?.concurrency;e.setValue(t?.length>0?t:`5`).onChange(async e=>{this.plugin.settings.concurrency=e,await this.plugin.saveSettings()})}),new l.Setting(e).setName(`Debug`).setHeading(),new l.Setting(e).setName(this.i18n.settings.debugMode).setDesc(`This is useful for troubleshooting.`).addToggle(e=>{e.setValue(this.plugin.settings.debug).onChange(async e=>{this.plugin.settings.debug=e,await this.plugin.saveSettings()})})}},dg=require(`fs`).promises,fg=process.env.NODE_ENV===`development`,pg={showTitle:!0,maxLevel:`6`,displayHeader:!0,displayFooter:!0,headerTemplate:`
`,footerTemplate:`
/
`,printBackground:!1,generateTaggedPDF:!1,displayMetadata:!1,debug:!1,isTimestamp:!1,enabledCss:!1,concurrency:`5`,version:`2`},mg=class extends l.Plugin{constructor(e,t){super(e,t),this.i18n=m.current}async onload(){await this.loadSettings(),this.registerCommand(),this.registerSetting(),this.registerEvents()}registerCommand(){this.addCommand({id:`export-current-file-to-pdf`,name:this.i18n.exportCurrentFile,checkCallback:e=>{let t=this.app.workspace.getActiveViewOfType(l.MarkdownView)?.file;return t?(e||new sg(this,t).open(),!0):!1}})}registerSetting(){this.addSettingTab(new ug(this.app,this))}registerEvents(){this.registerEvent(this.app.workspace.on(`file-menu`,(e,t)=>{let n=t instanceof l.TFolder?`Export folder to PDF`:`Better Export PDF`;fg&&(n=`${n} (dev)`),e.addItem(e=>{e.setTitle(n).setIcon(`download`).setSection(`action`).onClick(async()=>{new sg(this,t).open()})})})),this.registerEvent(this.app.workspace.on(`file-menu`,(e,t)=>{if(t instanceof l.TFolder){let n=`Export to PDF...`;fg&&(n=`${n} (dev)`),e.addItem(e=>{e.setTitle(n).setIcon(`lucide-folder-down`).setSection(`action`);let r=e.setSubmenu();r.addItem(e=>e.setTitle(`Export each file to PDF`).setIcon(`lucide-file-stack`).onClick(async()=>{new sg(this,t,!0).open()})),r.addItem(e=>e.setTitle(`Generate TOC.md file`).setIcon(`lucide-file-text`).onClick(async()=>{await this.generateToc(t)}))})}}))}async generateToc(e){let t=this.app.vault.adapter.basePath,n=d.default.join(t,e.path,`_TOC_.md`),r=`---\ntoc: true\ntitle: ${e.name}\n---\n`;if(await dg.writeFile(n,r),e instanceof l.TFolder){let t=eo(e);for(let e of t)e.name!=`_TOC_.md`&&await dg.appendFile(n,`[[${e.path}]]\n`)}}onunload(){}async loadSettings(){this.settings=Object.assign({},pg,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}changeConfig(){let e=this.app.vault?.getConfig(`theme`)===`obsidian`;e&&(document.body.addClass(`theme-light`),document.body.removeClass(`theme-dark`)),document.body.removeClass(`theme-dark`);let t=document.body.createDiv(`print`);t.addEventListener(`click`,function(){t.detach(),e&&(document.body.removeClass(`theme-light`),document.body.addClass(`theme-dark`))});let n=document.body.createDiv(`print`).createDiv(`markdown-preview-view markdown-rendered`);n.toggleClass(`rtl`,this.app.vault.getConfig(`rightToLeft`)),n.toggleClass(`show-frontmatter`,this.app.vault.getConfig(`showFrontmatter`)),n.createEl(`h1`,{text:`xxxxx`})}};module.exports=mg; + `);let r=H(a)[n]?.doc?.querySelector(`h1.__title__`);r&&(r.style.display=e?`block`:`none`)})}async function v(){let e=t.modal.file?.basename??t.modal.file?.name;if(t.modal.multiplePdf){let n=await Sh(e);n&&await Promise.all(H(o).map(async(e,i)=>{await bh(`${n}/${H(a)[i].file.basename}.pdf`,{...H(r),...t.config},e,H(a)[i])}))}else{let n=await xh(e,H(r).isTimestamp);n&&await bh(n,{...H(r),...t.config},H(o)[0],H(a)[0])}}function y(){H(o)?.[-1]?.openDevTools()}function b(e,r){H(o).push(e);let a=async()=>{if(nr(i,!0),ro().forEach(async t=>{await e.insertCSS(t)}),t.config.cssSnippet&&t.config.cssSnippet!=`0`)try{let r=await n.readFile(t.config.cssSnippet,{encoding:`utf8`}),i=r.replaceAll(/@media print\s*{([^}]+)}/g,`$1`);await e.insertCSS(i),await e.insertCSS(r)}catch(e){console.warn(e)}await e.executeJavaScript(bo(r.doc)),ao().forEach(async t=>{await e.insertCSS(t)}),r.resolve&&r.resolve()};return e.addEventListener(`dom-ready`,a),{destroy(){e.removeEventListener(`dom-ready`,a)}}}za(()=>{if(H(c))return d.startObserver(H(c)),g(!0),()=>{d.stopObserver()}});var x={calcPageSize:f,calcWebviewSize:p,handleChangeSize:m,renderPreview:g,toggleTitle:_,handlePrintToPDF:v,handleOpenDevTools:y},S=Bh(),C=gr(S),w=gr(C),T=e=>{var t=Lh();oa(vr(_r(t),2),17,()=>H(u),na,(e,t)=>{var n=Ih(),r=gr(n),i=e=>{var t=Fh();pa(t,(e,t)=>Po?.(e,t),()=>`check`),Bi(e,t)},a=e=>{var t=Fh();pa(t,(e,t)=>Po?.(e,t),()=>`loader`),Bi(e,t)};ta(r,e=>{H(t).status?e(i):e(a,-1)});var o=vr(r);ze(n),Fr(()=>Vi(o,` ${H(t).filename??``}`)),Bi(e,n)}),Bi(e,t)},E=Qt(()=>H(u).length>0&&!H(u).every(e=>e.status));ta(w,e=>{H(E)&&e(T)}),ze(C);var D=vr(C,2);return oa(D,21,()=>H(a),na,(e,n,r)=>{var i=zh(),a=_r(i),o=e=>{var t=Rh(),i=gr(t);ze(t),Fr(()=>Vi(i,`${r+1}-${H(n).doc.title??``}`)),Bi(e,t)};ta(a,e=>{t.modal.multiplePdf&&e(o)});var c=vr(a,2),l=gr(c);let u;var d=gr(l,!0);ze(l);var f=vr(l,2);Ta(f,`nodeintegration`,!0),pa(f,(e,t)=>b?.(e,t),()=>H(n)),ze(c),Fr(()=>{u=xa(l,``,u,{visibility:t.config.pageSize===`Custom`?`visible`:`hidden`}),Vi(d,H(n).printSize??``),xa(f,`--modal-scale: ${H(s)??``};`)}),Bi(e,i)}),ze(D),La(D,e=>nr(c,e),()=>H(c)),ze(S),Bi(e,S),Qe(x)}var Hh=zi(`
`),Uh={hash:`svelte-184lr04`,code:`.toggle-container.svelte-184lr04 {display:flex;gap:0px;text-align:right;justify-content:right;position:absolute;top:0;right:0;z-index:99;}button.svelte-184lr04 {height:24px;width:56px;padding:2px 4px;border:1px solid var(--background-modifier-border);background:var(--background-primary);color:var(--text-normal);cursor:pointer;border-radius:0px;display:flex;justify-content:center;line-height:14px;gap:2px;font-size:12px;}button.svelte-184lr04:hover {background:var(--background-modifier-hover);}button.active.svelte-184lr04 {background:var(--interactive-accent);color:var(--text-on-accent);border-color:var(--interactive-accent);}`};function Wh(e,t){Ze(t,!0),fa(e,Uh);let n=Ra(t,`initialMode`,3,`html`),r=er(sr(Ci(()=>qe(n()))));function i(e){H(r)!==e&&(nr(r,e,!0),t.onChange?.(H(r)))}var a=Hh(),o=gr(a);let s;var c=gr(o);pa(c,(e,t)=>Po?.(e,t),()=>`globe`),xa(vr(c,2),``,{},{"margin-left":`2px`}),ze(o);var l=vr(o,2);let u;var d=gr(l);pa(d,(e,t)=>Po?.(e,t),()=>`notebook`),xa(vr(d,2),``,{},{"margin-left":`2px`}),ze(l),ze(a),Fr(()=>{s=ya(o,1,`svelte-184lr04`,null,s,{active:H(r)===`html`}),u=ya(l,1,`svelte-184lr04`,null,u,{active:H(r)===`pdf`})}),ji(`click`,o,()=>i(`html`)),ji(`click`,l,()=>i(`pdf`)),Bi(e,a),Qe()}Mi([`click`]);var Gh=class{constructor(){this.queue=Promise.resolve()}async run(e){let t=this.queue.then(()=>e());return this.queue=t.catch(()=>{}),t}},Kh=zi(``),qh=zi(`
`),Jh=zi(`
Rendering...
`,1),Yh=zi(`
Rendering
`),Xh=zi(`
`),Zh=zi(` `,1),Qh=zi(`
`),$h=zi(``),eg={hash:`svelte-1czt1i6`,code:`.rendering.svelte-1czt1i6 {position:absolute;display:flex;flex-direction:row;align-items:center;justify-content:center;}`};function tg(e,t){Ze(t,!0),fa(e,eg);let n=require("fs").promises,r=Qt(()=>t.plugin.settings),i=er(!1),a=er(!1),o=er(sr([])),s=er(.75),c=er(void 0),p=er(sr([])),m=sr([]),h=sr([]),g=sr({}),_=qe(t.config),v=Qt(()=>yh({...H(r),...t.config})),y=new Eh(t.config);function b(){H(c)&&nr(s,y.calc(H(c)),!0)}async function x(){await b()}async function S(e,n){let i=Nh(Qa(H(r).concurrency)||5);console.debug(`file list data:`,e);let a=e.map((e,r)=>i(async()=>{let i=await uo({app:t.modal.app,file:e.file,config:t.config});return n?.(r),i})),o=[...await Promise.all(a)];return console.debug(o,t.modal.multiplePdf),!t.modal.multiplePdf&&o.length>1&&(o=t.modal.mergeDocV2(o)),o.map(({doc:e,...t})=>({...t,doc:go(e,e.title)}))}async function C(e=!0){if(e){let{data:e}=await t.modal.getAllFilesV2();nr(o,Ch(e),!0),nr(p,await S(e,e=>{nr(o,wh(H(o),e),!0)}),!0)}b()}async function w(e){nr(p,H(p).map(({doc:t,...n})=>{let r=t?.querySelector(`h1.__title__`);return r&&(r.style.display=e?`block`:`none`),{doc:t,...n}}),!0),H(c)?.querySelectorAll(`h1.__title__`).forEach(t=>{t.style.display=e?`block`:`none`})}function T(e,t){let n=()=>{m[t]={width:e.offsetWidth,height:e.offsetHeight}};n();let r=new ResizeObserver(n);return r.observe(e),{destroy:()=>r.disconnect()}}za(()=>{if(H(c))return y.startObserver(H(c)),C(!0),()=>{y.stopObserver()}}),Ba(()=>{document.querySelectorAll(`.print`).forEach(e=>e.remove())}),kr(()=>{console.debug(`config:`,qe(t.config))});let E=new Gh;async function D({el:e,outputFile:i,title:a,onlyPreview:o=!1}){console.debug(`printOptions:`,H(v));let s={...H(v),filepath:i};if(await E.run(async()=>{document.title=a,await So(e,s)}),o)return;let c=await n.readFile(i);c=await gh(c,{headings:Ha(e),frontMatter:H(p)[0].frontMatter,displayMetadata:H(r)?.displayMetadata,maxLevel:Qa(H(r)?.maxLevel,6)}),await n.writeFile(i,c),t.config.open&&u.remote.shell.openPath(i)}async function O({docs:e,outfiles:t,cb:n,onlyPreview:r}){let i=document.title;e.forEach(({doc:e})=>{e.style.display=`none`});for(let[i,a]of t.entries()){let{doc:t,file:o}=e[i],s=o.basename;t.style.display=`block`,await sleep(200),await D({el:t,outputFile:a,title:s,onlyPreview:r}),t.style.display=`none`,n&&await n(a)}document.title=i}async function k(){let e=t.modal.file?.basename??t.modal.file?.name,n=[];if(t.modal.multiplePdf){let t=await Sh(e);if(!t)return!1;n.push(...H(p).map(e=>`${t}/${e.file.basename}.pdf`))}else{let t=await xh(e,H(r).isTimestamp);if(!t)return!1;n.push(t)}return await O({docs:H(p),outfiles:n}),!0}async function ee(){nr(a,!0);let e=await(0,l.loadPdfJs)(),r=f.tmpdir(),i=0;async function o(t){let r=await n.readFile(t),a=await e.getDocument({data:r}).promise;console.debug(`loading tmp file`,a.numPages);for(let e=1;e<=a.numPages;e++){let t=await a.getPage(e),n=document.createElement(`canvas`),r=n.getContext(`2d`),o=t.getViewport({scale:5});n.height=o.height,n.width=o.width,await t.render({canvasContext:r,viewport:o}).promise,id.join(r,`obsidian-temp-${e.path.replace(/[/\\]/g,`_`)}-${Date.now()}.pdf`));console.debug(`tempFiles`,e),await O({docs:H(p),outfiles:e,cb:o,onlyPreview:!0}),g[s]=e}h.length=i,nr(a,!1),console.debug(`loaded tmp canvas pages:`,i)}function A(){document.win.electron.remote.getCurrentWebContents().openDevTools()}async function j(e){e===`pdf`?(nr(i,!0),await ee(),nr(a,!1)):nr(i,!1)}kr(()=>{let e=qe(t.config),n=[];for(let t of[`pageSize`,`scale`,`landscape`,`marginBottom`,`marginLeft`,`marginRight`,`marginTop`,`marginType`,`displayHeader`,`displayFooter`,`showTitle`]){let r=t;e?.[r]!=_?.[r]&&n.push({key:r,oldValue:_[r],newValue:e[r]})}if(n.length==0||(_=e,!H(i)))return;nr(a,!0);let r=setTimeout(async()=>{await ee(),nr(a,!1)},300);return()=>clearTimeout(r)});var te={calcPageSize:b,handleChangeSize:x,renderPreview:C,toggleTitle:w,exportToPDF:D,printDocs:O,handlePrintToPDF:k,handleOpenDevTools:A},ne=$h(),re=gr(ne),ie=gr(re),ae=e=>{var t=Jh();oa(vr(_r(t),2),17,()=>H(o),na,(e,t)=>{var n=qh(),r=gr(n),i=e=>{var t=Kh();pa(t,(e,t)=>Po?.(e,t),()=>`check`),Bi(e,t)},a=e=>{var t=Kh();pa(t,(e,t)=>Po?.(e,t),()=>`loader`),Bi(e,t)};ta(r,e=>{H(t).status?e(i):e(a,-1)});var o=vr(r);ze(n),Fr(()=>Vi(o,` ${H(t).filename??``}`)),Bi(e,n)}),Bi(e,t)},oe=Qt(()=>H(o).length>0&&!H(o).every(e=>e.status));ta(ie,e=>{H(oe)&&e(ae)}),ze(re);var se=vr(re,2),ce=e=>{var t=Yh();pa(gr(t),(e,t)=>Po?.(e,t),()=>`loader`),Be(2),ze(t),Bi(e,t)};ta(se,e=>{H(a)&&e(ce)});var le=vr(se,2);Wh(le,{initialMode:`html`,onChange:j});var ue=vr(le,2),M=gr(ue),N=gr(M);let de;oa(N,21,()=>H(p),na,(e,n,r)=>{var i=Zh(),a=_r(i);let o;var s=gr(a,!0);ze(a);var c=vr(a,2),l=e=>{var t=Xh(),r=gr(t,!0);ze(t),Fr(()=>Vi(r,H(n).file.name)),Bi(e,t)};ta(c,e=>{t.modal.multiplePdf&&e(l)});var u=vr(c,2);pa(u,(e,t)=>Fo?.(e,t),()=>H(n).doc),pa(u,(e,t)=>T?.(e,t),()=>r),Fr(e=>{o=xa(a,``,o,{visibility:t.config.pageSize===`Custom`?`visible`:`hidden`}),Vi(s,e)},[()=>m[r]?`${m[r].width}×${m[r].height}px\n${Ka(m[r].width)}×${Ka(m[r].height)}mm`:``]),Bi(e,i)}),ze(N);var fe=vr(N,2);let pe;return oa(fe,20,()=>h,e=>e,(e,t)=>{var n=Qh();pa(n,(e,t)=>Io?.(e,t),()=>t),Bi(e,n)}),ze(fe),ze(M),ze(ue),La(ue,e=>nr(c,e),()=>H(c)),ze(ne),Fr(()=>{de=xa(N,`--modal-scale: ${H(s)??``};`,de,{display:H(i)?`none`:`block`}),pe=xa(fe,``,pe,{display:H(i)?`block`:`none`})}),Bi(e,ne),Qe(te)}var ng=zi(`
`);function rg(e,t){Ze(t,!0);let n=Ra(t,`plugin`,7),r=er(sr(Ci(()=>qe(t.modal.defaultConfig)))),i=er(null);async function a(){await H(i)?.renderPreview(!1)}async function o(){await H(i)?.renderPreview(!0)}async function s(){await H(i)?.handleOpenDevTools()}async function c(){if(n().settings.prevConfig=H(r),await n().saveSettings(),H(r).pageSize==`Custom`&&(!Za(H(r).pageWidth??``)||!Za(H(r).pageHeight??``))){alert(`When the page size is Custom, the Width/Height cannot be empty.`);return}await H(i)?.handlePrintToPDF(),t.modal.close()}var l={onCssSnippetChange:a,refreshPreview:o,handleOpenDevTools:s,handleExport:c},u=ng(),d=gr(u),f=e=>{La(Vh(e,{get modal(){return t.modal},get plugin(){return n()},get config(){return H(r)}}),e=>nr(i,e,!0),()=>H(i))},p=e=>{La(tg(e,{get modal(){return t.modal},get plugin(){return n()},get config(){return H(r)}}),e=>nr(i,e,!0),()=>H(i))};return ta(d,e=>{n().settings?.version==`1`?e(f):e(p,-1)}),Bo(vr(d,2),{get modal(){return t.modal},get plugin(){return n()},get pdfPreview(){return H(i)},handleExport:c,refreshPreview:o,get config(){return H(r)},set config(e){nr(r,e,!0)}}),ze(u),Bi(e,u),Qe(l)}require("fs").promises;var ig=class extends l.Modal{constructor(e,t,n){super(e.app),this.plugin=e,this.file=t,this.i18n=m.current,this.multiplePdf=n,this.defaultConfig={pageSize:`A4`,marginType:`1`,showTitle:e.settings.showTitle??!0,open:!0,scale:100,landscape:!1,marginTop:`10`,marginBottom:`10`,marginLeft:`10`,marginRight:`10`,displayHeader:e.settings.displayHeader??!0,displayFooter:e.settings.displayHeader??!0,cssSnippet:`0`,...e.settings.prevConfig??{}}}onOpen(){this.contentEl.empty(),this.containerEl.style.setProperty(`--dialog-width`,`60vw`),this.titleEl.setText(`Export to PDF`);let e=eo();console.debug(`检测到以下衍生变量在亮色主题下未重置,即将进行注入:`,e),to(e),this.component=Hi(rg,{target:this.contentEl,props:{modal:this,plugin:this.plugin}})}onClose(){this.component&&(Ki(this.component),this.component=void 0),this.contentEl.empty(),document.querySelectorAll(`.print`).forEach(e=>e.remove()),no()}getFileCache(e){return this.app.metadataCache.getFileCache(e)}async getAllFiles(){let e=this.plugin.app,t=[],n=[];if(this.file instanceof l.TFolder){let n=Ja(this.file);for(let r of n)t.push({app:e,file:r})}else{let{doc:r,frontMatter:i,file:a}=await lo({app:e,file:this.file,config:this.defaultConfig});if(n.push({doc:r,frontMatter:i,file:a}),i.toc){let n=this.parseToc(r);for(let r of n)t.push({app:e,file:r.file,extra:r})}}return{data:t,docs:n}}async getAllFilesV2(){let e=[];if(this.file instanceof l.TFolder){let t=Ja(this.file);for(let n of t)e.push({file:n})}else{let{frontmatter:t,links:n}=this.getFileCache(this.file)??{};if(e.push({file:this.file,toc:t?.toc}),t?.toc&&n)for(let t of n){let n=this.app.metadataCache.getFirstLinkpathDest(t.link,this.file.path);n instanceof l.TFile&&e.push({file:n})}}return{data:e,multiplePdf:this.multiplePdf}}parseToc(e){return this.getFileCache(this.file)?.links?.map(({link:t,displayText:n})=>{let r=crypto.randomUUID(),i=e.querySelector(`a[data-href="${t}"]`);return i&&(i.href=`#${r}`),{title:n,file:this.app.metadataCache.getFirstLinkpathDest(t,this.file.path),id:r}}).filter(e=>e.file instanceof l.TFile)??[]}mergeDoc(e){let{doc:t,frontMatter:n,file:r}=e[0],i=[];for(let{doc:n}of e){let e=n.querySelector(`.markdown-preview-view`);if(e){let n=t.createElement(`section`);Array.from(e.children).forEach(e=>{n.appendChild(t.importNode(e,!0))}),i.push(n)}}let a=t.querySelector(`.markdown-preview-view`);return a&&(a.innerHTML=``),i.forEach(e=>{a?.appendChild(e)}),[{doc:t,frontMatter:n,file:r,node:a}]}mergeDocV2(e){let t=document.body.createDiv(`print`);for(let{doc:n}of e){let e=n.querySelector(`.markdown-preview-view`);e&&t.appendChild(e),document.body.removeChild(n)}return[{...e[0],doc:t}]}cssSnippets(){let{snippets:e,enabledSnippets:t}=this.app?.customCss??{},n=this.app.vault.adapter.basePath;return Object.fromEntries(e?.filter(e=>!t.has(e)).map(e=>[d.default.join(n,`.obsidian/snippets`,e+`.css`),e]))}};function ag(e,t){for(let n in t)e.setAttribute(n,t[n])}var og=(e,t=175)=>{let n=e.createEl(`a`,{href:`https://www.buymeacoffee.com/l1xnan`}).createEl(`img`);n.src=`https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=nathangeorge&button_colour=6a8696&font_colour=ffffff&font_family=Poppins&outline_colour=000000&coffee_colour=FFDD00`,n.alt=`Buy me a coffee`,n.width=t},sg=class extends l.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t,this.i18n=m.current}display(){let{containerEl:e}=this;e.empty();let t=new DocumentFragment;t.createDiv({text:`Support the continued development of this plugin.`}),new l.Setting(e).setDesc(t),og(e),new l.Setting(e).setName(this.i18n.settings.version).addDropdown(e=>{e.addOptions(Object.fromEntries([`1`,`2`].map(e=>[e,`v${e}`]))).setValue(this.plugin.settings.version).onChange(async e=>{this.plugin.settings.version=e,this.plugin.saveSettings(),s(e)})}),new l.Setting(e).setName(this.i18n.settings.showTitle).addToggle(e=>e.setTooltip(this.i18n.settings.showTitle).setValue(this.plugin.settings.showTitle).onChange(async e=>{this.plugin.settings.showTitle=e,this.plugin.saveSettings()})),new l.Setting(e).setName(this.i18n.settings.displayHeader).addToggle(e=>e.setTooltip(`Display header`).setValue(this.plugin.settings.displayHeader).onChange(async e=>{this.plugin.settings.displayHeader=e,this.plugin.saveSettings()})),new l.Setting(e).setName(this.i18n.settings.displayFooter).addToggle(e=>e.setTooltip(`Display footer`).setValue(this.plugin.settings.displayFooter).onChange(async e=>{this.plugin.settings.displayFooter=e,this.plugin.saveSettings()})),new l.Setting(e).setName(this.i18n.settings.printBackground).setDesc(`Whether to print background graphics`).addToggle(e=>e.setValue(this.plugin.settings.printBackground).onChange(async e=>{this.plugin.settings.printBackground=e,this.plugin.saveSettings()})),new l.Setting(e).setName(`Generate tagged PDF`).setDesc(`Whether or not to generate a tagged (accessible) PDF. Defaults to false. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards.`).addToggle(e=>e.setValue(this.plugin.settings.generateTaggedPDF).onChange(async e=>{this.plugin.settings.generateTaggedPDF=e,this.plugin.saveSettings()})),new l.Setting(e).setName(this.i18n.settings.maxLevel).addDropdown(e=>{e.addOptions(Object.fromEntries([`1`,`2`,`3`,`4`,`5`,`6`].map(e=>[e,`h${e}`]))).setValue(this.plugin.settings.maxLevel).onChange(async e=>{this.plugin.settings.maxLevel=e,this.plugin.saveSettings()})}),new l.Setting(e).setName(this.i18n.settings.displayMetadata).setDesc(`Add frontMatter(title, author, keywords, subject creator, etc) to pdf metadata`).addToggle(e=>e.setValue(this.plugin.settings.displayMetadata).onChange(async e=>{this.plugin.settings.displayMetadata=e,this.plugin.saveSettings()})),new l.Setting(e).setName(`Advanced`).setHeading();let n=new l.Setting(e);n.settingEl.setAttribute(`style`,`display: grid; grid-template-columns: 1fr;`),n.setName(this.i18n.settings.headerTemplate).setDesc(`HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: date (formatted print date), title (document title), url (document location), pageNumber (current page number) and totalPages (total pages in the document). For example, would generate span containing the title.`);let r=new l.TextAreaComponent(n.controlEl);ag(r.inputEl,{style:`margin-top: 12px; width: 100%; height: 6vh;`}),r.setValue(this.plugin.settings.headerTemplate).onChange(async e=>{this.plugin.settings.headerTemplate=e,this.plugin.saveSettings()});let i=new l.Setting(e);i.settingEl.setAttribute(`style`,`display: grid; grid-template-columns: 1fr;`),i.setName(this.i18n.settings.footerTemplate).setDesc(`HTML template for the print footer. Should use the same format as the headerTemplate.`);let a=new l.TextAreaComponent(i.controlEl);ag(a.inputEl,{style:`margin-top: 12px; width: 100%; height: 6vh;`}),a.setValue(this.plugin.settings.footerTemplate).onChange(async e=>{this.plugin.settings.footerTemplate=e,this.plugin.saveSettings()}),new l.Setting(e).setName(this.i18n.settings.isTimestamp).setDesc(`Add timestamp to output file name`).addToggle(e=>{e.setValue(this.plugin.settings.isTimestamp).onChange(async e=>{this.plugin.settings.isTimestamp=e,await this.plugin.saveSettings()})});let o=new l.Setting(e).setName(this.i18n.settings.enabledCss).setDesc(`Select the css snippet that are not enabled`).addToggle(e=>{e.setValue(this.plugin.settings.enabledCss).onChange(async e=>{this.plugin.settings.enabledCss=e,await this.plugin.saveSettings()})}),s=e=>{o.settingEl.hidden=e!==`1`};s(this.plugin.settings.version),new l.Setting(e).setName(this.i18n.settings.concurrency).setDesc(`Limit the number of concurrent renders`).addText(e=>{let t=this.plugin.settings?.concurrency;e.setValue(t?.length>0?t:`5`).onChange(async e=>{this.plugin.settings.concurrency=e,await this.plugin.saveSettings()})}),new l.Setting(e).setName(`Debug`).setHeading(),new l.Setting(e).setName(this.i18n.settings.debugMode).setDesc(`This is useful for troubleshooting.`).addToggle(e=>{e.setValue(this.plugin.settings.debug).onChange(async e=>{this.plugin.settings.debug=e,await this.plugin.saveSettings()})})}},cg=require("fs").promises,lg=process.env.NODE_ENV===`development`,ug={showTitle:!0,maxLevel:`6`,displayHeader:!0,displayFooter:!0,headerTemplate:`
`,footerTemplate:`
/
`,printBackground:!1,generateTaggedPDF:!1,displayMetadata:!1,debug:!1,isTimestamp:!1,enabledCss:!1,concurrency:`5`,version:`2`},dg=class extends l.Plugin{constructor(e,t){super(e,t),this.i18n=m.current}async onload(){await this.loadSettings(),this.registerCommand(),this.registerSetting(),this.registerEvents()}registerCommand(){this.addCommand({id:`export-current-file-to-pdf`,name:this.i18n.exportCurrentFile,checkCallback:e=>{let t=this.app.workspace.getActiveViewOfType(l.MarkdownView)?.file;return t?(e||new ig(this,t).open(),!0):!1}})}registerSetting(){this.addSettingTab(new sg(this.app,this))}registerEvents(){this.registerEvent(this.app.workspace.on(`file-menu`,(e,t)=>{let n=t instanceof l.TFolder?`Export folder to PDF`:`Better Export PDF`;lg&&(n=`${n} (dev)`),e.addItem(e=>{e.setTitle(n).setIcon(`download`).setSection(`action`).onClick(async()=>{new ig(this,t).open()})})})),this.registerEvent(this.app.workspace.on(`file-menu`,(e,t)=>{if(t instanceof l.TFolder){let n=`Export to PDF...`;lg&&(n=`${n} (dev)`),e.addItem(e=>{e.setTitle(n).setIcon(`lucide-folder-down`).setSection(`action`);let r=e.setSubmenu();r.addItem(e=>e.setTitle(`Export each file to PDF`).setIcon(`lucide-file-stack`).onClick(async()=>{new ig(this,t,!0).open()})),r.addItem(e=>e.setTitle(`Generate TOC.md file`).setIcon(`lucide-file-text`).onClick(async()=>{await this.generateToc(t)}))})}}))}async generateToc(e){let t=this.app.vault.adapter.basePath,n=d.default.join(t,e.path,`_TOC_.md`),r=`---\ntoc: true\ntitle: ${e.name}\n---\n`;if(await cg.writeFile(n,r),e instanceof l.TFolder){let t=Ja(e);for(let e of t)e.name!=`_TOC_.md`&&await cg.appendFile(n,`[[${e.path}]]\n`)}}onunload(){}async loadSettings(){this.settings=Object.assign({},ug,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}changeConfig(){let e=this.app.vault?.getConfig(`theme`)===`obsidian`;e&&(document.body.addClass(`theme-light`),document.body.removeClass(`theme-dark`)),document.body.removeClass(`theme-dark`);let t=document.body.createDiv(`print`);t.addEventListener(`click`,function(){t.detach(),e&&(document.body.removeClass(`theme-light`),document.body.addClass(`theme-dark`))});let n=document.body.createDiv(`print`).createDiv(`markdown-preview-view markdown-rendered`);n.toggleClass(`rtl`,this.app.vault.getConfig(`rightToLeft`)),n.toggleClass(`show-frontmatter`,this.app.vault.getConfig(`showFrontmatter`)),n.createEl(`h1`,{text:`xxxxx`})}};module.exports=dg; /* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/better-export-pdf/manifest.json b/.obsidian/plugins/better-export-pdf/manifest.json index c1ac749e..77086f26 100644 --- a/.obsidian/plugins/better-export-pdf/manifest.json +++ b/.obsidian/plugins/better-export-pdf/manifest.json @@ -1,7 +1,7 @@ { "id": "better-export-pdf", "name": "Better Export PDF", - "version": "2.0.2", + "version": "2.0.3", "minAppVersion": "0.15.0", "description": "Export your notes to PDF, support export preview, add bookmarks outline and header/footer.", "author": "l1xnan", diff --git a/.obsidian/plugins/breadcrumbs/data.json b/.obsidian/plugins/breadcrumbs/data.json index 5abf7548..733e0cca 100644 --- a/.obsidian/plugins/breadcrumbs/data.json +++ b/.obsidian/plugins/breadcrumbs/data.json @@ -286,7 +286,7 @@ "prevs" ], "lock_view": false, - "lock_path": "matrices particulières.md", + "lock_path": "language tool.md", "custom_sort_fields": false, "custom_sort_field_labels": [] }, @@ -295,9 +295,9 @@ "show_attributes": [], "merge_fields": false, "lock_view": false, - "lock_path": "matrices particulières.md", + "lock_path": "language tool.md", "field_group_labels": [ - "ups" + "downs" ], "edge_sort_id": { "field": "basename", diff --git a/.obsidian/plugins/darlal-switcher-plus/main.js b/.obsidian/plugins/darlal-switcher-plus/main.js index 0602d833..a240bbd0 100644 --- a/.obsidian/plugins/darlal-switcher-plus/main.js +++ b/.obsidian/plugins/darlal-switcher-plus/main.js @@ -1,3 +1,3 @@ -"use strict";var e,t,s,i,n,a=require("obsidian");!function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.FolderOnly=2]="FolderOnly",e[e.FolderWithFilename=3]="FolderWithFilename",e[e.FolderPathFilenameOptional=4]="FolderPathFilenameOptional"}(e||(e={})),function(e){e[e.Standard=1]="Standard",e[e.EditorList=2]="EditorList",e[e.SymbolList=4]="SymbolList",e[e.WorkspaceList=8]="WorkspaceList",e[e.HeadingsList=16]="HeadingsList",e[e.BookmarksList=32]="BookmarksList",e[e.CommandList=64]="CommandList",e[e.RelatedItemsList=128]="RelatedItemsList",e[e.VaultList=256]="VaultList"}(t||(t={})),function(e){e[e.Link=1]="Link",e[e.Embed=2]="Embed",e[e.Tag=4]="Tag",e[e.Heading=8]="Heading",e[e.Callout=16]="Callout",e[e.CanvasNode=32]="CanvasNode",e[e.BaseView=64]="BaseView"}(s||(s={})),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heading=2]="Heading",e[e.Block=4]="Block"}(i||(i={})),function(e){e.Both="both",e.Inline="inline",e.Frontmatter="frontmatter"}(n||(n={}));const o={};o[s.Link]="🔗",o[s.Embed]="!",o[s.Tag]="#",o[s.Heading]="H";const r={};var l,d,c;r[1]="H₁",r[2]="H₂",r[3]="H₃",r[4]="H₄",r[5]="H₅",r[6]="H₆",function(e){e.EditorList="editorList",e.SymbolList="symbolList",e.WorkspaceList="workspaceList",e.HeadingsList="headingsList",e.Bookmark="bookmark",e.CommandList="commandList",e.RelatedItemsList="relatedItemsList",e.VaultList="vaultList",e.File="file",e.Alias="alias",e.Unresolved="unresolved"}(l||(l={})),function(e){e[e.None=0]="None",e[e.Primary=1]="Primary",e[e.Basename=2]="Basename",e[e.Path=3]="Path"}(d||(d={})),function(e){e.DiskLocation="disk-location",e.Backlink="backlink",e.OutgoingLink="outgoing-link"}(c||(c={}));class h{static getAliases(e){let t=[];return e&&(t=h.getValueForKey(e,/^alias(es)?$/i)),t}static getTags(e){let t=[];return e&&(t=h.getValueForKey(e,/^tags?$/i)),t}static getValueForKey(e,t){const s=[],i=Object.keys(e).find((e=>t.test(e)));if(i){let t=e[i];"string"==typeof t&&(t=t.split(",")),Array.isArray(t)&&t.forEach((e=>{"string"==typeof e&&s.push(e.trim())}))}return s}}function m(e,t,s){let i=!1;return e&&void 0!==e[t]&&(i=!0,void 0!==s&&s!==e[t]&&(i=!1)),i}function u(e){return m(e,"type",l.SymbolList)}function g(e){return m(e,"type",l.HeadingsList)}function p(e){return m(e,"type",l.File)}function f(e){return m(e,"type",l.Alias)}function y(e){return m(e,"type",l.Unresolved)}function b(e){return e&&!(p(t=e)||y(t)||f(t));var t}function S(e){return m(e,"level")}function k(e){return m(e,"tag")}function v(e){return m(e,"type","callout")}function w(e){return m(e,"extension")}function C(e){return m(e,"children")}function I(e,t){return e?.internalPlugins?.getEnabledPluginById(t)}function L(e){const t=function(e,t){return e?.internalPlugins?.getPluginById(t)}(e,"switcher");return t?.instance}function T(e){return I(e,"global-search")}function E(){return Object.values(t).filter((e=>isNaN(Number(e)))).sort()}function F(){return[t.RelatedItemsList,t.SymbolList]}function x(e){let t=null;if(e){const s=a.normalizePath(e),i=s.lastIndexOf("/");t=-1===i?s:s.slice(i+1)}return t}function A(e,t){new a.Notice(`Switcher++: ${e}`),O(e,t)}function O(e,...t){console.error(`Switcher++: ${e}`,...t)}function P(e,...t){console.warn(`Switcher++: ${e}`,...t)}function M(e){e=e??[];const t=[];for(const s of e)try{const e=new RegExp(s);t.push(e)}catch(e){O(`Error creating RegExp from string: ${s}`,e)}return e=>{for(const s of t)if(s.test(e))return!0;return!1}}function B(e){let t=i.None;if(e){const s=e.link.split("|")[0];t=s.includes("#^")?i.Block:s.includes("#")?i.Heading:i.Normal}return t}function R(e,t){return t?.getFileByPath(e)}function H(e){let t=null;if(!e)return t;if(e.isDeferred){const s=e.getViewState()?.state?.file;s&&(t=R(s,e.app?.vault))}else e.view?.file&&(t=e.view.file);return t}function D(e,t,s,i,n){let o=null;if(n=Object.assign({useBasenameAsAlias:!0,useHeadingAsAlias:!0},n),s){let r=W(s),d=null,c=null;switch(s.type){case l.Unresolved:o=N(s.linktext);break;case l.Alias:d=s.alias;break;case l.Bookmark:{const{item:e}=s;"file"===e.type&&e.title&&(d=e.title);break}case l.HeadingsList:{const{heading:e}=s.item;({subpath:c,alias:d}=V(e,n.useHeadingAsAlias));break}case l.SymbolList:{const{item:{symbol:l}}=s;if(S(l))({subpath:c,alias:d}=V(l.heading,n.useHeadingAsAlias));else if(m(l,"link")){o=new RegExp(/^\[(.*?)\]\((.+?)\)/).test(l.original)?l.original:function(e,t,s,i,n,o){const{link:r,displayText:l}=i,{path:d,subpath:c}=a.parseLinktext(r);let h=l,m=null,u=null;m=d?.length?R(d,t):n;m?(!h?.length&&o&&(h=m.basename),u=e.generateMarkdownLink(m,s,c,h)):u=N(d,h);return u}(e,t,i,l,r,n.useBasenameAsAlias)}else r=null;break}case l.RelatedItemsList:{const{item:e}=s;e.unresolvedText&&(o=N(e.unresolvedText));break}}r&&!o&&(!d&&n.useBasenameAsAlias&&(d=r.basename),o=e.generateMarkdownLink(r,i,c,d))}return o}function V(e,t){const s=a.stripHeadingForLink(e);return{subpath:`#${s}`,alias:t?s:null}}function W(e){let t=null;return[l.Alias,l.Bookmark,l.HeadingsList,l.SymbolList,l.RelatedItemsList,l.EditorList,l.File].includes(e?.type)&&(t=e.file),t}function N(e,t){return`[[${e}${t=t?.length?`|${t}`:""}]]`}function K(e,t){return e?.view?.getViewType()===t&&!e.isDeferred}class q{static rootComponent;static getRootComponent(){return this.rootComponent||(this.rootComponent=new a.Component),this.rootComponent}static unload(){this.rootComponent?.unload()}}const j={file:"canvas-node-file",text:"canvas-node-text",link:"canvas-node-link",group:"canvas-node-group"},$={table:"base-view-table",list:"base-view-list",cards:"base-view-cards"},U=[{id:s[s.Heading],mode:t.SymbolList,label:"headings",isActive:!1,isAvailable:!0},{id:s[s.Tag],mode:t.SymbolList,label:"tags",isActive:!1,isAvailable:!0},{id:s[s.Callout],mode:t.SymbolList,label:"callouts",isActive:!1,isAvailable:!0},{id:s[s.Link],mode:t.SymbolList,label:"links",isActive:!1,isAvailable:!0},{id:s[s.Embed],mode:t.SymbolList,label:"embeds",isActive:!1,isAvailable:!0},{id:j.file,mode:t.SymbolList,label:"file cards",isActive:!1,isAvailable:!0},{id:j.text,mode:t.SymbolList,label:"text cards",isActive:!1,isAvailable:!0},{id:j.link,mode:t.SymbolList,label:"link cards",isActive:!1,isAvailable:!0},{id:j.group,mode:t.SymbolList,label:"groups",isActive:!1,isAvailable:!0},{id:$.table,mode:t.SymbolList,label:"table views",isActive:!1,isAvailable:!0},{id:$.list,mode:t.SymbolList,label:"list views",isActive:!1,isAvailable:!0},{id:$.cards,mode:t.SymbolList,label:"card views",isActive:!1,isAvailable:!0}],Q=[{id:c.Backlink,mode:t.RelatedItemsList,label:"backlinks",isActive:!1,isAvailable:!0},{id:c.OutgoingLink,mode:t.RelatedItemsList,label:"outgoing links",isActive:!1,isAvailable:!0},{id:c.DiskLocation,mode:t.RelatedItemsList,label:"disk location",isActive:!1,isAvailable:!0}],G={file:"bookmarks-file",folder:"bookmarks-folder",search:"bookmarks-search",group:"bookmarks-group"},_=[{id:G.file,mode:t.BookmarksList,label:"files",isActive:!1,isAvailable:!0},{id:G.folder,mode:t.BookmarksList,label:"folders",isActive:!1,isAvailable:!0},{id:G.search,mode:t.BookmarksList,label:"searches",isActive:!1,isAvailable:!0}];var z;!function(e){e.Pinned="pinnedCommands",e.Recent="recentCommands"}(z||(z={}));const Z=[{id:z.Pinned,mode:t.CommandList,label:"pinned",isActive:!1,isAvailable:!0},{id:z.Recent,mode:t.CommandList,label:"recent",isActive:!1,isAvailable:!0}];var J;!function(e){e.RecentFiles="recentFilesSearch",e.Bookmarks="bookmarksSearch",e.Filenames="filenamesSearch",e.Headings="headingsSearch",e.ExternalFiles="externalFilesSearch"}(J||(J={}));const Y=[{id:J.RecentFiles,mode:t.HeadingsList,label:"recent files",isActive:!1,isAvailable:!0},{id:J.Bookmarks,mode:t.HeadingsList,label:"bookmarks",isActive:!1,isAvailable:!0},{id:J.Filenames,mode:t.HeadingsList,label:"filenames",isActive:!1,isAvailable:!0},{id:J.Headings,mode:t.HeadingsList,label:"headings",isActive:!1,isAvailable:!0},{id:J.ExternalFiles,mode:t.HeadingsList,label:"external files",isActive:!1,isAvailable:!0}];function X(){const e={};return[U,Q,_,Z,Y].flat().reduce(((e,t)=>(e[t.id]=Object.assign({},t),e)),e),e}const ee=e=>{if("object"==typeof e&&null!==e){if("function"==typeof Object.getPrototypeOf){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}return"[object Object]"===Object.prototype.toString.call(e)}return!1},te=(...e)=>e.reduce(((e,t)=>{if(void 0===t)return e;if(Array.isArray(t))throw new TypeError("Arguments provided to ts-deepmerge must be objects, not arrays.");return Object.keys(t).forEach((s=>{["__proto__","constructor","prototype"].includes(s)||(Array.isArray(e[s])&&Array.isArray(t[s])?e[s]=te.options.mergeArrays?te.options.uniqueArrayItems?Array.from(new Set(e[s].concat(t[s]))):[...e[s],...t[s]]:t[s]:ee(e[s])&&ee(t[s])?e[s]=te(e[s],t[s]):!ee(e[s])&&ee(t[s])?e[s]=te(t[s],void 0):e[s]=void 0===t[s]?te.options.allowUndefinedOverrides?t[s]:e[s]:t[s])})),e}),{}),se={allowUndefinedOverrides:!0,mergeArrays:!0,uniqueArrayItems:!0};te.options=se,te.withOptions=(e,...t)=>{te.options=Object.assign(Object.assign({},se),e);const s=te(...t);return te.options=se,s};class ie{plugin;data;static get defaults(){const i={};return i[s.Link]=!0,i[s.Embed]=!0,i[s.Tag]=!0,i[s.Heading]=!0,i[s.Callout]=!0,{version:"2.0.0",onOpenPreferNewTab:!0,alwaysNewTabForSymbols:!1,useActiveTabForSymbolsOnMobile:!1,symbolsInLineOrder:!0,editorListCommand:"edt ",symbolListCommand:"@",symbolListActiveEditorCommand:"$ ",workspaceListCommand:"+",headingsListCommand:"#",bookmarksListCommand:"'",commandListCommand:">",recentCommandDisplayOrder:"desc",maxRecentCommands:25,vaultListCommand:"vault ",relatedItemsListCommand:"~",relatedItemsListActiveEditorCommand:"^ ",shouldSearchHeadings:!0,strictHeadingsOnly:!1,searchAllHeadings:!0,headingsSearchDebounceMilli:250,excludeViewTypes:["empty"],referenceViews:["backlink","localgraph","outgoing-link","outline"],limit:50,includeSidePanelViewTypes:["backlink","image","markdown","pdf"],enabledSymbolTypes:i,selectNearestHeading:!0,excludeFolders:[],excludeLinkSubTypes:0,excludeRelatedFolders:[""],excludeOpenRelatedFiles:!1,excludeObsidianIgnoredFiles:!1,shouldSearchFilenames:!1,shouldSearchBookmarks:!1,shouldSearchRecentFiles:!0,pathDisplayFormat:e.FolderWithFilename,hidePathIfRoot:!0,enabledRelatedItems:Object.values(c),showOptionalIndicatorIcons:!0,isFileExtensionIndicatorsEnabled:!0,excludeFileExtensionIndicators:["md"],overrideStandardModeBehaviors:!0,overrideStandardModeRendering:!0,enabledRibbonCommands:[t[t.HeadingsList],t[t.SymbolList]],fileExtAllowList:["canvas"],matchPriorityAdjustments:{isEnabled:!1,adjustments:{isOpenInEditor:{value:0,label:"Open items"},isBookmarked:{value:0,label:"Bookmarked items"},isRecent:{value:0,label:"Recent items"},isAttachment:{value:0,label:"Attachment file types"},file:{value:0,label:"Filenames"},alias:{value:0,label:"Aliases"},unresolved:{value:0,label:"Unresolved filenames"},h1:{value:0,label:"H₁ headings"}},fileExtAdjustments:{canvas:{value:0,label:"Canvas files"}}},quickFilters:{resetKey:"0",keyList:["1","2","3","4","5","6","7","8","9"],modifiers:["Ctrl","Alt"],facetList:X(),shouldResetActiveFacets:!1,shouldShowFacetInstructions:!0},preserveCommandPaletteLastInput:!1,preserveQuickSwitcherLastInput:!1,shouldCloseModalOnBackspace:!1,maxRecentFileSuggestionsOnInit:25,orderEditorListByAccessTime:!0,insertLinkInEditor:{isEnabled:!0,keymap:{modifiers:["Mod"],key:"i",purpose:"insert in editor"},insertableEditorTypes:["markdown"],useBasenameAsAlias:!0,useHeadingAsAlias:!0},removeDefaultTabBinding:!0,navigationKeys:{nextKeys:[{modifiers:["Ctrl"],key:"n"},{modifiers:["Ctrl"],key:"j"}],prevKeys:[{modifiers:["Ctrl"],key:"p"},{modifiers:["Ctrl"],key:"k"}]},preferredSourceForTitle:"H1",frontmatterTitleProperty:"title",closeWhenEmptyKeys:[{modifiers:null,key:"Backspace"}],navigateToHotkeySelectorKeys:{modifiers:["Ctrl","Shift"],key:"h"},togglePinnedCommandKeys:{modifiers:["Ctrl","Shift"],key:"p"},escapeCmdChar:"!",mobileLauncher:{isEnabled:!1,isMobileButtonEnabled:!0,isEmptyTabButtonEnabled:!0,modeString:t[t.HeadingsList],iconName:"",coreLauncherButtonIconSelector:"span.clickable-icon",coreLauncherButtonSelector:".mobile-navbar-action.mobile-navbar-action-quick-switcher"},allowCreateNewFileInModeNames:[t[t.Standard],t[t.HeadingsList]],showModeTriggerInstructions:!0,renderMarkdownContentInSuggestions:{isEnabled:!1,renderHeadings:!1,renderLinks:!1,renderTags:!1,renderCallouts:!1,toggleContentRenderingKeys:{modifiers:["Shift","Ctrl"],key:"m"}},quickOpen:{isEnabled:!0,modifiers:["Alt"],keyList:["1","2","3","4","5","6","7","8","9"]},openDefaultApp:{isEnabled:!0,openInDefaultAppKeys:{modifiers:["Shift","Ctrl"],key:"o"},excludeFileExtensions:[]},fulltextSearch:{isEnabled:!0,searchKeys:{modifiers:["Mod","Shift"],key:"f"}},openInBackground:{isEnabled:!0,openKeys:[{openType:"tab",hotkey:{modifiers:["Mod","Shift"],key:"t"}},{openType:"vertical",hotkey:null},{openType:"horizontal",hotkey:null},{openType:"window",hotkey:null}]},saveWorkspaceAndSwitchKeys:{modifiers:["Mod","Shift"],key:"s"},showHeadingBreadcrumbs:!0,headingBreadcrumbSeparator:" > ",maxBreadcrumbDepth:0,showHeadingBreadcrumbsInSymbolMode:!1,showTagsInSuggestions:!1,tagSource:n.Both,excludeTagsFromDisplay:[],tagDisplaySeparator:" ",removeHashPrefixFromTags:!1,maxTagsToDisplay:0}}shouldShowAlias;get version(){return this.data.version}set version(e){this.data.version=e}get builtInSystemOptions(){return L(this.plugin.app)?.options}get showAllFileTypes(){return this.builtInSystemOptions?.showAllFileTypes}get showAttachments(){return this.builtInSystemOptions?.showAttachments}get showExistingOnly(){return this.builtInSystemOptions?.showExistingOnly}get onOpenPreferNewTab(){return this.data.onOpenPreferNewTab}set onOpenPreferNewTab(e){this.data.onOpenPreferNewTab=e}get alwaysNewTabForSymbols(){return this.data.alwaysNewTabForSymbols}set alwaysNewTabForSymbols(e){this.data.alwaysNewTabForSymbols=e}get useActiveTabForSymbolsOnMobile(){return this.data.useActiveTabForSymbolsOnMobile}set useActiveTabForSymbolsOnMobile(e){this.data.useActiveTabForSymbolsOnMobile=e}get symbolsInLineOrder(){return this.data.symbolsInLineOrder}set symbolsInLineOrder(e){this.data.symbolsInLineOrder=e}get editorListPlaceholderText(){return ie.defaults.editorListCommand}get editorListCommand(){return this.data.editorListCommand}set editorListCommand(e){this.data.editorListCommand=e}get symbolListPlaceholderText(){return ie.defaults.symbolListCommand}get symbolListCommand(){return this.data.symbolListCommand}set symbolListCommand(e){this.data.symbolListCommand=e}get symbolListActiveEditorCommand(){return this.data.symbolListActiveEditorCommand}set symbolListActiveEditorCommand(e){this.data.symbolListActiveEditorCommand=e}get workspaceListCommand(){return this.data.workspaceListCommand}set workspaceListCommand(e){this.data.workspaceListCommand=e}get workspaceListPlaceholderText(){return ie.defaults.workspaceListCommand}get headingsListCommand(){return this.data.headingsListCommand}set headingsListCommand(e){this.data.headingsListCommand=e}get headingsListPlaceholderText(){return ie.defaults.headingsListCommand}get bookmarksListCommand(){return this.data.bookmarksListCommand}set bookmarksListCommand(e){this.data.bookmarksListCommand=e}get bookmarksListPlaceholderText(){return ie.defaults.bookmarksListCommand}get commandListCommand(){return this.data.commandListCommand}set commandListCommand(e){this.data.commandListCommand=e}get recentCommandDisplayOrder(){return this.data.recentCommandDisplayOrder}set recentCommandDisplayOrder(e){this.data.recentCommandDisplayOrder=e}get maxRecentCommands(){return this.data.maxRecentCommands}set maxRecentCommands(e){this.data.maxRecentCommands=e}get commandListPlaceholderText(){return ie.defaults.commandListCommand}get vaultListCommand(){return this.data.vaultListCommand}set vaultListCommand(e){this.data.vaultListCommand=e}get vaultListPlaceholderText(){return ie.defaults.vaultListCommand}get relatedItemsListCommand(){return this.data.relatedItemsListCommand}set relatedItemsListCommand(e){this.data.relatedItemsListCommand=e}get relatedItemsListPlaceholderText(){return ie.defaults.relatedItemsListCommand}get relatedItemsListActiveEditorCommand(){return this.data.relatedItemsListActiveEditorCommand}set relatedItemsListActiveEditorCommand(e){this.data.relatedItemsListActiveEditorCommand=e}get shouldSearchHeadings(){return this.data.shouldSearchHeadings}set shouldSearchHeadings(e){this.data.shouldSearchHeadings=e}get strictHeadingsOnly(){return this.data.strictHeadingsOnly}set strictHeadingsOnly(e){this.data.strictHeadingsOnly=e}get searchAllHeadings(){return this.data.searchAllHeadings}set searchAllHeadings(e){this.data.searchAllHeadings=e}get headingsSearchDebounceMilli(){return this.data.headingsSearchDebounceMilli}set headingsSearchDebounceMilli(e){this.data.headingsSearchDebounceMilli=e}get excludeViewTypes(){return this.data.excludeViewTypes}set excludeViewTypes(e){this.data.excludeViewTypes=e}get referenceViews(){return this.data.referenceViews}set referenceViews(e){this.data.referenceViews=e}get limit(){return this.data.limit}set limit(e){this.data.limit=e}get includeSidePanelViewTypes(){return this.data.includeSidePanelViewTypes}set includeSidePanelViewTypes(e){this.data.includeSidePanelViewTypes=[...new Set(e)]}get includeSidePanelViewTypesPlaceholder(){return ie.defaults.includeSidePanelViewTypes.join("\n")}get selectNearestHeading(){return this.data.selectNearestHeading}set selectNearestHeading(e){this.data.selectNearestHeading=e}get excludeFolders(){return this.data.excludeFolders}set excludeFolders(e){this.data.excludeFolders=[...new Set(e)]}get excludeLinkSubTypes(){return this.data.excludeLinkSubTypes}set excludeLinkSubTypes(e){this.data.excludeLinkSubTypes=e}get excludeRelatedFolders(){return this.data.excludeRelatedFolders}set excludeRelatedFolders(e){this.data.excludeRelatedFolders=[...new Set(e)]}get excludeOpenRelatedFiles(){return this.data.excludeOpenRelatedFiles}set excludeOpenRelatedFiles(e){this.data.excludeOpenRelatedFiles=e}get excludeObsidianIgnoredFiles(){return this.data.excludeObsidianIgnoredFiles}set excludeObsidianIgnoredFiles(e){this.data.excludeObsidianIgnoredFiles=e}get shouldSearchFilenames(){return this.data.shouldSearchFilenames}set shouldSearchFilenames(e){this.data.shouldSearchFilenames=e}get shouldSearchBookmarks(){return this.data.shouldSearchBookmarks}set shouldSearchBookmarks(e){this.data.shouldSearchBookmarks=e}get shouldSearchRecentFiles(){return this.data.shouldSearchRecentFiles}set shouldSearchRecentFiles(e){this.data.shouldSearchRecentFiles=e}get pathDisplayFormat(){return this.data.pathDisplayFormat}set pathDisplayFormat(e){this.data.pathDisplayFormat=e}get hidePathIfRoot(){return this.data.hidePathIfRoot}set hidePathIfRoot(e){this.data.hidePathIfRoot=e}get enabledRelatedItems(){return this.data.enabledRelatedItems}set enabledRelatedItems(e){this.data.enabledRelatedItems=e}get showOptionalIndicatorIcons(){return this.data.showOptionalIndicatorIcons}set showOptionalIndicatorIcons(e){this.data.showOptionalIndicatorIcons=e}get isFileExtensionIndicatorsEnabled(){return this.data.isFileExtensionIndicatorsEnabled}set isFileExtensionIndicatorsEnabled(e){this.data.isFileExtensionIndicatorsEnabled=e}get excludeFileExtensionIndicators(){return this.data.excludeFileExtensionIndicators}set excludeFileExtensionIndicators(e){this.data.excludeFileExtensionIndicators=[...new Set(e)]}get overrideStandardModeBehaviors(){return this.data.overrideStandardModeBehaviors}set overrideStandardModeBehaviors(e){this.data.overrideStandardModeBehaviors=e}get overrideStandardModeRendering(){return this.data.overrideStandardModeRendering}set overrideStandardModeRendering(e){this.data.overrideStandardModeRendering=e}get enabledRibbonCommands(){return this.data.enabledRibbonCommands}set enabledRibbonCommands(e){this.data.enabledRibbonCommands=[...new Set(e)]}get fileExtAllowList(){return this.data.fileExtAllowList}set fileExtAllowList(e){this.data.fileExtAllowList=e}get matchPriorityAdjustments(){return this.data.matchPriorityAdjustments}set matchPriorityAdjustments(e){this.data.matchPriorityAdjustments=e}get quickFilters(){return this.data.quickFilters}set quickFilters(e){this.data.quickFilters=e}get preserveCommandPaletteLastInput(){return this.data.preserveCommandPaletteLastInput}set preserveCommandPaletteLastInput(e){this.data.preserveCommandPaletteLastInput=e}get preserveQuickSwitcherLastInput(){return this.data.preserveQuickSwitcherLastInput}set preserveQuickSwitcherLastInput(e){this.data.preserveQuickSwitcherLastInput=e}get shouldCloseModalOnBackspace(){return this.data.shouldCloseModalOnBackspace}set shouldCloseModalOnBackspace(e){this.data.shouldCloseModalOnBackspace=e}get maxRecentFileSuggestionsOnInit(){return this.data.maxRecentFileSuggestionsOnInit}set maxRecentFileSuggestionsOnInit(e){this.data.maxRecentFileSuggestionsOnInit=e}get orderEditorListByAccessTime(){return this.data.orderEditorListByAccessTime}set orderEditorListByAccessTime(e){this.data.orderEditorListByAccessTime=e}get insertLinkInEditor(){return this.data.insertLinkInEditor}set insertLinkInEditor(e){this.data.insertLinkInEditor=e}get removeDefaultTabBinding(){return this.data.removeDefaultTabBinding}set removeDefaultTabBinding(e){this.data.removeDefaultTabBinding=e}get navigationKeys(){return this.data.navigationKeys}set navigationKeys(e){this.data.navigationKeys=e}get preferredSourceForTitle(){return this.data.preferredSourceForTitle}set preferredSourceForTitle(e){this.data.preferredSourceForTitle=e}get frontmatterTitleProperty(){return this.data.frontmatterTitleProperty}set frontmatterTitleProperty(e){this.data.frontmatterTitleProperty=e}get closeWhenEmptyKeys(){return this.data.closeWhenEmptyKeys}set closeWhenEmptyKeys(e){this.data.closeWhenEmptyKeys=e}get navigateToHotkeySelectorKeys(){return this.data.navigateToHotkeySelectorKeys}set navigateToHotkeySelectorKeys(e){this.data.navigateToHotkeySelectorKeys=e}get togglePinnedCommandKeys(){return this.data.togglePinnedCommandKeys}set togglePinnedCommandKeys(e){this.data.togglePinnedCommandKeys=e}get escapeCmdChar(){return this.data.escapeCmdChar}set escapeCmdChar(e){this.data.escapeCmdChar=e}get mobileLauncher(){return this.data.mobileLauncher}set mobileLauncher(e){this.data.mobileLauncher=e}get allowCreateNewFileInModeNames(){return this.data.allowCreateNewFileInModeNames}set allowCreateNewFileInModeNames(e){this.data.allowCreateNewFileInModeNames=[...new Set(e)]}get showModeTriggerInstructions(){return this.data.showModeTriggerInstructions}set showModeTriggerInstructions(e){this.data.showModeTriggerInstructions=e}get renderMarkdownContentInSuggestions(){return this.data.renderMarkdownContentInSuggestions}set renderMarkdownContentInSuggestions(e){this.data.renderMarkdownContentInSuggestions=e}get quickOpen(){return this.data.quickOpen}set quickOpen(e){this.data.quickOpen=e}get openDefaultApp(){return this.data.openDefaultApp}set openDefaultApp(e){this.data.openDefaultApp=e}get fulltextSearch(){return this.data.fulltextSearch}set fulltextSearch(e){this.data.fulltextSearch=e}get openInBackground(){return this.data.openInBackground}set openInBackground(e){this.data.openInBackground=e}get saveWorkspaceAndSwitchKeys(){return this.data.saveWorkspaceAndSwitchKeys}set saveWorkspaceAndSwitchKeys(e){this.data.saveWorkspaceAndSwitchKeys=e}get showHeadingBreadcrumbs(){return this.data.showHeadingBreadcrumbs}set showHeadingBreadcrumbs(e){this.data.showHeadingBreadcrumbs=e}get headingBreadcrumbSeparator(){return this.data.headingBreadcrumbSeparator}set headingBreadcrumbSeparator(e){this.data.headingBreadcrumbSeparator=e}get maxBreadcrumbDepth(){return this.data.maxBreadcrumbDepth}set maxBreadcrumbDepth(e){this.data.maxBreadcrumbDepth=e}get showHeadingBreadcrumbsInSymbolMode(){return this.data.showHeadingBreadcrumbsInSymbolMode}set showHeadingBreadcrumbsInSymbolMode(e){this.data.showHeadingBreadcrumbsInSymbolMode=e}get showTagsInSuggestions(){return this.data.showTagsInSuggestions}set showTagsInSuggestions(e){this.data.showTagsInSuggestions=e}get tagSource(){return this.data.tagSource}set tagSource(e){this.data.tagSource=e}get excludeTagsFromDisplay(){return this.data.excludeTagsFromDisplay}set excludeTagsFromDisplay(e){this.data.excludeTagsFromDisplay=e}get tagDisplaySeparator(){return this.data.tagDisplaySeparator}set tagDisplaySeparator(e){this.data.tagDisplaySeparator=e}get removeHashPrefixFromTags(){return this.data.removeHashPrefixFromTags}set removeHashPrefixFromTags(e){this.data.removeHashPrefixFromTags=e}get maxTagsToDisplay(){return this.data.maxTagsToDisplay}set maxTagsToDisplay(e){this.data.maxTagsToDisplay=e}constructor(e){this.plugin=e,this.data=ie.defaults}async updateDataAndLoadSettings(){return await ie.transformDataFile(this.plugin,ie.defaults),await this.loadSettings()}async loadSettings(){try{const e=await(this.plugin?.loadData());if(e){const t=Object.keys(ie.defaults);((e,t,s)=>{const i=["matchPriorityAdjustments","quickFilters","mobileLauncher"],n=s=>te.withOptions({mergeArrays:!1},t[s],e[s]);for(const a of s)a in e&&(t[a]=i.includes(a)?n(a):e[a])})(e,this.data,t)}}catch(e){O("Error loading settings, using defaults. ",e)}}async saveSettings(){const{plugin:e,data:t}=this;await(e?.saveData(t))}save(){this.saveSettings().catch((e=>{O("Error saving changes to settings",e)}))}isSymbolTypeEnabled(e){const{enabledSymbolTypes:t}=this.data;let s=ie.defaults.enabledSymbolTypes[e];return Object.prototype.hasOwnProperty.call(t,e)&&(s=t[e]),s}setSymbolTypeEnabled(e,t){this.data.enabledSymbolTypes[e]=t}shouldRenderSymbolAsHTML(e){const{renderMarkdownContentInSuggestions:t}=this.data;if(!t.isEnabled)return!1;const i={[s.Heading]:"renderHeadings",[s.Link]:"renderLinks",[s.Tag]:"renderTags",[s.Callout]:"renderCallouts"}[e];return!!i&&t[i]}static async transformDataFile(e,t){await ie.transformDataFileToV1(e,t),await ie.transformDataFileToV2(e,t)}static async transformDataFileToV1(e,t){let s=!1;try{const i=await(e?.loadData());if(i&&"object"==typeof i){const n="version";if(!Object.prototype.hasOwnProperty.call(i,n)){const a="starredListCommand";Object.prototype.hasOwnProperty.call(i,a)&&(i.bookmarksListCommand=i[a]??t.bookmarksListCommand,delete i[a]);const o="isStarred",r=i.matchPriorityAdjustments;r&&Object.prototype.hasOwnProperty.call(r,o)&&(r.isBookmarked=r[o],delete r[o]),i[n]="1.0.0",await(e?.saveData(i)),s=!0}}}catch(e){O("Error transforming data.json to v1.0.0",e)}return s}static async transformDataFileToV2(e,t){let s=!1;try{const i=await(e?.loadData());if(i&&"object"==typeof i){const n="version";if("1.0.0"===i[n]){const a="matchPriorityAdjustments";if(Object.prototype.hasOwnProperty.call(i,a)){const e=i[a],s={};i[a]={isEnabled:!!i.enableMatchPriorityAdjustments,adjustments:s},delete i.enableMatchPriorityAdjustments,Object.entries(e).forEach((([e,i])=>{const n=t.matchPriorityAdjustments.adjustments[e]?.label??"";s[e]={value:i,label:n}}))}const o="quickFilters";if(Object.prototype.hasOwnProperty.call(i,o)){const e="facetList",t=i[o],s=t[e],n=s?.reduce(((e,t)=>(e[t.id]=t,e)),{});t[e]=n}i[n]="2.0.0",await(e?.saveData(i)),s=!0}}}catch(e){O("Error transforming data.json to v2.0.0",e)}return s}}class ne{app;mainSettingsTab;config;constructor(e,t,s){this.app=e,this.mainSettingsTab=t,this.config=s}createSetting(e,t,s){let i;return e instanceof a.SettingGroup?e.addSetting((e=>{i=e,e.setName(t),e.setDesc(s)})):(i=new a.Setting(e),i.setName(t),i.setDesc(s)),i}withSetting(e,t,s,i){let n;return e instanceof a.SettingGroup?e.addSetting((e=>{n=e,e.setName(t).setDesc(s),i(e)})):(n=this.createSetting(e,t,s),i(n)),n}createOnChangeHandler(e,t){return s=>{t?t(s,this.config):e&&this.saveChangesToConfig(e,s)}}addSectionTitle(e,t,s=""){const i=this.createSetting(e,t,s);return i.setHeading(),i}addTextSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.addText((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{const t=e.length?e:i;this.saveChangesToConfig(n,t)}))}))}))}addToggleSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.addToggle((e=>{e.setValue(i),e.onChange(this.createOnChangeHandler(n,a))}))}))}addTextAreaSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addTextArea((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{if(o)o(e,this.config);else{const t=e.length?e:i,s=Array.isArray(this.config[n]);this.saveChangesToConfig(n,s?t.split("\n"):t)}}))}))}))}addDropdownSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addDropdown((e=>{e.addOptions(n),e.setValue(i),e.onChange(this.createOnChangeHandler(a,o))}))}))}addSliderSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addExtraButton((t=>(t.setIcon("lucide-rotate-ccw"),t.setTooltip("Restore default"),t.onClick((()=>e.components[1].setValue(n[3]))),t))),e.addSlider((e=>{e.setLimits(n[0],n[1],n[2]),e.setValue(i),e.setDynamicTooltip(),e.onChange(this.createOnChangeHandler(a,o))}))}))}saveChangesToConfig(e,t){if(e){const{config:s}=this;s[e]=t,s.save()}}showErrorPopup(e,t,s){const i=new a.Modal(this.app);i.titleEl.setText(e),i.contentEl.empty(),i.contentEl.createSpan({text:t}),i.contentEl.createEl("br"),i.contentEl.createEl("br"),s.forEach(((e,t)=>{t>0&&i.contentEl.createEl("br"),e.forEach(((e,t)=>{t>0&&i.contentEl.createEl("br");const s={text:e.text};void 0!==e.cls&&(s.cls=e.cls),i.contentEl.createSpan(s)}))})),i.open()}}class ae extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Bookmarks List Mode"),this.addTextSetting(e,"Bookmarks list mode trigger","Character that will trigger bookmarks list mode in the switcher",t.bookmarksListCommand,"bookmarksListCommand",t.bookmarksListPlaceholderText)}}class oe extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Command List Mode"),this.addTextSetting(e,"Command list mode trigger","Character that will trigger command list mode in the switcher",t.commandListCommand,"commandListCommand",t.commandListPlaceholderText),this.addSliderSetting(e,"Max recent commands","The maximum number of commands to save in the recent list.",t.maxRecentCommands,[0,75,1,25],"maxRecentCommands"),this.showRecentCommandDisplayOrder(e,t)}showRecentCommandDisplayOrder(e,t){this.addDropdownSetting(e,"Recent commands display order","Select the sort order for recently used commands.",t.recentCommandDisplayOrder,{desc:"Most recent first (descending)",asc:"Most recent last (ascending)"},"recentCommandDisplayOrder")}}class re extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Related Items List Mode"),this.addTextSetting(e,"Related Items list mode trigger","Character that will trigger related items list mode in the switcher. This triggers a display of Related Items for the source file of the currently selected (highlighted) suggestion in the switcher. If there is not a suggestion, display results for the active editor.",t.relatedItemsListCommand,"relatedItemsListCommand",t.relatedItemsListPlaceholderText),this.addTextSetting(e,"Related Items list mode trigger - Active editor only","Character that will trigger related items list mode in the switcher. This always triggers a display of Related Items for the active editor only.",t.relatedItemsListActiveEditorCommand,"relatedItemsListActiveEditorCommand",t.relatedItemsListActiveEditorCommand),this.showEnabledRelatedItems(e,t),this.addToggleSetting(e,"Exclude open files","Enable, related files which are already open will not be displayed in the list. Disabled, All related files will be displayed in the list.",t.excludeOpenRelatedFiles,"excludeOpenRelatedFiles")}showEnabledRelatedItems(e,t){const s=Object.values(c).sort(),i=s.join(", "),n=`The types of related items to show in the list. Add one type per line. Available types: ${i}`;this.createSetting(e,"Show related item types",n).addTextArea((e=>{e.setValue(t.enabledRelatedItems.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const n=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=[...new Set(n)].filter((e=>!s.includes(e)));a?.length?this.showErrorPopup("Invalid related item type",`Changes not saved. Available relation types are: ${i}. The following types are invalid:`,a.map((e=>[{text:e}]))):(t.enabledRelatedItems=n,t.save())}))}))}}class le extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"General"),this.addToggleSetting(e,"Default to open in new tab","When enabled, navigating to un-opened files will open a new editor tab whenever possible (as if cmd/ctrl were held). When the file is already open, the existing tab will be activated. This overrides all other tab settings.",t.onOpenPreferNewTab,"onOpenPreferNewTab"),this.showLauncherButtonOverrides(e,t),this.showEnabledRibbonCommands(e,t),this.addToggleSetting(e,"Show indicator icons","Display icons to indicate that an item is recent, bookmarked, etc..",t.showOptionalIndicatorIcons,"showOptionalIndicatorIcons"),this.addToggleSetting(e,"Display mode trigger instructions","When enabled, the trigger key for each mode will be displayed in the instructions section of the Switcher.",t.showModeTriggerInstructions,"showModeTriggerInstructions"),this.showStandardModeOverrides(e,t),this.showPathDisplayGroup(e,t),this.showPreferredSourceForTitle(e,t),this.showTagDisplaySettings(e,t),this.showQuickOpen(e,t),this.showRenderMarkdownContentAsHTML(e,t),this.addTextSetting(e,"Mode trigger escape character","Character to indicate that a mode trigger character should be treated just as a normal text.",t.escapeCmdChar,"escapeCmdChar"),this.addToggleSetting(e,"Allow Backspace key to close the Switcher","When the search box is empty, pressing the backspace key will close Switcher++.",t.shouldCloseModalOnBackspace,"shouldCloseModalOnBackspace"),this.showRestoreInput(e,t),this.showInsertLinkInEditor(e,t),this.showResetFacetEachSession(e,t),this.showMatchPriorityAdjustments(e,t)}showPreferredSourceForTitle(e,t){const s=new a.SettingGroup(e);this.addDropdownSetting(s,"Preferred suggestion title source",'The preferred source to use for the "title" text that will be searched and displayed for file based suggestions',t.preferredSourceForTitle,{H1:"First H₁ heading",Default:"Default",FrontMatter:"Frontmatter property"},"preferredSourceForTitle",((e,t)=>{t.preferredSourceForTitle=e,t.save(),this.mainSettingsTab.display()})),"FrontMatter"===t.preferredSourceForTitle&&this.addTextSetting(s,"Frontmatter property path",'The path to the frontmatter property to use as the title. Use dot notation for nested properties (e.g., "title" or "meta.display_name"). The property value must be a string, number, or boolean. If the property doesn\'t exist or has an invalid type, the default filename will be used.',t.frontmatterTitleProperty,"frontmatterTitleProperty","title")}showPathDisplayFormat(t,s){const i={};i[e.None.toString()]="Hide path",i[e.Full.toString()]="Full path",i[e.FolderOnly.toString()]="Only parent folder",i[e.FolderWithFilename.toString()]="Parent folder & filename",i[e.FolderPathFilenameOptional.toString()]="Parent folder path (filename optional)",this.addDropdownSetting(t,"Preferred file path display format","The preferred way to display file paths in suggestions",s.pathDisplayFormat.toString(),i,null,((e,t)=>{t.pathDisplayFormat=Number(e),t.save()}))}showPathDisplayGroup(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Path Display Settings","Configure how file paths are displayed in suggestions."),this.showPathDisplayFormat(s,t),this.addToggleSetting(s,"Hide path for root items","When enabled, path information will be hidden for items at the root of the vault.",t.hidePathIfRoot,"hidePathIfRoot")}showStandardModeOverrides(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Standard Mode Overrides","Configure how Switcher++ overrides the default Obsidian Switcher behavior in Standard mode."),this.addToggleSetting(s,"Override Standard mode file open behavior","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to inject custom file open behavior.",t.overrideStandardModeBehaviors,"overrideStandardModeBehaviors"),this.addToggleSetting(s,"Override Standard mode rendering","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to render suggestions as multi-line.",t.overrideStandardModeRendering,"overrideStandardModeRendering")}showRestoreInput(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Restore Previous Input","Configure whether to restore the last typed input when launching the Switcher."),this.addToggleSetting(s,"Restore previous input in Command Mode","When enabled, restore the last typed input in Command Mode when launched via global command hotkey.",t.preserveCommandPaletteLastInput,"preserveCommandPaletteLastInput"),this.addToggleSetting(s,"Restore previous input","When enabled, restore the last typed input when launched via global command hotkey.",t.preserveQuickSwitcherLastInput,"preserveQuickSwitcherLastInput")}showEnabledRibbonCommands(e,t){const s=E(),i=s.join(" "),n=`Display an icon in the ribbon menu to launch specific modes. Add one mode per line. Available modes: ${i}`;this.createSetting(e,"Show ribbon icons",n).addTextArea((e=>{e.setValue(t.enabledRibbonCommands.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const n=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=Array.from(new Set(n)).filter((e=>!s.includes(e)));a.length?this.showErrorPopup("Invalid mode",`Changes not saved. Available modes are: ${i}. The following are invalid:`,a.map((e=>[{text:e}]))):(t.enabledRibbonCommands=n,t.save(),this.mainSettingsTab.plugin.registerRibbonCommandIcons())}))}))}showLauncherButtonOverrides(e,t){const{mobileLauncher:s}=t,i=new a.SettingGroup(e),n="disabled",o={[n]:"Do not override"},r=E();r.forEach((e=>{o[e]=e}));let l=n;s.isEnabled&&r.includes(s.modeString)&&(l=s.modeString),this.addDropdownSetting(i,"New tab and mobile launcher buttons",'Select the Mode to launch Switcher++ in from the empty tab page and mobile navigation Bar button, or select "Do not override" to disable the feature.',l,o,null,((e,t)=>{const s=e!==n;t.mobileLauncher.isEnabled=s,s&&(t.mobileLauncher.modeString=e),t.save(),this.mainSettingsTab.display(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(s)})),s.isEnabled&&(this.addToggleSetting(i,"Override default Switcher launch button on mobile platforms",'When enabled, override the "🔍" button (in the Navigation Bar) on mobile platforms to launch Switcher++ instead of the default system switcher.',s.isMobileButtonEnabled,null,((e,t)=>{t.mobileLauncher.isMobileButtonEnabled=e,t.save(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(t.mobileLauncher.isEnabled)})),this.addToggleSetting(i,'Display launch button on the "New tab" page','When enabled, a button to launch Switcher++ using the selected mode above will be added to the default Obsidian "New tab" page.',s.isEmptyTabButtonEnabled,null,((e,t)=>{t.mobileLauncher.isEmptyTabButtonEnabled=e,t.save(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(t.mobileLauncher.isEnabled)})))}showMatchPriorityAdjustments(e,t){const{matchPriorityAdjustments:{isEnabled:s,adjustments:i,fileExtAdjustments:n}}=t,o=new a.SettingGroup(e);this.addToggleSetting(o,"Result priority adjustments","Artificially increase the match score of the specified item types by a fixed percentage so they appear higher in the results list (does not apply to Standard Mode).",s,null,((e,t)=>{t.matchPriorityAdjustments.isEnabled=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Result Priority Adjustments" setting. ',e)))})),s&&[i,n].forEach((e=>{Object.entries(e).forEach((([t,s])=>{const{value:i,label:n}=s;this.addSliderSetting(o,n,s.desc??"",i,[-1,1,.05,0],null,((s,i)=>{e[t].value=s,i.save()}))}))}))}showResetFacetEachSession(e,t){this.addToggleSetting(e,"Reset active Quick Filters","When enabled, the switcher will reset all Quick Filters back to inactive for each session.",t.quickFilters.shouldResetActiveFacets,null,((e,t)=>{t.quickFilters.shouldResetActiveFacets=e,t.save()}))}showRenderMarkdownContentAsHTML(e,t){const{renderMarkdownContentInSuggestions:s}=t,i=new a.SettingGroup(e),n=this.addToggleSetting(i,"Display markdown content as Live Preview",'When enabled, markdown content in symbol suggestions will be rendered as HTML similar to the Obsidian "Live Preview" display. When disabled, content will be rendered as raw text. Use the "toggle preview (selected item)" hotkey to toggle the display for individual items.',s.isEnabled,null,((e,t)=>{const{renderMarkdownContentInSuggestions:s}=t;s.isEnabled=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Display markdown content as Live Preview" setting. ',e)))}));if(n?.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"}),s.isEnabled){[{name:"Headings",property:"renderHeadings",description:"Render headings as HTML"},{name:"Links",property:"renderLinks",description:"Render links as HTML"},{name:"Tags",property:"renderTags",description:"Render tags as HTML"},{name:"Callouts",property:"renderCallouts",description:"Render callouts as HTML"}].forEach((({name:e,property:t,description:n})=>{this.addToggleSetting(i,e,n,s[t],null,((e,s)=>{s.renderMarkdownContentInSuggestions[t]=e,s.save()}))}))}}showInsertLinkInEditor(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Insert link in editor","Configure alias options when inserting links into the editor."),this.addToggleSetting(s,"Use filename as alias","When enabled, the file basename will be set as the link alias.",t.insertLinkInEditor.useBasenameAsAlias,null,((e,t)=>{t.insertLinkInEditor.useBasenameAsAlias=e,t.save()})),this.addToggleSetting(s,"Use heading as alias",'When enabled, the file heading will be set as the link alias. This overrides the "use filename as alias" setting.',t.insertLinkInEditor.useHeadingAsAlias,null,((e,t)=>{t.insertLinkInEditor.useHeadingAsAlias=e,t.save()}))}showQuickOpen(e,t){this.addToggleSetting(e,"Enable quick open hotkeys for top results","When enabled, hotkeys will be defined for each of the top N results displayed in the Switcher. These hotkeys can be used to quickly open the associated suggestion directly. when disabled, no hotkeys are defined.",t.quickOpen.isEnabled,null,((e,t)=>{t.quickOpen.isEnabled=e,t.save()}))}showTagDisplaySettings(e,t){const{showTagsInSuggestions:s}=t,i=new a.SettingGroup(e);if(this.addToggleSetting(i,"Show tags in suggestions","When enabled, tags associated with a file will be displayed in suggestions.",s,null,((e,t)=>{t.showTagsInSuggestions=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Show tags in suggestions" setting. ',e)))})),s){const e={[n.Both]:"Both",[n.Inline]:"Inline only",[n.Frontmatter]:"Frontmatter only"};this.addDropdownSetting(i,"Tag source","Select which tags to display: inline tags (in document body), frontmatter tags, or both.",t.tagSource,e,null,((e,t)=>{t.tagSource=e,t.save()})),this.addTextAreaSetting(i,"Excluded tags","Tags to exclude from display, one per line. Tags should be entered without the # prefix.",t.excludeTagsFromDisplay.join("\n"),null,"tag1\ntag2\ntag3",((e,t)=>{const s=e.split("\n").map((e=>e.trim())).filter((e=>e.length>0));t.excludeTagsFromDisplay=s,t.save()})),this.addSliderSetting(i,"Max tags to display","Maximum number of tags to show per suggestion. Set to 0 for unlimited.",t.maxTagsToDisplay,[0,20,1,5],"maxTagsToDisplay"),this.addTextSetting(i,"Tag separator","The string used to separate multiple tags in the display.",t.tagDisplaySeparator,"tagDisplaySeparator",", "),this.addToggleSetting(i,"Remove # prefix from tags","When enabled, the # prefix will be removed from tags when displayed.",t.removeHashPrefixFromTags,"removeHashPrefixFromTags")}}}class de extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Workspace List Mode"),this.addTextSetting(e,"Workspace list mode trigger","Character that will trigger workspace list mode in the switcher",t.workspaceListCommand,"workspaceListCommand",t.workspaceListPlaceholderText)}}class ce extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Editor List Mode"),this.addTextSetting(e,"Editor list mode trigger","Character that will trigger editor list mode in the switcher",t.editorListCommand,"editorListCommand",t.editorListPlaceholderText),this.showIncludeSidePanelViews(e,t),this.addToggleSetting(e,"Order default editor list by most recently accessed","When there is no search term, order the list of editors by most recent access time.",t.orderEditorListByAccessTime,"orderEditorListByAccessTime")}showIncludeSidePanelViews(e,t){const s=`When in Editor list mode, show the following view types from the side panels. Add one view type per line. Available view types: ${Object.keys(this.app.viewRegistry.viewByType).sort().join(" ")}`;this.addTextAreaSetting(e,"Include side panel views",s,t.includeSidePanelViewTypes.join("\n"),"includeSidePanelViewTypes",t.includeSidePanelViewTypesPlaceholder)}}class he extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Headings List Mode"),this.addTextSetting(e,"Headings list mode trigger","Character that will trigger headings list mode in the switcher",t.headingsListCommand,"headingsListCommand",t.headingsListPlaceholderText),this.addSliderSetting(e,"Max recent files to show","The maximum number of recent files to show when there is no search term",t.maxRecentFileSuggestionsOnInit,[0,75,1,25],"maxRecentFileSuggestionsOnInit"),this.showFileExtAllowList(e,t),this.addToggleSetting(e,"Search Filenames","Enabled, search and show suggestions for filenames. Disabled, Don't search through filenames (except for fallback searches)",t.shouldSearchFilenames,"shouldSearchFilenames"),this.addToggleSetting(e,"Search Bookmarks","Enabled, search and show suggestions for Bookmarks. Disabled, Don't search through Bookmarks",t.shouldSearchBookmarks,"shouldSearchBookmarks"),this.showHeadingSettings(e,t),this.showExclusionsGroup(e,t)}showHeadingSettings(e,t){const s=t.shouldSearchHeadings,i=new a.SettingGroup(e);this.addToggleSetting(i,"Search Headings","Enabled, search and show suggestions for Headings. Disabled, Don't search through Headings",s,null,((e,t)=>{t.shouldSearchHeadings=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Search Headings" setting. ',e)))})),s&&(this.addToggleSetting(i,"Turn off filename fallback","Enabled, strictly search through only the headings contained in the file. Do not fallback to searching the filename when an H1 match is not found. Disabled, fallback to searching against the filename when there is not a match in the first H1 contained in the file.",t.strictHeadingsOnly,"strictHeadingsOnly"),this.addToggleSetting(i,"Search all headings","Enabled, search through all headings contained in each file. Disabled, only search through the first H1 in each file.",t.searchAllHeadings,"searchAllHeadings"),this.showBreadcrumbSettings(i,t))}showFileExtAllowList(e,t){this.createSetting(e,"File extension override",'Override the "Show attachments" and the "Show all file types" builtin, system Switcher settings and always search files with the listed extensions. Add one path per line. For example to add ".canvas" file extension, just add "canvas".').addTextArea((e=>{e.setValue(t.fileExtAllowList.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const s=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0));t.fileExtAllowList=s,t.save()}))}))}showExclusionsGroup(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Exclusions","Configure which folders and files should be excluded from search results in Headings list mode."),this.showExcludeFolders(s,t),this.addToggleSetting(s,'Hide Obsidian "Excluded files"','Enabled, do not display suggestions for files that are in Obsidian\'s "Options > Files & Links > Excluded files" list. Disabled, suggestions for those files will be displayed but downranked.',t.excludeObsidianIgnoredFiles,"excludeObsidianIgnoredFiles")}showExcludeFolders(e,t){const s="Exclude folders";this.createSetting(e,s,"When in Headings list mode, folder path that match any regex listed here will not be searched for suggestions. Path should start from the Vault Root. Add one path per line.").addTextArea((e=>{e.setValue(t.excludeFolders.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const i=e.getValue().split("\n").filter((e=>e.length>0));this.validateExcludeFolderList(s,i)&&(t.excludeFolders=i,t.save())}))}))}showBreadcrumbSettings(e,t){this.addToggleSetting(e,"Show heading breadcrumbs","Enabled, display the hierarchical path of parent headings leading to each heading suggestion.",t.showHeadingBreadcrumbs,"showHeadingBreadcrumbs"),this.addTextSetting(e,"Breadcrumb separator","The string used to separate heading levels in breadcrumbs",t.headingBreadcrumbSeparator,"headingBreadcrumbSeparator"),this.addSliderSetting(e,"Max breadcrumb depth","Maximum number of heading levels to show in breadcrumbs. Set to 0 for unlimited depth.",t.maxBreadcrumbDepth,[0,6,1,0],"maxBreadcrumbDepth")}validateExcludeFolderList(e,t){let s=!0;const i=[];for(const e of t)try{new RegExp(e)}catch(t){i.push({regex:e,error:t}),s=!1}return s||this.showErrorPopup(e,"Changes not saved. The following regex contain errors:",i.map((({regex:e,error:t})=>[{text:e,cls:"qsp-warning"},{text:t.toString()}]))),s}}class me extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Symbol List Mode"),this.addTextSetting(e,"Symbol list mode trigger","Character that will trigger symbol list mode in the switcher. This triggers a display of Symbols for the source file of the currently selected (highlighted) suggestion in the switcher. If there is not a suggestion, display results for the active editor.",t.symbolListCommand,"symbolListCommand",t.symbolListPlaceholderText),this.addTextSetting(e,"Symbol list mode trigger - Active editor only","Character that will trigger symbol list mode in the switcher. This always triggers a display of Symbols for the active editor only.",t.symbolListActiveEditorCommand,"symbolListActiveEditorCommand",t.symbolListActiveEditorCommand),this.addToggleSetting(e,"List symbols as indented outline","Enabled, symbols will be displayed in the (line) order they appear in the source text, indented under any preceding heading. Disabled, symbols will be grouped by type: Headings, Tags, Links, Embeds.",t.symbolsInLineOrder,"symbolsInLineOrder"),this.addToggleSetting(e,"Auto-select nearest heading","Enabled, in an unfiltered symbol list, select the closest preceding Heading to the current cursor position. Disabled, the first symbol in the list is selected.",t.selectNearestHeading,"selectNearestHeading"),this.addToggleSetting(e,"Show heading breadcrumbs in Symbol mode","Enabled, display the hierarchical path of parent headings when showing heading symbols in Symbol mode.",t.showHeadingBreadcrumbsInSymbolMode,"showHeadingBreadcrumbsInSymbolMode"),this.showEnableSymbolTypesToggle(e,t),this.showEnableLinksToggle(e,t),this.showSymbolTabNavigationBehavior(e,t)}showSymbolTabNavigationBehavior(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Symbol Tab navigation behavior","Configure how symbols are opened when navigating from the symbol list."),this.addToggleSetting(s,"Open Symbols in new tab","Enabled, always open a new tab when navigating to Symbols. Disabled, navigate in an already open tab (if one exists).",t.alwaysNewTabForSymbols,"alwaysNewTabForSymbols"),this.addToggleSetting(s,"Open Symbols in active tab on mobile devices","Enabled, navigate to the target file and symbol in the active editor tab. Disabled, open a new tab when navigating to Symbols, even on mobile devices.",t.useActiveTabForSymbolsOnMobile,"useActiveTabForSymbolsOnMobile")}showEnableSymbolTypesToggle(e,t){[["Show Headings",s.Heading],["Show Tags",s.Tag],["Show Embeds",s.Embed],["Show Callouts",s.Callout]].forEach((([s,i])=>{this.addToggleSetting(e,s,"",t.isSymbolTypeEnabled(i),null,(e=>{t.setSymbolTypeEnabled(i,e),t.save()}))}))}showEnableLinksToggle(e,t){const n=t.isSymbolTypeEnabled(s.Link),o=new a.SettingGroup(e);if(this.addToggleSetting(o,"Show Links","",n,null,(e=>{t.setSymbolTypeEnabled(s.Link,e),t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Show Links" setting. ',e)))})),n){[["Links to headings",i.Heading],["Links to blocks",i.Block]].forEach((([e,s])=>{const i=(t.excludeLinkSubTypes&s)===s;this.addToggleSetting(o,e,"",!i,null,(e=>this.saveEnableSubLinkChange(s,e)))}))}}saveEnableSubLinkChange(e,t){const{config:s}=this;let i=s.excludeLinkSubTypes;t?i&=~e:i|=e,s.excludeLinkSubTypes=i,s.save()}}class ue extends ne{display(e){const{config:t}=this,s=this.addSectionTitle(e,"Vault List Mode");s.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"}),this.addTextSetting(e,"Vault list mode trigger","Character that will trigger vault list mode in the switcher",t.vaultListCommand,"vaultListCommand",t.vaultListPlaceholderText)}}class ge extends a.PluginSettingTab{plugin;config;constructor(e,t,s){super(e,t),this.plugin=t,this.config=s,this.containerEl.addClass("qsp-settings-container")}display(){const{containerEl:e}=this,t=[le,me,he,ce,re,ae,oe,de,ue];e.empty(),t.forEach((e=>{this.displayTabSection(e)}))}displayTabSection(e){const{app:t,config:s,containerEl:i}=this;new e(t,this,s).display(i)}}class pe{inputText;mode;parsedCommands;_cleanInput=null;static get defaultParsedCommand(){return{isValidated:!1,index:-1,parsedInput:null}}sessionOpts;currentWorkspaceEnvList={openWorkspaceLeaves:new Set,openWorkspaceFiles:new Set,fileBookmarks:new Map,nonFileBookmarks:new Set,mostRecentFiles:new Set,attachmentFileExtensions:new Set};get parsedInputQuery(){const e=(this.parsedCommand()?.parsedInput??"").trim().toLowerCase();return{query:e,hasSearchTerm:!!e.length}}get cleanInput(){return this._cleanInput??this.inputText}set cleanInput(e){this._cleanInput=e}constructor(e="",s=t.Standard,i){this.inputText=e,this.mode=s,this.sessionOpts=i??{};const n=F();this.parsedCommands={},E().forEach((e=>{const s=t[e];n.includes(s)?this.parsedCommands[s]={...pe.defaultParsedCommand,source:null}:this.parsedCommands[s]=pe.defaultParsedCommand}))}parsedCommand(e){return e=e??this.mode,this.parsedCommands[e]}}class fe{app;settings;facets;constructor(e,t){this.app=e,this.settings=t}reset(){}onNoResultsCreateAction(e,t){return!1}getFacets(e){if(!this.facets){const t=this.settings?.quickFilters?.facetList;t&&(this.facets=Object.values(t).filter((t=>t.mode===e)))}return this.facets??[]}getAvailableFacets(e){return this.getFacets(e.mode).filter((e=>e.isAvailable))}activateFacet(e,t){e.forEach((e=>e.isActive=t)),this.settings.quickFilters.shouldResetActiveFacets||this.settings.save()}getActiveFacetIds(e){const t=this.getAvailableFacets(e).filter((e=>e.isActive)).map((e=>e.id));return new Set(t)}isFacetedWith(e,t){const s=!!e.size;return s&&e.has(t)||!s}getEditorInfo(e){const{excludeViewTypes:t}=this.settings;let s=null,i=!1,n=null;if(e){s=H(e),n=this.getCursorPosition(e);i=!t.includes(e.view.getViewType())&&!!s}return{isValidSource:i,leaf:e,file:s,suggestion:null,cursor:n}}getSuggestionInfo(e){const t=this.getSourceInfoFromSuggestion(e);let s=t.leaf;t.isValidSource&&({leaf:s}=this.findMatchingLeaf(t.file,t.leaf));const i=this.getCursorPosition(s);return{...t,leaf:s,cursor:i}}getSourceInfoFromSuggestion(e){let t=null,s=null;const i=[l.SymbolList,l.Unresolved,l.WorkspaceList,l.CommandList,l.VaultList];e&&!i.includes(e.type)&&(t=e.file),m(e,"type",l.EditorList)&&(s=e.item);return{isValidSource:!!t,leaf:s,file:t,suggestion:e}}getCursorPosition(e){let t=null;if(K(e,"markdown")){const s=e.view;"preview"!==s.getMode()&&(t=s.editor.getCursor("head"))}return t}getTitleText(e){const t=function(e){let t=null;if(e){const{path:s}=e;if(t=s,"md"===e.extension){const e=s.lastIndexOf(".");-1!==e&&e!==s.length-1&&0!==e&&(t=s.slice(0,e))}}return t}(e),s=this.getFirstH1(e);return s?.heading??t}getFirstH1(e){return fe.getFirstH1(e,this.app.metadataCache)}static getFirstH1(e,t){let s=null;const i=t.getFileCache(e)?.headings?.filter((e=>1===e.level))??[];return i.length&&(s=i.reduce(((e,t)=>{const{line:s}=t.position.start;return s0?i.trim():"number"==typeof i||"boolean"==typeof i?String(i):null}findMatchingLeaf(e,t,s=!1){let i=null;const n=!!t,{settings:{referenceViews:a,excludeViewTypes:o,includeSidePanelViewTypes:r}}=this,l=i=>{let o=!1;if(i?.view){const r=a.includes(i.view.getViewType()),l=s||!r,d=n&&a.includes(t.view.getViewType());l&&(o=!n||!s&&d?H(i)===e:i===t)}return o},d=this.getActiveLeaf();if(l(d))i=d;else{const e=this.getOpenLeaves(o,r);i=[t,...e].find(l)}return{leaf:i??null,file:e,suggestion:null,isValidSource:!1}}extractTabNavigationType(e,t,s){const i=e?.shiftKey?"horizontal":"vertical",n=e?.key;let o=a.Keymap.isModEvent(e)??!1;return!0!==o&&"tab"!==o||("o"===n?o="window":"\\"===n&&(o="split")),o=this.applyTabCreationPreferences(o,t,s),{navType:o,splitDirection:i}}applyTabCreationPreferences(e,s=!1,i){let n=e;const{onOpenPreferNewTab:o,alwaysNewTabForSymbols:r,useActiveTabForSymbolsOnMobile:l}=this.settings;return!1===e&&(o?n=!s:i===t.SymbolList&&(n=a.Platform.isMobile?!l:r)),n}isMainPanelLeaf(e){const{workspace:t}=this.app,s=e?.getRoot();return s===t.rootSplit||s===t.floatingSplit}async activateLeaf(e,t){const{workspace:s}=this.app;try{await s.revealLeaf(e),s.setActiveLeaf(e,{focus:!0}),e.view.setEphemeralState({focus:!0,...t})}catch(t){const s=e?.getDisplayText();A(`Error activating WorkspaceLeaf with title: ${s}`,t)}}getOpenLeaves(e,t,s){const i=[];return this.app.workspace.iterateAllLeaves((s=>{const n=s?.view?.getViewType();this.isMainPanelLeaf(s)?e?.includes(n)||i.push(s):t?.includes(n)&&i.push(s)})),s?.orderByAccessTime&&i.sort(((e,t)=>{const s=e?.activeTime??0;return(t?.activeTime??0)-s})),i}static async openFileInLeaf(e,t,s,i,n="vertical"){const a="split"===t?s.getLeaf(t,n):s.getLeaf(t);await a.openFile(e,i)}navigateToLeafOrOpenFile(e,t,s,i,n,a,o=!1){this.navigateToLeafOrOpenFileAsync(e,t,i,n,a,o).catch((e=>{A(`Error navigating to open file. ${s}`,e)}))}async navigateToLeafOrOpenFileAsync(e,t,s,i,n,a=!1){const{leaf:o}=this.findMatchingLeaf(t,i,a),r=!!o,{navType:l,splitDirection:d}=this.extractTabNavigationType(e,r,n);await this.activateLeafOrOpenFile(l,t,o,s,d)}async activateLeafOrOpenFile(e,t,s,i,n){if(i=i??this.getOpenViewActiveState(),s&&!1===e){const e=i?.eState;await this.activateLeaf(s,e)}else await fe.openFileInLeaf(t,e,this.app.workspace,i,n)}renderPath(t,s,i,n,a){if(!t||!s)return;const o=s.parent.isRoot();let r=this.settings.pathDisplayFormat,l=r===e.None||o&&this.settings.hidePathIfRoot;if(a&&(r=e.FolderPathFilenameOptional,l=!1),!l){const e=this.getPathDisplayText(s,r,i);this.renderBreadcrumb(t,e,"lucide-folder-open",n,["qsp-path"])}}renderBreadcrumb(e,t,s,i,n){if(!e||!t)return;const o=["suggestion-note","qsp-note"];n&&o.push(...n);const r=e.createDiv({cls:o}),l=r.createSpan({cls:["qsp-breadcrumb-indicator"]});a.setIcon(l,s);const d=r.createSpan({cls:"qsp-breadcrumb"});a.renderResults(d,t,i)}renderHeadingBreadcrumbs(e,t,s,i){if(!((i??this.settings.showHeadingBreadcrumbs)&&e&&t&&s))return;if(1===t.level)return;const n=function(e,t,s){const i=s.getFileCache(t)?.headings??[],n=e.position.start.line,a=new Map;for(const t of i){const s=t.position.start.line;if(s>=n)continue;if(t.level>=e.level)continue;const i=a.get(t.level);(!i||s>i.position.start.line)&&a.set(t.level,t)}const o=[];for(let t=1;t0&&n.length>a&&o.push("qsp-truncated");const r=function(e,t=" > ",s=0){let i=e;return s>0&&e.length>s&&(i=e.slice(-s)),i.map((e=>e.heading)).join(t)}(n,this.settings.headingBreadcrumbSeparator,a);r&&this.renderBreadcrumb(e,r,"lucide-heading",void 0,o)}renderTags(e,t){const{settings:s}=this;if(!s.showTagsInSuggestions||!e||!t)return;const i=new Set(s.excludeTagsFromDisplay),a=function(e,t,s=n.Both,i){const a=t.getFileCache(e);if(!a)return[];const o=new Set;s!==n.Inline&&s!==n.Both||(a.tags??[]).forEach((e=>o.add(e.tag)));s!==n.Frontmatter&&s!==n.Both||h.getTags(a.frontmatter).forEach((e=>{o.add(e.startsWith("#")?e:`#${e}`)}));let r=Array.from(o);return i&&i.size>0&&(r=r.filter((e=>{const t=e.startsWith("#")?e.slice(1):e;return!i.has(t)}))),r.sort()}(t,this.app.metadataCache,s.tagSource,i);if(0===a.length)return;let o=a;const r=["qsp-tags-breadcrumbs"];s.maxTagsToDisplay>0&&a.length>s.maxTagsToDisplay&&(o=a.slice(0,s.maxTagsToDisplay),r.push("qsp-truncated"));const l=function(e,t=" ",s=!1){return e&&0!==e.length?(s?e.map((e=>e.startsWith("#")?e.slice(1):e)):e).join(t):""}(o,s.tagDisplaySeparator,s.removeHashPrefixFromTags);l&&this.renderBreadcrumb(e,l,"lucide-tags",void 0,r)}getPathDisplayText(t,s,i){let n="";if(t){const{parent:o}=t,r=o.name,l=o.isRoot(),d=this.app.vault.getRoot().path;switch(s){case e.FolderWithFilename:n=l?`${t.name}`:a.normalizePath(`${r}/${t.name}`);break;case e.FolderOnly:n=l?d:r;break;case e.Full:n=t.path;break;case e.FolderPathFilenameOptional:i?(n=o.path,l||(n+=d)):n=this.getPathDisplayText(t,e.Full)}}return n}renderContent(e,t,s,i){const{contentEl:n,titleEl:o}=fe.createContentStructureElements(e);return a.renderResults(o,t,s,i),n}static createContentStructureElements(e){const t=e.createDiv({cls:["suggestion-content","qsp-content"]}),s=t.createDiv({cls:["suggestion-title","qsp-title"]});return{contentEl:t,titleEl:s}}static renderMarkdownContentAsync(e,t,s,i){fe.renderMarkdownContent(e,t,s,i,q.getRootComponent()).catch((e=>{O("Error rendering markdown to html. ",e,`content: ${s}`)}))}static async renderMarkdownContent(e,t,s,i,n){const o=t.createDiv({cls:["qsp-rendered-container"]});if(await a.MarkdownRenderer.render(e,s,o,i,n),1===o.childNodes.length&&"P"===o.firstChild.nodeName){const e=o.firstChild;e.replaceWith(...Array.from(e.childNodes))}return o}addClassesToSuggestionContainer(e,t){const s=["mod-complex"];t&&s.push(...t),e?.addClasses(s)}splitSearchMatchesAtBasename(e,t){let s=null,i=null;const n=(e,t)=>{e.forEach((e=>{e[0]-=t,e[1]-=t}))};if(e&&t?.matches){const a=e.path.lastIndexOf(e.basename);if(a>=0){const{matches:e,score:o}=t,r=e[0][0],l=e[e.length-1][1];if(r>=a)s=t,n(s.matches,a);else if(l<=a)i=t;else{let t=e.length;for(;t--;){const r=e[t][0],l=t+1;if(e[t][1]<=a){i={score:o,matches:e.slice(0,l)},s={score:o,matches:e.slice(l)},n(s.matches,a);break}if(r{t=t??o;let s=0;return Object.prototype.hasOwnProperty.call(t,e)&&(s=Number(t[e]?.value)),isNaN(s)?0:s},h=(t,s)=>{let i=0;return(null!==t&&t===n||e[s])&&(i=c(s)),i};d+=h(l.Bookmark,"isBookmarked"),d+=h(l.EditorList,"isOpenInEditor"),d+=h(null,"isRecent"),d+=h(null,"isAttachment"),d+=c(a?.extension,r),g(e)&&(d+=c(`h${e.item?.level}`));const m=n.toString();d+=c(m),i.score+=Math.abs(i.score)/100*(100*d)}}return e}static updateWorkspaceEnvListStatus(e,t){if(e&&t?.file){const{file:s}=t;t.isOpenInEditor=e.openWorkspaceFiles?.has(s),t.isRecent=e.mostRecentFiles?.has(s),t.isBookmarked=e.fileBookmarks?.has(s),t.isAttachment=e.attachmentFileExtensions?.has(s.extension)}return t}renderFileCreationSuggestion(e,t){this.addClassesToSuggestionContainer(e);const s=this.renderContent(e,t,null),i=this.createFlairContainer(e);return i?.createSpan({cls:"suggestion-hotkey",text:"Enter to create"}),s}createFile(e,t){const{workspace:s}=this.app,{navType:i}=this.extractTabNavigationType(t),n=s.getActiveViewOfType(a.FileView);let o="";n?.file&&(o=n.file.path),s.openLinkText(e,o,i,{active:!0}).catch((e=>{A("Error creating new file. ",e)}))}getOpenViewState(e,t){const s=this.getPreferredViewLinePosition(e),{eState:i}=this.getOpenViewLinePositionState(s),n=this.getOpenViewActiveState(t);return Object.assign(n.eState,i),n}getOpenViewActiveState(e){const{active:t,focus:s}=Object.assign({active:!0,focus:!0},e);return{active:t,eState:{active:t,focus:s}}}getPreferredViewLinePosition(e){const t={line:0,col:0,offset:0};return{start:t,end:t}}getOpenViewLinePositionState(e){const t=Object.assign({line:0,col:0,offset:0},e?.start),s=Object.assign({line:0,col:0,offset:0},e?.end),{line:i,col:n}=t;return{eState:{startLoc:t,endLoc:s,line:i,cursor:{from:{line:i,ch:n},to:{line:i,ch:n}}}}}}class ye{useSimpleSearch;_searchDelegate;query;hasSearchTerm;constructor(e,t){this.useSimpleSearch=t,this.query=(e??"").trim().toLowerCase(),this.hasSearchTerm=!!this.query.length}static create(e,t=!1){return new ye(e,t)}searchWithFallback(e,t){let s,i=d.None,n=null,a=this.searchAndDownrankSecondaryMatch(e);if(a.match)n=a.match,i=d.Primary,s=e;else if(t){const{basename:e,path:o}=t;a=this.searchAndDownrankSecondaryMatch(e,o),a.isPrimary?(i=d.Basename,s=e):a.match&&(i=d.Path,s=o),n=a.match}return{matchType:i,matchText:s,match:n}}searchAndDownrankSecondaryMatch(e,t){let s=!1,i=null;return e&&(i=this.executeSearch(e),s=!!i),!i&&t&&(i=this.executeSearch(t),i&&(i.score-=1)),{isPrimary:s,match:i}}executeSearch(e){const t=this.getSearchDelegate();return t?t(e):null}getSearchDelegate(){if(!this._searchDelegate){const{query:e,useSimpleSearch:t}=this;this._searchDelegate=t?a.prepareSimpleSearch(e):a.prepareFuzzySearch(e)}return this._searchDelegate}}class be extends fe{getCommandString(e){return this.settings?.workspaceListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.WorkspaceList);return this.getEnabledWorkspacesPluginInstance()&&(e.mode=t.WorkspaceList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((e=>{let s=!0,a=null;i&&(({match:a}=n.searchWithFallback(e.id)),s=!!a),s&&t.push({type:l.WorkspaceList,item:e,match:a})})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;return e&&(this.addClassesToSuggestionContainer(t,["qsp-suggestion-workspace"]),this.renderContent(t,e.item.id,e.match),s=!0),s}onChooseSuggestion(e,t){let s=!1;if(e){const{id:t}=e.item,i=this.getEnabledWorkspacesPluginInstance();i&&i.loadWorkspace(t),s=!0}return s}onNoResultsCreateAction(e,s){const i=this.getEnabledWorkspacesPluginInstance();if(i){const s=e.parsedCommand(t.WorkspaceList)?.parsedInput;i.saveWorkspace(s),i.setActiveWorkspace(s)}return!0}getItems(){const e=[],t=this.getEnabledWorkspacesPluginInstance()?.workspaces;return t&&Object.keys(t).forEach((t=>e.push({id:t,type:"workspaceInfo"}))),e.sort(((e,t)=>e.id.localeCompare(t.id)))}getEnabledWorkspacesPluginInstance(){return be.getEnabledWorkspacesPluginInstance(this.app)}static getEnabledWorkspacesPluginInstance(e){return I(e,"workspaces")}}class Se extends fe{getCommandString(e){return""}validateCommand(e,t,s,i,n){throw new Error("Method not implemented.")}getSuggestions(e){throw new Error("Method not implemented.")}renderSuggestion(e,t){let s=!1;return p(e)?s=this.renderFileSuggestion(e,t):f(e)&&(s=this.renderAliasSuggestion(e,t)),e?.downranked&&t.addClass("mod-downranked"),s}onChooseSuggestion(e,t){let s=!1;if(e){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open file from SystemSuggestion ${i.path}`),s=!0}return s}renderFileSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-file"],null,i,n,a),this.renderOptionalIndicators(t,e),s=!0}return s}renderAliasSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-alias"],e.alias,i,n,a,!1);const o=this.renderOptionalIndicators(t,e);this.renderIndicator(o,["qsp-alias-indicator"],"lucide-forward"),s=!0}return s}addPropertiesToStandardSuggestions(e,t){const{match:s}=t;let i=d.None,n=null;s?.matches&&(f(t)?(i=d.Primary,n=t.alias):p(t)&&(i=d.Path,n=t.file.path)),t.matchType=i,t.matchText=n,fe.updateWorkspaceEnvListStatus(e,t)}static createUnresolvedSuggestion(e,t,s,i){const n={linktext:e,type:l.Unresolved,...t};return fe.applyMatchPriorityPreferences(n,s,i)}}class ke extends fe{getCommandString(e){return this.settings?.editorListCommand}validateCommand(e,s,i,n,a){e.mode=t.EditorList;const o=e.parsedCommand(t.EditorList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((s=>{const a=H(s);let o=!0,r={matchType:d.None,match:null};const l=this.getPreferredTitle(s,this.settings.preferredSourceForTitle);i&&(r=n.searchWithFallback(l,a),o=r.matchType!==d.None),o&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,s,a,r,l))})),i&&a.sortSearchResults(t)}return t}getPreferredTitle(e,t){return ke.getPreferredTitle(e,t,this.app.metadataCache,this.settings.frontmatterTitleProperty)}static getPreferredTitle(e,t,s,i){const n=H(e);let a=e.getDisplayText();if("H1"===t&&n){const e=ke.getFirstH1(n,s);e&&(a=a.replace(n.basename,e.heading))}else if("FrontMatter"===t&&n&&i){const e=s.getFileCache(n)?.frontmatter,t=fe.getFrontmatterProperty(e,i);t&&(a=a.replace(n.basename,t))}return a}getItems(){const{excludeViewTypes:e,includeSidePanelViewTypes:t,orderEditorListByAccessTime:s}=this.settings;return this.getOpenLeaves(e,t,{orderByAccessTime:s})}renderSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e,o=[d.None,d.Primary].includes(n);this.renderAsFileInfoPanel(t,["qsp-suggestion-editor"],e.preferredTitle,i,n,a,o),this.renderOptionalIndicators(t,e),s=!0}return s}onChooseSuggestion(e,t){let s=!1;return e&&(this.navigateToLeafOrOpenFile(t,e.file,"Unable to reopen existing editor in new Leaf.",null,e.item,null,!0),s=!0),s}createSuggestion(e,t,s,i,n){return ke.createSuggestion(e,t,s,this.settings,this.app.metadataCache,n,i)}static createSuggestion(e,t,s,i,n,a,o){o=o??{matchType:d.None,match:null,matchText:null};let r={item:t,file:s,preferredTitle:a=a??null,type:l.EditorList,...o};return r=fe.updateWorkspaceEnvListStatus(e,r),fe.applyMatchPriorityPreferences(r,i,n)}}class ve extends fe{getCommandString(e){return this.settings?.bookmarksListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.BookmarksList);return this.getEnabledBookmarksPluginInstance()&&(e.mode=t.BookmarksList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s),{allBookmarks:o}=this.getItems(e);o.forEach((s=>{let a=!0,o={matchType:d.None,match:null};i&&(o=n.searchWithFallback(s.bookmarkPath),a=o.matchType!==d.None),a&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,s,o))})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;if(e&&ve.isBookmarksPluginFileItem(e.item)){const{file:i,matchType:n,match:a,bookmarkPath:o}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-bookmark"],o,i,n,a),this.renderOptionalIndicators(t,e),s=!0}return s}onChooseSuggestion(e,t){let s=!1;if(ve.isBookmarksPluginFileItem(e?.item)){const{file:i}=e,n=`Unable to open file from BookmarkSuggestion ${i?.path}`,a=this.getOpenViewState(e);this.navigateToLeafOrOpenFile(t,i,n,a),s=!0}return s}getPreferredViewLinePosition(e){if(e&&ve.isBookmarksPluginFileItem(e.item)){const t=this.getBookmarkSubpathPosition(e.file,e.item.subpath);if(t)return t}return super.getPreferredViewLinePosition(e)}getBookmarkSubpathPosition(e,t){if(!t)return null;const s=this.app.metadataCache.getFileCache(e),i=s?a.resolveSubpath(s,t):null;return"block"===i?.type?i.block.position:"heading"===i?.type?i.current.position:null}getPreferredTitle(e,t,s,i){let n=e.getItemTitle(t);if(s&&!t.title)if("H1"===i){const e=this.getFirstH1(s);e&&(n=n.replace(/^[^#]*/,e.heading))}else if("FrontMatter"===i){const e=this.app.metadataCache.getFileCache(s)?.frontmatter,t=fe.getFrontmatterProperty(e,this.settings.frontmatterTitleProperty);t&&(n=n.replace(/^[^#]*/,t))}return n}getItems(e){const t=[],s=new Map,i=new Set,n=this.getEnabledBookmarksPluginInstance();if(n){const a=e?this.getActiveFacetIds(e):new Set,o=(e,r)=>{e?.forEach((e=>{if(ve.isBookmarksPluginGroupItem(e))o(e.items,`${r}${e.title}/`);else if(this.isFacetedWith(a,G[e.type])){let a;if(ve.isBookmarksPluginFileItem(e)){const t=this.getTFileByPath(e.path);if(t){a={item:e,bookmarkPath:null,file:t};const i=s.get(t)??[];i.push(a),s.set(t,i)}}else a={item:e,bookmarkPath:null,file:null},i.add(a);if(a){const s=this.getPreferredTitle(n,e,a.file,this.settings.preferredSourceForTitle);a.bookmarkPath=r+s,t.push(a)}}}))};o(n.items,"")}return{allBookmarks:t,fileBookmarks:s,nonFileBookmarks:i}}getEnabledBookmarksPluginInstance(){return I(this.app,"bookmarks")}createSuggestion(e,t,s){return ve.createSuggestion(e,t,this.settings,this.app.metadataCache,s)}static createSuggestion(e,t,s,i,n){let a={type:l.Bookmark,item:t.item,bookmarkPath:t.bookmarkPath,file:t.file,...n};return a=fe.updateWorkspaceEnvListStatus(e,a),fe.applyMatchPriorityPreferences(a,s,i)}static isBookmarksPluginFileItem(e){return m(e,"type","file")}static isBookmarksPluginGroupItem(e){return m(e,"type","group")}addPropertiesToStandardSuggestions(e,t){const{match:s,item:i}=t;let n=d.None,a=null;if(!t.file&&ve.isBookmarksPluginFileItem(i)){const e=i.path;t.file=this.getTFileByPath(e)}s?.matches&&(n=d.Primary,a=t.bookmarkPath),t.matchType=n,t.matchText=a,fe.updateWorkspaceEnvListStatus(e,t)}}const we={file:"lucide-file-text",text:"lucide-sticky-note",link:"lucide-globe",group:"create-group"},Ce={table:"lucide-table",list:"lucide-list",cards:"lucide-layout-grid"};class Ie extends fe{inputInfo;getCommandString(e){const{settings:t}=this;return e?.useActiveEditorAsSource?t.symbolListActiveEditorCommand:t.symbolListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.SymbolList),r=this.getSourceInfoForSymbolOperation(n,a,0===s,e.sessionOpts);return r&&(e.mode=t.SymbolList,o.source=r,o.index=s,o.parsedInput=i,o.isValidated=!0),o}async getSuggestions(e){const s=[];if(e){this.inputInfo=e;const{query:i,hasSearchTerm:n}=e.parsedInputQuery,o=ye.create(i),r=e.parsedCommand(t.SymbolList);(await this.getItems(r.source,n)).forEach((e=>{let t=!0,i=null;if(n){const s=Ie.getSuggestionTextForSymbol(e);({match:i}=o.searchWithFallback(s)),t=!!i}if(t){const{file:t}=r.source;s.push({type:l.SymbolList,file:t,item:e,match:i})}})),n&&a.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,o=["qsp-suggestion-symbol"];Object.prototype.hasOwnProperty.call(i,"indentLevel")&&this.settings.symbolsInLineOrder&&!this.inputInfo?.parsedInputQuery?.hasSearchTerm&&o.push(`qsp-symbol-l${i.indentLevel}`),this.addClassesToSuggestionContainer(t,o);const{contentEl:r,titleEl:l}=fe.createContentStructureElements(t);Ie.renderSymbolContent(this.app,this.settings,l,i,n,a),this.renderHeadingBreadcrumbsInSymbolMode(r,i.symbol,n),this.addSymbolIndicator(i,t),s=!0}return s}onChooseSuggestion(e,t){return!!e&&(this.navigateAndCompleteSymbol(t,e),!0)}async navigateAndCompleteSymbol(e,s){const i=this.inputInfo.parsedCommand(),{leaf:n,file:a}=i.source,o=this.getOpenViewState(s),{item:r}=s;try{await this.navigateToLeafOrOpenFileAsync(e,a,o,n,t.SymbolList)}catch(e){return void A(`Unable to navigate to symbols for file ${a?.path}`,e)}if(Ie.isCanvasSymbolPayload(r))this.zoomToCanvasNode(this.getActiveLeaf().view,r.symbol);else if(Ie.isBaseViewSymbolPayload(r)){const e=r.symbol,t=s.file?.path,i=`${t}#${e.name}`;try{await this.app.workspace.openLinkText(i,t,!1)}catch(s){A(`Unable to navigate to Base view ${e.name} in file ${t}`,s)}}}reset(){this.inputInfo=null}getAvailableFacets(e){const i=e.parsedCommand(t.SymbolList),n=Ie.isBaseFile(i?.source?.file),a=Ie.isCanvasFile(i?.source?.file),o=this.getFacets(e.mode),r=new Set(Object.values($)),l=new Set(Object.values(j)),d=new Set(Object.values(s).filter((e=>isNaN(Number(e)))));return o.forEach((e=>{const{id:t}=e;e.isAvailable=n?r.has(t):a?l.has(t):d.has(t)})),o.filter((e=>e.isAvailable))}zoomToCanvasNode(e,t){if(Ie.isCanvasView(e)&&t){const s=e.canvas,i=s.nodes.get(t.id);s.selectOnly(i),s.zoomToSelection()}}getPreferredViewLinePosition(e){let t=super.getPreferredViewLinePosition();if(e?.item?.symbol){const{item:s}=e;if(!Ie.isCanvasSymbolPayload(s)&&!Ie.isBaseViewSymbolPayload(s)){t=s.symbol.position}}return t}getSourceInfoForSymbolOperation(e,s,i,n){const a=this.inputInfo;let o=null,r=t.Standard;a&&(o=a.parsedCommand().source,r=a.mode);const l=r===t.SymbolList&&!!o,d=this.getEditorInfo(s),c=this.getSuggestionInfo(e);let h=null;return l?h=o:c.isValidSource&&!n.useActiveEditorAsSource?h=c:d.isValidSource&&i&&(h=d),h}async getItems(e,t){let s=[],i=!1,n=!1;return t||({selectNearestHeading:n,symbolsInLineOrder:i}=this.settings),s=await this.getSymbolsFromSource(e,i),n&&Ie.FindNearestHeadingSymbol(s,e),s}static FindNearestHeadingSymbol(e,t){const s=t?.cursor?.line;if(s){let t=null;const i=e.filter((e=>S(e.symbol)));i.length&&(t=i.reduce(((e,t)=>{const{line:i}=t.symbol.position.start,n=e?e.symbol.position.start.line:-1;return e?i>n&&i<=s?t:e:i<=s?t:null}),null)),t&&(t.isSelected=!0)}}async getSymbolsFromSource(e,t){const{app:{metadataCache:i},inputInfo:n}=this,a=[];if(e?.file){const{file:o}=e,r=this.getActiveFacetIds(n);if(Ie.isBaseFile(o))await this.addBaseViewsFromSource(o,a,r);else if(Ie.isCanvasFile(o))await this.addCanvasSymbolsFromSource(o,a,r);else{const e=i.getFileCache(o);if(e){const i=(e=[],t)=>{this.shouldIncludeSymbol(t,r)&&e.forEach((e=>a.push({type:"symbolInfo",symbol:e,symbolType:t})))};i(e.headings,s.Heading),this.addTagsFromSource(e,a,r),this.addLinksFromSource(e,a,r),i(e.embeds,s.Embed),await this.addCalloutsFromSource(o,e.sections?.filter((e=>"callout"===e.type)),a,r),t&&Ie.orderSymbolsByLineNumber(a)}}}return a}shouldIncludeSymbol(e,t){let i=!1;return i="string"==typeof e?this.isFacetedWith(t,e):this.settings.isSymbolTypeEnabled(e)&&this.isFacetedWith(t,s[e]),i}async addCanvasSymbolsFromSource(e,t,i){let n;try{const t=await this.app.vault.cachedRead(e);n=JSON.parse(t).nodes}catch(t){O(`Error reading file to extract canvas node information. ${e.path} `,t)}Array.isArray(n)&&n.forEach((e=>{this.shouldIncludeSymbol(j[e.type],i)&&t.push({type:"symbolInfo",symbolType:s.CanvasNode,symbol:{...e}})}))}async addBaseViewsFromSource(e,t,i){let n;try{const t=await this.app.vault.cachedRead(e);n=a.parseYaml(t)}catch(t){return void O(`Error reading file to extract base view information. ${e.path} `,t)}n&&n?.views&&Array.isArray(n.views)&&n.views.forEach((e=>{const n=$[e.type];(n?this.shouldIncludeSymbol(n,i):0===i.size)&&t.push({type:"symbolInfo",symbolType:s.BaseView,symbol:{type:e.type,name:e.name}})}))}async addCalloutsFromSource(e,t,i,n){const{app:{vault:a}}=this;if(this.shouldIncludeSymbol(s.Callout,n)&&t?.length&&e){let n=null;try{n=await a.cachedRead(e)}catch(t){O(`Error reading file to extract callout information. ${e.path} `,t)}if(n)for(const e of t){const{start:t,end:a}=e.position,o=n.slice(t.offset,a.offset).match(/^> \[!([^\]]+)\][+-]?(.*?)(?:\n>|$)/);if(o){const t=o[1],n={calloutTitle:o[o.length-1].trim(),calloutType:t,...e};i.push({type:"symbolInfo",symbolType:s.Callout,symbol:n})}}}}addLinksFromSource(e,t,i){const{settings:n}=this;if(!this.shouldIncludeSymbol(s.Link,i))return;const a=e?.links??[],o=e?.frontmatterLinks??[],r=Ie.getFrontmatterPositionOrZero(e),l=[...a,...o.map((e=>{const t={link:e.link,original:e.original,position:r};return e.displayText&&(t.displayText=e.displayText),t}))];for(const e of l){const i=B(e);(n.excludeLinkSubTypes&i)===i||t.push({type:"symbolInfo",symbol:e,symbolType:s.Link})}}addTagsFromSource(e,t,i){if(!this.shouldIncludeSymbol(s.Tag,i))return;const n=new Set,a=e.tags??[];for(const e of a)n.add(e.tag.toLowerCase()),t.push({type:"symbolInfo",symbol:e,symbolType:s.Tag});const o=e.frontmatter;if(o){const i=h.getTags(o),a=Ie.getFrontmatterPositionOrZero(e);for(const e of i){const i=e.startsWith("#")?e:`#${e}`;if(n.has(i.toLowerCase()))continue;const o={tag:i,position:a};t.push({type:"symbolInfo",symbol:o,symbolType:s.Tag})}}}static orderSymbolsByLineNumber(e){const t=e.sort(((e,t)=>{const{start:s}=e.symbol.position,{start:i}=t.symbol.position,n=s.line-i.line;return 0===n?s.col-i.col:n}));let s=0;return t.forEach((e=>{let t=0;S(e.symbol)?(s=e.symbol.level,t=e.symbol.level-1):t=s,e.indentLevel=t})),t}static getMarkdownContentForSymbol(e,t){const{symbol:s}=e;if(S(s))return s.heading.replace(/^(\d+)\./,"$1\\.");if(k(s))return s.tag;if(v(s))return s.calloutTitle;const i=s;return i.original?i.original:null}static renderSymbolContent(e,t,s,i,n,o,r){const l=Ie.getMarkdownContentForSymbol(i,n);if((r??(null!==l&&t.shouldRenderSymbolAsHTML(i.symbolType)))&&null!==l)fe.renderMarkdownContentAsync(e,s,l,n.path);else{const e=Ie.getSuggestionTextForSymbol(i);a.renderResults(s,e,o)}}static getSuggestionTextForSymbol(e){const{symbol:t}=e;let s;if(S(t))s=t.heading;else if(k(t))s=t.tag.slice(1);else if(v(t))s=t.calloutTitle;else if(Ie.isCanvasSymbolPayload(e))s=Ie.getSuggestionTextForCanvasNode(e.symbol);else if(Ie.isBaseViewSymbolPayload(e))s=e.symbol.name;else{const e=t;({link:s}=e);const{displayText:i}=e;i&&i!==s&&(s+=`|${i}`)}return s}static getSuggestionTextForCanvasNode(e){let t="";const s={file:()=>e.file,text:()=>e.text,link:()=>e.url,group:()=>e.label}[e?.type];return s&&(t=s()),t}addSymbolIndicator(e,t){const{symbolType:s,symbol:i}=e,n=["qsp-symbol-indicator"],l=this.createFlairContainer(t);if(v(i)){n.push("suggestion-flair","callout","callout-icon","svg-icon");const e=l.createSpan({cls:n,attr:{"data-callout":i.calloutType}}),t=e.getCssPropertyValue("--callout-icon");a.setIcon(e,t)}else if(Ie.isCanvasSymbolPayload(e)){const t=we[e.symbol.type];this.renderIndicator(l,n,t,null)}else if(Ie.isBaseViewSymbolPayload(e)){const t=e.symbol,s=Ce[t.type]||Ce.table;this.renderIndicator(l,n,s,null)}else{let e;e=S(i)?r[i.level]:o[s],this.renderIndicator(l,n,null,e)}}renderHeadingBreadcrumbsInSymbolMode(e,t,s){S(t)&&this.renderHeadingBreadcrumbs(e,t,s,this.settings.showHeadingBreadcrumbsInSymbolMode)}static getFrontmatterPositionOrZero(e){return e.frontmatterPosition??{start:{line:0,col:0,offset:0},end:{line:0,col:0,offset:0}}}static isCanvasSymbolPayload(e){return e.symbolType===s.CanvasNode}static isBaseViewSymbolPayload(e){return e.symbolType===s.BaseView}static isCanvasFile(e){return"canvas"===e?.extension}static isCanvasView(e){return"canvas"===e?.getViewType()}static isBaseFile(e){return"base"===e?.extension}static isBaseView(e){return"bases"===e?.getViewType()}}class Le extends fe{getCommandString(e){return this.settings?.headingsListCommand}validateCommand(e,s,i,n,a){e.mode=t.HeadingsList;const o=e.parsedCommand(t.HeadingsList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}onChooseSuggestion(e,t){let s=!1;if(e){const i=this.getOpenViewState(e);this.navigateToLeafOrOpenFile(t,e.file,"Unable to navigate to heading for file.",i),s=!0}return s}getPreferredViewLinePosition(e){return e?.item?.position}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,{app:o,settings:l}=this;this.addClassesToSuggestionContainer(t,["qsp-suggestion-headings",`qsp-headings-l${i.level}`]);const{contentEl:d,titleEl:c}=fe.createContentStructureElements(t);Le.renderHeadingContent(o,l,c,i,n,a),this.renderHeadingBreadcrumbs(d,i,n),this.renderTags(d,n),this.renderPath(d,n);const h=this.createFlairContainer(t);this.renderOptionalIndicators(t,e,h),this.renderIndicator(h,["qsp-headings-indicator"],null,r[i.level]),e.downranked&&t.addClass("mod-downranked"),s=!0}return s}static renderHeadingContent(e,t,i,n,a,o,r){const l={type:"symbolInfo",symbol:n,symbolType:s.Heading};Ie.renderSymbolContent(e,t,i,l,a,o,r)}getAvailableFacets(e){const{settings:{shouldSearchHeadings:t,shouldSearchBookmarks:s,shouldSearchFilenames:i,shouldSearchRecentFiles:n,builtInSystemOptions:{showAttachments:a,showAllFileTypes:o}}}=this,r=a||o,l={[J.RecentFiles]:n,[J.Bookmarks]:s,[J.Filenames]:i,[J.Headings]:t,[J.ExternalFiles]:r};return this.getFacets(e.mode).filter((e=>(Object.prototype.hasOwnProperty.call(l,e.id)&&(e.isAvailable=l[e.id]),e.isAvailable)))}getSuggestions(e){let t=[];if(e){const{hasSearchTerm:s}=e.parsedInputQuery,{settings:i}=this,n=this.getActiveFacetIds(e),o=!!n.size;if(s||o){const{limit:s}=i,{app:{vault:o}}=this,r={headings:i.shouldSearchHeadings,allHeadings:i.searchAllHeadings,aliases:i.shouldShowAlias,bookmarks:i.shouldSearchBookmarks,filename:i.shouldSearchFilenames,filenameAsFallback:!i.strictHeadingsOnly,unresolved:!i.showExistingOnly};this.getItems([o.getRoot()],e,t,n,r),a.sortSearchResults(t),s>0&&t.length>s&&(t=t.slice(0,s))}else this.getSuggestionsForEditorsAndRecentFiles(e,t,new Set,{editors:!0,recentFiles:i.shouldSearchRecentFiles})}return t}getItems(e,t,s,i,n){const a=!!i.size,o=ye.create(t.parsedInputQuery.query);this.getSuggestionsForEditorsAndRecentFiles(t,s,i,{editors:!1,recentFiles:!1});const r={fileBookmarks:n.bookmarks,nonFileBookmarks:n.bookmarks};this.getSuggestionsForBookmarks(t,o,s,i,r);const l={headings:n.headings,allHeadings:n.allHeadings,aliases:n.aliases,filename:n.filename,filenameAsFallback:n.filenameAsFallback};this.getSuggestionForFiles(t,o,e,s,i,l),n.unresolved&&!a&&this.addUnresolvedSuggestions(s,o)}getSuggestionsForBookmarks(e,t,s,i,n){const a=!!i.size,{fileBookmarks:o,nonFileBookmarks:r}=e.currentWorkspaceEnvList;if(a){const e=i.has(J.Bookmarks);n=Object.assign(n,{fileBookmarks:e,nonFileBookmarks:e})}const l=i=>{for(const n of i)this.addBookmarkSuggestion(e,s,t,n)};n.fileBookmarks&&o.forEach((e=>{l(e)})),n.nonFileBookmarks&&l(r)}getSuggestionForFiles(e,t,s,i,n,a){if(!!n.size){const e=this.isFacetedWith(n,J.Headings),t=this.isFacetedWith(n,J.ExternalFiles)||this.isFacetedWith(n,J.Filenames);let s=!1,i=!1;e&&(s=!0===a.allHeadings,i=!0===a.filenameAsFallback),a=Object.assign(a,{headings:e,aliases:!1,filename:t,allHeadings:s,filenameAsFallback:i})}else a=Object.assign({headings:!0,allHeadings:!0,aliases:!0,filename:!0,filenameAsFallback:!0},a);if([a.headings,a.aliases,a.filename].some((e=>!0===e))){const{excludeFolders:o}=this.settings,r=M(o);let l=Array.prototype.concat(s);for(;l.length>0;){const s=l.pop();w(s)?this.shouldIncludeFile(s,n)&&this.addSuggestionsForFile(e,t,i,s,a):C(s)&&!r(s.path)&&(l=l.concat(s.children))}}}addSuggestionsForFile(e,t,s,i,n){let a=!1;n.headings&&(a=this.addHeadingSuggestions(e,t,s,i,n.allHeadings)),(n.filename||!a&&n.filenameAsFallback)&&this.addFileSuggestions(e,t,s,i),n.aliases&&this.addAliasSuggestions(e,t,s,i)}shouldIncludeFile(e,t=new Set){let s=!1;if(e){const i=new Set(["md","canvas"]),{extension:n}=e,{app:{viewRegistry:a,metadataCache:o},settings:{excludeObsidianIgnoredFiles:r,fileExtAllowList:l,builtInSystemOptions:{showAttachments:d,showAllFileTypes:c}}}=this;if(!(r&&o.isUserIgnored(e.path)))if(t.has(J.ExternalFiles)){const e=d||c;s=!i.has(n)&&e}else{s=this.isExternalFileTypeAllowed(e,a,d,c,l)||i.has(n)}}return s}isExternalFileTypeAllowed(e,t,s,i,n){const{extension:a}=e;let o=t.isExtensionRegistered(a)?s:i;if(!o){o=new Set(n).has(a)}return o}addAliasSuggestions(e,t,s,i){const{metadataCache:n}=this.app,a=n.getFileCache(i)?.frontmatter;if(a){const n=h.getAliases(a);let o=n.length;for(;o--;){const a=n[o],{match:r}=t.searchWithFallback(a);r&&s.push(this.createAliasSuggestion(e,a,i,r))}}}addFileSuggestions(e,t,s,i){const{match:n,matchType:a,matchText:o}=t.searchWithFallback(null,i);n&&s.push(this.createFileSuggestion(e,i,n,a,o))}addBookmarkSuggestion(e,t,s,i){const n=s.searchWithFallback(i.bookmarkPath);if(n.match){const s=ve.createSuggestion(e.currentWorkspaceEnvList,i,this.settings,this.app.metadataCache,n);t.push(s)}}addHeadingSuggestions(e,t,s,i,n){const{metadataCache:a}=this.app,o=a.getFileCache(i)?.headings??[];let r=null,l=!1,d=o.length;for(;d--;){const a=o[d];let c=!1;if(n&&(c=this.matchAndPushHeading(e,t,s,i,a)),1===a.level){const{line:e}=a.position.start;(null===r||e{this.addOpenEditorSuggestions(s,e,a,t)}))}if(i.recentFiles){const i=e.currentWorkspaceEnvList?.mostRecentFiles;i?.forEach((i=>{this.shouldIncludeFile(i,s)&&this.addRecentFilesSuggestions(i,e,a,t)}))}}onNoResultsCreateAction(e,s){const i=e.parsedCommand(t.HeadingsList)?.parsedInput;return this.createFile(i,s),!0}}class Te extends fe{static recentlyUsedCommandIds=[];getCommandString(e){return this.settings?.commandListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.CommandList);return this.getEnabledCommandPalettePluginInstance()&&(e.mode=t.CommandList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems(e,i).forEach((e=>{let s=!0,a=null;i&&(({match:a}=n.searchWithFallback(e.cmd.name)),s=!!a),s&&t.push(this.createSuggestion(e,a))})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;if(e){const{item:i,match:n,isPinned:a,isRecent:o}=e;this.addClassesToSuggestionContainer(t,["qsp-suggestion-command"]),this.renderContent(t,i.name,n);const r=this.createFlairContainer(t);this.renderHotkeyForCommand(i.id,this.app,r),i.icon&&this.renderIndicator(r,[],i.icon),a?this.renderIndicator(r,[],"filled-pin"):o&&this.renderOptionalIndicators(t,e,r),s=!0}return s}renderHotkeyForCommand(e,t,s){try{const{hotkeyManager:i}=t;if(i.getHotkeys(e)||i.getDefaultHotkeys(e)){const t=i.printHotkeyForCommand(e);t?.length&&s.createEl("kbd",{cls:"suggestion-hotkey",text:t})}}catch(t){O("Error rendering hotkey for command id: ",e,t)}}onChooseSuggestion(e){let t=!1;if(e){const{item:s}=e;this.app.commands.executeCommandById(s.id),this.saveUsageToList(s.id,Te.recentlyUsedCommandIds),t=!0}return t}saveUsageToList(e,t){if(t){const s=t.indexOf(e);s>-1&&t.splice(s,1),t.unshift(e),t.splice(this.settings.maxRecentCommands)}}getItems(e,t){let s=[];const i=this.getActiveFacetIds(e);if(!!i.size)s=this.getPinnedAndRecentCommands(i);else if(t)s=this.getAllCommands();else{const e=this.getPinnedAndRecentCommands(i);s=e.length?e:this.getAllCommands()}return s}getPinnedAndRecentCommands(e){const t=[],s=this.getPinnedCommandIds(),i=this.getRecentCommandIds(),n=e=>{let t=null;const n=this.app.commands.findCommand(e);return n&&(t={isPinned:s.has(e),isRecent:i.has(e),cmd:n}),t},a=(s,i)=>{this.isFacetedWith(e,s)&&i.forEach((e=>{const s=n(e);s&&t.push(s)}))};a(z.Pinned,Array.from(s));const o=this.isFacetedWith(e,z.Pinned),r=Array.from(i).filter((e=>!o||o&&!s.has(e)));return"asc"===this.settings.recentCommandDisplayOrder&&r.reverse(),a(z.Recent,r),t}getAllCommands(){const e=this.getPinnedCommandIds(),t=this.getRecentCommandIds();return this.app.commands.listCommands()?.sort(((e,t)=>e.name.localeCompare(t.name))).map((s=>({isPinned:e.has(s.id),isRecent:t.has(s.id),cmd:s})))}getPinnedCommandIds(){const e=this.getEnabledCommandPalettePluginInstance()?.options?.pinned;return new Set(e??[])}getRecentCommandIds(){return new Set(Te.recentlyUsedCommandIds)}createSuggestion(e,t){const{cmd:s,isPinned:i,isRecent:n}=e,a={type:l.CommandList,item:s,isPinned:i,isRecent:n,match:t};return this.applyMatchPriorityPreferences(a)}getEnabledCommandPalettePluginInstance(){return Te.getEnabledCommandPalettePluginInstance(this.app)}static getEnabledCommandPalettePluginInstance(e){return I(e,"command-palette")}}class Ee extends fe{inputInfo;getCommandString(e){const{settings:t}=this;return e?.useActiveEditorAsSource?t.relatedItemsListActiveEditorCommand:t.relatedItemsListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.RelatedItemsList),r=this.getSourceInfo(n,a,0===s,e.sessionOpts);return r&&(e.mode=t.RelatedItemsList,o.source=r,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const s=[];if(e){this.inputInfo=e;const i=ye.create(e.parsedInputQuery.query),n=e.parsedCommand(t.RelatedItemsList);this.getItems(n.source,e).forEach((t=>{const n=this.searchAndCreateSuggestion(e,i,t);n&&s.push(n)})),i.hasSearchTerm&&a.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a,item:o}=e,r=new Map([[c.Backlink,"links-coming-in"],[c.DiskLocation,"folder-tree"],[c.OutgoingLink,"links-going-out"]]);t.setAttribute("data-relation-type",o.relationType),this.renderAsFileInfoPanel(t,["qsp-suggestion-related"],e.preferredTitle,i,n,a);const l=this.renderOptionalIndicators(t,e);e.item.count&&this.renderIndicator(l,[],null,`${e.item.count}`),this.renderIndicator(l,["qsp-related-indicator"],r.get(o.relationType)),s=!0}return s}onChooseSuggestion(e,t){let s=!1;if(e){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open related file ${i.path}`),s=!0}return s}getPreferredTitle(e,t){let s=null;const{file:i,unresolvedText:n}=e;if(i){if("H1"===t)s=this.getFirstH1(i)?.heading??null;else if("FrontMatter"===t){const e=this.app.metadataCache.getFileCache(i)?.frontmatter;s=fe.getFrontmatterProperty(e,this.settings.frontmatterTitleProperty)}}else{!!n?.length&&(s=n)}return s}searchAndCreateSuggestion(e,t,s){const{file:i,unresolvedText:n}=s;let a={matchType:d.None,match:null};const o=null===i&&n?.length,{currentWorkspaceEnvList:r}=e,{settings:l,app:{metadataCache:c}}=this,h=this.getPreferredTitle(s,l.preferredSourceForTitle);return t.hasSearchTerm&&(a=t.searchWithFallback(h,i),a.matchType===d.None)?null:o?Se.createUnresolvedSuggestion(h,a,l,c):this.createSuggestion(r,s,a,h)}getItems(e,t){const s=[],{metadataCache:i}=this.app,{file:n,suggestion:a}=e,o=new Set(this.settings.enabledRelatedItems),r=this.getActiveFacetIds(t),l=e=>o.has(e)&&this.isFacetedWith(r,e);if(l(c.Backlink)){let e=n?.path,t=i.resolvedLinks;y(a)&&(e=a.linktext,t=i.unresolvedLinks),this.addBacklinks(e,t,s)}return l(c.DiskLocation)&&this.addRelatedDiskFiles(n,s),l(c.OutgoingLink)&&this.addOutgoingLinks(n,s),s}addRelatedDiskFiles(e,t){const{excludeRelatedFolders:s,excludeOpenRelatedFiles:i}=this.settings;if(e){const n=M(s);let a=[...e.parent.children];for(;a.length>0;){const s=a.pop();if(w(s)){s===e||i&&!!this.findMatchingLeaf(s).leaf||t.push({file:s,relationType:c.DiskLocation})}else C(s)&&!n(s.path)&&(a=a.concat(s.children))}}}addOutgoingLinks(e,t){if(!e)return;const{metadataCache:s}=this.app,i=e.path,n=s.resolvedLinks[i]??{};for(const[e,a]of Object.entries(n)){if(e===i)continue;const n=s.getFirstLinkpathDest(e,i);n&&t.push({file:n,relationType:c.OutgoingLink,count:a})}const a=s.unresolvedLinks[i]??{};for(const[e,s]of Object.entries(a))t.push({file:null,relationType:c.OutgoingLink,unresolvedText:e,count:s})}addBacklinks(e,t,s){for(const[i,n]of Object.entries(t))if(i!==e&&Object.prototype.hasOwnProperty.call(n,e)){const t=n[e],a=this.getTFileByPath(i);a&&s.push({count:t,file:a,relationType:c.Backlink})}}reset(){this.inputInfo=null}getSourceInfo(e,s,i,n){const a=this.inputInfo;let o=null,r=t.Standard;a&&(o=a.parsedCommand().source,r=a.mode);const l=r===t.RelatedItemsList&&!!o,d=this.getEditorInfo(s),c=this.getSuggestionInfo(e);!c.isValidSource&&y(e)&&(c.isValidSource=!0);let h=null;return l?h=o:c.isValidSource&&!n.useActiveEditorAsSource?h=c:d.isValidSource&&i&&(h=d),h}createSuggestion(e,t,s,i){let n={item:t,file:t?.file,type:l.RelatedItemsList,preferredTitle:i,...s};return n=fe.updateWorkspaceEnvListStatus(e,n),this.applyMatchPriorityPreferences(n)}}class Fe extends fe{mobileVaultChooserMarker={type:l.VaultList,match:null,item:null,pathSegments:null};getCommandString(e){return this.settings?.vaultListCommand}validateCommand(e,s,i,n,a){e.mode=t.VaultList;const o=e.parsedCommand(t.VaultList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((e=>{let s=!0;if(i){const t=n.searchWithFallback(null,e.pathSegments);Object.assign(e,t),s=!!t.match}s&&t.push(e)})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;return e&&(this.addClassesToSuggestionContainer(t,["qsp-suggestion-vault"]),s=!0,a.Platform.isDesktop?this.renderVaultSuggestion(e,t):e===this.mobileVaultChooserMarker&&this.renderMobileHintSuggestion(t)),s}renderMobileHintSuggestion(e){this.renderContent(e,"Show mobile vault chooser",null)}renderVaultSuggestion(e,t){const{pathSegments:s,matchType:i}=e;let{match:n}=e,o=null;i===d.Basename&&(o=n,n=null);const r=this.renderContent(t,s.basename,o).createDiv({cls:["suggestion-note","qsp-note"]}),l=r.createSpan({cls:["qsp-path-indicator"]}),c=r.createSpan({cls:"qsp-path"});a.setIcon(l,"folder"),a.renderResults(c,s.path,n)}onChooseSuggestion(e,t){let s=!1;return e&&(a.Platform.isDesktop?(this.openVaultOnDesktop(e.pathSegments?.path),s=!0):e===this.mobileVaultChooserMarker&&(this.app.openVaultChooser(),s=!0)),s}getItems(){const e=[];if(a.Platform.isDesktop)try{const t=this.getVaultListDataOnDesktop();for(const[s,{path:i,open:n}]of Object.entries(t)){const t=x(i),a={type:l.VaultList,match:null,item:s,isOpen:!!n,pathSegments:{basename:t,path:i}};e.push(a)}}catch(e){O("Error parsing vault data. ",e)}else e.push(this.mobileVaultChooserMarker);return e.sort(((e,t)=>e.pathSegments.basename.localeCompare(t.pathSegments.basename)))}getIpcRenderer(){if(!a.Platform.isDesktop)return null;try{return window.require("electron").ipcRenderer}catch{return null}}openVaultOnDesktop(e){const t=this.getIpcRenderer();if(t)try{t.sendSync("vault-open",e,!1)}catch(t){A(`Error opening vault with path: ${e} `,t)}}getVaultListDataOnDesktop(){let e=null;const t=this.getIpcRenderer();if(t)try{e=t.sendSync("vault-list")}catch(e){A("Error retrieving list of available vaults.",e)}return e}}class xe{app;config;static instance;instanceCache=new Map;modeToHandlerClass=new Map;suggestionTypeToMode=new Map;cmdStrToMode=new Map;sourcedHandlerModes=new Set;constructor(e,t,s){this.app=e,this.config=t;for(const e of s)e.handlerClass&&(this.modeToHandlerClass.set(e.mode,e.handlerClass),this.mapSuggestionTypesToMode(e),this.mapCommandStrToMode(e),this.registerSourcedHandler(e))}static initialize(e,t,s){this.instance?P("HandlerRegistry already initialized."):this.instance=new xe(e,t,s)}static reset(){this.instance=null}static getInstance(){return this.instance??null}getHandler(e){let t=null;const s=this.resolveMode(e);if(s)if(this.instanceCache.has(s))t=this.instanceCache.get(s)??null;else{const e=this.modeToHandlerClass.get(s);if(e){const i=new e(this.app,this.config);this.instanceCache.set(s,i),t=i}}return t}resetSourcedHandlers(e){const t=new Set(e);for(const e of this.sourcedHandlerModes){const s=this.instanceCache.get(e);s&&!t.has(s)&&s.reset()}}mapSuggestionTypesToMode(e){e.ownSuggestionTypes?.forEach((t=>{this.suggestionTypeToMode.set(t,e.mode)}))}mapCommandStrToMode(e){const t=e.parserCommand?.getCommandStr();t?.length&&this.cmdStrToMode.set(t,e.mode)}registerSourcedHandler(e){"sourced"===e.parserCommand?.type&&this.sourcedHandlerModes.add(e.mode)}resolveMode(e){let s;return"number"==typeof e&&Object.values(t).includes(e)?s=e:m(e,"type")?s=this.suggestionTypeToMode.get(e.type):"string"==typeof e&&(s=this.cmdStrToMode.get(e)),s}}class Ae{commandMap=new Map;escapeCmdChar;handlerRegistry;constructor(e,t,s){this.handlerRegistry=e,this.escapeCmdChar=t.escapeCmdChar,this.commandMap=this.buildCommandMap(s)}parseInputForMode(e,s,i){const{cleanInput:n,resolvedCommands:a}=this.parse(e.inputText);e.cleanInput=n;this.findFirstValidCommand(a,e,s,i)||(this.handlerRegistry.resetSourcedHandlers(),e.mode=t.Standard)}parse(e){let t="";const s=[],i=this.escapeCmdChar.length;let n=0;for(;n0){const i=e[0];t.has(i)||t.set(i,[]),t.get(i)?.push({cmdDef:s,cmdStr:e})}}for(const e of t.values())e.sort(((e,t)=>t.cmdStr.length-e.cmdStr.length));return t}findCommandMatch(e,t){const s=this.commandMap.get(e[t]);if(!s)return null;for(const i of s)if(e.startsWith(i.cmdStr,t))return i;return null}resolveCommandPrecedence(e,t){const s=[];let i;for(const n of e){const e=n.indexInCleanInput+n.cmdStr.length,a=t.substring(e),o={cmdDef:n.cmdDef,cmdStr:n.cmdStr,indexInCleanInput:n.indexInCleanInput,filterText:a},r=n.cmdDef.parserCommand.type;"prefix"!==r||0!==n.indexInCleanInput||i?"sourced"===r&&s.push(o):i=o}return s.sort(((e,t)=>e.indexInCleanInput-t.indexInCleanInput)),i?[...s,i]:s}findFirstValidCommand(e,t,s,i){for(const n of e){const e=this.handlerRegistry.getHandler(n.cmdDef.mode);if(!e)continue;t.sessionOpts.useActiveEditorAsSource=n.cmdDef.parserCommand.useActiveEditorAsSource;if(e.validateCommand(t,n.indexInCleanInput,n.filterText,s,i).isValidated){const t="sourced"===n.cmdDef.parserCommand.type?[e]:[];return this.handlerRegistry.resetSourcedHandlers(t),!0}}return!1}}const Oe={};class Pe{app;settings;exKeymap;_inputInfo;get inputInfo(){return this._inputInfo}get previousInputHistory(){return Oe}_handlerRegistry;get handlerRegistry(){return this._handlerRegistry}_inputParser;get inputParser(){return this._inputParser}debouncedGetSuggestions;workspaceEnvList=null;sessionOpts={};noResultActionModes=[t.HeadingsList,t.WorkspaceList];constructor(e,s,i){this.app=e,this.settings=s,this.exKeymap=i;const n=(o=s,[{commandId:"switcher-plus:open",commandName:"Open in Standard Mode",mode:t.Standard,iconId:"lucide-file-search",handlerClass:Se,ownSuggestionTypes:[l.Alias,l.File],parserCommand:{type:"none",getCommandStr:()=>""}},{commandId:"switcher-plus:open-editors",commandName:"Open in Editor Mode",mode:t.EditorList,iconId:"lucide-file-edit",handlerClass:ke,ownSuggestionTypes:[l.EditorList],parserCommand:{type:"prefix",getCommandStr:()=>o.editorListCommand}},{commandId:"switcher-plus:open-symbols",commandName:"Open Symbols for selected suggestion or editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",handlerClass:Ie,ownSuggestionTypes:[l.SymbolList],parserCommand:{type:"sourced",getCommandStr:()=>o.symbolListCommand}},{commandId:"switcher-plus:open-symbols-active",commandName:"Open Symbols for the active editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",handlerClass:Ie,parserCommand:{type:"prefix",getCommandStr:()=>o.symbolListActiveEditorCommand,useActiveEditorAsSource:!0}},{commandId:"switcher-plus:open-workspaces",commandName:"Open in Workspaces Mode",mode:t.WorkspaceList,iconId:"lucide-album",handlerClass:be,ownSuggestionTypes:[l.WorkspaceList],parserCommand:{type:"prefix",getCommandStr:()=>o.workspaceListCommand}},{commandId:"switcher-plus:open-headings",commandName:"Open in Headings Mode",mode:t.HeadingsList,iconId:"lucide-file-search",handlerClass:Le,ownSuggestionTypes:[l.HeadingsList],parserCommand:{type:"prefix",getCommandStr:()=>o.headingsListCommand}},{commandId:"switcher-plus:open-starred",commandName:"Open in Bookmarks Mode",mode:t.BookmarksList,iconId:"lucide-bookmark",handlerClass:ve,ownSuggestionTypes:[l.Bookmark],parserCommand:{type:"prefix",getCommandStr:()=>o.bookmarksListCommand}},{commandId:"switcher-plus:open-commands",commandName:"Open in Commands Mode",mode:t.CommandList,iconId:"run-command",handlerClass:Te,ownSuggestionTypes:[l.CommandList],parserCommand:{type:"prefix",getCommandStr:()=>o.commandListCommand}},{commandId:"switcher-plus:open-related-items",commandName:"Open Related Items for selected suggestion or editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",handlerClass:Ee,ownSuggestionTypes:[l.RelatedItemsList],parserCommand:{type:"sourced",getCommandStr:()=>o.relatedItemsListCommand}},{commandId:"switcher-plus:open-related-items-active",commandName:"Open Related Items for the active editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",handlerClass:Ee,parserCommand:{type:"prefix",getCommandStr:()=>o.relatedItemsListActiveEditorCommand,useActiveEditorAsSource:!0}},{commandId:"switcher-plus:open-vaults",commandName:"Open in Vaults Mode",mode:t.VaultList,iconId:"vault",handlerClass:Fe,ownSuggestionTypes:[l.VaultList],parserCommand:{type:"prefix",getCommandStr:()=>o.vaultListCommand}}]);var o;xe.getInstance()||xe.initialize(e,s,n),this._handlerRegistry=xe.getInstance(),this._inputParser=new Ae(this._handlerRegistry,s,n),this.debouncedGetSuggestions=a.debounce(this.getSuggestions.bind(this),s.headingsSearchDebounceMilli,!0),this.reset()}onOpen(){const{app:e,exKeymap:t,handlerRegistry:s,settings:i}=this;t.isOpen=!0,i.quickFilters?.shouldResetActiveFacets&&Object.values(i.quickFilters.facetList).forEach((e=>e.isActive=!1)),this.workspaceEnvList=this.buildWorkspaceEnvList(e.workspace,e.vault,e.viewRegistry,s,i)}onClose(){this.exKeymap.isOpen=!1,q.unload()}setSessionOpenMode(e,t){this.reset(),e?.setSuggestions([]),this.sessionOpts=Object.assign({},t)}setInitialInputForSession(e){const{mode:s}=this.sessionOpts;if(!s)return;this.sessionOpts.mode=null;const i=s===t.Standard?this.previousInputHistory[s]?.inputText:this.previousInputHistory[s]?.parsedCommand(s)?.parsedInput,n=this.handlerRegistry.getHandler(s),a=s!==t.Standard?n.getCommandString(this.sessionOpts):"";if((s===t.CommandList&&this.settings.preserveCommandPaletteLastInput||s!==t.CommandList&&this.settings.preserveQuickSwitcherLastInput)&&i?.length){e.value=a+i;const t=a?.length??0;e.setSelectionRange(t,e.value.length)}else a&&(e.value=a)}updateSuggestions(e,s,i){const{exKeymap:n,settings:a,sessionOpts:o}=this;let r=!1;this.debouncedGetSuggestions.cancel();const l=fe.getActiveLeaf(this.app.workspace),d=Pe.getActiveSuggestion(s),c=this.determineRunMode(e,d,l,o);this._inputInfo=c;const{mode:h}=c;return this.previousInputHistory[h]=c,this.updatedKeymapForMode(c,s,i,n,a,l),this.toggleMobileCreateFileButton(i,h,a),h!==t.Standard&&(h===t.HeadingsList&&c.parsedCommand().parsedInput?.length?this.debouncedGetSuggestions(c,s,i):this.getSuggestions(c,s,i),r=!0),r}toggleMobileCreateFileButton(e,s,i){if(!a.Platform.isMobile)return;const n=t[s];e.allowCreateNewFile=i.allowCreateNewFileInModeNames.includes(n),e.allowCreateNewFile||e.createButtonEl?.detach()}updatedKeymapForMode(e,t,s,i,n,a){const{mode:o}=e,r=this.handlerRegistry.getHandler(o),l=r?.getAvailableFacets(e)??[],d={mode:o,activeLeaf:a,facets:{facetList:l,facetSettings:n.quickFilters,onToggleFacet:((o,l)=>{if(l){const e=o.some((e=>!0===e.isActive));r.activateFacet(o,!e)}else r.activateFacet(o,!o[0].isActive);return this.updatedKeymapForMode(e,t,s,i,n,a),this.getSuggestions(e,t,s),!1}).bind(this)}};i.updateKeymapForMode(d)}renderSuggestion(e,s){const{handlerRegistry:i,inputInfo:n,settings:{overrideStandardModeRendering:a}}=this,{mode:o}=n,r=o===t.HeadingsList;let d=!1;const c=new Set([l.Unresolved]);if(null===e){if(r){const e=i.getHandler(o),t=n.parsedCommand(o)?.parsedInput;e.renderFileCreationSuggestion(s,t),d=!0}}else if(!c.has(e.type)&&(a||r||b(e))){const t=i.getHandler(e);t&&(d=t.renderSuggestion(e,s))}return d}onChooseSuggestion(e,s){const{handlerRegistry:i,inputInfo:n,settings:{overrideStandardModeBehaviors:a}}=this,{mode:o}=n,r=o===t.HeadingsList;let d=!1;const c=new Set([l.Unresolved]);if(null===e){if(this.noResultActionModes.includes(o)){const e=i.getHandler(o);d=!!e?.onNoResultsCreateAction(n,s)}}else if(!c.has(e.type)&&(a||r||b(e))){const t=i.getHandler(e);t&&(d=t.onChooseSuggestion(e,s))}return d}determineRunMode(e,s,i,n){const a=e??"",o=new pe(a,t.Standard,n);return 0===a.length?(this.reset(),o):(o.currentWorkspaceEnvList=this.workspaceEnvList,this.inputParser.parseInputForMode(o,s,i),o)}getSuggestions(e,t,s){t.setSuggestions([]);const{mode:i}=e,n=this.handlerRegistry.getHandler(i).getSuggestions(e),a=n=>{n?.length?(t.setSuggestions(n),Pe.setActiveSuggestion(i,t),this.exKeymap?.renderQuickOpenFlairIcons(t.suggestions,this.settings)):this.noResultActionModes.includes(i)&&e.parsedCommand(i).parsedInput?s.onNoSuggestion():t.setSuggestions(null)};Array.isArray(n)?a(n):n.then((e=>{a(e)}),(e=>{A("Error retrieving suggestions as Promise. ",e)}))}static setActiveSuggestion(e,s){if(e===t.SymbolList){const e=s.values.filter((e=>u(e))).findIndex((e=>e.item.isSelected));-1!==e&&(s.setSelectedItem(e,null),s.suggestions[s.selectedItem].scrollIntoView(!1))}}static getActiveSuggestion(e){let t=null;return e?.values&&(t=e.values[e.selectedItem]),t}reset(){this._inputInfo=new pe,this.sessionOpts={},this.handlerRegistry.resetSourcedHandlers()}buildWorkspaceEnvList(e,s,i,n,a){const o=n.getHandler(t.EditorList).getItems(),r=o.reduce(((e,t)=>{const s=H(t);return s&&e.add(s),e}),new Set),{fileBookmarks:l,nonFileBookmarks:d}=n.getHandler(t.BookmarksList).getItems(null),c=this.getAttachmentFileExtensions(i,a.fileExtAllowList),h=r.size+a.maxRecentFileSuggestionsOnInit,m=this.getRecentFiles(e,s,r,h);return{openWorkspaceLeaves:new Set(o),openWorkspaceFiles:r,fileBookmarks:l,nonFileBookmarks:d,attachmentFileExtensions:c,mostRecentFiles:m}}getAttachmentFileExtensions(e,t){const s=new Set;try{const i=new Set(["md","canvas",...t]);Object.keys(e.typeByExtension).reduce(((e,t)=>(i.has(t)||e.add(t),e)),s)}catch(e){O("Error retrieving attachment list from ViewRegistry",e)}return s}getRecentFiles(e,t,s,i=75){s=s??new Set;const n=new Set;if(i>0){const a=e.getRecentFiles({showMarkdown:!0,showCanvas:!0,showNonImageAttachments:!0,showImages:!0,maxCount:i});a?.forEach((e=>{const i=t.getAbstractFileByPath(e);w(i)&&!s.has(i)&&n.add(i)}))}return n}inputTextForStandardMode(e){const{mode:s,cleanInput:i}=this.inputInfo;let n=e;return s===t.Standard&&i?.length&&(n=i),n}inputTextForFulltextSearch(){const{inputInfo:e}=this,s=e.mode;let i=null,n=e.cleanInput;if(s!==t.Standard){const t=e.parsedCommand();n=t.parsedInput,F().includes(s)&&(i=t.source?.file)}return{mode:s,parsedInput:n,file:i}}addPropertiesToStandardSuggestions(e,s){if(!e||!s.overrideStandardModeBehaviors&&!s.overrideStandardModeRendering)return;const{handlerRegistry:i,inputInfo:{currentWorkspaceEnvList:n}}=this;for(let s=0;s{A(`Error opening file (${i?.path}) in background. `,e)}))}}const Me={Enter:"↵",Backspace:"⌫",ArrowLeft:"←",ArrowUp:"↑",ArrowDown:"↓",ArrowRight:"→",Tab:"↹"},Be={...Me,Mod:"Ctrl",Ctrl:"Ctrl",Meta:"Win",Alt:"Alt",Shift:"Shift"},Re={...Me,Mod:"⌘",Ctrl:"⌃",Meta:"⌘",Alt:"⌥",Shift:"⇧"},He=[t.EditorList,t.HeadingsList,t.RelatedItemsList,t.BookmarksList,t.SymbolList],De=[t.CommandList,t.VaultList,t.WorkspaceList,...He];class Ve{app;scope;chooser;modal;config;standardKeysInfo=[];customKeysInfo=[];savedStandardKeysInfo=[];_isOpen;customInstructionEls=new Map;standardInstructionsEl;facetKeysInfo=[];insertIntoEditorKeysInfo=[];get isOpen(){return this._isOpen}set isOpen(e){this._isOpen=e}static get modKey(){return a.Platform.isMacOS?"Meta":"Ctrl"}static get keyDisplayStr(){return a.Platform.isMacOS?Re:Be}get exModeHandler(){return this.modal?.exMode}constructor(e,t,s,i,n){this.app=e,this.scope=t,this.chooser=s,this.modal=i,this.config=n,this.initKeysInfo(n,t),this.renderModeTriggerInstructions(i.modalEl,n),this.standardInstructionsEl=i.modalEl.find(".prompt-instructions")}initKeysInfo(e,t){this.standardKeysInfo.push(),this.addCustomKeymaps(this.config),this.removeDefaultTabKeyBinding(t,e),this.registerNavigationBindings(t,e.navigationKeys),this.registerEditorTabBindings(t),this.registerCloseWhenEmptyBindings(t,e),this.registerQuickOpenBindings(t,e),this.registerFulltextSearchBindings(t,e),this.registerOpenInBackgroundBindings(t,e)}removeDefaultTabKeyBinding(e,t){if(t?.removeDefaultTabBinding){const t=e.keys.find((({modifiers:e,key:t})=>null===e&&"Tab"===t));e.unregister(t)}}registerNavigationBindings(e,t){const s=(t,s)=>{t.forEach((({modifiers:t,key:i})=>{e.register(t,i,((e,t)=>(this.navigateItems(e,s),!1)))}))};s(t?.nextKeys??[],!0),s(t?.prevKeys??[],!1)}registerFacetBinding(e,s){const{mode:i,facets:n}=s;if(n?.facetList?.length){const{facetList:s,facetSettings:a,onToggleFacet:o}=n,{keyList:r,modifiers:l,resetKey:d,resetModifiers:c}=a;let h=0;const m=(t,s,i,n)=>e.register(t,s,(()=>o(i,n)));for(let e=0;e{e.register(t[0],t[1],this.useSelectedItem.bind(this))}))}registerCloseWhenEmptyBindings(e,t){const s=t.closeWhenEmptyKeys;s?.forEach((({modifiers:t,key:s})=>{e.register(t,s,this.closeModalIfEmpty.bind(this))}))}registerQuickOpenBindings(e,t){const{isEnabled:s,modifiers:i,keyList:n}=t.quickOpen;s&&n?.forEach((t=>{e.register(i,t,this.quickOpenByIndex.bind(this))}))}quickOpenByIndex(e,t){const s=this.config.quickOpen.keyList.indexOf(t.vkey);if(-1!==s){const{chooser:i}=this;i.values.length>s&&(i.setSelectedItem(s,e),this.useSelectedItem(e,t))}return!1}registerFulltextSearchBindings(e,t){const{isEnabled:s,searchKeys:i}=t.fulltextSearch;if(s){T(this.app)&&e.register(i.modifiers,i.key,this.LaunchSystemGlobalSearch.bind(this))}}LaunchSystemGlobalSearch(e,t){const{parsedInput:s,file:i}=this.modal.exMode.inputTextForFulltextSearch();let n="";return i&&(n=`path:"${i.path}" `),this.modal.close(),T(this.app)?.openGlobalSearch(`${n}${s}`),!1}registerOpenInBackgroundBindings(e,t){const{openInBackground:{isEnabled:s,openKeys:i}}=t;if(s){const t={tab:"open in background tab",vertical:"open in background to the right",horizontal:"open in background below",window:"open in background window"};i?.filter((e=>e.hotkey)).forEach((({openType:s,hotkey:i})=>{e.register(i.modifiers,i.key,(()=>this.openInBackground(this.chooser,s))),this.createCustomKeymap(t[s],De,i,null,!0,!0)}))}}openInBackground(e,t){let s,i="vertical";"vertical"===t||"horizontal"===t?(s="split",i=t):s=t;const n=e?.values?.[e.selectedItem];return this.exModeHandler.openSuggestionInBackground(n,s,i),!1}renderQuickOpenFlairIcons(e,t){const{isEnabled:s,modifiers:i,keyList:n}=t.quickOpen;if(s)for(let t=0;te.purpose===o.purpose)),!a){const{modifiers:e,key:t,purpose:s}=o;a={isInstructionOnly:!1,command:Ve.commandDisplayStr(e,t),modifiers:e,key:t,purpose:s},i.push(a)}a.eventListener=()=>{const{modal:e,chooser:t}=this;e.close();const i=t.values?.[t.selectedItem];return this.insertIntoEditorAsLink(i,s,n),!1},a.modes=[e]}}return a}updateKeymapForMode(e){const{mode:s,activeLeaf:i}=e,{modal:n,scope:a,customKeysInfo:o,facetKeysInfo:r,standardKeysInfo:l,savedStandardKeysInfo:d,config:{insertLinkInEditor:c,showModeTriggerInstructions:h}}=this;this.updateInsertIntoEditorCommand(s,i,o,c);const m=o.filter((e=>!e.isInstructionOnly));this.unregisterKeys(a,m),this.unregisterKeys(a,r),r.length=0;const u=m.filter((e=>e.modes?.includes(s)));s===t.Standard?this.updateKeymapForStandardMode(a,u,d):this.updateKeymapForCustomModes(a,u,l,e,n),this.showModeTriggerInstructions(n.modalEl,h)}updateKeymapForStandardMode(e,t,s){const i=s.map((([e,t])=>({eventListener:t.func,...e})));this.registerKeys(e,i),s.length=0,this.registerKeys(e,t),this.toggleStandardInstructions(!0)}updateKeymapForCustomModes(e,t,s,i,n){const{savedStandardKeysInfo:a,customKeysInfo:o,facetKeysInfo:r}=this,l=this.unregisterKeys(e,s);l.length&&a.push(...l),this.registerKeys(e,t),this.registerFacetBinding(e,i),this.showCustomInstructions(n,i,o,r)}registerKeys(e,t){t.forEach((({modifiers:t,key:s,eventListener:i})=>{e.register(t,s,i)}))}unregisterKeys(e,t){const s=[],i={};t.map((e=>{const{key:t,modifiers:s}=e,n=Ve.modifiersToKeymapInfoStr(s),a=i[t];a?a[n]=e:i[t]={[n]:e}}));let n=e.keys.length;for(;n--;){const t=e.keys[n],a=i[t.key],o=a?.[t.modifiers];o&&(e.unregister(t),s.push([o,t]))}return s}detachCustomInstructionEls(){this.customInstructionEls.forEach((e=>{e.detach()}))}toggleStandardInstructions(e){const{standardInstructionsEl:t}=this;let s="none";e&&(s="",this.detachCustomInstructionEls()),t&&(t.style.display=s)}showCustomInstructions(e,t,s,i){const{mode:n,facets:a}=t,{modalEl:o}=e,r=s.filter((e=>e.modes?.includes(n)));this.toggleStandardInstructions(!1),this.renderCustomInstructions(o,r),this.renderFacetInstructions(o,a?.facetSettings,i)}renderFacetInstructions(e,t,s){if(s?.length&&t.shouldShowFacetInstructions){const i=this.getCustomInstructionsEl("facets",e);i.empty(),e.appendChild(i);const n=`filters | ${Ve.commandDisplayStr(t.modifiers)}`;this.createPromptInstructionCommandEl(i,n),s.forEach((e=>{const{facet:s,command:n,purpose:a}=e;let o,r,l=null;s?(r=n,o=s.modifiers,s.isActive&&(l=["qsp-filter-active"])):(r=t.resetKey,o=t.resetModifiers);const d=o?`(${Ve.commandDisplayStr(o)}) ${r}`:`${r}`;this.createPromptInstructionCommandEl(i,d,a,[],l)}))}}renderCustomInstructions(e,t){const s=this.getCustomInstructionsEl("custom",e);s.empty(),e.appendChild(s),t.forEach((e=>{this.createPromptInstructionCommandEl(s,e.command,e.purpose)}))}showModeTriggerInstructions(e,t){if(t){const t=this.customInstructionEls.get("modes");t&&e.appendChild(t)}}renderModeTriggerInstructions(e,t){const s=new Map([[t.headingsListCommand,"heading list"],[t.editorListCommand,"editor list"],[t.bookmarksListCommand,"bookmark list"],[t.commandListCommand,"command list"],[t.workspaceListCommand,"workspace list"],[t.vaultListCommand,"vault list"],[t.symbolListActiveEditorCommand,"symbol list (active editor)"],[t.symbolListCommand,"symbol list (embedded)"],[t.relatedItemsListActiveEditorCommand,"related items (active editor)"],[t.relatedItemsListCommand,"related items (embedded)"]]),i=this.getCustomInstructionsEl("modes",e);i.detach(),i.empty(),this.createPromptInstructionCommandEl(i,"mode triggers |"),s.forEach(((e,t)=>{this.createPromptInstructionCommandEl(i,t,e)}))}getCustomInstructionsEl(e,t){let s=this.customInstructionEls.get(e);if(!s){const i={custom:["qsp-prompt-instructions"],facets:["qsp-prompt-instructions-facets"],modes:["qsp-prompt-instructions-modes"]};s=this.createPromptInstructionsEl(i[e],t),this.customInstructionEls.set(e,s)}return s}createPromptInstructionsEl(e,t){const s={cls:["prompt-instructions",...e]};return t.createDiv(s)}createPromptInstructionCommandEl(e,t,s,i,n){i=i??[];const a=e.createDiv();return a.createSpan({cls:["prompt-instruction-command",...i],text:t}),s&&(n=n??[],a.createSpan({cls:n,text:s})),a}closeModalIfEmpty(e,t){const{modal:s,config:i}=this;i.shouldCloseModalOnBackspace&&!s?.inputEl.value&&(s.close(),e.preventDefault())}navigateToCommandHotkeySelector(e,t){const{modal:s,chooser:i,app:{setting:n}}=this,a=i.values?.[i.selectedItem];if(a){n.open();const e=n.openTabById("hotkeys");if(e){s.close();const t=a.item.id;e.setQuery(`${t}`)}}return!1}togglePinnedCommand(e,t){const{app:s,config:i,chooser:n}=this,a=n.values?.[n.selectedItem],o=Te.getEnabledCommandPalettePluginInstance(s);if(a&&o){const e=a.item.id,t=n.suggestions[n.selectedItem];let r=o.options?.pinned;if(r){const t=r.indexOf(e);a.isPinned=-1===t,a.isPinned?r.push(e):r.splice(t,1)}else r=[e],o.options.pinned=r;o.saveSettings(o.plugin),t.empty(),new Te(s,i).renderSuggestion(a,t)}return!1}toggleMarkdownContentRendering(e,t){const{app:i,config:n,chooser:a}=this,o=a.values?.[a.selectedItem],r=o.file;let l=null;if(u(o)?l=o.item:g(o)&&(l={type:"symbolInfo",symbol:o.item,symbolType:s.Heading}),l&&r&&n.shouldRenderSymbolAsHTML(l.symbolType)){const e=a.suggestions[a.selectedItem].find(".qsp-title"),t=0===e.findAll(".qsp-rendered-container").length;e.empty(),Ie.renderSymbolContent(i,n,e,l,r,o.match,t)}return!1}openDefaultApp(e,t){const{app:s,config:{openDefaultApp:{excludeFileExtensions:i}},chooser:n}=this,a=n.values?.[n.selectedItem],o=W(a);if(o&&!i.includes(o.extension)){const e=`Error opening file (${o.path}) in default app. `;s.openWithDefaultApp(o.path).catch((t=>{A(e,t)}))}return!1}saveCurrentAndOpenSelectedWorkspace(){const{app:e,chooser:t,modal:s}=this,i=t?.values?.[t.selectedItem];if(i&&i.item){const t=be.getEnabledWorkspacesPluginInstance(e);t&&(t.saveWorkspace(t.activeWorkspace),t.loadWorkspace(i.item.id),s.close())}return!1}useSelectedItem(e,t){return this.chooser.useSelectedItem(e),!1}insertIntoEditorAsLink(e,t,s){const{app:{workspace:i,fileManager:n,vault:o}}=this,r=i.getActiveViewOfType(a.MarkdownView),l=r?.leaf===t,d=r?.file;if(l&&d){const t=D(n,o,e,d.path,s);t&&r.editor?.replaceSelection(t)}}navigateItems(e,t){const{isOpen:s,chooser:i}=this;if(s){let s=i.selectedItem;s=t?++s:--s,i.setSelectedItem(s,e)}}static commandDisplayStr(e,t){const{keyDisplayStr:s}=this;let i=null,n=null;return e&&(i=e.map((e=>s[e]?.toLocaleLowerCase())).sort().join(" ")),t&&(n=Object.prototype.hasOwnProperty.call(s,t)?s[t]:t),[i,n].filter((e=>e)).join(" ")}static modifiersToKeymapInfoStr(e){return e?.map((e=>"Mod"===e?this.modKey:e)).sort().join(",")}createCustomKeymap(e,t,s,i,n=!0,a=!1){let o=null;if(s){const{modifiers:r,key:l}=s;o={modes:t,modifiers:r,key:l,eventListener:i,purpose:e,command:Ve.commandDisplayStr(r,l),isInstructionOnly:a},n&&this.customKeysInfo.push(o)}return o}addCustomKeymaps(e){const{quickOpen:s}=e,i=s?.keyList;if(i?.length){const e=`${i[0]}~${i[i.length-1]}`;this.createCustomKeymap("open nth item",De,{modifiers:s.modifiers,key:e},null,s.isEnabled,!0)}this.createCustomKeymap("open in new tab",He,{modifiers:["Mod"],key:"Enter"},null,!0,!0),this.createCustomKeymap("open to the right",He,{modifiers:["Mod"],key:"\\"},null,!0,!0),this.createCustomKeymap("open below",He,{modifiers:["Mod","Shift"],key:"\\"},null,!0,!0),this.createCustomKeymap("open in new window",He,{modifiers:["Mod"],key:"o"},null,!0,!0),this.createCustomKeymap("execute command",[t.CommandList],{modifiers:[],key:"Enter"},null,!0,!0),this.createCustomKeymap("open workspace",[t.WorkspaceList],{modifiers:[],key:"Enter"},null,!0,!0),this.createCustomKeymap("save and switch workspace",[t.WorkspaceList],e.saveWorkspaceAndSwitchKeys,this.saveCurrentAndOpenSelectedWorkspace.bind(this)),this.createCustomKeymap("set hotkey",[t.CommandList],e.navigateToHotkeySelectorKeys,this.navigateToCommandHotkeySelector.bind(this)),this.createCustomKeymap("toggle pinned",[t.CommandList],e.togglePinnedCommandKeys,this.togglePinnedCommand.bind(this));const{renderMarkdownContentInSuggestions:n}=e;this.createCustomKeymap("toggle preview (selected item)",[t.HeadingsList,t.SymbolList],n.toggleContentRenderingKeys,this.toggleMarkdownContentRendering.bind(this),n.isEnabled);const{openDefaultApp:a}=e;this.createCustomKeymap("open default app",He,a.openInDefaultAppKeys,this.openDefaultApp.bind(this),a.isEnabled);const{fulltextSearch:o}=e;this.createCustomKeymap("fulltext search",De,o.searchKeys,null,o.isEnabled,!0)}}class We{static coreMobileLauncherButtonEl;static qspMobileLauncherButtonEl;static installMobileLauncherOverride(e,t,s){let i=null;if(!(a.Platform.isMobile&&t.isEnabled&&t.isMobileButtonEnabled)||We.coreMobileLauncherButtonEl)return null;const n=function(e,t){let s=null;const i=e?.mobileNavbar?.containerEl;return i&&(s=i.find(ie.defaults.mobileLauncher.coreLauncherButtonSelector),s||(s=i.find(t.coreLauncherButtonSelector))),s}(e,t);if(n){const e=function(e,t,s){let i=null;if(e&&(i=e.cloneNode(!0),i)){const{iconName:e,coreLauncherButtonIconSelector:n}=t;if(i.addClass("qsp-mobile-launcher-button"),i.addEventListener("click",s),e?.length){const t=i.find(n);t&&a.setIcon(t,e)}}return i}(n,t,s);(function(e,t){let s=!1;return e&&t&&(t.toggleClass("qsp-hidden",!0),e.insertAdjacentElement("beforebegin",t)&&(e.remove(),s=!0),t.toggleClass("qsp-hidden",!1)),s})(n,e)&&(We.coreMobileLauncherButtonEl=n,We.qspMobileLauncherButtonEl=e,i=e)}return i}static removeMobileLauncherOverride(){let e=!1;if(!We.coreMobileLauncherButtonEl)return e;if(We.qspMobileLauncherButtonEl?.parentElement){const t=We.qspMobileLauncherButtonEl,s=We.coreMobileLauncherButtonEl;s.toggleClass("qsp-hidden",!0),t.insertAdjacentElement("beforebegin",s)&&(t.remove(),We.qspMobileLauncherButtonEl=null,We.coreMobileLauncherButtonEl=null,e=!0),s.toggleClass("qsp-hidden",!1)}return e}}class Ne{static emptyLeaves=new Map;static layoutChangeEventRef;static installEmptyTabMonitor(e,t){if(!t?.isEnabled)return;const{workspace:s}=e.app;Ne.layoutChangeEventRef=s.on("layout-change",(()=>{Ne.updateEmptyTabs(s,t)})),e.registerEvent(Ne.layoutChangeEventRef),s.onLayoutReady((()=>{Ne.updateEmptyTabs(s,t)}))}static removeEmptyTabButtons(e){e.offref(Ne.layoutChangeEventRef),Ne.layoutChangeEventRef=null;const{emptyLeaves:t}=Ne;for(const e of t.keys())t.get(e)?.detach(),t.delete(e)}static updateEmptyTabs(e,t){if(!t.isEnabled)return;const{buttonLabel:s,onclickListener:i}=t;e.iterateAllLeaves((e=>{const{emptyLeaves:t}=Ne;if(K(e,"empty")&&!t.has(e)){const{containerEl:n}=e.view,a=function(e,t,s){let i=null;const n=e.find(".empty-state-action-list");return n&&(i=n.createDiv({cls:["empty-state-action","tappable","qsp-empty-state-action-launch"],text:t}),i.addEventListener("click",s),n.firstElementChild!==i&&n.insertAfter(i,n.firstElementChild)),i}(n,s,i);a&&t.set(e,a)}}))}}const Ke=[{id:"switcher-plus:open",name:"Open in Standard Mode",mode:t.Standard,iconId:"lucide-file-search",ribbonIconEl:null},{id:"switcher-plus:open-editors",name:"Open in Editor Mode",mode:t.EditorList,iconId:"lucide-file-edit",ribbonIconEl:null},{id:"switcher-plus:open-symbols",name:"Open Symbols for selected suggestion or editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",ribbonIconEl:null},{id:"switcher-plus:open-symbols-active",name:"Open Symbols for the active editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",ribbonIconEl:null,sessionOpts:{useActiveEditorAsSource:!0}},{id:"switcher-plus:open-workspaces",name:"Open in Workspaces Mode",mode:t.WorkspaceList,iconId:"lucide-album",ribbonIconEl:null},{id:"switcher-plus:open-headings",name:"Open in Headings Mode",mode:t.HeadingsList,iconId:"lucide-file-search",ribbonIconEl:null},{id:"switcher-plus:open-starred",name:"Open in Bookmarks Mode",mode:t.BookmarksList,iconId:"lucide-bookmark",ribbonIconEl:null},{id:"switcher-plus:open-commands",name:"Open in Commands Mode",mode:t.CommandList,iconId:"run-command",ribbonIconEl:null},{id:"switcher-plus:open-related-items",name:"Open Related Items for selected suggestion or editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",ribbonIconEl:null},{id:"switcher-plus:open-related-items-active",name:"Open Related Items for the active editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",ribbonIconEl:null,sessionOpts:{useActiveEditorAsSource:!0}},{id:"switcher-plus:open-vaults",name:"Open in Vaults Mode",mode:t.VaultList,iconId:"vault",ribbonIconEl:null}];class qe extends a.Plugin{options;async onload(){const e=new ie(this);await e.updateDataAndLoadSettings(),this.options=e,this.addSettingTab(new ge(this.app,this,e)),this.registerRibbonCommandIcons(),this.updateLauncherButtonOverrides(!0),Ke.forEach((({id:e,name:t,mode:s,iconId:i,sessionOpts:n})=>{this.registerCommand(e,t,s,i,n)}))}onunload(){this.updateLauncherButtonOverrides(!1)}registerCommand(e,t,s,i,n){this.addCommand({id:e,name:t,icon:i,checkCallback:e=>this.createModalAndOpen(s,e,n)})}registerRibbonCommandIcons(){Ke.forEach((e=>{e.ribbonIconEl?.remove(),e.ribbonIconEl=null}));const e=Ke.reduce(((e,t)=>(e[t.mode]=t,e)),{});this.options.enabledRibbonCommands.forEach((s=>{const i=e[t[s]];i&&(i.ribbonIconEl=this.addRibbonIcon(i.iconId,i.name,(()=>{this.createModalAndOpen(i.mode,!1)})))}))}createModalAndOpen(e,t,s){if(!t){const t=function(e,t){const s=L(e)?.QuickSwitcherModal;return s?new class extends s{plugin;_exMode;get exMode(){return this._exMode}constructor(e,t){super(e,t.options.builtInSystemOptions),this.plugin=t;const{options:s}=t;s.shouldShowAlias=this.shouldShowAlias;const i=new Ve(e,this.scope,this.chooser,this,s);this._exMode=new Pe(e,s,i)}openInMode(e){this.exMode.setSessionOpenMode(this.chooser,e),super.open()}onOpen(){this.exMode.onOpen(),super.onOpen()}onClose(){super.onClose(),this.exMode.onClose()}updateSuggestions(){const{exMode:e,inputEl:t,chooser:s}=this;e.setInitialInputForSession(t),e.updateSuggestions(t.value,s,this)||super.updateSuggestions()}getSuggestions(e){const{exMode:t,plugin:s}=this,i=t.inputTextForStandardMode(e),n=super.getSuggestions(i);return t.addPropertiesToStandardSuggestions(n,s.options),n}onChooseSuggestion(e,t){this.exMode.onChooseSuggestion(e,t)||super.onChooseSuggestion(e,t)}renderSuggestion(e,t){this.exMode.renderSuggestion(e,t)||super.renderSuggestion(e,t)}}(e,t):(O("Unable to extend system switcher. Plugin UI will not be loaded. Use the builtin switcher instead."),null)}(this.app,this);if(!t)return!1;const i=Object.assign({mode:e},s);t.openInMode(i)}return!0}updateLauncherButtonOverrides(e){const{app:s,options:{mobileLauncher:i}}=this;if(We.removeMobileLauncherOverride(),Ne.removeEmptyTabButtons(s.workspace),e){const e=i.modeString,n=t[e],a=()=>{n&&this.createModalAndOpen(n,!1)};We.installMobileLauncherOverride(s,i,a);const o=Ke.find((e=>e.mode===n)),r="Switcher++: "+(o?.name??"");Ne.installEmptyTabMonitor(this,{isEnabled:i.isEnabled&&i.isEmptyTabButtonEnabled,buttonLabel:r,onclickListener:a})}}}module.exports=qe; +"use strict";var e,t,s,i,n,a=require("obsidian");!function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.FolderOnly=2]="FolderOnly",e[e.FolderWithFilename=3]="FolderWithFilename",e[e.FolderPathFilenameOptional=4]="FolderPathFilenameOptional"}(e||(e={})),function(e){e[e.Standard=1]="Standard",e[e.EditorList=2]="EditorList",e[e.SymbolList=4]="SymbolList",e[e.WorkspaceList=8]="WorkspaceList",e[e.HeadingsList=16]="HeadingsList",e[e.BookmarksList=32]="BookmarksList",e[e.CommandList=64]="CommandList",e[e.RelatedItemsList=128]="RelatedItemsList",e[e.VaultList=256]="VaultList"}(t||(t={})),function(e){e[e.Link=1]="Link",e[e.Embed=2]="Embed",e[e.Tag=4]="Tag",e[e.Heading=8]="Heading",e[e.Callout=16]="Callout",e[e.CanvasNode=32]="CanvasNode",e[e.BaseView=64]="BaseView"}(s||(s={})),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heading=2]="Heading",e[e.Block=4]="Block"}(i||(i={})),function(e){e.Both="both",e.Inline="inline",e.Frontmatter="frontmatter"}(n||(n={}));const o={};o[s.Link]="🔗",o[s.Embed]="!",o[s.Tag]="#",o[s.Heading]="H";const r={};var l,d,c;r[1]="H₁",r[2]="H₂",r[3]="H₃",r[4]="H₄",r[5]="H₅",r[6]="H₆",function(e){e.EditorList="editorList",e.SymbolList="symbolList",e.WorkspaceList="workspaceList",e.HeadingsList="headingsList",e.Bookmark="bookmark",e.CommandList="commandList",e.RelatedItemsList="relatedItemsList",e.VaultList="vaultList",e.File="file",e.Alias="alias",e.Unresolved="unresolved"}(l||(l={})),function(e){e[e.None=0]="None",e[e.Primary=1]="Primary",e[e.Basename=2]="Basename",e[e.Path=3]="Path"}(d||(d={})),function(e){e.DiskLocation="disk-location",e.Backlink="backlink",e.OutgoingLink="outgoing-link"}(c||(c={}));class h{static getAliases(e){let t=[];return e&&(t=h.getValueForKey(e,/^alias(es)?$/i)),t}static getTags(e){let t=[];return e&&(t=h.getValueForKey(e,/^tags?$/i)),t}static getValueForKey(e,t){const s=[],i=Object.keys(e).find((e=>t.test(e)));if(i){let t=e[i];"string"==typeof t&&(t=t.split(",")),Array.isArray(t)&&t.forEach((e=>{"string"==typeof e&&s.push(e.trim())}))}return s}}function m(e,t,s){let i=!1;return e&&void 0!==e[t]&&(i=!0,void 0!==s&&s!==e[t]&&(i=!1)),i}function u(e){return m(e,"type",l.SymbolList)}function g(e){return m(e,"type",l.HeadingsList)}function p(e){return m(e,"type",l.File)}function f(e){return m(e,"type",l.Alias)}function y(e){return m(e,"type",l.Unresolved)}function b(e){return e&&!(p(t=e)||y(t)||f(t));var t}function S(e){return m(e,"level")}function k(e){return m(e,"tag")}function v(e){return m(e,"type","callout")}function w(e){return m(e,"extension")}function C(e){return m(e,"children")}function I(e,t){return e?.internalPlugins?.getEnabledPluginById(t)}function L(e){const t=function(e,t){return e?.internalPlugins?.getPluginById(t)}(e,"switcher");return t?.instance}function T(e){return I(e,"global-search")}function E(){return Object.values(t).filter((e=>isNaN(Number(e)))).sort()}function F(){return[t.RelatedItemsList,t.SymbolList]}function x(e){let t=null;if(e){const s=a.normalizePath(e),i=s.lastIndexOf("/");t=-1===i?s:s.slice(i+1)}return t}function A(e,t){new a.Notice(`Switcher++: ${e}`),O(e,t)}function O(e,...t){console.error(`Switcher++: ${e}`,...t)}function P(e,...t){console.warn(`Switcher++: ${e}`,...t)}function M(e){e=e??[];const t=[];for(const s of e)try{const e=new RegExp(s);t.push(e)}catch(e){O(`Error creating RegExp from string: ${s}`,e)}return e=>{for(const s of t)if(s.test(e))return!0;return!1}}function B(e){let t=i.None;if(e){const s=e.link.split("|")[0];t=s.includes("#^")?i.Block:s.includes("#")?i.Heading:i.Normal}return t}function R(e,t){return t?.getFileByPath(e)}function H(e){let t=null;if(!e)return t;if(e.isDeferred){const s=e.getViewState()?.state?.file;s&&(t=R(s,e.app?.vault))}else e.view?.file&&(t=e.view.file);return t}function D(e,t,s,i,n){let o=null;if(n=Object.assign({useBasenameAsAlias:!0,useHeadingAsAlias:!0},n),s){let r=W(s),d=null,c=null;switch(s.type){case l.Unresolved:o=N(s.linktext);break;case l.Alias:d=s.alias;break;case l.Bookmark:{const{item:e}=s;"file"===e.type&&e.title&&(d=e.title);break}case l.HeadingsList:{const{heading:e}=s.item;({subpath:c,alias:d}=V(e,n.useHeadingAsAlias));break}case l.SymbolList:{const{item:{symbol:l}}=s;if(S(l))({subpath:c,alias:d}=V(l.heading,n.useHeadingAsAlias));else if(m(l,"link")){o=new RegExp(/^\[(.*?)\]\((.+?)\)/).test(l.original)?l.original:function(e,t,s,i,n,o){const{link:r,displayText:l}=i,{path:d,subpath:c}=a.parseLinktext(r);let h=l,m=null,u=null;m=d?.length?R(d,t):n;m?(!h?.length&&o&&(h=m.basename),u=e.generateMarkdownLink(m,s,c,h)):u=N(d,h);return u}(e,t,i,l,r,n.useBasenameAsAlias)}else r=null;break}case l.RelatedItemsList:{const{item:e}=s;e.unresolvedText&&(o=N(e.unresolvedText));break}}r&&!o&&(!d&&n.useBasenameAsAlias&&(d=r.basename),o=e.generateMarkdownLink(r,i,c,d))}return o}function V(e,t){const s=a.stripHeadingForLink(e);return{subpath:`#${s}`,alias:t?s:null}}function W(e){let t=null;return[l.Alias,l.Bookmark,l.HeadingsList,l.SymbolList,l.RelatedItemsList,l.EditorList,l.File].includes(e?.type)&&(t=e.file),t}function N(e,t){return`[[${e}${t=t?.length?`|${t}`:""}]]`}function K(e,t){return e?.view?.getViewType()===t&&!e.isDeferred}class q{static rootComponent;static getRootComponent(){return this.rootComponent||(this.rootComponent=new a.Component,this.rootComponent.load()),this.rootComponent}static unload(){this.rootComponent?.unload(),this.rootComponent=null}}const j={file:"canvas-node-file",text:"canvas-node-text",link:"canvas-node-link",group:"canvas-node-group"},$={table:"base-view-table",list:"base-view-list",cards:"base-view-cards"},U=[{id:s[s.Heading],mode:t.SymbolList,label:"headings",isActive:!1,isAvailable:!0},{id:s[s.Tag],mode:t.SymbolList,label:"tags",isActive:!1,isAvailable:!0},{id:s[s.Callout],mode:t.SymbolList,label:"callouts",isActive:!1,isAvailable:!0},{id:s[s.Link],mode:t.SymbolList,label:"links",isActive:!1,isAvailable:!0},{id:s[s.Embed],mode:t.SymbolList,label:"embeds",isActive:!1,isAvailable:!0},{id:j.file,mode:t.SymbolList,label:"file cards",isActive:!1,isAvailable:!0},{id:j.text,mode:t.SymbolList,label:"text cards",isActive:!1,isAvailable:!0},{id:j.link,mode:t.SymbolList,label:"link cards",isActive:!1,isAvailable:!0},{id:j.group,mode:t.SymbolList,label:"groups",isActive:!1,isAvailable:!0},{id:$.table,mode:t.SymbolList,label:"table views",isActive:!1,isAvailable:!0},{id:$.list,mode:t.SymbolList,label:"list views",isActive:!1,isAvailable:!0},{id:$.cards,mode:t.SymbolList,label:"card views",isActive:!1,isAvailable:!0}],Q=[{id:c.Backlink,mode:t.RelatedItemsList,label:"backlinks",isActive:!1,isAvailable:!0},{id:c.OutgoingLink,mode:t.RelatedItemsList,label:"outgoing links",isActive:!1,isAvailable:!0},{id:c.DiskLocation,mode:t.RelatedItemsList,label:"disk location",isActive:!1,isAvailable:!0}],G={file:"bookmarks-file",folder:"bookmarks-folder",search:"bookmarks-search",group:"bookmarks-group"},_=[{id:G.file,mode:t.BookmarksList,label:"files",isActive:!1,isAvailable:!0},{id:G.folder,mode:t.BookmarksList,label:"folders",isActive:!1,isAvailable:!0},{id:G.search,mode:t.BookmarksList,label:"searches",isActive:!1,isAvailable:!0}];var z;!function(e){e.Pinned="pinnedCommands",e.Recent="recentCommands"}(z||(z={}));const Z=[{id:z.Pinned,mode:t.CommandList,label:"pinned",isActive:!1,isAvailable:!0},{id:z.Recent,mode:t.CommandList,label:"recent",isActive:!1,isAvailable:!0}];var J;!function(e){e.RecentFiles="recentFilesSearch",e.Bookmarks="bookmarksSearch",e.Filenames="filenamesSearch",e.Headings="headingsSearch",e.ExternalFiles="externalFilesSearch"}(J||(J={}));const Y=[{id:J.RecentFiles,mode:t.HeadingsList,label:"recent files",isActive:!1,isAvailable:!0},{id:J.Bookmarks,mode:t.HeadingsList,label:"bookmarks",isActive:!1,isAvailable:!0},{id:J.Filenames,mode:t.HeadingsList,label:"filenames",isActive:!1,isAvailable:!0},{id:J.Headings,mode:t.HeadingsList,label:"headings",isActive:!1,isAvailable:!0},{id:J.ExternalFiles,mode:t.HeadingsList,label:"external files",isActive:!1,isAvailable:!0}];function X(){const e={};return[U,Q,_,Z,Y].flat().reduce(((e,t)=>(e[t.id]=Object.assign({},t),e)),e),e}const ee=e=>{if("object"==typeof e&&null!==e){if("function"==typeof Object.getPrototypeOf){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}return"[object Object]"===Object.prototype.toString.call(e)}return!1},te=(...e)=>e.reduce(((e,t)=>{if(void 0===t)return e;if(Array.isArray(t))throw new TypeError("Arguments provided to ts-deepmerge must be objects, not arrays.");return Object.keys(t).forEach((s=>{["__proto__","constructor","prototype"].includes(s)||(Array.isArray(e[s])&&Array.isArray(t[s])?e[s]=te.options.mergeArrays?te.options.uniqueArrayItems?Array.from(new Set(e[s].concat(t[s]))):[...e[s],...t[s]]:t[s]:ee(e[s])&&ee(t[s])?e[s]=te(e[s],t[s]):!ee(e[s])&&ee(t[s])?e[s]=te(t[s],void 0):e[s]=void 0===t[s]?te.options.allowUndefinedOverrides?t[s]:e[s]:t[s])})),e}),{}),se={allowUndefinedOverrides:!0,mergeArrays:!0,uniqueArrayItems:!0};te.options=se,te.withOptions=(e,...t)=>{te.options=Object.assign(Object.assign({},se),e);const s=te(...t);return te.options=se,s};class ie{plugin;data;static get defaults(){const i={};return i[s.Link]=!0,i[s.Embed]=!0,i[s.Tag]=!0,i[s.Heading]=!0,i[s.Callout]=!0,{version:"2.0.0",onOpenPreferNewTab:!0,alwaysNewTabForSymbols:!1,useActiveTabForSymbolsOnMobile:!1,symbolsInLineOrder:!0,editorListCommand:"edt ",symbolListCommand:"@",symbolListActiveEditorCommand:"$ ",workspaceListCommand:"+",headingsListCommand:"#",bookmarksListCommand:"'",commandListCommand:">",recentCommandDisplayOrder:"desc",maxRecentCommands:25,vaultListCommand:"vault ",relatedItemsListCommand:"~",relatedItemsListActiveEditorCommand:"^ ",shouldSearchHeadings:!0,strictHeadingsOnly:!1,searchAllHeadings:!0,headingsSearchDebounceMilli:250,excludeViewTypes:["empty"],referenceViews:["backlink","localgraph","outgoing-link","outline"],limit:50,includeSidePanelViewTypes:["backlink","image","markdown","pdf"],enabledSymbolTypes:i,selectNearestHeading:!0,excludeFolders:[],excludeLinkSubTypes:0,excludeRelatedFolders:[""],excludeOpenRelatedFiles:!1,excludeObsidianIgnoredFiles:!1,shouldSearchFilenames:!1,shouldSearchBookmarks:!1,shouldSearchRecentFiles:!0,pathDisplayFormat:e.FolderWithFilename,hidePathIfRoot:!0,enabledRelatedItems:Object.values(c),showOptionalIndicatorIcons:!0,isFileExtensionIndicatorsEnabled:!0,excludeFileExtensionIndicators:["md"],overrideStandardModeBehaviors:!0,overrideStandardModeRendering:!0,enabledRibbonCommands:[t[t.HeadingsList],t[t.SymbolList]],fileExtAllowList:["canvas"],matchPriorityAdjustments:{isEnabled:!1,adjustments:{isOpenInEditor:{value:0,label:"Open items"},isBookmarked:{value:0,label:"Bookmarked items"},isRecent:{value:0,label:"Recent items"},isAttachment:{value:0,label:"Attachment file types"},file:{value:0,label:"Filenames"},alias:{value:0,label:"Aliases"},unresolved:{value:0,label:"Unresolved filenames"},h1:{value:0,label:"H₁ headings"}},fileExtAdjustments:{canvas:{value:0,label:"Canvas files"}}},quickFilters:{resetKey:"0",keyList:["1","2","3","4","5","6","7","8","9"],modifiers:["Ctrl","Alt"],facetList:X(),shouldResetActiveFacets:!1,shouldShowFacetInstructions:!0},preserveCommandPaletteLastInput:!1,preserveQuickSwitcherLastInput:!1,shouldCloseModalOnBackspace:!1,maxRecentFileSuggestionsOnInit:25,orderEditorListByAccessTime:!0,insertLinkInEditor:{isEnabled:!0,keymap:{modifiers:["Mod"],key:"i",purpose:"insert in editor"},insertableEditorTypes:["markdown"],useBasenameAsAlias:!0,useHeadingAsAlias:!0},removeDefaultTabBinding:!0,navigationKeys:{nextKeys:[{modifiers:["Ctrl"],key:"n"},{modifiers:["Ctrl"],key:"j"}],prevKeys:[{modifiers:["Ctrl"],key:"p"},{modifiers:["Ctrl"],key:"k"}]},preferredSourceForTitle:"H1",frontmatterTitleProperty:"title",closeWhenEmptyKeys:[{modifiers:null,key:"Backspace"}],navigateToHotkeySelectorKeys:{modifiers:["Ctrl","Shift"],key:"h"},togglePinnedCommandKeys:{modifiers:["Ctrl","Shift"],key:"p"},escapeCmdChar:"!",mobileLauncher:{isEnabled:!1,isMobileButtonEnabled:!0,isEmptyTabButtonEnabled:!0,modeString:t[t.HeadingsList],iconName:"",coreLauncherButtonIconSelector:"span.clickable-icon",coreLauncherButtonSelector:".mobile-navbar-action.mobile-navbar-action-quick-switcher"},allowCreateNewFileInModeNames:[t[t.Standard],t[t.HeadingsList]],showModeTriggerInstructions:!0,renderMarkdownContentInSuggestions:{isEnabled:!1,renderHeadings:!1,renderLinks:!1,renderTags:!1,renderCallouts:!1,toggleContentRenderingKeys:{modifiers:["Shift","Ctrl"],key:"m"}},quickOpen:{isEnabled:!0,modifiers:["Alt"],keyList:["1","2","3","4","5","6","7","8","9"]},openDefaultApp:{isEnabled:!0,openInDefaultAppKeys:{modifiers:["Shift","Ctrl"],key:"o"},excludeFileExtensions:[]},fulltextSearch:{isEnabled:!0,searchKeys:{modifiers:["Mod","Shift"],key:"f"}},openInBackground:{isEnabled:!0,openKeys:[{openType:"tab",hotkey:{modifiers:["Mod","Shift"],key:"t"}},{openType:"vertical",hotkey:null},{openType:"horizontal",hotkey:null},{openType:"window",hotkey:null}]},saveWorkspaceAndSwitchKeys:{modifiers:["Mod","Shift"],key:"s"},showHeadingBreadcrumbs:!0,headingBreadcrumbSeparator:" > ",maxBreadcrumbDepth:0,showHeadingBreadcrumbsInSymbolMode:!1,showTagsInSuggestions:!1,tagSource:n.Both,excludeTagsFromDisplay:[],tagDisplaySeparator:" ",removeHashPrefixFromTags:!1,maxTagsToDisplay:0}}shouldShowAlias;get version(){return this.data.version}set version(e){this.data.version=e}get builtInSystemOptions(){return L(this.plugin.app)?.options}get showAllFileTypes(){return this.builtInSystemOptions?.showAllFileTypes}get showAttachments(){return this.builtInSystemOptions?.showAttachments}get showExistingOnly(){return this.builtInSystemOptions?.showExistingOnly}get onOpenPreferNewTab(){return this.data.onOpenPreferNewTab}set onOpenPreferNewTab(e){this.data.onOpenPreferNewTab=e}get alwaysNewTabForSymbols(){return this.data.alwaysNewTabForSymbols}set alwaysNewTabForSymbols(e){this.data.alwaysNewTabForSymbols=e}get useActiveTabForSymbolsOnMobile(){return this.data.useActiveTabForSymbolsOnMobile}set useActiveTabForSymbolsOnMobile(e){this.data.useActiveTabForSymbolsOnMobile=e}get symbolsInLineOrder(){return this.data.symbolsInLineOrder}set symbolsInLineOrder(e){this.data.symbolsInLineOrder=e}get editorListPlaceholderText(){return ie.defaults.editorListCommand}get editorListCommand(){return this.data.editorListCommand}set editorListCommand(e){this.data.editorListCommand=e}get symbolListPlaceholderText(){return ie.defaults.symbolListCommand}get symbolListCommand(){return this.data.symbolListCommand}set symbolListCommand(e){this.data.symbolListCommand=e}get symbolListActiveEditorCommand(){return this.data.symbolListActiveEditorCommand}set symbolListActiveEditorCommand(e){this.data.symbolListActiveEditorCommand=e}get workspaceListCommand(){return this.data.workspaceListCommand}set workspaceListCommand(e){this.data.workspaceListCommand=e}get workspaceListPlaceholderText(){return ie.defaults.workspaceListCommand}get headingsListCommand(){return this.data.headingsListCommand}set headingsListCommand(e){this.data.headingsListCommand=e}get headingsListPlaceholderText(){return ie.defaults.headingsListCommand}get bookmarksListCommand(){return this.data.bookmarksListCommand}set bookmarksListCommand(e){this.data.bookmarksListCommand=e}get bookmarksListPlaceholderText(){return ie.defaults.bookmarksListCommand}get commandListCommand(){return this.data.commandListCommand}set commandListCommand(e){this.data.commandListCommand=e}get recentCommandDisplayOrder(){return this.data.recentCommandDisplayOrder}set recentCommandDisplayOrder(e){this.data.recentCommandDisplayOrder=e}get maxRecentCommands(){return this.data.maxRecentCommands}set maxRecentCommands(e){this.data.maxRecentCommands=e}get commandListPlaceholderText(){return ie.defaults.commandListCommand}get vaultListCommand(){return this.data.vaultListCommand}set vaultListCommand(e){this.data.vaultListCommand=e}get vaultListPlaceholderText(){return ie.defaults.vaultListCommand}get relatedItemsListCommand(){return this.data.relatedItemsListCommand}set relatedItemsListCommand(e){this.data.relatedItemsListCommand=e}get relatedItemsListPlaceholderText(){return ie.defaults.relatedItemsListCommand}get relatedItemsListActiveEditorCommand(){return this.data.relatedItemsListActiveEditorCommand}set relatedItemsListActiveEditorCommand(e){this.data.relatedItemsListActiveEditorCommand=e}get shouldSearchHeadings(){return this.data.shouldSearchHeadings}set shouldSearchHeadings(e){this.data.shouldSearchHeadings=e}get strictHeadingsOnly(){return this.data.strictHeadingsOnly}set strictHeadingsOnly(e){this.data.strictHeadingsOnly=e}get searchAllHeadings(){return this.data.searchAllHeadings}set searchAllHeadings(e){this.data.searchAllHeadings=e}get headingsSearchDebounceMilli(){return this.data.headingsSearchDebounceMilli}set headingsSearchDebounceMilli(e){this.data.headingsSearchDebounceMilli=e}get excludeViewTypes(){return this.data.excludeViewTypes}set excludeViewTypes(e){this.data.excludeViewTypes=e}get referenceViews(){return this.data.referenceViews}set referenceViews(e){this.data.referenceViews=e}get limit(){return this.data.limit}set limit(e){this.data.limit=e}get includeSidePanelViewTypes(){return this.data.includeSidePanelViewTypes}set includeSidePanelViewTypes(e){this.data.includeSidePanelViewTypes=[...new Set(e)]}get includeSidePanelViewTypesPlaceholder(){return ie.defaults.includeSidePanelViewTypes.join("\n")}get selectNearestHeading(){return this.data.selectNearestHeading}set selectNearestHeading(e){this.data.selectNearestHeading=e}get excludeFolders(){return this.data.excludeFolders}set excludeFolders(e){this.data.excludeFolders=[...new Set(e)]}get excludeLinkSubTypes(){return this.data.excludeLinkSubTypes}set excludeLinkSubTypes(e){this.data.excludeLinkSubTypes=e}get excludeRelatedFolders(){return this.data.excludeRelatedFolders}set excludeRelatedFolders(e){this.data.excludeRelatedFolders=[...new Set(e)]}get excludeOpenRelatedFiles(){return this.data.excludeOpenRelatedFiles}set excludeOpenRelatedFiles(e){this.data.excludeOpenRelatedFiles=e}get excludeObsidianIgnoredFiles(){return this.data.excludeObsidianIgnoredFiles}set excludeObsidianIgnoredFiles(e){this.data.excludeObsidianIgnoredFiles=e}get shouldSearchFilenames(){return this.data.shouldSearchFilenames}set shouldSearchFilenames(e){this.data.shouldSearchFilenames=e}get shouldSearchBookmarks(){return this.data.shouldSearchBookmarks}set shouldSearchBookmarks(e){this.data.shouldSearchBookmarks=e}get shouldSearchRecentFiles(){return this.data.shouldSearchRecentFiles}set shouldSearchRecentFiles(e){this.data.shouldSearchRecentFiles=e}get pathDisplayFormat(){return this.data.pathDisplayFormat}set pathDisplayFormat(e){this.data.pathDisplayFormat=e}get hidePathIfRoot(){return this.data.hidePathIfRoot}set hidePathIfRoot(e){this.data.hidePathIfRoot=e}get enabledRelatedItems(){return this.data.enabledRelatedItems}set enabledRelatedItems(e){this.data.enabledRelatedItems=e}get showOptionalIndicatorIcons(){return this.data.showOptionalIndicatorIcons}set showOptionalIndicatorIcons(e){this.data.showOptionalIndicatorIcons=e}get isFileExtensionIndicatorsEnabled(){return this.data.isFileExtensionIndicatorsEnabled}set isFileExtensionIndicatorsEnabled(e){this.data.isFileExtensionIndicatorsEnabled=e}get excludeFileExtensionIndicators(){return this.data.excludeFileExtensionIndicators}set excludeFileExtensionIndicators(e){this.data.excludeFileExtensionIndicators=[...new Set(e)]}get overrideStandardModeBehaviors(){return this.data.overrideStandardModeBehaviors}set overrideStandardModeBehaviors(e){this.data.overrideStandardModeBehaviors=e}get overrideStandardModeRendering(){return this.data.overrideStandardModeRendering}set overrideStandardModeRendering(e){this.data.overrideStandardModeRendering=e}get enabledRibbonCommands(){return this.data.enabledRibbonCommands}set enabledRibbonCommands(e){this.data.enabledRibbonCommands=[...new Set(e)]}get fileExtAllowList(){return this.data.fileExtAllowList}set fileExtAllowList(e){this.data.fileExtAllowList=e}get matchPriorityAdjustments(){return this.data.matchPriorityAdjustments}set matchPriorityAdjustments(e){this.data.matchPriorityAdjustments=e}get quickFilters(){return this.data.quickFilters}set quickFilters(e){this.data.quickFilters=e}get preserveCommandPaletteLastInput(){return this.data.preserveCommandPaletteLastInput}set preserveCommandPaletteLastInput(e){this.data.preserveCommandPaletteLastInput=e}get preserveQuickSwitcherLastInput(){return this.data.preserveQuickSwitcherLastInput}set preserveQuickSwitcherLastInput(e){this.data.preserveQuickSwitcherLastInput=e}get shouldCloseModalOnBackspace(){return this.data.shouldCloseModalOnBackspace}set shouldCloseModalOnBackspace(e){this.data.shouldCloseModalOnBackspace=e}get maxRecentFileSuggestionsOnInit(){return this.data.maxRecentFileSuggestionsOnInit}set maxRecentFileSuggestionsOnInit(e){this.data.maxRecentFileSuggestionsOnInit=e}get orderEditorListByAccessTime(){return this.data.orderEditorListByAccessTime}set orderEditorListByAccessTime(e){this.data.orderEditorListByAccessTime=e}get insertLinkInEditor(){return this.data.insertLinkInEditor}set insertLinkInEditor(e){this.data.insertLinkInEditor=e}get removeDefaultTabBinding(){return this.data.removeDefaultTabBinding}set removeDefaultTabBinding(e){this.data.removeDefaultTabBinding=e}get navigationKeys(){return this.data.navigationKeys}set navigationKeys(e){this.data.navigationKeys=e}get preferredSourceForTitle(){return this.data.preferredSourceForTitle}set preferredSourceForTitle(e){this.data.preferredSourceForTitle=e}get frontmatterTitleProperty(){return this.data.frontmatterTitleProperty}set frontmatterTitleProperty(e){this.data.frontmatterTitleProperty=e}get closeWhenEmptyKeys(){return this.data.closeWhenEmptyKeys}set closeWhenEmptyKeys(e){this.data.closeWhenEmptyKeys=e}get navigateToHotkeySelectorKeys(){return this.data.navigateToHotkeySelectorKeys}set navigateToHotkeySelectorKeys(e){this.data.navigateToHotkeySelectorKeys=e}get togglePinnedCommandKeys(){return this.data.togglePinnedCommandKeys}set togglePinnedCommandKeys(e){this.data.togglePinnedCommandKeys=e}get escapeCmdChar(){return this.data.escapeCmdChar}set escapeCmdChar(e){this.data.escapeCmdChar=e}get mobileLauncher(){return this.data.mobileLauncher}set mobileLauncher(e){this.data.mobileLauncher=e}get allowCreateNewFileInModeNames(){return this.data.allowCreateNewFileInModeNames}set allowCreateNewFileInModeNames(e){this.data.allowCreateNewFileInModeNames=[...new Set(e)]}get showModeTriggerInstructions(){return this.data.showModeTriggerInstructions}set showModeTriggerInstructions(e){this.data.showModeTriggerInstructions=e}get renderMarkdownContentInSuggestions(){return this.data.renderMarkdownContentInSuggestions}set renderMarkdownContentInSuggestions(e){this.data.renderMarkdownContentInSuggestions=e}get quickOpen(){return this.data.quickOpen}set quickOpen(e){this.data.quickOpen=e}get openDefaultApp(){return this.data.openDefaultApp}set openDefaultApp(e){this.data.openDefaultApp=e}get fulltextSearch(){return this.data.fulltextSearch}set fulltextSearch(e){this.data.fulltextSearch=e}get openInBackground(){return this.data.openInBackground}set openInBackground(e){this.data.openInBackground=e}get saveWorkspaceAndSwitchKeys(){return this.data.saveWorkspaceAndSwitchKeys}set saveWorkspaceAndSwitchKeys(e){this.data.saveWorkspaceAndSwitchKeys=e}get showHeadingBreadcrumbs(){return this.data.showHeadingBreadcrumbs}set showHeadingBreadcrumbs(e){this.data.showHeadingBreadcrumbs=e}get headingBreadcrumbSeparator(){return this.data.headingBreadcrumbSeparator}set headingBreadcrumbSeparator(e){this.data.headingBreadcrumbSeparator=e}get maxBreadcrumbDepth(){return this.data.maxBreadcrumbDepth}set maxBreadcrumbDepth(e){this.data.maxBreadcrumbDepth=e}get showHeadingBreadcrumbsInSymbolMode(){return this.data.showHeadingBreadcrumbsInSymbolMode}set showHeadingBreadcrumbsInSymbolMode(e){this.data.showHeadingBreadcrumbsInSymbolMode=e}get showTagsInSuggestions(){return this.data.showTagsInSuggestions}set showTagsInSuggestions(e){this.data.showTagsInSuggestions=e}get tagSource(){return this.data.tagSource}set tagSource(e){this.data.tagSource=e}get excludeTagsFromDisplay(){return this.data.excludeTagsFromDisplay}set excludeTagsFromDisplay(e){this.data.excludeTagsFromDisplay=e}get tagDisplaySeparator(){return this.data.tagDisplaySeparator}set tagDisplaySeparator(e){this.data.tagDisplaySeparator=e}get removeHashPrefixFromTags(){return this.data.removeHashPrefixFromTags}set removeHashPrefixFromTags(e){this.data.removeHashPrefixFromTags=e}get maxTagsToDisplay(){return this.data.maxTagsToDisplay}set maxTagsToDisplay(e){this.data.maxTagsToDisplay=e}constructor(e){this.plugin=e,this.data=ie.defaults}async updateDataAndLoadSettings(){return await ie.transformDataFile(this.plugin,ie.defaults),await this.loadSettings()}async loadSettings(){try{const e=await(this.plugin?.loadData());if(e){const t=Object.keys(ie.defaults);((e,t,s)=>{const i=["matchPriorityAdjustments","quickFilters","mobileLauncher"],n=s=>te.withOptions({mergeArrays:!1},t[s],e[s]);for(const a of s)a in e&&(t[a]=i.includes(a)?n(a):e[a])})(e,this.data,t)}}catch(e){O("Error loading settings, using defaults. ",e)}}async saveSettings(){const{plugin:e,data:t}=this;await(e?.saveData(t))}save(){this.saveSettings().catch((e=>{O("Error saving changes to settings",e)}))}isSymbolTypeEnabled(e){const{enabledSymbolTypes:t}=this.data;let s=ie.defaults.enabledSymbolTypes[e];return Object.prototype.hasOwnProperty.call(t,e)&&(s=t[e]),s}setSymbolTypeEnabled(e,t){this.data.enabledSymbolTypes[e]=t}shouldRenderSymbolAsHTML(e){const{renderMarkdownContentInSuggestions:t}=this.data;if(!t.isEnabled)return!1;const i={[s.Heading]:"renderHeadings",[s.Link]:"renderLinks",[s.Tag]:"renderTags",[s.Callout]:"renderCallouts"}[e];return!!i&&t[i]}static async transformDataFile(e,t){await ie.transformDataFileToV1(e,t),await ie.transformDataFileToV2(e,t)}static async transformDataFileToV1(e,t){let s=!1;try{const i=await(e?.loadData());if(i&&"object"==typeof i){const n="version";if(!Object.prototype.hasOwnProperty.call(i,n)){const a="starredListCommand";Object.prototype.hasOwnProperty.call(i,a)&&(i.bookmarksListCommand=i[a]??t.bookmarksListCommand,delete i[a]);const o="isStarred",r=i.matchPriorityAdjustments;r&&Object.prototype.hasOwnProperty.call(r,o)&&(r.isBookmarked=r[o],delete r[o]),i[n]="1.0.0",await(e?.saveData(i)),s=!0}}}catch(e){O("Error transforming data.json to v1.0.0",e)}return s}static async transformDataFileToV2(e,t){let s=!1;try{const i=await(e?.loadData());if(i&&"object"==typeof i){const n="version";if("1.0.0"===i[n]){const a="matchPriorityAdjustments";if(Object.prototype.hasOwnProperty.call(i,a)){const e=i[a],s={};i[a]={isEnabled:!!i.enableMatchPriorityAdjustments,adjustments:s},delete i.enableMatchPriorityAdjustments,Object.entries(e).forEach((([e,i])=>{const n=t.matchPriorityAdjustments.adjustments[e]?.label??"";s[e]={value:i,label:n}}))}const o="quickFilters";if(Object.prototype.hasOwnProperty.call(i,o)){const e="facetList",t=i[o],s=t[e],n=s?.reduce(((e,t)=>(e[t.id]=t,e)),{});t[e]=n}i[n]="2.0.0",await(e?.saveData(i)),s=!0}}}catch(e){O("Error transforming data.json to v2.0.0",e)}return s}}class ne{app;mainSettingsTab;config;constructor(e,t,s){this.app=e,this.mainSettingsTab=t,this.config=s}createSetting(e,t,s){let i;return e instanceof a.SettingGroup?e.addSetting((e=>{i=e,e.setName(t),e.setDesc(s)})):(i=new a.Setting(e),i.setName(t),i.setDesc(s)),i}withSetting(e,t,s,i){let n;return e instanceof a.SettingGroup?e.addSetting((e=>{n=e,e.setName(t).setDesc(s),i(e)})):(n=this.createSetting(e,t,s),i(n)),n}createOnChangeHandler(e,t){return s=>{t?t(s,this.config):e&&this.saveChangesToConfig(e,s)}}addSectionTitle(e,t,s=""){const i=this.createSetting(e,t,s);return i.setHeading(),i}addTextSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.addText((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{const t=e.length?e:i;this.saveChangesToConfig(n,t)}))}))}))}addToggleSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.addToggle((e=>{e.setValue(i),e.onChange(this.createOnChangeHandler(n,a))}))}))}addTextAreaSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addTextArea((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{if(o)o(e,this.config);else{const t=e.length?e:i,s=Array.isArray(this.config[n]);this.saveChangesToConfig(n,s?t.split("\n"):t)}}))}))}))}addDropdownSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addDropdown((e=>{e.addOptions(n),e.setValue(i),e.onChange(this.createOnChangeHandler(a,o))}))}))}addSliderSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addExtraButton((t=>(t.setIcon("lucide-rotate-ccw"),t.setTooltip("Restore default"),t.onClick((()=>e.components[1].setValue(n[3]))),t))),e.addSlider((e=>{e.setLimits(n[0],n[1],n[2]),e.setValue(i),e.setDynamicTooltip(),e.onChange(this.createOnChangeHandler(a,o))}))}))}saveChangesToConfig(e,t){if(e){const{config:s}=this;s[e]=t,s.save()}}showErrorPopup(e,t,s){const i=new a.Modal(this.app);i.titleEl.setText(e),i.contentEl.empty(),i.contentEl.createSpan({text:t}),i.contentEl.createEl("br"),i.contentEl.createEl("br"),s.forEach(((e,t)=>{t>0&&i.contentEl.createEl("br"),e.forEach(((e,t)=>{t>0&&i.contentEl.createEl("br");const s={text:e.text};void 0!==e.cls&&(s.cls=e.cls),i.contentEl.createSpan(s)}))})),i.open()}}class ae extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Bookmarks List Mode"),this.addTextSetting(e,"Bookmarks list mode trigger","Character that will trigger bookmarks list mode in the switcher",t.bookmarksListCommand,"bookmarksListCommand",t.bookmarksListPlaceholderText)}}class oe extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Command List Mode"),this.addTextSetting(e,"Command list mode trigger","Character that will trigger command list mode in the switcher",t.commandListCommand,"commandListCommand",t.commandListPlaceholderText),this.addSliderSetting(e,"Max recent commands","The maximum number of commands to save in the recent list.",t.maxRecentCommands,[0,75,1,25],"maxRecentCommands"),this.showRecentCommandDisplayOrder(e,t)}showRecentCommandDisplayOrder(e,t){this.addDropdownSetting(e,"Recent commands display order","Select the sort order for recently used commands.",t.recentCommandDisplayOrder,{desc:"Most recent first (descending)",asc:"Most recent last (ascending)"},"recentCommandDisplayOrder")}}class re extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Related Items List Mode"),this.addTextSetting(e,"Related Items list mode trigger","Character that will trigger related items list mode in the switcher. This triggers a display of Related Items for the source file of the currently selected (highlighted) suggestion in the switcher. If there is not a suggestion, display results for the active editor.",t.relatedItemsListCommand,"relatedItemsListCommand",t.relatedItemsListPlaceholderText),this.addTextSetting(e,"Related Items list mode trigger - Active editor only","Character that will trigger related items list mode in the switcher. This always triggers a display of Related Items for the active editor only.",t.relatedItemsListActiveEditorCommand,"relatedItemsListActiveEditorCommand",t.relatedItemsListActiveEditorCommand),this.showEnabledRelatedItems(e,t),this.addToggleSetting(e,"Exclude open files","Enable, related files which are already open will not be displayed in the list. Disabled, All related files will be displayed in the list.",t.excludeOpenRelatedFiles,"excludeOpenRelatedFiles")}showEnabledRelatedItems(e,t){const s=Object.values(c).sort(),i=s.join(", "),n=`The types of related items to show in the list. Add one type per line. Available types: ${i}`;this.createSetting(e,"Show related item types",n).addTextArea((e=>{e.setValue(t.enabledRelatedItems.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const n=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=[...new Set(n)].filter((e=>!s.includes(e)));a?.length?this.showErrorPopup("Invalid related item type",`Changes not saved. Available relation types are: ${i}. The following types are invalid:`,a.map((e=>[{text:e}]))):(t.enabledRelatedItems=n,t.save())}))}))}}class le extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"General"),this.addToggleSetting(e,"Default to open in new tab","When enabled, navigating to un-opened files will open a new editor tab whenever possible (as if cmd/ctrl were held). When the file is already open, the existing tab will be activated. This overrides all other tab settings.",t.onOpenPreferNewTab,"onOpenPreferNewTab"),this.showLauncherButtonOverrides(e,t),this.showEnabledRibbonCommands(e,t),this.addToggleSetting(e,"Show indicator icons","Display icons to indicate that an item is recent, bookmarked, etc..",t.showOptionalIndicatorIcons,"showOptionalIndicatorIcons"),this.addToggleSetting(e,"Display mode trigger instructions","When enabled, the trigger key for each mode will be displayed in the instructions section of the Switcher.",t.showModeTriggerInstructions,"showModeTriggerInstructions"),this.showStandardModeOverrides(e,t),this.showPathDisplayGroup(e,t),this.showPreferredSourceForTitle(e,t),this.showTagDisplaySettings(e,t),this.showQuickOpen(e,t),this.showRenderMarkdownContentAsHTML(e,t),this.addTextSetting(e,"Mode trigger escape character","Character to indicate that a mode trigger character should be treated just as a normal text.",t.escapeCmdChar,"escapeCmdChar"),this.addToggleSetting(e,"Allow Backspace key to close the Switcher","When the search box is empty, pressing the backspace key will close Switcher++.",t.shouldCloseModalOnBackspace,"shouldCloseModalOnBackspace"),this.showRestoreInput(e,t),this.showInsertLinkInEditor(e,t),this.showResetFacetEachSession(e,t),this.showMatchPriorityAdjustments(e,t)}showPreferredSourceForTitle(e,t){const s=new a.SettingGroup(e);this.addDropdownSetting(s,"Preferred suggestion title source",'The preferred source to use for the "title" text that will be searched and displayed for file based suggestions',t.preferredSourceForTitle,{H1:"First H₁ heading",Default:"Default",FrontMatter:"Frontmatter property"},"preferredSourceForTitle",((e,t)=>{t.preferredSourceForTitle=e,t.save(),this.mainSettingsTab.display()})),"FrontMatter"===t.preferredSourceForTitle&&this.addTextSetting(s,"Frontmatter property path",'The path to the frontmatter property to use as the title. Use dot notation for nested properties (e.g., "title" or "meta.display_name"). The property value must be a string, number, or boolean. If the property doesn\'t exist or has an invalid type, the default filename will be used.',t.frontmatterTitleProperty,"frontmatterTitleProperty","title")}showPathDisplayFormat(t,s){const i={};i[e.None.toString()]="Hide path",i[e.Full.toString()]="Full path",i[e.FolderOnly.toString()]="Only parent folder",i[e.FolderWithFilename.toString()]="Parent folder & filename",i[e.FolderPathFilenameOptional.toString()]="Parent folder path (filename optional)",this.addDropdownSetting(t,"Preferred file path display format","The preferred way to display file paths in suggestions",s.pathDisplayFormat.toString(),i,null,((e,t)=>{t.pathDisplayFormat=Number(e),t.save()}))}showPathDisplayGroup(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Path Display Settings","Configure how file paths are displayed in suggestions."),this.showPathDisplayFormat(s,t),this.addToggleSetting(s,"Hide path for root items","When enabled, path information will be hidden for items at the root of the vault.",t.hidePathIfRoot,"hidePathIfRoot")}showStandardModeOverrides(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Standard Mode Overrides","Configure how Switcher++ overrides the default Obsidian Switcher behavior in Standard mode."),this.addToggleSetting(s,"Override Standard mode file open behavior","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to inject custom file open behavior.",t.overrideStandardModeBehaviors,"overrideStandardModeBehaviors"),this.addToggleSetting(s,"Override Standard mode rendering","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to render suggestions as multi-line.",t.overrideStandardModeRendering,"overrideStandardModeRendering")}showRestoreInput(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Restore Previous Input","Configure whether to restore the last typed input when launching the Switcher."),this.addToggleSetting(s,"Restore previous input in Command Mode","When enabled, restore the last typed input in Command Mode when launched via global command hotkey.",t.preserveCommandPaletteLastInput,"preserveCommandPaletteLastInput"),this.addToggleSetting(s,"Restore previous input","When enabled, restore the last typed input when launched via global command hotkey.",t.preserveQuickSwitcherLastInput,"preserveQuickSwitcherLastInput")}showEnabledRibbonCommands(e,t){const s=E(),i=s.join(" "),n=`Display an icon in the ribbon menu to launch specific modes. Add one mode per line. Available modes: ${i}`;this.createSetting(e,"Show ribbon icons",n).addTextArea((e=>{e.setValue(t.enabledRibbonCommands.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const n=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=Array.from(new Set(n)).filter((e=>!s.includes(e)));a.length?this.showErrorPopup("Invalid mode",`Changes not saved. Available modes are: ${i}. The following are invalid:`,a.map((e=>[{text:e}]))):(t.enabledRibbonCommands=n,t.save(),this.mainSettingsTab.plugin.registerRibbonCommandIcons())}))}))}showLauncherButtonOverrides(e,t){const{mobileLauncher:s}=t,i=new a.SettingGroup(e),n="disabled",o={[n]:"Do not override"},r=E();r.forEach((e=>{o[e]=e}));let l=n;s.isEnabled&&r.includes(s.modeString)&&(l=s.modeString),this.addDropdownSetting(i,"New tab and mobile launcher buttons",'Select the Mode to launch Switcher++ in from the empty tab page and mobile navigation Bar button, or select "Do not override" to disable the feature.',l,o,null,((e,t)=>{const s=e!==n;t.mobileLauncher.isEnabled=s,s&&(t.mobileLauncher.modeString=e),t.save(),this.mainSettingsTab.display(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(s)})),s.isEnabled&&(this.addToggleSetting(i,"Override default Switcher launch button on mobile platforms",'When enabled, override the "🔍" button (in the Navigation Bar) on mobile platforms to launch Switcher++ instead of the default system switcher.',s.isMobileButtonEnabled,null,((e,t)=>{t.mobileLauncher.isMobileButtonEnabled=e,t.save(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(t.mobileLauncher.isEnabled)})),this.addToggleSetting(i,'Display launch button on the "New tab" page','When enabled, a button to launch Switcher++ using the selected mode above will be added to the default Obsidian "New tab" page.',s.isEmptyTabButtonEnabled,null,((e,t)=>{t.mobileLauncher.isEmptyTabButtonEnabled=e,t.save(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(t.mobileLauncher.isEnabled)})))}showMatchPriorityAdjustments(e,t){const{matchPriorityAdjustments:{isEnabled:s,adjustments:i,fileExtAdjustments:n}}=t,o=new a.SettingGroup(e);this.addToggleSetting(o,"Result priority adjustments","Artificially increase the match score of the specified item types by a fixed percentage so they appear higher in the results list (does not apply to Standard Mode).",s,null,((e,t)=>{t.matchPriorityAdjustments.isEnabled=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Result Priority Adjustments" setting. ',e)))})),s&&[i,n].forEach((e=>{Object.entries(e).forEach((([t,s])=>{const{value:i,label:n}=s;this.addSliderSetting(o,n,s.desc??"",i,[-1,1,.05,0],null,((s,i)=>{e[t].value=s,i.save()}))}))}))}showResetFacetEachSession(e,t){this.addToggleSetting(e,"Reset active Quick Filters","When enabled, the switcher will reset all Quick Filters back to inactive for each session.",t.quickFilters.shouldResetActiveFacets,null,((e,t)=>{t.quickFilters.shouldResetActiveFacets=e,t.save()}))}showRenderMarkdownContentAsHTML(e,t){const{renderMarkdownContentInSuggestions:s}=t,i=new a.SettingGroup(e),n=this.addToggleSetting(i,"Display markdown content as Live Preview",'When enabled, markdown content in symbol suggestions will be rendered as HTML similar to the Obsidian "Live Preview" display. When disabled, content will be rendered as raw text. Use the "toggle preview (selected item)" hotkey to toggle the display for individual items.',s.isEnabled,null,((e,t)=>{const{renderMarkdownContentInSuggestions:s}=t;s.isEnabled=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Display markdown content as Live Preview" setting. ',e)))}));if(n?.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"}),s.isEnabled){[{name:"Headings",property:"renderHeadings",description:"Render headings as HTML"},{name:"Links",property:"renderLinks",description:"Render links as HTML"},{name:"Tags",property:"renderTags",description:"Render tags as HTML"},{name:"Callouts",property:"renderCallouts",description:"Render callouts as HTML"}].forEach((({name:e,property:t,description:n})=>{this.addToggleSetting(i,e,n,s[t],null,((e,s)=>{s.renderMarkdownContentInSuggestions[t]=e,s.save()}))}))}}showInsertLinkInEditor(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Insert link in editor","Configure alias options when inserting links into the editor."),this.addToggleSetting(s,"Use filename as alias","When enabled, the file basename will be set as the link alias.",t.insertLinkInEditor.useBasenameAsAlias,null,((e,t)=>{t.insertLinkInEditor.useBasenameAsAlias=e,t.save()})),this.addToggleSetting(s,"Use heading as alias",'When enabled, the file heading will be set as the link alias. This overrides the "use filename as alias" setting.',t.insertLinkInEditor.useHeadingAsAlias,null,((e,t)=>{t.insertLinkInEditor.useHeadingAsAlias=e,t.save()}))}showQuickOpen(e,t){this.addToggleSetting(e,"Enable quick open hotkeys for top results","When enabled, hotkeys will be defined for each of the top N results displayed in the Switcher. These hotkeys can be used to quickly open the associated suggestion directly. when disabled, no hotkeys are defined.",t.quickOpen.isEnabled,null,((e,t)=>{t.quickOpen.isEnabled=e,t.save()}))}showTagDisplaySettings(e,t){const{showTagsInSuggestions:s}=t,i=new a.SettingGroup(e);if(this.addToggleSetting(i,"Show tags in suggestions","When enabled, tags associated with a file will be displayed in suggestions.",s,null,((e,t)=>{t.showTagsInSuggestions=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Show tags in suggestions" setting. ',e)))})),s){const e={[n.Both]:"Both",[n.Inline]:"Inline only",[n.Frontmatter]:"Frontmatter only"};this.addDropdownSetting(i,"Tag source","Select which tags to display: inline tags (in document body), frontmatter tags, or both.",t.tagSource,e,null,((e,t)=>{t.tagSource=e,t.save()})),this.addTextAreaSetting(i,"Excluded tags","Tags to exclude from display, one per line. Tags should be entered without the # prefix.",t.excludeTagsFromDisplay.join("\n"),null,"tag1\ntag2\ntag3",((e,t)=>{const s=e.split("\n").map((e=>e.trim())).filter((e=>e.length>0));t.excludeTagsFromDisplay=s,t.save()})),this.addSliderSetting(i,"Max tags to display","Maximum number of tags to show per suggestion. Set to 0 for unlimited.",t.maxTagsToDisplay,[0,20,1,5],"maxTagsToDisplay"),this.addTextSetting(i,"Tag separator","The string used to separate multiple tags in the display.",t.tagDisplaySeparator,"tagDisplaySeparator",", "),this.addToggleSetting(i,"Remove # prefix from tags","When enabled, the # prefix will be removed from tags when displayed.",t.removeHashPrefixFromTags,"removeHashPrefixFromTags")}}}class de extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Workspace List Mode"),this.addTextSetting(e,"Workspace list mode trigger","Character that will trigger workspace list mode in the switcher",t.workspaceListCommand,"workspaceListCommand",t.workspaceListPlaceholderText)}}class ce extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Editor List Mode"),this.addTextSetting(e,"Editor list mode trigger","Character that will trigger editor list mode in the switcher",t.editorListCommand,"editorListCommand",t.editorListPlaceholderText),this.showIncludeSidePanelViews(e,t),this.addToggleSetting(e,"Order default editor list by most recently accessed","When there is no search term, order the list of editors by most recent access time.",t.orderEditorListByAccessTime,"orderEditorListByAccessTime")}showIncludeSidePanelViews(e,t){const s=`When in Editor list mode, show the following view types from the side panels. Add one view type per line. Available view types: ${Object.keys(this.app.viewRegistry.viewByType).sort().join(" ")}`;this.addTextAreaSetting(e,"Include side panel views",s,t.includeSidePanelViewTypes.join("\n"),"includeSidePanelViewTypes",t.includeSidePanelViewTypesPlaceholder)}}class he extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Headings List Mode"),this.addTextSetting(e,"Headings list mode trigger","Character that will trigger headings list mode in the switcher",t.headingsListCommand,"headingsListCommand",t.headingsListPlaceholderText),this.addSliderSetting(e,"Max recent files to show","The maximum number of recent files to show when there is no search term",t.maxRecentFileSuggestionsOnInit,[0,75,1,25],"maxRecentFileSuggestionsOnInit"),this.showFileExtAllowList(e,t),this.addToggleSetting(e,"Search Filenames","Enabled, search and show suggestions for filenames. Disabled, Don't search through filenames (except for fallback searches)",t.shouldSearchFilenames,"shouldSearchFilenames"),this.addToggleSetting(e,"Search Bookmarks","Enabled, search and show suggestions for Bookmarks. Disabled, Don't search through Bookmarks",t.shouldSearchBookmarks,"shouldSearchBookmarks"),this.showHeadingSettings(e,t),this.showExclusionsGroup(e,t)}showHeadingSettings(e,t){const s=t.shouldSearchHeadings,i=new a.SettingGroup(e);this.addToggleSetting(i,"Search Headings","Enabled, search and show suggestions for Headings. Disabled, Don't search through Headings",s,null,((e,t)=>{t.shouldSearchHeadings=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Search Headings" setting. ',e)))})),s&&(this.addToggleSetting(i,"Turn off filename fallback","Enabled, strictly search through only the headings contained in the file. Do not fallback to searching the filename when an H1 match is not found. Disabled, fallback to searching against the filename when there is not a match in the first H1 contained in the file.",t.strictHeadingsOnly,"strictHeadingsOnly"),this.addToggleSetting(i,"Search all headings","Enabled, search through all headings contained in each file. Disabled, only search through the first H1 in each file.",t.searchAllHeadings,"searchAllHeadings"),this.showBreadcrumbSettings(i,t))}showFileExtAllowList(e,t){this.createSetting(e,"File extension override",'Override the "Show attachments" and the "Show all file types" builtin, system Switcher settings and always search files with the listed extensions. Add one path per line. For example to add ".canvas" file extension, just add "canvas".').addTextArea((e=>{e.setValue(t.fileExtAllowList.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const s=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0));t.fileExtAllowList=s,t.save()}))}))}showExclusionsGroup(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Exclusions","Configure which folders and files should be excluded from search results in Headings list mode."),this.showExcludeFolders(s,t),this.addToggleSetting(s,'Hide Obsidian "Excluded files"','Enabled, do not display suggestions for files that are in Obsidian\'s "Options > Files & Links > Excluded files" list. Disabled, suggestions for those files will be displayed but downranked.',t.excludeObsidianIgnoredFiles,"excludeObsidianIgnoredFiles")}showExcludeFolders(e,t){const s="Exclude folders";this.createSetting(e,s,"When in Headings list mode, folder path that match any regex listed here will not be searched for suggestions. Path should start from the Vault Root. Add one path per line.").addTextArea((e=>{e.setValue(t.excludeFolders.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const i=e.getValue().split("\n").filter((e=>e.length>0));this.validateExcludeFolderList(s,i)&&(t.excludeFolders=i,t.save())}))}))}showBreadcrumbSettings(e,t){this.addToggleSetting(e,"Show heading breadcrumbs","Enabled, display the hierarchical path of parent headings leading to each heading suggestion.",t.showHeadingBreadcrumbs,"showHeadingBreadcrumbs"),this.addTextSetting(e,"Breadcrumb separator","The string used to separate heading levels in breadcrumbs",t.headingBreadcrumbSeparator,"headingBreadcrumbSeparator"),this.addSliderSetting(e,"Max breadcrumb depth","Maximum number of heading levels to show in breadcrumbs. Set to 0 for unlimited depth.",t.maxBreadcrumbDepth,[0,6,1,0],"maxBreadcrumbDepth")}validateExcludeFolderList(e,t){let s=!0;const i=[];for(const e of t)try{new RegExp(e)}catch(t){i.push({regex:e,error:t}),s=!1}return s||this.showErrorPopup(e,"Changes not saved. The following regex contain errors:",i.map((({regex:e,error:t})=>[{text:e,cls:"qsp-warning"},{text:t.toString()}]))),s}}class me extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Symbol List Mode"),this.addTextSetting(e,"Symbol list mode trigger","Character that will trigger symbol list mode in the switcher. This triggers a display of Symbols for the source file of the currently selected (highlighted) suggestion in the switcher. If there is not a suggestion, display results for the active editor.",t.symbolListCommand,"symbolListCommand",t.symbolListPlaceholderText),this.addTextSetting(e,"Symbol list mode trigger - Active editor only","Character that will trigger symbol list mode in the switcher. This always triggers a display of Symbols for the active editor only.",t.symbolListActiveEditorCommand,"symbolListActiveEditorCommand",t.symbolListActiveEditorCommand),this.addToggleSetting(e,"List symbols as indented outline","Enabled, symbols will be displayed in the (line) order they appear in the source text, indented under any preceding heading. Disabled, symbols will be grouped by type: Headings, Tags, Links, Embeds.",t.symbolsInLineOrder,"symbolsInLineOrder"),this.addToggleSetting(e,"Auto-select nearest heading","Enabled, in an unfiltered symbol list, select the closest preceding Heading to the current cursor position. Disabled, the first symbol in the list is selected.",t.selectNearestHeading,"selectNearestHeading"),this.addToggleSetting(e,"Show heading breadcrumbs in Symbol mode","Enabled, display the hierarchical path of parent headings when showing heading symbols in Symbol mode.",t.showHeadingBreadcrumbsInSymbolMode,"showHeadingBreadcrumbsInSymbolMode"),this.showEnableSymbolTypesToggle(e,t),this.showEnableLinksToggle(e,t),this.showSymbolTabNavigationBehavior(e,t)}showSymbolTabNavigationBehavior(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Symbol Tab navigation behavior","Configure how symbols are opened when navigating from the symbol list."),this.addToggleSetting(s,"Open Symbols in new tab","Enabled, always open a new tab when navigating to Symbols. Disabled, navigate in an already open tab (if one exists).",t.alwaysNewTabForSymbols,"alwaysNewTabForSymbols"),this.addToggleSetting(s,"Open Symbols in active tab on mobile devices","Enabled, navigate to the target file and symbol in the active editor tab. Disabled, open a new tab when navigating to Symbols, even on mobile devices.",t.useActiveTabForSymbolsOnMobile,"useActiveTabForSymbolsOnMobile")}showEnableSymbolTypesToggle(e,t){[["Show Headings",s.Heading],["Show Tags",s.Tag],["Show Embeds",s.Embed],["Show Callouts",s.Callout]].forEach((([s,i])=>{this.addToggleSetting(e,s,"",t.isSymbolTypeEnabled(i),null,(e=>{t.setSymbolTypeEnabled(i,e),t.save()}))}))}showEnableLinksToggle(e,t){const n=t.isSymbolTypeEnabled(s.Link),o=new a.SettingGroup(e);if(this.addToggleSetting(o,"Show Links","",n,null,(e=>{t.setSymbolTypeEnabled(s.Link,e),t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Show Links" setting. ',e)))})),n){[["Links to headings",i.Heading],["Links to blocks",i.Block]].forEach((([e,s])=>{const i=(t.excludeLinkSubTypes&s)===s;this.addToggleSetting(o,e,"",!i,null,(e=>this.saveEnableSubLinkChange(s,e)))}))}}saveEnableSubLinkChange(e,t){const{config:s}=this;let i=s.excludeLinkSubTypes;t?i&=~e:i|=e,s.excludeLinkSubTypes=i,s.save()}}class ue extends ne{display(e){const{config:t}=this,s=this.addSectionTitle(e,"Vault List Mode");s.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"}),this.addTextSetting(e,"Vault list mode trigger","Character that will trigger vault list mode in the switcher",t.vaultListCommand,"vaultListCommand",t.vaultListPlaceholderText)}}class ge extends a.PluginSettingTab{plugin;config;constructor(e,t,s){super(e,t),this.plugin=t,this.config=s,this.containerEl.addClass("qsp-settings-container")}display(){const{containerEl:e}=this,t=[le,me,he,ce,re,ae,oe,de,ue];e.empty(),t.forEach((e=>{this.displayTabSection(e)}))}displayTabSection(e){const{app:t,config:s,containerEl:i}=this;new e(t,this,s).display(i)}}class pe{inputText;mode;parsedCommands;_cleanInput=null;static get defaultParsedCommand(){return{isValidated:!1,index:-1,parsedInput:null}}sessionOpts;currentWorkspaceEnvList={openWorkspaceLeaves:new Set,openWorkspaceFiles:new Set,fileBookmarks:new Map,nonFileBookmarks:new Set,mostRecentFiles:new Set,attachmentFileExtensions:new Set};get parsedInputQuery(){const e=(this.parsedCommand()?.parsedInput??"").trim().toLowerCase();return{query:e,hasSearchTerm:!!e.length}}get cleanInput(){return this._cleanInput??this.inputText}set cleanInput(e){this._cleanInput=e}constructor(e="",s=t.Standard,i){this.inputText=e,this.mode=s,this.sessionOpts=i??{};const n=F();this.parsedCommands={},E().forEach((e=>{const s=t[e];n.includes(s)?this.parsedCommands[s]={...pe.defaultParsedCommand,source:null}:this.parsedCommands[s]=pe.defaultParsedCommand}))}parsedCommand(e){return e=e??this.mode,this.parsedCommands[e]}}class fe{app;settings;facets;constructor(e,t){this.app=e,this.settings=t}reset(){}onNoResultsCreateAction(e,t){return!1}getFacets(e){if(!this.facets){const t=this.settings?.quickFilters?.facetList;t&&(this.facets=Object.values(t).filter((t=>t.mode===e)))}return this.facets??[]}getAvailableFacets(e){return this.getFacets(e.mode).filter((e=>e.isAvailable))}activateFacet(e,t){e.forEach((e=>e.isActive=t)),this.settings.quickFilters.shouldResetActiveFacets||this.settings.save()}getActiveFacetIds(e){const t=this.getAvailableFacets(e).filter((e=>e.isActive)).map((e=>e.id));return new Set(t)}isFacetedWith(e,t){const s=!!e.size;return s&&e.has(t)||!s}getEditorInfo(e){const{excludeViewTypes:t}=this.settings;let s=null,i=!1,n=null;if(e){s=H(e),n=this.getCursorPosition(e);i=!t.includes(e.view.getViewType())&&!!s}return{isValidSource:i,leaf:e,file:s,suggestion:null,cursor:n}}getSuggestionInfo(e){const t=this.getSourceInfoFromSuggestion(e);let s=t.leaf;t.isValidSource&&({leaf:s}=this.findMatchingLeaf(t.file,t.leaf));const i=this.getCursorPosition(s);return{...t,leaf:s,cursor:i}}getSourceInfoFromSuggestion(e){let t=null,s=null;const i=[l.SymbolList,l.Unresolved,l.WorkspaceList,l.CommandList,l.VaultList];e&&!i.includes(e.type)&&(t=e.file),m(e,"type",l.EditorList)&&(s=e.item);return{isValidSource:!!t,leaf:s,file:t,suggestion:e}}getCursorPosition(e){let t=null;if(K(e,"markdown")){const s=e.view;"preview"!==s.getMode()&&(t=s.editor.getCursor("head"))}return t}getTitleText(e){const t=function(e){let t=null;if(e){const{path:s}=e;if(t=s,"md"===e.extension){const e=s.lastIndexOf(".");-1!==e&&e!==s.length-1&&0!==e&&(t=s.slice(0,e))}}return t}(e),s=this.getFirstH1(e);return s?.heading??t}getFirstH1(e){return fe.getFirstH1(e,this.app.metadataCache)}static getFirstH1(e,t){let s=null;const i=t.getFileCache(e)?.headings?.filter((e=>1===e.level))??[];return i.length&&(s=i.reduce(((e,t)=>{const{line:s}=t.position.start;return s0?i.trim():"number"==typeof i||"boolean"==typeof i?String(i):null}findMatchingLeaf(e,t,s=!1){let i=null;const n=!!t,{settings:{referenceViews:a,excludeViewTypes:o,includeSidePanelViewTypes:r}}=this,l=i=>{let o=!1;if(i?.view){const r=a.includes(i.view.getViewType()),l=s||!r,d=n&&a.includes(t.view.getViewType());l&&(o=!n||!s&&d?H(i)===e:i===t)}return o},d=this.getActiveLeaf();if(l(d))i=d;else{const e=this.getOpenLeaves(o,r);i=[t,...e].find(l)}return{leaf:i??null,file:e,suggestion:null,isValidSource:!1}}extractTabNavigationType(e,t,s){const i=e?.shiftKey?"horizontal":"vertical",n=e?.key;let o=a.Keymap.isModEvent(e)??!1;return!0!==o&&"tab"!==o||("o"===n?o="window":"\\"===n&&(o="split")),o=this.applyTabCreationPreferences(o,t,s),{navType:o,splitDirection:i}}applyTabCreationPreferences(e,s=!1,i){let n=e;const{onOpenPreferNewTab:o,alwaysNewTabForSymbols:r,useActiveTabForSymbolsOnMobile:l}=this.settings;return!1===e&&(o?n=!s:i===t.SymbolList&&(n=a.Platform.isMobile?!l:r)),n}isMainPanelLeaf(e){const{workspace:t}=this.app,s=e?.getRoot();return s===t.rootSplit||s===t.floatingSplit}async activateLeaf(e,t){const{workspace:s}=this.app;try{await s.revealLeaf(e),s.setActiveLeaf(e,{focus:!0}),e.view.setEphemeralState({focus:!0,...t})}catch(t){const s=e?.getDisplayText();A(`Error activating WorkspaceLeaf with title: ${s}`,t)}}getOpenLeaves(e,t,s){const i=[];return this.app.workspace.iterateAllLeaves((s=>{const n=s?.view?.getViewType();this.isMainPanelLeaf(s)?e?.includes(n)||i.push(s):t?.includes(n)&&i.push(s)})),s?.orderByAccessTime&&i.sort(((e,t)=>{const s=e?.activeTime??0;return(t?.activeTime??0)-s})),i}static async openFileInLeaf(e,t,s,i,n="vertical"){const a="split"===t?s.getLeaf(t,n):s.getLeaf(t);await a.openFile(e,i)}navigateToLeafOrOpenFile(e,t,s,i,n,a,o=!1){this.navigateToLeafOrOpenFileAsync(e,t,i,n,a,o).catch((e=>{A(`Error navigating to open file. ${s}`,e)}))}async navigateToLeafOrOpenFileAsync(e,t,s,i,n,a=!1){const{leaf:o}=this.findMatchingLeaf(t,i,a),r=!!o,{navType:l,splitDirection:d}=this.extractTabNavigationType(e,r,n);await this.activateLeafOrOpenFile(l,t,o,s,d)}async activateLeafOrOpenFile(e,t,s,i,n){if(i=i??this.getOpenViewActiveState(),s&&!1===e){const e=i?.eState;await this.activateLeaf(s,e)}else await fe.openFileInLeaf(t,e,this.app.workspace,i,n)}renderPath(t,s,i,n,a){if(!t||!s)return;const o=s.parent.isRoot();let r=this.settings.pathDisplayFormat,l=r===e.None||o&&this.settings.hidePathIfRoot;if(a&&(r=e.FolderPathFilenameOptional,l=!1),!l){const e=this.getPathDisplayText(s,r,i);this.renderBreadcrumb(t,e,"lucide-folder-open",n,["qsp-path"])}}renderBreadcrumb(e,t,s,i,n){if(!e||!t)return;const o=["suggestion-note","qsp-note"];n&&o.push(...n);const r=e.createDiv({cls:o}),l=r.createSpan({cls:["qsp-breadcrumb-indicator"]});a.setIcon(l,s);const d=r.createSpan({cls:"qsp-breadcrumb"});a.renderResults(d,t,i)}renderHeadingBreadcrumbs(e,t,s,i){if(!((i??this.settings.showHeadingBreadcrumbs)&&e&&t&&s))return;if(1===t.level)return;const n=function(e,t,s){const i=s.getFileCache(t)?.headings??[],n=e.position.start.line,a=new Map;for(const t of i){const s=t.position.start.line;if(s>=n)continue;if(t.level>=e.level)continue;const i=a.get(t.level);(!i||s>i.position.start.line)&&a.set(t.level,t)}const o=[];for(let t=1;t0&&n.length>a&&o.push("qsp-truncated");const r=function(e,t=" > ",s=0){let i=e;return s>0&&e.length>s&&(i=e.slice(-s)),i.map((e=>e.heading)).join(t)}(n,this.settings.headingBreadcrumbSeparator,a);r&&this.renderBreadcrumb(e,r,"lucide-heading",void 0,o)}renderTags(e,t){const{settings:s}=this;if(!s.showTagsInSuggestions||!e||!t)return;const i=new Set(s.excludeTagsFromDisplay),a=function(e,t,s=n.Both,i){const a=t.getFileCache(e);if(!a)return[];const o=new Set;s!==n.Inline&&s!==n.Both||(a.tags??[]).forEach((e=>o.add(e.tag)));s!==n.Frontmatter&&s!==n.Both||h.getTags(a.frontmatter).forEach((e=>{o.add(e.startsWith("#")?e:`#${e}`)}));let r=Array.from(o);return i&&i.size>0&&(r=r.filter((e=>{const t=e.startsWith("#")?e.slice(1):e;return!i.has(t)}))),r.sort()}(t,this.app.metadataCache,s.tagSource,i);if(0===a.length)return;let o=a;const r=["qsp-tags-breadcrumbs"];s.maxTagsToDisplay>0&&a.length>s.maxTagsToDisplay&&(o=a.slice(0,s.maxTagsToDisplay),r.push("qsp-truncated"));const l=function(e,t=" ",s=!1){return e&&0!==e.length?(s?e.map((e=>e.startsWith("#")?e.slice(1):e)):e).join(t):""}(o,s.tagDisplaySeparator,s.removeHashPrefixFromTags);l&&this.renderBreadcrumb(e,l,"lucide-tags",void 0,r)}getPathDisplayText(t,s,i){let n="";if(t){const{parent:o}=t,r=o.name,l=o.isRoot(),d=this.app.vault.getRoot().path;switch(s){case e.FolderWithFilename:n=l?`${t.name}`:a.normalizePath(`${r}/${t.name}`);break;case e.FolderOnly:n=l?d:r;break;case e.Full:n=t.path;break;case e.FolderPathFilenameOptional:i?(n=o.path,l||(n+=d)):n=this.getPathDisplayText(t,e.Full)}}return n}renderContent(e,t,s,i){const{contentEl:n,titleEl:o}=fe.createContentStructureElements(e);return a.renderResults(o,t,s,i),n}static createContentStructureElements(e){const t=e.createDiv({cls:["suggestion-content","qsp-content"]}),s=t.createDiv({cls:["suggestion-title","qsp-title"]});return{contentEl:t,titleEl:s}}static renderMarkdownContentAsync(e,t,s,i){fe.renderMarkdownContent(e,t,s,i,q.getRootComponent()).catch((e=>{O("Error rendering markdown to html. ",e,`content: ${s}`)}))}static async renderMarkdownContent(e,t,s,i,n){const o=t.createDiv({cls:["qsp-rendered-container"]});if(await a.MarkdownRenderer.render(e,s,o,i,n),1===o.childNodes.length&&"P"===o.firstChild.nodeName){const e=o.firstChild;e.replaceWith(...Array.from(e.childNodes))}return o}addClassesToSuggestionContainer(e,t){const s=["mod-complex"];t&&s.push(...t),e?.addClasses(s)}splitSearchMatchesAtBasename(e,t){let s=null,i=null;const n=(e,t)=>{e.forEach((e=>{e[0]-=t,e[1]-=t}))};if(e&&t?.matches){const a=e.path.lastIndexOf(e.basename);if(a>=0){const{matches:e,score:o}=t,r=e[0][0],l=e[e.length-1][1];if(r>=a)s=t,n(s.matches,a);else if(l<=a)i=t;else{let t=e.length;for(;t--;){const r=e[t][0],l=t+1;if(e[t][1]<=a){i={score:o,matches:e.slice(0,l)},s={score:o,matches:e.slice(l)},n(s.matches,a);break}if(r{t=t??o;let s=0;return Object.prototype.hasOwnProperty.call(t,e)&&(s=Number(t[e]?.value)),isNaN(s)?0:s},h=(t,s)=>{let i=0;return(null!==t&&t===n||e[s])&&(i=c(s)),i};d+=h(l.Bookmark,"isBookmarked"),d+=h(l.EditorList,"isOpenInEditor"),d+=h(null,"isRecent"),d+=h(null,"isAttachment"),d+=c(a?.extension,r),g(e)&&(d+=c(`h${e.item?.level}`));const m=n.toString();d+=c(m),i.score+=Math.abs(i.score)/100*(100*d)}}return e}static updateWorkspaceEnvListStatus(e,t){if(e&&t?.file){const{file:s}=t;t.isOpenInEditor=e.openWorkspaceFiles?.has(s),t.isRecent=e.mostRecentFiles?.has(s),t.isBookmarked=e.fileBookmarks?.has(s),t.isAttachment=e.attachmentFileExtensions?.has(s.extension)}return t}renderFileCreationSuggestion(e,t){this.addClassesToSuggestionContainer(e);const s=this.renderContent(e,t,null),i=this.createFlairContainer(e);return i?.createSpan({cls:"suggestion-hotkey",text:"Enter to create"}),s}createFile(e,t){const{workspace:s}=this.app,{navType:i}=this.extractTabNavigationType(t),n=s.getActiveViewOfType(a.FileView);let o="";n?.file&&(o=n.file.path),s.openLinkText(e,o,i,{active:!0}).catch((e=>{A("Error creating new file. ",e)}))}getOpenViewState(e,t){const s=this.getPreferredViewLinePosition(e),{eState:i}=this.getOpenViewLinePositionState(s),n=this.getOpenViewActiveState(t);return Object.assign(n.eState,i),n}getOpenViewActiveState(e){const{active:t,focus:s}=Object.assign({active:!0,focus:!0},e);return{active:t,eState:{active:t,focus:s}}}getPreferredViewLinePosition(e){const t={line:0,col:0,offset:0};return{start:t,end:t}}getOpenViewLinePositionState(e){const t=Object.assign({line:0,col:0,offset:0},e?.start),s=Object.assign({line:0,col:0,offset:0},e?.end),{line:i,col:n}=t;return{eState:{startLoc:t,endLoc:s,line:i,cursor:{from:{line:i,ch:n},to:{line:i,ch:n}}}}}}class ye{useSimpleSearch;_searchDelegate;query;hasSearchTerm;constructor(e,t){this.useSimpleSearch=t,this.query=(e??"").trim().toLowerCase(),this.hasSearchTerm=!!this.query.length}static create(e,t=!1){return new ye(e,t)}searchWithFallback(e,t){let s,i=d.None,n=null,a=this.searchAndDownrankSecondaryMatch(e);if(a.match)n=a.match,i=d.Primary,s=e;else if(t){const{basename:e,path:o}=t;a=this.searchAndDownrankSecondaryMatch(e,o),a.isPrimary?(i=d.Basename,s=e):a.match&&(i=d.Path,s=o),n=a.match}return{matchType:i,matchText:s,match:n}}searchAndDownrankSecondaryMatch(e,t){let s=!1,i=null;return e&&(i=this.executeSearch(e),s=!!i),!i&&t&&(i=this.executeSearch(t),i&&(i.score-=1)),{isPrimary:s,match:i}}executeSearch(e){const t=this.getSearchDelegate();return t?t(e):null}getSearchDelegate(){if(!this._searchDelegate){const{query:e,useSimpleSearch:t}=this;this._searchDelegate=t?a.prepareSimpleSearch(e):a.prepareFuzzySearch(e)}return this._searchDelegate}}class be extends fe{getCommandString(e){return this.settings?.workspaceListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.WorkspaceList);return this.getEnabledWorkspacesPluginInstance()&&(e.mode=t.WorkspaceList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((e=>{let s=!0,a=null;i&&(({match:a}=n.searchWithFallback(e.id)),s=!!a),s&&t.push({type:l.WorkspaceList,item:e,match:a})})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;return e&&(this.addClassesToSuggestionContainer(t,["qsp-suggestion-workspace"]),this.renderContent(t,e.item.id,e.match),s=!0),s}onChooseSuggestion(e,t){let s=!1;if(e){const{id:t}=e.item,i=this.getEnabledWorkspacesPluginInstance();i&&i.loadWorkspace(t),s=!0}return s}onNoResultsCreateAction(e,s){const i=this.getEnabledWorkspacesPluginInstance();if(i){const s=e.parsedCommand(t.WorkspaceList)?.parsedInput;i.saveWorkspace(s),i.setActiveWorkspace(s)}return!0}getItems(){const e=[],t=this.getEnabledWorkspacesPluginInstance()?.workspaces;return t&&Object.keys(t).forEach((t=>e.push({id:t,type:"workspaceInfo"}))),e.sort(((e,t)=>e.id.localeCompare(t.id)))}getEnabledWorkspacesPluginInstance(){return be.getEnabledWorkspacesPluginInstance(this.app)}static getEnabledWorkspacesPluginInstance(e){return I(e,"workspaces")}}class Se extends fe{getCommandString(e){return""}validateCommand(e,t,s,i,n){throw new Error("Method not implemented.")}getSuggestions(e){throw new Error("Method not implemented.")}renderSuggestion(e,t){let s=!1;return p(e)?s=this.renderFileSuggestion(e,t):f(e)&&(s=this.renderAliasSuggestion(e,t)),e?.downranked&&t.addClass("mod-downranked"),s}onChooseSuggestion(e,t){let s=!1;if(e){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open file from SystemSuggestion ${i.path}`),s=!0}return s}renderFileSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-file"],null,i,n,a),this.renderOptionalIndicators(t,e),s=!0}return s}renderAliasSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-alias"],e.alias,i,n,a,!1);const o=this.renderOptionalIndicators(t,e);this.renderIndicator(o,["qsp-alias-indicator"],"lucide-forward"),s=!0}return s}addPropertiesToStandardSuggestions(e,t){const{match:s}=t;let i=d.None,n=null;s?.matches&&(f(t)?(i=d.Primary,n=t.alias):p(t)&&(i=d.Path,n=t.file.path)),t.matchType=i,t.matchText=n,fe.updateWorkspaceEnvListStatus(e,t)}static createUnresolvedSuggestion(e,t,s,i){const n={linktext:e,type:l.Unresolved,...t};return fe.applyMatchPriorityPreferences(n,s,i)}}class ke extends fe{getCommandString(e){return this.settings?.editorListCommand}validateCommand(e,s,i,n,a){e.mode=t.EditorList;const o=e.parsedCommand(t.EditorList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((s=>{const a=H(s);let o=!0,r={matchType:d.None,match:null};const l=this.getPreferredTitle(s,this.settings.preferredSourceForTitle);i&&(r=n.searchWithFallback(l,a),o=r.matchType!==d.None),o&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,s,a,r,l))})),i&&a.sortSearchResults(t)}return t}getPreferredTitle(e,t){return ke.getPreferredTitle(e,t,this.app.metadataCache,this.settings.frontmatterTitleProperty)}static getPreferredTitle(e,t,s,i){const n=H(e);let a=e.getDisplayText();if("H1"===t&&n){const e=ke.getFirstH1(n,s);e&&(a=a.replace(n.basename,e.heading))}else if("FrontMatter"===t&&n&&i){const e=s.getFileCache(n)?.frontmatter,t=fe.getFrontmatterProperty(e,i);t&&(a=a.replace(n.basename,t))}return a}getItems(){const{excludeViewTypes:e,includeSidePanelViewTypes:t,orderEditorListByAccessTime:s}=this.settings,i=this.getOpenLeaves(e,t,{orderByAccessTime:s});return ke.orderByPinnedStatus(i)}static orderByPinnedStatus(e){const t=[],s=[];return e.forEach((e=>{(ke.isLeafPinned(e)?t:s).push(e)})),[...t,...s]}static isLeafPinned(e){return!0===e.getViewState()?.pinned}renderSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e,o=[d.None,d.Primary].includes(n);this.renderAsFileInfoPanel(t,["qsp-suggestion-editor"],e.preferredTitle,i,n,a,o);const r=this.renderOptionalIndicators(t,e);e.isPinned&&this.renderIndicator(r,[],"filled-pin"),s=!0}return s}onChooseSuggestion(e,t){let s=!1;return e&&(this.navigateToLeafOrOpenFile(t,e.file,"Unable to reopen existing editor in new Leaf.",null,e.item,null,!0),s=!0),s}createSuggestion(e,t,s,i,n){return ke.createSuggestion(e,t,s,this.settings,this.app.metadataCache,n,i)}static createSuggestion(e,t,s,i,n,a,o){o=o??{matchType:d.None,match:null,matchText:null};let r={item:t,file:s,preferredTitle:a=a??null,isPinned:ke.isLeafPinned(t),type:l.EditorList,...o};return r=fe.updateWorkspaceEnvListStatus(e,r),fe.applyMatchPriorityPreferences(r,i,n)}}class ve extends fe{getCommandString(e){return this.settings?.bookmarksListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.BookmarksList);return this.getEnabledBookmarksPluginInstance()&&(e.mode=t.BookmarksList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s),{allBookmarks:o}=this.getItems(e);o.forEach((s=>{let a=!0,o={matchType:d.None,match:null};i&&(o=n.searchWithFallback(s.bookmarkPath),a=o.matchType!==d.None),a&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,s,o))})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;if(e&&ve.isBookmarksPluginFileItem(e.item)){const{file:i,matchType:n,match:a,bookmarkPath:o}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-bookmark"],o,i,n,a),this.renderOptionalIndicators(t,e),s=!0}return s}onChooseSuggestion(e,t){let s=!1;if(ve.isBookmarksPluginFileItem(e?.item)){const{file:i}=e,n=`Unable to open file from BookmarkSuggestion ${i?.path}`,a=this.getOpenViewState(e);this.navigateToLeafOrOpenFile(t,i,n,a),s=!0}return s}getPreferredViewLinePosition(e){if(e&&ve.isBookmarksPluginFileItem(e.item)){const t=this.getBookmarkSubpathPosition(e.file,e.item.subpath);if(t)return t}return super.getPreferredViewLinePosition(e)}getBookmarkSubpathPosition(e,t){if(!t)return null;const s=this.app.metadataCache.getFileCache(e),i=s?a.resolveSubpath(s,t):null;return"block"===i?.type?i.block.position:"heading"===i?.type?i.current.position:null}getPreferredTitle(e,t,s,i){let n=e.getItemTitle(t);if(s&&!t.title)if("H1"===i){const e=this.getFirstH1(s);e&&(n=n.replace(/^[^#]*/,e.heading))}else if("FrontMatter"===i){const e=this.app.metadataCache.getFileCache(s)?.frontmatter,t=fe.getFrontmatterProperty(e,this.settings.frontmatterTitleProperty);t&&(n=n.replace(/^[^#]*/,t))}return n}getItems(e){const t=[],s=new Map,i=new Set,n=this.getEnabledBookmarksPluginInstance();if(n){const a=e?this.getActiveFacetIds(e):new Set,o=(e,r)=>{e?.forEach((e=>{if(ve.isBookmarksPluginGroupItem(e))o(e.items,`${r}${e.title}/`);else if(this.isFacetedWith(a,G[e.type])){let a;if(ve.isBookmarksPluginFileItem(e)){const t=this.getTFileByPath(e.path);if(t){a={item:e,bookmarkPath:null,file:t};const i=s.get(t)??[];i.push(a),s.set(t,i)}}else a={item:e,bookmarkPath:null,file:null},i.add(a);if(a){const s=this.getPreferredTitle(n,e,a.file,this.settings.preferredSourceForTitle);a.bookmarkPath=r+s,t.push(a)}}}))};o(n.items,"")}return{allBookmarks:t,fileBookmarks:s,nonFileBookmarks:i}}getEnabledBookmarksPluginInstance(){return I(this.app,"bookmarks")}createSuggestion(e,t,s){return ve.createSuggestion(e,t,this.settings,this.app.metadataCache,s)}static createSuggestion(e,t,s,i,n){let a={type:l.Bookmark,item:t.item,bookmarkPath:t.bookmarkPath,file:t.file,...n};return a=fe.updateWorkspaceEnvListStatus(e,a),fe.applyMatchPriorityPreferences(a,s,i)}static isBookmarksPluginFileItem(e){return m(e,"type","file")}static isBookmarksPluginGroupItem(e){return m(e,"type","group")}addPropertiesToStandardSuggestions(e,t){const{match:s,item:i}=t;let n=d.None,a=null;if(!t.file&&ve.isBookmarksPluginFileItem(i)){const e=i.path;t.file=this.getTFileByPath(e)}s?.matches&&(n=d.Primary,a=t.bookmarkPath),t.matchType=n,t.matchText=a,fe.updateWorkspaceEnvListStatus(e,t)}}const we={file:"lucide-file-text",text:"lucide-sticky-note",link:"lucide-globe",group:"create-group"},Ce={table:"lucide-table",list:"lucide-list",cards:"lucide-layout-grid"};class Ie extends fe{inputInfo;getCommandString(e){const{settings:t}=this;return e?.useActiveEditorAsSource?t.symbolListActiveEditorCommand:t.symbolListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.SymbolList),r=this.getSourceInfoForSymbolOperation(n,a,0===s,e.sessionOpts);return r&&(e.mode=t.SymbolList,o.source=r,o.index=s,o.parsedInput=i,o.isValidated=!0),o}async getSuggestions(e){const s=[];if(e){this.inputInfo=e;const{query:i,hasSearchTerm:n}=e.parsedInputQuery,o=ye.create(i),r=e.parsedCommand(t.SymbolList);(await this.getItems(r.source,n)).forEach((e=>{let t=!0,i=null;if(n){const s=Ie.getSuggestionTextForSymbol(e);({match:i}=o.searchWithFallback(s)),t=!!i}if(t){const{file:t}=r.source;s.push({type:l.SymbolList,file:t,item:e,match:i})}})),n&&a.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,o=["qsp-suggestion-symbol"];Object.prototype.hasOwnProperty.call(i,"indentLevel")&&this.settings.symbolsInLineOrder&&!this.inputInfo?.parsedInputQuery?.hasSearchTerm&&o.push(`qsp-symbol-l${i.indentLevel}`),this.addClassesToSuggestionContainer(t,o);const{contentEl:r,titleEl:l}=fe.createContentStructureElements(t);Ie.renderSymbolContent(this.app,this.settings,l,i,n,a),this.renderHeadingBreadcrumbsInSymbolMode(r,i.symbol,n),this.addSymbolIndicator(i,t),s=!0}return s}onChooseSuggestion(e,t){return!!e&&(this.navigateAndCompleteSymbol(t,e),!0)}async navigateAndCompleteSymbol(e,s){const i=this.inputInfo.parsedCommand(),{leaf:n,file:a}=i.source,o=this.getOpenViewState(s),{item:r}=s;try{await this.navigateToLeafOrOpenFileAsync(e,a,o,n,t.SymbolList)}catch(e){return void A(`Unable to navigate to symbols for file ${a?.path}`,e)}if(Ie.isCanvasSymbolPayload(r))this.zoomToCanvasNode(this.getActiveLeaf().view,r.symbol);else if(Ie.isBaseViewSymbolPayload(r)){const e=r.symbol,t=s.file?.path,i=`${t}#${e.name}`;try{await this.app.workspace.openLinkText(i,t,!1)}catch(s){A(`Unable to navigate to Base view ${e.name} in file ${t}`,s)}}}reset(){this.inputInfo=null}getAvailableFacets(e){const i=e.parsedCommand(t.SymbolList),n=Ie.isBaseFile(i?.source?.file),a=Ie.isCanvasFile(i?.source?.file),o=this.getFacets(e.mode),r=new Set(Object.values($)),l=new Set(Object.values(j)),d=new Set(Object.values(s).filter((e=>isNaN(Number(e)))));return o.forEach((e=>{const{id:t}=e;e.isAvailable=n?r.has(t):a?l.has(t):d.has(t)})),o.filter((e=>e.isAvailable))}zoomToCanvasNode(e,t){if(Ie.isCanvasView(e)&&t){const s=e.canvas,i=s.nodes.get(t.id);s.selectOnly(i),s.zoomToSelection()}}getPreferredViewLinePosition(e){let t=super.getPreferredViewLinePosition();if(e?.item?.symbol){const{item:s}=e;if(!Ie.isCanvasSymbolPayload(s)&&!Ie.isBaseViewSymbolPayload(s)){t=s.symbol.position}}return t}getSourceInfoForSymbolOperation(e,s,i,n){const a=this.inputInfo;let o=null,r=t.Standard;a&&(o=a.parsedCommand().source,r=a.mode);const l=r===t.SymbolList&&!!o,d=this.getEditorInfo(s),c=this.getSuggestionInfo(e);let h=null;return l?h=o:c.isValidSource&&!n.useActiveEditorAsSource?h=c:d.isValidSource&&i&&(h=d),h}async getItems(e,t){let s=[],i=!1,n=!1;return t||({selectNearestHeading:n,symbolsInLineOrder:i}=this.settings),s=await this.getSymbolsFromSource(e,i),n&&Ie.FindNearestHeadingSymbol(s,e),s}static FindNearestHeadingSymbol(e,t){const s=t?.cursor?.line;if(s){let t=null;const i=e.filter((e=>S(e.symbol)));i.length&&(t=i.reduce(((e,t)=>{const{line:i}=t.symbol.position.start,n=e?e.symbol.position.start.line:-1;return e?i>n&&i<=s?t:e:i<=s?t:null}),null)),t&&(t.isSelected=!0)}}async getSymbolsFromSource(e,t){const{app:{metadataCache:i},inputInfo:n}=this,a=[];if(e?.file){const{file:o}=e,r=this.getActiveFacetIds(n);if(Ie.isBaseFile(o))await this.addBaseViewsFromSource(o,a,r);else if(Ie.isCanvasFile(o))await this.addCanvasSymbolsFromSource(o,a,r);else{const e=i.getFileCache(o);if(e){const i=(e=[],t)=>{this.shouldIncludeSymbol(t,r)&&e.forEach((e=>a.push({type:"symbolInfo",symbol:e,symbolType:t})))};i(e.headings,s.Heading),this.addTagsFromSource(e,a,r),this.addLinksFromSource(e,a,r),i(e.embeds,s.Embed),await this.addCalloutsFromSource(o,e.sections?.filter((e=>"callout"===e.type)),a,r),t&&Ie.orderSymbolsByLineNumber(a)}}}return a}shouldIncludeSymbol(e,t){let i=!1;return i="string"==typeof e?this.isFacetedWith(t,e):this.settings.isSymbolTypeEnabled(e)&&this.isFacetedWith(t,s[e]),i}async addCanvasSymbolsFromSource(e,t,i){let n;try{const t=await this.app.vault.cachedRead(e);n=JSON.parse(t).nodes}catch(t){O(`Error reading file to extract canvas node information. ${e.path} `,t)}Array.isArray(n)&&n.forEach((e=>{this.shouldIncludeSymbol(j[e.type],i)&&t.push({type:"symbolInfo",symbolType:s.CanvasNode,symbol:{...e}})}))}async addBaseViewsFromSource(e,t,i){let n;try{const t=await this.app.vault.cachedRead(e);n=a.parseYaml(t)}catch(t){return void O(`Error reading file to extract base view information. ${e.path} `,t)}n&&n?.views&&Array.isArray(n.views)&&n.views.forEach((e=>{const n=$[e.type];(n?this.shouldIncludeSymbol(n,i):0===i.size)&&t.push({type:"symbolInfo",symbolType:s.BaseView,symbol:{type:e.type,name:e.name}})}))}async addCalloutsFromSource(e,t,i,n){const{app:{vault:a}}=this;if(this.shouldIncludeSymbol(s.Callout,n)&&t?.length&&e){let n=null;try{n=await a.cachedRead(e)}catch(t){O(`Error reading file to extract callout information. ${e.path} `,t)}if(n)for(const e of t){const{start:t,end:a}=e.position,o=n.slice(t.offset,a.offset).match(/^> \[!([^\]]+)\][+-]?(.*?)(?:\n>|$)/);if(o){const t=o[1],n={calloutTitle:o[o.length-1].trim(),calloutType:t,...e};i.push({type:"symbolInfo",symbolType:s.Callout,symbol:n})}}}}addLinksFromSource(e,t,i){const{settings:n}=this;if(!this.shouldIncludeSymbol(s.Link,i))return;const a=e?.links??[],o=e?.frontmatterLinks??[],r=Ie.getFrontmatterPositionOrZero(e),l=[...a,...o.map((e=>{const t={link:e.link,original:e.original,position:r};return e.displayText&&(t.displayText=e.displayText),t}))];for(const e of l){const i=B(e);(n.excludeLinkSubTypes&i)===i||t.push({type:"symbolInfo",symbol:e,symbolType:s.Link})}}addTagsFromSource(e,t,i){if(!this.shouldIncludeSymbol(s.Tag,i))return;const n=new Set,a=e.tags??[];for(const e of a)n.add(e.tag.toLowerCase()),t.push({type:"symbolInfo",symbol:e,symbolType:s.Tag});const o=e.frontmatter;if(o){const i=h.getTags(o),a=Ie.getFrontmatterPositionOrZero(e);for(const e of i){const i=e.startsWith("#")?e:`#${e}`;if(n.has(i.toLowerCase()))continue;const o={tag:i,position:a};t.push({type:"symbolInfo",symbol:o,symbolType:s.Tag})}}}static orderSymbolsByLineNumber(e){const t=e.sort(((e,t)=>{const{start:s}=e.symbol.position,{start:i}=t.symbol.position,n=s.line-i.line;return 0===n?s.col-i.col:n}));let s=0;return t.forEach((e=>{let t=0;S(e.symbol)?(s=e.symbol.level,t=e.symbol.level-1):t=s,e.indentLevel=t})),t}static getMarkdownContentForSymbol(e,t){const{symbol:s}=e;if(S(s))return s.heading.replace(/^(\d+)\./,"$1\\.");if(k(s))return s.tag;if(v(s))return s.calloutTitle;const i=s;return i.original?i.original:null}static renderSymbolContent(e,t,s,i,n,o,r){const l=Ie.getMarkdownContentForSymbol(i,n);if((r??(null!==l&&t.shouldRenderSymbolAsHTML(i.symbolType)))&&null!==l)fe.renderMarkdownContentAsync(e,s,l,n.path);else{const e=Ie.getSuggestionTextForSymbol(i);a.renderResults(s,e,o)}}static getSuggestionTextForSymbol(e){const{symbol:t}=e;let s;if(S(t))s=t.heading;else if(k(t))s=t.tag.slice(1);else if(v(t))s=t.calloutTitle;else if(Ie.isCanvasSymbolPayload(e))s=Ie.getSuggestionTextForCanvasNode(e.symbol);else if(Ie.isBaseViewSymbolPayload(e))s=e.symbol.name;else{const e=t;({link:s}=e);const{displayText:i}=e;i&&i!==s&&(s+=`|${i}`)}return s}static getSuggestionTextForCanvasNode(e){let t="";const s={file:()=>e.file,text:()=>e.text,link:()=>e.url,group:()=>e.label}[e?.type];return s&&(t=s()),t}addSymbolIndicator(e,t){const{symbolType:s,symbol:i}=e,n=["qsp-symbol-indicator"],l=this.createFlairContainer(t);if(v(i)){n.push("suggestion-flair","callout","callout-icon","svg-icon");const e=l.createSpan({cls:n,attr:{"data-callout":i.calloutType}}),t=e.getCssPropertyValue("--callout-icon");a.setIcon(e,t)}else if(Ie.isCanvasSymbolPayload(e)){const t=we[e.symbol.type];this.renderIndicator(l,n,t,null)}else if(Ie.isBaseViewSymbolPayload(e)){const t=e.symbol,s=Ce[t.type]||Ce.table;this.renderIndicator(l,n,s,null)}else{let e;e=S(i)?r[i.level]:o[s],this.renderIndicator(l,n,null,e)}}renderHeadingBreadcrumbsInSymbolMode(e,t,s){S(t)&&this.renderHeadingBreadcrumbs(e,t,s,this.settings.showHeadingBreadcrumbsInSymbolMode)}static getFrontmatterPositionOrZero(e){return e.frontmatterPosition??{start:{line:0,col:0,offset:0},end:{line:0,col:0,offset:0}}}static isCanvasSymbolPayload(e){return e.symbolType===s.CanvasNode}static isBaseViewSymbolPayload(e){return e.symbolType===s.BaseView}static isCanvasFile(e){return"canvas"===e?.extension}static isCanvasView(e){return"canvas"===e?.getViewType()}static isBaseFile(e){return"base"===e?.extension}static isBaseView(e){return"bases"===e?.getViewType()}}class Le extends fe{getCommandString(e){return this.settings?.headingsListCommand}validateCommand(e,s,i,n,a){e.mode=t.HeadingsList;const o=e.parsedCommand(t.HeadingsList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}onChooseSuggestion(e,t){let s=!1;if(e){const i=this.getOpenViewState(e);this.navigateToLeafOrOpenFile(t,e.file,"Unable to navigate to heading for file.",i),s=!0}return s}getPreferredViewLinePosition(e){return e?.item?.position}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,{app:o,settings:l}=this;this.addClassesToSuggestionContainer(t,["qsp-suggestion-headings",`qsp-headings-l${i.level}`]);const{contentEl:d,titleEl:c}=fe.createContentStructureElements(t);Le.renderHeadingContent(o,l,c,i,n,a),this.renderHeadingBreadcrumbs(d,i,n),this.renderTags(d,n),this.renderPath(d,n);const h=this.createFlairContainer(t);this.renderOptionalIndicators(t,e,h),this.renderIndicator(h,["qsp-headings-indicator"],null,r[i.level]),e.downranked&&t.addClass("mod-downranked"),s=!0}return s}static renderHeadingContent(e,t,i,n,a,o,r){const l={type:"symbolInfo",symbol:n,symbolType:s.Heading};Ie.renderSymbolContent(e,t,i,l,a,o,r)}getAvailableFacets(e){const{settings:{shouldSearchHeadings:t,shouldSearchBookmarks:s,shouldSearchFilenames:i,shouldSearchRecentFiles:n,builtInSystemOptions:{showAttachments:a,showAllFileTypes:o}}}=this,r=a||o,l={[J.RecentFiles]:n,[J.Bookmarks]:s,[J.Filenames]:i,[J.Headings]:t,[J.ExternalFiles]:r};return this.getFacets(e.mode).filter((e=>(Object.prototype.hasOwnProperty.call(l,e.id)&&(e.isAvailable=l[e.id]),e.isAvailable)))}getSuggestions(e){let t=[];if(e){const{hasSearchTerm:s}=e.parsedInputQuery,{settings:i}=this,n=this.getActiveFacetIds(e),o=!!n.size;if(s||o){const{limit:s}=i,{app:{vault:o}}=this,r={headings:i.shouldSearchHeadings,allHeadings:i.searchAllHeadings,aliases:i.shouldShowAlias,bookmarks:i.shouldSearchBookmarks,filename:i.shouldSearchFilenames,filenameAsFallback:!i.strictHeadingsOnly,unresolved:!i.showExistingOnly};this.getItems([o.getRoot()],e,t,n,r),a.sortSearchResults(t),s>0&&t.length>s&&(t=t.slice(0,s))}else this.getSuggestionsForEditorsAndRecentFiles(e,t,new Set,{editors:!0,recentFiles:i.shouldSearchRecentFiles})}return t}getItems(e,t,s,i,n){const a=!!i.size,o=ye.create(t.parsedInputQuery.query);this.getSuggestionsForEditorsAndRecentFiles(t,s,i,{editors:!1,recentFiles:!1});const r={fileBookmarks:n.bookmarks,nonFileBookmarks:n.bookmarks};this.getSuggestionsForBookmarks(t,o,s,i,r);const l={headings:n.headings,allHeadings:n.allHeadings,aliases:n.aliases,filename:n.filename,filenameAsFallback:n.filenameAsFallback};this.getSuggestionForFiles(t,o,e,s,i,l),n.unresolved&&!a&&this.addUnresolvedSuggestions(s,o)}getSuggestionsForBookmarks(e,t,s,i,n){const a=!!i.size,{fileBookmarks:o,nonFileBookmarks:r}=e.currentWorkspaceEnvList;if(a){const e=i.has(J.Bookmarks);n=Object.assign(n,{fileBookmarks:e,nonFileBookmarks:e})}const l=i=>{for(const n of i)this.addBookmarkSuggestion(e,s,t,n)};n.fileBookmarks&&o.forEach((e=>{l(e)})),n.nonFileBookmarks&&l(r)}getSuggestionForFiles(e,t,s,i,n,a){if(!!n.size){const e=this.isFacetedWith(n,J.Headings),t=this.isFacetedWith(n,J.ExternalFiles)||this.isFacetedWith(n,J.Filenames);let s=!1,i=!1;e&&(s=!0===a.allHeadings,i=!0===a.filenameAsFallback),a=Object.assign(a,{headings:e,aliases:!1,filename:t,allHeadings:s,filenameAsFallback:i})}else a=Object.assign({headings:!0,allHeadings:!0,aliases:!0,filename:!0,filenameAsFallback:!0},a);if([a.headings,a.aliases,a.filename].some((e=>!0===e))){const{excludeFolders:o}=this.settings,r=M(o);let l=Array.prototype.concat(s);for(;l.length>0;){const s=l.pop();w(s)?this.shouldIncludeFile(s,n)&&this.addSuggestionsForFile(e,t,i,s,a):C(s)&&!r(s.path)&&(l=l.concat(s.children))}}}addSuggestionsForFile(e,t,s,i,n){let a=!1;n.headings&&(a=this.addHeadingSuggestions(e,t,s,i,n.allHeadings)),(n.filename||!a&&n.filenameAsFallback)&&this.addFileSuggestions(e,t,s,i),n.aliases&&this.addAliasSuggestions(e,t,s,i)}shouldIncludeFile(e,t=new Set){let s=!1;if(e){const i=new Set(["md","canvas"]),{extension:n}=e,{app:{viewRegistry:a,metadataCache:o},settings:{excludeObsidianIgnoredFiles:r,fileExtAllowList:l,builtInSystemOptions:{showAttachments:d,showAllFileTypes:c}}}=this;if(!(r&&o.isUserIgnored(e.path)))if(t.has(J.ExternalFiles)){const e=d||c;s=!i.has(n)&&e}else{s=this.isExternalFileTypeAllowed(e,a,d,c,l)||i.has(n)}}return s}isExternalFileTypeAllowed(e,t,s,i,n){const{extension:a}=e;let o=t.isExtensionRegistered(a)?s:i;if(!o){o=new Set(n).has(a)}return o}addAliasSuggestions(e,t,s,i){const{metadataCache:n}=this.app,a=n.getFileCache(i)?.frontmatter;if(a){const n=h.getAliases(a);let o=n.length;for(;o--;){const a=n[o],{match:r}=t.searchWithFallback(a);r&&s.push(this.createAliasSuggestion(e,a,i,r))}}}addFileSuggestions(e,t,s,i){const{match:n,matchType:a,matchText:o}=t.searchWithFallback(null,i);n&&s.push(this.createFileSuggestion(e,i,n,a,o))}addBookmarkSuggestion(e,t,s,i){const n=s.searchWithFallback(i.bookmarkPath);if(n.match){const s=ve.createSuggestion(e.currentWorkspaceEnvList,i,this.settings,this.app.metadataCache,n);t.push(s)}}addHeadingSuggestions(e,t,s,i,n){const{metadataCache:a}=this.app,o=a.getFileCache(i)?.headings??[];let r=null,l=!1,d=o.length;for(;d--;){const a=o[d];let c=!1;if(n&&(c=this.matchAndPushHeading(e,t,s,i,a)),1===a.level){const{line:e}=a.position.start;(null===r||e{this.addOpenEditorSuggestions(s,e,a,t)}))}if(i.recentFiles){const i=e.currentWorkspaceEnvList?.mostRecentFiles;i?.forEach((i=>{this.shouldIncludeFile(i,s)&&this.addRecentFilesSuggestions(i,e,a,t)}))}}onNoResultsCreateAction(e,s){const i=e.parsedCommand(t.HeadingsList)?.parsedInput;return this.createFile(i,s),!0}}class Te extends fe{static recentlyUsedCommandIds=[];getCommandString(e){return this.settings?.commandListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.CommandList);return this.getEnabledCommandPalettePluginInstance()&&(e.mode=t.CommandList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems(e,i).forEach((e=>{let s=!0,a=null;i&&(({match:a}=n.searchWithFallback(e.cmd.name)),s=!!a),s&&t.push(this.createSuggestion(e,a))})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;if(e){const{item:i,match:n,isPinned:a,isRecent:o}=e;this.addClassesToSuggestionContainer(t,["qsp-suggestion-command"]),this.renderContent(t,i.name,n);const r=this.createFlairContainer(t);this.renderHotkeyForCommand(i.id,this.app,r),i.icon&&this.renderIndicator(r,[],i.icon),a?this.renderIndicator(r,[],"filled-pin"):o&&this.renderOptionalIndicators(t,e,r),s=!0}return s}renderHotkeyForCommand(e,t,s){try{const{hotkeyManager:i}=t;if(i.getHotkeys(e)||i.getDefaultHotkeys(e)){const t=i.printHotkeyForCommand(e);t?.length&&s.createEl("kbd",{cls:"suggestion-hotkey",text:t})}}catch(t){O("Error rendering hotkey for command id: ",e,t)}}onChooseSuggestion(e){let t=!1;if(e){const{item:s}=e;this.app.commands.executeCommandById(s.id),this.saveUsageToList(s.id,Te.recentlyUsedCommandIds),t=!0}return t}saveUsageToList(e,t){if(t){const s=t.indexOf(e);s>-1&&t.splice(s,1),t.unshift(e),t.splice(this.settings.maxRecentCommands)}}getItems(e,t){let s=[];const i=this.getActiveFacetIds(e);if(!!i.size)s=this.getPinnedAndRecentCommands(i);else if(t)s=this.getAllCommands();else{const e=this.getPinnedAndRecentCommands(i);s=e.length?e:this.getAllCommands()}return s}getPinnedAndRecentCommands(e){const t=[],s=this.getPinnedCommandIds(),i=this.getRecentCommandIds(),n=e=>{let t=null;const n=this.app.commands.findCommand(e);return n&&(t={isPinned:s.has(e),isRecent:i.has(e),cmd:n}),t},a=(s,i)=>{this.isFacetedWith(e,s)&&i.forEach((e=>{const s=n(e);s&&t.push(s)}))};a(z.Pinned,Array.from(s));const o=this.isFacetedWith(e,z.Pinned),r=Array.from(i).filter((e=>!o||o&&!s.has(e)));return"asc"===this.settings.recentCommandDisplayOrder&&r.reverse(),a(z.Recent,r),t}getAllCommands(){const e=this.getPinnedCommandIds(),t=this.getRecentCommandIds();return this.app.commands.listCommands()?.sort(((e,t)=>e.name.localeCompare(t.name))).map((s=>({isPinned:e.has(s.id),isRecent:t.has(s.id),cmd:s})))}getPinnedCommandIds(){const e=this.getEnabledCommandPalettePluginInstance()?.options?.pinned;return new Set(e??[])}getRecentCommandIds(){return new Set(Te.recentlyUsedCommandIds)}createSuggestion(e,t){const{cmd:s,isPinned:i,isRecent:n}=e,a={type:l.CommandList,item:s,isPinned:i,isRecent:n,match:t};return this.applyMatchPriorityPreferences(a)}getEnabledCommandPalettePluginInstance(){return Te.getEnabledCommandPalettePluginInstance(this.app)}static getEnabledCommandPalettePluginInstance(e){return I(e,"command-palette")}}class Ee extends fe{inputInfo;getCommandString(e){const{settings:t}=this;return e?.useActiveEditorAsSource?t.relatedItemsListActiveEditorCommand:t.relatedItemsListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.RelatedItemsList),r=this.getSourceInfo(n,a,0===s,e.sessionOpts);return r&&(e.mode=t.RelatedItemsList,o.source=r,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const s=[];if(e){this.inputInfo=e;const i=ye.create(e.parsedInputQuery.query),n=e.parsedCommand(t.RelatedItemsList);this.getItems(n.source,e).forEach((t=>{const n=this.searchAndCreateSuggestion(e,i,t);n&&s.push(n)})),i.hasSearchTerm&&a.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a,item:o}=e,r=new Map([[c.Backlink,"links-coming-in"],[c.DiskLocation,"folder-tree"],[c.OutgoingLink,"links-going-out"]]);t.setAttribute("data-relation-type",o.relationType),this.renderAsFileInfoPanel(t,["qsp-suggestion-related"],e.preferredTitle,i,n,a);const l=this.renderOptionalIndicators(t,e);e.item.count&&this.renderIndicator(l,[],null,`${e.item.count}`),this.renderIndicator(l,["qsp-related-indicator"],r.get(o.relationType)),s=!0}return s}onChooseSuggestion(e,t){let s=!1;if(e){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open related file ${i.path}`),s=!0}return s}getPreferredTitle(e,t){let s=null;const{file:i,unresolvedText:n}=e;if(i){if("H1"===t)s=this.getFirstH1(i)?.heading??null;else if("FrontMatter"===t){const e=this.app.metadataCache.getFileCache(i)?.frontmatter;s=fe.getFrontmatterProperty(e,this.settings.frontmatterTitleProperty)}}else{!!n?.length&&(s=n)}return s}searchAndCreateSuggestion(e,t,s){const{file:i,unresolvedText:n}=s;let a={matchType:d.None,match:null};const o=null===i&&n?.length,{currentWorkspaceEnvList:r}=e,{settings:l,app:{metadataCache:c}}=this,h=this.getPreferredTitle(s,l.preferredSourceForTitle);return t.hasSearchTerm&&(a=t.searchWithFallback(h,i),a.matchType===d.None)?null:o?Se.createUnresolvedSuggestion(h,a,l,c):this.createSuggestion(r,s,a,h)}getItems(e,t){const s=[],{metadataCache:i}=this.app,{file:n,suggestion:a}=e,o=new Set(this.settings.enabledRelatedItems),r=this.getActiveFacetIds(t),l=e=>o.has(e)&&this.isFacetedWith(r,e);if(l(c.Backlink)){let e=n?.path,t=i.resolvedLinks;y(a)&&(e=a.linktext,t=i.unresolvedLinks),this.addBacklinks(e,t,s)}return l(c.DiskLocation)&&this.addRelatedDiskFiles(n,s),l(c.OutgoingLink)&&this.addOutgoingLinks(n,s),s}addRelatedDiskFiles(e,t){const{excludeRelatedFolders:s,excludeOpenRelatedFiles:i}=this.settings;if(e){const n=M(s);let a=[...e.parent.children];for(;a.length>0;){const s=a.pop();if(w(s)){s===e||i&&!!this.findMatchingLeaf(s).leaf||t.push({file:s,relationType:c.DiskLocation})}else C(s)&&!n(s.path)&&(a=a.concat(s.children))}}}addOutgoingLinks(e,t){if(!e)return;const{metadataCache:s}=this.app,i=e.path,n=s.resolvedLinks[i]??{};for(const[e,a]of Object.entries(n)){if(e===i)continue;const n=s.getFirstLinkpathDest(e,i);n&&t.push({file:n,relationType:c.OutgoingLink,count:a})}const a=s.unresolvedLinks[i]??{};for(const[e,s]of Object.entries(a))t.push({file:null,relationType:c.OutgoingLink,unresolvedText:e,count:s})}addBacklinks(e,t,s){for(const[i,n]of Object.entries(t))if(i!==e&&Object.prototype.hasOwnProperty.call(n,e)){const t=n[e],a=this.getTFileByPath(i);a&&s.push({count:t,file:a,relationType:c.Backlink})}}reset(){this.inputInfo=null}getSourceInfo(e,s,i,n){const a=this.inputInfo;let o=null,r=t.Standard;a&&(o=a.parsedCommand().source,r=a.mode);const l=r===t.RelatedItemsList&&!!o,d=this.getEditorInfo(s),c=this.getSuggestionInfo(e);!c.isValidSource&&y(e)&&(c.isValidSource=!0);let h=null;return l?h=o:c.isValidSource&&!n.useActiveEditorAsSource?h=c:d.isValidSource&&i&&(h=d),h}createSuggestion(e,t,s,i){let n={item:t,file:t?.file,type:l.RelatedItemsList,preferredTitle:i,...s};return n=fe.updateWorkspaceEnvListStatus(e,n),this.applyMatchPriorityPreferences(n)}}class Fe extends fe{mobileVaultChooserMarker={type:l.VaultList,match:null,item:null,pathSegments:null};getCommandString(e){return this.settings?.vaultListCommand}validateCommand(e,s,i,n,a){e.mode=t.VaultList;const o=e.parsedCommand(t.VaultList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((e=>{let s=!0;if(i){const t=n.searchWithFallback(null,e.pathSegments);Object.assign(e,t),s=!!t.match}s&&t.push(e)})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;return e&&(this.addClassesToSuggestionContainer(t,["qsp-suggestion-vault"]),s=!0,a.Platform.isDesktop?this.renderVaultSuggestion(e,t):e===this.mobileVaultChooserMarker&&this.renderMobileHintSuggestion(t)),s}renderMobileHintSuggestion(e){this.renderContent(e,"Show mobile vault chooser",null)}renderVaultSuggestion(e,t){const{pathSegments:s,matchType:i}=e;let{match:n}=e,o=null;i===d.Basename&&(o=n,n=null);const r=this.renderContent(t,s.basename,o).createDiv({cls:["suggestion-note","qsp-note"]}),l=r.createSpan({cls:["qsp-path-indicator"]}),c=r.createSpan({cls:"qsp-path"});a.setIcon(l,"folder"),a.renderResults(c,s.path,n)}onChooseSuggestion(e,t){let s=!1;return e&&(a.Platform.isDesktop?(this.openVaultOnDesktop(e.pathSegments?.path),s=!0):e===this.mobileVaultChooserMarker&&(this.app.openVaultChooser(),s=!0)),s}getItems(){const e=[];if(a.Platform.isDesktop)try{const t=this.getVaultListDataOnDesktop();for(const[s,{path:i,open:n}]of Object.entries(t)){const t=x(i),a={type:l.VaultList,match:null,item:s,isOpen:!!n,pathSegments:{basename:t,path:i}};e.push(a)}}catch(e){O("Error parsing vault data. ",e)}else e.push(this.mobileVaultChooserMarker);return e.sort(((e,t)=>e.pathSegments.basename.localeCompare(t.pathSegments.basename)))}getIpcRenderer(){if(!a.Platform.isDesktop)return null;try{return window.require("electron").ipcRenderer}catch{return null}}openVaultOnDesktop(e){const t=this.getIpcRenderer();if(t)try{t.sendSync("vault-open",e,!1)}catch(t){A(`Error opening vault with path: ${e} `,t)}}getVaultListDataOnDesktop(){let e=null;const t=this.getIpcRenderer();if(t)try{e=t.sendSync("vault-list")}catch(e){A("Error retrieving list of available vaults.",e)}return e}}class xe{app;config;static instance;instanceCache=new Map;modeToHandlerClass=new Map;suggestionTypeToMode=new Map;cmdStrToMode=new Map;sourcedHandlerModes=new Set;constructor(e,t,s){this.app=e,this.config=t;for(const e of s)e.handlerClass&&(this.modeToHandlerClass.set(e.mode,e.handlerClass),this.mapSuggestionTypesToMode(e),this.mapCommandStrToMode(e),this.registerSourcedHandler(e))}static initialize(e,t,s){this.instance?P("HandlerRegistry already initialized."):this.instance=new xe(e,t,s)}static reset(){this.instance=null}static getInstance(){return this.instance??null}getHandler(e){let t=null;const s=this.resolveMode(e);if(s)if(this.instanceCache.has(s))t=this.instanceCache.get(s)??null;else{const e=this.modeToHandlerClass.get(s);if(e){const i=new e(this.app,this.config);this.instanceCache.set(s,i),t=i}}return t}resetSourcedHandlers(e){const t=new Set(e);for(const e of this.sourcedHandlerModes){const s=this.instanceCache.get(e);s&&!t.has(s)&&s.reset()}}mapSuggestionTypesToMode(e){e.ownSuggestionTypes?.forEach((t=>{this.suggestionTypeToMode.set(t,e.mode)}))}mapCommandStrToMode(e){const t=e.parserCommand?.getCommandStr();t?.length&&this.cmdStrToMode.set(t,e.mode)}registerSourcedHandler(e){"sourced"===e.parserCommand?.type&&this.sourcedHandlerModes.add(e.mode)}resolveMode(e){let s;return"number"==typeof e&&Object.values(t).includes(e)?s=e:m(e,"type")?s=this.suggestionTypeToMode.get(e.type):"string"==typeof e&&(s=this.cmdStrToMode.get(e)),s}}class Ae{commandMap=new Map;escapeCmdChar;handlerRegistry;constructor(e,t,s){this.handlerRegistry=e,this.escapeCmdChar=t.escapeCmdChar,this.commandMap=this.buildCommandMap(s)}parseInputForMode(e,s,i){const{cleanInput:n,resolvedCommands:a}=this.parse(e.inputText);e.cleanInput=n;this.findFirstValidCommand(a,e,s,i)||(this.handlerRegistry.resetSourcedHandlers(),e.mode=t.Standard)}parse(e){let t="";const s=[],i=this.escapeCmdChar.length;let n=0;for(;n0){const i=e[0];t.has(i)||t.set(i,[]),t.get(i)?.push({cmdDef:s,cmdStr:e})}}for(const e of t.values())e.sort(((e,t)=>t.cmdStr.length-e.cmdStr.length));return t}findCommandMatch(e,t){const s=this.commandMap.get(e[t]);if(!s)return null;for(const i of s)if(e.startsWith(i.cmdStr,t))return i;return null}resolveCommandPrecedence(e,t){const s=[];let i;for(const n of e){const e=n.indexInCleanInput+n.cmdStr.length,a=t.substring(e),o={cmdDef:n.cmdDef,cmdStr:n.cmdStr,indexInCleanInput:n.indexInCleanInput,filterText:a},r=n.cmdDef.parserCommand.type;"prefix"!==r||0!==n.indexInCleanInput||i?"sourced"===r&&s.push(o):i=o}return s.sort(((e,t)=>e.indexInCleanInput-t.indexInCleanInput)),i?[...s,i]:s}findFirstValidCommand(e,t,s,i){for(const n of e){const e=this.handlerRegistry.getHandler(n.cmdDef.mode);if(!e)continue;t.sessionOpts.useActiveEditorAsSource=n.cmdDef.parserCommand.useActiveEditorAsSource;if(e.validateCommand(t,n.indexInCleanInput,n.filterText,s,i).isValidated){const t="sourced"===n.cmdDef.parserCommand.type?[e]:[];return this.handlerRegistry.resetSourcedHandlers(t),!0}}return!1}}const Oe={};class Pe{app;settings;exKeymap;_inputInfo;get inputInfo(){return this._inputInfo}get previousInputHistory(){return Oe}_handlerRegistry;get handlerRegistry(){return this._handlerRegistry}_inputParser;get inputParser(){return this._inputParser}debouncedGetSuggestions;workspaceEnvList=null;sessionOpts={};noResultActionModes=[t.HeadingsList,t.WorkspaceList];constructor(e,s,i){this.app=e,this.settings=s,this.exKeymap=i;const n=(o=s,[{commandId:"switcher-plus:open",commandName:"Open in Standard Mode",mode:t.Standard,iconId:"lucide-file-search",handlerClass:Se,ownSuggestionTypes:[l.Alias,l.File],parserCommand:{type:"none",getCommandStr:()=>""}},{commandId:"switcher-plus:open-editors",commandName:"Open in Editor Mode",mode:t.EditorList,iconId:"lucide-file-edit",handlerClass:ke,ownSuggestionTypes:[l.EditorList],parserCommand:{type:"prefix",getCommandStr:()=>o.editorListCommand}},{commandId:"switcher-plus:open-symbols",commandName:"Open Symbols for selected suggestion or editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",handlerClass:Ie,ownSuggestionTypes:[l.SymbolList],parserCommand:{type:"sourced",getCommandStr:()=>o.symbolListCommand}},{commandId:"switcher-plus:open-symbols-active",commandName:"Open Symbols for the active editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",handlerClass:Ie,parserCommand:{type:"prefix",getCommandStr:()=>o.symbolListActiveEditorCommand,useActiveEditorAsSource:!0}},{commandId:"switcher-plus:open-workspaces",commandName:"Open in Workspaces Mode",mode:t.WorkspaceList,iconId:"lucide-album",handlerClass:be,ownSuggestionTypes:[l.WorkspaceList],parserCommand:{type:"prefix",getCommandStr:()=>o.workspaceListCommand}},{commandId:"switcher-plus:open-headings",commandName:"Open in Headings Mode",mode:t.HeadingsList,iconId:"lucide-file-search",handlerClass:Le,ownSuggestionTypes:[l.HeadingsList],parserCommand:{type:"prefix",getCommandStr:()=>o.headingsListCommand}},{commandId:"switcher-plus:open-starred",commandName:"Open in Bookmarks Mode",mode:t.BookmarksList,iconId:"lucide-bookmark",handlerClass:ve,ownSuggestionTypes:[l.Bookmark],parserCommand:{type:"prefix",getCommandStr:()=>o.bookmarksListCommand}},{commandId:"switcher-plus:open-commands",commandName:"Open in Commands Mode",mode:t.CommandList,iconId:"run-command",handlerClass:Te,ownSuggestionTypes:[l.CommandList],parserCommand:{type:"prefix",getCommandStr:()=>o.commandListCommand}},{commandId:"switcher-plus:open-related-items",commandName:"Open Related Items for selected suggestion or editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",handlerClass:Ee,ownSuggestionTypes:[l.RelatedItemsList],parserCommand:{type:"sourced",getCommandStr:()=>o.relatedItemsListCommand}},{commandId:"switcher-plus:open-related-items-active",commandName:"Open Related Items for the active editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",handlerClass:Ee,parserCommand:{type:"prefix",getCommandStr:()=>o.relatedItemsListActiveEditorCommand,useActiveEditorAsSource:!0}},{commandId:"switcher-plus:open-vaults",commandName:"Open in Vaults Mode",mode:t.VaultList,iconId:"vault",handlerClass:Fe,ownSuggestionTypes:[l.VaultList],parserCommand:{type:"prefix",getCommandStr:()=>o.vaultListCommand}}]);var o;xe.getInstance()||xe.initialize(e,s,n),this._handlerRegistry=xe.getInstance(),this._inputParser=new Ae(this._handlerRegistry,s,n),this.debouncedGetSuggestions=a.debounce(this.getSuggestions.bind(this),s.headingsSearchDebounceMilli,!0),this.reset()}onOpen(){const{app:e,exKeymap:t,handlerRegistry:s,settings:i}=this;t.isOpen=!0,i.quickFilters?.shouldResetActiveFacets&&Object.values(i.quickFilters.facetList).forEach((e=>e.isActive=!1)),this.workspaceEnvList=this.buildWorkspaceEnvList(e.workspace,e.vault,e.viewRegistry,s,i)}onClose(){this.exKeymap.isOpen=!1,q.unload()}setSessionOpenMode(e,t){this.reset(),e?.setSuggestions([]),this.sessionOpts=Object.assign({},t)}setInitialInputForSession(e){const{mode:s}=this.sessionOpts;if(!s)return;this.sessionOpts.mode=null;const i=s===t.Standard?this.previousInputHistory[s]?.inputText:this.previousInputHistory[s]?.parsedCommand(s)?.parsedInput,n=this.handlerRegistry.getHandler(s),a=s!==t.Standard?n.getCommandString(this.sessionOpts):"";if((s===t.CommandList&&this.settings.preserveCommandPaletteLastInput||s!==t.CommandList&&this.settings.preserveQuickSwitcherLastInput)&&i?.length){e.value=a+i;const t=a?.length??0;e.setSelectionRange(t,e.value.length)}else a&&(e.value=a)}updateSuggestions(e,s,i){const{exKeymap:n,settings:a,sessionOpts:o}=this;let r=!1;this.debouncedGetSuggestions.cancel();const l=fe.getActiveLeaf(this.app.workspace),d=Pe.getActiveSuggestion(s),c=this.determineRunMode(e,d,l,o);this._inputInfo=c;const{mode:h}=c;return this.previousInputHistory[h]=c,this.updatedKeymapForMode(c,s,i,n,a,l),this.toggleMobileCreateFileButton(i,h,a),h!==t.Standard&&(h===t.HeadingsList&&c.parsedCommand().parsedInput?.length?this.debouncedGetSuggestions(c,s,i):this.getSuggestions(c,s,i),r=!0),r}toggleMobileCreateFileButton(e,s,i){if(!a.Platform.isMobile)return;const n=t[s];e.allowCreateNewFile=i.allowCreateNewFileInModeNames.includes(n),e.allowCreateNewFile||e.createButtonEl?.detach()}updatedKeymapForMode(e,t,s,i,n,a){const{mode:o}=e,r=this.handlerRegistry.getHandler(o),l=r?.getAvailableFacets(e)??[],d={mode:o,activeLeaf:a,facets:{facetList:l,facetSettings:n.quickFilters,onToggleFacet:((o,l)=>{if(l){const e=o.some((e=>!0===e.isActive));r.activateFacet(o,!e)}else r.activateFacet(o,!o[0].isActive);return this.updatedKeymapForMode(e,t,s,i,n,a),this.getSuggestions(e,t,s),!1}).bind(this)}};i.updateKeymapForMode(d)}renderSuggestion(e,s){const{handlerRegistry:i,inputInfo:n,settings:{overrideStandardModeRendering:a}}=this,{mode:o}=n,r=o===t.HeadingsList;let d=!1;const c=new Set([l.Unresolved]);if(null===e){if(r){const e=i.getHandler(o),t=n.parsedCommand(o)?.parsedInput;e.renderFileCreationSuggestion(s,t),d=!0}}else if(!c.has(e.type)&&(a||r||b(e))){const t=i.getHandler(e);t&&(d=t.renderSuggestion(e,s))}return d}onChooseSuggestion(e,s){const{handlerRegistry:i,inputInfo:n,settings:{overrideStandardModeBehaviors:a}}=this,{mode:o}=n,r=o===t.HeadingsList;let d=!1;const c=new Set([l.Unresolved]);if(null===e){if(this.noResultActionModes.includes(o)){const e=i.getHandler(o);d=!!e?.onNoResultsCreateAction(n,s)}}else if(!c.has(e.type)&&(a||r||b(e))){const t=i.getHandler(e);t&&(d=t.onChooseSuggestion(e,s))}return d}determineRunMode(e,s,i,n){const a=e??"",o=new pe(a,t.Standard,n);return 0===a.length?(this.reset(),o):(o.currentWorkspaceEnvList=this.workspaceEnvList,this.inputParser.parseInputForMode(o,s,i),o)}getSuggestions(e,t,s){t.setSuggestions([]);const{mode:i}=e,n=this.handlerRegistry.getHandler(i).getSuggestions(e),a=n=>{n?.length?(t.setSuggestions(n),Pe.setActiveSuggestion(i,t),this.exKeymap?.renderQuickOpenFlairIcons(t.suggestions,this.settings)):this.noResultActionModes.includes(i)&&e.parsedCommand(i).parsedInput?s.onNoSuggestion():t.setSuggestions(null)};Array.isArray(n)?a(n):n.then((e=>{a(e)}),(e=>{A("Error retrieving suggestions as Promise. ",e)}))}static setActiveSuggestion(e,s){if(e===t.SymbolList){const e=s.values.filter((e=>u(e))).findIndex((e=>e.item.isSelected));-1!==e&&(s.setSelectedItem(e,null),s.suggestions[s.selectedItem].scrollIntoView(!1))}}static getActiveSuggestion(e){let t=null;return e?.values&&(t=e.values[e.selectedItem]),t}reset(){this._inputInfo=new pe,this.sessionOpts={},this.handlerRegistry.resetSourcedHandlers()}buildWorkspaceEnvList(e,s,i,n,a){const o=n.getHandler(t.EditorList).getItems(),r=o.reduce(((e,t)=>{const s=H(t);return s&&e.add(s),e}),new Set),{fileBookmarks:l,nonFileBookmarks:d}=n.getHandler(t.BookmarksList).getItems(null),c=this.getAttachmentFileExtensions(i,a.fileExtAllowList),h=r.size+a.maxRecentFileSuggestionsOnInit,m=this.getRecentFiles(e,s,r,h);return{openWorkspaceLeaves:new Set(o),openWorkspaceFiles:r,fileBookmarks:l,nonFileBookmarks:d,attachmentFileExtensions:c,mostRecentFiles:m}}getAttachmentFileExtensions(e,t){const s=new Set;try{const i=new Set(["md","canvas",...t]);Object.keys(e.typeByExtension).reduce(((e,t)=>(i.has(t)||e.add(t),e)),s)}catch(e){O("Error retrieving attachment list from ViewRegistry",e)}return s}getRecentFiles(e,t,s,i=75){s=s??new Set;const n=new Set;if(i>0){const a=e.getRecentFiles({showMarkdown:!0,showCanvas:!0,showNonImageAttachments:!0,showImages:!0,maxCount:i});a?.forEach((e=>{const i=t.getAbstractFileByPath(e);w(i)&&!s.has(i)&&n.add(i)}))}return n}inputTextForStandardMode(e){const{mode:s,cleanInput:i}=this.inputInfo;let n=e;return s===t.Standard&&i?.length&&(n=i),n}inputTextForFulltextSearch(){const{inputInfo:e}=this,s=e.mode;let i=null,n=e.cleanInput;if(s!==t.Standard){const t=e.parsedCommand();n=t.parsedInput,F().includes(s)&&(i=t.source?.file)}return{mode:s,parsedInput:n,file:i}}addPropertiesToStandardSuggestions(e,s){if(!e||!s.overrideStandardModeBehaviors&&!s.overrideStandardModeRendering)return;const{handlerRegistry:i,inputInfo:{currentWorkspaceEnvList:n}}=this;for(let s=0;s{A(`Error opening file (${i?.path}) in background. `,e)}))}}const Me={Enter:"↵",Backspace:"⌫",ArrowLeft:"←",ArrowUp:"↑",ArrowDown:"↓",ArrowRight:"→",Tab:"↹"},Be={...Me,Mod:"Ctrl",Ctrl:"Ctrl",Meta:"Win",Alt:"Alt",Shift:"Shift"},Re={...Me,Mod:"⌘",Ctrl:"⌃",Meta:"⌘",Alt:"⌥",Shift:"⇧"},He=[t.EditorList,t.HeadingsList,t.RelatedItemsList,t.BookmarksList,t.SymbolList],De=[t.CommandList,t.VaultList,t.WorkspaceList,...He];class Ve{app;scope;chooser;modal;config;standardKeysInfo=[];customKeysInfo=[];savedStandardKeysInfo=[];_isOpen;customInstructionEls=new Map;standardInstructionsEl;facetKeysInfo=[];insertIntoEditorKeysInfo=[];get isOpen(){return this._isOpen}set isOpen(e){this._isOpen=e}static get modKey(){return a.Platform.isMacOS?"Meta":"Ctrl"}static get keyDisplayStr(){return a.Platform.isMacOS?Re:Be}get exModeHandler(){return this.modal?.exMode}constructor(e,t,s,i,n){this.app=e,this.scope=t,this.chooser=s,this.modal=i,this.config=n,this.initKeysInfo(n,t),this.renderModeTriggerInstructions(i.modalEl,n),this.standardInstructionsEl=i.modalEl.find(".prompt-instructions")}initKeysInfo(e,t){this.standardKeysInfo.push(),this.addCustomKeymaps(this.config),this.removeDefaultTabKeyBinding(t,e),this.registerNavigationBindings(t,e.navigationKeys),this.registerEditorTabBindings(t),this.registerCloseWhenEmptyBindings(t,e),this.registerQuickOpenBindings(t,e),this.registerFulltextSearchBindings(t,e),this.registerOpenInBackgroundBindings(t,e)}removeDefaultTabKeyBinding(e,t){if(t?.removeDefaultTabBinding){const t=e.keys.find((({modifiers:e,key:t})=>null===e&&"Tab"===t));e.unregister(t)}}registerNavigationBindings(e,t){const s=(t,s)=>{t.forEach((({modifiers:t,key:i})=>{e.register(t,i,((e,t)=>(this.navigateItems(e,s),!1)))}))};s(t?.nextKeys??[],!0),s(t?.prevKeys??[],!1)}registerFacetBinding(e,s){const{mode:i,facets:n}=s;if(n?.facetList?.length){const{facetList:s,facetSettings:a,onToggleFacet:o}=n,{keyList:r,modifiers:l,resetKey:d,resetModifiers:c}=a;let h=0;const m=(t,s,i,n)=>e.register(t,s,(()=>o(i,n)));for(let e=0;e{e.register(t[0],t[1],this.useSelectedItem.bind(this))}))}registerCloseWhenEmptyBindings(e,t){const s=t.closeWhenEmptyKeys;s?.forEach((({modifiers:t,key:s})=>{e.register(t,s,this.closeModalIfEmpty.bind(this))}))}registerQuickOpenBindings(e,t){const{isEnabled:s,modifiers:i,keyList:n}=t.quickOpen;s&&n?.forEach((t=>{e.register(i,t,this.quickOpenByIndex.bind(this))}))}quickOpenByIndex(e,t){const s=this.config.quickOpen.keyList.indexOf(t.vkey);if(-1!==s){const{chooser:i}=this;i.values.length>s&&(i.setSelectedItem(s,e),this.useSelectedItem(e,t))}return!1}registerFulltextSearchBindings(e,t){const{isEnabled:s,searchKeys:i}=t.fulltextSearch;if(s){T(this.app)&&e.register(i.modifiers,i.key,this.LaunchSystemGlobalSearch.bind(this))}}LaunchSystemGlobalSearch(e,t){const{parsedInput:s,file:i}=this.modal.exMode.inputTextForFulltextSearch();let n="";return i&&(n=`path:"${i.path}" `),this.modal.close(),T(this.app)?.openGlobalSearch(`${n}${s}`),!1}registerOpenInBackgroundBindings(e,t){const{openInBackground:{isEnabled:s,openKeys:i}}=t;if(s){const t={tab:"open in background tab",vertical:"open in background to the right",horizontal:"open in background below",window:"open in background window"};i?.filter((e=>e.hotkey)).forEach((({openType:s,hotkey:i})=>{e.register(i.modifiers,i.key,(()=>this.openInBackground(this.chooser,s))),this.createCustomKeymap(t[s],De,i,null,!0,!0)}))}}openInBackground(e,t){let s,i="vertical";"vertical"===t||"horizontal"===t?(s="split",i=t):s=t;const n=e?.values?.[e.selectedItem];return this.exModeHandler.openSuggestionInBackground(n,s,i),!1}renderQuickOpenFlairIcons(e,t){const{isEnabled:s,modifiers:i,keyList:n}=t.quickOpen;if(s)for(let t=0;te.purpose===o.purpose)),!a){const{modifiers:e,key:t,purpose:s}=o;a={isInstructionOnly:!1,command:Ve.commandDisplayStr(e,t),modifiers:e,key:t,purpose:s},i.push(a)}a.eventListener=()=>{const{modal:e,chooser:t}=this;e.close();const i=t.values?.[t.selectedItem];return this.insertIntoEditorAsLink(i,s,n),!1},a.modes=[e]}}return a}updateKeymapForMode(e){const{mode:s,activeLeaf:i}=e,{modal:n,scope:a,customKeysInfo:o,facetKeysInfo:r,standardKeysInfo:l,savedStandardKeysInfo:d,config:{insertLinkInEditor:c,showModeTriggerInstructions:h}}=this;this.updateInsertIntoEditorCommand(s,i,o,c);const m=o.filter((e=>!e.isInstructionOnly));this.unregisterKeys(a,m),this.unregisterKeys(a,r),r.length=0;const u=m.filter((e=>e.modes?.includes(s)));s===t.Standard?this.updateKeymapForStandardMode(a,u,d):this.updateKeymapForCustomModes(a,u,l,e,n),this.showModeTriggerInstructions(n.modalEl,h)}updateKeymapForStandardMode(e,t,s){const i=s.map((([e,t])=>({eventListener:t.func,...e})));this.registerKeys(e,i),s.length=0,this.registerKeys(e,t),this.toggleStandardInstructions(!0)}updateKeymapForCustomModes(e,t,s,i,n){const{savedStandardKeysInfo:a,customKeysInfo:o,facetKeysInfo:r}=this,l=this.unregisterKeys(e,s);l.length&&a.push(...l),this.registerKeys(e,t),this.registerFacetBinding(e,i),this.showCustomInstructions(n,i,o,r)}registerKeys(e,t){t.forEach((({modifiers:t,key:s,eventListener:i})=>{e.register(t,s,i)}))}unregisterKeys(e,t){const s=[],i={};t.map((e=>{const{key:t,modifiers:s}=e,n=Ve.modifiersToKeymapInfoStr(s),a=i[t];a?a[n]=e:i[t]={[n]:e}}));let n=e.keys.length;for(;n--;){const t=e.keys[n],a=i[t.key],o=a?.[t.modifiers];o&&(e.unregister(t),s.push([o,t]))}return s}detachCustomInstructionEls(){this.customInstructionEls.forEach((e=>{e.detach()}))}toggleStandardInstructions(e){const{standardInstructionsEl:t}=this;let s="none";e&&(s="",this.detachCustomInstructionEls()),t&&(t.style.display=s)}showCustomInstructions(e,t,s,i){const{mode:n,facets:a}=t,{modalEl:o}=e,r=s.filter((e=>e.modes?.includes(n)));this.toggleStandardInstructions(!1),this.renderCustomInstructions(o,r),this.renderFacetInstructions(o,a?.facetSettings,i)}renderFacetInstructions(e,t,s){if(s?.length&&t.shouldShowFacetInstructions){const i=this.getCustomInstructionsEl("facets",e);i.empty(),e.appendChild(i);const n=`filters | ${Ve.commandDisplayStr(t.modifiers)}`;this.createPromptInstructionCommandEl(i,n),s.forEach((e=>{const{facet:s,command:n,purpose:a}=e;let o,r,l=null;s?(r=n,o=s.modifiers,s.isActive&&(l=["qsp-filter-active"])):(r=t.resetKey,o=t.resetModifiers);const d=o?`(${Ve.commandDisplayStr(o)}) ${r}`:`${r}`;this.createPromptInstructionCommandEl(i,d,a,[],l)}))}}renderCustomInstructions(e,t){const s=this.getCustomInstructionsEl("custom",e);s.empty(),e.appendChild(s),t.forEach((e=>{this.createPromptInstructionCommandEl(s,e.command,e.purpose)}))}showModeTriggerInstructions(e,t){if(t){const t=this.customInstructionEls.get("modes");t&&e.appendChild(t)}}renderModeTriggerInstructions(e,t){const s=new Map([[t.headingsListCommand,"heading list"],[t.editorListCommand,"editor list"],[t.bookmarksListCommand,"bookmark list"],[t.commandListCommand,"command list"],[t.workspaceListCommand,"workspace list"],[t.vaultListCommand,"vault list"],[t.symbolListActiveEditorCommand,"symbol list (active editor)"],[t.symbolListCommand,"symbol list (embedded)"],[t.relatedItemsListActiveEditorCommand,"related items (active editor)"],[t.relatedItemsListCommand,"related items (embedded)"]]),i=this.getCustomInstructionsEl("modes",e);i.detach(),i.empty(),this.createPromptInstructionCommandEl(i,"mode triggers |"),s.forEach(((e,t)=>{this.createPromptInstructionCommandEl(i,t,e)}))}getCustomInstructionsEl(e,t){let s=this.customInstructionEls.get(e);if(!s){const i={custom:["qsp-prompt-instructions"],facets:["qsp-prompt-instructions-facets"],modes:["qsp-prompt-instructions-modes"]};s=this.createPromptInstructionsEl(i[e],t),this.customInstructionEls.set(e,s)}return s}createPromptInstructionsEl(e,t){const s={cls:["prompt-instructions",...e]};return t.createDiv(s)}createPromptInstructionCommandEl(e,t,s,i,n){i=i??[];const a=e.createDiv();return a.createSpan({cls:["prompt-instruction-command",...i],text:t}),s&&(n=n??[],a.createSpan({cls:n,text:s})),a}closeModalIfEmpty(e,t){const{modal:s,config:i}=this;i.shouldCloseModalOnBackspace&&!s?.inputEl.value&&(s.close(),e.preventDefault())}navigateToCommandHotkeySelector(e,t){const{modal:s,chooser:i,app:{setting:n}}=this,a=i.values?.[i.selectedItem];if(a){n.open();const e=n.openTabById("hotkeys");if(e){s.close();const t=a.item.id;e.setQuery(`${t}`)}}return!1}togglePinnedCommand(e,t){const{app:s,config:i,chooser:n}=this,a=n.values?.[n.selectedItem],o=Te.getEnabledCommandPalettePluginInstance(s);if(a&&o){const e=a.item.id,t=n.suggestions[n.selectedItem];let r=o.options?.pinned;if(r){const t=r.indexOf(e);a.isPinned=-1===t,a.isPinned?r.push(e):r.splice(t,1)}else r=[e],o.options.pinned=r;o.saveSettings(o.plugin),t.empty(),new Te(s,i).renderSuggestion(a,t)}return!1}toggleEditorLeafPinned(e,t){const{chooser:s}=this,i=s.values?.[s.selectedItem];if(i){const e=i.item;e.togglePinned(),i.isPinned=ke.isLeafPinned(e);const t=s.suggestions[s.selectedItem];t.empty(),this.exModeHandler.renderSuggestion(i,t)}return!1}toggleMarkdownContentRendering(e,t){const{app:i,config:n,chooser:a}=this,o=a.values?.[a.selectedItem],r=o.file;let l=null;if(u(o)?l=o.item:g(o)&&(l={type:"symbolInfo",symbol:o.item,symbolType:s.Heading}),l&&r&&n.shouldRenderSymbolAsHTML(l.symbolType)){const e=a.suggestions[a.selectedItem].find(".qsp-title"),t=0===e.findAll(".qsp-rendered-container").length;e.empty(),Ie.renderSymbolContent(i,n,e,l,r,o.match,t)}return!1}openDefaultApp(e,t){const{app:s,config:{openDefaultApp:{excludeFileExtensions:i}},chooser:n}=this,a=n.values?.[n.selectedItem],o=W(a);if(o&&!i.includes(o.extension)){const e=`Error opening file (${o.path}) in default app. `;s.openWithDefaultApp(o.path).catch((t=>{A(e,t)}))}return!1}saveCurrentAndOpenSelectedWorkspace(){const{app:e,chooser:t,modal:s}=this,i=t?.values?.[t.selectedItem];if(i&&i.item){const t=be.getEnabledWorkspacesPluginInstance(e);t&&(t.saveWorkspace(t.activeWorkspace),t.loadWorkspace(i.item.id),s.close())}return!1}useSelectedItem(e,t){return this.chooser.useSelectedItem(e),!1}insertIntoEditorAsLink(e,t,s){const{app:{workspace:i,fileManager:n,vault:o}}=this,r=i.getActiveViewOfType(a.MarkdownView),l=r?.leaf===t,d=r?.file;if(l&&d){const t=D(n,o,e,d.path,s);t&&r.editor?.replaceSelection(t)}}navigateItems(e,t){const{isOpen:s,chooser:i}=this;if(s){let s=i.selectedItem;s=t?++s:--s,i.setSelectedItem(s,e)}}static commandDisplayStr(e,t){const{keyDisplayStr:s}=this;let i=null,n=null;return e&&(i=e.map((e=>s[e]?.toLocaleLowerCase())).sort().join(" ")),t&&(n=Object.prototype.hasOwnProperty.call(s,t)?s[t]:t),[i,n].filter((e=>e)).join(" ")}static modifiersToKeymapInfoStr(e){return e?.map((e=>"Mod"===e?this.modKey:e)).sort().join(",")}createCustomKeymap(e,t,s,i,n=!0,a=!1){let o=null;if(s){const{modifiers:r,key:l}=s;o={modes:t,modifiers:r,key:l,eventListener:i,purpose:e,command:Ve.commandDisplayStr(r,l),isInstructionOnly:a},n&&this.customKeysInfo.push(o)}return o}addCustomKeymaps(e){const{quickOpen:s}=e,i=s?.keyList;if(i?.length){const e=`${i[0]}~${i[i.length-1]}`;this.createCustomKeymap("open nth item",De,{modifiers:s.modifiers,key:e},null,s.isEnabled,!0)}this.createCustomKeymap("open in new tab",He,{modifiers:["Mod"],key:"Enter"},null,!0,!0),this.createCustomKeymap("open to the right",He,{modifiers:["Mod"],key:"\\"},null,!0,!0),this.createCustomKeymap("open below",He,{modifiers:["Mod","Shift"],key:"\\"},null,!0,!0),this.createCustomKeymap("open in new window",He,{modifiers:["Mod"],key:"o"},null,!0,!0),this.createCustomKeymap("execute command",[t.CommandList],{modifiers:[],key:"Enter"},null,!0,!0),this.createCustomKeymap("open workspace",[t.WorkspaceList],{modifiers:[],key:"Enter"},null,!0,!0),this.createCustomKeymap("save and switch workspace",[t.WorkspaceList],e.saveWorkspaceAndSwitchKeys,this.saveCurrentAndOpenSelectedWorkspace.bind(this)),this.createCustomKeymap("set hotkey",[t.CommandList],e.navigateToHotkeySelectorKeys,this.navigateToCommandHotkeySelector.bind(this)),this.createCustomKeymap("toggle pinned",[t.CommandList],e.togglePinnedCommandKeys,this.togglePinnedCommand.bind(this)),this.createCustomKeymap("toggle pinned",[t.EditorList],e.togglePinnedCommandKeys,this.toggleEditorLeafPinned.bind(this));const{renderMarkdownContentInSuggestions:n}=e;this.createCustomKeymap("toggle preview (selected item)",[t.HeadingsList,t.SymbolList],n.toggleContentRenderingKeys,this.toggleMarkdownContentRendering.bind(this),n.isEnabled);const{openDefaultApp:a}=e;this.createCustomKeymap("open default app",He,a.openInDefaultAppKeys,this.openDefaultApp.bind(this),a.isEnabled);const{fulltextSearch:o}=e;this.createCustomKeymap("fulltext search",De,o.searchKeys,null,o.isEnabled,!0)}}class We{static coreMobileLauncherButtonEl;static qspMobileLauncherButtonEl;static installMobileLauncherOverride(e,t,s){let i=null;if(!(a.Platform.isMobile&&t.isEnabled&&t.isMobileButtonEnabled)||We.coreMobileLauncherButtonEl)return null;const n=function(e,t){let s=null;const i=e?.mobileNavbar?.containerEl;return i&&(s=i.find(ie.defaults.mobileLauncher.coreLauncherButtonSelector),s||(s=i.find(t.coreLauncherButtonSelector))),s}(e,t);if(n){const e=function(e,t,s){let i=null;if(e&&(i=e.cloneNode(!0),i)){const{iconName:e,coreLauncherButtonIconSelector:n}=t;if(i.addClass("qsp-mobile-launcher-button"),i.addEventListener("click",s),e?.length){const t=i.find(n);t&&a.setIcon(t,e)}}return i}(n,t,s);(function(e,t){let s=!1;return e&&t&&(t.toggleClass("qsp-hidden",!0),e.insertAdjacentElement("beforebegin",t)&&(e.remove(),s=!0),t.toggleClass("qsp-hidden",!1)),s})(n,e)&&(We.coreMobileLauncherButtonEl=n,We.qspMobileLauncherButtonEl=e,i=e)}return i}static removeMobileLauncherOverride(){let e=!1;if(!We.coreMobileLauncherButtonEl)return e;if(We.qspMobileLauncherButtonEl?.parentElement){const t=We.qspMobileLauncherButtonEl,s=We.coreMobileLauncherButtonEl;s.toggleClass("qsp-hidden",!0),t.insertAdjacentElement("beforebegin",s)&&(t.remove(),We.qspMobileLauncherButtonEl=null,We.coreMobileLauncherButtonEl=null,e=!0),s.toggleClass("qsp-hidden",!1)}return e}}class Ne{static emptyLeaves=new Map;static layoutChangeEventRef;static installEmptyTabMonitor(e,t){if(!t?.isEnabled)return;const{workspace:s}=e.app;Ne.layoutChangeEventRef=s.on("layout-change",(()=>{Ne.updateEmptyTabs(s,t)})),e.registerEvent(Ne.layoutChangeEventRef),s.onLayoutReady((()=>{Ne.updateEmptyTabs(s,t)}))}static removeEmptyTabButtons(e){e.offref(Ne.layoutChangeEventRef),Ne.layoutChangeEventRef=null;const{emptyLeaves:t}=Ne;for(const e of t.keys())t.get(e)?.detach(),t.delete(e)}static updateEmptyTabs(e,t){if(!t.isEnabled)return;const{buttonLabel:s,onclickListener:i}=t;e.iterateAllLeaves((e=>{const{emptyLeaves:t}=Ne;if(K(e,"empty")&&!t.has(e)){const{containerEl:n}=e.view,a=function(e,t,s){let i=null;const n=e.find(".empty-state-action-list");return n&&(i=n.createDiv({cls:["empty-state-action","tappable","qsp-empty-state-action-launch"],text:t}),i.addEventListener("click",s),n.firstElementChild!==i&&n.insertAfter(i,n.firstElementChild)),i}(n,s,i);a&&t.set(e,a)}}))}}const Ke=[{id:"switcher-plus:open",name:"Open in Standard Mode",mode:t.Standard,iconId:"lucide-file-search",ribbonIconEl:null},{id:"switcher-plus:open-editors",name:"Open in Editor Mode",mode:t.EditorList,iconId:"lucide-file-edit",ribbonIconEl:null},{id:"switcher-plus:open-symbols",name:"Open Symbols for selected suggestion or editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",ribbonIconEl:null},{id:"switcher-plus:open-symbols-active",name:"Open Symbols for the active editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",ribbonIconEl:null,sessionOpts:{useActiveEditorAsSource:!0}},{id:"switcher-plus:open-workspaces",name:"Open in Workspaces Mode",mode:t.WorkspaceList,iconId:"lucide-album",ribbonIconEl:null},{id:"switcher-plus:open-headings",name:"Open in Headings Mode",mode:t.HeadingsList,iconId:"lucide-file-search",ribbonIconEl:null},{id:"switcher-plus:open-starred",name:"Open in Bookmarks Mode",mode:t.BookmarksList,iconId:"lucide-bookmark",ribbonIconEl:null},{id:"switcher-plus:open-commands",name:"Open in Commands Mode",mode:t.CommandList,iconId:"run-command",ribbonIconEl:null},{id:"switcher-plus:open-related-items",name:"Open Related Items for selected suggestion or editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",ribbonIconEl:null},{id:"switcher-plus:open-related-items-active",name:"Open Related Items for the active editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",ribbonIconEl:null,sessionOpts:{useActiveEditorAsSource:!0}},{id:"switcher-plus:open-vaults",name:"Open in Vaults Mode",mode:t.VaultList,iconId:"vault",ribbonIconEl:null}];class qe extends a.Plugin{options;async onload(){const e=new ie(this);await e.updateDataAndLoadSettings(),this.options=e,this.addSettingTab(new ge(this.app,this,e)),this.registerRibbonCommandIcons(),this.updateLauncherButtonOverrides(!0),Ke.forEach((({id:e,name:t,mode:s,iconId:i,sessionOpts:n})=>{this.registerCommand(e,t,s,i,n)}))}onunload(){this.updateLauncherButtonOverrides(!1)}registerCommand(e,t,s,i,n){this.addCommand({id:e,name:t,icon:i,checkCallback:e=>this.createModalAndOpen(s,e,n)})}registerRibbonCommandIcons(){Ke.forEach((e=>{e.ribbonIconEl?.remove(),e.ribbonIconEl=null}));const e=Ke.reduce(((e,t)=>(e[t.mode]=t,e)),{});this.options.enabledRibbonCommands.forEach((s=>{const i=e[t[s]];i&&(i.ribbonIconEl=this.addRibbonIcon(i.iconId,i.name,(()=>{this.createModalAndOpen(i.mode,!1)})))}))}createModalAndOpen(e,t,s){if(!t){const t=function(e,t){const s=L(e)?.QuickSwitcherModal;return s?new class extends s{plugin;_exMode;get exMode(){return this._exMode}constructor(e,t){super(e,t.options.builtInSystemOptions),this.plugin=t;const{options:s}=t;s.shouldShowAlias=this.shouldShowAlias;const i=new Ve(e,this.scope,this.chooser,this,s);this._exMode=new Pe(e,s,i)}openInMode(e){this.exMode.setSessionOpenMode(this.chooser,e),super.open()}onOpen(){this.exMode.onOpen(),super.onOpen()}onClose(){super.onClose(),this.exMode.onClose()}updateSuggestions(){const{exMode:e,inputEl:t,chooser:s}=this;e.setInitialInputForSession(t),e.updateSuggestions(t.value,s,this)||super.updateSuggestions()}getSuggestions(e){const{exMode:t,plugin:s}=this,i=t.inputTextForStandardMode(e),n=super.getSuggestions(i);return t.addPropertiesToStandardSuggestions(n,s.options),n}onChooseSuggestion(e,t){this.exMode.onChooseSuggestion(e,t)||super.onChooseSuggestion(e,t)}renderSuggestion(e,t){this.exMode.renderSuggestion(e,t)||super.renderSuggestion(e,t)}}(e,t):(O("Unable to extend system switcher. Plugin UI will not be loaded. Use the builtin switcher instead."),null)}(this.app,this);if(!t)return!1;const i=Object.assign({mode:e},s);t.openInMode(i)}return!0}updateLauncherButtonOverrides(e){const{app:s,options:{mobileLauncher:i}}=this;if(We.removeMobileLauncherOverride(),Ne.removeEmptyTabButtons(s.workspace),e){const e=i.modeString,n=t[e],a=()=>{n&&this.createModalAndOpen(n,!1)};We.installMobileLauncherOverride(s,i,a);const o=Ke.find((e=>e.mode===n)),r="Switcher++: "+(o?.name??"");Ne.installEmptyTabMonitor(this,{isEnabled:i.isEnabled&&i.isEmptyTabButtonEnabled,buttonLabel:r,onclickListener:a})}}}module.exports=qe; /* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/darlal-switcher-plus/manifest.json b/.obsidian/plugins/darlal-switcher-plus/manifest.json index 2c5257a2..a2f3bfe1 100644 --- a/.obsidian/plugins/darlal-switcher-plus/manifest.json +++ b/.obsidian/plugins/darlal-switcher-plus/manifest.json @@ -1,7 +1,7 @@ { "id": "darlal-switcher-plus", "name": "Quick Switcher++", - "version": "6.1.3", + "version": "6.1.4", "minAppVersion": "1.12.7", "description": "Enhanced Quick Switcher, search open panels, and symbols.", "author": "darlal", diff --git a/.obsidian/plugins/darlal-switcher-plus/styles.css b/.obsidian/plugins/darlal-switcher-plus/styles.css index aa08e500..ec627426 100644 --- a/.obsidian/plugins/darlal-switcher-plus/styles.css +++ b/.obsidian/plugins/darlal-switcher-plus/styles.css @@ -66,16 +66,6 @@ justify-content: left; } -/* highlight recently used file suggestions */ -.suggestion-item.qsp-recent-file .qsp-title { - text-decoration: underline dotted var(--text-muted); -} - -/* highlight currently open editor suggestions */ -.suggestion-item.qsp-open-editor .qsp-title { - text-decoration: underline var(--text-accent); -} - /* highlight the open editor flair icon */ .suggestion-item.qsp-open-editor .suggestion-aux.qsp-aux .qsp-editor-indicator, .suggestion-item.qsp-open-editor .suggestion-aux.qsp-aux .qsp-editor-indicator svg { diff --git a/.obsidian/plugins/header-enhancer/main.js b/.obsidian/plugins/header-enhancer/main.js index c93832eb..601d7a2f 100644 --- a/.obsidian/plugins/header-enhancer/main.js +++ b/.obsidian/plugins/header-enhancer/main.js @@ -7,8 +7,13 @@ var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +var __esm = (fn, res, err) => function __init() { + if (err) throw err[0]; + try { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; + } catch (e) { + throw err = [e], e; + } }; var __export = (target, all) => { for (var name in all) @@ -27,8 +32,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/core.ts function getHeaderLevel(text, startHeaderLevel) { const match = text.match(/^#+/); - if (!match) - return [0, 0]; + if (!match) return [0, 0]; let level = match ? match[0].length : 0; return [level - startHeaderLevel + 1, level]; } @@ -46,8 +50,7 @@ function getNextNumber(cntNums, headerLevel) { } function isNeedInsertNumber(text, splitor) { const match = text.match(/^(#{1,6})\s+(.*)/); - if (!match) - return false; + if (!match) return false; const contentAfterHash = match[2]; if (splitor == " ") { return !/^\d+(?:\.\d+)*\s+/.test(contentAfterHash); @@ -57,35 +60,30 @@ function isNeedInsertNumber(text, splitor) { } function isNeedUpdateNumber(nextNumsStr, text, splitor) { const match = text.match(/^(#{1,6})\s+(.*)/); - if (!match) - return false; + if (!match) return false; const contentAfterHash = match[2]; let cntNumsStr; if (splitor == " ") { const numMatch = contentAfterHash.match(/^(\d+(?:\.\d+)*)\s+/); - if (!numMatch) - return true; + if (!numMatch) return true; cntNumsStr = numMatch[1]; } else { const parts = contentAfterHash.split(splitor); - if (parts.length < 2) - return true; + if (parts.length < 2) return true; cntNumsStr = parts[0].trim(); } return nextNumsStr !== cntNumsStr; } function removeHeaderNumber(text, splitor) { const match = text.match(/^(#{1,6})\s+(.*)/); - if (!match) - return text; + if (!match) return text; const sharp = match[1]; const contentAfterHash = match[2]; if (splitor == " ") { const header = contentAfterHash.replace(/^\d+(?:\.\d+)*\s+/, ""); return sharp + " " + header; } else { - if (!contentAfterHash.contains(splitor)) - return text; + if (!contentAfterHash.contains(splitor)) return text; const parts = contentAfterHash.split(splitor); const header = parts.slice(1).join(splitor).trim(); return sharp + " " + header; @@ -112,8 +110,7 @@ function analyzeHeaderLevels(content) { let headerCount = 0; for (const line of lines) { isCodeBlock = updateCodeBlockState(line, isCodeBlock); - if (isCodeBlock) - continue; + if (isCodeBlock) continue; if (isHeader(line)) { const match = line.match(/^#+/); if (match) { @@ -779,15 +776,15 @@ var init_i18n = __esm({ en: en_default, zh: zh_default }; - I18n = class { + I18n = class _I18n { constructor() { this.currentLanguage = "en"; } static getInstance() { - if (!I18n.instance) { - I18n.instance = new I18n(); + if (!_I18n.instance) { + _I18n.instance = new _I18n(); } - return I18n.instance; + return _I18n.instance; } setLanguage(lang) { if (translations[lang]) { @@ -990,9 +987,9 @@ var init_dialogs = __esm({ }); }); this.progressContainer = contentEl.createDiv({ - cls: "progress-container", - attr: { style: "display: none;" } + cls: "progress-container" }); + this.progressContainer.hide(); } async handleRemoveAndTurnOff() { this.isProcessing = true; @@ -1023,7 +1020,7 @@ var init_dialogs = __esm({ showProgress() { const i18n = I18n.getInstance(); if (this.progressContainer) { - this.progressContainer.style.display = "block"; + this.progressContainer.show(); this.progressContainer.empty(); this.progressContainer.createEl("p", { text: i18n.t("settings.autoNumbering.removeConfirmation.processing"), @@ -1036,7 +1033,7 @@ var init_dialogs = __esm({ } hideProgress() { if (this.progressContainer) { - this.progressContainer.style.display = "none"; + this.progressContainer.hide(); this.progressContainer.empty(); } this.contentEl.querySelectorAll("button").forEach((button) => { @@ -1057,16 +1054,16 @@ var init_dialogs = __esm({ const modified = await this.processFile(file); if (modified) { modifiedCount++; - await new Promise((resolve) => setTimeout(resolve, 10)); + await new Promise((resolve) => window.setTimeout(resolve, 10)); } processedCount++; this.updateProgress(processedCount, totalFiles); } catch (error) { console.error(`Error processing file ${file.path}:`, error); } - await new Promise((resolve) => setTimeout(resolve, 5)); + await new Promise((resolve) => window.setTimeout(resolve, 5)); } - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => window.setTimeout(resolve, 50)); } if (modifiedCount > 0) { new import_obsidian2.Notice(i18n.t("settings.autoNumbering.removeConfirmation.completed", { @@ -1104,7 +1101,7 @@ var init_dialogs = __esm({ if (modified) { await this.app.vault.modify(file, lines.join("\n")); if (isCurrentlyOpen) { - await new Promise((resolve) => setTimeout(resolve, 20)); + await new Promise((resolve) => window.setTimeout(resolve, 20)); } if (this.plugin.settings.updateBacklinks) { } @@ -1191,9 +1188,9 @@ var init_dialogs = __esm({ }); }); this.progressContainer = contentEl.createDiv({ - cls: "progress-container", - attr: { style: "display: none;" } + cls: "progress-container" }); + this.progressContainer.hide(); } async handleAddToAll() { this.isProcessing = true; @@ -1224,7 +1221,7 @@ var init_dialogs = __esm({ showProgress() { const i18n = I18n.getInstance(); if (this.progressContainer) { - this.progressContainer.style.display = "block"; + this.progressContainer.show(); this.progressContainer.empty(); this.progressContainer.createEl("p", { text: i18n.t("settings.autoNumbering.activationConfirmation.processing"), @@ -1237,7 +1234,7 @@ var init_dialogs = __esm({ } hideProgress() { if (this.progressContainer) { - this.progressContainer.style.display = "none"; + this.progressContainer.hide(); this.progressContainer.empty(); } this.contentEl.querySelectorAll("button").forEach((button) => { @@ -1258,16 +1255,16 @@ var init_dialogs = __esm({ const modified = await this.processFile(file); if (modified) { modifiedCount++; - await new Promise((resolve) => setTimeout(resolve, 10)); + await new Promise((resolve) => window.setTimeout(resolve, 10)); } processedCount++; this.updateProgress(processedCount, totalFiles); } catch (error) { console.error(`Error processing file ${file.path}:`, error); } - await new Promise((resolve) => setTimeout(resolve, 5)); + await new Promise((resolve) => window.setTimeout(resolve, 5)); } - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => window.setTimeout(resolve, 50)); } if (modifiedCount > 0) { new import_obsidian2.Notice(i18n.t("settings.autoNumbering.activationConfirmation.completed", { @@ -1323,7 +1320,7 @@ var init_dialogs = __esm({ if (modified) { await this.app.vault.modify(file, lines.join("\n")); if (isCurrentlyOpen) { - await new Promise((resolve) => setTimeout(resolve, 20)); + await new Promise((resolve) => window.setTimeout(resolve, 20)); } } return modified; @@ -1352,7 +1349,7 @@ var init_dialogs = __esm({ }); // src/setting.ts -var import_obsidian3, DEFAULT_SETTINGS, HeaderEnhancerSettingTab; +var import_obsidian3, DEFAULT_SETTINGS, ResetSettingsConfirmModal, HeaderEnhancerSettingTab; var init_setting = __esm({ "src/setting.ts"() { import_obsidian3 = require("obsidian"); @@ -1390,10 +1387,31 @@ var init_setting = __esm({ titleFontFamily: "inherit", titleFontSize: "inherit" }; + ResetSettingsConfirmModal = class extends import_obsidian3.Modal { + constructor(app, message, onConfirm) { + super(app); + this.message = message; + this.onConfirm = onConfirm; + } + onOpen() { + const { contentEl } = this; + contentEl.empty(); + contentEl.addClass("header-enhancer-reset-confirm"); + contentEl.createEl("p", { text: this.message }); + new import_obsidian3.Setting(contentEl).addButton((button) => { + button.setButtonText("Cancel").onClick(() => this.close()); + }).addButton((button) => { + button.setButtonText("Reset").setWarning().onClick(async () => { + await this.onConfirm(); + this.close(); + }); + }); + } + }; HeaderEnhancerSettingTab = class extends import_obsidian3.PluginSettingTab { constructor(app, plugin) { super(app, plugin); - this.formatPreviewSetting = null; + this.formatPreviewContainer = null; this.autoDetectionPreviewContainer = null; this.plugin = plugin; } @@ -1401,7 +1419,7 @@ var init_setting = __esm({ const { containerEl } = this; const i18n = I18n.getInstance(); containerEl.empty(); - this.formatPreviewSetting = null; + this.formatPreviewContainer = null; this.autoDetectionPreviewContainer = null; containerEl.createEl("h1", { text: i18n.t("settings.title") }); containerEl.createEl("h2", { text: i18n.t("settings.general") }); @@ -1445,22 +1463,14 @@ var init_setting = __esm({ const globalDisabledInfo = containerEl.createDiv({ cls: "header-enhancer-global-disabled-info" }); - globalDisabledInfo.style.cssText = ` - margin: 1.5em 0; - padding: 1.2em; - border: 2px solid var(--text-muted); - border-radius: 8px; - background: var(--background-secondary); - opacity: 0.8; - `; - globalDisabledInfo.innerHTML = ` -
- ${i18n.t("settings.autoNumbering.globalDisabled.title")} -
-
- ${i18n.t("settings.autoNumbering.globalDisabled.description")} -
- `; + globalDisabledInfo.createDiv({ + text: i18n.t("settings.autoNumbering.globalDisabled.title"), + cls: "header-enhancer-info-title" + }); + globalDisabledInfo.createDiv({ + text: i18n.t("settings.autoNumbering.globalDisabled.description"), + cls: "header-enhancer-info-description" + }); return; } new import_obsidian3.Setting(containerEl).setName(i18n.t("settings.autoNumbering.mode.name")).setDesc(i18n.t("settings.autoNumbering.mode.desc")).addDropdown((dropdown) => { @@ -1517,22 +1527,14 @@ var init_setting = __esm({ const offInfo = containerEl.createDiv({ cls: "header-enhancer-off-info" }); - offInfo.style.cssText = ` - margin: 1.5em 0; - padding: 1.2em; - border: 2px solid var(--text-muted); - border-radius: 8px; - background: var(--background-secondary); - opacity: 0.8; - `; - offInfo.innerHTML = ` -
- ${i18n.t("autoDetection.info.offMode.title")} -
-
- ${i18n.t("autoDetection.info.offMode.description")} -
- `; + offInfo.createDiv({ + text: i18n.t("autoDetection.info.offMode.title"), + cls: "header-enhancer-info-title" + }); + offInfo.createDiv({ + text: i18n.t("autoDetection.info.offMode.description"), + cls: "header-enhancer-info-description" + }); } containerEl.createEl("h2", { text: i18n.t("settings.headerFont.title") }); new import_obsidian3.Setting(containerEl).setName(i18n.t("settings.headerFont.separate.name")).setDesc(i18n.t("settings.headerFont.separate.desc")).addToggle((toggle) => { @@ -1545,13 +1547,6 @@ var init_setting = __esm({ }); if (this.plugin.settings.isSeparateHeaderFont) { const previewContainer = containerEl.createDiv({ cls: "header-enhancer-font-preview" }); - previewContainer.style.cssText = ` - margin: 1em 0; - padding: 1em; - border: 1px solid var(--background-modifier-border); - border-radius: 6px; - background: var(--background-secondary); - `; previewContainer.createEl("div", { text: i18n.t("settings.headerFont.preview.title"), cls: "setting-item-name" @@ -1579,13 +1574,6 @@ var init_setting = __esm({ }); if (this.plugin.settings.isSeparateTitleFont) { const previewContainer = containerEl.createDiv({ cls: "header-enhancer-title-font-preview" }); - previewContainer.style.cssText = ` - margin: 1em 0; - padding: 1em; - border: 1px solid var(--background-modifier-border); - border-radius: 6px; - background: var(--background-secondary); - `; previewContainer.createEl("div", { text: i18n.t("settings.titleFont.preview.title"), cls: "setting-item-name" @@ -1595,20 +1583,21 @@ var init_setting = __esm({ text: i18n.t("settings.titleFont.preview.sample"), cls: "header-enhancer-preview-title" }); - titleEl.style.cssText = "font-size: 1.5em; font-weight: bold; margin: 0.5em 0;"; this.updateTitlePreviewStyles(titleEl); } this.createFontFamilySetting(containerEl, "title"); this.createFontSizeSetting(containerEl, "title"); new import_obsidian3.Setting(containerEl).addButton((button) => { button.setButtonText(i18n.t("settings.resetSettings.name")).onClick(async () => { - if (confirm( - i18n.t("settings.resetSettings.confirm") - )) { - this.plugin.settings = DEFAULT_SETTINGS; - await this.plugin.saveSettings(); - this.display(); - } + new ResetSettingsConfirmModal( + this.app, + i18n.t("settings.resetSettings.confirm"), + async () => { + this.plugin.settings = DEFAULT_SETTINGS; + await this.plugin.saveSettings(); + this.display(); + } + ).open(); }); }); containerEl.createEl("h2", { text: i18n.t("settings.moreInfo") }); @@ -1657,24 +1646,10 @@ var init_setting = __esm({ this.autoDetectionPreviewContainer = containerEl.createDiv({ cls: "header-enhancer-auto-detection-preview" }); - this.autoDetectionPreviewContainer.style.cssText = ` - margin: 1em 0; - padding: 1.2em; - border: 2px solid var(--color-green); - border-radius: 8px; - background: var(--background-secondary); - position: relative; - `; - const previewTitle2 = this.autoDetectionPreviewContainer.createDiv(); - previewTitle2.style.cssText = ` - font-weight: 600; - font-size: 1em; - color: var(--color-green); - margin-bottom: 0.8em; - display: flex; - align-items: center; - `; - previewTitle2.innerHTML = "\u{1F527} \u667A\u80FD\u68C0\u6D4B\u7ED3\u679C"; + this.autoDetectionPreviewContainer.createDiv({ + text: "\u{1F527} \u667A\u80FD\u68C0\u6D4B\u7ED3\u679C", + cls: "header-enhancer-auto-detection-title" + }); this.updateAutoDetectionPreview(); } else { new import_obsidian3.Setting(containerEl).setName(i18n.t("settings.headerLevel.start.name")).setDesc(i18n.t("settings.headerLevel.start.desc")).addDropdown((dropdown) => { @@ -1774,29 +1749,21 @@ var init_setting = __esm({ const formatPreviewContainer = containerEl.createDiv({ cls: "header-enhancer-format-preview-container" }); - formatPreviewContainer.style.cssText = ` - margin: 1.5em 0; - `; - const previewTitle = formatPreviewContainer.createDiv(); - previewTitle.style.cssText = ` - font-weight: 600; - font-size: 1.1em; - color: var(--text-accent); - margin-bottom: 1em; - display: flex; - align-items: center; - gap: 0.5em; - `; - previewTitle.innerHTML = `\u{1F3AF} ${i18n.t("settings.autoNumbering.format.name")}`; + const previewTitle = formatPreviewContainer.createDiv({ + cls: "header-enhancer-format-preview-title" + }); + previewTitle.createSpan({ + text: "\u{1F3AF}", + cls: "header-enhancer-format-preview-icon" + }); + previewTitle.createSpan({ + text: i18n.t("settings.autoNumbering.format.name") + }); const previewContent = formatPreviewContainer.createDiv({ cls: "format-preview-content" }); - this.formatPreviewSetting = { - setDesc: (content) => { - previewContent.innerHTML = content; - } - }; - previewContent.innerHTML = this.getFormatPreview(); + this.formatPreviewContainer = previewContent; + this.renderFormatPreview(previewContent); } /** * Create font family setting for header or title @@ -1917,8 +1884,7 @@ var init_setting = __esm({ * Update auto detection preview */ updateAutoDetectionPreview() { - if (!this.autoDetectionPreviewContainer) - return; + if (!this.autoDetectionPreviewContainer) return; const i18n = I18n.getInstance(); const activeView = this.app.workspace.getActiveViewOfType(import_obsidian3.MarkdownView); let contentContainer = this.autoDetectionPreviewContainer.querySelector(".preview-content"); @@ -1927,90 +1893,103 @@ var init_setting = __esm({ cls: "preview-content" }); } + contentContainer.empty(); if (!activeView) { - contentContainer.innerHTML = `
${i18n.t("autoDetection.noActiveDocument")}
`; + contentContainer.createDiv({ + text: i18n.t("autoDetection.noActiveDocument"), + cls: "header-enhancer-muted-italic" + }); this.updateFormatPreview(); return; } const content = activeView.editor.getValue(); const analysis = analyzeHeaderLevels(content); - contentContainer.innerHTML = ` -
- ${this.formatAnalysisResult(analysis)} -
- `; + this.renderAnalysisResult(contentContainer, analysis); this.updateFormatPreview(); } /** - * Format analysis result for display + * Render analysis result for display */ - formatAnalysisResult(analysis) { + renderAnalysisResult(containerEl, analysis) { const i18n = I18n.getInstance(); if (analysis.isEmpty) { - return `
- \u{1F4DD} ${i18n.t("autoDetection.noHeaders")} -
`; + containerEl.createDiv({ + text: `\u{1F4DD} ${i18n.t("autoDetection.noHeaders")}`, + cls: "header-enhancer-empty-analysis" + }); + return; } - const levelNames = analysis.usedLevels.map((level) => `H${level}`).join(" "); - const mappingInfo = analysis.usedLevels.map( - (level, index) => `H${level}\u2192${index + 1}\u7EA7` - ).join(" "); - return ` -
-
- ${i18n.t("autoDetection.detected")}: -
${levelNames}
-
-
- ${i18n.t("autoDetection.range")}: - H${analysis.minLevel} - H${analysis.maxLevel} -
-
- ${i18n.t("autoDetection.mapping")}: -
${mappingInfo}
-
-
- ${i18n.t("autoDetection.totalHeaders")}: - ${analysis.headerCount} -
-
- `; + const grid = containerEl.createDiv({ + cls: "header-enhancer-analysis-grid" + }); + const detectedRow = this.createAnalysisRow(grid, `${i18n.t("autoDetection.detected")}:`); + analysis.usedLevels.forEach((level) => { + detectedRow.createSpan({ + text: `H${level}`, + cls: "header-enhancer-level-chip" + }); + }); + const rangeRow = this.createAnalysisRow(grid, `${i18n.t("autoDetection.range")}:`); + rangeRow.createSpan({ + text: `H${analysis.minLevel} - H${analysis.maxLevel}`, + cls: "header-enhancer-range-badge" + }); + const mappingRow = this.createAnalysisRow(grid, `${i18n.t("autoDetection.mapping")}:`, true); + analysis.usedLevels.forEach((level, index) => { + mappingRow.createSpan({ + text: `H${level}\u2192${index + 1}\u7EA7`, + cls: "header-enhancer-mapping-chip" + }); + }); + const totalRow = this.createAnalysisRow(grid, `${i18n.t("autoDetection.totalHeaders")}:`); + totalRow.createSpan({ + text: analysis.headerCount.toString(), + cls: "header-enhancer-total-badge" + }); } /** - * Get format preview string + * Create an analysis row and return its value container. */ - getFormatPreview() { + createAnalysisRow(containerEl, label, alignStart = false) { + const row = containerEl.createDiv({ + cls: alignStart ? "header-enhancer-analysis-row header-enhancer-analysis-row-start" : "header-enhancer-analysis-row" + }); + row.createEl("strong", { + text: label, + cls: "header-enhancer-analysis-label" + }); + return row.createDiv({ + cls: "header-enhancer-analysis-values" + }); + } + /** + * Render format preview + */ + renderFormatPreview(containerEl) { const i18n = I18n.getInstance(); + containerEl.empty(); switch (this.plugin.settings.autoNumberingMode) { case "off" /* OFF */: - return `
-
\u23F9\uFE0F
-
${i18n.t("settings.autoNumbering.format.disabled")}
-
`; + this.renderEmptyFormatState( + containerEl, + "\u23F9\uFE0F", + i18n.t("settings.autoNumbering.format.disabled"), + "header-enhancer-format-state-muted" + ); + return; case "yaml" /* YAML_CONTROLLED */: - return `
-
\u{1F4C4}
-
${i18n.t("settings.autoNumbering.format.yamlControlled")}
-
`; + this.renderEmptyFormatState( + containerEl, + "\u{1F4C4}", + i18n.t("settings.autoNumbering.format.yamlControlled"), + "header-enhancer-format-state-yaml" + ); + return; case "on" /* ON */: default: const formatExample = this.plugin.settings.autoNumberingStartNumber + this.plugin.settings.autoNumberingSeparator + "1" + this.plugin.settings.autoNumberingSeparator + "1"; let levelInfo; - let statusBadge; + let statusClass; if (this.plugin.settings.isAutoDetectHeaderLevel) { const activeView = this.app.workspace.getActiveViewOfType(import_obsidian3.MarkdownView); if (activeView) { @@ -2018,95 +1997,68 @@ var init_setting = __esm({ const analysis = analyzeHeaderLevels(content); if (!analysis.isEmpty) { levelInfo = `${i18n.t("settings.autoNumbering.format.fromLevel")} H${analysis.minLevel} ${i18n.t("settings.autoNumbering.format.toLevel")} H${analysis.maxLevel}`; - statusBadge = `${i18n.t("settings.autoNumbering.format.autoDetect")}`; + statusClass = "header-enhancer-status-auto"; } else { levelInfo = i18n.t("autoDetection.noHeaders"); - statusBadge = `${i18n.t("settings.autoNumbering.format.autoDetect")}`; + statusClass = "header-enhancer-status-warning"; } } else { levelInfo = i18n.t("autoDetection.noActiveDocument"); - statusBadge = `${i18n.t("settings.autoNumbering.format.autoDetect")}`; + statusClass = "header-enhancer-status-muted"; } } else { levelInfo = `${i18n.t("settings.autoNumbering.format.fromLevel")} H${this.plugin.settings.startHeaderLevel} ${i18n.t("settings.autoNumbering.format.toLevel")} H${this.plugin.settings.endHeaderLevel}`; - statusBadge = `${i18n.t("settings.autoNumbering.format.manual")}`; + statusClass = "header-enhancer-status-manual"; } - return ` -
- -
-
${formatExample}
-
- - -
-
- \u{1F4CF} - ${levelInfo} -
- ${statusBadge} -
-
- `; + const preview = containerEl.createDiv({ + cls: "header-enhancer-format-preview" + }); + const exampleWrapper = preview.createDiv({ + cls: "header-enhancer-format-example-wrapper" + }); + exampleWrapper.createDiv({ + text: formatExample, + cls: "header-enhancer-format-example" + }); + const details = preview.createDiv({ + cls: "header-enhancer-format-details" + }); + const levelInfoEl = details.createDiv({ + cls: "header-enhancer-format-level-info" + }); + levelInfoEl.createSpan({ + text: "\u{1F4CF}", + cls: "header-enhancer-format-preview-icon" + }); + levelInfoEl.createSpan({ + text: levelInfo + }); + details.createSpan({ + text: this.plugin.settings.isAutoDetectHeaderLevel ? i18n.t("settings.autoNumbering.format.autoDetect") : i18n.t("settings.autoNumbering.format.manual"), + cls: `header-enhancer-status-badge ${statusClass}` + }); + return; } } + renderEmptyFormatState(containerEl, icon, text, stateClass) { + const stateEl = containerEl.createDiv({ + cls: `header-enhancer-format-state ${stateClass}` + }); + stateEl.createDiv({ + text: icon, + cls: "header-enhancer-format-state-icon" + }); + stateEl.createDiv({ + text, + cls: "header-enhancer-format-state-text" + }); + } /** * Update format preview */ updateFormatPreview() { - if (this.formatPreviewSetting) { - this.formatPreviewSetting.setDesc(this.getFormatPreview()); + if (this.formatPreviewContainer) { + this.renderFormatPreview(this.formatPreviewContainer); } } /** @@ -2192,27 +2144,25 @@ var init_setting = __esm({ const yamlInfo = containerEl.createDiv({ cls: "header-enhancer-yaml-info" }); - yamlInfo.style.cssText = ` - margin: 1.5em 0; - padding: 1.2em; - border: 2px solid var(--color-blue); - border-radius: 8px; - background: var(--background-secondary); - `; - yamlInfo.innerHTML = ` -
- ${i18n.t("autoDetection.info.yamlMode.title")} -
-
- ${i18n.t("autoDetection.info.yamlMode.description")}

- ----
-header-auto-numbering: ${yamlExample}
---- -

- ${i18n.t("autoDetection.info.yamlMode.usage")} -
- `; + yamlInfo.createDiv({ + text: i18n.t("autoDetection.info.yamlMode.title"), + cls: "header-enhancer-yaml-title" + }); + const yamlDescription = yamlInfo.createDiv({ + cls: "header-enhancer-yaml-description" + }); + yamlDescription.createDiv({ + text: i18n.t("autoDetection.info.yamlMode.description") + }); + yamlDescription.createEl("code", { + text: `--- +header-auto-numbering: ${yamlExample} +---`, + cls: "header-enhancer-yaml-example" + }); + yamlDescription.createDiv({ + text: i18n.t("autoDetection.info.yamlMode.usage") + }); new import_obsidian3.Setting(containerEl).setName(i18n.t("settings.yamlMode.fallback.name")).setDesc(i18n.t("settings.yamlMode.fallback.desc")).addDropdown((dropdown) => { dropdown.addOption("no_numbering" /* NO_NUMBERING */, i18n.t("settings.yamlMode.fallback.noNumbering")); dropdown.addOption("use_default" /* USE_DEFAULT */, i18n.t("settings.yamlMode.fallback.useDefault")); @@ -2333,8 +2283,7 @@ var BacklinkManager = class { } for (const [sourcePath, references] of actualMap) { const sourceFile = this.app.vault.getAbstractFileByPath(sourcePath); - if (!(sourceFile instanceof import_obsidian4.TFile)) - continue; + if (!(sourceFile instanceof import_obsidian4.TFile)) continue; const content = await this.app.vault.read(sourceFile); const lines = content.split("\n"); for (const ref of references) { @@ -2364,8 +2313,7 @@ var BacklinkManager = class { * @returns Whether all updates were successful */ async updateBacklinks(updates) { - if (updates.length === 0) - return true; + if (updates.length === 0) return true; const updatePromises = []; const backupData = []; try { @@ -2397,8 +2345,7 @@ var BacklinkManager = class { async updateSingleBacklink(update, originalContent) { const lines = originalContent.split("\n"); const { line } = update.position.start; - if (line >= lines.length) - return; + if (line >= lines.length) return; const oldLine = lines[line]; const newLine = oldLine.replace(update.oldLink, update.newLink); if (oldLine !== newLine) { @@ -2412,8 +2359,7 @@ var BacklinkManager = class { */ extractHeaderLink(sourceFile, ref, lines, targetFileName, oldHeading) { const { line, ch } = ref.position.start; - if (line >= lines.length) - return null; + if (line >= lines.length) return null; const lineContent = lines[line]; const expectedLinkPrefix = `${targetFileName}#`; if (ref.link && ref.link.startsWith(expectedLinkPrefix)) { @@ -2563,7 +2509,7 @@ var EditorHandlers = class { selection: { anchor: currentLine.from + textBeforeCursor.length + 1 }, userEvent: "HeaderEnhancer.changeAutoNumbering" }); - setTimeout(async () => { + window.setTimeout(async () => { await this.plugin.handleAddHeaderNumber(activeView); if (this.plugin.settings.isAutoDetectHeaderLevel) { this.plugin.handleShowStateBarChange(); @@ -2605,315 +2551,61 @@ var EditorHandlers = class { var StyleManager = class { constructor(settings) { this.settings = settings; - this.headerFontStyleEl = null; - this.titleFontStyleEl = null; - this.dialogStyleEl = null; - this.ribbonIconStyleEl = null; } - /** - * Apply all CSS styles - */ applyCSSStyles() { this.applyHeaderFontStyles(); this.applyTitleFontStyles(); - this.applyDialogStyles(); - this.applyRibbonIconStyles(); } - /** - * Remove all CSS styles - */ removeCSSStyles() { this.removeHeaderFontStyles(); this.removeTitleFontStyles(); - this.removeDialogStyles(); - this.removeRibbonIconStyles(); } - /** - * Apply header font styles (# ## ### etc.) - */ applyHeaderFontStyles() { - this.removeHeaderFontStyles(); - if (!this.settings.isSeparateHeaderFont) { - return; - } - this.headerFontStyleEl = document.createElement("style"); - this.headerFontStyleEl.id = "header-enhancer-header-font-styles"; - let cssRules = ""; - const headerSelectors = [ - ".markdown-preview-view h1", - ".markdown-preview-view h2", - ".markdown-preview-view h3", - ".markdown-preview-view h4", - ".markdown-preview-view h5", - ".markdown-preview-view h6", - ".markdown-source-view.mod-cm6 .HyperMD-header-1", - ".markdown-source-view.mod-cm6 .HyperMD-header-2", - ".markdown-source-view.mod-cm6 .HyperMD-header-3", - ".markdown-source-view.mod-cm6 .HyperMD-header-4", - ".markdown-source-view.mod-cm6 .HyperMD-header-5", - ".markdown-source-view.mod-cm6 .HyperMD-header-6" - ].join(", "); - if (this.settings.headerFontFamily && this.settings.headerFontFamily !== "inherit") { - cssRules += `${headerSelectors} { font-family: ${this.settings.headerFontFamily} !important; } -`; - } - if (this.settings.headerFontSize && this.settings.headerFontSize !== "inherit") { - cssRules += `${headerSelectors} { font-size: ${this.settings.headerFontSize} !important; } -`; - } - this.headerFontStyleEl.textContent = cssRules; - if (cssRules) { - document.head.appendChild(this.headerFontStyleEl); - } + const hasHeaderFontFamily = this.settings.isSeparateHeaderFont && this.settings.headerFontFamily && this.settings.headerFontFamily !== "inherit"; + const hasHeaderFontSize = this.settings.isSeparateHeaderFont && this.settings.headerFontSize && this.settings.headerFontSize !== "inherit"; + activeDocument.body.toggleClass("header-enhancer-custom-header-font-family", hasHeaderFontFamily); + activeDocument.body.toggleClass("header-enhancer-custom-header-font-size", hasHeaderFontSize); + this.setBodyCssVariable( + "--header-enhancer-header-font-family", + hasHeaderFontFamily ? this.settings.headerFontFamily : "" + ); + this.setBodyCssVariable( + "--header-enhancer-header-font-size", + hasHeaderFontSize ? this.settings.headerFontSize : "" + ); } - /** - * 应用文档标题字体样式 - */ applyTitleFontStyles() { - this.removeTitleFontStyles(); - if (!this.settings.isSeparateTitleFont) { - return; - } - this.titleFontStyleEl = document.createElement("style"); - this.titleFontStyleEl.id = "header-enhancer-title-font-styles"; - let cssRules = ""; - const titleSelectors = [ - // 标签页中的文件标题 - 只针对特定的标签标题元素 - ".workspace-tab-header-inner-title", - ".workspace-tab-header .workspace-tab-header-inner-title", - ".workspace-tabs .workspace-tab-header-inner-title", - // 视图标题栏标题 - ".workspace-leaf-content .view-header-title", - // 文档内联标题(在文档中显示的主标题) - ".inline-title", - ".markdown-preview-view .inline-title", - ".markdown-source-view .inline-title", - // 文件资源管理器中的文件标题 - ".nav-file-title-content", - ".tree-item-inner.nav-file-title-content", - // Frontmatter 标题显示 - '.frontmatter-container .metadata-property[data-property-key="title"] .metadata-property-value' - ].join(", "); - if (this.settings.titleFontFamily && this.settings.titleFontFamily !== "inherit") { - cssRules += `${titleSelectors} { font-family: ${this.settings.titleFontFamily} !important; } -`; - } - if (this.settings.titleFontSize && this.settings.titleFontSize !== "inherit") { - cssRules += `${titleSelectors} { font-size: ${this.settings.titleFontSize} !important; } -`; - } - this.titleFontStyleEl.textContent = cssRules; - if (cssRules) { - document.head.appendChild(this.titleFontStyleEl); - } + const hasTitleFontFamily = this.settings.isSeparateTitleFont && this.settings.titleFontFamily && this.settings.titleFontFamily !== "inherit"; + const hasTitleFontSize = this.settings.isSeparateTitleFont && this.settings.titleFontSize && this.settings.titleFontSize !== "inherit"; + activeDocument.body.toggleClass("header-enhancer-custom-title-font-family", hasTitleFontFamily); + activeDocument.body.toggleClass("header-enhancer-custom-title-font-size", hasTitleFontSize); + this.setBodyCssVariable( + "--header-enhancer-title-font-family", + hasTitleFontFamily ? this.settings.titleFontFamily : "" + ); + this.setBodyCssVariable( + "--header-enhancer-title-font-size", + hasTitleFontSize ? this.settings.titleFontSize : "" + ); } - /** - * Apply ribbon icon state styles - */ - applyRibbonIconStyles() { - this.removeRibbonIconStyles(); - this.ribbonIconStyleEl = document.createElement("style"); - this.ribbonIconStyleEl.id = "header-enhancer-ribbon-icon-styles"; - const ribbonIconCSS = ` -/* Ribbon icon state styles for Header Enhancer */ -.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-global-disabled { - opacity: 0.4; -} - -.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-global-disabled:hover { - opacity: 0.6; -} - -.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-document-enabled { - color: var(--color-accent); -} - -.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-document-enabled:hover { - color: var(--color-accent-hover); -} - -.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-document-disabled { - opacity: 0.7; - color: var(--text-muted); -} - -.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-document-disabled:hover { - opacity: 1; - color: var(--text-normal); -} - -/* Additional visual indicator for global disabled state */ -.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-global-disabled::before { - content: ""; - position: absolute; - top: 2px; - right: 2px; - width: 6px; - height: 6px; - border-radius: 50%; - background-color: var(--text-error); - z-index: 10; -} - `; - this.ribbonIconStyleEl.textContent = ribbonIconCSS; - document.head.appendChild(this.ribbonIconStyleEl); - } - /** - * 应用对话框组件样式 - */ - applyDialogStyles() { - this.removeDialogStyles(); - this.dialogStyleEl = document.createElement("style"); - this.dialogStyleEl.id = "header-enhancer-dialog-styles"; - const dialogCSS = ` -/* Auto numbering dialog styles - shared between removal and activation */ -.header-enhancer-removal-dialog, -.header-enhancer-activation-dialog { - max-width: 500px; -} - -.header-enhancer-removal-dialog .modal-title, -.header-enhancer-activation-dialog .modal-title { - margin-bottom: 1em; - padding-bottom: 0.5em; - color: var(--text-accent); - border-bottom: 1px solid var(--background-modifier-border); -} - -.header-enhancer-removal-dialog .modal-message, -.header-enhancer-activation-dialog .modal-message { - margin-bottom: 1.5em; - line-height: 1.5; - color: var(--text-normal); -} - -.header-enhancer-removal-dialog .modal-actions, -.header-enhancer-activation-dialog .modal-actions { - margin-top: 1em; - padding-top: 1em; - border-top: 1px solid var(--background-modifier-border); -} - -.header-enhancer-removal-dialog .modal-actions .setting-item, -.header-enhancer-activation-dialog .modal-actions .setting-item { - margin-bottom: 0.75em; - padding: 0.75em; - background-color: var(--background-secondary); - border: 1px solid var(--background-modifier-border); - border-radius: 6px; - transition: all 0.2s ease; -} - -.header-enhancer-removal-dialog .modal-actions .setting-item:hover, -.header-enhancer-activation-dialog .modal-actions .setting-item:hover { - background-color: var(--background-secondary-alt); - border-color: var(--background-modifier-border-hover); -} - -/* Warning and tip text styles */ -.header-enhancer-removal-dialog .setting-item-warning, -.header-enhancer-removal-dialog .setting-item-tip, -.header-enhancer-activation-dialog .setting-item-warning, -.header-enhancer-activation-dialog .setting-item-tip { - margin-top: 0.5em; - font-size: 0.85em; - line-height: 1.3; -} - -.header-enhancer-removal-dialog .warning-label, -.header-enhancer-activation-dialog .warning-label { - color: var(--text-error); - font-weight: 600; -} - -.header-enhancer-removal-dialog .warning-text, -.header-enhancer-removal-dialog .progress-text, -.header-enhancer-activation-dialog .warning-text, -.header-enhancer-activation-dialog .progress-text { - color: var(--text-muted); - margin: 0; -} - -.header-enhancer-removal-dialog .manual-tip-text, -.header-enhancer-activation-dialog .manual-tip-text { - color: var(--text-muted); - font-style: italic; -} - -.header-enhancer-removal-dialog .modal-cancel, -.header-enhancer-activation-dialog .modal-cancel { - margin-top: 1em; - padding-top: 1em; - text-align: center; - border-top: 1px solid var(--background-modifier-border-focus); -} - -.header-enhancer-removal-dialog .progress-container, -.header-enhancer-activation-dialog .progress-container { - margin-top: 1em; - padding: 1em; - background-color: var(--background-secondary); - border: 1px solid var(--background-modifier-border); - border-radius: 6px; - text-align: center; -} - -.header-enhancer-removal-dialog .progress-text, -.header-enhancer-activation-dialog .progress-text { - font-size: 0.9em; -} - -.header-enhancer-removal-dialog button:disabled, -.header-enhancer-activation-dialog button:disabled { - opacity: 0.5; - cursor: not-allowed; -} - `; - this.dialogStyleEl.textContent = dialogCSS; - document.head.appendChild(this.dialogStyleEl); - } - /** - * 移除标题字体样式 - */ removeHeaderFontStyles() { - if (this.headerFontStyleEl) { - this.headerFontStyleEl.remove(); - this.headerFontStyleEl = null; - } + activeDocument.body.removeClass("header-enhancer-custom-header-font-family"); + activeDocument.body.removeClass("header-enhancer-custom-header-font-size"); + this.setBodyCssVariable("--header-enhancer-header-font-family", ""); + this.setBodyCssVariable("--header-enhancer-header-font-size", ""); } - /** - * 移除文档标题字体样式 - */ removeTitleFontStyles() { - if (this.titleFontStyleEl) { - this.titleFontStyleEl.remove(); - this.titleFontStyleEl = null; - } + activeDocument.body.removeClass("header-enhancer-custom-title-font-family"); + activeDocument.body.removeClass("header-enhancer-custom-title-font-size"); + this.setBodyCssVariable("--header-enhancer-title-font-family", ""); + this.setBodyCssVariable("--header-enhancer-title-font-size", ""); } - /** - * 移除对话框样式 - */ - removeDialogStyles() { - if (this.dialogStyleEl) { - this.dialogStyleEl.remove(); - this.dialogStyleEl = null; - } - } - /** - * 移除侧边栏图标样式 - */ - removeRibbonIconStyles() { - if (this.ribbonIconStyleEl) { - this.ribbonIconStyleEl.remove(); - this.ribbonIconStyleEl = null; - } - } - /** - * 更新设置引用(当设置改变时调用) - */ updateSettings(newSettings) { this.settings = newSettings; } + setBodyCssVariable(name, value) { + activeDocument.body.setCssProps({ [name]: value || "inherit" }); + } }; // src/main.ts @@ -2963,7 +2655,7 @@ var HeaderEnhancerPlugin = class extends import_obsidian6.Plugin { ); this.registerEvent( this.app.workspace.on("file-open", () => { - setTimeout(() => { + window.setTimeout(() => { this.updateAllUIStates(); }, 50); }) @@ -3474,8 +3166,7 @@ var HeaderEnhancerPlugin = class extends import_obsidian6.Plugin { var _a; const i18n = I18n.getInstance(); const filePath = (_a = activeView.file) == null ? void 0 : _a.path; - if (!filePath) - return; + if (!filePath) return; if (this.settings.autoNumberingMode === "yaml" /* YAML_CONTROLLED */) { await this.setDocumentAutoNumberingState(filePath, newState); const editor = activeView.editor; diff --git a/.obsidian/plugins/header-enhancer/manifest.json b/.obsidian/plugins/header-enhancer/manifest.json index 02a34299..00001932 100644 --- a/.obsidian/plugins/header-enhancer/manifest.json +++ b/.obsidian/plugins/header-enhancer/manifest.json @@ -1,8 +1,8 @@ { "id": "header-enhancer", "name": "Header Enhancer", - "version": "0.5.2", - "minAppVersion": "0.14.0", + "version": "0.6.0", + "minAppVersion": "1.8.7", "description": "Level up your headers, customize your notes. Header Enhancer makes your notes header better and more useful.", "author": "Hobee Liu", "authorUrl": "https://github.com/HoBeedzc", diff --git a/.obsidian/plugins/header-enhancer/styles.css b/.obsidian/plugins/header-enhancer/styles.css index 7bed3db9..c0924b35 100644 --- a/.obsidian/plugins/header-enhancer/styles.css +++ b/.obsidian/plugins/header-enhancer/styles.css @@ -1,8 +1,467 @@ -/* +/* Header and title font settings */ +body.header-enhancer-custom-header-font-family .markdown-preview-view h1, +body.header-enhancer-custom-header-font-family .markdown-preview-view h2, +body.header-enhancer-custom-header-font-family .markdown-preview-view h3, +body.header-enhancer-custom-header-font-family .markdown-preview-view h4, +body.header-enhancer-custom-header-font-family .markdown-preview-view h5, +body.header-enhancer-custom-header-font-family .markdown-preview-view h6, +body.header-enhancer-custom-header-font-family .markdown-source-view.mod-cm6 .HyperMD-header-1, +body.header-enhancer-custom-header-font-family .markdown-source-view.mod-cm6 .HyperMD-header-2, +body.header-enhancer-custom-header-font-family .markdown-source-view.mod-cm6 .HyperMD-header-3, +body.header-enhancer-custom-header-font-family .markdown-source-view.mod-cm6 .HyperMD-header-4, +body.header-enhancer-custom-header-font-family .markdown-source-view.mod-cm6 .HyperMD-header-5, +body.header-enhancer-custom-header-font-family .markdown-source-view.mod-cm6 .HyperMD-header-6 { + font-family: var(--header-enhancer-header-font-family) !important; +} -This CSS file will be included with your plugin, and -available in the app when your plugin is enabled. +body.header-enhancer-custom-header-font-size .markdown-preview-view h1, +body.header-enhancer-custom-header-font-size .markdown-preview-view h2, +body.header-enhancer-custom-header-font-size .markdown-preview-view h3, +body.header-enhancer-custom-header-font-size .markdown-preview-view h4, +body.header-enhancer-custom-header-font-size .markdown-preview-view h5, +body.header-enhancer-custom-header-font-size .markdown-preview-view h6, +body.header-enhancer-custom-header-font-size .markdown-source-view.mod-cm6 .HyperMD-header-1, +body.header-enhancer-custom-header-font-size .markdown-source-view.mod-cm6 .HyperMD-header-2, +body.header-enhancer-custom-header-font-size .markdown-source-view.mod-cm6 .HyperMD-header-3, +body.header-enhancer-custom-header-font-size .markdown-source-view.mod-cm6 .HyperMD-header-4, +body.header-enhancer-custom-header-font-size .markdown-source-view.mod-cm6 .HyperMD-header-5, +body.header-enhancer-custom-header-font-size .markdown-source-view.mod-cm6 .HyperMD-header-6 { + font-size: var(--header-enhancer-header-font-size) !important; +} -If your plugin does not need CSS, delete this file. +body.header-enhancer-custom-title-font-family .workspace-tab-header-inner-title, +body.header-enhancer-custom-title-font-family .workspace-tab-header .workspace-tab-header-inner-title, +body.header-enhancer-custom-title-font-family .workspace-tabs .workspace-tab-header-inner-title, +body.header-enhancer-custom-title-font-family .workspace-leaf-content .view-header-title, +body.header-enhancer-custom-title-font-family .inline-title, +body.header-enhancer-custom-title-font-family .markdown-preview-view .inline-title, +body.header-enhancer-custom-title-font-family .markdown-source-view .inline-title, +body.header-enhancer-custom-title-font-family .nav-file-title-content, +body.header-enhancer-custom-title-font-family .tree-item-inner.nav-file-title-content, +body.header-enhancer-custom-title-font-family .frontmatter-container .metadata-property[data-property-key="title"] .metadata-property-value { + font-family: var(--header-enhancer-title-font-family) !important; +} -*/ \ No newline at end of file +body.header-enhancer-custom-title-font-size .workspace-tab-header-inner-title, +body.header-enhancer-custom-title-font-size .workspace-tab-header .workspace-tab-header-inner-title, +body.header-enhancer-custom-title-font-size .workspace-tabs .workspace-tab-header-inner-title, +body.header-enhancer-custom-title-font-size .workspace-leaf-content .view-header-title, +body.header-enhancer-custom-title-font-size .inline-title, +body.header-enhancer-custom-title-font-size .markdown-preview-view .inline-title, +body.header-enhancer-custom-title-font-size .markdown-source-view .inline-title, +body.header-enhancer-custom-title-font-size .nav-file-title-content, +body.header-enhancer-custom-title-font-size .tree-item-inner.nav-file-title-content, +body.header-enhancer-custom-title-font-size .frontmatter-container .metadata-property[data-property-key="title"] .metadata-property-value { + font-size: var(--header-enhancer-title-font-size) !important; +} + +/* Ribbon icon state styles */ +.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-global-disabled { + opacity: 0.4; +} + +.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-global-disabled:hover { + opacity: 0.6; +} + +.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-document-enabled { + color: var(--color-accent); +} + +.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-document-enabled:hover { + color: var(--color-accent-hover); +} + +.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-document-disabled { + opacity: 0.7; + color: var(--text-muted); +} + +.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-document-disabled:hover { + opacity: 1; + color: var(--text-normal); +} + +.side-dock-ribbon-action[aria-label*="Header Enhancer"].header-enhancer-global-disabled::before { + content: ""; + position: absolute; + top: 2px; + right: 2px; + width: 6px; + height: 6px; + border-radius: 50%; + background-color: var(--text-error); + z-index: 10; +} + +/* Settings page */ +.header-enhancer-global-disabled-info, +.header-enhancer-off-info { + margin: 1.5em 0; + padding: 1.2em; + border: 2px solid var(--text-muted); + border-radius: 8px; + background: var(--background-secondary); + opacity: 0.8; +} + +.header-enhancer-info-title { + font-weight: 600; + color: var(--text-muted); + margin-bottom: 0.8em; + display: flex; + align-items: center; +} + +.header-enhancer-info-description { + line-height: 1.6; + color: var(--text-muted); +} + +.header-enhancer-font-preview, +.header-enhancer-title-font-preview { + margin: 1em 0; + padding: 1em; + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + background: var(--background-secondary); +} + +.header-enhancer-preview-title { + font-size: 1.5em; + font-weight: bold; + margin: 0.5em 0; +} + +.header-enhancer-auto-detection-preview { + margin: 1em 0; + padding: 1.2em; + border: 2px solid var(--color-green); + border-radius: 8px; + background: var(--background-secondary); + position: relative; +} + +.header-enhancer-auto-detection-title { + font-weight: 600; + font-size: 1em; + color: var(--color-green); + margin-bottom: 0.8em; + display: flex; + align-items: center; +} + +.header-enhancer-muted-italic { + color: var(--text-muted); + font-style: italic; +} + +.header-enhancer-empty-analysis { + color: var(--text-muted); + text-align: center; + padding: 1em; +} + +.header-enhancer-analysis-grid { + display: grid; + gap: 0.8em; + line-height: 1.6; +} + +.header-enhancer-analysis-row { + display: flex; + align-items: center; + gap: 0.8em; +} + +.header-enhancer-analysis-row-start { + align-items: flex-start; +} + +.header-enhancer-analysis-label { + color: var(--text-normal); + min-width: 70px; +} + +.header-enhancer-analysis-row-start .header-enhancer-analysis-label { + margin-top: 0.2em; +} + +.header-enhancer-analysis-values { + display: flex; + gap: 0.4em; + flex-wrap: wrap; +} + +.header-enhancer-level-chip { + background: var(--tag-background); + color: var(--tag-color); + padding: 0.2em 0.4em; + border-radius: 3px; + font-family: monospace; +} + +.header-enhancer-mapping-chip { + background: var(--background-modifier-hover); + padding: 0.2em 0.4em; + border-radius: 3px; + font-family: monospace; +} + +.header-enhancer-range-badge, +.header-enhancer-total-badge { + color: var(--text-on-accent); + padding: 0.3em 0.6em; + border-radius: 4px; + font-weight: 500; +} + +.header-enhancer-range-badge { + background: var(--color-green); +} + +.header-enhancer-total-badge { + background: var(--color-blue); +} + +.header-enhancer-format-preview-container { + margin: 1.5em 0; +} + +.header-enhancer-format-preview-title { + font-weight: 600; + font-size: 1.1em; + color: var(--text-accent); + margin-bottom: 1em; + display: flex; + align-items: center; + gap: 0.5em; +} + +.header-enhancer-format-preview-icon { + color: var(--color-accent); +} + +.header-enhancer-format-state { + text-align: center; + padding: 1.5em; + border: 2px dashed var(--background-modifier-border); + border-radius: 8px; + background: var(--background-modifier-hover); +} + +.header-enhancer-format-state-muted { + color: var(--text-muted); +} + +.header-enhancer-format-state-yaml { + color: var(--text-accent); + border-color: var(--color-blue); +} + +.header-enhancer-format-state-icon { + font-size: 1.5em; + margin-bottom: 0.5em; +} + +.header-enhancer-format-state-text { + font-size: 1em; + font-weight: 500; +} + +.header-enhancer-format-preview { + display: flex; + flex-direction: column; + gap: 1.5em; +} + +.header-enhancer-format-example-wrapper { + text-align: center; +} + +.header-enhancer-format-example { + font-family: monospace; + font-size: 1.8em; + font-weight: 700; + color: var(--color-accent); + background: var(--background-primary); + padding: 1em; + border-radius: 8px; + border: 2px solid var(--color-accent); +} + +.header-enhancer-format-details { + display: flex; + justify-content: space-between; + align-items: center; + gap: 1em; +} + +.header-enhancer-format-level-info { + display: flex; + align-items: center; + gap: 0.5em; + font-weight: 500; + color: var(--text-normal); +} + +.header-enhancer-status-badge { + color: white; + padding: 0.3em 0.8em; + border-radius: 15px; + font-size: 0.85em; + font-weight: 600; + white-space: nowrap; +} + +.header-enhancer-status-auto { + background: linear-gradient(135deg, #10b981 0%, #059669 100%); + box-shadow: 0 2px 4px rgba(16, 185, 129, 0.3); +} + +.header-enhancer-status-warning { + background: var(--color-orange); +} + +.header-enhancer-status-muted { + background: var(--text-muted); +} + +.header-enhancer-status-manual { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3); +} + +.header-enhancer-yaml-info { + margin: 1.5em 0; + padding: 1.2em; + border: 2px solid var(--color-blue); + border-radius: 8px; + background: var(--background-secondary); +} + +.header-enhancer-yaml-title { + font-weight: 600; + color: var(--color-blue); + margin-bottom: 0.8em; + display: flex; + align-items: center; +} + +.header-enhancer-yaml-description { + display: grid; + gap: 1em; + line-height: 1.6; + color: var(--text-normal); +} + +.header-enhancer-yaml-example { + background: var(--code-background); + padding: 0.5em; + border-radius: 4px; + display: block; + font-family: monospace; + white-space: pre-wrap; +} + +/* Auto numbering dialog styles */ +.header-enhancer-removal-dialog, +.header-enhancer-activation-dialog { + max-width: 500px; +} + +.header-enhancer-removal-dialog .modal-title, +.header-enhancer-activation-dialog .modal-title { + margin-bottom: 1em; + padding-bottom: 0.5em; + color: var(--text-accent); + border-bottom: 1px solid var(--background-modifier-border); +} + +.header-enhancer-removal-dialog .modal-message, +.header-enhancer-activation-dialog .modal-message { + margin-bottom: 1.5em; + line-height: 1.5; + color: var(--text-normal); +} + +.header-enhancer-removal-dialog .modal-actions, +.header-enhancer-activation-dialog .modal-actions { + margin-top: 1em; + padding-top: 1em; + border-top: 1px solid var(--background-modifier-border); +} + +.header-enhancer-removal-dialog .modal-actions .setting-item, +.header-enhancer-activation-dialog .modal-actions .setting-item { + margin-bottom: 0.75em; + padding: 0.75em; + background-color: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + transition: all 0.2s ease; +} + +.header-enhancer-removal-dialog .modal-actions .setting-item:hover, +.header-enhancer-activation-dialog .modal-actions .setting-item:hover { + background-color: var(--background-secondary-alt); + border-color: var(--background-modifier-border-hover); +} + +.header-enhancer-removal-dialog .setting-item-warning, +.header-enhancer-removal-dialog .setting-item-tip, +.header-enhancer-activation-dialog .setting-item-warning, +.header-enhancer-activation-dialog .setting-item-tip { + margin-top: 0.5em; + font-size: 0.85em; + line-height: 1.3; +} + +.header-enhancer-removal-dialog .warning-label, +.header-enhancer-activation-dialog .warning-label { + color: var(--text-error); + font-weight: 600; +} + +.header-enhancer-removal-dialog .warning-text, +.header-enhancer-removal-dialog .progress-text, +.header-enhancer-activation-dialog .warning-text, +.header-enhancer-activation-dialog .progress-text { + color: var(--text-muted); + margin: 0; +} + +.header-enhancer-removal-dialog .manual-tip-text, +.header-enhancer-activation-dialog .manual-tip-text { + color: var(--text-muted); + font-style: italic; +} + +.header-enhancer-removal-dialog .modal-cancel, +.header-enhancer-activation-dialog .modal-cancel { + margin-top: 1em; + padding-top: 1em; + text-align: center; + border-top: 1px solid var(--background-modifier-border-focus); +} + +.header-enhancer-removal-dialog .progress-container, +.header-enhancer-activation-dialog .progress-container { + margin-top: 1em; + padding: 1em; + background-color: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + text-align: center; +} + +.header-enhancer-removal-dialog .progress-text, +.header-enhancer-activation-dialog .progress-text { + font-size: 0.9em; +} + +.header-enhancer-removal-dialog button:disabled, +.header-enhancer-activation-dialog button:disabled { + opacity: 0.5; + cursor: not-allowed; +} diff --git a/.obsidian/plugins/metaedit/main.js b/.obsidian/plugins/metaedit/main.js index 7716ef49..bed6c436 100644 --- a/.obsidian/plugins/metaedit/main.js +++ b/.obsidian/plugins/metaedit/main.js @@ -1,5450 +1,11822 @@ -'use strict'; - -var obsidian = require('obsidian'); -var fs_1 = require('fs'); -var path_1 = require('path'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - -var fs_1__default = /*#__PURE__*/_interopDefaultLegacy(fs_1); -var path_1__default = /*#__PURE__*/_interopDefaultLegacy(path_1); - -var EditMode; -(function (EditMode) { - EditMode["AllSingle"] = "All Single"; - EditMode["AllMulti"] = "All Multi"; - EditMode["SomeMulti"] = "Some Multi"; -})(EditMode || (EditMode = {})); - -function noop() { } -function run(fn) { - return fn(); -} -function blank_object() { - return Object.create(null); -} -function run_all(fns) { - fns.forEach(run); -} -function is_function(thing) { - return typeof thing === 'function'; -} -function safe_not_equal(a, b) { - return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); -} -function is_empty(obj) { - return Object.keys(obj).length === 0; -} -function append(target, node) { - target.appendChild(node); -} -function append_styles(target, style_sheet_id, styles) { - const append_styles_to = get_root_for_style(target); - if (!append_styles_to.getElementById(style_sheet_id)) { - const style = element('style'); - style.id = style_sheet_id; - style.textContent = styles; - append_stylesheet(append_styles_to, style); - } -} -function get_root_for_style(node) { - if (!node) - return document; - const root = node.getRootNode ? node.getRootNode() : node.ownerDocument; - if (root && root.host) { - return root; - } - return node.ownerDocument; -} -function append_stylesheet(node, style) { - append(node.head || node, style); - return style.sheet; -} -function insert(target, node, anchor) { - target.insertBefore(node, anchor || null); -} -function detach(node) { - if (node.parentNode) { - node.parentNode.removeChild(node); - } -} -function destroy_each(iterations, detaching) { - for (let i = 0; i < iterations.length; i += 1) { - if (iterations[i]) - iterations[i].d(detaching); - } -} -function element(name) { - return document.createElement(name); -} -function text(data) { - return document.createTextNode(data); -} -function space() { - return text(' '); -} -function listen(node, event, handler, options) { - node.addEventListener(event, handler, options); - return () => node.removeEventListener(event, handler, options); -} -function attr(node, attribute, value) { - if (value == null) - node.removeAttribute(attribute); - else if (node.getAttribute(attribute) !== value) - node.setAttribute(attribute, value); -} -function children(element) { - return Array.from(element.childNodes); -} -function set_data(text, data) { - data = '' + data; - if (text.data === data) - return; - text.data = data; -} -function set_input_value(input, value) { - input.value = value == null ? '' : value; -} -function set_style(node, key, value, important) { - if (value == null) { - node.style.removeProperty(key); - } - else { - node.style.setProperty(key, value, important ? 'important' : ''); - } -} -function select_option(select, value, mounting) { - for (let i = 0; i < select.options.length; i += 1) { - const option = select.options[i]; - if (option.__value === value) { - option.selected = true; - return; - } - } - if (!mounting || value !== undefined) { - select.selectedIndex = -1; // no option should be selected - } -} -function select_value(select) { - const selected_option = select.querySelector(':checked'); - return selected_option && selected_option.__value; -} - -let current_component; -function set_current_component(component) { - current_component = component; -} -function get_current_component() { - if (!current_component) - throw new Error('Function called outside component initialization'); - return current_component; -} -/** - * The `onMount` function schedules a callback to run as soon as the component has been mounted to the DOM. - * It must be called during the component's initialisation (but doesn't need to live *inside* the component; - * it can be called from an external module). - * - * `onMount` does not run inside a [server-side component](/docs#run-time-server-side-component-api). - * - * https://svelte.dev/docs#run-time-svelte-onmount - */ -function onMount(fn) { - get_current_component().$$.on_mount.push(fn); -} - -const dirty_components = []; -const binding_callbacks = []; -let render_callbacks = []; -const flush_callbacks = []; -const resolved_promise = /* @__PURE__ */ Promise.resolve(); -let update_scheduled = false; -function schedule_update() { - if (!update_scheduled) { - update_scheduled = true; - resolved_promise.then(flush); - } -} -function add_render_callback(fn) { - render_callbacks.push(fn); -} -// flush() calls callbacks in this order: -// 1. All beforeUpdate callbacks, in order: parents before children -// 2. All bind:this callbacks, in reverse order: children before parents. -// 3. All afterUpdate callbacks, in order: parents before children. EXCEPT -// for afterUpdates called during the initial onMount, which are called in -// reverse order: children before parents. -// Since callbacks might update component values, which could trigger another -// call to flush(), the following steps guard against this: -// 1. During beforeUpdate, any updated components will be added to the -// dirty_components array and will cause a reentrant call to flush(). Because -// the flush index is kept outside the function, the reentrant call will pick -// up where the earlier call left off and go through all dirty components. The -// current_component value is saved and restored so that the reentrant call will -// not interfere with the "parent" flush() call. -// 2. bind:this callbacks cannot trigger new flush() calls. -// 3. During afterUpdate, any updated components will NOT have their afterUpdate -// callback called a second time; the seen_callbacks set, outside the flush() -// function, guarantees this behavior. -const seen_callbacks = new Set(); -let flushidx = 0; // Do *not* move this inside the flush() function -function flush() { - // Do not reenter flush while dirty components are updated, as this can - // result in an infinite loop. Instead, let the inner flush handle it. - // Reentrancy is ok afterwards for bindings etc. - if (flushidx !== 0) { - return; - } - const saved_component = current_component; - do { - // first, call beforeUpdate functions - // and update components - try { - while (flushidx < dirty_components.length) { - const component = dirty_components[flushidx]; - flushidx++; - set_current_component(component); - update(component.$$); - } - } - catch (e) { - // reset dirty state to not end up in a deadlocked state and then rethrow - dirty_components.length = 0; - flushidx = 0; - throw e; - } - set_current_component(null); - dirty_components.length = 0; - flushidx = 0; - while (binding_callbacks.length) - binding_callbacks.pop()(); - // then, once components are updated, call - // afterUpdate functions. This may cause - // subsequent updates... - for (let i = 0; i < render_callbacks.length; i += 1) { - const callback = render_callbacks[i]; - if (!seen_callbacks.has(callback)) { - // ...so guard against infinite loops - seen_callbacks.add(callback); - callback(); - } - } - render_callbacks.length = 0; - } while (dirty_components.length); - while (flush_callbacks.length) { - flush_callbacks.pop()(); - } - update_scheduled = false; - seen_callbacks.clear(); - set_current_component(saved_component); -} -function update($$) { - if ($$.fragment !== null) { - $$.update(); - run_all($$.before_update); - const dirty = $$.dirty; - $$.dirty = [-1]; - $$.fragment && $$.fragment.p($$.ctx, dirty); - $$.after_update.forEach(add_render_callback); - } -} -/** - * Useful for example to execute remaining `afterUpdate` callbacks before executing `destroy`. - */ -function flush_render_callbacks(fns) { - const filtered = []; - const targets = []; - render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c)); - targets.forEach((c) => c()); - render_callbacks = filtered; -} -const outroing = new Set(); -function transition_in(block, local) { - if (block && block.i) { - outroing.delete(block); - block.i(local); - } -} -function mount_component(component, target, anchor, customElement) { - const { fragment, after_update } = component.$$; - fragment && fragment.m(target, anchor); - if (!customElement) { - // onMount happens before the initial afterUpdate - add_render_callback(() => { - const new_on_destroy = component.$$.on_mount.map(run).filter(is_function); - // if the component was destroyed immediately - // it will update the `$$.on_destroy` reference to `null`. - // the destructured on_destroy may still reference to the old array - if (component.$$.on_destroy) { - component.$$.on_destroy.push(...new_on_destroy); - } - else { - // Edge case - component was destroyed immediately, - // most likely as a result of a binding initialising - run_all(new_on_destroy); - } - component.$$.on_mount = []; - }); - } - after_update.forEach(add_render_callback); -} -function destroy_component(component, detaching) { - const $$ = component.$$; - if ($$.fragment !== null) { - flush_render_callbacks($$.after_update); - run_all($$.on_destroy); - $$.fragment && $$.fragment.d(detaching); - // TODO null out other refs, including component.$$ (but need to - // preserve final state?) - $$.on_destroy = $$.fragment = null; - $$.ctx = []; - } -} -function make_dirty(component, i) { - if (component.$$.dirty[0] === -1) { - dirty_components.push(component); - schedule_update(); - component.$$.dirty.fill(0); - } - component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31)); -} -function init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) { - const parent_component = current_component; - set_current_component(component); - const $$ = component.$$ = { - fragment: null, - ctx: [], - // state - props, - update: noop, - not_equal, - bound: blank_object(), - // lifecycle - on_mount: [], - on_destroy: [], - on_disconnect: [], - before_update: [], - after_update: [], - context: new Map(options.context || (parent_component ? parent_component.$$.context : [])), - // everything else - callbacks: blank_object(), - dirty, - skip_bound: false, - root: options.target || parent_component.$$.root - }; - append_styles && append_styles($$.root); - let ready = false; - $$.ctx = instance - ? instance(component, options.props || {}, (i, ret, ...rest) => { - const value = rest.length ? rest[0] : ret; - if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) { - if (!$$.skip_bound && $$.bound[i]) - $$.bound[i](value); - if (ready) - make_dirty(component, i); - } - return ret; - }) - : []; - $$.update(); - ready = true; - run_all($$.before_update); - // `false` as a special case of no DOM component - $$.fragment = create_fragment ? create_fragment($$.ctx) : false; - if (options.target) { - if (options.hydrate) { - const nodes = children(options.target); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - $$.fragment && $$.fragment.l(nodes); - nodes.forEach(detach); - } - else { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - $$.fragment && $$.fragment.c(); - } - if (options.intro) - transition_in(component.$$.fragment); - mount_component(component, options.target, options.anchor, options.customElement); - flush(); - } - set_current_component(parent_component); -} -/** - * Base class for Svelte components. Used when dev=false. - */ -class SvelteComponent { - $destroy() { - destroy_component(this, 1); - this.$destroy = noop; - } - $on(type, callback) { - if (!is_function(callback)) { - return noop; - } - const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); - callbacks.push(callback); - return () => { - const index = callbacks.indexOf(callback); - if (index !== -1) - callbacks.splice(index, 1); - }; - } - $set($$props) { - if (this.$$set && !is_empty($$props)) { - this.$$.skip_bound = true; - this.$$set($$props); - this.$$.skip_bound = false; - } - } -} - -var ProgressPropertyOptions; -(function (ProgressPropertyOptions) { - ProgressPropertyOptions["TaskTotal"] = "Total Tasks"; - ProgressPropertyOptions["TaskComplete"] = "Completed Tasks"; - ProgressPropertyOptions["TaskIncomplete"] = "Incomplete Tasks"; -})(ProgressPropertyOptions || (ProgressPropertyOptions = {})); - -/* src/Modals/ProgressPropertiesSettingModal/ProgressPropertiesModalContent.svelte generated by Svelte v3.59.2 */ - -function add_css$3(target) { - append_styles(target, "svelte-kqcr7b", ".buttonContainer.svelte-kqcr7b{display:flex;justify-content:center;margin-top:1rem}select.svelte-kqcr7b{border-radius:4px;width:100%;height:30px;border:1px solid #dbdbdc;color:#383a42;background-color:#fff;padding:3px}button.svelte-kqcr7b{margin-left:5px;margin-right:5px;font-size:15px}"); -} - -function get_each_context$3(ctx, list, i) { - const child_ctx = ctx.slice(); - child_ctx[10] = list[i]; - child_ctx[11] = list; - child_ctx[12] = i; - return child_ctx; -} - -function get_each_context_1$1(ctx, list, i) { - const child_ctx = ctx.slice(); - child_ctx[13] = list[i]; - return child_ctx; -} - -// (32:24) {#each options as text} -function create_each_block_1$1(ctx) { - let option; - - return { - c() { - option = element("option"); - option.__value = /*text*/ ctx[13]; - option.value = option.__value; - attr(option, "label", /*text*/ ctx[13]); - }, - m(target, anchor) { - insert(target, option, anchor); - }, - p: noop, - d(detaching) { - if (detaching) detach(option); - } - }; -} - -// (25:8) {#each properties as property} -function create_each_block$3(ctx) { - let tr; - let td0; - let input0; - let t0; - let td1; - let select; - let t1; - let td2; - let input1; - let t2; - let mounted; - let dispose; - - function input0_input_handler() { - /*input0_input_handler*/ ctx[5].call(input0, /*each_value*/ ctx[11], /*property_index*/ ctx[12]); - } - - let each_value_1 = /*options*/ ctx[2]; - let each_blocks = []; - - for (let i = 0; i < each_value_1.length; i += 1) { - each_blocks[i] = create_each_block_1$1(get_each_context_1$1(ctx, each_value_1, i)); - } - - function select_change_handler() { - /*select_change_handler*/ ctx[7].call(select, /*each_value*/ ctx[11], /*property_index*/ ctx[12]); - } - - function click_handler() { - return /*click_handler*/ ctx[9](/*property*/ ctx[10]); - } - - return { - c() { - tr = element("tr"); - td0 = element("td"); - input0 = element("input"); - t0 = space(); - td1 = element("td"); - select = element("select"); - - for (let i = 0; i < each_blocks.length; i += 1) { - each_blocks[i].c(); - } - - t1 = space(); - td2 = element("td"); - input1 = element("input"); - t2 = space(); - attr(input0, "type", "text"); - attr(input0, "placeholder", "Property name"); - attr(select, "class", "svelte-kqcr7b"); - if (/*property*/ ctx[10].type === void 0) add_render_callback(select_change_handler); - attr(input1, "type", "button"); - attr(input1, "class", "not-a-button"); - input1.value = "❌"; - }, - m(target, anchor) { - insert(target, tr, anchor); - append(tr, td0); - append(td0, input0); - set_input_value(input0, /*property*/ ctx[10].name); - append(tr, t0); - append(tr, td1); - append(td1, select); - - for (let i = 0; i < each_blocks.length; i += 1) { - if (each_blocks[i]) { - each_blocks[i].m(select, null); - } - } - - select_option(select, /*property*/ ctx[10].type, true); - append(tr, t1); - append(tr, td2); - append(td2, input1); - append(tr, t2); - - if (!mounted) { - dispose = [ - listen(input0, "input", input0_input_handler), - listen(input0, "change", /*change_handler*/ ctx[6]), - listen(select, "change", select_change_handler), - listen(select, "change", /*change_handler_1*/ ctx[8]), - listen(input1, "click", click_handler) - ]; - - mounted = true; - } - }, - p(new_ctx, dirty) { - ctx = new_ctx; - - if (dirty & /*properties, options*/ 5 && input0.value !== /*property*/ ctx[10].name) { - set_input_value(input0, /*property*/ ctx[10].name); - } - - if (dirty & /*options*/ 4) { - each_value_1 = /*options*/ ctx[2]; - let i; - - for (i = 0; i < each_value_1.length; i += 1) { - const child_ctx = get_each_context_1$1(ctx, each_value_1, i); - - if (each_blocks[i]) { - each_blocks[i].p(child_ctx, dirty); - } else { - each_blocks[i] = create_each_block_1$1(child_ctx); - each_blocks[i].c(); - each_blocks[i].m(select, null); - } - } - - for (; i < each_blocks.length; i += 1) { - each_blocks[i].d(1); - } - - each_blocks.length = each_value_1.length; - } - - if (dirty & /*properties, options*/ 5) { - select_option(select, /*property*/ ctx[10].type); - } - }, - d(detaching) { - if (detaching) detach(tr); - destroy_each(each_blocks, detaching); - mounted = false; - run_all(dispose); - } - }; -} - -function create_fragment$4(ctx) { - let div1; - let table; - let thead; - let t3; - let t4; - let div0; - let button; - let mounted; - let dispose; - let each_value = /*properties*/ ctx[0]; - let each_blocks = []; - - for (let i = 0; i < each_value.length; i += 1) { - each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i)); - } - - return { - c() { - div1 = element("div"); - table = element("table"); - thead = element("thead"); - - thead.innerHTML = `Name - Type`; - - t3 = space(); - - for (let i = 0; i < each_blocks.length; i += 1) { - each_blocks[i].c(); - } - - t4 = space(); - div0 = element("div"); - button = element("button"); - button.textContent = "Add"; - set_style(table, "width", "100%"); - attr(button, "class", "mod-cta svelte-kqcr7b"); - attr(div0, "class", "buttonContainer svelte-kqcr7b"); - attr(div1, "class", "centerSettingContent"); - }, - m(target, anchor) { - insert(target, div1, anchor); - append(div1, table); - append(table, thead); - append(table, t3); - - for (let i = 0; i < each_blocks.length; i += 1) { - if (each_blocks[i]) { - each_blocks[i].m(table, null); - } - } - - append(div1, t4); - append(div1, div0); - append(div0, button); - - if (!mounted) { - dispose = listen(button, "click", /*addNewProperty*/ ctx[3]); - mounted = true; - } - }, - p(ctx, [dirty]) { - if (dirty & /*removeProperty, properties, save, options*/ 23) { - each_value = /*properties*/ ctx[0]; - let i; - - for (i = 0; i < each_value.length; i += 1) { - const child_ctx = get_each_context$3(ctx, each_value, i); - - if (each_blocks[i]) { - each_blocks[i].p(child_ctx, dirty); - } else { - each_blocks[i] = create_each_block$3(child_ctx); - each_blocks[i].c(); - each_blocks[i].m(table, null); - } - } - - for (; i < each_blocks.length; i += 1) { - each_blocks[i].d(1); - } - - each_blocks.length = each_value.length; - } - }, - i: noop, - o: noop, - d(detaching) { - if (detaching) detach(div1); - destroy_each(each_blocks, detaching); - mounted = false; - dispose(); - } - }; -} - -function instance$4($$self, $$props, $$invalidate) { - const options = Object.keys(ProgressPropertyOptions).map(k => ProgressPropertyOptions[k]); - let { save } = $$props; - let { properties } = $$props; - - function addNewProperty() { - let newProp = { - name: "", - type: ProgressPropertyOptions.TaskTotal - }; - - $$invalidate(0, properties = [...properties, newProp]); - save(properties); - } - - function removeProperty(property) { - $$invalidate(0, properties = properties.filter(prop => prop !== property)); - save(properties); - } - - function input0_input_handler(each_value, property_index) { - each_value[property_index].name = this.value; - $$invalidate(0, properties); - $$invalidate(2, options); - } - - const change_handler = () => save(properties); - - function select_change_handler(each_value, property_index) { - each_value[property_index].type = select_value(this); - $$invalidate(0, properties); - $$invalidate(2, options); - } - - const change_handler_1 = () => save(properties); - const click_handler = property => removeProperty(property); - - $$self.$$set = $$props => { - if ('save' in $$props) $$invalidate(1, save = $$props.save); - if ('properties' in $$props) $$invalidate(0, properties = $$props.properties); - }; - - return [ - properties, - save, - options, - addNewProperty, - removeProperty, - input0_input_handler, - change_handler, - select_change_handler, - change_handler_1, - click_handler - ]; -} - -class ProgressPropertiesModalContent extends SvelteComponent { - constructor(options) { - super(); - init(this, options, instance$4, create_fragment$4, safe_not_equal, { save: 1, properties: 0 }, add_css$3); - } -} - -/* src/Modals/AutoPropertiesSettingModal/AutoPropertiesModalContent.svelte generated by Svelte v3.59.2 */ - -function add_css$2(target) { - append_styles(target, "svelte-kqcr7b", ".buttonContainer.svelte-kqcr7b{display:flex;justify-content:center;margin-top:1rem}button.svelte-kqcr7b{margin-left:5px;margin-right:5px;font-size:15px}"); -} - -function get_each_context$2(ctx, list, i) { - const child_ctx = ctx.slice(); - child_ctx[13] = list[i]; - child_ctx[14] = list; - child_ctx[15] = i; - return child_ctx; -} - -function get_each_context_1(ctx, list, i) { - const child_ctx = ctx.slice(); - child_ctx[16] = list[i]; - child_ctx[17] = list; - child_ctx[18] = i; - return child_ctx; -} - -// (49:20) {#each property.choices as choice, i} -function create_each_block_1(ctx) { - let div; - let input0; - let t0; - let input1; - let t1; - let mounted; - let dispose; - - function input0_input_handler() { - /*input0_input_handler*/ ctx[10].call(input0, /*each_value_1*/ ctx[17], /*i*/ ctx[18]); - } - - function click_handler_1() { - return /*click_handler_1*/ ctx[11](/*property*/ ctx[13], /*i*/ ctx[18]); - } - - return { - c() { - div = element("div"); - input0 = element("input"); - t0 = space(); - input1 = element("input"); - t1 = space(); - attr(input0, "type", "text"); - attr(input1, "class", "not-a-button"); - attr(input1, "type", "button"); - input1.value = "❌"; - set_style(div, "display", "block"); - }, - m(target, anchor) { - insert(target, div, anchor); - append(div, input0); - set_input_value(input0, /*choice*/ ctx[16]); - append(div, t0); - append(div, input1); - append(div, t1); - - if (!mounted) { - dispose = [ - listen(input0, "change", /*change_handler_1*/ ctx[9]), - listen(input0, "input", input0_input_handler), - listen(input1, "click", click_handler_1) - ]; - - mounted = true; - } - }, - p(new_ctx, dirty) { - ctx = new_ctx; - - if (dirty & /*autoProperties*/ 1 && input0.value !== /*choice*/ ctx[16]) { - set_input_value(input0, /*choice*/ ctx[16]); - } - }, - d(detaching) { - if (detaching) detach(div); - mounted = false; - run_all(dispose); - } - }; -} - -// (40:8) {#each autoProperties as property} -function create_each_block$2(ctx) { - let tr; - let td0; - let input0; - let t0; - let td1; - let input1; - let t1; - let td2; - let t2; - let td3; - let div; - let input2; - let t3; - let br; - let mounted; - let dispose; - - function click_handler() { - return /*click_handler*/ ctx[6](/*property*/ ctx[13]); - } - - function input1_input_handler() { - /*input1_input_handler*/ ctx[8].call(input1, /*each_value*/ ctx[14], /*property_index*/ ctx[15]); - } - - let each_value_1 = /*property*/ ctx[13].choices; - let each_blocks = []; - - for (let i = 0; i < each_value_1.length; i += 1) { - each_blocks[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i)); - } - - function click_handler_2() { - return /*click_handler_2*/ ctx[12](/*property*/ ctx[13]); - } - - return { - c() { - tr = element("tr"); - td0 = element("td"); - input0 = element("input"); - t0 = space(); - td1 = element("td"); - input1 = element("input"); - t1 = space(); - td2 = element("td"); - - for (let i = 0; i < each_blocks.length; i += 1) { - each_blocks[i].c(); - } - - t2 = space(); - td3 = element("td"); - div = element("div"); - input2 = element("input"); - t3 = space(); - br = element("br"); - attr(input0, "type", "button"); - input0.value = "❌"; - attr(input0, "class", "not-a-button"); - attr(input1, "type", "text"); - attr(input1, "placeholder", "Property name"); - attr(input2, "class", "not-a-button"); - attr(input2, "type", "button"); - input2.value = "➕"; - set_style(div, "width", "50%"); - set_style(div, "text-align", "center"); - set_style(div, "margin", "5px auto auto"); - }, - m(target, anchor) { - insert(target, tr, anchor); - append(tr, td0); - append(td0, input0); - append(tr, t0); - append(tr, td1); - append(td1, input1); - set_input_value(input1, /*property*/ ctx[13].name); - append(tr, t1); - append(tr, td2); - - for (let i = 0; i < each_blocks.length; i += 1) { - if (each_blocks[i]) { - each_blocks[i].m(td2, null); - } - } - - append(tr, t2); - append(tr, td3); - append(td3, div); - append(div, input2); - insert(target, t3, anchor); - insert(target, br, anchor); - - if (!mounted) { - dispose = [ - listen(input0, "click", click_handler), - listen(input1, "change", /*change_handler*/ ctx[7]), - listen(input1, "input", input1_input_handler), - listen(input2, "click", click_handler_2) - ]; - - mounted = true; - } - }, - p(new_ctx, dirty) { - ctx = new_ctx; - - if (dirty & /*autoProperties*/ 1 && input1.value !== /*property*/ ctx[13].name) { - set_input_value(input1, /*property*/ ctx[13].name); - } - - if (dirty & /*removeChoice, autoProperties, save*/ 19) { - each_value_1 = /*property*/ ctx[13].choices; - let i; - - for (i = 0; i < each_value_1.length; i += 1) { - const child_ctx = get_each_context_1(ctx, each_value_1, i); - - if (each_blocks[i]) { - each_blocks[i].p(child_ctx, dirty); - } else { - each_blocks[i] = create_each_block_1(child_ctx); - each_blocks[i].c(); - each_blocks[i].m(td2, null); - } - } - - for (; i < each_blocks.length; i += 1) { - each_blocks[i].d(1); - } - - each_blocks.length = each_value_1.length; - } - }, - d(detaching) { - if (detaching) detach(tr); - destroy_each(each_blocks, detaching); - if (detaching) detach(t3); - if (detaching) detach(br); - mounted = false; - run_all(dispose); - } - }; -} - -function create_fragment$3(ctx) { - let div1; - let table; - let thead; - let t4; - let t5; - let div0; - let button; - let mounted; - let dispose; - let each_value = /*autoProperties*/ ctx[0]; - let each_blocks = []; - - for (let i = 0; i < each_value.length; i += 1) { - each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i)); - } - - return { - c() { - div1 = element("div"); - table = element("table"); - thead = element("thead"); - - thead.innerHTML = ` - Name - Values`; - - t4 = space(); - - for (let i = 0; i < each_blocks.length; i += 1) { - each_blocks[i].c(); - } - - t5 = space(); - div0 = element("div"); - button = element("button"); - button.textContent = "Add"; - attr(button, "class", "mod-cta svelte-kqcr7b"); - attr(div0, "class", "buttonContainer svelte-kqcr7b"); - attr(div1, "class", "centerSettingContent"); - }, - m(target, anchor) { - insert(target, div1, anchor); - append(div1, table); - append(table, thead); - append(table, t4); - - for (let i = 0; i < each_blocks.length; i += 1) { - if (each_blocks[i]) { - each_blocks[i].m(table, null); - } - } - - append(div1, t5); - append(div1, div0); - append(div0, button); - - if (!mounted) { - dispose = listen(button, "click", /*addNewProperty*/ ctx[2]); - mounted = true; - } - }, - p(ctx, [dirty]) { - if (dirty & /*addChoice, autoProperties, removeChoice, save, removeProperty*/ 59) { - each_value = /*autoProperties*/ ctx[0]; - let i; - - for (i = 0; i < each_value.length; i += 1) { - const child_ctx = get_each_context$2(ctx, each_value, i); - - if (each_blocks[i]) { - each_blocks[i].p(child_ctx, dirty); - } else { - each_blocks[i] = create_each_block$2(child_ctx); - each_blocks[i].c(); - each_blocks[i].m(table, null); - } - } - - for (; i < each_blocks.length; i += 1) { - each_blocks[i].d(1); - } - - each_blocks.length = each_value.length; - } - }, - i: noop, - o: noop, - d(detaching) { - if (detaching) detach(div1); - destroy_each(each_blocks, detaching); - mounted = false; - dispose(); - } - }; -} - -function instance$3($$self, $$props, $$invalidate) { - let { save } = $$props; - let { autoProperties = [] } = $$props; - - function addNewProperty() { - let newProp = { name: "", choices: [""] }; - if (typeof autoProperties[Symbol.iterator] !== 'function') $$invalidate(0, autoProperties = [newProp]); else $$invalidate(0, autoProperties = [...autoProperties, newProp]); - save(autoProperties); - } - - function removeProperty(property) { - $$invalidate(0, autoProperties = autoProperties.filter(ac => ac !== property)); - save(autoProperties); - } - - function removeChoice(property, i) { - property.choices.splice(i, 1); - $$invalidate(0, autoProperties); // Svelte - save(autoProperties); - } - - function addChoice(property) { - $$invalidate(0, autoProperties = autoProperties.map(prop => { - if (prop === property) { - prop.choices.push(""); - } - - return prop; - })); - - save(autoProperties); - } - - const click_handler = property => removeProperty(property); - const change_handler = () => save(autoProperties); - - function input1_input_handler(each_value, property_index) { - each_value[property_index].name = this.value; - $$invalidate(0, autoProperties); - } - - const change_handler_1 = () => save(autoProperties); - - function input0_input_handler(each_value_1, i) { - each_value_1[i] = this.value; - $$invalidate(0, autoProperties); - } - - const click_handler_1 = (property, i) => removeChoice(property, i); - const click_handler_2 = property => addChoice(property); - - $$self.$$set = $$props => { - if ('save' in $$props) $$invalidate(1, save = $$props.save); - if ('autoProperties' in $$props) $$invalidate(0, autoProperties = $$props.autoProperties); - }; - - return [ - autoProperties, - save, - addNewProperty, - removeProperty, - removeChoice, - addChoice, - click_handler, - change_handler, - input1_input_handler, - change_handler_1, - input0_input_handler, - click_handler_1, - click_handler_2 - ]; -} - -class AutoPropertiesModalContent extends SvelteComponent { - constructor(options) { - super(); - init(this, options, instance$3, create_fragment$3, safe_not_equal, { save: 1, autoProperties: 0 }, add_css$2); - } -} - -var top = 'top'; -var bottom = 'bottom'; -var right = 'right'; -var left = 'left'; -var auto = 'auto'; -var basePlacements = [top, bottom, right, left]; -var start = 'start'; -var end = 'end'; -var clippingParents = 'clippingParents'; -var viewport = 'viewport'; -var popper = 'popper'; -var reference = 'reference'; -var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) { - return acc.concat([placement + "-" + start, placement + "-" + end]); -}, []); -var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) { - return acc.concat([placement, placement + "-" + start, placement + "-" + end]); -}, []); // modifiers that need to read the DOM - -var beforeRead = 'beforeRead'; -var read = 'read'; -var afterRead = 'afterRead'; // pure-logic modifiers - -var beforeMain = 'beforeMain'; -var main = 'main'; -var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state) - -var beforeWrite = 'beforeWrite'; -var write = 'write'; -var afterWrite = 'afterWrite'; -var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; - -function getNodeName(element) { - return element ? (element.nodeName || '').toLowerCase() : null; -} - -function getWindow(node) { - if (node == null) { - return window; - } - - if (node.toString() !== '[object Window]') { - var ownerDocument = node.ownerDocument; - return ownerDocument ? ownerDocument.defaultView || window : window; - } - - return node; -} - -function isElement(node) { - var OwnElement = getWindow(node).Element; - return node instanceof OwnElement || node instanceof Element; -} - -function isHTMLElement(node) { - var OwnElement = getWindow(node).HTMLElement; - return node instanceof OwnElement || node instanceof HTMLElement; -} - -function isShadowRoot(node) { - // IE 11 has no ShadowRoot - if (typeof ShadowRoot === 'undefined') { - return false; - } - - var OwnElement = getWindow(node).ShadowRoot; - return node instanceof OwnElement || node instanceof ShadowRoot; -} - -// and applies them to the HTMLElements such as popper and arrow - -function applyStyles(_ref) { - var state = _ref.state; - Object.keys(state.elements).forEach(function (name) { - var style = state.styles[name] || {}; - var attributes = state.attributes[name] || {}; - var element = state.elements[name]; // arrow is optional + virtual elements - - if (!isHTMLElement(element) || !getNodeName(element)) { - return; - } // Flow doesn't support to extend this property, but it's the most - // effective way to apply styles to an HTMLElement - // $FlowFixMe[cannot-write] - - - Object.assign(element.style, style); - Object.keys(attributes).forEach(function (name) { - var value = attributes[name]; - - if (value === false) { - element.removeAttribute(name); - } else { - element.setAttribute(name, value === true ? '' : value); - } - }); - }); -} - -function effect$2(_ref2) { - var state = _ref2.state; - var initialStyles = { - popper: { - position: state.options.strategy, - left: '0', - top: '0', - margin: '0' - }, - arrow: { - position: 'absolute' - }, - reference: {} - }; - Object.assign(state.elements.popper.style, initialStyles.popper); - state.styles = initialStyles; - - if (state.elements.arrow) { - Object.assign(state.elements.arrow.style, initialStyles.arrow); - } - - return function () { - Object.keys(state.elements).forEach(function (name) { - var element = state.elements[name]; - var attributes = state.attributes[name] || {}; - var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them - - var style = styleProperties.reduce(function (style, property) { - style[property] = ''; - return style; - }, {}); // arrow is optional + virtual elements - - if (!isHTMLElement(element) || !getNodeName(element)) { - return; - } - - Object.assign(element.style, style); - Object.keys(attributes).forEach(function (attribute) { - element.removeAttribute(attribute); - }); - }); - }; -} // eslint-disable-next-line import/no-unused-modules - - -var applyStyles$1 = { - name: 'applyStyles', - enabled: true, - phase: 'write', - fn: applyStyles, - effect: effect$2, - requires: ['computeStyles'] +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __typeError = (msg) => { + throw TypeError(msg); }; - -function getBasePlacement(placement) { - return placement.split('-')[0]; -} - -var max = Math.max; -var min = Math.min; -var round = Math.round; - -function getUAString() { - var uaData = navigator.userAgentData; - - if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { - return uaData.brands.map(function (item) { - return item.brand + "/" + item.version; - }).join(' '); +var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key2 of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key2) && key2 !== except) + __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value); +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); +var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); - return navigator.userAgent; +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => MetaEdit +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian25 = require("obsidian"); + +// src/Settings/metaEditSettingsTab.ts +var import_obsidian3 = require("obsidian"); + +// node_modules/.pnpm/svelte@5.56.4_@typescript-eslint+types@8.62.0/node_modules/svelte/src/version.js +var PUBLIC_VERSION = "5"; + +// node_modules/.pnpm/svelte@5.56.4_@typescript-eslint+types@8.62.0/node_modules/svelte/src/internal/disclose-version.js +var _a; +if (typeof window !== "undefined") { + ((_a = window.__svelte ?? (window.__svelte = {})).v ?? (_a.v = /* @__PURE__ */ new Set())).add(PUBLIC_VERSION); } -function isLayoutViewport() { - return !/^((?!chrome|android).)*safari/i.test(getUAString()); -} +// node_modules/.pnpm/svelte@5.56.4_@typescript-eslint+types@8.62.0/node_modules/svelte/src/constants.js +var EACH_ITEM_REACTIVE = 1; +var EACH_INDEX_REACTIVE = 1 << 1; +var EACH_IS_CONTROLLED = 1 << 2; +var EACH_IS_ANIMATED = 1 << 3; +var EACH_ITEM_IMMUTABLE = 1 << 4; +var PROPS_IS_IMMUTABLE = 1; +var PROPS_IS_RUNES = 1 << 1; +var PROPS_IS_UPDATED = 1 << 2; +var PROPS_IS_BINDABLE = 1 << 3; +var PROPS_IS_LAZY_INITIAL = 1 << 4; +var TRANSITION_OUT = 1 << 1; +var TRANSITION_GLOBAL = 1 << 2; +var TEMPLATE_FRAGMENT = 1; +var TEMPLATE_USE_IMPORT_NODE = 1 << 1; +var TEMPLATE_USE_SVG = 1 << 2; +var TEMPLATE_USE_MATHML = 1 << 3; +var HYDRATION_START = "["; +var HYDRATION_START_ELSE = "[!"; +var HYDRATION_START_FAILED = "[?"; +var HYDRATION_END = "]"; +var HYDRATION_ERROR = {}; +var ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1; +var ELEMENT_IS_INPUT = 1 << 2; +var UNINITIALIZED = /* @__PURE__ */ Symbol("uninitialized"); +var FILENAME = /* @__PURE__ */ Symbol("filename"); +var NAMESPACE_HTML = "http://www.w3.org/1999/xhtml"; -function getBoundingClientRect(element, includeScale, isFixedStrategy) { - if (includeScale === void 0) { - includeScale = false; +// node_modules/.pnpm/esm-env@1.2.2/node_modules/esm-env/dev-fallback.js +var node_env = globalThis.process?.env?.NODE_ENV; +var dev_fallback_default = node_env && !node_env.toLowerCase().startsWith("prod"); + +// node_modules/.pnpm/svelte@5.56.4_@typescript-eslint+types@8.62.0/node_modules/svelte/src/internal/shared/utils.js +var is_array = Array.isArray; +var index_of = Array.prototype.indexOf; +var includes = Array.prototype.includes; +var array_from = Array.from; +var object_keys = Object.keys; +var define_property = Object.defineProperty; +var get_descriptor = Object.getOwnPropertyDescriptor; +var get_descriptors = Object.getOwnPropertyDescriptors; +var object_prototype = Object.prototype; +var array_prototype = Array.prototype; +var get_prototype_of = Object.getPrototypeOf; +var is_extensible = Object.isExtensible; +var noop = () => { +}; +function run_all(arr) { + for (var i = 0; i < arr.length; i++) { + arr[i](); } +} +function deferred() { + var resolve; + var reject; + var promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} - if (isFixedStrategy === void 0) { - isFixedStrategy = false; +// node_modules/.pnpm/svelte@5.56.4_@typescript-eslint+types@8.62.0/node_modules/svelte/src/internal/client/constants.js +var DERIVED = 1 << 1; +var EFFECT = 1 << 2; +var RENDER_EFFECT = 1 << 3; +var MANAGED_EFFECT = 1 << 24; +var BLOCK_EFFECT = 1 << 4; +var BRANCH_EFFECT = 1 << 5; +var ROOT_EFFECT = 1 << 6; +var BOUNDARY_EFFECT = 1 << 7; +var CONNECTED = 1 << 9; +var CLEAN = 1 << 10; +var DIRTY = 1 << 11; +var MAYBE_DIRTY = 1 << 12; +var INERT = 1 << 13; +var DESTROYED = 1 << 14; +var REACTION_RAN = 1 << 15; +var DESTROYING = 1 << 25; +var EFFECT_TRANSPARENT = 1 << 16; +var EAGER_EFFECT = 1 << 17; +var HEAD_EFFECT = 1 << 18; +var EFFECT_PRESERVED = 1 << 19; +var USER_EFFECT = 1 << 20; +var EFFECT_OFFSCREEN = 1 << 25; +var WAS_MARKED = 1 << 16; +var REACTION_IS_UPDATING = 1 << 21; +var ASYNC = 1 << 22; +var ERROR_VALUE = 1 << 23; +var STATE_SYMBOL = /* @__PURE__ */ Symbol("$state"); +var LEGACY_PROPS = /* @__PURE__ */ Symbol("legacy props"); +var LOADING_ATTR_SYMBOL = /* @__PURE__ */ Symbol(""); +var PROXY_PATH_SYMBOL = /* @__PURE__ */ Symbol("proxy path"); +var ATTRIBUTES_CACHE = /* @__PURE__ */ Symbol("attributes"); +var CLASS_CACHE = /* @__PURE__ */ Symbol("class"); +var STYLE_CACHE = /* @__PURE__ */ Symbol("style"); +var TEXT_CACHE = /* @__PURE__ */ Symbol("text"); +var FORM_RESET_HANDLER = /* @__PURE__ */ Symbol("form reset"); +var HMR_ANCHOR = /* @__PURE__ */ Symbol("hmr anchor"); +var STALE_REACTION = new class StaleReactionError extends Error { + constructor() { + super(...arguments); + __publicField(this, "name", "StaleReactionError"); + __publicField(this, "message", "The reaction that called `getAbortSignal()` was re-run or destroyed"); } +}(); +var IS_XHTML = ( + // We gotta write it like this because after downleveling the pure comment may end up in the wrong location + !!globalThis.document?.contentType && /* @__PURE__ */ globalThis.document.contentType.includes("xml") +); +var TEXT_NODE = 3; +var COMMENT_NODE = 8; - var clientRect = element.getBoundingClientRect(); - var scaleX = 1; - var scaleY = 1; - - if (includeScale && isHTMLElement(element)) { - scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1; - scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1; +// node_modules/.pnpm/svelte@5.56.4_@typescript-eslint+types@8.62.0/node_modules/svelte/src/internal/shared/errors.js +function invariant_violation(message) { + if (dev_fallback_default) { + const error = new Error(`invariant_violation +An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app \u2014 please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${message}" +https://svelte.dev/e/invariant_violation`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/invariant_violation`); } - - var _ref = isElement(element) ? getWindow(element) : window, - visualViewport = _ref.visualViewport; - - var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; - var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; - var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; - var width = clientRect.width / scaleX; - var height = clientRect.height / scaleY; - return { - width: width, - height: height, - top: y, - right: x + width, - bottom: y + height, - left: x, - x: x, - y: y - }; } -// means it doesn't take into account transforms. - -function getLayoutRect(element) { - var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed. - // Fixes https://github.com/popperjs/popper-core/issues/1223 - - var width = element.offsetWidth; - var height = element.offsetHeight; - - if (Math.abs(clientRect.width - width) <= 1) { - width = clientRect.width; +// node_modules/.pnpm/svelte@5.56.4_@typescript-eslint+types@8.62.0/node_modules/svelte/src/internal/client/errors.js +function async_derived_orphan() { + if (dev_fallback_default) { + const error = new Error(`async_derived_orphan +Cannot create a \`$derived(...)\` with an \`await\` expression outside of an effect tree +https://svelte.dev/e/async_derived_orphan`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/async_derived_orphan`); } - - if (Math.abs(clientRect.height - height) <= 1) { - height = clientRect.height; +} +function bind_invalid_checkbox_value() { + if (dev_fallback_default) { + const error = new Error(`bind_invalid_checkbox_value +Using \`bind:value\` together with a checkbox input is not allowed. Use \`bind:checked\` instead +https://svelte.dev/e/bind_invalid_checkbox_value`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/bind_invalid_checkbox_value`); } - - return { - x: element.offsetLeft, - y: element.offsetTop, - width: width, - height: height - }; } - -function contains(parent, child) { - var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method - - if (parent.contains(child)) { - return true; - } // then fallback to custom implementation with Shadow DOM support - else if (rootNode && isShadowRoot(rootNode)) { - var next = child; - - do { - if (next && parent.isSameNode(next)) { - return true; - } // $FlowFixMe[prop-missing]: need a better way to handle this... - - - next = next.parentNode || next.host; - } while (next); - } // Give up, the result is false - - - return false; -} - -function getComputedStyle(element) { - return getWindow(element).getComputedStyle(element); -} - -function isTableElement(element) { - return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0; -} - -function getDocumentElement(element) { - // $FlowFixMe[incompatible-return]: assume body is always available - return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing] - element.document) || window.document).documentElement; -} - -function getParentNode(element) { - if (getNodeName(element) === 'html') { - return element; +function derived_references_self() { + if (dev_fallback_default) { + const error = new Error(`derived_references_self +A derived value cannot reference itself recursively +https://svelte.dev/e/derived_references_self`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/derived_references_self`); } +} +function each_key_duplicate(a, b, value) { + if (dev_fallback_default) { + const error = new Error(`each_key_duplicate +${value ? `Keyed each block has duplicate key \`${value}\` at indexes ${a} and ${b}` : `Keyed each block has duplicate key at indexes ${a} and ${b}`} +https://svelte.dev/e/each_key_duplicate`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/each_key_duplicate`); + } +} +function each_key_volatile(index2, a, b) { + if (dev_fallback_default) { + const error = new Error(`each_key_volatile +Keyed each block has key that is not idempotent \u2014 the key for item at index ${index2} was \`${a}\` but is now \`${b}\`. Keys must be the same each time for a given item +https://svelte.dev/e/each_key_volatile`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/each_key_volatile`); + } +} +function effect_in_teardown(rune) { + if (dev_fallback_default) { + const error = new Error(`effect_in_teardown +\`${rune}\` cannot be used inside an effect cleanup function +https://svelte.dev/e/effect_in_teardown`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/effect_in_teardown`); + } +} +function effect_in_unowned_derived() { + if (dev_fallback_default) { + const error = new Error(`effect_in_unowned_derived +Effect cannot be created inside a \`$derived\` value that was not itself created inside an effect +https://svelte.dev/e/effect_in_unowned_derived`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/effect_in_unowned_derived`); + } +} +function effect_orphan(rune) { + if (dev_fallback_default) { + const error = new Error(`effect_orphan +\`${rune}\` can only be used inside an effect (e.g. during component initialisation) +https://svelte.dev/e/effect_orphan`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/effect_orphan`); + } +} +function effect_update_depth_exceeded() { + if (dev_fallback_default) { + const error = new Error(`effect_update_depth_exceeded +Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state +https://svelte.dev/e/effect_update_depth_exceeded`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`); + } +} +function hydration_failed() { + if (dev_fallback_default) { + const error = new Error(`hydration_failed +Failed to hydrate the application +https://svelte.dev/e/hydration_failed`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/hydration_failed`); + } +} +function props_invalid_value(key2) { + if (dev_fallback_default) { + const error = new Error(`props_invalid_value +Cannot do \`bind:${key2}={undefined}\` when \`${key2}\` has a fallback value +https://svelte.dev/e/props_invalid_value`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/props_invalid_value`); + } +} +function rune_outside_svelte(rune) { + if (dev_fallback_default) { + const error = new Error(`rune_outside_svelte +The \`${rune}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files +https://svelte.dev/e/rune_outside_svelte`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/rune_outside_svelte`); + } +} +function state_descriptors_fixed() { + if (dev_fallback_default) { + const error = new Error(`state_descriptors_fixed +Property descriptors defined on \`$state\` objects must contain \`value\` and always be \`enumerable\`, \`configurable\` and \`writable\`. +https://svelte.dev/e/state_descriptors_fixed`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/state_descriptors_fixed`); + } +} +function state_prototype_fixed() { + if (dev_fallback_default) { + const error = new Error(`state_prototype_fixed +Cannot set prototype of \`$state\` object +https://svelte.dev/e/state_prototype_fixed`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/state_prototype_fixed`); + } +} +function state_unsafe_mutation() { + if (dev_fallback_default) { + const error = new Error(`state_unsafe_mutation +Updating state inside \`$derived(...)\`, \`$inspect(...)\` or a template expression is forbidden. If the value should not be reactive, declare it without \`$state\` +https://svelte.dev/e/state_unsafe_mutation`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/state_unsafe_mutation`); + } +} +function svelte_boundary_reset_onerror() { + if (dev_fallback_default) { + const error = new Error(`svelte_boundary_reset_onerror +A \`\` \`reset\` function cannot be called while an error is still being handled +https://svelte.dev/e/svelte_boundary_reset_onerror`); + error.name = "Svelte error"; + throw error; + } else { + throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`); + } +} - return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle - // $FlowFixMe[incompatible-return] - // $FlowFixMe[prop-missing] - element.assignedSlot || // step into the shadow DOM of the parent of a slotted node - element.parentNode || ( // DOM Element detected - isShadowRoot(element) ? element.host : null) || // ShadowRoot detected - // $FlowFixMe[incompatible-call]: HTMLElement is a Node - getDocumentElement(element) // fallback +// node_modules/.pnpm/svelte@5.56.4_@typescript-eslint+types@8.62.0/node_modules/svelte/src/internal/client/warnings.js +var bold = "font-weight: bold"; +var normal = "font-weight: normal"; +function await_reactivity_loss(name) { + if (dev_fallback_default) { + console.warn(`%c[svelte] await_reactivity_loss +%cDetected reactivity loss when reading \`${name}\`. This happens when state is read in an async function after an earlier \`await\` +https://svelte.dev/e/await_reactivity_loss`, bold, normal); + } else { + console.warn(`https://svelte.dev/e/await_reactivity_loss`); + } +} +function await_waterfall(name, location) { + if (dev_fallback_default) { + console.warn(`%c[svelte] await_waterfall +%cAn async derived, \`${name}\` (${location}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app +https://svelte.dev/e/await_waterfall`, bold, normal); + } else { + console.warn(`https://svelte.dev/e/await_waterfall`); + } +} +function derived_inert() { + if (dev_fallback_default) { + console.warn(`%c[svelte] derived_inert +%cReading a derived belonging to a now-destroyed effect may result in stale values +https://svelte.dev/e/derived_inert`, bold, normal); + } else { + console.warn(`https://svelte.dev/e/derived_inert`); + } +} +function hydration_attribute_changed(attribute, html2, value) { + if (dev_fallback_default) { + console.warn(`%c[svelte] hydration_attribute_changed +%cThe \`${attribute}\` attribute on \`${html2}\` changed its value between server and client renders. The client value, \`${value}\`, will be ignored in favour of the server value +https://svelte.dev/e/hydration_attribute_changed`, bold, normal); + } else { + console.warn(`https://svelte.dev/e/hydration_attribute_changed`); + } +} +function hydration_mismatch(location) { + if (dev_fallback_default) { + console.warn( + `%c[svelte] hydration_mismatch +%c${location ? `Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}` : "Hydration failed because the initial UI does not match what was rendered on the server"} +https://svelte.dev/e/hydration_mismatch`, + bold, + normal + ); + } else { + console.warn(`https://svelte.dev/e/hydration_mismatch`); + } +} +function lifecycle_double_unmount() { + if (dev_fallback_default) { + console.warn(`%c[svelte] lifecycle_double_unmount +%cTried to unmount a component that was not mounted +https://svelte.dev/e/lifecycle_double_unmount`, bold, normal); + } else { + console.warn(`https://svelte.dev/e/lifecycle_double_unmount`); + } +} +function select_multiple_invalid_value() { + if (dev_fallback_default) { + console.warn(`%c[svelte] select_multiple_invalid_value +%cThe \`value\` property of a \``); +var root_2 = from_html(`
NameType
`); +var $$css = { + hash: "svelte-1eh4i7q", + code: ".buttonContainer.svelte-1eh4i7q {display:flex;justify-content:center;margin-top:1rem;}select.svelte-1eh4i7q {border-radius:4px;width:100%;height:30px;border:1px solid #dbdbdc;color:#383a42;background-color:#fff;padding:3px;}button.svelte-1eh4i7q {margin-left:5px;margin-right:5px;font-size:15px;}" +}; +function ProgressPropertiesModalContent($$anchor, $$props) { + push($$props, true); + append_styles($$anchor, $$css); + const options = Object.keys(ProgressPropertyOptions).map((k) => ProgressPropertyOptions[k]); + let initialProperties = prop($$props, "properties", 19, () => []); + let properties = state(proxy(untrack(() => initialProperties().map((property) => ({ ...property }))))); + function saveProperties() { + $$props.save(snapshot(get2(properties))); + } + function addNewProperty() { + const newProp = { name: "", type: "Total Tasks" /* TaskTotal */ }; + set(properties, [...get2(properties), newProp], true); + saveProperties(); + } + function removeProperty(property) { + set(properties, get2(properties).filter((prop2) => prop2 !== property), true); + saveProperties(); + } + var div = root_2(); + var table = child(div); + var tbody = sibling(child(table)); + each(tbody, 20, () => get2(properties), (property) => property, ($$anchor2, property, $$index_1) => { + var tr = root_1(); + var td = child(tr); + var input = child(td); + remove_input_defaults(input); + reset(td); + var td_1 = sibling(td); + var select = child(td_1); + each(select, 20, () => options, (text2) => text2, ($$anchor3, text2) => { + var option = root(); + var option_value = {}; + template_effect(() => { + set_attribute2(option, "label", text2); + if (option_value !== (option_value = text2)) { + option.value = (option.__value = text2) ?? ""; + } }); - } - - return pending; - }; -} - -function mergeByName(modifiers) { - var merged = modifiers.reduce(function (merged, current) { - var existing = merged[current.name]; - merged[current.name] = existing ? Object.assign({}, existing, current, { - options: Object.assign({}, existing.options, current.options), - data: Object.assign({}, existing.data, current.data) - }) : current; - return merged; - }, {}); // IE11 does not support Object.values - - return Object.keys(merged).map(function (key) { - return merged[key]; + append($$anchor3, option); + }); + reset(select); + reset(td_1); + var td_2 = sibling(td_1); + var input_1 = child(td_2); + reset(td_2); + reset(tr); + delegated("change", input, saveProperties); + bind_value(input, () => property.name, ($$value) => property.name = $$value); + delegated("change", select, saveProperties); + bind_select_value(select, () => property.type, ($$value) => property.type = $$value); + delegated("click", input_1, () => removeProperty(property)); + append($$anchor2, tr); }); + reset(tbody); + reset(table); + var div_1 = sibling(table, 2); + var button = child(div_1); + reset(div_1); + reset(div); + delegated("click", button, addNewProperty); + append($$anchor, div); + pop(); +} +delegate(["change", "click"]); + +// src/Modals/AutoPropertiesSettingModal/AutoPropertiesModalContent.svelte +var import_obsidian = require("obsidian"); + +// src/autoProperties.ts +function findAutoProperty(properties, propertyName) { + return properties?.find((a) => a.name === propertyName); +} +function isMultiAutoProperty(autoProp, editMode, propertyName) { + if (autoProp.type === "Multi") return true; + if (autoProp.type === "Single") return false; + if (editMode.mode === "All Multi" /* AllMulti */) return true; + if (editMode.mode === "Some Multi" /* SomeMulti */ && editMode.properties.includes(propertyName)) { + return true; + } + return false; +} +function normalizeChoices(choices) { + if (!choices) return []; + const seen = /* @__PURE__ */ new Set(); + const out = []; + for (const raw of choices) { + const choice = (raw ?? "").trim(); + if (choice === "" || seen.has(choice)) continue; + seen.add(choice); + out.push(choice); + } + return out; +} +function splitPastedChoices(text2) { + if (!text2) return []; + const parts = /[\r\n]/.test(text2) ? text2.split(/\r\n|\r|\n/) : text2.split(","); + return parts.map((p) => p.trim()).filter((p) => p !== ""); +} +function withChoicesPasted(choices, index2, tokens) { + const before = choices.slice(0, index2); + const after = choices.slice(index2 + 1); + const taken = new Set( + [...before, ...after].map((c) => (c ?? "").trim()).filter((c) => c !== "") + ); + const inserted = []; + for (const raw of tokens) { + const choice = (raw ?? "").trim(); + if (choice === "" || taken.has(choice)) continue; + taken.add(choice); + inserted.push(choice); + } + return [...before, ...inserted, ...after]; +} +function cloneAutoProperty(property) { + const clone2 = { + name: property.name, + choices: Array.isArray(property.choices) ? [...property.choices] : [] + }; + if (property.description !== void 0) clone2.description = property.description; + if (property.type !== void 0) clone2.type = property.type; + return clone2; +} +function cloneAutoProperties(properties) { + if (!Array.isArray(properties)) return []; + return properties.map(cloneAutoProperty); +} +function applyAutoPropertySettingsOperation(properties, operation) { + const next2 = cloneAutoProperties(properties); + switch (operation.kind) { + case "addProperty": { + const index2 = boundedInsertIndex(operation.index, next2.length); + next2.splice(index2, 0, cloneAutoProperty(operation.property)); + return next2; + } + case "removeProperty": { + const index2 = findAutoPropertyOperationTargetIndex(next2, operation.target); + if (index2 === -1) return false; + next2.splice(index2, 1); + return next2; + } + case "setName": + case "setDescription": + case "setType": { + const index2 = findAutoPropertyOperationTargetIndex(next2, operation.target); + if (index2 === -1) return false; + const current = next2[index2]; + if (operation.kind === "setName") { + if (current.name === operation.value) return false; + current.name = operation.value; + } else if (operation.kind === "setDescription") { + if ((current.description ?? "") === operation.value) return false; + current.description = operation.value; + } else { + if ((current.type ?? "Single") === operation.value) return false; + current.type = operation.value; + } + return next2; + } + case "addChoice": { + const property = findAutoPropertyOperationTarget(next2, operation.target); + if (!property) return false; + property.choices.splice(boundedInsertIndex(operation.index, property.choices.length), 0, operation.value); + return next2; + } + case "removeChoice": { + const property = findAutoPropertyOperationTarget(next2, operation.target); + if (!property) return false; + const choiceIndex = findExistingChoiceIndex(property.choices, operation.index, operation.value); + if (choiceIndex === -1) return false; + property.choices.splice(choiceIndex, 1); + return next2; + } + case "setChoice": { + const property = findAutoPropertyOperationTarget(next2, operation.target); + if (!property) return false; + if (operation.previousValue === operation.value) return false; + const choiceIndex = findWritableChoiceIndex(property.choices, operation.index, operation.previousValue); + property.choices.splice(choiceIndex, choiceIndex < property.choices.length ? 1 : 0, operation.value); + return next2; + } + case "replaceChoiceWithChoices": { + const property = findAutoPropertyOperationTarget(next2, operation.target); + if (!property) return false; + const choiceIndex = findExistingChoiceIndex(property.choices, operation.index, operation.previousValue); + if (choiceIndex === -1) { + property.choices = withChoicesInserted(property.choices, operation.index, operation.values); + } else { + property.choices = withChoicesPasted(property.choices, choiceIndex, operation.values); + } + return next2; + } + } +} +function boundedInsertIndex(index2, length) { + if (!Number.isFinite(index2)) return length; + return Math.max(0, Math.min(index2, length)); +} +function findAutoPropertyOperationTarget(properties, target) { + const index2 = findAutoPropertyOperationTargetIndex(properties, target); + return index2 === -1 ? void 0 : properties[index2]; +} +function findAutoPropertyOperationTargetIndex(properties, target) { + if (isValidIndex(target.index, properties.length) && properties[target.index].name === target.name) { + return target.index; + } + if (target.name !== "") { + const namedIndex = properties.findIndex((property) => property.name === target.name); + if (namedIndex !== -1) return namedIndex; + } + if (target.name === "" && isValidIndex(target.index, properties.length)) return target.index; + return -1; +} +function findExistingChoiceIndex(choices, index2, value) { + if (isValidIndex(index2, choices.length) && choices[index2] === value) return index2; + return choices.findIndex((choice) => choice === value); +} +function findWritableChoiceIndex(choices, index2, value) { + const existingIndex = findExistingChoiceIndex(choices, index2, value); + if (existingIndex !== -1) return existingIndex; + return boundedInsertIndex(index2, choices.length); +} +function withChoicesInserted(choices, index2, tokens) { + const next2 = [...choices]; + const taken = new Set(next2.map((c) => (c ?? "").trim()).filter((c) => c !== "")); + const inserted = []; + for (const raw of tokens) { + const choice = (raw ?? "").trim(); + if (choice === "" || taken.has(choice)) continue; + taken.add(choice); + inserted.push(choice); + } + next2.splice(boundedInsertIndex(index2, next2.length), 0, ...inserted); + return next2; +} +function isValidIndex(index2, length) { + return Number.isInteger(index2) && index2 >= 0 && index2 < length; +} +function splitCommaSeparatedValues(value) { + const parts = []; + let start = 0; + let wikilinkDepth = 0; + for (let i = 0; i < value.length; i++) { + if (value.startsWith("[[", i)) { + wikilinkDepth++; + i++; + continue; + } + if (wikilinkDepth > 0 && value.startsWith("]]", i)) { + wikilinkDepth--; + i++; + continue; + } + if (value[i] === "," && wikilinkDepth === 0) { + parts.push(value.slice(start, i)); + start = i + 1; + } + } + parts.push(value.slice(start)); + return parts; +} +function matchingOuterBracketIndex(value) { + let depth = 0; + for (let i = 0; i < value.length; i++) { + const char = value[i]; + if (char === "[") { + depth++; + } else if (char === "]") { + depth--; + if (depth === 0) return i; + if (depth < 0) return null; + } + } + return null; +} +function shouldUnwrapBracketedList(value) { + if (!value.startsWith("[") || !value.endsWith("]")) return false; + if (value.startsWith("[[")) return false; + if (matchingOuterBracketIndex(value) !== value.length - 1) return false; + const innerValue = value.slice(1, -1); + if (innerValue.trim() === "") return true; + return splitCommaSeparatedValues(innerValue).length > 1; +} +function toValueArray(content) { + if (content === null || content === void 0) return []; + if (Array.isArray(content)) { + return content.map((v) => (v ?? "").toString().trim()).filter(Boolean); + } + const value = content.toString().trim(); + const splitValue = shouldUnwrapBracketedList(value) ? value.slice(1, -1) : value; + return splitCommaSeparatedValues(splitValue).map((s) => s.trim()).filter(Boolean); +} +function multiSelectOptions(autoProp, currentValue) { + const seen = /* @__PURE__ */ new Set(); + const out = []; + for (const value of [...toValueArray(currentValue), ...normalizeChoices(autoProp.choices)]) { + if (!seen.has(value)) { + seen.add(value); + out.push(value); + } + } + return out; +} +function isNewChoice(autoProp, value) { + const trimmed = value.trim(); + if (trimmed === "") return false; + return !(autoProp.choices ?? []).some((c) => (c ?? "").trim() === trimmed); +} +function withChoiceAdded(autoProp, value) { + if (!isNewChoice(autoProp, value)) return autoProp; + return { ...autoProp, choices: [...autoProp.choices ?? [], value.trim()] }; } -var DEFAULT_OPTIONS = { - placement: 'bottom', - modifiers: [], - strategy: 'absolute' +// src/Modals/AutoPropertiesSettingModal/AutoPropertiesModalContent.svelte +var root2 = from_html(`

No auto properties yet. Add one to define a reusable set of values for a property.

`); +var root_12 = from_html(``); +var root_22 = from_html(`
`); +var root_3 = from_html(`
Values
`); +var root_4 = from_html(`
`); +var $$css2 = { + hash: "svelte-1i9u2va", + code: ".metaedit-auto-properties.svelte-1i9u2va {display:flex;flex-direction:column;gap:0.75rem;margin-top:0.5rem;}.metaedit-empty.svelte-1i9u2va {color:var(--text-muted);text-align:center;margin:0.5rem 0;}.metaedit-ap-card.svelte-1i9u2va {display:flex;flex-direction:column;gap:0.5rem;padding:0.75rem;border:1px solid var(--background-modifier-border);border-radius:var(--radius-m, 8px);background-color:var(--background-secondary);}.metaedit-ap-header.svelte-1i9u2va {display:flex;gap:0.5rem;align-items:center;}.metaedit-ap-name.svelte-1i9u2va {flex:1 1 auto;min-width:0;font-weight:var(--font-semibold, 600);}.metaedit-ap-type.svelte-1i9u2va {flex:0 0 auto;}.metaedit-ap-description.svelte-1i9u2va {width:100%;}.metaedit-ap-values.svelte-1i9u2va {display:flex;flex-direction:column;gap:0.35rem;}.metaedit-ap-label.svelte-1i9u2va {color:var(--text-muted);font-size:var(--font-ui-smaller, 0.8em);}.metaedit-ap-choice.svelte-1i9u2va {display:flex;gap:0.5rem;align-items:center;}.metaedit-ap-choice.svelte-1i9u2va input:where(.svelte-1i9u2va) {flex:1 1 auto;min-width:0;}.metaedit-ap-icon.svelte-1i9u2va {flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;}.metaedit-ap-add-value.svelte-1i9u2va {display:inline-flex;align-items:center;gap:0.35rem;align-self:flex-start;background:transparent;box-shadow:none;color:var(--text-muted);padding:0.25rem 0.4rem;cursor:pointer;}.metaedit-ap-add-value.svelte-1i9u2va:hover {color:var(--text-normal);}.metaedit-ap-footer.svelte-1i9u2va {display:flex;justify-content:center;margin-top:0.25rem;}" +}; +function AutoPropertiesModalContent($$anchor, $$props) { + push($$props, true); + append_styles($$anchor, $$css2); + let initialAutoProperties = prop($$props, "autoProperties", 19, () => []); + const types = ["Single", "Multi"]; + let nextPropertyId = 0; + let autoProperties = state(proxy(untrack(() => createEditableAutoProperties(initialAutoProperties())))); + function icon(node, name) { + const render = (n) => { + node.textContent = ""; + (0, import_obsidian.setIcon)(node, n); + }; + render(name); + return { update: render }; + } + function indexes(values) { + return values.map((_, i) => i); + } + function createEditableAutoProperties(properties) { + return cloneAutoProperties(properties).map((property) => createEditableAutoProperty(property)); + } + function createEditableAutoProperty(property) { + return { + id: nextPropertyId++, + property, + targetName: property.name, + choiceTargets: [...property.choices] + }; + } + function targetFor(entry, index2) { + return { name: entry.targetName, index: index2 }; + } + function persist(operation) { + void Promise.resolve($$props.save(operation)).catch((error) => { + console.error("MetaEdit could not save Auto Properties settings.", error); + }); + } + function addNewProperty() { + const property = { name: "", choices: [""], type: "Single" }; + const entry = createEditableAutoProperty(cloneAutoProperty(property)); + const index2 = get2(autoProperties).length; + set(autoProperties, [...get2(autoProperties), entry], true); + persist({ kind: "addProperty", index: index2, property }); + } + function removeProperty(entry, index2) { + const target = targetFor(entry, index2); + set(autoProperties, get2(autoProperties).filter((candidate) => candidate !== entry), true); + persist({ kind: "removeProperty", target }); + } + function removeChoice(entry, propertyIndex, choiceIndex) { + const value = entry.choiceTargets[choiceIndex] ?? entry.property.choices[choiceIndex] ?? ""; + entry.property.choices = entry.property.choices.filter((_, index2) => index2 !== choiceIndex); + entry.choiceTargets = entry.choiceTargets.filter((_, index2) => index2 !== choiceIndex); + persist({ + kind: "removeChoice", + target: targetFor(entry, propertyIndex), + index: choiceIndex, + value + }); + } + function addChoice(entry, propertyIndex) { + const index2 = entry.property.choices.length; + entry.property.choices = [...entry.property.choices, ""]; + entry.choiceTargets = [...entry.choiceTargets, ""]; + persist({ + kind: "addChoice", + target: targetFor(entry, propertyIndex), + index: index2, + value: "" + }); + } + function pasteChoices(entry, propertyIndex, index2, event2) { + const tokens = splitPastedChoices(event2.clipboardData?.getData("text") ?? ""); + if (tokens.length < 2) return; + event2.preventDefault(); + const previousValue = entry.choiceTargets[index2] ?? entry.property.choices[index2] ?? ""; + entry.property.choices = withChoicesPasted(entry.property.choices, index2, tokens); + entry.choiceTargets = withChoicesPasted(entry.choiceTargets, index2, tokens); + persist({ + kind: "replaceChoiceWithChoices", + target: targetFor(entry, propertyIndex), + index: index2, + previousValue, + values: tokens + }); + } + function setName(entry, index2, value) { + const target = targetFor(entry, index2); + entry.property.name = value; + entry.targetName = value; + persist({ kind: "setName", target, value }); + } + function setDescription(entry, index2, value) { + entry.property.description = value; + persist({ + kind: "setDescription", + target: targetFor(entry, index2), + value + }); + } + function setType(entry, index2, value) { + const type = value; + entry.property.type = type; + persist({ + kind: "setType", + target: targetFor(entry, index2), + value: type + }); + } + function setChoice(entry, propertyIndex, choiceIndex, value) { + const previousValue = entry.choiceTargets[choiceIndex] ?? entry.property.choices[choiceIndex] ?? ""; + entry.property.choices[choiceIndex] = value; + entry.choiceTargets[choiceIndex] = value; + persist({ + kind: "setChoice", + target: targetFor(entry, propertyIndex), + index: choiceIndex, + previousValue, + value + }); + } + var div = root_4(); + var node_1 = child(div); + { + var consequent = ($$anchor2) => { + var p = root2(); + append($$anchor2, p); + }; + if_block(node_1, ($$render) => { + if (get2(autoProperties).length === 0) $$render(consequent); + }); + } + var node_2 = sibling(node_1, 2); + each(node_2, 19, () => get2(autoProperties), (entry) => entry.id, ($$anchor2, entry, propertyIndex) => { + const property = user_derived(() => get2(entry).property); + var div_1 = root_3(); + var div_2 = child(div_1); + var input = child(div_2); + remove_input_defaults(input); + var select = sibling(input, 2); + each(select, 20, () => types, (t) => t, ($$anchor3, t) => { + var option = root_12(); + var text2 = child(option, true); + reset(option); + var option_value = {}; + template_effect(() => { + set_selected(option, (get2(property).type ?? "Single") === t); + set_text(text2, t); + if (option_value !== (option_value = t)) { + option.value = (option.__value = t) ?? ""; + } + }); + append($$anchor3, option); + }); + reset(select); + var button = sibling(select, 2); + var span = child(button); + action(span, ($$node, $$action_arg) => icon?.($$node, $$action_arg), () => "trash-2"); + reset(button); + reset(div_2); + var input_1 = sibling(div_2, 2); + remove_input_defaults(input_1); + var div_3 = sibling(input_1, 2); + var node_3 = sibling(child(div_3), 2); + each(node_3, 16, () => indexes(get2(property).choices), (i) => i, ($$anchor3, i) => { + var div_4 = root_22(); + var input_2 = child(div_4); + remove_input_defaults(input_2); + var button_1 = sibling(input_2, 2); + var span_1 = child(button_1); + action(span_1, ($$node, $$action_arg) => icon?.($$node, $$action_arg), () => "x"); + reset(button_1); + reset(div_4); + template_effect(() => set_value(input_2, get2(property).choices[i])); + delegated("input", input_2, (e) => get2(property).choices[i] = e.currentTarget.value); + delegated("change", input_2, (e) => setChoice(get2(entry), get2(propertyIndex), i, e.currentTarget.value)); + event("paste", input_2, (e) => pasteChoices(get2(entry), get2(propertyIndex), i, e)); + delegated("click", button_1, () => removeChoice(get2(entry), get2(propertyIndex), i)); + append($$anchor3, div_4); + }); + var button_2 = sibling(node_3, 2); + var span_2 = child(button_2); + action(span_2, ($$node, $$action_arg) => icon?.($$node, $$action_arg), () => "plus"); + next(); + reset(button_2); + reset(div_3); + reset(div_1); + template_effect(() => { + set_value(input, get2(property).name); + set_value(input_1, get2(property).description ?? ""); + }); + delegated("input", input, (e) => get2(property).name = e.currentTarget.value); + delegated("change", input, (e) => setName(get2(entry), get2(propertyIndex), e.currentTarget.value)); + delegated("change", select, (e) => setType(get2(entry), get2(propertyIndex), e.currentTarget.value)); + delegated("click", button, () => removeProperty(get2(entry), get2(propertyIndex))); + delegated("input", input_1, (e) => get2(property).description = e.currentTarget.value); + delegated("change", input_1, (e) => setDescription(get2(entry), get2(propertyIndex), e.currentTarget.value)); + delegated("click", button_2, () => addChoice(get2(entry), get2(propertyIndex))); + append($$anchor2, div_1); + }); + var div_5 = sibling(node_2, 2); + var button_3 = child(div_5); + reset(div_5); + reset(div); + delegated("click", button_3, addNewProperty); + append($$anchor, div); + pop(); +} +delegate(["input", "change", "click"]); + +// src/Modals/KanbanHelperSetting/KanbanHelperSettingSuggester.ts +var import_obsidian2 = require("obsidian"); +var KanbanHelperSettingSuggester = class extends import_obsidian2.AbstractInputSuggest { + constructor(app, inputEl, boards) { + super(app, inputEl); + this.inputEl = inputEl; + this.boards = boards; + this.onSelect((item) => this.acceptSuggestion(item)); + } + getSuggestions(inputStr) { + const inputLowerCase = inputStr.toLowerCase(); + return this.boards.filter((board) => board.basename.toLowerCase().includes(inputLowerCase)); + } + acceptSuggestion(item) { + this.setValue(item.basename); + this.inputEl.trigger("input"); + this.close(); + } + renderSuggestion(value, el) { + if (value) + el.setText(value.basename); + } }; -function areValidElements() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; +// src/logger/logManager.ts +var _LogManager = class _LogManager { + register(logger) { + _LogManager.loggers.push(logger); + return this; } - - return !args.some(function (element) { - return !(element && typeof element.getBoundingClientRect === 'function'); - }); -} - -function popperGenerator(generatorOptions) { - if (generatorOptions === void 0) { - generatorOptions = {}; + logError(message) { + _LogManager.loggers.forEach((logger) => logger.logError(message)); + throw new Error(); + } + logWarning(message) { + _LogManager.loggers.forEach((logger) => logger.logError(message)); + } + logMessage(message) { + _LogManager.loggers.forEach((logger) => logger.logMessage(message)); } - - var _generatorOptions = generatorOptions, - _generatorOptions$def = _generatorOptions.defaultModifiers, - defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, - _generatorOptions$def2 = _generatorOptions.defaultOptions, - defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; - return function createPopper(reference, popper, options) { - if (options === void 0) { - options = defaultOptions; - } - - var state = { - placement: 'bottom', - orderedModifiers: [], - options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), - modifiersData: {}, - elements: { - reference: reference, - popper: popper - }, - attributes: {}, - styles: {} - }; - var effectCleanupFns = []; - var isDestroyed = false; - var instance = { - state: state, - setOptions: function setOptions(setOptionsAction) { - var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction; - cleanupModifierEffects(); - state.options = Object.assign({}, defaultOptions, state.options, options); - state.scrollParents = { - reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [], - popper: listScrollParents(popper) - }; // Orders the modifiers based on their dependencies and `phase` - // properties - - var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers - - state.orderedModifiers = orderedModifiers.filter(function (m) { - return m.enabled; - }); - runModifierEffects(); - return instance.update(); - }, - // Sync update – it will always be executed, even if not necessary. This - // is useful for low frequency updates where sync behavior simplifies the - // logic. - // For high frequency updates (e.g. `resize` and `scroll` events), always - // prefer the async Popper#update method - forceUpdate: function forceUpdate() { - if (isDestroyed) { - return; - } - - var _state$elements = state.elements, - reference = _state$elements.reference, - popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements - // anymore - - if (!areValidElements(reference, popper)) { - return; - } // Store the reference and popper rects to be read by modifiers - - - state.rects = { - reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'), - popper: getLayoutRect(popper) - }; // Modifiers have the ability to reset the current update cycle. The - // most common use case for this is the `flip` modifier changing the - // placement, which then needs to re-run all the modifiers, because the - // logic was previously ran for the previous placement and is therefore - // stale/incorrect - - state.reset = false; - state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier - // is filled with the initial data specified by the modifier. This means - // it doesn't persist and is fresh on each update. - // To ensure persistent data, use `${name}#persistent` - - state.orderedModifiers.forEach(function (modifier) { - return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); - }); - - for (var index = 0; index < state.orderedModifiers.length; index++) { - if (state.reset === true) { - state.reset = false; - index = -1; - continue; - } - - var _state$orderedModifie = state.orderedModifiers[index], - fn = _state$orderedModifie.fn, - _state$orderedModifie2 = _state$orderedModifie.options, - _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, - name = _state$orderedModifie.name; - - if (typeof fn === 'function') { - state = fn({ - state: state, - options: _options, - name: name, - instance: instance - }) || state; - } - } - }, - // Async and optimistically optimized update – it will not be executed if - // not necessary (debounced to run at most once-per-tick) - update: debounce(function () { - return new Promise(function (resolve) { - instance.forceUpdate(); - resolve(state); - }); - }), - destroy: function destroy() { - cleanupModifierEffects(); - isDestroyed = true; - } - }; - - if (!areValidElements(reference, popper)) { - return instance; - } - - instance.setOptions(options).then(function (state) { - if (!isDestroyed && options.onFirstUpdate) { - options.onFirstUpdate(state); - } - }); // Modifiers have the ability to execute arbitrary code before the first - // update cycle runs. They will be executed in the same order as the update - // cycle. This is useful when a modifier adds some persistent data that - // other modifiers need to use, but the modifier is run after the dependent - // one. - - function runModifierEffects() { - state.orderedModifiers.forEach(function (_ref) { - var name = _ref.name, - _ref$options = _ref.options, - options = _ref$options === void 0 ? {} : _ref$options, - effect = _ref.effect; - - if (typeof effect === 'function') { - var cleanupFn = effect({ - state: state, - name: name, - instance: instance, - options: options - }); - - var noopFn = function noopFn() {}; - - effectCleanupFns.push(cleanupFn || noopFn); - } - }); - } - - function cleanupModifierEffects() { - effectCleanupFns.forEach(function (fn) { - return fn(); - }); - effectCleanupFns = []; - } - - return instance; - }; -} - -var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1]; -var createPopper = /*#__PURE__*/popperGenerator({ - defaultModifiers: defaultModifiers -}); // eslint-disable-next-line import/no-unused-modules - -// Sam stole all this from Liam's Periodic Notes Plugin: https://github.com/liamcain/obsidian-periodic-notes -const wrapAround = (value, size) => { - return ((value % size) + size) % size; }; -class Suggest { - constructor(owner, containerEl, scope) { - this.owner = owner; - this.containerEl = containerEl; - containerEl.on("click", ".suggestion-item", this.onSuggestionClick.bind(this)); - containerEl.on("mousemove", ".suggestion-item", this.onSuggestionMouseover.bind(this)); - scope.register([], "ArrowUp", (event) => { - if (!event.isComposing) { - this.setSelectedItem(this.selectedItem - 1, true); - return false; - } - }); - scope.register([], "ArrowDown", (event) => { - if (!event.isComposing) { - this.setSelectedItem(this.selectedItem + 1, true); - return false; - } - }); - scope.register([], "Enter", (event) => { - if (!event.isComposing) { - this.useSelectedItem(event); - return false; - } - }); +_LogManager.loggers = []; +var LogManager = _LogManager; +var log = new LogManager(); + +// src/Modals/KanbanHelperSetting/KanbanHelperSettingContent.svelte +var root3 = from_html(` `); +var root_13 = from_html(`
BoardProperty in linkPossible values
`); +var $$css3 = { + hash: "svelte-pptp52", + code: ".buttonContainer.svelte-pptp52 {display:flex;justify-content:center;margin-top:1rem;}button.svelte-pptp52 {margin-left:5px;margin-right:5px;font-size:15px;}" +}; +function KanbanHelperSettingContent($$anchor, $$props) { + push($$props, true); + append_styles($$anchor, $$css3); + let initialKanbanProperties = prop($$props, "kanbanProperties", 19, () => []); + const initialApp = untrack(() => $$props.app); + const initialBoards = untrack(() => $$props.boards); + let kanbanProperties = state(proxy(untrack(() => initialKanbanProperties().map((property) => ({ ...property }))))); + let suggestEl = state(void 0); + let suggester; + let inputValue = state(""); + let didInitialise = false; + user_effect(() => { + const el = get2(suggestEl); + if (!el || didInitialise) return; + didInitialise = true; + suggester = new KanbanHelperSettingSuggester(initialApp, el, initialBoards); + return () => { + suggester?.close(); + suggester = void 0; + }; + }); + function saveProperties() { + $$props.save(snapshot(get2(kanbanProperties))); + } + function addNewProperty() { + const board = initialBoards.find((board2) => board2.basename === get2(inputValue)); + if (!board) return; + const exists = !!get2(kanbanProperties).find((kp) => kp.boardName === board.basename); + if (exists) return; + set( + kanbanProperties, + [ + ...get2(kanbanProperties), + { property: "", boardName: board.basename } + ], + true + ); + saveProperties(); + } + function removeProperty(i) { + set(kanbanProperties, get2(kanbanProperties).filter((_, index2) => index2 !== i), true); + saveProperties(); + } + function getHeadingsInBoard(boardName) { + const file = initialBoards.find((board) => board.basename === boardName); + if (!file) { + log.logWarning(`file ${boardName} not found.`); + return "FILE NOT FOUND"; } - onSuggestionClick(event, el) { - event.preventDefault(); - const item = this.suggestions.indexOf(el); - this.setSelectedItem(item, false); - this.useSelectedItem(event); - } - onSuggestionMouseover(_event, el) { - const item = this.suggestions.indexOf(el); - this.setSelectedItem(item, false); - } - setSuggestions(values) { - this.containerEl.empty(); - const suggestionEls = []; - values.forEach((value) => { - const suggestionEl = this.containerEl.createDiv("suggestion-item"); - this.owner.renderSuggestion(value, suggestionEl); - suggestionEls.push(suggestionEl); - }); - this.values = values; - this.suggestions = suggestionEls; - this.setSelectedItem(0, false); - } - useSelectedItem(event) { - const currentValue = this.values[this.selectedItem]; - if (currentValue) { - this.owner.selectSuggestion(currentValue, event); + const headings = initialApp.metadataCache.getFileCache(file)?.headings; + if (!headings) return ""; + return headings.map((heading) => heading.heading).join(", "); + } + var div = root_13(); + var table = child(div); + var tbody = sibling(child(table)); + each(tbody, 23, () => get2(kanbanProperties), (kanbanProperty) => kanbanProperty.boardName, ($$anchor2, kanbanProperty, i) => { + var tr = root3(); + var td = child(tr); + var input = child(td); + reset(td); + var td_1 = sibling(td); + var text2 = child(td_1, true); + reset(td_1); + var td_2 = sibling(td_1); + var input_1 = child(td_2); + remove_input_defaults(input_1); + reset(td_2); + var td_3 = sibling(td_2); + var text_1 = child(td_3, true); + reset(td_3); + reset(tr); + template_effect( + ($0) => { + set_text(text2, get2(kanbanProperty).boardName); + set_text(text_1, $0); + }, + [() => getHeadingsInBoard(get2(kanbanProperty).boardName)] + ); + delegated("click", input, () => removeProperty(get2(i))); + delegated("change", input_1, saveProperties); + bind_value(input_1, () => get2(kanbanProperty).property, ($$value) => get2(kanbanProperty).property = $$value); + append($$anchor2, tr); + }); + reset(tbody); + reset(table); + var input_2 = sibling(table, 2); + remove_input_defaults(input_2); + bind_this(input_2, ($$value) => set(suggestEl, $$value), () => get2(suggestEl)); + var div_1 = sibling(input_2, 2); + var button = child(div_1); + reset(div_1); + reset(div); + bind_value(input_2, () => get2(inputValue), ($$value) => set(inputValue, $$value)); + delegated("click", button, addNewProperty); + append($$anchor, div); + pop(); +} +delegate(["click", "change"]); + +// src/Modals/shared/SingleValueTableEditorContent.svelte +var root4 = from_html(``); +var root_14 = from_html(`
Property
`); +var $$css4 = { + hash: "svelte-158j4ih", + code: ".buttonContainer.svelte-158j4ih {display:flex;justify-content:center;margin-top:1rem;}button.svelte-158j4ih {margin-left:5px;margin-right:5px;font-size:15px;}" +}; +function SingleValueTableEditorContent($$anchor, $$props) { + push($$props, true); + append_styles($$anchor, $$css4); + let initialProperties = prop($$props, "properties", 19, () => []); + let properties = state(proxy(untrack(() => [...initialProperties()]))); + let propertyIndexes = user_derived(() => get2(properties).map((_, i) => i)); + function saveProperties() { + $$props.save(snapshot(get2(properties))); + } + function addNewProperty() { + set(properties, [...get2(properties), ""], true); + saveProperties(); + } + function removeProperty(i) { + set(properties, get2(properties).filter((_, index2) => index2 !== i), true); + saveProperties(); + } + var div = root_14(); + var table = child(div); + var tbody = sibling(child(table)); + each(tbody, 20, () => get2(propertyIndexes), (i) => i, ($$anchor2, i) => { + var tr = root4(); + var td = child(tr); + var input = child(td); + reset(td); + var td_1 = sibling(td); + var input_1 = child(td_1); + remove_input_defaults(input_1); + reset(td_1); + reset(tr); + delegated("click", input, () => removeProperty(i)); + delegated("change", input_1, saveProperties); + bind_value(input_1, () => get2(properties)[i], ($$value) => get2(properties)[i] = $$value); + append($$anchor2, tr); + }); + reset(tbody); + reset(table); + var div_1 = sibling(table, 2); + var button = child(div_1); + reset(div_1); + reset(div); + delegated("click", button, addNewProperty); + append($$anchor, div); + pop(); +} +delegate(["click", "change"]); + +// src/svelteMount.ts +function mountSvelteComponent(component2, target, props) { + return mount( + component2, + { target, props } + ); +} +function unmountSvelteComponent(component2) { + if (!component2) return; + void unmount(component2); +} + +// src/Settings/metaEditSettingsTab.ts +function toggleHiddenEl(el, hidden) { + if (!el) return hidden; + el.classList.toggle("metaedit-hidden", !hidden); + return !hidden; +} +var MetaEditSettingsTab = class extends import_obsidian3.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.svelteElements = []; + this.plugin = plugin; + } + display() { + const { containerEl } = this; + this.destroySvelteElements(); + containerEl.empty(); + new import_obsidian3.Setting(containerEl).setName("MetaEdit Settings").setHeading(); + this.addProgressPropertiesSetting(containerEl); + this.addAutoPropertiesSetting(containerEl); + this.addEditMetaMenuSetting(containerEl); + this.addEditModeSetting(containerEl); + this.addKanbanHelperSetting(containerEl); + this.addUIElementsSetting(containerEl); + } + addProgressPropertiesSetting(containerEl) { + let hidden = true; + const setting = new import_obsidian3.Setting(containerEl).setName("Progress Properties").setDesc("Update properties automatically.").addToggle((toggle) => { + toggle.setTooltip("Toggle Progress Properties").setValue(this.plugin.settings.ProgressProperties.enabled).onChange(async (value) => { + if (value === this.plugin.settings.ProgressProperties.enabled) return; + this.plugin.settings.ProgressProperties.enabled = value; + this.plugin.toggleAutomators(); + await this.plugin.saveSettings(); + }); + }); + const div = setting.settingEl.createDiv({ cls: "metaedit-hidden" }); + setting.settingEl.classList.add("metaedit-setting-with-details"); + setting.addExtraButton((button) => button.onClick(() => hidden = toggleHiddenEl(div, hidden))); + const modal = mountSvelteComponent( + ProgressPropertiesModalContent, + div, + { + properties: this.plugin.settings.ProgressProperties.properties, + save: async (progressProperties) => { + this.plugin.settings.ProgressProperties.properties = progressProperties; + await this.plugin.saveSettings(); } + } + ); + this.svelteElements.push(modal); + } + addAutoPropertiesSetting(containerEl) { + let hidden = true; + const setting = new import_obsidian3.Setting(containerEl).setName("Auto Properties").setDesc("Quick switch for values you know the value of.").addToggle((toggle) => { + toggle.setTooltip("Toggle Auto Properties").setValue(this.plugin.settings.AutoProperties.enabled).onChange(async (value) => { + if (value === this.plugin.settings.AutoProperties.enabled) return; + this.plugin.settings.AutoProperties.enabled = value; + await this.plugin.saveSettings(); + }); + }); + const div = setting.settingEl.createDiv({ cls: "metaedit-hidden" }); + setting.settingEl.classList.add("metaedit-setting-with-details"); + setting.addExtraButton((b) => b.onClick(() => hidden = toggleHiddenEl(div, hidden))); + const modal = mountSvelteComponent( + AutoPropertiesModalContent, + div, + { + autoProperties: this.plugin.settings.AutoProperties.properties, + save: (operation) => this.saveAutoPropertiesOperation(operation) + } + ); + this.svelteElements.push(modal); + } + async saveAutoPropertiesOperation(operation) { + try { + await this.plugin.updateSettings(() => { + const previousAutoProperties = this.plugin.settings.AutoProperties.properties; + const nextAutoProperties = applyAutoPropertySettingsOperation(previousAutoProperties, operation); + if (nextAutoProperties === false) return false; + this.plugin.settings.AutoProperties.properties = nextAutoProperties; + return () => { + if (this.plugin.settings.AutoProperties.properties === nextAutoProperties) { + this.plugin.settings.AutoProperties.properties = previousAutoProperties; + } + }; + }); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + new import_obsidian3.Notice(`MetaEdit could not save the Auto Properties setting: ${reason}`); } - setSelectedItem(selectedIndex, scrollIntoView) { - const normalizedIndex = wrapAround(selectedIndex, this.suggestions.length); - const prevSelectedSuggestion = this.suggestions[this.selectedItem]; - const selectedSuggestion = this.suggestions[normalizedIndex]; - prevSelectedSuggestion === null || prevSelectedSuggestion === void 0 ? void 0 : prevSelectedSuggestion.removeClass("is-selected"); - selectedSuggestion === null || selectedSuggestion === void 0 ? void 0 : selectedSuggestion.addClass("is-selected"); - this.selectedItem = normalizedIndex; - if (scrollIntoView) { - selectedSuggestion.scrollIntoView(false); + } + addEditMetaMenuSetting(containerEl) { + let hidden = true; + const setting = new import_obsidian3.Setting(containerEl).setName("Edit Meta menu").setDesc("Control what the 'Edit Meta' menu lists. Enable it, then use the gear to hide specific properties by name or all of a note's file tags.").addToggle((toggle) => { + toggle.setTooltip("Toggle menu filtering").setValue(this.plugin.settings.IgnoredProperties.enabled).onChange(async (value) => { + if (value === this.plugin.settings.IgnoredProperties.enabled) return; + this.plugin.settings.IgnoredProperties.enabled = value; + await this.plugin.saveSettings(); + this.display(); + }); + }); + const div = this.plugin.settings.IgnoredProperties.enabled ? setting.settingEl.createDiv({ cls: "metaedit-hidden" }) : void 0; + if (div) setting.settingEl.classList.add("metaedit-setting-with-details"); + setting.addExtraButton((b) => b.onClick(() => hidden = toggleHiddenEl(div, hidden))); + if (div) { + new import_obsidian3.Setting(div).setName("Hide file tags").setDesc("Hide the note's #tags from the menu, leaving only frontmatter and inline fields. A frontmatter 'tags' property stays editable.").addToggle((toggle) => { + toggle.setTooltip("Toggle hiding file tags").setValue(this.plugin.settings.IgnoredProperties.hideFileTags).onChange(async (value) => { + if (value === this.plugin.settings.IgnoredProperties.hideFileTags) return; + this.plugin.settings.IgnoredProperties.hideFileTags = value; + await this.plugin.saveSettings(); + }); + }); + div.createEl("p", { text: "Hide specific properties by name:", cls: "metaedit-table-label" }); + const modal = mountSvelteComponent( + SingleValueTableEditorContent, + div, + { + properties: this.plugin.settings.IgnoredProperties.properties, + save: async (ignoredProperties) => { + this.plugin.settings.IgnoredProperties.properties = ignoredProperties; + await this.plugin.saveSettings(); + } } + ); + this.svelteElements.push(modal); } -} -class TextInputSuggest { - constructor(app, inputEl) { - this.app = app; - this.inputEl = inputEl; - this.scope = new obsidian.Scope(); - this.suggestEl = createDiv("suggestion-container"); - const suggestion = this.suggestEl.createDiv("suggestion"); - this.suggest = new Suggest(this, suggestion, this.scope); - this.scope.register([], "Escape", this.close.bind(this)); - this.inputEl.addEventListener("input", this.onInputChanged.bind(this)); - this.inputEl.addEventListener("focus", this.onInputChanged.bind(this)); - this.inputEl.addEventListener("blur", this.close.bind(this)); - this.suggestEl.on("mousedown", ".suggestion-container", (event) => { - event.preventDefault(); - }); - } - onInputChanged() { - const inputStr = this.inputEl.value; - const suggestions = this.getSuggestions(inputStr); - if (!suggestions) { - this.close(); - return; - } - if (suggestions.length > 0) { - this.suggest.setSuggestions(suggestions); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.open(this.app.dom.appContainerEl, this.inputEl); - } - else { - this.close(); - } - } - open(container, inputEl) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.app.keymap.pushScope(this.scope); - container.appendChild(this.suggestEl); - this.popper = createPopper(inputEl, this.suggestEl, { - placement: "bottom-start", - modifiers: [ - { - name: "sameWidth", - enabled: true, - fn: ({ state, instance }) => { - // Note: positioning needs to be calculated twice - - // first pass - positioning it according to the width of the popper - // second pass - position it with the width bound to the reference element - // we need to early exit to avoid an infinite loop - const targetWidth = `${state.rects.reference.width}px`; - if (state.styles.popper.width === targetWidth) { - return; - } - state.styles.popper.width = targetWidth; - instance.update(); - }, - phase: "beforeWrite", - requires: ["computeStyles"], - }, - ], - }); - } - close() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.app.keymap.popScope(this.scope); - this.suggest.setSuggestions([]); - this.popper.destroy(); - this.suggestEl.detach(); - } -} - -class KanbanHelperSettingSuggester extends TextInputSuggest { - constructor(app, inputEl, boards) { - super(app, inputEl); - this.app = app; - this.inputEl = inputEl; - this.boards = boards; - } - getSuggestions(inputStr) { - const inputLowerCase = inputStr.toLowerCase(); - return this.boards.map(board => { - if (board.basename.toLowerCase().contains(inputLowerCase)) - return board; - }); - } - selectSuggestion(item) { - this.inputEl.value = item.basename; - this.inputEl.trigger("input"); - this.close(); - } - renderSuggestion(value, el) { - if (value) - el.setText(value.basename); - } -} - -class LogManager { - register(logger) { - LogManager.loggers.push(logger); - return this; - } - logError(message) { - LogManager.loggers.forEach(logger => logger.logError(message)); - throw new Error(); - } - logWarning(message) { - LogManager.loggers.forEach(logger => logger.logError(message)); - } - logMessage(message) { - LogManager.loggers.forEach(logger => logger.logMessage(message)); - } -} -LogManager.loggers = []; -const log = new LogManager(); - -/* src/Modals/KanbanHelperSetting/KanbanHelperSettingContent.svelte generated by Svelte v3.59.2 */ - -function add_css$1(target) { - append_styles(target, "svelte-kqcr7b", ".buttonContainer.svelte-kqcr7b{display:flex;justify-content:center;margin-top:1rem}button.svelte-kqcr7b{margin-left:5px;margin-right:5px;font-size:15px}"); -} - -function get_each_context$1(ctx, list, i) { - const child_ctx = ctx.slice(); - child_ctx[15] = list[i]; - child_ctx[16] = list; - child_ctx[17] = i; - return child_ctx; -} - -// (55:8) {#each kanbanProperties as kanbanProperty, i} -function create_each_block$1(ctx) { - let tr; - let td0; - let input0; - let t0; - let td1; - let t1_value = /*kanbanProperty*/ ctx[15].boardName + ""; - let t1; - let t2; - let td2; - let input1; - let t3; - let td3; - let t4_value = /*getHeadingsInBoard*/ ctx[6](/*kanbanProperty*/ ctx[15].boardName) + ""; - let t4; - let t5; - let br; - let mounted; - let dispose; - - function click_handler() { - return /*click_handler*/ ctx[9](/*i*/ ctx[17]); - } - - function input1_input_handler() { - /*input1_input_handler*/ ctx[11].call(input1, /*each_value*/ ctx[16], /*i*/ ctx[17]); - } - - return { - c() { - tr = element("tr"); - td0 = element("td"); - input0 = element("input"); - t0 = space(); - td1 = element("td"); - t1 = text(t1_value); - t2 = space(); - td2 = element("td"); - input1 = element("input"); - t3 = space(); - td3 = element("td"); - t4 = text(t4_value); - t5 = space(); - br = element("br"); - attr(input0, "type", "button"); - input0.value = "❌"; - attr(input0, "class", "not-a-button"); - attr(input1, "type", "text"); - attr(input1, "placeholder", "Property name"); - }, - m(target, anchor) { - insert(target, tr, anchor); - append(tr, td0); - append(td0, input0); - append(tr, t0); - append(tr, td1); - append(td1, t1); - append(tr, t2); - append(tr, td2); - append(td2, input1); - set_input_value(input1, /*kanbanProperty*/ ctx[15].property); - append(tr, t3); - append(tr, td3); - append(td3, t4); - insert(target, t5, anchor); - insert(target, br, anchor); - - if (!mounted) { - dispose = [ - listen(input0, "click", click_handler), - listen(input1, "change", /*change_handler*/ ctx[10]), - listen(input1, "input", input1_input_handler) - ]; - - mounted = true; - } - }, - p(new_ctx, dirty) { - ctx = new_ctx; - if (dirty & /*kanbanProperties*/ 1 && t1_value !== (t1_value = /*kanbanProperty*/ ctx[15].boardName + "")) set_data(t1, t1_value); - - if (dirty & /*kanbanProperties*/ 1 && input1.value !== /*kanbanProperty*/ ctx[15].property) { - set_input_value(input1, /*kanbanProperty*/ ctx[15].property); - } - - if (dirty & /*kanbanProperties*/ 1 && t4_value !== (t4_value = /*getHeadingsInBoard*/ ctx[6](/*kanbanProperty*/ ctx[15].boardName) + "")) set_data(t4, t4_value); - }, - d(detaching) { - if (detaching) detach(tr); - if (detaching) detach(t5); - if (detaching) detach(br); - mounted = false; - run_all(dispose); - } - }; -} - -function create_fragment$2(ctx) { - let div1; - let table; - let thead; - let t6; - let t7; - let input; - let t8; - let div0; - let button; - let mounted; - let dispose; - let each_value = /*kanbanProperties*/ ctx[0]; - let each_blocks = []; - - for (let i = 0; i < each_value.length; i += 1) { - each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i)); - } - - return { - c() { - div1 = element("div"); - table = element("table"); - thead = element("thead"); - - thead.innerHTML = ` - Board - Property in link - Possible values`; - - t6 = space(); - - for (let i = 0; i < each_blocks.length; i += 1) { - each_blocks[i].c(); - } - - t7 = space(); - input = element("input"); - t8 = space(); - div0 = element("div"); - button = element("button"); - button.textContent = "Add"; - set_style(table, "width", "100%"); - attr(input, "type", "text"); - attr(button, "class", "mod-cta svelte-kqcr7b"); - attr(div0, "class", "buttonContainer svelte-kqcr7b"); - attr(div1, "class", "centerSettingContent"); - }, - m(target, anchor) { - insert(target, div1, anchor); - append(div1, table); - append(table, thead); - append(table, t6); - - for (let i = 0; i < each_blocks.length; i += 1) { - if (each_blocks[i]) { - each_blocks[i].m(table, null); - } - } - - append(div1, t7); - append(div1, input); - /*input_binding*/ ctx[12](input); - set_input_value(input, /*inputValue*/ ctx[3]); - append(div1, t8); - append(div1, div0); - append(div0, button); - - if (!mounted) { - dispose = [ - listen(input, "input", /*input_input_handler*/ ctx[13]), - listen(button, "click", /*addNewProperty*/ ctx[4]) - ]; - - mounted = true; - } - }, - p(ctx, [dirty]) { - if (dirty & /*getHeadingsInBoard, kanbanProperties, save, removeProperty*/ 99) { - each_value = /*kanbanProperties*/ ctx[0]; - let i; - - for (i = 0; i < each_value.length; i += 1) { - const child_ctx = get_each_context$1(ctx, each_value, i); - - if (each_blocks[i]) { - each_blocks[i].p(child_ctx, dirty); - } else { - each_blocks[i] = create_each_block$1(child_ctx); - each_blocks[i].c(); - each_blocks[i].m(table, null); - } - } - - for (; i < each_blocks.length; i += 1) { - each_blocks[i].d(1); - } - - each_blocks.length = each_value.length; - } - - if (dirty & /*inputValue*/ 8 && input.value !== /*inputValue*/ ctx[3]) { - set_input_value(input, /*inputValue*/ ctx[3]); - } - }, - i: noop, - o: noop, - d(detaching) { - if (detaching) detach(div1); - destroy_each(each_blocks, detaching); - /*input_binding*/ ctx[12](null); - mounted = false; - run_all(dispose); - } - }; -} - -function instance$2($$self, $$props, $$invalidate) { - let { save } = $$props; - let { kanbanProperties = [] } = $$props; - let { boards } = $$props; - let { app } = $$props; - let suggestEl; - let inputValue; - - onMount(() => { - new KanbanHelperSettingSuggester(app, suggestEl, boards); - }); - - function addNewProperty() { - const board = boards.find(board => board.basename === inputValue); - const exists = !!kanbanProperties.find(kp => kp.boardName === board.basename); - if (!board || exists) return; - kanbanProperties.push({ property: "", boardName: board.basename }); - $$invalidate(0, kanbanProperties); // Svelte - save(kanbanProperties); - } - - function removeProperty(i) { - kanbanProperties.splice(i, 1); - $$invalidate(0, kanbanProperties); // Svelte - save(kanbanProperties); - } - - function getHeadingsInBoard(boardName) { - const file = boards.find(board => board.basename === boardName); - - if (!file) { - log.logWarning(`file ${boardName} not found.`); - return "FILE NOT FOUND"; - } - - const headings = app.metadataCache.getFileCache(file).headings; - if (!headings) return ""; - return headings.map(heading => heading.heading).join(", "); - } - - const click_handler = i => removeProperty(i); - const change_handler = () => save(kanbanProperties); - - function input1_input_handler(each_value, i) { - each_value[i].property = this.value; - $$invalidate(0, kanbanProperties); - } - - function input_binding($$value) { - binding_callbacks[$$value ? 'unshift' : 'push'](() => { - suggestEl = $$value; - $$invalidate(2, suggestEl); - }); - } - - function input_input_handler() { - inputValue = this.value; - $$invalidate(3, inputValue); - } - - $$self.$$set = $$props => { - if ('save' in $$props) $$invalidate(1, save = $$props.save); - if ('kanbanProperties' in $$props) $$invalidate(0, kanbanProperties = $$props.kanbanProperties); - if ('boards' in $$props) $$invalidate(7, boards = $$props.boards); - if ('app' in $$props) $$invalidate(8, app = $$props.app); - }; - - return [ - kanbanProperties, - save, - suggestEl, - inputValue, - addNewProperty, - removeProperty, - getHeadingsInBoard, - boards, - app, - click_handler, - change_handler, - input1_input_handler, - input_binding, - input_input_handler - ]; -} - -class KanbanHelperSettingContent extends SvelteComponent { - constructor(options) { - super(); - - init( - this, - options, - instance$2, - create_fragment$2, - safe_not_equal, - { - save: 1, - kanbanProperties: 0, - boards: 7, - app: 8 - }, - add_css$1 - ); - } -} - -/* src/Modals/shared/SingleValueTableEditorContent.svelte generated by Svelte v3.59.2 */ - -function add_css(target) { - append_styles(target, "svelte-kqcr7b", ".buttonContainer.svelte-kqcr7b{display:flex;justify-content:center;margin-top:1rem}button.svelte-kqcr7b{margin-left:5px;margin-right:5px;font-size:15px}"); -} - -function get_each_context(ctx, list, i) { - const child_ctx = ctx.slice(); - child_ctx[7] = list[i]; - child_ctx[8] = list; - child_ctx[9] = i; - return child_ctx; -} - -// (23:8) {#each properties as property, i} -function create_each_block(ctx) { - let tr; - let td0; - let input0; - let t0; - let td1; - let input1; - let t1; - let mounted; - let dispose; - - function click_handler() { - return /*click_handler*/ ctx[4](/*i*/ ctx[9]); - } - - function input1_input_handler() { - /*input1_input_handler*/ ctx[6].call(input1, /*each_value*/ ctx[8], /*i*/ ctx[9]); - } - - return { - c() { - tr = element("tr"); - td0 = element("td"); - input0 = element("input"); - t0 = space(); - td1 = element("td"); - input1 = element("input"); - t1 = space(); - attr(input0, "type", "button"); - input0.value = "❌"; - attr(input0, "class", "not-a-button"); - set_style(input1, "width", "100%"); - attr(input1, "type", "text"); - attr(input1, "placeholder", "Property name"); - }, - m(target, anchor) { - insert(target, tr, anchor); - append(tr, td0); - append(td0, input0); - append(tr, t0); - append(tr, td1); - append(td1, input1); - set_input_value(input1, /*property*/ ctx[7]); - append(tr, t1); - - if (!mounted) { - dispose = [ - listen(input0, "click", click_handler), - listen(input1, "change", /*change_handler*/ ctx[5]), - listen(input1, "input", input1_input_handler) - ]; - - mounted = true; - } - }, - p(new_ctx, dirty) { - ctx = new_ctx; - - if (dirty & /*properties*/ 1 && input1.value !== /*property*/ ctx[7]) { - set_input_value(input1, /*property*/ ctx[7]); - } - }, - d(detaching) { - if (detaching) detach(tr); - mounted = false; - run_all(dispose); - } - }; -} - -function create_fragment$1(ctx) { - let div1; - let table; - let thead; - let t2; - let t3; - let div0; - let button; - let mounted; - let dispose; - let each_value = /*properties*/ ctx[0]; - let each_blocks = []; - - for (let i = 0; i < each_value.length; i += 1) { - each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i)); - } - - return { - c() { - div1 = element("div"); - table = element("table"); - thead = element("thead"); - - thead.innerHTML = ` - Property`; - - t2 = space(); - - for (let i = 0; i < each_blocks.length; i += 1) { - each_blocks[i].c(); - } - - t3 = space(); - div0 = element("div"); - button = element("button"); - button.textContent = "Add"; - set_style(table, "width", "100%"); - attr(button, "class", "mod-cta svelte-kqcr7b"); - attr(div0, "class", "buttonContainer svelte-kqcr7b"); - attr(div1, "class", "centerSettingContent"); - }, - m(target, anchor) { - insert(target, div1, anchor); - append(div1, table); - append(table, thead); - append(table, t2); - - for (let i = 0; i < each_blocks.length; i += 1) { - if (each_blocks[i]) { - each_blocks[i].m(table, null); - } - } - - append(div1, t3); - append(div1, div0); - append(div0, button); - - if (!mounted) { - dispose = listen(button, "click", /*addNewProperty*/ ctx[2]); - mounted = true; - } - }, - p(ctx, [dirty]) { - if (dirty & /*properties, save, removeProperty*/ 11) { - each_value = /*properties*/ ctx[0]; - let i; - - for (i = 0; i < each_value.length; i += 1) { - const child_ctx = get_each_context(ctx, each_value, i); - - if (each_blocks[i]) { - each_blocks[i].p(child_ctx, dirty); - } else { - each_blocks[i] = create_each_block(child_ctx); - each_blocks[i].c(); - each_blocks[i].m(table, null); - } - } - - for (; i < each_blocks.length; i += 1) { - each_blocks[i].d(1); - } - - each_blocks.length = each_value.length; - } - }, - i: noop, - o: noop, - d(detaching) { - if (detaching) detach(div1); - destroy_each(each_blocks, detaching); - mounted = false; - dispose(); - } - }; -} - -function instance$1($$self, $$props, $$invalidate) { - let { save } = $$props; - let { properties = [] } = $$props; - - function addNewProperty() { - properties.push(""); - $$invalidate(0, properties); // Svelte - save(properties); - } - - function removeProperty(i) { - properties.splice(i, 1); - $$invalidate(0, properties); // Svelte - save(properties); - } - - const click_handler = i => removeProperty(i); - const change_handler = async () => save(properties); - - function input1_input_handler(each_value, i) { - each_value[i] = this.value; - $$invalidate(0, properties); - } - - $$self.$$set = $$props => { - if ('save' in $$props) $$invalidate(1, save = $$props.save); - if ('properties' in $$props) $$invalidate(0, properties = $$props.properties); - }; - - return [ - properties, - save, - addNewProperty, - removeProperty, - click_handler, - change_handler, - input1_input_handler - ]; -} - -class SingleValueTableEditorContent extends SvelteComponent { - constructor(options) { - super(); - init(this, options, instance$1, create_fragment$1, safe_not_equal, { save: 1, properties: 0 }, add_css); - } -} - -function toggleHiddenEl(el, bShow) { - if (el && !bShow) { - el.style.display = "none"; - return true; - } - else if (el && bShow) { - el.style.display = "block"; - return false; - } - return bShow; -} -class MetaEditSettingsTab extends obsidian.PluginSettingTab { - constructor(app, plugin) { - super(app, plugin); - this.svelteElements = []; - this.plugin = plugin; - } - display() { - let { containerEl } = this; - containerEl.empty(); - containerEl.createEl('h2', { text: 'MetaEdit Settings' }); - this.addProgressPropertiesSetting(containerEl); - this.addAutoPropertiesSetting(containerEl); - this.addIgnorePropertiesSetting(containerEl); - this.addEditModeSetting(containerEl); - this.addKanbanHelperSetting(containerEl); - this.addUIElementsSetting(containerEl); - } - addProgressPropertiesSetting(containerEl) { - let modal, div, hidden = true; - const setting = new obsidian.Setting(containerEl) - .setName("Progress Properties") - .setDesc("Update properties automatically.") - .addToggle(toggle => { - toggle - .setTooltip("Toggle Progress Properties") - .setValue(this.plugin.settings.ProgressProperties.enabled) - .onChange(async (value) => { - if (value === this.plugin.settings.ProgressProperties.enabled) - return; - this.plugin.settings.ProgressProperties.enabled = value; - this.plugin.toggleAutomators(); - await this.plugin.saveSettings(); - }); - }) - .addExtraButton(button => button.onClick(() => hidden = toggleHiddenEl(div, hidden))); - div = setting.settingEl.createDiv(); - setting.settingEl.style.display = "block"; - div.style.display = "none"; - modal = new ProgressPropertiesModalContent({ - target: div, - props: { - properties: this.plugin.settings.ProgressProperties.properties, - save: async (progressProperties) => { - this.plugin.settings.ProgressProperties.properties = progressProperties; - await this.plugin.saveSettings(); - } - }, - }); - this.svelteElements.push(modal); - } - addAutoPropertiesSetting(containerEl) { - let modal, div, hidden = true; - const setting = new obsidian.Setting(containerEl) - .setName("Auto Properties") - .setDesc("Quick switch for values you know the value of.") - .addToggle(toggle => { - toggle - .setTooltip("Toggle Auto Properties") - .setValue(this.plugin.settings.AutoProperties.enabled) - .onChange(async (value) => { - if (value === this.plugin.settings.AutoProperties.enabled) - return; - this.plugin.settings.AutoProperties.enabled = value; - await this.plugin.saveSettings(); - }); - }) - .addExtraButton(b => b.onClick(() => hidden = toggleHiddenEl(div, hidden))); - div = setting.settingEl.createDiv(); - setting.settingEl.style.display = "block"; - div.style.display = "none"; - modal = new AutoPropertiesModalContent({ - target: div, - props: { - autoProperties: this.plugin.settings.AutoProperties.properties, - save: async (autoProperties) => { - this.plugin.settings.AutoProperties.properties = autoProperties; - await this.plugin.saveSettings(); - } - }, - }); - this.svelteElements.push(modal); - } - addIgnorePropertiesSetting(containerEl) { - let modal, div, hidden = true; - const setting = new obsidian.Setting(containerEl) - .setName("Ignore Properties") - .setDesc("Hide these properties from the menu.") - .addToggle(toggle => { - toggle - .setTooltip("Toggle Ignored Properties") - .setValue(this.plugin.settings.IgnoredProperties.enabled) - .onChange(async (value) => { - if (value === this.plugin.settings.IgnoredProperties.enabled) - return; - this.plugin.settings.IgnoredProperties.enabled = value; - await this.plugin.saveSettings(); - this.display(); - }); - }).addExtraButton(b => b.onClick(() => hidden = toggleHiddenEl(div, hidden))); - if (this.plugin.settings.IgnoredProperties.enabled) { - div = setting.settingEl.createDiv(); - setting.settingEl.style.display = "block"; - div.style.display = "none"; - modal = new SingleValueTableEditorContent({ - target: div, - props: { - properties: this.plugin.settings.IgnoredProperties.properties, - save: async (ignoredProperties) => { - this.plugin.settings.IgnoredProperties.properties = ignoredProperties; - await this.plugin.saveSettings(); - } - }, - }); - this.svelteElements.push(modal); - } - } - addEditModeSetting(containerEl) { - let modal, div, bDivToggle = true, extraButtonEl; - // For linebreaks - const df = new DocumentFragment(); - df.createEl('p', { text: "Single: property values are just one value. " }); - df.createEl('p', { text: "Multi: properties are arrays. " }); - df.createEl('p', { text: "Some Multi: all options are single, except those specified in the settings (click button)." }); - const setting = new obsidian.Setting(containerEl) - .setName("Edit Mode") - .setDesc(df) - .addDropdown(dropdown => { - dropdown - .addOption(EditMode.AllSingle, EditMode.AllSingle) - .addOption(EditMode.AllMulti, EditMode.AllMulti) - .addOption(EditMode.SomeMulti, EditMode.SomeMulti) - .setValue(this.plugin.settings.EditMode.mode) - .onChange(async (value) => { - switch (value) { - case EditMode.AllMulti: - this.plugin.settings.EditMode.mode = EditMode.AllMulti; - toggleHiddenEl(extraButtonEl, false); - bDivToggle = toggleHiddenEl(div, false); - break; - case EditMode.AllSingle: - this.plugin.settings.EditMode.mode = EditMode.AllSingle; - toggleHiddenEl(extraButtonEl, false); - bDivToggle = toggleHiddenEl(div, false); - break; - case EditMode.SomeMulti: - this.plugin.settings.EditMode.mode = EditMode.SomeMulti; - toggleHiddenEl(extraButtonEl, true); - break; - } - await this.plugin.saveSettings(); - }); - }) - .addExtraButton(b => { - extraButtonEl = b.extraSettingsEl; - b.setTooltip("Configure which properties are Multi."); - return b.onClick(() => bDivToggle = toggleHiddenEl(div, bDivToggle)); - }); - if (this.plugin.settings.EditMode.mode != EditMode.SomeMulti) { + } + addEditModeSetting(containerEl) { + let bDivToggle = true; + let extraButtonEl; + const df = new DocumentFragment(); + df.createEl("p", { text: "Single: property values are just one value. " }); + df.createEl("p", { text: "Multi: properties are arrays. " }); + df.createEl("p", { text: "Some Multi: all options are single, except those specified in the settings (click button)." }); + const setting = new import_obsidian3.Setting(containerEl).setName("Edit Mode").setDesc(df); + const div = setting.settingEl.createDiv({ cls: "metaedit-hidden" }); + setting.settingEl.classList.add("metaedit-setting-with-details"); + setting.addDropdown((dropdown) => { + dropdown.addOption("All Single" /* AllSingle */, "All Single" /* AllSingle */).addOption("All Multi" /* AllMulti */, "All Multi" /* AllMulti */).addOption("Some Multi" /* SomeMulti */, "Some Multi" /* SomeMulti */).setValue(this.plugin.settings.EditMode.mode).onChange(async (value) => { + switch (value) { + case "All Multi" /* AllMulti */: + this.plugin.settings.EditMode.mode = "All Multi" /* AllMulti */; toggleHiddenEl(extraButtonEl, false); + bDivToggle = toggleHiddenEl(div, false); + break; + case "All Single" /* AllSingle */: + this.plugin.settings.EditMode.mode = "All Single" /* AllSingle */; + toggleHiddenEl(extraButtonEl, false); + bDivToggle = toggleHiddenEl(div, false); + break; + case "Some Multi" /* SomeMulti */: + this.plugin.settings.EditMode.mode = "Some Multi" /* SomeMulti */; + toggleHiddenEl(extraButtonEl, true); + break; } - div = setting.settingEl.createDiv(); - setting.settingEl.style.display = "block"; - div.style.display = "none"; - modal = new SingleValueTableEditorContent({ - target: div, - props: { - properties: this.plugin.settings.EditMode.properties, - save: async (properties) => { - this.plugin.settings.EditMode.properties = properties; - await this.plugin.saveSettings(); - } - }, - }); - this.svelteElements.push(modal); + await this.plugin.saveSettings(); + }); + }).addExtraButton((b) => { + extraButtonEl = b.extraSettingsEl; + b.setTooltip("Configure which properties are Multi."); + return b.onClick(() => bDivToggle = toggleHiddenEl(div, bDivToggle)); + }); + if (this.plugin.settings.EditMode.mode != "Some Multi" /* SomeMulti */) { + toggleHiddenEl(extraButtonEl, false); } - hide() { - this.svelteElements.forEach(el => el.$destroy()); - return super.hide(); - } - addKanbanHelperSetting(containerEl) { - let modal, div, hidden = true; - const setting = new obsidian.Setting(containerEl) - .setName("Kanban Board Helper") - .setDesc("Update properties in links in kanban boards automatically when a card is moved to a new lane.") - .addToggle(toggle => { - toggle - .setTooltip("Toggle Kanban Helper") - .setValue(this.plugin.settings.KanbanHelper.enabled) - .onChange(async (value) => { - if (value === this.plugin.settings.KanbanHelper.enabled) - return; - this.plugin.settings.KanbanHelper.enabled = value; - this.plugin.toggleAutomators(); - await this.plugin.saveSettings(); - }); - }) - .addExtraButton(button => button.onClick(() => hidden = toggleHiddenEl(div, hidden))); - div = setting.settingEl.createDiv(); - setting.settingEl.style.display = "block"; - div.style.display = "none"; - modal = new KanbanHelperSettingContent({ - target: div, - props: { - kanbanProperties: this.plugin.settings.KanbanHelper.boards, - boards: this.plugin.getFilesWithProperty("kanban-plugin"), - app: this.app, - save: async (kanbanProperties) => { - this.plugin.settings.KanbanHelper.boards = kanbanProperties; - await this.plugin.saveSettings(); - } - }, - }); - this.svelteElements.push(modal); - } - addUIElementsSetting(containerEl) { - new obsidian.Setting(containerEl) - .setName("UI Elements") - .setDesc("Toggle UI elements: the 'Edit Meta' right-click menu option.") - .addToggle(toggle => { - toggle - .setTooltip("Toggle UI elements") - .setValue(this.plugin.settings.UIElements.enabled) - .onChange(async (value) => { - if (value === this.plugin.settings.UIElements.enabled) - return; - this.plugin.settings.UIElements.enabled = value; - value ? this.plugin.linkMenu.registerEvent() : this.plugin.linkMenu.unregisterEvent(); - await this.plugin.saveSettings(); - }); - }); - } -} + const modal = mountSvelteComponent( + SingleValueTableEditorContent, + div, + { + properties: this.plugin.settings.EditMode.properties, + save: async (properties) => { + this.plugin.settings.EditMode.properties = properties; + await this.plugin.saveSettings(); + } + } + ); + this.svelteElements.push(modal); + } + hide() { + this.destroySvelteElements(); + return super.hide(); + } + destroySvelteElements() { + this.svelteElements.forEach(unmountSvelteComponent); + this.svelteElements = []; + } + addKanbanHelperSetting(containerEl) { + let hidden = true; + const setting = new import_obsidian3.Setting(containerEl).setName("Kanban Board Helper").setDesc("Update properties in links in kanban boards automatically when a card is moved to a new lane.").addToggle((toggle) => { + toggle.setTooltip("Toggle Kanban Helper").setValue(this.plugin.settings.KanbanHelper.enabled).onChange(async (value) => { + if (value === this.plugin.settings.KanbanHelper.enabled) return; + this.plugin.settings.KanbanHelper.enabled = value; + this.plugin.toggleAutomators(); + await this.plugin.saveSettings(); + }); + }); + const div = setting.settingEl.createDiv({ cls: "metaedit-hidden" }); + setting.settingEl.classList.add("metaedit-setting-with-details"); + setting.addExtraButton((button) => button.onClick(() => hidden = toggleHiddenEl(div, hidden))); + const modal = mountSvelteComponent( + KanbanHelperSettingContent, + div, + { + kanbanProperties: this.plugin.settings.KanbanHelper.boards, + boards: this.plugin.getFilesWithProperty("kanban-plugin"), + app: this.app, + save: async (kanbanProperties) => { + this.plugin.settings.KanbanHelper.boards = kanbanProperties; + await this.plugin.saveSettings(); + } + } + ); + this.svelteElements.push(modal); + } + addUIElementsSetting(containerEl) { + new import_obsidian3.Setting(containerEl).setName("UI Elements").setDesc("Toggle UI elements: the 'Edit Meta' right-click menu option.").addToggle((toggle) => { + toggle.setTooltip("Toggle UI elements").setValue(this.plugin.settings.UIElements.enabled).onChange(async (value) => { + if (value === this.plugin.settings.UIElements.enabled) return; + this.plugin.settings.UIElements.enabled = value; + if (value) { + this.plugin.linkMenu.registerEvent(); + } else { + this.plugin.linkMenu.unregisterEvent(); + } + await this.plugin.saveSettings(); + }); + }); + } +}; -var MetaType; -(function (MetaType) { - MetaType[MetaType["YAML"] = 0] = "YAML"; - MetaType[MetaType["Dataview"] = 1] = "Dataview"; - MetaType[MetaType["Tag"] = 2] = "Tag"; - MetaType[MetaType["Option"] = 3] = "Option"; -})(MetaType || (MetaType = {})); +// src/Modals/metaEditSuggester.ts +var import_obsidian4 = require("obsidian"); -const ADD_FIRST_ELEMENT = "cmd:addfirst"; -const ADD_TO_BEGINNING = "cmd:beg"; -const ADD_TO_END = "cmd:end"; -const newDataView = "New Dataview field"; -const newYaml = "New YAML property"; -const MAIN_SUGGESTER_OPTIONS = [ - { key: newYaml, content: newYaml, type: MetaType.Option }, - { key: newDataView, content: newDataView, type: MetaType.Option } +// src/constants.ts +var newDataView = "New Dataview field"; +var newYaml = "New YAML property"; +var MAIN_SUGGESTER_OPTIONS = [ + { key: newYaml, content: newYaml, type: 3 /* Option */ }, + { key: newDataView, content: newDataView, type: 3 /* Option */ } ]; -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function createCommonjsModule(fn) { - var module = { exports: {} }; - return fn(module, module.exports), module.exports; -} - -function commonjsRequire (path) { - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); -} - -var utils = createCommonjsModule(function (module, exports) { -var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JAVASCRIPT_RESERVED_KEYWORD_SET = exports.setProp = exports.findUp = exports.isValidLocalPath = exports.hasDepInstalled = exports.getIncludePaths = exports.concat = exports.importAny = void 0; - - -async function importAny(...modules) { - try { - const mod = await modules.reduce((acc, moduleName) => acc.catch(() => Promise.resolve().then(() => __importStar(commonjsRequire(moduleName)))), Promise.reject()); - return mod; - } - catch (e) { - throw new Error(`Cannot find any of modules: ${modules}\n\n${e}`); - } -} -exports.importAny = importAny; -function concat(...arrs) { - return arrs.reduce((acc, a) => { - if (a) { - return acc.concat(a); - } - return acc; - }, []); -} -exports.concat = concat; -/** Paths used by preprocessors to resolve @imports */ -function getIncludePaths(fromFilename, base = []) { - if (fromFilename == null) - return []; - return [ - ...new Set([...base, 'node_modules', process.cwd(), (0, path_1__default["default"].dirname)(fromFilename)]), - ]; -} -exports.getIncludePaths = getIncludePaths; -const depCheckCache = {}; -/** - * Checks if a package is installed. - * - * @export - * @param {string} dep - * @returns boolean - */ -async function hasDepInstalled(dep) { - if (depCheckCache[dep] != null) { - return depCheckCache[dep]; - } - let result = false; - try { - await Promise.resolve().then(() => __importStar(commonjsRequire(dep))); - result = true; - } - catch (e) { - result = false; - } - return (depCheckCache[dep] = result); -} -exports.hasDepInstalled = hasDepInstalled; -function isValidLocalPath(path) { - return path.startsWith('.'); -} -exports.isValidLocalPath = isValidLocalPath; -// finds a existing path up the tree -function findUp({ what, from }) { - const { root, dir } = (0, path_1__default["default"].parse)(from); - let cur = dir; - try { - while (cur !== root) { - const possiblePath = (0, path_1__default["default"].join)(cur, what); - if ((0, fs_1__default["default"].existsSync)(possiblePath)) { - return possiblePath; - } - cur = (0, path_1__default["default"].dirname)(cur); - } - } - catch (e) { - console.error(e); - } - return null; -} -exports.findUp = findUp; -// set deep property in object -function setProp(obj, keyList, value) { - let i = 0; - for (; i < keyList.length - 1; i++) { - const key = keyList[i]; - if (typeof obj[key] !== 'object') { - obj[key] = {}; - } - obj = obj[key]; - } - obj[keyList[i]] = value; -} -exports.setProp = setProp; -exports.JAVASCRIPT_RESERVED_KEYWORD_SET = new Set([ - 'arguments', - 'await', - 'break', - 'case', - 'catch', - 'class', - 'const', - 'continue', - 'debugger', - 'default', - 'delete', - 'do', - 'else', - 'enum', - 'eval', - 'export', - 'extends', - 'false', - 'finally', - 'for', - 'function', - 'if', - 'implements', - 'import', - 'in', - 'instanceof', - 'interface', - 'let', - 'new', - 'null', - 'package', - 'private', - 'protected', - 'public', - 'return', - 'static', - 'super', - 'switch', - 'this', - 'throw', - 'true', - 'try', - 'typeof', - 'var', - 'void', - 'while', - 'with', - 'yield', +// src/Modals/GenericPrompt/valueSuggest.ts +var ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; +var ISO_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/; +var NATIVE_BUILT_IN_PROPERTY_NAMES = Object.freeze([ + "aliases", + "cssclass", + "cssclasses", + "publish", + "tags" ]); -}); - -class MetaEditSuggester extends obsidian.FuzzySuggestModal { - constructor(app, plugin, data, file, controller) { - super(app); - this.file = file; - this.app = app; - this.plugin = plugin; - this.data = this.removeIgnored(data); - this.controller = controller; - this.options = MAIN_SUGGESTER_OPTIONS; - this.setSuggestValues(); - this.setInstructions([ - { command: "❌", purpose: "Delete property" }, - { command: "🔃", purpose: "Transform to YAML/Dataview" } - ]); +var MAX_RENDERED_SUGGESTIONS = 100; +function getValueSuggestions(app, key2, type, tagMode) { + if (!key2) return []; + try { + if (type === 2 /* Tag */) { + return tagMode === "leaf" ? rankByCount(collectTagLeafCounts(app)) : rankByCount(collectTagFullCounts(app)); } - renderSuggestion(item, el) { - super.renderSuggestion(item, el); - if (Object.values(this.options).find(v => v === item.item)) { - el.style.fontWeight = "bold"; - } - else { - this.createButton(el, "❌", this.deleteItem(item)); - this.createButton(el, "🔃", this.transformProperty(item)); - } + if (type === 0 /* YAML */) { + return rankByCount(collectFrontmatterValueCounts(app, key2)); } - getItemText(item) { - return item.key; + return []; + } catch { + return []; + } +} +function getDateInputType(app, key2, currentValue, type) { + if (type !== 0 /* YAML */ || !key2) return null; + let obsidianType; + try { + obsidianType = readObsidianType(app, key2); + } catch { + return null; + } + if (obsidianType !== "date" && obsidianType !== "datetime") return null; + const value = currentValue === null || currentValue === void 0 ? "" : String(currentValue).trim(); + if (value === "") return obsidianType; + if (obsidianType === "date" && ISO_DATE.test(value)) return "date"; + if (obsidianType === "datetime" && ISO_DATETIME.test(value)) return "datetime"; + return null; +} +function getKnownPropertyNames(app) { + const names = /* @__PURE__ */ new Set(); + for (const name of NATIVE_BUILT_IN_PROPERTY_NAMES) names.add(name); + try { + const all = getMetadataTypeManager(app)?.getAllProperties?.(); + if (!all) return [...names]; + for (const [key2, info] of Object.entries(all)) { + addPropertyName(names, key2); + addPropertyName(names, info?.name); } - getItems() { - return utils.concat(this.options, this.data); - } - async onChooseItem(item, evt) { - if (item.content === newYaml) { - const newProperty = await this.controller.createNewProperty(this.suggestValues); - if (!newProperty) - return null; - const { propName, propValue } = newProperty; - await this.controller.addYamlProp(propName, propValue, this.file); - return; - } - if (item.content === newDataView) { - const newProperty = await this.controller.createNewProperty(this.suggestValues); - if (!newProperty) - return null; - const { propName, propValue } = newProperty; - await this.controller.addDataviewField(propName, propValue, this.file); - return; - } - await this.controller.editMetaElement(item, this.data, this.file); - } - deleteItem(item) { - return async (evt) => { - evt.stopPropagation(); - await this.controller.deleteProperty(item.item, this.file); - this.close(); - }; - } - transformProperty(item) { - return async (evt) => { - evt.stopPropagation(); - const { item: property } = item; - if (property.type === MetaType.YAML) { - await this.toDataview(property); - } - else { - await this.toYaml(property); - } - this.close(); - }; - } - async toYaml(property) { - await this.controller.deleteProperty(property, this.file); - await this.controller.addYamlProp(property.key, property.content, this.file); - } - async toDataview(property) { - await this.controller.deleteProperty(property, this.file); - await this.controller.addDataviewField(property.key, property.content, this.file); - } - createButton(el, content, callback) { - const itemButton = el.createEl("button"); - itemButton.textContent = content; - itemButton.classList.add("not-a-button"); - itemButton.style.float = "right"; - itemButton.style.marginRight = "4px"; - itemButton.addEventListener("click", callback); - } - removeIgnored(data) { - const ignored = this.plugin.settings.IgnoredProperties.properties; - let purged = []; - for (let item in data) { - if (!ignored.contains(data[item].key)) - purged.push(data[item]); - } - return purged; - } - setSuggestValues() { - const autoProps = this.plugin.settings.AutoProperties.properties; - this.suggestValues = autoProps.reduce((arr, val) => { - if (!this.data.find(prop => val.name === prop.key || val.name.startsWith('#'))) { - arr.push(val.name); - } - return arr; - }, []); + } catch { + return [...names]; + } + return [...names]; +} +function filterSuggestions(items, inputStr) { + const query = inputStr.toLowerCase(); + const filtered = items.filter((item) => item.toLowerCase().includes(query)); + if (filtered.length === 0) return []; + if (filtered.length === 1 && filtered[0] === inputStr) return []; + return filtered.slice(0, MAX_RENDERED_SUGGESTIONS); +} +function collectTagLeafCounts(app) { + const counts = /* @__PURE__ */ new Map(); + for (const [tag2, count] of Object.entries(readVaultTags(app))) { + const leaf = tag2.replace(/^#/, "").split("/").pop()?.trim(); + if (!leaf) continue; + counts.set(leaf, (counts.get(leaf) ?? 0) + (count ?? 1)); + } + return counts; +} +function collectTagFullCounts(app) { + const counts = /* @__PURE__ */ new Map(); + for (const [tag2, count] of Object.entries(readVaultTags(app))) { + const full = tag2.replace(/^#/, "").trim(); + if (!full) continue; + counts.set(full, (counts.get(full) ?? 0) + (count ?? 1)); + } + return counts; +} +function readVaultTags(app) { + const metadataCache = app.metadataCache; + return metadataCache.getTags?.() ?? {}; +} +function collectFrontmatterValueCounts(app, key2) { + const counts = /* @__PURE__ */ new Map(); + for (const file of app.vault.getMarkdownFiles()) { + const frontmatter = app.metadataCache.getFileCache(file)?.frontmatter; + if (!frontmatter || !Object.prototype.hasOwnProperty.call(frontmatter, key2)) continue; + for (const value of flattenValues(frontmatter[key2])) { + counts.set(value, (counts.get(value) ?? 0) + 1); } + } + return counts; +} +function flattenValues(raw) { + const values = Array.isArray(raw) ? raw : [raw]; + const out = []; + for (const value of values) { + if (value === null || value === void 0) continue; + if (typeof value === "object") continue; + const text2 = String(value).trim(); + if (text2) out.push(text2); + } + return out; +} +function rankByCount(counts) { + return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([value]) => value); +} +function readObsidianType(app, key2) { + const typeManager = getMetadataTypeManager(app); + if (!typeManager) return null; + const assigned = typeManager.getAssignedWidget?.(key2); + if (typeof assigned === "string") return assigned; + const registered = typeManager.getAllProperties?.()?.[key2]?.widget; + if (typeof registered === "string") return registered; + const inferred = typeManager.getTypeInfo?.(key2)?.expected?.type; + return typeof inferred === "string" ? inferred : null; +} +function addPropertyName(names, value) { + if (typeof value !== "string") return; + const trimmed = value.trim(); + if (trimmed) names.add(trimmed); +} +function getMetadataTypeManager(app) { + return app.metadataTypeManager ?? null; } -class MetaEditParser { - constructor(app) { - this.app = app; - } - async getTagsForFile(file) { - const cache = this.app.metadataCache.getFileCache(file); - if (!cache) - return []; - const tags = cache.tags; - if (!tags) - return []; - let mTags = []; - tags.forEach(tag => mTags.push({ key: tag.tag, content: tag.tag, type: MetaType.Tag })); - return mTags; - } - async parseFrontmatter(file) { - const fileCache = this.app.metadataCache.getFileCache(file); - const frontmatter = fileCache === null || fileCache === void 0 ? void 0 : fileCache.frontmatter; - if (!frontmatter) - return []; - //@ts-ignore - this is part of the new Obsidian API as of v1.4.1 - const { start, end } = fileCache === null || fileCache === void 0 ? void 0 : fileCache.frontmatterPosition; - const filecontent = await this.app.vault.cachedRead(file); - const yamlContent = filecontent.split("\n").slice(start.line, end.line).join("\n"); - const parsedYaml = obsidian.parseYaml(yamlContent); - let metaYaml = []; - for (const key in parsedYaml) { - metaYaml.push({ key, content: parsedYaml[key], type: MetaType.YAML }); - } - return metaYaml; - } - async parseInlineFields(file) { - const content = await this.app.vault.cachedRead(file); - const regex = /[\[\(]?([^\n\r\(\[]*)::[ ]*([^\)\]\n\r]*)[\]\)]?/g; - const properties = []; - let match; - while ((match = regex.exec(content)) !== null) { - const key = match[1].trim(); - const value = match[2].trim(); - properties.push({ key, content: value, type: MetaType.Dataview }); - } - return properties; - } +// src/Modals/GenericPrompt/promptValueContext.ts +var pending2 = null; +function setPendingValueContext(context) { + pending2 = context; +} +function consumePendingValueContext() { + const context = pending2; + pending2 = null; + return context; } -class GenericTextSuggester extends TextInputSuggest { - constructor(app, inputEl, items) { - super(app, inputEl); - this.app = app; - this.inputEl = inputEl; - this.items = items; +// src/Modals/menuFilter.ts +function filterMenuItems(data, opts) { + if (!opts.enabled) return [...data]; + const ignored = new Set(opts.ignoredProperties); + return data.filter((item) => { + if (ignored.has(item.key)) return false; + if (opts.hideFileTags && item.type === 2 /* Tag */) return false; + return true; + }); +} +function canStructureEditProperty(property) { + if (property.type === 2 /* Tag */) return false; + return !property.isNested && !property.isVirtual; +} + +// src/yamlPath.ts +var YamlPathError = class extends Error { + constructor(message) { + super(message); + this.name = "YamlPathError"; + } +}; +function isReservedFrontmatterKey(key2) { + return key2 === "__proto__" || key2 === "constructor" || key2 === "prototype"; +} +function parseYamlPath(path) { + if (Array.isArray(path)) return validateYamlPath(path); + if (typeof path !== "string") throw new YamlPathError("YAML path must be a string or path segment array."); + const trimmed = path.trim(); + if (!trimmed) throw new YamlPathError("YAML path cannot be empty."); + const segments = []; + for (const part of trimmed.split(".")) { + if (!part) throw new YamlPathError(`Invalid YAML path '${path}'. Empty path segments are not supported.`); + readPathPart(part, path, segments); + } + return validateYamlPath(segments); +} +function formatYamlPath(path) { + const validated = validateYamlPath(path); + return validated.reduce((label, segment) => { + if (typeof segment === "number") return `${label}[${segment}]`; + return label ? `${label}.${segment}` : segment; + }, ""); +} +function getYamlPath(root7, path) { + const resolvedPath = parseYamlPath(path); + let current = root7; + for (const segment of resolvedPath) { + current = readYamlPathSegment(current, segment, formatYamlPath(resolvedPath)); + } + return current; +} +function setYamlPath(root7, path, value, options = {}) { + const resolvedPath = parseYamlPath(path); + for (const segment of resolvedPath) { + if (typeof segment === "string" && isReservedFrontmatterKey(segment)) { + throw new YamlPathError( + `Cannot write YAML path '${formatYamlPath(resolvedPath)}': '${segment}' is a reserved property name.` + ); } - getSuggestions(inputStr) { - const inputLowerCase = inputStr.toLowerCase(); - const filtered = this.items.filter(item => { - if (item.toLowerCase().contains(inputLowerCase)) - return item; - }); - if (!filtered) - this.close(); - if ((filtered === null || filtered === void 0 ? void 0 : filtered.length) === 1) - return [...filtered, inputStr]; - if ((filtered === null || filtered === void 0 ? void 0 : filtered.length) > 1) - return filtered; + } + let current = root7; + for (let idx = 0; idx < resolvedPath.length; idx++) { + const segment = resolvedPath[idx]; + const isLeaf = idx === resolvedPath.length - 1; + const location = formatYamlPath(resolvedPath.slice(0, idx + 1)); + if (typeof segment === "string") { + if (!isPlainYamlObject(current)) { + throw new YamlPathError(`Cannot write YAML path '${formatYamlPath(resolvedPath)}': '${location}' is not an object.`); + } + if (isLeaf) { + validateLeafWrite(current, segment, resolvedPath, options); + current[segment] = value; + return; + } + if (!Object.prototype.hasOwnProperty.call(current, segment)) { + current[segment] = createMissingParent(options, resolvedPath[idx + 1], location); + } + current = current[segment]; + continue; } - selectSuggestion(item) { - this.inputEl.value = item; - this.inputEl.trigger("input"); + if (!Array.isArray(current)) { + throw new YamlPathError(`Cannot write YAML path '${formatYamlPath(resolvedPath)}': '${location}' is not an array.`); + } + if (!arrayIndexExists(current, segment)) { + throw new YamlPathError(`Cannot write YAML path '${formatYamlPath(resolvedPath)}': array index ${segment} is out of range.`); + } + if (isLeaf) { + validateLeafWrite(current, segment, resolvedPath, options); + current[segment] = value; + return; + } + current = current[segment]; + } +} +function isPlainYamlObject(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + return Object.prototype.toString.call(value) === "[object Object]"; +} +function isYamlScalarLeaf(value) { + return !isPlainYamlObject(value) && !Array.isArray(value); +} +function isYamlParentContainerValue(value) { + if (isPlainYamlObject(value)) return true; + if (!Array.isArray(value)) return false; + return value.some((item) => isPlainYamlObject(item) || Array.isArray(item)); +} +function readPathPart(part, originalPath, segments) { + const keyMatch = part.match(/^([^\[\]]+)/); + if (!keyMatch) throw new YamlPathError(`Invalid YAML path '${originalPath}'. Bracket paths must follow a property name.`); + segments.push(keyMatch[1]); + let rest = part.substring(keyMatch[1].length); + while (rest.length > 0) { + const indexMatch = rest.match(/^\[(\d+)\]/); + if (!indexMatch) throw new YamlPathError(`Invalid YAML path '${originalPath}'. Only numeric array indexes are supported.`); + segments.push(Number(indexMatch[1])); + rest = rest.substring(indexMatch[0].length); + } +} +function validateYamlPath(path) { + if (path.length === 0) throw new YamlPathError("YAML path cannot be empty."); + return path.map((segment) => { + if (typeof segment === "string") { + if (!segment) throw new YamlPathError("YAML path string segments cannot be empty."); + return segment; + } + if (!Number.isInteger(segment) || segment < 0) { + throw new YamlPathError(`YAML path array index '${segment}' must be a non-negative integer.`); + } + return segment; + }); +} +function readYamlPathSegment(current, segment, pathLabel) { + if (typeof segment === "string") { + if (!isPlainYamlObject(current) || !Object.prototype.hasOwnProperty.call(current, segment)) { + throw new YamlPathError(`YAML path '${pathLabel}' does not exist.`); + } + return current[segment]; + } + if (!Array.isArray(current) || !arrayIndexExists(current, segment)) { + throw new YamlPathError(`YAML path '${pathLabel}' does not exist.`); + } + return current[segment]; +} +function createMissingParent(options, nextSegment, location) { + if (!options.createParents) { + throw new YamlPathError(`Cannot write YAML path: '${location}' does not exist.`); + } + if (typeof nextSegment === "number") { + throw new YamlPathError(`Cannot create array parent at '${location}'. Array creation is not supported.`); + } + return {}; +} +function arrayIndexExists(array, index2) { + return index2 >= 0 && index2 < array.length && Object.prototype.hasOwnProperty.call(array, index2); +} +function validateLeafWrite(current, segment, path, options) { + const exists = typeof segment === "number" ? arrayIndexExists(current, segment) : Object.prototype.hasOwnProperty.call(current, segment); + const label = formatYamlPath(path); + if (!exists && options.createLeaf === false) { + throw new YamlPathError(`Cannot write YAML path '${label}': path does not exist.`); + } + const currentValue = typeof segment === "number" ? current[segment] : current[segment]; + if (exists && options.validateExpectedValue && !yamlValuesEqual(currentValue, options.expectedValue)) { + throw new YamlPathError(`Cannot write YAML path '${label}': current value changed before update.`); + } +} +function yamlValuesEqual(left, right) { + if (left instanceof Date && right instanceof Date) return left.getTime() === right.getTime(); + return Object.is(left, right); +} + +// src/Modals/metaEditSuggester.ts +var DELETE_PROPERTY_ICON = "trash-2"; +var TRANSFORM_PROPERTY_ICON = "replace"; +var DELETE_PROPERTY_TOOLTIP = "Delete property"; +var TRANSFORM_PROPERTY_TOOLTIP = "Transform to YAML \u21C4 Dataview"; +var MetaEditSuggester = class _MetaEditSuggester extends import_obsidian4.FuzzySuggestModal { + constructor(app, plugin, data, file, controller) { + super(app); + this.file = file; + this.app = app; + this.plugin = plugin; + this.fileKeys = new Set(data.map((prop2) => prop2.key)); + const ignored = plugin.settings.IgnoredProperties; + this.data = filterMenuItems(data, { + enabled: ignored.enabled, + ignoredProperties: ignored.properties, + hideFileTags: ignored.hideFileTags + }).filter((item) => !_MetaEditSuggester.isYamlParentContainer(item)); + this.controller = controller; + this.options = MAIN_SUGGESTER_OPTIONS; + this.setSuggestValues(); + this.setInstructions([ + { command: "#tag", purpose: "rename in this note \xB7 vault-wide: Tag pane" } + ]); + } + renderSuggestion(item, el) { + super.renderSuggestion(item, el); + if (Object.values(this.options).find((v) => v === item.item)) { + el.classList.add("metaedit-suggester-command"); + } else { + if (_MetaEditSuggester.canStructureEdit(item.item)) { + this.createButton(el, DELETE_PROPERTY_ICON, DELETE_PROPERTY_TOOLTIP, this.deleteItem(item)); + this.createButton(el, TRANSFORM_PROPERTY_ICON, TRANSFORM_PROPERTY_TOOLTIP, this.transformProperty(item)); + } + } + } + getItemText(item) { + if (item.type === 2 /* Tag */ && item.position) { + const sameKey = this.data.filter((d) => d.type === 2 /* Tag */ && d.key === item.key && d.position).sort((a, b) => a.position.start - b.position.start); + if (sameKey.length > 1) { + const ordinal = sameKey.findIndex((d) => d.position.start === item.position.start) + 1; + const line = item.position.line !== void 0 ? `line ${item.position.line + 1}, ` : ""; + return `${item.key} (${line}${ordinal}/${sameKey.length})`; + } + } + return item.key; + } + getItems() { + return [...this.options, ...this.data]; + } + async onChooseItem(item, _evt) { + if (item.content === newYaml) { + await this.controller.createNewYamlPropertyFluid(this.file, this.suggestValues, this.fileKeys); + return; + } + if (item.content === newDataView) { + const newProperty = await this.controller.createNewProperty(this.suggestValues); + if (!newProperty) return null; + const { propName, propValue } = newProperty; + await this.controller.appendDataviewField(propName, propValue, this.file); + return; + } + if (_MetaEditSuggester.isYamlParentContainer(item)) return; + setPendingValueContext({ app: this.app, key: item.key, type: item.type }); + try { + await this.controller.editMetaElement(item, this.data, this.file); + } finally { + setPendingValueContext(null); + } + } + deleteItem(item) { + return async (evt) => { + evt.stopPropagation(); + try { + await this.controller.deleteProperty(item.item, this.file); + } finally { this.close(); + } + }; + } + transformProperty(item) { + return async (evt) => { + evt.stopPropagation(); + const { item: property } = item; + if (!_MetaEditSuggester.canStructureEdit(property)) return; + if (property.type !== 0 /* YAML */ && isReservedFrontmatterKey(property.key)) { + new import_obsidian4.Notice(`MetaEdit: "${property.key}" is a reserved property name and can't be a YAML property.`); + this.close(); + return; + } + try { + if (property.type === 0 /* YAML */) { + await this.toDataview(property); + } else { + await this.toYaml(property); + } + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + new import_obsidian4.Notice(`MetaEdit could not transform '${property.key}': ${reason}. It may have been removed - reopen the note to check.`); + } finally { + this.close(); + } + }; + } + async toYaml(property) { + await this.controller.deleteProperty(property, this.file); + await this.controller.addYamlProp(property.key, property.content, this.file); + } + async toDataview(property) { + await this.controller.deleteProperty(property, this.file); + await this.controller.appendDataviewField(property.key, property.content, this.file); + } + createButton(el, iconName, tooltip, callback) { + const itemButton = el.createEl("button"); + itemButton.type = "button"; + itemButton.classList.add("clickable-icon", "metaedit-suggester-action-button"); + itemButton.setAttribute("aria-label", tooltip); + (0, import_obsidian4.setIcon)(itemButton, iconName); + (0, import_obsidian4.setTooltip)(itemButton, tooltip); + itemButton.addEventListener("click", callback); + } + static canStructureEdit(property) { + return canStructureEditProperty(property); + } + static isYamlParentContainer(property) { + if (property.type !== 0 /* YAML */ || property.isVirtual) return false; + return isYamlParentContainerValue(property.content); + } + setSuggestValues() { + const existing = this.fileKeys; + const names = /* @__PURE__ */ new Set(); + for (const autoProp of this.plugin.settings.AutoProperties.properties) { + if (!autoProp.name.startsWith("#")) names.add(autoProp.name); } - renderSuggestion(value, el) { - if (value) - el.setText(value); + for (const name of getKnownPropertyNames(this.app)) names.add(name); + this.suggestValues = [...names].filter((name) => !existing.has(name)); + } +}; + +// src/parser.ts +var import_obsidian5 = require("obsidian"); +var INLINE_FIELD_WRAPPERS = Object.freeze({ "[": "]", "(": ")" }); +var FULL_LINE_PREFIX = /^\s*(?:>\s+)*(?:[-*+]\s+|\d+[.)]\s+)?/; +var CODE_FENCE = /^\s{0,3}(`{3,}|~{3,})/; +function matchFenceLine(line) { + const match = line.match(CODE_FENCE); + if (!match) return null; + const run3 = match[1]; + return { char: run3[0], len: run3.length, bare: line.slice(match[0].length).trim() === "" }; +} +function nextFenceState(openFence, line) { + const fence = matchFenceLine(line); + if (!fence) return { open: openFence, boundary: null }; + if (openFence === null) return { open: { char: fence.char, len: fence.len }, boundary: "open" }; + if (fence.char === openFence.char && fence.len >= openFence.len && fence.bare) { + return { open: null, boundary: "close" }; + } + return { open: openFence, boundary: null }; +} +var MetaEditParser = class { + constructor(app) { + this.app = app; + } + async getTagsForFile(file) { + const cache = this.app.metadataCache.getFileCache(file); + if (!cache) return []; + const tags = cache.tags; + if (!tags) return []; + return tags.map((tag2) => ({ + key: tag2.tag, + content: tag2.tag, + type: 2 /* Tag */, + position: { start: tag2.position.start.offset, end: tag2.position.end.offset, line: tag2.position.start.line } + })); + } + async parseFrontmatter(file) { + const frontmatter = await this.parseFrontmatterObject(file); + if (!frontmatter) return []; + return this.objectToYamlProperties(frontmatter); + } + parseFrontmatterCache(fileCache) { + const frontmatter = fileCache?.frontmatter; + if (!frontmatter) return []; + return this.objectToYamlProperties(frontmatter, true); + } + async parseFrontmatterObject(file) { + const fileCache = this.app.metadataCache.getFileCache(file); + const filecontent = await this.app.vault.cachedRead(file); + const parsedYaml = this.parseFrontmatterContent(filecontent); + if (this.isFrontmatterObject(parsedYaml)) return parsedYaml; + const frontmatter = fileCache?.frontmatter; + if (this.isFrontmatterObject(frontmatter)) return this.omitInternalFrontmatterPosition(frontmatter); + return null; + } + isFrontmatterObject(value) { + return isPlainYamlObject(value); + } + omitInternalFrontmatterPosition(frontmatter) { + if (!this.isFrontmatterPosition(frontmatter.position)) return frontmatter; + const cleaned = { ...frontmatter }; + delete cleaned.position; + return cleaned; + } + isFrontmatterPosition(position) { + if (!position || typeof position !== "object") return false; + const candidate = position; + return this.isPosition(candidate.start) && this.isPosition(candidate.end); + } + isPosition(position) { + if (!position || typeof position !== "object") return false; + const candidate = position; + return typeof candidate.line === "number" && typeof candidate.col === "number" && typeof candidate.offset === "number"; + } + objectToYamlProperties(parsedYaml, omitInternalPosition = false) { + if (!this.isFrontmatterObject(parsedYaml)) return []; + const rootProperties = []; + const nestedProperties = []; + for (const key2 in parsedYaml) { + const value = parsedYaml[key2]; + if (omitInternalPosition && key2 === "position" && this.isFrontmatterPosition(value)) continue; + rootProperties.push({ key: key2, content: value, type: 0 /* YAML */ }); + this.collectNestedYamlProperties(value, [key2], nestedProperties); } -} - -/* src/Modals/GenericPrompt/GenericPromptContent.svelte generated by Svelte v3.59.2 */ - -function create_fragment(ctx) { - let div; - let h1; - let t0; - let t1; - let input; - let mounted; - let dispose; - - return { - c() { - div = element("div"); - h1 = element("h1"); - t0 = text(/*header*/ ctx[1]); - t1 = space(); - input = element("input"); - set_style(h1, "text-align", "center"); - attr(input, "class", "metaEditPromptInput"); - attr(input, "placeholder", /*placeholder*/ ctx[2]); - set_style(input, "width", "100%"); - attr(input, "type", "text"); - attr(div, "class", "metaEditPrompt"); - }, - m(target, anchor) { - insert(target, div, anchor); - append(div, h1); - append(h1, t0); - append(div, t1); - append(div, input); - /*input_binding*/ ctx[8](input); - set_input_value(input, /*value*/ ctx[0]); - - if (!mounted) { - dispose = [ - listen(input, "input", /*input_input_handler*/ ctx[9]), - listen(input, "keydown", /*submit*/ ctx[4]) - ]; - - mounted = true; - } - }, - p(ctx, [dirty]) { - if (dirty & /*header*/ 2) set_data(t0, /*header*/ ctx[1]); - - if (dirty & /*placeholder*/ 4) { - attr(input, "placeholder", /*placeholder*/ ctx[2]); - } - - if (dirty & /*value*/ 1 && input.value !== /*value*/ ctx[0]) { - set_input_value(input, /*value*/ ctx[0]); - } - }, - i: noop, - o: noop, - d(detaching) { - if (detaching) detach(div); - /*input_binding*/ ctx[8](null); - mounted = false; - run_all(dispose); - } - }; -} - -function instance($$self, $$props, $$invalidate) { - let { app } = $$props; - let { header = "" } = $$props; - let { placeholder = "" } = $$props; - let { value = "" } = $$props; - let { onSubmit } = $$props; - let { suggestValues } = $$props; - let inputEl; - - onMount(() => { - if (suggestValues && suggestValues.length > 0) new GenericTextSuggester(app, inputEl, suggestValues); - inputEl.select(); - inputEl.focus(); - }); - - function submit(evt) { - if (evt.key === "Enter") { - evt.preventDefault(); - onSubmit(value); - } - } - - function input_binding($$value) { - binding_callbacks[$$value ? 'unshift' : 'push'](() => { - inputEl = $$value; - $$invalidate(3, inputEl); - }); - } - - function input_input_handler() { - value = this.value; - $$invalidate(0, value); - } - - $$self.$$set = $$props => { - if ('app' in $$props) $$invalidate(5, app = $$props.app); - if ('header' in $$props) $$invalidate(1, header = $$props.header); - if ('placeholder' in $$props) $$invalidate(2, placeholder = $$props.placeholder); - if ('value' in $$props) $$invalidate(0, value = $$props.value); - if ('onSubmit' in $$props) $$invalidate(6, onSubmit = $$props.onSubmit); - if ('suggestValues' in $$props) $$invalidate(7, suggestValues = $$props.suggestValues); - }; - - return [ - value, - header, - placeholder, - inputEl, - submit, - app, - onSubmit, - suggestValues, - input_binding, - input_input_handler - ]; -} - -class GenericPromptContent extends SvelteComponent { - constructor(options) { - super(); - - init(this, options, instance, create_fragment, safe_not_equal, { - app: 5, - header: 1, - placeholder: 2, - value: 0, - onSubmit: 6, - suggestValues: 7 - }); - } -} - -class GenericPrompt extends obsidian.Modal { - static Prompt(app, header, placeholder, value, suggestValues) { - const newPromptModal = new GenericPrompt(app, header, placeholder, value, suggestValues); - return newPromptModal.waitForClose; - } - constructor(app, header, placeholder, value, suggestValues) { - super(app); - this.didSubmit = false; - this.modalContent = new GenericPromptContent({ - target: this.contentEl, - props: { - app, - header, - placeholder, - value, - suggestValues, - onSubmit: (input) => { - this.input = input; - this.didSubmit = true; - this.close(); - } - } + return [...rootProperties, ...nestedProperties]; + } + collectNestedYamlProperties(value, path, properties) { + if (isYamlScalarLeaf(value)) { + if (path.length > 1 && typeof path[path.length - 1] !== "number") { + const rootKey = String(path[0]); + properties.push({ + key: formatYamlPath(path), + content: value, + type: 0 /* YAML */, + path: [...path], + rootKey, + isNested: true, + isVirtual: true }); - this.waitForClose = new Promise((resolve, reject) => { - this.resolvePromise = resolve; - this.rejectPromise = reject; - }); - this.open(); + } + return; } - onOpen() { - super.onOpen(); - const modalPrompt = document.querySelector('.metaEditPrompt'); - const modalInput = modalPrompt.querySelector('.metaEditPromptInput'); - modalInput.focus(); - modalInput.select(); + if (Array.isArray(value)) { + value.forEach((item, idx) => this.collectNestedYamlProperties(item, [...path, idx], properties)); + return; } - onClose() { - super.onClose(); - this.modalContent.$destroy(); - if (!this.didSubmit) - this.rejectPromise("No input given."); - else - this.resolvePromise(this.input); + if (isPlainYamlObject(value)) { + for (const key2 in value) { + this.collectNestedYamlProperties(value[key2], [...path, key2], properties); + } } -} + } + async parseInlineFields(file) { + const content = await this.app.vault.cachedRead(file); + return this.parseInlineContent(content); + } + /** + * Extract inline `key:: value` fields from raw note content. + * + * Mirrors Dataview's two-mode model: bracketed fields (`[k:: v]` / `(k:: v)`) + * take precedence over a single "full-line" field, and a line yields one or + * the other - never both. Keys are returned clean (without leading list or + * blockquote markers) so callers can match and round-trip them; the + * full-line key is otherwise kept verbatim so odd-but-real keys like + * `progress (%)` survive a read/write cycle. + */ + parseInlineContent(content) { + const properties = []; + for (const line of this.walkInlineContentLines(content)) { + if (!line.readable) continue; + if (!line.text.includes("::")) continue; + for (const field of this.parseLineFields(line.text)) { + properties.push({ key: field.key, content: field.value, type: 1 /* Dataview */ }); + } + } + return properties; + } + parseFrontmatterContent(content) { + const frontmatterInfo = this.getFrontmatterInfo(content); + if (!frontmatterInfo?.exists) return null; + try { + return (0, import_obsidian5.parseYaml)(frontmatterInfo.frontmatter); + } catch { + return null; + } + } + getFrontmatterInfo(content) { + const info = (0, import_obsidian5.getFrontMatterInfo)(content); + const legacyDotInfo = this.getLegacyDotCloseFrontmatterInfo(content); + if (legacyDotInfo && (!info.exists || legacyDotInfo.contentStart < info.contentStart)) + return legacyDotInfo; + if (info.exists) return info; + return null; + } + getLegacyDotCloseFrontmatterInfo(content) { + const lines = this.splitContentLines(content); + if (!/^---\s*$/.test(lines[0]?.text ?? "")) return null; + for (let i = 1; i < lines.length; i++) { + if (!/^\.\.\.\s*$/.test(lines[i].text)) continue; + const from = lines[0].nextStart; + const to = lines[i].start; + return { + exists: true, + frontmatter: content.slice(from, to), + from, + to, + contentStart: lines[i].nextStart + }; + } + return null; + } + splitContentLines(content) { + const textLines = content.split(/\r?\n/); + const lines = []; + let offset = 0; + for (let i = 0; i < textLines.length; i++) { + const text2 = textLines[i]; + const start = offset; + const end = start + text2.length; + let nextStart = end; + if (i < textLines.length - 1) { + nextStart += content.startsWith("\r\n", end) ? 2 : 1; + } + lines.push({ text: text2, start, end, nextStart }); + offset = nextStart; + } + return lines; + } + *walkInlineContentLines(content) { + const lines = this.splitContentLines(content); + const frontmatterInfo = this.getFrontmatterInfo(content); + let openFence = null; + for (let index2 = 0; index2 < lines.length; index2++) { + const line = lines[index2]; + const inFrontmatter = frontmatterInfo?.exists === true && line.start < frontmatterInfo.contentStart; + if (inFrontmatter) { + yield { ...line, index: index2, inFrontmatter, fenceBoundary: null, readable: false }; + continue; + } + const { open, boundary: boundary2 } = nextFenceState(openFence, line.text); + openFence = open; + yield { + ...line, + index: index2, + inFrontmatter: false, + fenceBoundary: boundary2, + readable: boundary2 === null && openFence === null + }; + } + } + parseLineFields(line) { + const bracketed = this.extractBracketedFields(line); + if (bracketed.length > 0) return bracketed; + const fullLine = this.extractFullLineField(line); + return fullLine ? [fullLine] : []; + } + extractBracketedFields(line) { + const fields = []; + for (const open of Object.keys(INLINE_FIELD_WRAPPERS)) { + let idx = line.indexOf(open); + while (idx >= 0) { + const field = this.findBracketedField(line, idx); + if (!field) { + idx = line.indexOf(open, idx + 1); + continue; + } + fields.push(field); + idx = line.indexOf(open, field.end); + } + } + fields.sort((a, b) => a.start - b.start); + const kept = []; + for (const field of fields) { + if (kept.length === 0 || kept[kept.length - 1].end <= field.start) { + kept.push(field); + } + } + return kept; + } + findBracketedField(line, start) { + const open = line[start]; + const close = INLINE_FIELD_WRAPPERS[open]; + const sep = line.indexOf("::", start + 1); + if (sep < 0) return null; + const key2 = line.substring(start + 1, sep).trim(); + if (!key2 || /[[\]()]/.test(key2)) return null; + const closing = this.findClosingBracket(line, sep + 2, open, close); + if (!closing) return null; + return { key: key2, value: closing.value, start, end: closing.end, sepEnd: sep + 2, valueEnd: closing.end - 1 }; + } + findClosingBracket(line, start, open, close) { + let nesting = 0; + for (let i = start; i < line.length; i++) { + const char = line[i]; + if (char === open) { + nesting++; + } else if (char === close) { + if (nesting === 0) { + return { value: line.substring(start, i).trim(), end: i + 1 }; + } + nesting--; + } + } + return null; + } + extractFullLineField(line) { + const lineEnd = line.endsWith("\r") ? line.length - 1 : line.length; + const prefix = line.match(FULL_LINE_PREFIX)?.[0] ?? ""; + const body = line.slice(prefix.length, lineEnd); + const sep = body.indexOf("::"); + if (sep < 0) return null; + const key2 = body.substring(0, sep).trim(); + if (!key2) return null; + const value = body.substring(sep + 2).trim(); + const sepEnd = prefix.length + sep + 2; + return { key: key2, value, start: prefix.length, end: lineEnd, sepEnd, valueEnd: lineEnd }; + } + /** + * Rewrite the value of every inline field named `key` on a single line, + * leaving the key, surrounding text, and any `[...]`/`(...)` wrapper intact. + * + * This is the write-side counterpart to {@link parseInlineContent}: because + * it reuses the same field boundaries, a full-line value (which may itself + * contain `]`/`)`, e.g. `ref:: [[Note]]`) is replaced up to end-of-line and a + * bracketed value only up to its matching close bracket - so updates no + * longer append a stray closing bracket. Returns the line unchanged when no + * field matches. + */ + replaceInlineFieldValue(line, key2, newValue) { + const matches = this.parseLineFields(line).filter((field) => field.key === key2); + if (matches.length === 0) return line; + let result = line; + for (let i = matches.length - 1; i >= 0; i--) { + const field = matches[i]; + result = result.slice(0, field.sepEnd) + " " + newValue + result.slice(field.valueEnd); + } + return result; + } + /** + * Rewrite inline field values in raw note content using the same readable-line + * boundary as {@link parseInlineContent}. Only the changed line spans are + * replaced; all untouched bytes, including mixed CRLF/LF line endings, are + * preserved exactly. + */ + replaceInlineFieldValuesInContent(content, replacements) { + const activeReplacements = replacements.filter(({ key: key2 }) => key2.length > 0); + if (activeReplacements.length === 0) return content; + let result = ""; + let cursor = 0; + for (const line of this.walkInlineContentLines(content)) { + if (!line.readable) continue; + if (!line.text.includes("::")) continue; + let updatedLine = line.text; + for (const { key: key2, value } of activeReplacements) { + updatedLine = this.replaceInlineFieldValue(updatedLine, key2, value); + } + if (updatedLine === line.text) continue; + result += content.slice(cursor, line.start) + updatedLine; + cursor = line.end; + } + if (cursor === 0) return content; + return result + content.slice(cursor); + } + /** + * Compute the line index at which to splice a new `name:: value` inline field. + * + * This is the write-placement counterpart to {@link parseInlineContent}: it walks + * the content with the SAME frontmatter, fenced-code, and inline-field detection so + * the insertion point is always consistent with what MetaEdit reads as a field. The + * returned index is into `content.split(/\r?\n/)` (the same split + * {@link splitContentLines} performs), so a caller can splice directly. + * + * Guarantees: the index is never inside YAML frontmatter or a fenced code block. + * - "afterLastMatch": just after the last body line that declares `name` (full-line + * or bracketed), falling back to "end" when there is no such field. + * - "end": just after the last body content line or trailing closing code fence. + * When the note has no body content (empty or frontmatter-only), the field is placed + * at the start of the body, or at the very end when the whole file is frontmatter. + */ + computeInlineInsertIndex(content, name, location = "afterLastMatch") { + let lastMatchIdx = -1; + let lastAnchorIdx = -1; + let firstBodyIdx = -1; + let lineCount = 0; + for (const line of this.walkInlineContentLines(content)) { + lineCount = line.index + 1; + if (line.inFrontmatter) continue; + if (firstBodyIdx === -1) firstBodyIdx = line.index; + if (line.fenceBoundary === "open") continue; + if (line.fenceBoundary === "close") { + lastAnchorIdx = line.index; + continue; + } + if (!line.readable) continue; + if (line.text.trim() !== "") lastAnchorIdx = line.index; + if (line.text.includes("::") && this.parseLineFields(line.text).some((field) => field.key === name)) { + lastMatchIdx = line.index; + } + } + if (location === "afterLastMatch" && lastMatchIdx !== -1) return lastMatchIdx + 1; + if (lastAnchorIdx !== -1) return lastAnchorIdx + 1; + return firstBodyIdx !== -1 ? firstBodyIdx : lineCount; + } +}; -class GenericSuggester extends obsidian.FuzzySuggestModal { - static Suggest(app, displayItems, items) { - const newSuggester = new GenericSuggester(app, displayItems, items); - return newSuggester.promise; - } - constructor(app, displayItems, items) { - super(app); - this.displayItems = displayItems; - this.items = items; - this.promise = new Promise((resolve) => (this.resolvePromise = resolve)); - this.open(); - } - getItemText(item) { - return this.displayItems[this.items.indexOf(item)]; - } - getItems() { - return this.items; - } - onChooseItem(item, evt) { - this.resolvePromise(item); - } -} +// src/Modals/GenericPrompt/GenericPrompt.ts +var import_obsidian7 = require("obsidian"); -class MetaController { - constructor(app, plugin) { - this.hasTrackerPlugin = false; - this.useTrackerPlugin = false; - this.app = app; - this.parser = new MetaEditParser(app); - this.plugin = plugin; - // @ts-ignore - this.hasTrackerPlugin = !!this.app.plugins.plugins["obsidian-tracker"]; +// src/Modals/GenericPrompt/genericTextSuggester.ts +var import_obsidian6 = require("obsidian"); +var GenericTextSuggester = class extends import_obsidian6.AbstractInputSuggest { + constructor(app, inputEl, items) { + super(app, inputEl); + this.inputEl = inputEl; + this.items = items; + this.onSelect((item) => this.acceptSuggestion(item)); + } + getSuggestions(inputStr) { + return filterSuggestions(this.items, inputStr); + } + acceptSuggestion(item) { + this.setValue(item); + this.inputEl.trigger("input"); + this.close(); + } + renderSuggestion(value, el) { + if (value) + el.setText(value); + } + refreshSuggestions() { + this.inputEl.trigger("input"); + } +}; + +// src/Modals/GenericPrompt/GenericPromptContent.svelte +var root5 = from_html(``); +var root_15 = from_html(``); +var root_23 = from_html(``); +var root_32 = from_html(`

`); +function GenericPromptContent($$anchor, $$props) { + push($$props, true); + let header = prop($$props, "header", 3, ""), placeholder = prop($$props, "placeholder", 3, ""), propValue = prop($$props, "value", 3, ""), suggestValues = prop($$props, "suggestValues", 19, () => []); + const initialApp = untrack(() => $$props.app); + const initialSuggestValues = untrack(() => suggestValues()); + const initialValue = untrack(() => propValue()); + let value = state(proxy(initialValue)); + let suggester; + let inputEl = state(void 0); + const context = consumePendingValueContext(); + const hasExplicitSuggestions = Array.isArray(initialSuggestValues) && initialSuggestValues.length > 0; + const dateInputType = !hasExplicitSuggestions && context ? getDateInputType(context.app, context.key, initialValue, context.type) : null; + const datetimeStep = dateInputType === "datetime" && /T\d{2}:\d{2}:\d{2}/.test(initialValue) ? "1" : void 0; + let didInitialise = false; + user_effect(() => { + const el = get2(inputEl); + if (!el || didInitialise) return; + didInitialise = true; + let suggestions = []; + if (!dateInputType) { + suggestions = hasExplicitSuggestions ? initialSuggestValues : context ? getValueSuggestions(context.app, context.key, context.type, context.tagMode) : []; } - async getPropertiesInFile(file) { - const yaml = await this.parser.parseFrontmatter(file); - const inlineFields = await this.parser.parseInlineFields(file); - const tags = await this.parser.getTagsForFile(file); - return [...tags, ...yaml, ...inlineFields]; + el.focus(); + if (!dateInputType) el.select(); + if (!dateInputType && suggestions.length > 0) { + suggester = new GenericTextSuggester(initialApp, el, suggestions); } - async addYamlProp(propName, propValue, file) { - const fileContent = await this.app.vault.read(file); - const frontmatter = await this.parser.parseFrontmatter(file); - const isYamlEmpty = ((!frontmatter || frontmatter.length === 0) && !fileContent.match(/^-{3}\s*\n*\r*-{3}/)); - if (frontmatter.some(value => value.key === propName)) { - new obsidian.Notice(`Frontmatter in file '${file.name}' already has property '${propName}. Will not add.'`); - return; - } - const settings = this.plugin.settings; - if (settings.EditMode.mode === EditMode.AllMulti || - (settings.EditMode.mode === EditMode.SomeMulti && settings.EditMode.properties.contains(propName))) { - propValue = `[${propValue}]`; - } - let splitContent = fileContent.split("\n"); - if (isYamlEmpty) { - splitContent.unshift("---"); - splitContent.unshift(`${propName}: ${propValue}`); - splitContent.unshift("---"); - } - else { - splitContent.splice(1, 0, `${propName}: ${propValue}`); - } - const newFileContent = splitContent.join("\n"); - await this.app.vault.modify(file, newFileContent); + if (suggester && !initialValue) suggester.refreshSuggestions(); + return () => { + suggester?.close(); + suggester = void 0; + }; + }); + function submit(evt) { + if (evt.key === "Enter") { + evt.preventDefault(); + $$props.onSubmit(get2(value)); } - async addDataviewField(propName, propValue, file) { - const fileContent = await this.app.vault.read(file); - let lines = fileContent.split("\n").reduce((obj, line, idx) => { - obj[idx] = !!line ? line : ""; - return obj; - }, {}); - let appendAfter = await GenericSuggester.Suggest(this.app, Object.values(lines), Object.keys(lines)); - if (!appendAfter) - return; - let splitContent = fileContent.split("\n"); - if (typeof appendAfter === "number" || parseInt(appendAfter)) { - splitContent.splice(parseInt(appendAfter), 0, `${propName}:: ${propValue}`); + } + var div = root_32(); + var h1 = child(div); + var text2 = child(h1, true); + reset(h1); + var node = sibling(h1, 2); + { + var consequent = ($$anchor2) => { + var input = root5(); + remove_input_defaults(input); + bind_this(input, ($$value) => set(inputEl, $$value), () => get2(inputEl)); + delegated("keydown", input, submit); + bind_value(input, () => get2(value), ($$value) => set(value, $$value)); + append($$anchor2, input); + }; + var consequent_1 = ($$anchor2) => { + var input_1 = root_15(); + remove_input_defaults(input_1); + bind_this(input_1, ($$value) => set(inputEl, $$value), () => get2(inputEl)); + template_effect(() => set_attribute2(input_1, "step", datetimeStep)); + delegated("keydown", input_1, submit); + bind_value(input_1, () => get2(value), ($$value) => set(value, $$value)); + append($$anchor2, input_1); + }; + var alternate = ($$anchor2) => { + var input_2 = root_23(); + remove_input_defaults(input_2); + bind_this(input_2, ($$value) => set(inputEl, $$value), () => get2(inputEl)); + template_effect(() => set_attribute2(input_2, "placeholder", placeholder())); + delegated("keydown", input_2, submit); + bind_value(input_2, () => get2(value), ($$value) => set(value, $$value)); + append($$anchor2, input_2); + }; + if_block(node, ($$render) => { + if (dateInputType === "date") $$render(consequent); + else if (dateInputType === "datetime") $$render(consequent_1, 1); + else $$render(alternate, -1); + }); + } + reset(div); + template_effect(() => set_text(text2, header())); + append($$anchor, div); + pop(); +} +delegate(["keydown"]); + +// src/Modals/GenericPrompt/GenericPrompt.ts +var GenericPrompt = class _GenericPrompt extends import_obsidian7.Modal { + constructor(app, header, placeholder, value, suggestValues) { + super(app); + this.didSubmit = false; + this.modalContent = mountSvelteComponent( + GenericPromptContent, + this.contentEl, + { + app, + header, + placeholder, + value, + suggestValues, + onSubmit: (input) => { + this.input = input; + this.didSubmit = true; + this.close(); } - const newFileContent = splitContent.join("\n"); - await this.app.vault.modify(file, newFileContent); + } + ); + this.waitForClose = new Promise( + (resolve) => { + this.resolvePromise = resolve; + } + ); + this.open(); + } + static Prompt(app, header, placeholder, value, suggestValues) { + const newPromptModal = new _GenericPrompt(app, header, placeholder, value, suggestValues); + return newPromptModal.waitForClose; + } + onOpen() { + super.onOpen(); + const modalPrompt = activeDocument.querySelector(".metaEditPrompt"); + const modalInput = modalPrompt?.querySelector(".metaEditPromptInput"); + modalInput?.focus(); + if (modalInput?.type === "text") modalInput.select(); + } + onClose() { + super.onClose(); + unmountSvelteComponent(this.modalContent); + if (!this.didSubmit) this.resolvePromise(null); + else this.resolvePromise(this.input); + } +}; + +// src/Modals/GenericSuggester/GenericSuggester.ts +var import_obsidian8 = require("obsidian"); +var GenericSuggester = class _GenericSuggester extends import_obsidian8.FuzzySuggestModal { + constructor(app, displayItems, items) { + super(app); + this.displayItems = displayItems; + this.items = items; + this.didChoose = false; + this.promise = new Promise( + (resolve) => this.resolvePromise = resolve + ); + this.open(); + } + static Suggest(app, displayItems, items) { + const newSuggester = new _GenericSuggester(app, displayItems, items); + return newSuggester.promise; + } + getItemText(item) { + return this.displayItems[this.items.indexOf(item)]; + } + getItems() { + return this.items; + } + onChooseItem(item, _evt) { + this.didChoose = true; + this.resolvePromise(item); + } + onClose() { + super.onClose(); + queueMicrotask(() => { + if (!this.didChoose) this.resolvePromise(""); + }); + } +}; + +// src/metaController.ts +var import_obsidian16 = require("obsidian"); + +// src/Modals/AutoPropertyValueModal/AutoPropertyValueModal.ts +var import_obsidian10 = require("obsidian"); + +// src/Modals/AutoPropertyValueModal/AutoPropertyValueModalContent.svelte +var import_obsidian9 = require("obsidian"); +var root6 = from_html(`
`); +var root_16 = from_html(`new`); +var root_24 = from_html(``); +var root_33 = from_html(`
No values yet - type one above and press Enter.
`); +var root_42 = from_html(``); +var root_5 = from_html(`
`, 1); +var root_6 = from_html(``); +var root_7 = from_html(``); +var root_8 = from_html(`
No choices defined - type a value and press Enter.
`); +var root_9 = from_html(`
`, 1); +var root_10 = from_html(`
`); +var $$css5 = { + hash: "svelte-rukrzs", + code: ".metaedit-ap-prompt.svelte-rukrzs {display:flex;flex-direction:column;gap:0.6rem;}.metaedit-ap-prompt-head.svelte-rukrzs {display:flex;flex-direction:column;gap:0.15rem;}.metaedit-ap-prompt-title.svelte-rukrzs {font-size:var(--font-ui-large, 1.1em);font-weight:var(--font-semibold, 600);color:var(--text-normal);}.metaedit-ap-prompt-desc.svelte-rukrzs {color:var(--text-muted);font-size:var(--font-ui-small, 0.85em);line-height:1.4;}.metaedit-ap-prompt-input.svelte-rukrzs {width:100%;}.metaedit-ap-prompt-list.svelte-rukrzs {display:flex;flex-direction:column;gap:2px;max-height:16rem;overflow-y:auto;}.metaedit-ap-prompt-row.svelte-rukrzs {display:flex;align-items:center;gap:0.5rem;width:100%;text-align:left;padding:0.4rem 0.55rem;border-radius:var(--radius-s, 4px);background:transparent;box-shadow:none;color:var(--text-normal);cursor:pointer;font-size:var(--font-ui-medium, 1em);}.metaedit-ap-prompt-row.is-selected.svelte-rukrzs {background-color:var(--background-modifier-hover);}.metaedit-ap-prompt-action.svelte-rukrzs {color:var(--text-muted);}.metaedit-ap-prompt-check.svelte-rukrzs {cursor:pointer;}.metaedit-ap-prompt-check.svelte-rukrzs input:where(.svelte-rukrzs) {margin:0;}.metaedit-ap-prompt-row-icon.svelte-rukrzs {display:inline-flex;align-items:center;}.metaedit-ap-prompt-row-label.svelte-rukrzs {flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.metaedit-ap-prompt-tag.svelte-rukrzs {flex:0 0 auto;font-size:var(--font-ui-smaller, 0.75em);color:var(--text-accent);border:1px solid var(--background-modifier-border);border-radius:var(--radius-s, 4px);padding:0 0.3rem;}.metaedit-ap-prompt-empty.svelte-rukrzs {color:var(--text-muted);padding:0.4rem 0.55rem;font-size:var(--font-ui-small, 0.85em);}.metaedit-ap-prompt-savenew.svelte-rukrzs {display:flex;align-items:center;gap:0.45rem;color:var(--text-muted);font-size:var(--font-ui-small, 0.85em);cursor:pointer;}.metaedit-ap-prompt-actions.svelte-rukrzs {display:flex;justify-content:flex-end;}" +}; +function AutoPropertyValueModalContent($$anchor, $$props) { + push($$props, true); + append_styles($$anchor, $$css5); + let isMulti = prop($$props, "isMulti", 3, false), currentValue = prop($$props, "currentValue", 3, null); + const initialAutoProperty = untrack(() => $$props.autoProperty); + const initialIsMulti = untrack(() => isMulti()); + const initialCurrentValue = untrack(() => currentValue()); + const choices = normalizeChoices(initialAutoProperty.choices); + let inputEl = state(void 0); + let query = state(""); + let highlight = state(0); + function icon(node, name) { + node.textContent = ""; + (0, import_obsidian9.setIcon)(node, name); + return {}; + } + let trimmedQuery = user_derived(() => get2(query).trim()); + let filtered = user_derived(() => choices.filter((c) => c.toLowerCase().includes(get2(trimmedQuery).toLowerCase()))); + let exactMatch = user_derived(() => choices.some((c) => c.toLowerCase() === get2(trimmedQuery).toLowerCase())); + let singleItems = user_derived(() => buildSingleItems(get2(filtered), get2(trimmedQuery), get2(exactMatch))); + user_effect(() => { + const maxHighlight = Math.max(0, get2(singleItems).length - 1); + if (get2(highlight) > maxHighlight) set(highlight, maxHighlight, true); + }); + function buildSingleItems(matches, q, exact) { + const items = matches.map((c) => ({ kind: "choice", value: c, label: c })); + if (q !== "" && !exact) { + items.push({ kind: "use", value: q, label: `Use "${q}"` }); + items.push({ kind: "save", value: q, label: `Save "${q}" as a choice` }); } - async editMetaElement(property, meta, file) { - const mode = this.plugin.settings.EditMode.mode; - if (property.type === MetaType.Tag) - await this.editTag(property, file); - else if (mode === EditMode.AllMulti || mode === EditMode.SomeMulti) - await this.multiValueMode(property, file); - else - await this.standardMode(property, file); + return items; + } + async function persistChoices(values) { + try { + await $$props.onSaveChoices(values); + } catch (e) { + console.error("MetaEdit: failed to save new auto property choice", e); } - async editTag(property, file) { - const splitTag = property.key.split("/"); - const allButLast = splitTag.slice(0, splitTag.length - 1).join("/"); - const trackerPluginMethod = "Use Tracker", metaEditMethod = "Use MetaEdit", choices = [trackerPluginMethod, metaEditMethod]; - let newValue; - let method = metaEditMethod; - if (this.hasTrackerPlugin) - method = await GenericSuggester.Suggest(this.app, choices, choices); - if (!method) - return; - if (method === trackerPluginMethod) { - newValue = await GenericPrompt.Prompt(this.app, `Enter a new value for ${property.key}`); - this.useTrackerPlugin = true; - } - else if (method === metaEditMethod) { - const autoProp = await this.handleAutoProperties(allButLast); - if (autoProp) - newValue = autoProp; - else - newValue = await GenericPrompt.Prompt(this.app, `Enter a new value for ${property.key}`); - } - if (newValue) { - await this.updatePropertyInFile(property, newValue, file); - } + } + async function chooseSingle(item) { + if (!item) return; + if (item.kind === "save") { + await persistChoices([item.value]); } - async handleProgressProps(meta, file) { - var _a, _b; - try { - const { enabled, properties } = this.plugin.settings.ProgressProperties; - if (!enabled) - return; - const tasks = (_b = (_a = this.app.metadataCache.getFileCache(file)) === null || _a === void 0 ? void 0 : _a.listItems) === null || _b === void 0 ? void 0 : _b.filter(li => li.task); - if (!tasks) - return; - let total = 0, complete = 0, incomplete = 0; - total = tasks.length; - complete = tasks.filter(i => i.task != " ").length; - incomplete = total - complete; - const props = await this.progressPropHelper(properties, meta, { total, complete, incomplete }); - await this.updateMultipleInFile(props, file); - } - catch (e) { - log.logError(e); - } + $$props.onSubmit(item.value); + } + function onSingleKeydown(e) { + if (e.key === "ArrowDown") { + e.preventDefault(); + set(highlight, Math.min(get2(highlight) + 1, get2(singleItems).length - 1), true); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + set(highlight, Math.max(get2(highlight) - 1, 0), true); + } else if (e.key === "Enter") { + e.preventDefault(); + if (get2(singleItems).length > 0) chooseSingle(get2(singleItems)[get2(highlight)]); + else if (get2(trimmedQuery) !== "") $$props.onSubmit(get2(trimmedQuery)); } - async createNewProperty(suggestValues) { - let propName = await GenericPrompt.Prompt(this.app, "Enter a property name", "Property", "", suggestValues); - if (!propName) - return null; - let propValue; - const autoProp = await this.handleAutoProperties(propName); - if (autoProp) { - propValue = autoProp; - } - else { - propValue = await GenericPrompt.Prompt(this.app, "Enter a property value", "Value") - .catch(() => null); - } - if (propValue === null) - return null; - return { propName, propValue: propValue.trim() }; + } + let options = state(proxy(untrack(() => initialIsMulti ? multiSelectOptions(initialAutoProperty, initialCurrentValue) : []))); + let checkedValues = state(proxy(untrack(() => toValueArray(initialCurrentValue)))); + let saveNew = state(false); + let newCheckedValues = user_derived(() => get2(options).filter((o) => get2(checkedValues).includes(o) && !choices.includes(o))); + function toggleCheck(value) { + set( + checkedValues, + get2(checkedValues).includes(value) ? get2(checkedValues).filter((checkedValue) => checkedValue !== value) : [...get2(checkedValues), value], + true + ); + } + function addMultiValue() { + const value = get2(query).trim(); + if (value === "") return; + if (!get2(options).includes(value)) set(options, [...get2(options), value], true); + if (!get2(checkedValues).includes(value)) set(checkedValues, [...get2(checkedValues), value], true); + set(query, ""); + } + function onMultiAddKeydown(e) { + if (e.key === "Enter") { + e.preventDefault(); + addMultiValue(); } - async deleteProperty(property, file) { - const fileContent = await this.app.vault.read(file); - const splitContent = fileContent.split("\n"); - const regexp = new RegExp(`^\s*${property.key}:`); - const idx = splitContent.findIndex(s => s.match(regexp)); - const newFileContent = splitContent.filter((v, i) => { - if (i != idx) - return true; - }).join("\n"); - await this.app.vault.modify(file, newFileContent); + } + async function confirmMulti() { + const result = get2(options).filter((o) => get2(checkedValues).includes(o)); + if (get2(saveNew) && get2(newCheckedValues).length > 0) { + await persistChoices(get2(newCheckedValues)); } - async progressPropHelper(progressProps, meta, counts) { - return progressProps.reduce((obj, el) => { - const property = meta.find(prop => prop.key === el.name); - if (property) { - switch (el.type) { - case ProgressPropertyOptions.TaskComplete: - obj.push(Object.assign(Object.assign({}, property), { content: counts.complete.toString() })); - break; - case ProgressPropertyOptions.TaskIncomplete: - obj.push(Object.assign(Object.assign({}, property), { content: counts.incomplete.toString() })); - break; - case ProgressPropertyOptions.TaskTotal: - obj.push(Object.assign(Object.assign({}, property), { content: counts.total.toString() })); - break; - } - } - return obj; - }, []); - } - async standardMode(property, file) { - const autoProp = await this.handleAutoProperties(property.key); - let newValue; - if (autoProp) - newValue = autoProp; - else - newValue = await GenericPrompt.Prompt(this.app, `Enter a new value for ${property.key}`, property.content, property.content); - if (newValue) { - await this.updatePropertyInFile(property, newValue, file); - } - } - async multiValueMode(property, file) { - const settings = this.plugin.settings; - let newValue; - if (settings.EditMode.mode == EditMode.SomeMulti && !settings.EditMode.properties.includes(property.key)) { - await this.standardMode(property, file); - return false; - } - let selectedOption, tempValue, splitValues; - let currentPropValue = property.content; - if (currentPropValue !== null) - currentPropValue = currentPropValue.toString(); - else - currentPropValue = ""; - if (property.type === MetaType.YAML) { - splitValues = currentPropValue.split('').filter(c => !c.includes("[]")).join('').split(","); - } - else { - splitValues = currentPropValue.split(",").map(prop => prop.trim()); - } - if (splitValues.length == 0 || (splitValues.length == 1 && splitValues[0] == "")) { - const options = ["Add new value"]; - selectedOption = await GenericSuggester.Suggest(this.app, options, [ADD_FIRST_ELEMENT]); - } - else if (splitValues.length == 1) { - const options = [splitValues[0], "Add to end", "Add to beginning"]; - selectedOption = await GenericSuggester.Suggest(this.app, options, [splitValues[0], ADD_TO_END, ADD_TO_BEGINNING]); - } - else { - const options = ["Add to end", ...splitValues, "Add to beginning"]; - selectedOption = await GenericSuggester.Suggest(this.app, options, [ADD_TO_END, ...splitValues, ADD_TO_BEGINNING]); - } - if (!selectedOption) - return; - let selectedIndex; - const autoProp = await this.handleAutoProperties(property.key); - if (autoProp) { - tempValue = autoProp; - } - else if (selectedOption.includes("cmd")) { - tempValue = await GenericPrompt.Prompt(this.app, "Enter a new value"); - } - else { - selectedIndex = splitValues.findIndex(el => el == selectedOption); - tempValue = await GenericPrompt.Prompt(this.app, `Change ${selectedOption} to`, selectedOption); - } - if (!tempValue) - return; - switch (selectedOption) { - case ADD_FIRST_ELEMENT: - newValue = `${tempValue}`; - break; - case ADD_TO_BEGINNING: - newValue = `${[tempValue, ...splitValues].join(", ")}`; - break; - case ADD_TO_END: - newValue = `${[...splitValues, tempValue].join(", ")}`; - break; - default: - if (selectedIndex) - splitValues[selectedIndex] = tempValue; - else - splitValues = [tempValue]; - newValue = `${splitValues.join(", ")}`; - break; - } - if (property.type === MetaType.YAML) - newValue = `[${newValue}]`; - if (newValue) { - await this.updatePropertyInFile(property, newValue, file); - return true; - } - return false; - } - async handleAutoProperties(propertyName) { - const autoProp = this.plugin.settings.AutoProperties.properties.find(a => a.name === propertyName); - if (this.plugin.settings.AutoProperties.enabled && autoProp) { - const options = autoProp.choices; - return await GenericPrompt.Prompt(this.app, `Enter a new value for ${propertyName}`, '', '', options); - } - return null; - } - updateYamlProperty(property, newValue, file) { - const fileCache = this.app.metadataCache.getFileCache(file); - const frontMatter = fileCache.frontmatter; - frontMatter[property.key] = newValue; - return obsidian.stringifyYaml(frontMatter); - } - async updatePropertyInFile(property, newValue, file) { - // I'm aware this is hacky. Didn't want to spend a bunch of time rewriting old logic. - // This uses the new frontmatter API to update the frontmatter. Later TODO: rewrite old logic to just do this & clean. - if (property.type === MetaType.YAML) { - const updatedMetaData = `---\n${this.updateYamlProperty(property, newValue, file)}\n---`; - //@ts-ignore - const frontmatterPosition = this.app.metadataCache.getFileCache(file).frontmatterPosition; - const fileContents = await this.app.vault.read(file); - const deleteFrom = frontmatterPosition.start.offset; - const deleteTo = frontmatterPosition.end.offset; - const newFileContents = fileContents.substring(0, deleteFrom) + updatedMetaData + fileContents.substring(deleteTo); - await this.app.vault.modify(file, newFileContents); - return; - } - const fileContent = await this.app.vault.read(file); - const newFileContent = fileContent.split("\n").map(line => { - if (this.lineMatch(property, line)) { - return this.updatePropertyLine(property, newValue, line); - } - return line; - }).join("\n"); - await this.app.vault.modify(file, newFileContent); - } - escapeSpecialCharacters(text) { - return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); - } - lineMatch(property, line) { - const propertyRegex = new RegExp(`${this.escapeSpecialCharacters(property.key)}\:{1,2}`); - const tagRegex = new RegExp(`^\s*${this.escapeSpecialCharacters(property.key)}`); - if (property.key.contains('#')) { - return tagRegex.test(line); - } - return propertyRegex.test(line); - } - updatePropertyLine(property, newValue, line) { - let newLine; - switch (property.type) { - case MetaType.Dataview: - const propertyRegex = new RegExp(`([\\(\\[]?)${this.escapeSpecialCharacters(property.key)}::[ ]*[^\\)\\]\n\r]*(?:\\]\])?([\\]\\)]?)`, 'g'); - newLine = line.replace(propertyRegex, `$1${property.key}:: ${newValue}$2`); - break; - case MetaType.YAML: - newLine = `${property.key}: ${newValue}`; - break; - case MetaType.Tag: - if (this.useTrackerPlugin) { - newLine = `${property.key}:${newValue}`; - } - else { - const splitTag = property.key.split("/"); - if (splitTag.length === 1) - newLine = `${splitTag[0]}/${newValue}`; - else if (splitTag.length > 1) { - const allButLast = splitTag.slice(0, splitTag.length - 1).join("/"); - newLine = `${allButLast}/${newValue}`; - } - else - newLine = property.key; - } - break; - default: - newLine = property.key; - break; - } - return newLine; - } - async updateMultipleInFile(properties, file) { - let fileContent = (await this.app.vault.read(file)).split("\n"); - for (const prop of properties) { - fileContent = fileContent.map(line => { - if (this.lineMatch(prop, line)) { - return this.updatePropertyLine(prop, prop.content, line); - } - return line; + $$props.onSubmit(result); + } + let didFocus = false; + user_effect(() => { + const el = get2(inputEl); + if (!el || didFocus) return; + didFocus = true; + el.focus(); + }); + var div = root_10(); + var div_1 = child(div); + var div_2 = child(div_1); + var text2 = child(div_2, true); + reset(div_2); + var node_1 = sibling(div_2, 2); + { + var consequent = ($$anchor2) => { + var div_3 = root6(); + var text_1 = child(div_3, true); + reset(div_3); + template_effect(() => set_text(text_1, initialAutoProperty.description)); + append($$anchor2, div_3); + }; + if_block(node_1, ($$render) => { + if (initialAutoProperty.description) $$render(consequent); + }); + } + reset(div_1); + var node_2 = sibling(div_1, 2); + { + var consequent_3 = ($$anchor2) => { + var fragment = root_5(); + var input = first_child(fragment); + remove_input_defaults(input); + bind_this(input, ($$value) => set(inputEl, $$value), () => get2(inputEl)); + var div_4 = sibling(input, 2); + each( + div_4, + 20, + () => get2(options), + (option) => option, + ($$anchor3, option) => { + var label = root_24(); + var input_1 = child(label); + remove_input_defaults(input_1); + var span = sibling(input_1, 2); + var text_2 = child(span, true); + reset(span); + var node_3 = sibling(span, 2); + { + var consequent_1 = ($$anchor4) => { + var span_1 = root_16(); + append($$anchor4, span_1); + }; + var d = user_derived(() => !choices.includes(option)); + if_block(node_3, ($$render) => { + if (get2(d)) $$render(consequent_1); }); + } + reset(label); + template_effect( + ($0) => { + set_checked(input_1, $0); + set_text(text_2, option); + }, + [() => get2(checkedValues).includes(option)] + ); + delegated("change", input_1, () => toggleCheck(option)); + append($$anchor3, label); + }, + ($$anchor3) => { + var div_5 = root_33(); + append($$anchor3, div_5); } - const newFileContent = fileContent.join("\n"); - await this.app.vault.modify(file, newFileContent); + ); + reset(div_4); + var node_4 = sibling(div_4, 2); + { + var consequent_2 = ($$anchor3) => { + var label_1 = root_42(); + var input_2 = child(label_1); + remove_input_defaults(input_2); + next(); + reset(label_1); + bind_checked(input_2, () => get2(saveNew), ($$value) => set(saveNew, $$value)); + append($$anchor3, label_1); + }; + if_block(node_4, ($$render) => { + if (get2(newCheckedValues).length > 0) $$render(consequent_2); + }); + } + var div_6 = sibling(node_4, 2); + var button = child(div_6); + reset(div_6); + delegated("keydown", input, onMultiAddKeydown); + bind_value(input, () => get2(query), ($$value) => set(query, $$value)); + delegated("click", button, confirmMulti); + append($$anchor2, fragment); + }; + var alternate = ($$anchor2) => { + var fragment_1 = root_9(); + var input_3 = first_child(fragment_1); + remove_input_defaults(input_3); + bind_this(input_3, ($$value) => set(inputEl, $$value), () => get2(inputEl)); + var div_7 = sibling(input_3, 2); + each( + div_7, + 23, + () => get2(singleItems), + (item) => item.kind + item.value, + ($$anchor3, item, i) => { + var button_1 = root_7(); + let classes; + var node_5 = child(button_1); + { + var consequent_4 = ($$anchor4) => { + var span_2 = root_6(); + action(span_2, ($$node, $$action_arg) => icon?.($$node, $$action_arg), () => "plus"); + append($$anchor4, span_2); + }; + var consequent_5 = ($$anchor4) => { + var span_3 = root_6(); + action(span_3, ($$node, $$action_arg) => icon?.($$node, $$action_arg), () => "corner-down-left"); + append($$anchor4, span_3); + }; + if_block(node_5, ($$render) => { + if (get2(item).kind === "save") $$render(consequent_4); + else if (get2(item).kind === "use") $$render(consequent_5, 1); + }); + } + var span_4 = sibling(node_5, 2); + var text_3 = child(span_4, true); + reset(span_4); + reset(button_1); + template_effect(() => { + classes = set_class(button_1, 1, "metaedit-ap-prompt-row svelte-rukrzs", null, classes, { + "is-selected": get2(i) === get2(highlight), + "metaedit-ap-prompt-action": get2(item).kind !== "choice" + }); + set_text(text_3, get2(item).label); + }); + delegated("click", button_1, () => chooseSingle(get2(item))); + event("mouseenter", button_1, () => set(highlight, get2(i), true)); + append($$anchor3, button_1); + }, + ($$anchor3) => { + var div_8 = root_8(); + append($$anchor3, div_8); + } + ); + reset(div_7); + delegated("keydown", input_3, onSingleKeydown); + bind_value(input_3, () => get2(query), ($$value) => set(query, $$value)); + append($$anchor2, fragment_1); + }; + if_block(node_2, ($$render) => { + if (initialIsMulti) $$render(consequent_3); + else $$render(alternate, -1); + }); + } + reset(div); + template_effect(() => set_text(text2, initialAutoProperty.name)); + append($$anchor, div); + pop(); +} +delegate(["keydown", "change", "click"]); + +// src/Modals/AutoPropertyValueModal/AutoPropertyValueModal.ts +var AutoPropertyValueModal = class _AutoPropertyValueModal extends import_obsidian10.Modal { + constructor(app, autoProperty, options) { + super(app); + this.result = null; + this.didSubmit = false; + this.waitForClose = new Promise((resolve) => this.resolvePromise = resolve); + this.content = mountSvelteComponent( + AutoPropertyValueModalContent, + this.contentEl, + { + autoProperty, + isMulti: options.isMulti, + currentValue: options.currentValue ?? null, + onSaveChoices: options.onSaveChoices, + onSubmit: (value) => { + this.result = value; + this.didSubmit = true; + this.close(); + } + } + ); + this.open(); + } + static Show(app, autoProperty, options) { + return new _AutoPropertyValueModal(app, autoProperty, options).waitForClose; + } + onClose() { + super.onClose(); + unmountSvelteComponent(this.content); + this.resolvePromise(this.didSubmit ? this.result : null); + } +}; + +// src/tagEditing.ts +function stripHash(tag2) { + return tag2.replace(/^#+/, ""); +} +function isNestedTag(tag2) { + return stripHash(tag2).includes("/"); +} +function tagLeaf(tag2) { + const body = stripHash(tag2); + return body.split("/").pop() ?? ""; +} +function tagParent(tag2) { + const segments = stripHash(tag2).split("/"); + segments.pop(); + return `#${segments.join("/")}`; +} +function computeTagRewrite(oldTag, input, mode) { + const value = input.trim(); + if (mode === "tracker") { + return value === "" ? "" : `${oldTag}:${value}`; + } + const normalized = stripHash(value); + if (normalized === "") return ""; + if (mode === "leaf") { + return `${tagParent(oldTag)}/${normalized}`; + } + return `#${normalized}`; +} +var TRACKER_VALUE = "[A-Za-z0-9._+-]+"; +function isTrackerToken(token) { + return new RegExp(`^#[^\\s:]+:${TRACKER_VALUE}$`).test(token); +} +function normalizeTagToken(value) { + const trimmed = value.trim(); + if (trimmed === "") return ""; + return `#${trimmed.replace(/^#+/, "")}`; +} +function isValidTagToken(token) { + if (!token.startsWith("#")) return false; + const tracker = token.match(new RegExp(`^(#.+?):${TRACKER_VALUE}$`, "u")); + const body = (tracker ? tracker[1] : token).slice(1); + if (!/^[\p{L}\p{N}_/-]+$/u.test(body)) return false; + return /[^\d/]/u.test(body); +} +function spliceTag(content, position, expectedTag, newToken) { + if (!position) return null; + const { start, end } = position; + if (!Number.isInteger(start) || !Number.isInteger(end)) return null; + if (start < 0 || end > content.length || start >= end) return null; + if (content.slice(start, end) !== expectedTag) return null; + let cutEnd = end; + if (isTrackerToken(newToken)) { + const existingSuffix = content.slice(end).match(new RegExp(`^:${TRACKER_VALUE}`)); + if (existingSuffix) cutEnd = end + existingSuffix[0].length; + } + return content.slice(0, start) + newToken + content.slice(cutEnd); +} +var TAG_FRONTMATTER_KEYS = /* @__PURE__ */ new Set(["tags", "tag"]); +function isTagsKey(key2) { + return !!key2 && TAG_FRONTMATTER_KEYS.has(key2.toLowerCase()); +} +function canonicalizeFrontmatterTag(value) { + return stripHash(value.trim()).trim(); +} +function splitFrontmatterTags(content) { + const items = Array.isArray(content) ? content : [content]; + const out = []; + for (const item of items) { + if (item === null || item === void 0 || typeof item === "object") continue; + for (const token of String(item).split(/[\s,]+/)) { + const tag2 = canonicalizeFrontmatterTag(token); + if (tag2) out.push(tag2); } + } + return out; } -const DEFAULT_SETTINGS = Object.freeze({ - ProgressProperties: { - enabled: false, - properties: [] - }, - IgnoredProperties: { - enabled: false, - properties: [] - }, - AutoProperties: { - enabled: false, - properties: [] - }, - EditMode: { - mode: EditMode.AllSingle, - properties: [], - }, - KanbanHelper: { - enabled: false, - boards: [] - }, - UIElements: { - enabled: true +// src/multiValue.ts +function isMultiValueYamlProperty(property) { + return property.type === 0 /* YAML */ && Array.isArray(property.content); +} +function shouldUseMultiValueEditor(property, editMode) { + if (isMultiValueYamlProperty(property)) return true; + if (property.type === 0 /* YAML */ && isTagsKey(property.key)) return true; + if (editMode.mode === "All Multi" /* AllMulti */) return true; + if (editMode.mode === "Some Multi" /* SomeMulti */ && !!property.key && editMode.properties.includes(property.key)) { + return true; + } + return false; +} +function applyMultiValueEdit(base, edit) { + switch (edit.kind) { + case "addFirst": + return [edit.value]; + case "prepend": + return [edit.value, ...base]; + case "append": + return [...base, edit.value]; + case "replace": { + if (edit.index < 0 || edit.index >= base.length) return [edit.value]; + const next2 = [...base]; + next2[edit.index] = edit.value; + return next2; } + } +} + +// src/Modals/NativePropertyPrompt/NativePropertyPrompt.ts +var import_obsidian14 = require("obsidian"); + +// src/typedProperties/nativePropertyTypes.ts +var STANDARD_NATIVE_PROPERTY_TYPES = [ + "text", + "multitext", + "number", + "checkbox", + "date", + "datetime", + "tags", + "aliases", + "cssclasses" +]; +var NATIVE_TYPE_CHOICES = [ + { type: "text", label: "Text" }, + { type: "multitext", label: "List" }, + { type: "number", label: "Number" }, + { type: "checkbox", label: "Checkbox" }, + { type: "date", label: "Date" }, + { type: "datetime", label: "Date & time" } +]; +var LOCKED_NATIVE_TYPES = /* @__PURE__ */ new Set(["tags", "aliases", "cssclasses"]); +var STANDARD_TYPE_SET = new Set(STANDARD_NATIVE_PROPERTY_TYPES); +var DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +var DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/; +function isNativeEditableYamlProperty(property) { + return property.type === 0 /* YAML */ && !property.path && !property.isNested && !property.isVirtual && !isYamlParentContainerValue(property.content); +} +function resolveNativeProperty(app, property) { + const manager = getMetadataTypeManager2(app); + const widgets = manager?.registeredTypeWidgets; + if (!widgets) { + return { + kind: "fallback", + reason: "Obsidian native property widgets are not available.", + type: "text" + }; + } + const type = resolveNativePropertyType(manager, widgets, property.key, property.content); + const widget = widgets[type]; + if (!widget || typeof widget.render !== "function") { + return { + kind: "fallback", + reason: `Obsidian's native ${type} property widget is not available.`, + type: "text" + }; + } + return { kind: "native", type, widget }; +} +function canAssignVaultPropertyType(app) { + return typeof getMetadataTypeManager2(app)?.setType === "function"; +} +async function assignVaultPropertyType(app, key2, type) { + const manager = getMetadataTypeManager2(app); + if (!manager || typeof manager.setType !== "function") return false; + try { + await manager.setType(key2, type); + return true; + } catch { + return false; + } +} +function getNativeWidgetForType(app, type) { + const widget = getMetadataTypeManager2(app)?.registeredTypeWidgets?.[type]; + return widget && typeof widget.render === "function" ? widget : null; +} +function normalizeWidgetValue(type, value, valueSource) { + if (valueSource === "fallback") { + return { ok: true, value: value === null || value === void 0 ? "" : String(value) }; + } + switch (type) { + case "text": + if (typeof value === "string" || value === null) return { ok: true, value }; + return invalidType(type, "a string or null"); + case "multitext": + case "tags": + case "aliases": + case "cssclasses": + if (typeof value === "string") return { ok: true, value }; + if (Array.isArray(value) && value.every((item) => typeof item === "string")) { + return { ok: true, value }; + } + return invalidType(type, "a string or string array"); + case "number": + if (value === null) return { ok: true, value }; + if (typeof value === "number" && Number.isFinite(value)) return { ok: true, value }; + return invalidType(type, "a finite number or null"); + case "checkbox": + if (typeof value === "boolean") return { ok: true, value }; + return invalidType(type, "a boolean"); + case "date": + if (value === null || value === "") return { ok: true, value }; + if (typeof value === "string" && DATE_RE.test(value)) return { ok: true, value }; + return invalidType(type, "an ISO date string, empty string, or null"); + case "datetime": + if (value === null || value === "") return { ok: true, value }; + if (typeof value === "string" && DATETIME_RE.test(value)) return { ok: true, value }; + return invalidType(type, "an ISO datetime string, empty string, or null"); + } +} +function resolveCreationType(app, key2) { + const manager = getMetadataTypeManager2(app); + const widgets = manager?.registeredTypeWidgets; + if (!manager || !widgets) return "text"; + const normalizedKey = key2.toLowerCase(); + if (isTagsKey(normalizedKey)) return "tags"; + if (normalizedKey === "aliases") return "aliases"; + if (normalizedKey === "cssclasses" && widgets.cssclasses) return "cssclasses"; + const assigned = toStandardType(manager.getAssignedWidget?.(key2), widgets); + if (assigned) return assigned; + const propertyInfoType = toStandardType(readPropertyInfoWidget(manager, key2), widgets); + if (propertyInfoType) return propertyInfoType; + const expectedType = toStandardType(readTypeInfoExpected(manager, key2, void 0), widgets); + if (expectedType) return expectedType; + return "text"; +} +function emptyValueForType(type) { + switch (type) { + case "number": + return null; + case "checkbox": + return false; + case "multitext": + case "tags": + case "aliases": + case "cssclasses": + return []; + case "text": + case "date": + case "datetime": + return ""; + } +} +function inferCreationTypeFromText(rawText, currentType) { + if (currentType !== "text") return null; + const inferred = inferTypeFromText(rawText.trim()); + return inferred && inferred !== currentType ? inferred : null; +} +function seedFromRawText(rawText, nextType) { + const trimmed = rawText.trim(); + switch (nextType) { + case "text": + return rawText; + case "multitext": + case "tags": + case "aliases": + case "cssclasses": + return trimmed === "" ? [] : [trimmed]; + case "number": + return isFiniteNumericString(trimmed) ? Number(trimmed) : null; + case "checkbox": + return trimmed === "true" ? true : false; + case "date": + return isValidIsoDate(trimmed) ? trimmed : ""; + case "datetime": + return isValidIsoDatetime(trimmed) ? trimmed : ""; + } +} +function frontmatterValuesEqual(left, right) { + if (left instanceof Date && right instanceof Date) return left.getTime() === right.getTime(); + if (left instanceof Date || right instanceof Date) return compareDateWithPrimitive(left, right); + if (Array.isArray(left) || Array.isArray(right)) return arraysEqual(left, right); + if (isPlainYamlObject(left) || isPlainYamlObject(right)) return objectsEqual(left, right); + return Object.is(left, right); +} +function resolveNativePropertyType(manager, widgets, key2, value) { + const normalizedKey = key2.toLowerCase(); + if (isTagsKey(normalizedKey)) return "tags"; + if (normalizedKey === "aliases") return "aliases"; + if (normalizedKey === "cssclasses" && widgets.cssclasses) return "cssclasses"; + const assigned = toStandardType(manager.getAssignedWidget?.(key2), widgets); + if (assigned) return assigned; + const propertyInfoWidget = readPropertyInfoWidget(manager, key2); + const propertyInfoType = toStandardType(propertyInfoWidget, widgets); + if (propertyInfoType) return propertyInfoType; + const expected = readTypeInfoExpected(manager, key2, value); + const expectedType = toStandardType(expected, widgets); + if (expectedType) return expectedType; + return inferTypeFromValue(value); +} +function readPropertyInfoWidget(manager, key2) { + try { + const all = manager.getAllProperties?.(); + return all?.[key2]?.widget ?? all?.[key2.toLowerCase()]?.widget; + } catch { + return null; + } +} +function readTypeInfoExpected(manager, key2, value) { + try { + return manager.getTypeInfo?.(key2, value)?.expected?.type ?? manager.getTypeInfo?.(key2)?.expected?.type; + } catch { + return null; + } +} +function toStandardType(value, widgets) { + if (typeof value !== "string") return null; + if (!STANDARD_TYPE_SET.has(value)) return null; + if (value === "cssclasses" && !widgets.cssclasses) return null; + return value; +} +function inferTypeFromValue(value) { + if (Array.isArray(value)) return "multitext"; + if (typeof value === "boolean") return "checkbox"; + if (typeof value === "number" && Number.isFinite(value)) return "number"; + if (value instanceof Date) return hasDateTime(value) ? "datetime" : "date"; + if (typeof value === "string") { + if (DATETIME_RE.test(value)) return "datetime"; + if (DATE_RE.test(value)) return "date"; + } + return "text"; +} +function hasDateTime(value) { + return value.getUTCHours() !== 0 || value.getUTCMinutes() !== 0 || value.getUTCSeconds() !== 0 || value.getUTCMilliseconds() !== 0; +} +var NUMERIC_RE = /^-?(?:\d+\.?\d*|\.\d+)$/; +function isFiniteNumericString(text2) { + if (!NUMERIC_RE.test(text2)) return false; + return Number.isFinite(Number(text2)); +} +function isValidIsoDate(value) { + if (!DATE_RE.test(value)) return false; + const year = Number(value.slice(0, 4)); + const month = Number(value.slice(5, 7)); + const day = Number(value.slice(8, 10)); + const date = new Date(Date.UTC(year, month - 1, day)); + return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day; +} +function isValidIsoDatetime(value) { + if (!DATETIME_RE.test(value)) return false; + if (!isValidIsoDate(value.slice(0, 10))) return false; + const hour = Number(value.slice(11, 13)); + const minute = Number(value.slice(14, 16)); + const second = value.length > 16 ? Number(value.slice(17, 19)) : 0; + return hour <= 23 && minute <= 59 && second <= 59; +} +function inferTypeFromText(text2) { + if (text2 === "") return null; + if (isValidIsoDatetime(text2)) return "datetime"; + if (isValidIsoDate(text2)) return "date"; + if (text2 === "true" || text2 === "false") return "checkbox"; + if (/^0\d/.test(text2)) return null; + if (isFiniteNumericString(text2)) return "number"; + return null; +} +function invalidType(type, expected) { + return { + ok: false, + reason: `Obsidian's native ${type} editor returned an unsupported value shape; expected ${expected}.` + }; +} +function arraysEqual(left, right) { + if (!Array.isArray(left) || !Array.isArray(right)) return false; + if (left.length !== right.length) return false; + return left.every((value, index2) => frontmatterValuesEqual(value, right[index2])); +} +function objectsEqual(left, right) { + if (!isPlainYamlObject(left) || !isPlainYamlObject(right)) return false; + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + if (leftKeys.length !== rightKeys.length) return false; + return leftKeys.every( + (key2) => Object.prototype.hasOwnProperty.call(right, key2) && frontmatterValuesEqual(left[key2], right[key2]) + ); +} +function compareDateWithPrimitive(left, right) { + const date = left instanceof Date ? left : right instanceof Date ? right : null; + const other = left instanceof Date ? right : left; + if (!date || typeof other !== "string") return false; + if (DATE_RE.test(other)) return date.toISOString().slice(0, 10) === other; + if (DATETIME_RE.test(other)) return date.toISOString().replace(/\.\d{3}Z$/, "").startsWith(other); + return false; +} +function getMetadataTypeManager2(app) { + return app.metadataTypeManager ?? null; +} + +// src/Modals/NativeWidgetHost.ts +var import_obsidian12 = require("obsidian"); + +// src/Modals/NativePropertyPrompt/nativeWikilinkSuggester.ts +var import_obsidian11 = require("obsidian"); +var WIKILINK_QUERY = /\[\[([^\]]*)$/; +var NativeWikilinkSuggester = class extends import_obsidian11.AbstractInputSuggest { + constructor(app, inputEl, sourcePath) { + const mirrorHost = inputEl.parentElement ?? inputEl; + const mirrorEl = mirrorHost.createEl("input", { + cls: "metaedit-native-wikilink-suggest-mirror", + type: "text" + }); + super(app, mirrorEl); + this.inputEl = inputEl; + this.sourcePath = sourcePath; + this.onInput = () => this.refreshFromContent(); + this.mirrorEl = mirrorEl; + this.mirrorEl.tabIndex = -1; + this.mirrorEl.setAttribute("aria-hidden", "true"); + this.inputEl.addEventListener("input", this.onInput); + this.inputEl.addEventListener("keyup", this.onInput); + this.onSelect((suggestion) => this.acceptSuggestion(suggestion)); + } + getSuggestions(query) { + const normalized = query.toLowerCase(); + return this.readLinkSuggestions().filter((suggestion) => { + const path = suggestion.path ?? suggestion.file?.basename ?? ""; + const alias = suggestion.alias ?? ""; + return path.toLowerCase().includes(normalized) || alias.toLowerCase().includes(normalized); + }).slice(0, 50); + } + renderSuggestion(value, el) { + const label = value.alias ?? value.path ?? value.file?.basename ?? value.file?.path ?? ""; + el.setText(label); + } + selectSuggestion(value, _evt) { + this.acceptSuggestion(value); + } + destroy() { + this.inputEl.removeEventListener("input", this.onInput); + this.inputEl.removeEventListener("keyup", this.onInput); + this.close(); + this.mirrorEl.remove(); + } + refreshFromContent() { + const match = this.currentQuery(); + if (!match) { + this.close(); + return; + } + this.mirrorEl.value = match.query; + this.mirrorEl.focus(); + this.mirrorEl.trigger("input"); + } + currentQuery() { + const text2 = this.inputEl.textContent ?? ""; + const match = text2.match(WIKILINK_QUERY); + if (!match) return null; + return { query: match[1] ?? "" }; + } + acceptSuggestion(suggestion) { + if (!suggestion.file) return; + const link2 = this.app.fileManager.generateMarkdownLink( + suggestion.file, + this.sourcePath, + "", + suggestion.alias + ); + this.inputEl.textContent = link2; + this.inputEl.focus(); + this.inputEl.trigger("input"); + this.close(); + } + readLinkSuggestions() { + const metadataCache = this.app.metadataCache; + const suggestions = metadataCache.getLinkSuggestions?.() ?? []; + return suggestions.filter((suggestion) => suggestion.file); + } +}; + +// src/Modals/NativeWidgetHost.ts +var BODY_PORTAL_SELECTOR = ".suggestion-container, .popover, .hover-popover"; +var EDITING_KEYS = /* @__PURE__ */ new Set([ + "Backspace", + "Delete", + "Enter", + "Spacebar", + " " +]); +var NativeWidgetHost = class { + constructor(options) { + this.widgetInstance = null; + this.preMountBodyChildren = /* @__PURE__ */ new Set(); + this.perMountCleanup = []; + this.typeInternal = "text"; + this.valueSourceInternal = "native"; + this.didReceiveChangeInternal = false; + this.didEditDomInternal = false; + this.renderFailedInternal = false; + this.app = options.app; + this.hostEl = options.hostEl; + this.sourcePath = options.sourcePath; + this.key = options.key; + this.onChangeCallback = options.onChange; + } + get value() { + return this.lastValueInternal; + } + get type() { + return this.typeInternal; + } + get valueSource() { + return this.valueSourceInternal; + } + get didReceiveChange() { + return this.didReceiveChangeInternal; + } + get didEditDom() { + return this.didEditDomInternal; + } + get renderFailed() { + return this.renderFailedInternal; + } + setKey(key2) { + this.key = key2; + } + /** + * Mount `type`'s native widget seeded with `value`, tearing down any currently + * mounted widget first. Falls back to a plain text input when the native widget + * is unavailable. `lastValue` starts at the seed so an untouched widget commits + * exactly what was mounted. + */ + mountNative(type, value) { + const widget = getNativeWidgetForType(this.app, type); + if (!widget) { + this.mountFallback(`Obsidian's native ${type} property widget is not available.`, value); + this.typeInternal = type; + return; + } + this.beginMount(type, value, "native"); + try { + this.widgetInstance = widget.render?.(this.hostEl, value, { + app: this.app, + key: this.key, + sourcePath: this.sourcePath, + onChange: (changed) => { + this.lastValueInternal = changed; + this.didReceiveChangeInternal = true; + this.onChangeCallback?.(changed); + }, + blur: () => void 0 + }); + this.installAliasesWikilinkFallback(type); + } catch (error) { + this.handleRenderFailure(type, error, widget); + } + } + /** Mount a plain text input (native widgets unavailable, or a render failure fallback). */ + mountFallback(reason, value) { + this.beginMount("text", value, "fallback"); + this.hostEl.createDiv({ + cls: "metaedit-native-property-fallback-note", + text: reason + }); + const inputEl = this.hostEl.createEl("input", { + cls: "metadata-input metadata-input-text metaedit-native-property-fallback-input", + type: "text" + }); + inputEl.value = value === null || value === void 0 ? "" : String(value); + const onInput = () => { + this.lastValueInternal = inputEl.value; + this.didReceiveChangeInternal = true; + this.onChangeCallback?.(inputEl.value); + }; + inputEl.addEventListener("input", onInput); + this.perMountCleanup.push(() => inputEl.removeEventListener("input", onInput)); + } + focus() { + const focusable = this.hostEl.querySelector( + "input, textarea, [contenteditable='true'], select, button" + ); + if (!focusable) return; + focusable.focus(); + if (focusable instanceof HTMLInputElement && focusable.type === "text") focusable.select(); + } + /** Blur the focused editor if it lives in this host, so a pending edit flushes to onChange before submit. */ + flushFocus() { + const active = activeDocument.activeElement; + if (active instanceof HTMLElement && this.hostEl.contains(active)) { + active.blur(); + } + } + /** + * Whether the mounted editor is a genuinely single-line control (a real + * ``/`