From 9ca0bf1a0e237716143545f3cf22550666ac75dc Mon Sep 17 00:00:00 2001 From: SVM0N <61781578+SVM0N@users.noreply.github.com> Date: Sat, 18 Jul 2026 13:30:02 +0800 Subject: [PATCH] =?UTF-8?q?chore(release):=20v1.7.1=20=E2=80=94=20communit?= =?UTF-8?q?y-plugin=20review=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the automated review's warnings: !important overrides resolved via higher-specificity selectors (a handful of legitimate overrides of Obsidian's own core .modal chrome are kept, since they guard against unowned CSS loaded after the plugin), a :has() selector replaced with a JS-toggled class, duplicate-property fallback chains rewritten with @supports, TFile casts routed through an instanceof fast path, and a couple of narrow, justified exceptions left as-is (a proper-noun tooltip, a createEl helper that isn't stubbed in the test harness). Bumped the obsidian devDependency to pick up current types along the way. Co-Authored-By: Claude Sonnet 5 --- main.js | 28 ++++++------ manifest.json | 2 +- package-lock.json | 27 ++++++++--- package.json | 4 +- src/chart-block.ts | 11 +++-- src/inline-view.ts | 10 +++-- src/random-block.ts | 14 +++--- src/tasks-block.ts | 6 ++- src/utils.ts | 12 +++++ src/view/chart.ts | 4 ++ src/view/toolbar.ts | 12 ++++- styles.css | 107 +++++++++++++++++++++++++++++--------------- versions.json | 3 +- 13 files changed, 164 insertions(+), 76 deletions(-) diff --git a/main.js b/main.js index df668a2..498f135 100644 --- a/main.js +++ b/main.js @@ -1,25 +1,25 @@ -"use strict";var Dl=Object.create;var Vs=Object.defineProperty;var Tl=Object.getOwnPropertyDescriptor;var Al=Object.getOwnPropertyNames;var Rl=Object.getPrototypeOf,Pl=Object.prototype.hasOwnProperty;var Ol=(s,t,e)=>t in s?Vs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var En=(s,t)=>()=>(s&&(t=s(s=0)),t);var Fl=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),tr=(s,t)=>{for(var e in t)Vs(s,e,{get:t[e],enumerable:!0})},er=(s,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Al(t))!Pl.call(s,n)&&n!==e&&Vs(s,n,{get:()=>t[n],enumerable:!(i=Tl(t,n))||i.enumerable});return s};var Ns=(s,t,e)=>(e=s!=null?Dl(Rl(s)):{},er(t||!s||!s.__esModule?Vs(e,"default",{value:s,enumerable:!0}):e,s)),Il=s=>er(Vs({},"__esModule",{value:!0}),s);var Y=(s,t,e)=>(Ol(s,typeof t!="symbol"?t+"":t,e),e);var is=Fl((Mn,wn)=>{((s,t)=>{typeof define=="function"&&define.amd?define([],t):typeof wn=="object"&&typeof Mn!="undefined"?wn.exports=t():s.Papa=t()})(Mn,function s(){var t=typeof self!="undefined"?self:typeof window!="undefined"?window:t!==void 0?t:{},e,i=!t.document&&!!t.postMessage,n=t.IS_PAPA_WORKER||!1,o={},r=0,a={};function L(y){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},function(v){var x=C(v);x.chunkSize=parseInt(x.chunkSize),v.step||v.chunk||(x.chunkSize=null),this._handle=new u(x),(this._handle.streamer=this)._config=x}.call(this,y),this.parseChunk=function(v,x){var k=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview),n)t.postMessage({results:E,workerId:a.WORKER_ID,finished:k});else if(_(this._config.chunk)&&!x){if(this._config.chunk(E,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=E=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(E.data),this._completeResults.errors=this._completeResults.errors.concat(E.errors),this._completeResults.meta=E.meta),this._completed||!k||!_(this._config.complete)||E&&E.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),k||E&&E.meta.paused||this._nextChunk(),E}this._halted=!0},this._sendError=function(v){_(this._config.error)?this._config.error(v):n&&this._config.error&&t.postMessage({workerId:a.WORKER_ID,error:v,finished:!1})}}function l(y){var v;(y=y||{}).chunkSize||(y.chunkSize=a.RemoteChunkSize),L.call(this,y),this._nextChunk=i?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(x){this._input=x,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(v=new XMLHttpRequest,this._config.withCredentials&&(v.withCredentials=this._config.withCredentials),i||(v.onload=S(this._chunkLoaded,this),v.onerror=S(this._chunkError,this)),v.open(this._config.downloadRequestBody?"POST":"GET",this._input,!i),this._config.downloadRequestHeaders){var x,k=this._config.downloadRequestHeaders;for(x in k)v.setRequestHeader(x,k[x])}var E;this._config.chunkSize&&(E=this._start+this._config.chunkSize-1,v.setRequestHeader("Range","bytes="+this._start+"-"+E));try{v.send(this._config.downloadRequestBody)}catch(M){this._chunkError(M.message)}i&&v.status===0&&this._chunkError()}},this._chunkLoaded=function(){v.readyState===4&&(v.status<200||400<=v.status?this._chunkError():(this._start+=this._config.chunkSize||v.responseText.length,this._finished=!this._config.chunkSize||this._start>=(x=>(x=x.getResponseHeader("Content-Range"))!==null?parseInt(x.substring(x.lastIndexOf("/")+1)):-1)(v),this.parseChunk(v.responseText)))},this._chunkError=function(x){x=v.statusText||x,this._sendError(new Error(x))}}function c(y){(y=y||{}).chunkSize||(y.chunkSize=a.LocalChunkSize),L.call(this,y);var v,x,k=typeof FileReader!="undefined";this.stream=function(E){this._input=E,x=E.slice||E.webkitSlice||E.mozSlice,k?((v=new FileReader).onload=S(this._chunkLoaded,this),v.onerror=S(this._chunkError,this)):v=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(E.target.result)},this._chunkError=function(){this._sendError(v.error)}}function d(y){var v;L.call(this,y=y||{}),this.stream=function(x){return v=x,this._nextChunk()},this._nextChunk=function(){var x,k;if(!this._finished)return x=this._config.chunkSize,v=x?(k=v.substring(0,x),v.substring(x)):(k=v,""),this._finished=!v,this.parseChunk(k)}}function h(y){L.call(this,y=y||{});var v=[],x=!0,k=!1;this.pause=function(){L.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){L.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(E){this._input=E,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){k&&v.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),v.length?this.parseChunk(v.shift()):x=!0},this._streamData=S(function(E){try{v.push(typeof E=="string"?E:E.toString(this._config.encoding)),x&&(x=!1,this._checkIsFinished(),this.parseChunk(v.shift()))}catch(M){this._streamError(M)}},this),this._streamError=S(function(E){this._streamCleanUp(),this._sendError(E)},this),this._streamEnd=S(function(){this._streamCleanUp(),k=!0,this._streamData("")},this),this._streamCleanUp=S(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function u(y){var v,x,k,E,M=Math.pow(2,53),D=-M,A=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,N=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,I=this,P=0,w=0,U=!1,O=!1,Z=[],B={data:[],errors:[],meta:{}};function G(T){return y.skipEmptyLines==="greedy"?T.join("").trim()==="":T.length===1&&T[0].length===0}function R(){if(B&&k&&(K("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),k=!1),y.skipEmptyLines&&(B.data=B.data.filter(function(z){return!G(z)})),W()){let z=function(V,j){_(y.transformHeader)&&(V=y.transformHeader(V,j)),Z.push(V)};var $=z;if(B)if(Array.isArray(B.data[0])){for(var T=0;W()&&T(J=>(y.dynamicTypingFunction&&y.dynamicTyping[J]===void 0&&(y.dynamicTyping[J]=y.dynamicTypingFunction(J)),(y.dynamicTyping[J]||y.dynamicTyping)===!0))(Q)?et==="true"||et==="TRUE"||et!=="false"&&et!=="FALSE"&&((J=>{if(A.test(J)&&(J=parseFloat(J),D=Z.length?"__parsed_extra":Z[X]:q,nt=y.transform?y.transform(nt,q):nt);q==="__parsed_extra"?(j[q]=j[q]||[],j[q].push(nt)):j[q]=nt}return y.header&&(X>Z.length?K("FieldMismatch","TooManyFields","Too many fields: expected "+Z.length+" fields but parsed "+X,w+V):Xy.preview?x.abort():(B.data=B.data[0],E(B,I))))}),this.parse=function(T,F,H){var $=y.quoteChar||'"',$=(y.newline||(y.newline=this.guessLineEndings(T,$)),k=!1,y.delimiter?_(y.delimiter)&&(y.delimiter=y.delimiter(T),B.meta.delimiter=y.delimiter):(($=((z,V,j,X,q)=>{var nt,Q,et,J;q=q||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var ot=0;ott in s?Vs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Mn=(s,t)=>()=>(s&&(t=s(s=0)),t);var Vl=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),sr=(s,t)=>{for(var e in t)Vs(s,e,{get:t[e],enumerable:!0})},ir=(s,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Pl(t))!Fl.call(s,n)&&n!==e&&Vs(s,n,{get:()=>t[n],enumerable:!(i=Rl(t,n))||i.enumerable});return s};var Ns=(s,t,e)=>(e=s!=null?Al(Ol(s)):{},ir(t||!s||!s.__esModule?Vs(e,"default",{value:s,enumerable:!0}):e,s)),Nl=s=>ir(Vs({},"__esModule",{value:!0}),s);var Y=(s,t,e)=>(Il(s,typeof t!="symbol"?t+"":t,e),e);var is=Vl((wn,Dn)=>{((s,t)=>{typeof define=="function"&&define.amd?define([],t):typeof Dn=="object"&&typeof wn!="undefined"?Dn.exports=t():s.Papa=t()})(wn,function s(){var t=typeof self!="undefined"?self:typeof window!="undefined"?window:t!==void 0?t:{},e,i=!t.document&&!!t.postMessage,n=t.IS_PAPA_WORKER||!1,o={},r=0,a={};function L(y){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},function(v){var x=C(v);x.chunkSize=parseInt(x.chunkSize),v.step||v.chunk||(x.chunkSize=null),this._handle=new u(x),(this._handle.streamer=this)._config=x}.call(this,y),this.parseChunk=function(v,x){var k=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview),n)t.postMessage({results:E,workerId:a.WORKER_ID,finished:k});else if(_(this._config.chunk)&&!x){if(this._config.chunk(E,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=E=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(E.data),this._completeResults.errors=this._completeResults.errors.concat(E.errors),this._completeResults.meta=E.meta),this._completed||!k||!_(this._config.complete)||E&&E.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),k||E&&E.meta.paused||this._nextChunk(),E}this._halted=!0},this._sendError=function(v){_(this._config.error)?this._config.error(v):n&&this._config.error&&t.postMessage({workerId:a.WORKER_ID,error:v,finished:!1})}}function l(y){var v;(y=y||{}).chunkSize||(y.chunkSize=a.RemoteChunkSize),L.call(this,y),this._nextChunk=i?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(x){this._input=x,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(v=new XMLHttpRequest,this._config.withCredentials&&(v.withCredentials=this._config.withCredentials),i||(v.onload=S(this._chunkLoaded,this),v.onerror=S(this._chunkError,this)),v.open(this._config.downloadRequestBody?"POST":"GET",this._input,!i),this._config.downloadRequestHeaders){var x,k=this._config.downloadRequestHeaders;for(x in k)v.setRequestHeader(x,k[x])}var E;this._config.chunkSize&&(E=this._start+this._config.chunkSize-1,v.setRequestHeader("Range","bytes="+this._start+"-"+E));try{v.send(this._config.downloadRequestBody)}catch(M){this._chunkError(M.message)}i&&v.status===0&&this._chunkError()}},this._chunkLoaded=function(){v.readyState===4&&(v.status<200||400<=v.status?this._chunkError():(this._start+=this._config.chunkSize||v.responseText.length,this._finished=!this._config.chunkSize||this._start>=(x=>(x=x.getResponseHeader("Content-Range"))!==null?parseInt(x.substring(x.lastIndexOf("/")+1)):-1)(v),this.parseChunk(v.responseText)))},this._chunkError=function(x){x=v.statusText||x,this._sendError(new Error(x))}}function c(y){(y=y||{}).chunkSize||(y.chunkSize=a.LocalChunkSize),L.call(this,y);var v,x,k=typeof FileReader!="undefined";this.stream=function(E){this._input=E,x=E.slice||E.webkitSlice||E.mozSlice,k?((v=new FileReader).onload=S(this._chunkLoaded,this),v.onerror=S(this._chunkError,this)):v=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(E.target.result)},this._chunkError=function(){this._sendError(v.error)}}function d(y){var v;L.call(this,y=y||{}),this.stream=function(x){return v=x,this._nextChunk()},this._nextChunk=function(){var x,k;if(!this._finished)return x=this._config.chunkSize,v=x?(k=v.substring(0,x),v.substring(x)):(k=v,""),this._finished=!v,this.parseChunk(k)}}function h(y){L.call(this,y=y||{});var v=[],x=!0,k=!1;this.pause=function(){L.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){L.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(E){this._input=E,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){k&&v.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),v.length?this.parseChunk(v.shift()):x=!0},this._streamData=S(function(E){try{v.push(typeof E=="string"?E:E.toString(this._config.encoding)),x&&(x=!1,this._checkIsFinished(),this.parseChunk(v.shift()))}catch(M){this._streamError(M)}},this),this._streamError=S(function(E){this._streamCleanUp(),this._sendError(E)},this),this._streamEnd=S(function(){this._streamCleanUp(),k=!0,this._streamData("")},this),this._streamCleanUp=S(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function u(y){var v,x,k,E,M=Math.pow(2,53),D=-M,A=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,N=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,I=this,P=0,w=0,U=!1,O=!1,Z=[],B={data:[],errors:[],meta:{}};function G(T){return y.skipEmptyLines==="greedy"?T.join("").trim()==="":T.length===1&&T[0].length===0}function R(){if(B&&k&&(K("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),k=!1),y.skipEmptyLines&&(B.data=B.data.filter(function(z){return!G(z)})),W()){let z=function(V,j){_(y.transformHeader)&&(V=y.transformHeader(V,j)),Z.push(V)};var $=z;if(B)if(Array.isArray(B.data[0])){for(var T=0;W()&&T(J=>(y.dynamicTypingFunction&&y.dynamicTyping[J]===void 0&&(y.dynamicTyping[J]=y.dynamicTypingFunction(J)),(y.dynamicTyping[J]||y.dynamicTyping)===!0))(Q)?et==="true"||et==="TRUE"||et!=="false"&&et!=="FALSE"&&((J=>{if(A.test(J)&&(J=parseFloat(J),D=Z.length?"__parsed_extra":Z[X]:q,nt=y.transform?y.transform(nt,q):nt);q==="__parsed_extra"?(j[q]=j[q]||[],j[q].push(nt)):j[q]=nt}return y.header&&(X>Z.length?K("FieldMismatch","TooManyFields","Too many fields: expected "+Z.length+" fields but parsed "+X,w+V):Xy.preview?x.abort():(B.data=B.data[0],E(B,I))))}),this.parse=function(T,F,H){var $=y.quoteChar||'"',$=(y.newline||(y.newline=this.guessLineEndings(T,$)),k=!1,y.delimiter?_(y.delimiter)&&(y.delimiter=y.delimiter(T),B.meta.delimiter=y.delimiter):(($=((z,V,j,X,q)=>{var nt,Q,et,J;q=q||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var ot=0;ot=H.length/2?`\r `:"\r"}}function f(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function g(y){var v=(y=y||{}).delimiter,x=y.newline,k=y.comments,E=y.step,M=y.preview,D=y.fastMode,A=null,N=!1,I=y.quoteChar==null?'"':y.quoteChar,P=I;if(y.escapeChar!==void 0&&(P=y.escapeChar),(typeof v!="string"||-1=M)return St(!0);break}H.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:F.length,index:w}),Q++}}else if(k&&$.length===0&&O.substring(w,w+K)===k){if(q===-1)return St();w=q+W,q=O.indexOf(x,w),X=O.indexOf(v,w)}else if(X!==-1&&(X=M)return St(!0)}return lt();function J(bt){F.push(bt),z=w}function ot(bt){var wt=0;return wt=bt!==-1&&(bt=O.substring(Q+1,bt))&&bt.trim()===""?bt.length:wt}function lt(bt){return B||(bt===void 0&&(bt=O.substring(w)),$.push(bt),w=G,J($),T&&Gt()),St()}function Bt(bt){w=bt,J($),$=[],q=O.indexOf(x,w)}function St(bt){if(y.header&&!Z&&F.length&&!N){var wt=F[0],ae=Object.create(null),kn=new Set(wt);let Qo=!1;for(let ss=0;ssk.charCodeAt(0)!==65279?k:k.slice(1))(y),x=new(v.download?l:d)(v)):y.readable===!0&&_(y.read)&&_(y.on)?x=new h(v):(t.File&&y instanceof File||y instanceof Object)&&(x=new c(v)),x.stream(y);(x=(()=>{var k;return!!a.WORKERS_SUPPORTED&&(k=(()=>{var E=t.URL||t.webkitURL||null,M=s.toString();return a.BLOB_URL||(a.BLOB_URL=E.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",M,")();"],{type:"text/javascript"})))})(),(k=new t.Worker(k)).onmessage=m,k.id=r++,o[k.id]=k)})()).userStep=v.step,x.userChunk=v.chunk,x.userComplete=v.complete,x.userError=v.error,v.step=_(v.step),v.chunk=_(v.chunk),v.complete=_(v.complete),v.error=_(v.error),delete v.worker,x.postMessage({input:y,config:v,workerId:x.id})},a.unparse=function(y,v){var x=!1,k=!0,E=",",M=`\r +`);var w=0,U=!1;this.parse=function(O,Z,B){if(typeof O!="string")throw new Error("Input must be a string");var G=O.length,R=v.length,W=x.length,K=k.length,T=_(E),F=[],H=[],$=[],z=w=0;if(!O)return St();if(D||D!==!1&&O.indexOf(I)===-1){for(var V=O.split(x),j=0;j=M)return St(!0);break}H.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:F.length,index:w}),Q++}}else if(k&&$.length===0&&O.substring(w,w+K)===k){if(q===-1)return St();w=q+W,q=O.indexOf(x,w),X=O.indexOf(v,w)}else if(X!==-1&&(X=M)return St(!0)}return lt();function J(bt){F.push(bt),z=w}function ot(bt){var Dt=0;return Dt=bt!==-1&&(bt=O.substring(Q+1,bt))&&bt.trim()===""?bt.length:Dt}function lt(bt){return B||(bt===void 0&&(bt=O.substring(w)),$.push(bt),w=G,J($),T&&Kt()),St()}function Bt(bt){w=bt,J($),$=[],q=O.indexOf(x,w)}function St(bt){if(y.header&&!Z&&F.length&&!N){var Dt=F[0],ae=Object.create(null),En=new Set(Dt);let tr=!1;for(let ss=0;ssk.charCodeAt(0)!==65279?k:k.slice(1))(y),x=new(v.download?l:d)(v)):y.readable===!0&&_(y.read)&&_(y.on)?x=new h(v):(t.File&&y instanceof File||y instanceof Object)&&(x=new c(v)),x.stream(y);(x=(()=>{var k;return!!a.WORKERS_SUPPORTED&&(k=(()=>{var E=t.URL||t.webkitURL||null,M=s.toString();return a.BLOB_URL||(a.BLOB_URL=E.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",M,")();"],{type:"text/javascript"})))})(),(k=new t.Worker(k)).onmessage=m,k.id=r++,o[k.id]=k)})()).userStep=v.step,x.userChunk=v.chunk,x.userComplete=v.complete,x.userError=v.error,v.step=_(v.step),v.chunk=_(v.chunk),v.complete=_(v.complete),v.error=_(v.error),delete v.worker,x.postMessage({input:y,config:v,workerId:x.id})},a.unparse=function(y,v){var x=!1,k=!0,E=",",M=`\r `,D='"',A=D+D,N=!1,I=null,P=!1,w=((()=>{if(typeof v=="object"){if(typeof v.delimiter!="string"||a.BAD_DELIMITERS.filter(function(Z){return v.delimiter.indexOf(Z)!==-1}).length||(E=v.delimiter),typeof v.quotes!="boolean"&&typeof v.quotes!="function"&&!Array.isArray(v.quotes)||(x=v.quotes),typeof v.skipEmptyLines!="boolean"&&typeof v.skipEmptyLines!="string"||(N=v.skipEmptyLines),typeof v.newline=="string"&&(M=v.newline),typeof v.quoteChar=="string"&&(D=v.quoteChar),typeof v.header=="boolean"&&(k=v.header),Array.isArray(v.columns)){if(v.columns.length===0)throw new Error("Option columns is empty");I=v.columns}v.escapeChar!==void 0&&(A=v.escapeChar+D),v.escapeFormulae instanceof RegExp?P=v.escapeFormulae:typeof v.escapeFormulae=="boolean"&&v.escapeFormulae&&(P=/^[=+\-@\t\r].*$/)}})(),new RegExp(f(D),"g"));if(typeof y=="string"&&(y=JSON.parse(y)),Array.isArray(y)){if(!y.length||Array.isArray(y[0]))return U(null,y,N);if(typeof y[0]=="object")return U(I||Object.keys(y[0]),y,N)}else if(typeof y=="object")return typeof y.data=="string"&&(y.data=JSON.parse(y.data)),Array.isArray(y.data)&&(y.fields||(y.fields=y.meta&&y.meta.fields||I),y.fields||(y.fields=Array.isArray(y.data[0])?y.fields:typeof y.data[0]=="object"?Object.keys(y.data[0]):[]),Array.isArray(y.data[0])||typeof y.data[0]=="object"||(y.data=[y.data])),U(y.fields||[],y.data||[],N);throw new Error("Unable to serialize unrecognized input");function U(Z,B,G){var R="",W=(typeof Z=="string"&&(Z=JSON.parse(Z)),typeof B=="string"&&(B=JSON.parse(B)),Array.isArray(Z)&&0{for(var T=0;Te-i*Math.max(Math.min(r-3,9-r,1),-1);return[n(0),n(8),n(4)]}function gc(s,t,e){let i=(n,o=(n+s/60)%6)=>e-e*t*Math.max(Math.min(o,4-o,1),0);return[i(5),i(3),i(1)]}function mc(s,t,e){let i=Ar(s,1,.5),n;for(t+e>1&&(n=1/(t+e),t*=n,e*=n),n=0;n<3;n++)i[n]*=1-t-e,i[n]+=t;return i}function bc(s,t,e,i,n){return s===n?(t-e)/i+(t.5?c/(2-o-r):c/(o+r),L=bc(e,i,n,c,o),L=L*60+.5),[L|0,l||0,a]}function Bn(s,t,e,i){return(Array.isArray(t)?s(t[0],t[1],t[2]):s(t,e,i)).map(xe)}function $n(s,t,e){return Bn(Ar,s,t,e)}function vc(s,t,e){return Bn(mc,s,t,e)}function yc(s,t,e){return Bn(gc,s,t,e)}function Rr(s){return(s%360+360)%360}function xc(s){let t=pc.exec(s),e=255,i;if(!t)return;t[5]!==i&&(e=t[6]?js(+t[5]):xe(+t[5]));let n=Rr(+t[2]),o=+t[3]/100,r=+t[4]/100;return t[1]==="hwb"?i=vc(n,o,r):t[1]==="hsv"?i=yc(n,o,r):i=$n(n,o,r),{r:i[0],g:i[1],b:i[2],a:e}}function Cc(s,t){var e=Nn(s);e[0]=Rr(e[0]+t),e=$n(e),s.r=e[0],s.g=e[1],s.b=e[2]}function _c(s){if(!s)return;let t=Nn(s),e=t[0],i=Mr(t[1]),n=Mr(t[2]);return s.a<255?`hsla(${e}, ${i}%, ${n}%, ${Le(s.a)})`:`hsl(${e}, ${i}%, ${n}%)`}function Sc(){let s={},t=Object.keys(Dr),e=Object.keys(wr),i,n,o,r,a;for(i=0;i>16&255,o>>8&255,o&255]}return s}function kc(s){wi||(wi=Sc(),wi.transparent=[0,0,0,0]);let t=wi[s.toLowerCase()];return t&&{r:t[0],g:t[1],b:t[2],a:t.length===4?t[3]:255}}function Mc(s){let t=Ec.exec(s),e=255,i,n,o;if(t){if(t[7]!==i){let r=+t[7];e=t[8]?js(r):ye(r*255,0,255)}return i=+t[1],n=+t[3],o=+t[5],i=255&(t[2]?js(i):ye(i,0,255)),n=255&(t[4]?js(n):ye(n,0,255)),o=255&(t[6]?js(o):ye(o,0,255)),{r:i,g:n,b:o,a:e}}}function wc(s){return s&&(s.a<255?`rgba(${s.r}, ${s.g}, ${s.b}, ${Le(s.a)})`:`rgb(${s.r}, ${s.g}, ${s.b})`)}function Dc(s,t,e){let i=hs(Le(s.r)),n=hs(Le(s.g)),o=hs(Le(s.b));return{r:xe(In(i+e*(hs(Le(t.r))-i))),g:xe(In(n+e*(hs(Le(t.g))-n))),b:xe(In(o+e*(hs(Le(t.b))-o))),a:s.a+e*(t.a-s.a)}}function Di(s,t,e){if(s){let i=Nn(s);i[t]=Math.max(0,Math.min(i[t]+i[t]*e,t===0?360:1)),i=$n(i),s.r=i[0],s.g=i[1],s.b=i[2]}}function Pr(s,t){return s&&Object.assign(t||{},s)}function Tr(s){var t={r:0,g:0,b:0,a:255};return Array.isArray(s)?s.length>=3&&(t={r:s[0],g:s[1],b:s[2],a:255},s.length>3&&(t.a=xe(s[3]))):(t=Pr(s,{r:0,g:0,b:0,a:1}),t.a=xe(t.a)),t}function Tc(s){return s.charAt(0)==="r"?Mc(s):xc(s)}var ye,Ht,Vn,lc,cc,Mi,dc,uc,pc,wr,Dr,wi,Ec,In,hs,Us,Or=En(()=>{ye=(s,t,e)=>Math.max(Math.min(s,e),t);Ht={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Vn=[..."0123456789ABCDEF"],lc=s=>Vn[s&15],cc=s=>Vn[(s&240)>>4]+Vn[s&15],Mi=s=>(s&240)>>4===(s&15),dc=s=>Mi(s.r)&&Mi(s.g)&&Mi(s.b)&&Mi(s.a);uc=(s,t)=>s<255?t(s):"";pc=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;wr={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Dr={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};Ec=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;In=s=>s<=.0031308?s*12.92:Math.pow(s,1/2.4)*1.055-.055,hs=s=>s<=.04045?s/12.92:Math.pow((s+.055)/1.055,2.4);Us=class s{constructor(t){if(t instanceof s)return t;let e=typeof t,i;e==="object"?i=Tr(t):e==="string"&&(i=hc(t)||kc(t)||Tc(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=Pr(this._rgb);return t&&(t.a=Le(t.a)),t}set rgb(t){this._rgb=Tr(t)}rgbString(){return this._valid?wc(this._rgb):void 0}hexString(){return this._valid?fc(this._rgb):void 0}hslString(){return this._valid?_c(this._rgb):void 0}mix(t,e){if(t){let i=this.rgb,n=t.rgb,o,r=e===o?.5:e,a=2*r-1,L=i.a-n.a,l=((a*L===-1?a:(a+L)/(1+a*L))+1)/2;o=1-l,i.r=255&l*i.r+o*n.r+.5,i.g=255&l*i.g+o*n.g+.5,i.b=255&l*i.b+o*n.b+.5,i.a=r*i.a+(1-r)*n.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=Dc(this._rgb,t._rgb,e)),this}clone(){return new s(this.rgb)}alpha(t){return this._rgb.a=xe(t),this}clearer(t){let e=this._rgb;return e.a*=1-t,this}greyscale(){let t=this._rgb,e=Ys(t.r*.3+t.g*.59+t.b*.11);return t.r=t.g=t.b=e,this}opaquer(t){let e=this._rgb;return e.a*=1+t,this}negate(){let t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Di(this._rgb,2,t),this}darken(t){return Di(this._rgb,2,-t),this}saturate(t){return Di(this._rgb,1,t),this}desaturate(t){return Di(this._rgb,1,-t),this}rotate(t){return Cc(this._rgb,t),this}}});function te(){}function st(s){return s==null}function dt(s){if(Array.isArray&&Array.isArray(s))return!0;let t=Object.prototype.toString.call(s);return t.slice(0,7)==="[object"&&t.slice(-6)==="Array]"}function it(s){return s!==null&&Object.prototype.toString.call(s)==="[object Object]"}function ft(s){return(typeof s=="number"||s instanceof Number)&&isFinite(+s)}function Pt(s,t){return ft(s)?s:t}function tt(s,t){return typeof s=="undefined"?t:s}function ct(s,t,e){if(s&&typeof s.call=="function")return s.apply(e,t)}function Lt(s,t,e,i){let n,o,r;if(dt(s))if(o=s.length,i)for(n=o-1;n>=0;n--)t.call(e,s[n],n);else for(n=0;n{for(let i of t){if(i==="")break;e=e&&e[i]}return e}}function de(s,t){return(Fr[t]||(Fr[t]=Oc(t)))(s)}function Vi(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Gr(s){return s.type==="mouseup"||s.type==="click"||s.type==="contextmenu"}function bs(s,t,e){return Math.abs(s-t)n-o).pop(),t}function Vc(s){return typeof s=="symbol"||typeof s=="object"&&s!==null&&!(Symbol.toPrimitive in s||"toString"in s||"valueOf"in s)}function Ze(s){return!Vc(s)&&!isNaN(parseFloat(s))&&isFinite(s)}function qr(s,t){let e=Math.round(s);return e-t<=s&&e+t>=s}function Yn(s,t,e){let i,n,o;for(i=0,n=s.length;iL&&l=Math.min(t,e)-i&&s<=Math.max(t,e)+i}function Bi(s,t,e){e=e||(r=>s[r]1;)o=n+i>>1,e(o)?n=o:i=o;return{lo:n,hi:i}}function Jr(s,t,e){let i=0,n=s.length;for(;ii&&s[n-1]>e;)n--;return i>0||n{let i="_onData"+Vi(e),n=s[e];Object.defineProperty(s,e,{configurable:!0,enumerable:!1,value(...o){let r=n.apply(this,o);return s._chartjs.listeners.forEach(a=>{typeof a[i]=="function"&&a[i](...o)}),r}})})}function qn(s,t){let e=s._chartjs;if(!e)return;let i=e.listeners,n=i.indexOf(t);n!==-1&&i.splice(n,1),!(i.length>0)&&(ta.forEach(o=>{delete s[o]}),delete s._chartjs)}function Xn(s){let t=new Set(s);return t.size===s.length?s:Array.from(t)}function Jn(s,t){let e=[],i=!1;return function(...n){e=n,i||(i=!0,Qn.call(window,()=>{i=!1,s.apply(t,e)}))}}function sa(s,t){let e;return function(...i){return t?(clearTimeout(e),e=setTimeout(s,t,i)):s.apply(this,i),t}}function to(s,t,e){let i=t.length,n=0,o=i;if(s._sorted){let{iScale:r,vScale:a,_parsed:L}=s,l=s.dataset&&s.dataset.options?s.dataset.options.spanGaps:null,c=r.axis,{min:d,max:h,minDefined:u,maxDefined:f}=r.getUserBounds();if(u){if(n=Math.min(Qt(L,c,d).lo,e?i:Qt(t,c,r.getPixelForValue(d)).lo),l){let g=L.slice(0,n+1).reverse().findIndex(m=>!st(m[a.axis]));n-=Math.max(0,g)}n=mt(n,0,i-1)}if(f){let g=Math.max(Qt(L,r.axis,h,!0).hi+1,e?0:Qt(t,c,r.getPixelForValue(h),!0).hi+1);if(l){let m=L.slice(g-1).findIndex(p=>!st(p[a.axis]));g+=Math.max(0,m)}o=mt(g,n,i)-n}else o=i-n}return{start:n,count:o}}function eo(s){let{xScale:t,yScale:e,_scaleRanges:i}=s,n={xmin:t.min,xmax:t.max,ymin:e.min,ymax:e.max};if(!i)return s._scaleRanges=n,!0;let o=i.xmin!==t.min||i.xmax!==t.max||i.ymin!==e.min||i.ymax!==e.max;return Object.assign(i,n),o}function so(s){if(s&&typeof s=="object"){let t=s.toString();return t==="[object CanvasPattern]"||t==="[object CanvasGradient]"}return!1}function io(s){return so(s)?s:new Us(s)}function zn(s){return so(s)?s:new Us(s).saturate(.5).darken(.1).hexString()}function zc(s){s.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),s.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>t!=="onProgress"&&t!=="onComplete"&&t!=="fn"}),s.set("animations",{colors:{type:"color",properties:$c},numbers:{type:"number",properties:Bc}}),s.describe("animations",{_fallback:"animation"}),s.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>t|0}}}})}function Hc(s){s.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}function Zc(s,t){t=t||{};let e=s+JSON.stringify(t),i=Br.get(e);return i||(i=new Intl.NumberFormat(s,t),Br.set(e,i)),i}function ys(s,t,e){return Zc(t,e).format(s)}function Wc(s,t){let e=t.length>3?t[2].value-t[1].value:t[1].value-t[0].value;return Math.abs(e)>=1&&s!==Math.floor(s)&&(e=s-Math.floor(s)),e}function jc(s){s.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:xs.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),s.route("scale.ticks","color","","color"),s.route("scale.grid","color","","borderColor"),s.route("scale.border","color","","borderColor"),s.route("scale.title","color","","color"),s.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&t!=="callback"&&t!=="parser",_indexable:t=>t!=="borderDash"&&t!=="tickBorderDash"&&t!=="dash"}),s.describe("scales",{_fallback:"scale"}),s.describe("scale.ticks",{_scriptable:t=>t!=="backdropPadding"&&t!=="callback",_indexable:t=>t!=="backdropPadding"})}function Gs(s,t){if(!t)return s;let e=t.split(".");for(let i=0,n=e.length;ii&&(i=o),i}function oa(s,t,e,i){i=i||{};let n=i.data=i.data||{},o=i.garbageCollect=i.garbageCollect||[];i.font!==t&&(n=i.data={},o=i.garbageCollect=[],i.font=t),s.save(),s.font=t;let r=0,a=e.length,L,l,c,d,h;for(L=0;Le.length){for(L=0;L0&&s.stroke()}}function Jt(s,t,e){return e=e||.5,!t||s&&s.x>t.left-e&&s.xt.top-e&&s.y0&&o.strokeColor!=="",L,l;for(s.save(),s.font=n.string,Yc(s,o),L=0;Ltt(s[r],s[t[r]]):r=>s[r]:()=>s;for(let r of n)e[r]=Jc(o(r));return e}function ro(s){return Zi(s,{top:"y",right:"x",bottom:"y",left:"x"})}function Me(s){return Zi(s,["topLeft","topRight","bottomLeft","bottomRight"])}function Ct(s){let t=ro(s);return t.width=t.left+t.right,t.height=t.top+t.bottom,t}function gt(s,t){s=s||{},t=t||ut.font;let e=tt(s.size,t.size);typeof e=="string"&&(e=parseInt(e,10));let i=tt(s.style,t.style);i&&!(""+i).match(Xc)&&(console.warn('Invalid font style specified: "'+i+'"'),i=void 0);let n={family:tt(s.family,t.family),lineHeight:Qc(tt(s.lineHeight,t.lineHeight),e),size:e,style:i,weight:tt(s.weight,t.weight),string:""};return n.string=Uc(n),n}function _s(s,t,e,i){let n=!0,o,r,a;for(o=0,r=s.length;oe&&a===0?0:a+L;return{min:r(i,-Math.abs(o)),max:r(n,o)}}function he(s,t){return Object.assign(Object.create(s),t)}function Wi(s,t=[""],e,i,n=()=>s[0]){let o=e||s;typeof i=="undefined"&&(i=da("_fallback",s));let r={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:s,_rootScopes:o,_fallback:i,_getTarget:n,override:a=>Wi([a,...s],t,o,i)};return new Proxy(r,{deleteProperty(a,L){return delete a[L],delete a._keys,delete s[0][L],!0},get(a,L){return la(a,L,()=>a2(L,t,s,a))},getOwnPropertyDescriptor(a,L){return Reflect.getOwnPropertyDescriptor(a._scopes[0],L)},getPrototypeOf(){return Reflect.getPrototypeOf(s[0])},has(a,L){return zr(a).includes(L)},ownKeys(a){return zr(a)},set(a,L,l){let c=a._storage||(a._storage=n());return a[L]=c[L]=l,delete a._keys,!0}})}function He(s,t,e,i){let n={_cacheable:!1,_proxy:s,_context:t,_subProxy:e,_stack:new Set,_descriptors:ao(s,i),setContext:o=>He(s,o,e,i),override:o=>He(s.override(o),t,e,i)};return new Proxy(n,{deleteProperty(o,r){return delete o[r],delete s[r],!0},get(o,r,a){return la(o,r,()=>e2(o,r,a))},getOwnPropertyDescriptor(o,r){return o._descriptors.allKeys?Reflect.has(s,r)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(s,r)},getPrototypeOf(){return Reflect.getPrototypeOf(s)},has(o,r){return Reflect.has(s,r)},ownKeys(){return Reflect.ownKeys(s)},set(o,r,a){return s[r]=a,delete o[r],!0}})}function ao(s,t={scriptable:!0,indexable:!0}){let{_scriptable:e=t.scriptable,_indexable:i=t.indexable,_allKeys:n=t.allKeys}=s;return{allKeys:n,scriptable:e,indexable:i,isScriptable:le(e)?e:()=>e,isIndexable:le(i)?i:()=>i}}function la(s,t,e){if(Object.prototype.hasOwnProperty.call(s,t)||t==="constructor")return s[t];let i=e();return s[t]=i,i}function e2(s,t,e){let{_proxy:i,_context:n,_subProxy:o,_descriptors:r}=s,a=i[t];return le(a)&&r.isScriptable(t)&&(a=s2(t,a,s,e)),dt(a)&&a.length&&(a=i2(t,a,s,r.isIndexable)),Lo(t,a)&&(a=He(a,n,o&&o[t],r)),a}function s2(s,t,e,i){let{_proxy:n,_context:o,_subProxy:r,_stack:a}=e;if(a.has(s))throw new Error("Recursion detected: "+Array.from(a).join("->")+"->"+s);a.add(s);let L=t(o,r||i);return a.delete(s),Lo(s,L)&&(L=lo(n._scopes,n,s,L)),L}function i2(s,t,e,i){let{_proxy:n,_context:o,_subProxy:r,_descriptors:a}=e;if(typeof o.index!="undefined"&&i(s))return t[o.index%t.length];if(it(t[0])){let L=t,l=n._scopes.filter(c=>c!==L);t=[];for(let c of L){let d=lo(l,n,s,c);t.push(He(d,o,r&&r[s],a))}}return t}function ca(s,t,e){return le(s)?s(t,e):s}function o2(s,t,e,i,n){for(let o of t){let r=n2(e,o);if(r){s.add(r);let a=ca(r._fallback,e,n);if(typeof a!="undefined"&&a!==e&&a!==i)return a}else if(r===!1&&typeof i!="undefined"&&e!==i)return null}return!1}function lo(s,t,e,i){let n=t._rootScopes,o=ca(t._fallback,e,i),r=[...s,...n],a=new Set;a.add(i);let L=$r(a,r,e,o||e,i);return L===null||typeof o!="undefined"&&o!==e&&(L=$r(a,r,o,L,i),L===null)?!1:Wi(Array.from(a),[""],n,o,()=>r2(t,e,i))}function $r(s,t,e,i,n){for(;e;)e=o2(s,t,e,i,n);return e}function r2(s,t,e){let i=s._getTarget();t in i||(i[t]={});let n=i[t];return dt(n)&&it(e)?e:n||{}}function a2(s,t,e,i){let n;for(let o of t)if(n=da(t2(o,s),e),typeof n!="undefined")return Lo(s,n)?lo(e,i,s,n):n}function da(s,t){for(let e of t){if(!e)continue;let i=e[s];if(typeof i!="undefined")return i}}function zr(s){let t=s._keys;return t||(t=s._keys=L2(s._scopes)),t}function L2(s){let t=new Set;for(let e of s)for(let i of Object.keys(e).filter(n=>!n.startsWith("_")))t.add(i);return Array.from(t)}function co(s,t,e,i){let{iScale:n}=s,{key:o="r"}=this._parsing,r=new Array(i),a,L,l,c;for(a=0,L=i;a!l.skip)),t.cubicInterpolationMode==="monotone")u2(s,n);else{let l=i?s[s.length-1]:s[0];for(o=0,r=s.length;oL.height&&(c=L.height,l=_e(Math.floor(c*i))),{width:l,height:c}}function ho(s,t,e){let i=t||1,n=_e(s.height*i),o=_e(s.width*i);s.height=_e(s.height),s.width=_e(s.width);let r=s.canvas;return r.style&&(e||!r.style.height&&!r.style.width)&&(r.style.height=`${s.height}px`,r.style.width=`${s.width}px`),s.currentDevicePixelRatio!==i||r.height!==n||r.width!==o?(s.currentDevicePixelRatio=i,r.height=n,r.width=o,s.ctx.setTransform(i,0,0,i,0,0),!0):!1}function uo(s,t){let e=p2(s,t),i=e&&e.match(/^(\d+)(\.\d+)?px$/);return i?+i[1]:void 0}function Ce(s,t,e,i){return{x:s.x+e*(t.x-s.x),y:s.y+e*(t.y-s.y)}}function ga(s,t,e,i){return{x:s.x+e*(t.x-s.x),y:i==="middle"?e<.5?s.y:t.y:i==="after"?e<1?s.y:t.y:e>0?t.y:s.y}}function ma(s,t,e,i){let n={x:s.cp2x,y:s.cp2y},o={x:t.cp1x,y:t.cp1y},r=Ce(s,n,e),a=Ce(n,o,e),L=Ce(o,t,e),l=Ce(r,a,e),c=Ce(a,L,e);return Ce(l,c,e)}function We(s,t,e){return s?y2(t,e):x2()}function fo(s,t){let e,i;(t==="ltr"||t==="rtl")&&(e=s.canvas.style,i=[e.getPropertyValue("direction"),e.getPropertyPriority("direction")],e.setProperty("direction",t,"important"),s.prevTextDirection=i)}function po(s,t){t!==void 0&&(delete s.prevTextDirection,s.canvas.style.setProperty("direction",t[0],t[1]))}function ba(s){return s==="angle"?{between:vs,compare:Nc,normalize:yt}:{between:ee,compare:(t,e)=>t-e,normalize:t=>t}}function Hr({start:s,end:t,count:e,loop:i,style:n}){return{start:s%e,end:t%e,loop:i&&(t-s+1)%e===0,style:n}}function C2(s,t,e){let{property:i,start:n,end:o}=e,{between:r,normalize:a}=ba(i),L=t.length,{start:l,end:c,loop:d}=s,h,u;if(d){for(l+=L,c+=L,h=0,u=L;hL(n,C,p)&&a(n,C)!==0,_=()=>a(o,p)===0||L(o,C,p),y=()=>g||S(),v=()=>!g||_();for(let x=c,k=c;x<=d;++x)b=t[x%r],!b.skip&&(p=l(b[i]),p!==C&&(g=L(p,n,o),m===null&&y()&&(m=a(p,n)===0?x:k),m!==null&&v()&&(f.push(Hr({start:m,end:x,loop:h,count:r,style:u})),m=null),k=x,C=p));return m!==null&&f.push(Hr({start:m,end:d,loop:h,count:r,style:u})),f}function mo(s,t){let e=[],i=s.segments;for(let n=0;nn&&s[o%t].skip;)o--;return o%=t,{start:n,end:o}}function S2(s,t,e,i){let n=s.length,o=[],r=t,a=s[t],L;for(L=t+1;L<=e;++L){let l=s[L%n];l.skip||l.stop?a.skip||(i=!1,o.push({start:t%n,end:(L-1)%n,loop:i}),t=r=l.stop?L:null):(r=L,a.skip&&(t=L)),a=l}return r!==null&&o.push({start:t%n,end:r%n,loop:i}),o}function va(s,t){let e=s.points,i=s.options.spanGaps,n=e.length;if(!n)return[];let o=!!s._loop,{start:r,end:a}=_2(e,n,o,i);if(i===!0)return Zr(s,[{start:r,end:a,loop:o}],e,t);let L=a{Or();jr=(()=>{let s=0;return()=>s++})();Ur=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100:+s/t,Wn=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100*t:+s;Fr={"":s=>s,x:s=>s.x,y:s=>s.y};ms=s=>typeof s!="undefined",le=s=>typeof s=="function",jn=(s,t)=>{if(s.size!==t.size)return!1;for(let e of s)if(!t.has(e))return!1;return!0};rt=Math.PI,ht=2*rt,Fc=ht+rt,Oi=Number.POSITIVE_INFINITY,Ic=rt/180,pt=rt/2,$e=rt/4,Ir=rt*2/3,ce=Math.log10,jt=Math.sign;Qt=(s,t,e,i)=>Bi(s,e,i?n=>{let o=s[n][t];return os[n][t]Bi(s,e,i=>s[i][t]>=e);ta=["push","pop","shift","splice","unshift"];Qn=function(){return typeof window=="undefined"?function(s){return s()}:window.requestAnimationFrame}();$i=s=>s==="start"?"left":s==="end"?"right":"center",xt=(s,t,e)=>s==="start"?t:s==="end"?e:(t+e)/2,ia=(s,t,e,i)=>s===(i?"left":"right")?e:s==="center"?(t+e)/2:t;Ti=s=>s===0||s===1,Vr=(s,t,e)=>-(Math.pow(2,10*(s-=1))*Math.sin((s-t)*ht/e)),Nr=(s,t,e)=>Math.pow(2,-10*s)*Math.sin((s-t)*ht/e)+1,us={linear:s=>s,easeInQuad:s=>s*s,easeOutQuad:s=>-s*(s-2),easeInOutQuad:s=>(s/=.5)<1?.5*s*s:-.5*(--s*(s-2)-1),easeInCubic:s=>s*s*s,easeOutCubic:s=>(s-=1)*s*s+1,easeInOutCubic:s=>(s/=.5)<1?.5*s*s*s:.5*((s-=2)*s*s+2),easeInQuart:s=>s*s*s*s,easeOutQuart:s=>-((s-=1)*s*s*s-1),easeInOutQuart:s=>(s/=.5)<1?.5*s*s*s*s:-.5*((s-=2)*s*s*s-2),easeInQuint:s=>s*s*s*s*s,easeOutQuint:s=>(s-=1)*s*s*s*s+1,easeInOutQuint:s=>(s/=.5)<1?.5*s*s*s*s*s:.5*((s-=2)*s*s*s*s+2),easeInSine:s=>-Math.cos(s*pt)+1,easeOutSine:s=>Math.sin(s*pt),easeInOutSine:s=>-.5*(Math.cos(rt*s)-1),easeInExpo:s=>s===0?0:Math.pow(2,10*(s-1)),easeOutExpo:s=>s===1?1:-Math.pow(2,-10*s)+1,easeInOutExpo:s=>Ti(s)?s:s<.5?.5*Math.pow(2,10*(s*2-1)):.5*(-Math.pow(2,-10*(s*2-1))+2),easeInCirc:s=>s>=1?s:-(Math.sqrt(1-s*s)-1),easeOutCirc:s=>Math.sqrt(1-(s-=1)*s),easeInOutCirc:s=>(s/=.5)<1?-.5*(Math.sqrt(1-s*s)-1):.5*(Math.sqrt(1-(s-=2)*s)+1),easeInElastic:s=>Ti(s)?s:Vr(s,.075,.3),easeOutElastic:s=>Ti(s)?s:Nr(s,.075,.3),easeInOutElastic(s){return Ti(s)?s:s<.5?.5*Vr(s*2,.1125,.45):.5+.5*Nr(s*2-1,.1125,.45)},easeInBack(s){return s*s*((1.70158+1)*s-1.70158)},easeOutBack(s){return(s-=1)*s*((1.70158+1)*s+1.70158)+1},easeInOutBack(s){let t=1.70158;return(s/=.5)<1?.5*(s*s*(((t*=1.525)+1)*s-t)):.5*((s-=2)*s*(((t*=1.525)+1)*s+t)+2)},easeInBounce:s=>1-us.easeOutBounce(1-s),easeOutBounce(s){return s<1/2.75?7.5625*s*s:s<2/2.75?7.5625*(s-=1.5/2.75)*s+.75:s<2.5/2.75?7.5625*(s-=2.25/2.75)*s+.9375:7.5625*(s-=2.625/2.75)*s+.984375},easeInOutBounce:s=>s<.5?us.easeInBounce(s*2)*.5:us.easeOutBounce(s*2-1)*.5+.5};Bc=["x","y","borderWidth","radius","tension"],$c=["color","borderColor","backgroundColor"];Br=new Map;na={values(s){return dt(s)?s:""+s},numeric(s,t,e){if(s===0)return"0";let i=this.chart.options.locale,n,o=s;if(e.length>1){let l=Math.max(Math.abs(e[0].value),Math.abs(e[e.length-1].value));(l<1e-4||l>1e15)&&(n="scientific"),o=Wc(s,e)}let r=ce(Math.abs(o)),a=isNaN(r)?1:Math.max(Math.min(-1*Math.floor(r),20),0),L={notation:n,minimumFractionDigits:a,maximumFractionDigits:a};return Object.assign(L,this.options.ticks.format),ys(s,i,L)},logarithmic(s,t,e){if(s===0)return"0";let i=e[t].significand||s/Math.pow(10,Math.floor(ce(s)));return[1,2,3,5,10,15].includes(i)||t>.8*e.length?na.numeric.call(this,s,t,e):""}};xs={formatters:na};Se=Object.create(null),zi=Object.create(null);Zn=class{constructor(t,e){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=i=>i.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(i,n)=>zn(n.backgroundColor),this.hoverBorderColor=(i,n)=>zn(n.borderColor),this.hoverColor=(i,n)=>zn(n.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return Hn(this,t,e)}get(t){return Gs(this,t)}describe(t,e){return Hn(zi,t,e)}override(t,e){return Hn(Se,t,e)}route(t,e,i,n){let o=Gs(this,t),r=Gs(this,i),a="_"+e;Object.defineProperties(o,{[a]:{value:o[e],writable:!0},[e]:{enumerable:!0,get(){let L=this[a],l=r[n];return it(L)?Object.assign({},l,L):tt(L,l)},set(L){this[a]=L}}})}apply(t){t.forEach(e=>e(this))}},ut=new Zn({_scriptable:s=>!s.startsWith("on"),_indexable:s=>s!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[zc,Hc,jc]);qc=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,Xc=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;Jc=s=>+s||0;t2=(s,t)=>s?s+Vi(t):t,Lo=(s,t)=>it(t)&&s!=="adapters"&&(Object.getPrototypeOf(t)===null||t.constructor===Object);n2=(s,t)=>s===!0?t:typeof s=="string"?de(t,s):void 0;l2=Number.EPSILON||1e-14,ps=(s,t)=>ts==="x"?"y":"x";Yi=s=>s.ownerDocument.defaultView.getComputedStyle(s,null);g2=["top","right","bottom","left"];m2=(s,t,e)=>(s>0||t>0)&&(!e||!e.shadowRoot);_e=s=>Math.round(s*10)/10;pa=function(){let s=!1;try{let t={get passive(){return s=!0,!1}};ji()&&(window.addEventListener("test",null,t),window.removeEventListener("test",null,t))}catch(t){}return s}();y2=function(s,t){return{x(e){return s+s+t-e},setWidth(e){t=e},textAlign(e){return e==="center"?e:e==="right"?"left":"right"},xPlus(e,i){return e-i},leftForLtr(e,i){return e-i}}},x2=function(){return{x(s){return s},setWidth(s){},textAlign(s){return s},xPlus(s,t){return s+t},leftForLtr(s,t){return s}}}});var tl={};tr(tl,{Animation:()=>sn,Animations:()=>ai,ArcElement:()=>De,BarController:()=>Ye,BarElement:()=>Je,BasePlatform:()=>Li,BasicPlatform:()=>nn,BubbleController:()=>Ge,CategoryScale:()=>Ms,Chart:()=>ne,Colors:()=>$L,DatasetController:()=>Ft,Decimation:()=>HL,DomPlatform:()=>rn,DoughnutController:()=>oe,Element:()=>Vt,Filler:()=>WL,Interaction:()=>SL,Legend:()=>UL,LineController:()=>Ke,LineElement:()=>Yt,LinearScale:()=>ws,LogarithmicScale:()=>Ds,PieController:()=>ks,PointElement:()=>Qe,PolarAreaController:()=>Ae,RadarController:()=>qe,RadialLinearScale:()=>Te,Scale:()=>Oe,ScatterController:()=>Xe,SubTitle:()=>GL,Ticks:()=>xs,TimeScale:()=>Pe,TimeSeriesScale:()=>Ts,Title:()=>YL,Tooltip:()=>qL,_adapters:()=>_L,_detectPlatform:()=>DL,animator:()=>ie,controllers:()=>CL,defaults:()=>ut,elements:()=>VL,layouts:()=>_t,plugins:()=>XL,registerables:()=>M5,registry:()=>Ut,scales:()=>JL});function D2(s,t){let e=[],i=Object.keys(t);for(let n=0;n0||!e&&o<0)return n.index}return null}function ka(s,t){let{chart:e,_cachedMeta:i}=s,n=e._stacks||(e._stacks={}),{iScale:o,vScale:r,index:a}=i,L=o.axis,l=r.axis,c=O2(o,r,i),d=t.length,h;for(let u=0;ue[i].axis===t).shift()}function V2(s,t){return he(s,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function N2(s,t,e){return he(s,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:e,index:t,mode:"default",type:"data"})}function Js(s,t){let e=s.controller.index,i=s.vScale&&s.vScale.axis;if(i){t=t||s._parsed;for(let n of t){let o=n._stacks;if(!o||o[i]===void 0||o[i][e]===void 0)return;delete o[i][e],o[i]._visualValues!==void 0&&o[i]._visualValues[e]!==void 0&&delete o[i]._visualValues[e]}}}function $2(s,t){if(!s._cache.$bar){let e=s.getMatchingVisibleMetas(t),i=[];for(let n=0,o=e.length;nn-o))}return s._cache.$bar}function z2(s){let t=s.iScale,e=$2(t,s.type),i=t._length,n,o,r,a,L=()=>{r===32767||r===-32768||(ms(a)&&(i=Math.min(i,Math.abs(r-a)||i)),a=r)};for(n=0,o=e.length;n0?n[s-1]:null,a=sMath.abs(a)&&(L=a,l=r),t[e.axis]=l,t._custom={barStart:L,barEnd:l,start:n,end:o,min:r,max:a}}function xL(s,t,e,i){return dt(s)?W2(s,t,e,i):t[e.axis]=e.parse(s,i),t}function Ma(s,t,e,i){let n=s.iScale,o=s.vScale,r=n.getLabels(),a=n===o,L=[],l,c,d,h;for(l=e,c=e+i;l=e?1:-1)}function U2(s){let t,e,i,n,o;return s.horizontal?(t=s.base>s.x,e="left",i="right"):(t=s.basevs(C,a,L,!0)?1:Math.max(S,S*e,_,_*e),f=(C,S,_)=>vs(C,a,L,!0)?-1:Math.min(S,S*e,_,_*e),g=u(0,l,d),m=u(pt,c,h),p=f(rt,l,d),b=f(rt+pt,c,h);i=(g-p)/2,n=(m-b)/2,o=-(g+p)/2,r=-(m+b)/2}return{ratioX:i,ratioY:n,offsetX:o,offsetY:r}}function je(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}function X2(s,t,e,i){let{controller:n,data:o,_sorted:r}=s,a=n._cachedMeta.iScale,L=s.dataset&&s.dataset.options?s.dataset.options.spanGaps:null;if(a&&t===a.axis&&t!=="r"&&r&&o.length){let l=a._reversePixels?Qr:Qt;if(i){if(n._sharedOptions){let c=o[0],d=typeof c.getRange=="function"&&c.getRange(t);if(d){let h=l(o,t,e-d),u=l(o,t,e+d);return{lo:h.lo,hi:u.hi}}}}else{let c=l(o,t,e);if(L){let{vScale:d}=n._cachedMeta,{_parsed:h}=s,u=h.slice(0,c.lo+1).reverse().findIndex(g=>!st(g[d.axis]));c.lo-=Math.max(0,u);let f=h.slice(c.hi).findIndex(g=>!st(g[d.axis]));c.hi+=Math.max(0,f)}return c}}return{lo:0,hi:o.length-1}}function hi(s,t,e,i,n){let o=s.getSortedVisibleDatasetMetas(),r=e[t];for(let a=0,L=o.length;a{L[r]&&L[r](t[e],n)&&(o.push({element:L,datasetIndex:l,index:c}),a=a||L.inRange(t.x,t.y,n))}),i&&!a?[]:o}function ti(s,t){return s.filter(e=>e.pos===t)}function Aa(s,t){return s.filter(e=>kL.indexOf(e.pos)===-1&&e.box.axis===t)}function ei(s,t){return s.sort((e,i)=>{let n=t?i:e,o=t?e:i;return n.weight===o.weight?n.index-o.index:n.weight-o.weight})}function e1(s){let t=[],e,i,n,o,r,a;for(e=0,i=(s||[]).length;el.box.fullSize),!0),i=ei(ti(t,"left"),!0),n=ei(ti(t,"right")),o=ei(ti(t,"top"),!0),r=ei(ti(t,"bottom")),a=Aa(t,"x"),L=Aa(t,"y");return{fullSize:e,leftAndTop:i.concat(o),rightAndBottom:n.concat(L).concat(r).concat(a),chartArea:ti(t,"chartArea"),vertical:i.concat(n).concat(L),horizontal:o.concat(r).concat(a)}}function Ra(s,t,e,i){return Math.max(s[e],t[e])+Math.max(s[i],t[i])}function EL(s,t){s.top=Math.max(s.top,t.top),s.left=Math.max(s.left,t.left),s.bottom=Math.max(s.bottom,t.bottom),s.right=Math.max(s.right,t.right)}function o1(s,t,e,i){let{pos:n,box:o}=e,r=s.maxPadding;if(!it(n)){e.size&&(s[n]-=e.size);let d=i[e.stack]||{size:0,count:1};d.size=Math.max(d.size,e.horizontal?o.height:o.width),e.size=d.size/d.count,s[n]+=e.size}o.getPadding&&EL(r,o.getPadding());let a=Math.max(0,t.outerWidth-Ra(r,s,"left","right")),L=Math.max(0,t.outerHeight-Ra(r,s,"top","bottom")),l=a!==s.w,c=L!==s.h;return s.w=a,s.h=L,e.horizontal?{same:l,other:c}:{same:c,other:l}}function r1(s){let t=s.maxPadding;function e(i){let n=Math.max(t[i]-s[i],0);return s[i]+=n,n}s.y+=e("top"),s.x+=e("left"),e("right"),e("bottom")}function a1(s,t){let e=t.maxPadding;function i(n){let o={left:0,top:0,right:0,bottom:0};return n.forEach(r=>{o[r]=Math.max(t[r],e[r])}),o}return i(s?["left","right"]:["top","bottom"])}function ni(s,t,e,i){let n=[],o,r,a,L,l,c;for(o=0,r=s.length,l=0;o{let r=!1;for(let a of o)r=r||on(a.addedNodes,i),r=r&&!on(a.removedNodes,i);r&&e()});return n.observe(document,{childList:!0,subtree:!0}),n}function f1(s,t,e){let i=s.canvas,n=new MutationObserver(o=>{let r=!1;for(let a of o)r=r||on(a.removedNodes,i),r=r&&!on(a.addedNodes,i);r&&e()});return n.observe(document,{childList:!0,subtree:!0}),n}function wL(){let s=window.devicePixelRatio;s!==Fa&&(Fa=s,li.forEach((t,e)=>{e.currentDevicePixelRatio!==s&&t()}))}function p1(s,t){li.size||window.addEventListener("resize",wL),li.set(s,t)}function g1(s){li.delete(s),li.size||window.removeEventListener("resize",wL)}function m1(s,t,e){let i=s.canvas,n=i&&Ui(i);if(!n)return;let o=Jn((a,L)=>{let l=n.clientWidth;e(a,L),l{let L=a[0],l=L.contentRect.width,c=L.contentRect.height;l===0&&c===0||o(l,c)});return r.observe(n),p1(s,o),r}function ko(s,t,e){e&&e.disconnect(),t==="resize"&&g1(s)}function b1(s,t,e){let i=s.canvas,n=Jn(o=>{s.ctx!==null&&e(h1(o,s))},s);return c1(i,t,n),n}function DL(s){return!ji()||typeof OffscreenCanvas!="undefined"&&s instanceof OffscreenCanvas?nn:rn}function v1(s,t){let e=s.options.ticks,i=y1(s),n=Math.min(e.maxTicksLimit||i,i),o=e.major.enabled?C1(t):[],r=o.length,a=o[0],L=o[r-1],l=[];if(r>n)return _1(t,l,o,r/n),l;let c=x1(o,t,n);if(r>0){let d,h,u=r>1?Math.round((L-a)/(r-1)):null;for(Ki(t,l,c,st(u)?0:a-u,a),d=0,h=r-1;dn)return L}return Math.max(n,1)}function C1(s){let t=[],e,i;for(e=0,i=s.length;er+a)))return L}function M1(s,t){Lt(s,e=>{let i=e.gc,n=i.length/2,o;if(n>t){for(o=0;o{let i=e.split("."),n=i.pop(),o=[s].concat(i).join("."),r=t[e].split("."),a=r.pop(),L=r.join(".");ut.route(o,n,L,a)})}function O1(s){return"id"in s&&"defaults"in s}function F1(s){let t={},e=[],i=Object.keys(Ut.plugins.items);for(let o=0;o1&&$a(s[0].toLowerCase());if(i)return i}throw new Error(`Cannot determine type of '${s}' axis. Please provide 'axis' or 'position' option.`)}function za(s,t,e){if(e[t+"AxisID"]===s)return{axis:t}}function H1(s,t){if(t.data&&t.data.datasets){let e=t.data.datasets.filter(i=>i.xAxisID===s||i.yAxisID===s);if(e.length)return za(s,"x",e[0])||za(s,"y",e[0])}return{}}function Z1(s,t){let e=Se[s.type]||{scales:{}},i=t.scales||{},n=Oo(s.type,t),o=Object.create(null);return Object.keys(i).forEach(r=>{let a=i[r];if(!it(a))return console.error(`Invalid scale configuration for scale: ${r}`);if(a._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${r}`);let L=Fo(r,a,H1(r,s),ut.scales[a.type]),l=$1(L,n),c=e.scales||{};o[r]=gs(Object.create(null),[{axis:L},a,c[L],c[l]])}),s.data.datasets.forEach(r=>{let a=r.type||s.type,L=r.indexAxis||Oo(a,t),c=(Se[a]||{}).scales||{};Object.keys(c).forEach(d=>{let h=B1(d,L),u=r[h+"AxisID"]||h;o[u]=o[u]||Object.create(null),gs(o[u],[{axis:h},i[u],c[d]])})}),Object.keys(o).forEach(r=>{let a=o[r];gs(a,[ut.scales[a.type],ut.scale])}),o}function TL(s){let t=s.options||(s.options={});t.plugins=tt(t.plugins,{}),t.scales=Z1(s,t)}function AL(s){return s=s||{},s.datasets=s.datasets||[],s.labels=s.labels||[],s}function W1(s){return s=s||{},s.data=AL(s.data),TL(s),s}function qi(s,t){let e=Ha.get(s);return e||(e=t(),Ha.set(s,e),RL.add(e)),e}function Za(s,t,e){let i=s.get(t);i||(i=new Map,s.set(t,i));let n=e.join(),o=i.get(n);return o||(o={resolver:Wi(t,e),subPrefixes:e.filter(a=>!a.toLowerCase().includes("hover"))},i.set(n,o)),o}function U1(s,t){let{isScriptable:e,isIndexable:i}=ao(s);for(let n of t){let o=e(n),r=i(n),a=(r||o)&&s[n];if(o&&(le(a)||j1(a))||r&&dt(a))return!0}return!1}function Wa(s,t){return s==="top"||s==="bottom"||G1.indexOf(s)===-1&&t==="x"}function ja(s,t){return function(e,i){return e[s]===i[s]?e[t]-i[t]:e[s]-i[s]}}function Ua(s){let t=s.chart,e=t.options.animation;t.notifyPlugins("afterRender"),ct(e&&e.onComplete,[s],t)}function K1(s){let t=s.chart,e=t.options.animation;ct(e&&e.onProgress,[s],t)}function PL(s){return ji()&&typeof s=="string"?s=document.getElementById(s):s&&s.length&&(s=s[0]),s&&s.canvas&&(s=s.canvas),s}function q1(s,t,e){let i=Object.keys(s);for(let n of i){let o=+n;if(o>=t){let r=s[n];delete s[n],(e>0||o>t)&&(s[o+e]=r)}}}function X1(s,t,e,i){return!e||s.type==="mouseout"?null:i?t:s}function Ga(){return Lt(ne.instances,s=>s._plugins.invalidate())}function Q1(s,t,e){let{startAngle:i,x:n,y:o,outerRadius:r,innerRadius:a,options:L}=t,{borderWidth:l,borderJoinStyle:c}=L,d=Math.min(l/r,yt(i-e));if(s.beginPath(),s.arc(n,o,r-l/2,i+d/2,e-d/2),a>0){let h=Math.min(l/a,yt(i-e));s.arc(n,o,a+l/2,e-h/2,i+h/2,!0)}else{let h=Math.min(l/2,r*yt(i-e));if(c==="round")s.arc(n,o,h,e-rt/2,i+rt/2,!0);else if(c==="bevel"){let u=2*h*h,f=-u*Math.cos(e+rt/2)+n,g=-u*Math.sin(e+rt/2)+o,m=u*Math.cos(i+rt/2)+n,p=u*Math.sin(i+rt/2)+o;s.lineTo(f,g),s.lineTo(m,p)}}s.closePath(),s.moveTo(0,0),s.rect(0,0,s.canvas.width,s.canvas.height),s.clip("evenodd")}function J1(s,t,e){let{startAngle:i,pixelMargin:n,x:o,y:r,outerRadius:a,innerRadius:L}=t,l=n/a;s.beginPath(),s.arc(o,r,a,i-l,e+l),L>n?(l=n/L,s.arc(o,r,L,e+l,i-l,!0)):s.arc(o,r,n,e+pt,i-pt),s.closePath(),s.clip()}function td(s){return Zi(s,["outerStart","outerEnd","innerStart","innerEnd"])}function ed(s,t,e,i){let n=td(s.options.borderRadius),o=(e-t)/2,r=Math.min(o,i*t/2),a=L=>{let l=(e-Math.min(o,L))*i/2;return mt(L,0,Math.min(o,l))};return{outerStart:a(n.outerStart),outerEnd:a(n.outerEnd),innerStart:mt(n.innerStart,0,r),innerEnd:mt(n.innerEnd,0,r)}}function Ss(s,t,e,i){return{x:e+s*Math.cos(t),y:i+s*Math.sin(t)}}function an(s,t,e,i,n,o){let{x:r,y:a,startAngle:L,pixelMargin:l,innerRadius:c}=t,d=Math.max(t.outerRadius+i+e-l,0),h=c>0?c+i+e+l:0,u=0,f=n-L;if(i){let I=c>0?c-i:0,P=d>0?d-i:0,w=(I+P)/2,U=w!==0?f*w/(w+i):f;u=(f-U)/2}let g=Math.max(.001,f*d-e/rt)/d,m=(f-g)/2,p=L+m+u,b=n-m-u,{outerStart:C,outerEnd:S,innerStart:_,innerEnd:y}=ed(t,h,d,b-p),v=d-C,x=d-S,k=p+C/v,E=b-S/x,M=h+_,D=h+y,A=p+_/M,N=b-y/D;if(s.beginPath(),o){let I=(k+E)/2;if(s.arc(r,a,d,k,I),s.arc(r,a,d,I,E),S>0){let O=Ss(x,E,r,a);s.arc(O.x,O.y,S,E,b+pt)}let P=Ss(D,b,r,a);if(s.lineTo(P.x,P.y),y>0){let O=Ss(D,N,r,a);s.arc(O.x,O.y,y,b+pt,N+Math.PI)}let w=(b-y/h+(p+_/h))/2;if(s.arc(r,a,h,b-y/h,w,!0),s.arc(r,a,h,w,p+_/h,!0),_>0){let O=Ss(M,A,r,a);s.arc(O.x,O.y,_,A+Math.PI,p-pt)}let U=Ss(v,p,r,a);if(s.lineTo(U.x,U.y),C>0){let O=Ss(v,k,r,a);s.arc(O.x,O.y,C,p-pt,k)}}else{s.moveTo(r,a);let I=Math.cos(k)*d+r,P=Math.sin(k)*d+a;s.lineTo(I,P);let w=Math.cos(E)*d+r,U=Math.sin(E)*d+a;s.lineTo(w,U)}s.closePath()}function sd(s,t,e,i,n){let{fullCircles:o,startAngle:r,circumference:a}=t,L=t.endAngle;if(o){an(s,t,e,i,L,n);for(let l=0;l=rt&&u===0&&c!=="miter"&&Q1(s,t,g),o||(an(s,t,e,i,g,n),s.stroke())}function OL(s,t,e=t){s.lineCap=tt(e.borderCapStyle,t.borderCapStyle),s.setLineDash(tt(e.borderDash,t.borderDash)),s.lineDashOffset=tt(e.borderDashOffset,t.borderDashOffset),s.lineJoin=tt(e.borderJoinStyle,t.borderJoinStyle),s.lineWidth=tt(e.borderWidth,t.borderWidth),s.strokeStyle=tt(e.borderColor,t.borderColor)}function nd(s,t,e){s.lineTo(e.x,e.y)}function od(s){return s.stepped?ra:s.tension||s.cubicInterpolationMode==="monotone"?aa:nd}function FL(s,t,e={}){let i=s.length,{start:n=0,end:o=i-1}=e,{start:r,end:a}=t,L=Math.max(n,r),l=Math.min(o,a),c=na&&o>a;return{count:i,start:L,loop:t.loop,ilen:l(r+(l?a-S:S))%o,C=()=>{g!==m&&(s.lineTo(c,m),s.lineTo(c,g),s.lineTo(c,p))};for(L&&(u=n[b(0)],s.moveTo(u.x,u.y)),h=0;h<=a;++h){if(u=n[b(h)],u.skip)continue;let S=u.x,_=u.y,y=S|0;y===f?(_m&&(m=_),c=(d*c+S)/++d):(C(),s.lineTo(S,_),f=y,d=0,g=m=_),p=_}C()}function Vo(s){let t=s.options,e=t.borderDash&&t.borderDash.length;return!s._decimated&&!s._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!e?ad:rd}function Ld(s){return s.stepped?ga:s.tension||s.cubicInterpolationMode==="monotone"?ma:Ce}function ld(s,t,e,i){let n=t._path;n||(n=t._path=new Path2D,t.path(n,e,i)&&n.closePath()),OL(s,t.options),s.stroke(n)}function cd(s,t,e,i){let{segments:n,options:o}=t,r=Vo(t);for(let a of n)OL(s,o,a.style),s.beginPath(),r(s,t,a,{start:e,end:e+i-1})&&s.closePath(),s.stroke()}function hd(s,t,e,i){dd&&!t.options.segment?ld(s,t,e,i):cd(s,t,e,i)}function Ka(s,t,e,i){let n=s.options,{[e]:o}=s.getProps([e],i);return Math.abs(t-o)NL(t++)),t}function yd(s,t){return s.backgroundColor=s.data.map(()=>BL(t++)),t}function xd(s){let t=0;return(e,i)=>{let n=s.getDatasetMeta(i).controller;n instanceof oe?t=vd(e,t):n instanceof Ae?t=yd(e,t):n&&(t=bd(e,t))}}function Xa(s){let t;for(t in s)if(s[t].borderColor||s[t].backgroundColor)return!0;return!1}function Cd(s){return s&&(s.borderColor||s.backgroundColor)}function _d(){return ut.borderColor!=="rgba(0,0,0,0.1)"||ut.backgroundColor!=="rgba(0,0,0,0.1)"}function Sd(s,t,e,i,n){let o=n.samples||i;if(o>=e)return s.slice(t,t+e);let r=[],a=(e-2)/(o-2),L=0,l=t+e-1,c=t,d,h,u,f,g;for(r[L++]=s[c],d=0;du&&(u=f,h=s[b],g=b);r[L++]=h,c=g}return r[L++]=s[l],r}function kd(s,t,e,i){let n=0,o=0,r,a,L,l,c,d,h,u,f,g,m=[],p=t+e-1,b=s[t].x,S=s[p].x-b;for(r=t;rg&&(g=l,h=r),n=(o*n+a.x)/++o;else{let y=r-1;if(!st(d)&&!st(h)){let v=Math.min(d,h),x=Math.max(d,h);v!==u&&v!==y&&m.push({...s[v],x:n}),x!==u&&x!==y&&m.push({...s[x],x:n})}r>0&&y!==u&&m.push(s[y]),m.push(a),c=_,o=0,f=g=l,d=h=u=r}}return m}function zL(s){if(s._decimated){let t=s._data;delete s._decimated,delete s._data,Object.defineProperty(s,"data",{configurable:!0,enumerable:!0,writable:!0,value:t})}}function Qa(s){s.data.datasets.forEach(t=>{zL(t)})}function Ed(s,t){let e=t.length,i=0,n,{iScale:o}=s,{min:r,max:a,minDefined:L,maxDefined:l}=o.getUserBounds();return L&&(i=mt(Qt(t,o.axis,r).lo,0,e-1)),l?n=mt(Qt(t,o.axis,a).hi+1,i,e)-i:n=e-i,{start:i,count:n}}function Md(s,t,e){let i=s.segments,n=s.points,o=t.points,r=[];for(let a of i){let{start:L,end:l}=a;l=cn(L,l,n);let c=Bo(e,n[L],n[l],a.loop);if(!t.segments){r.push({source:a,target:c,start:n[L],end:n[l]});continue}let d=mo(t,c);for(let h of d){let u=Bo(e,o[h.start],o[h.end],h.loop),f=go(a,n,u);for(let g of f)r.push({source:g,target:h,start:{[e]:Ja(c,u,"start",Math.max)},end:{[e]:Ja(c,u,"end",Math.min)}})}}return r}function Bo(s,t,e,i){if(i)return;let n=t[s],o=e[s];return s==="angle"&&(n=yt(n),o=yt(o)),{property:s,start:n,end:o}}function wd(s,t){let{x:e=null,y:i=null}=s||{},n=t.points,o=[];return t.segments.forEach(({start:r,end:a})=>{a=cn(r,a,n);let L=n[r],l=n[a];i!==null?(o.push({x:L.x,y:i}),o.push({x:l.x,y:i})):e!==null&&(o.push({x:e,y:L.y}),o.push({x:e,y:l.y}))}),o}function cn(s,t,e){for(;t>s;t--){let i=e[t];if(!isNaN(i.x)&&!isNaN(i.y))break}return t}function Ja(s,t,e,i){return s&&t?i(s[e],t[e]):s?s[e]:t?t[e]:0}function ZL(s,t){let e=[],i=!1;return dt(s)?(i=!0,e=s):e=wd(s,t),e.length?new Yt({points:e,options:{tension:0},_loop:i,_fullLoop:i}):null}function tL(s){return s&&s.fill!==!1}function Dd(s,t,e){let n=s[t].fill,o=[t],r;if(!e)return n;for(;n!==!1&&o.indexOf(n)===-1;){if(!ft(n))return n;if(r=s[n],!r)return!1;if(r.visible)return n;o.push(n),n=r.fill}return!1}function Td(s,t,e){let i=Od(s);if(it(i))return isNaN(i.value)?!1:i;let n=parseFloat(i);return ft(n)&&Math.floor(n)===n?Ad(i[0],t,n,e):["origin","start","end","stack","shape"].indexOf(i)>=0&&i}function Ad(s,t,e,i){return(s==="-"||s==="+")&&(e=t+e),e===t||e<0||e>=i?!1:e}function Rd(s,t){let e=null;return s==="start"?e=t.bottom:s==="end"?e=t.top:it(s)?e=t.getPixelForValue(s.value):t.getBasePixel&&(e=t.getBasePixel()),e}function Pd(s,t,e){let i;return s==="start"?i=e:s==="end"?i=t.options.reverse?t.min:t.max:it(s)?i=s.value:i=t.getBaseValue(),i}function Od(s){let t=s.options,e=t.fill,i=tt(e&&e.target,e);return i===void 0&&(i=!!t.backgroundColor),i===!1||i===null?!1:i===!0?"origin":i}function Fd(s){let{scale:t,index:e,line:i}=s,n=[],o=i.segments,r=i.points,a=Id(t,e);a.push(ZL({x:null,y:t.bottom},i));for(let L=0;Lo.length>r.length?o:r)),t+e.size/2+i.measureText(n).width}function Kd(s,t,e){let i=s;return typeof t.text!="string"&&(i=jL(t,e)),i}function jL(s,t){let e=s.text?s.text.length:0;return t*e}function qd(s,t){return!!((s==="mousemove"||s==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(s==="click"||s==="mouseup"))}function Xd(s,t){let e=new ci({ctx:s.ctx,options:t,chart:s});_t.configure(s,e,t),_t.addBox(s,e),s.titleBlock=e}function se(s,t){return t&&(dt(t)?Array.prototype.push.apply(s,t):s.push(t)),s}function ue(s){return(typeof s=="string"||s instanceof String)&&s.indexOf(` +`,'"',a.BYTE_ORDER_MARK],a.WORKERS_SUPPORTED=!i&&!!t.Worker,a.NODE_STREAM_INPUT=1,a.LocalChunkSize=10485760,a.RemoteChunkSize=5242880,a.DefaultDelimiter=",",a.Parser=g,a.ParserHandle=u,a.NetworkStreamer=l,a.FileStreamer=c,a.StringStreamer=d,a.ReadableStreamStreamer=h,t.jQuery&&((e=t.jQuery).fn.parse=function(y){var v=y.config||{},x=[];return this.each(function(M){if(!(e(this).prop("tagName").toUpperCase()==="INPUT"&&e(this).attr("type").toLowerCase()==="file"&&t.FileReader)||!this.files||this.files.length===0)return!0;for(var D=0;De-i*Math.max(Math.min(r-3,9-r,1),-1);return[n(0),n(8),n(4)]}function bc(s,t,e){let i=(n,o=(n+s/60)%6)=>e-e*t*Math.max(Math.min(o,4-o,1),0);return[i(5),i(3),i(1)]}function vc(s,t,e){let i=Pr(s,1,.5),n;for(t+e>1&&(n=1/(t+e),t*=n,e*=n),n=0;n<3;n++)i[n]*=1-t-e,i[n]+=t;return i}function yc(s,t,e,i,n){return s===n?(t-e)/i+(t.5?c/(2-o-r):c/(o+r),L=yc(e,i,n,c,o),L=L*60+.5),[L|0,l||0,a]}function $n(s,t,e,i){return(Array.isArray(t)?s(t[0],t[1],t[2]):s(t,e,i)).map(xe)}function zn(s,t,e){return $n(Pr,s,t,e)}function xc(s,t,e){return $n(vc,s,t,e)}function Cc(s,t,e){return $n(bc,s,t,e)}function Or(s){return(s%360+360)%360}function _c(s){let t=mc.exec(s),e=255,i;if(!t)return;t[5]!==i&&(e=t[6]?js(+t[5]):xe(+t[5]));let n=Or(+t[2]),o=+t[3]/100,r=+t[4]/100;return t[1]==="hwb"?i=xc(n,o,r):t[1]==="hsv"?i=Cc(n,o,r):i=zn(n,o,r),{r:i[0],g:i[1],b:i[2],a:e}}function Sc(s,t){var e=Bn(s);e[0]=Or(e[0]+t),e=zn(e),s.r=e[0],s.g=e[1],s.b=e[2]}function kc(s){if(!s)return;let t=Bn(s),e=t[0],i=Dr(t[1]),n=Dr(t[2]);return s.a<255?`hsla(${e}, ${i}%, ${n}%, ${Le(s.a)})`:`hsl(${e}, ${i}%, ${n}%)`}function Ec(){let s={},t=Object.keys(Ar),e=Object.keys(Tr),i,n,o,r,a;for(i=0;i>16&255,o>>8&255,o&255]}return s}function Mc(s){wi||(wi=Ec(),wi.transparent=[0,0,0,0]);let t=wi[s.toLowerCase()];return t&&{r:t[0],g:t[1],b:t[2],a:t.length===4?t[3]:255}}function Dc(s){let t=wc.exec(s),e=255,i,n,o;if(t){if(t[7]!==i){let r=+t[7];e=t[8]?js(r):ye(r*255,0,255)}return i=+t[1],n=+t[3],o=+t[5],i=255&(t[2]?js(i):ye(i,0,255)),n=255&(t[4]?js(n):ye(n,0,255)),o=255&(t[6]?js(o):ye(o,0,255)),{r:i,g:n,b:o,a:e}}}function Tc(s){return s&&(s.a<255?`rgba(${s.r}, ${s.g}, ${s.b}, ${Le(s.a)})`:`rgb(${s.r}, ${s.g}, ${s.b})`)}function Ac(s,t,e){let i=hs(Le(s.r)),n=hs(Le(s.g)),o=hs(Le(s.b));return{r:xe(Vn(i+e*(hs(Le(t.r))-i))),g:xe(Vn(n+e*(hs(Le(t.g))-n))),b:xe(Vn(o+e*(hs(Le(t.b))-o))),a:s.a+e*(t.a-s.a)}}function Di(s,t,e){if(s){let i=Bn(s);i[t]=Math.max(0,Math.min(i[t]+i[t]*e,t===0?360:1)),i=zn(i),s.r=i[0],s.g=i[1],s.b=i[2]}}function Fr(s,t){return s&&Object.assign(t||{},s)}function Rr(s){var t={r:0,g:0,b:0,a:255};return Array.isArray(s)?s.length>=3&&(t={r:s[0],g:s[1],b:s[2],a:255},s.length>3&&(t.a=xe(s[3]))):(t=Fr(s,{r:0,g:0,b:0,a:1}),t.a=xe(t.a)),t}function Rc(s){return s.charAt(0)==="r"?Dc(s):_c(s)}var ye,Ht,Nn,dc,hc,Mi,uc,pc,mc,Tr,Ar,wi,wc,Vn,hs,Us,Ir=Mn(()=>{ye=(s,t,e)=>Math.max(Math.min(s,e),t);Ht={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Nn=[..."0123456789ABCDEF"],dc=s=>Nn[s&15],hc=s=>Nn[(s&240)>>4]+Nn[s&15],Mi=s=>(s&240)>>4===(s&15),uc=s=>Mi(s.r)&&Mi(s.g)&&Mi(s.b)&&Mi(s.a);pc=(s,t)=>s<255?t(s):"";mc=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;Tr={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Ar={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};wc=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;Vn=s=>s<=.0031308?s*12.92:Math.pow(s,1/2.4)*1.055-.055,hs=s=>s<=.04045?s/12.92:Math.pow((s+.055)/1.055,2.4);Us=class s{constructor(t){if(t instanceof s)return t;let e=typeof t,i;e==="object"?i=Rr(t):e==="string"&&(i=fc(t)||Mc(t)||Rc(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=Fr(this._rgb);return t&&(t.a=Le(t.a)),t}set rgb(t){this._rgb=Rr(t)}rgbString(){return this._valid?Tc(this._rgb):void 0}hexString(){return this._valid?gc(this._rgb):void 0}hslString(){return this._valid?kc(this._rgb):void 0}mix(t,e){if(t){let i=this.rgb,n=t.rgb,o,r=e===o?.5:e,a=2*r-1,L=i.a-n.a,l=((a*L===-1?a:(a+L)/(1+a*L))+1)/2;o=1-l,i.r=255&l*i.r+o*n.r+.5,i.g=255&l*i.g+o*n.g+.5,i.b=255&l*i.b+o*n.b+.5,i.a=r*i.a+(1-r)*n.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=Ac(this._rgb,t._rgb,e)),this}clone(){return new s(this.rgb)}alpha(t){return this._rgb.a=xe(t),this}clearer(t){let e=this._rgb;return e.a*=1-t,this}greyscale(){let t=this._rgb,e=Ys(t.r*.3+t.g*.59+t.b*.11);return t.r=t.g=t.b=e,this}opaquer(t){let e=this._rgb;return e.a*=1+t,this}negate(){let t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Di(this._rgb,2,t),this}darken(t){return Di(this._rgb,2,-t),this}saturate(t){return Di(this._rgb,1,t),this}desaturate(t){return Di(this._rgb,1,-t),this}rotate(t){return Sc(this._rgb,t),this}}});function ee(){}function st(s){return s==null}function dt(s){if(Array.isArray&&Array.isArray(s))return!0;let t=Object.prototype.toString.call(s);return t.slice(0,7)==="[object"&&t.slice(-6)==="Array]"}function it(s){return s!==null&&Object.prototype.toString.call(s)==="[object Object]"}function ft(s){return(typeof s=="number"||s instanceof Number)&&isFinite(+s)}function Ot(s,t){return ft(s)?s:t}function tt(s,t){return typeof s=="undefined"?t:s}function ct(s,t,e){if(s&&typeof s.call=="function")return s.apply(e,t)}function Lt(s,t,e,i){let n,o,r;if(dt(s))if(o=s.length,i)for(n=o-1;n>=0;n--)t.call(e,s[n],n);else for(n=0;n{for(let i of t){if(i==="")break;e=e&&e[i]}return e}}function de(s,t){return(Vr[t]||(Vr[t]=Ic(t)))(s)}function Vi(s){return s.charAt(0).toUpperCase()+s.slice(1)}function qr(s){return s.type==="mouseup"||s.type==="click"||s.type==="contextmenu"}function bs(s,t,e){return Math.abs(s-t)n-o).pop(),t}function Bc(s){return typeof s=="symbol"||typeof s=="object"&&s!==null&&!(Symbol.toPrimitive in s||"toString"in s||"valueOf"in s)}function Ze(s){return!Bc(s)&&!isNaN(parseFloat(s))&&isFinite(s)}function Qr(s,t){let e=Math.round(s);return e-t<=s&&e+t>=s}function Gn(s,t,e){let i,n,o;for(i=0,n=s.length;iL&&l=Math.min(t,e)-i&&s<=Math.max(t,e)+i}function Bi(s,t,e){e=e||(r=>s[r]1;)o=n+i>>1,e(o)?n=o:i=o;return{lo:n,hi:i}}function ea(s,t,e){let i=0,n=s.length;for(;ii&&s[n-1]>e;)n--;return i>0||n{let i="_onData"+Vi(e),n=s[e];Object.defineProperty(s,e,{configurable:!0,enumerable:!1,value(...o){let r=n.apply(this,o);return s._chartjs.listeners.forEach(a=>{typeof a[i]=="function"&&a[i](...o)}),r}})})}function Xn(s,t){let e=s._chartjs;if(!e)return;let i=e.listeners,n=i.indexOf(t);n!==-1&&i.splice(n,1),!(i.length>0)&&(sa.forEach(o=>{delete s[o]}),delete s._chartjs)}function Qn(s){let t=new Set(s);return t.size===s.length?s:Array.from(t)}function to(s,t){let e=[],i=!1;return function(...n){e=n,i||(i=!0,Jn.call(window,()=>{i=!1,s.apply(t,e)}))}}function na(s,t){let e;return function(...i){return t?(clearTimeout(e),e=setTimeout(s,t,i)):s.apply(this,i),t}}function eo(s,t,e){let i=t.length,n=0,o=i;if(s._sorted){let{iScale:r,vScale:a,_parsed:L}=s,l=s.dataset&&s.dataset.options?s.dataset.options.spanGaps:null,c=r.axis,{min:d,max:h,minDefined:u,maxDefined:f}=r.getUserBounds();if(u){if(n=Math.min(Jt(L,c,d).lo,e?i:Jt(t,c,r.getPixelForValue(d)).lo),l){let g=L.slice(0,n+1).reverse().findIndex(m=>!st(m[a.axis]));n-=Math.max(0,g)}n=mt(n,0,i-1)}if(f){let g=Math.max(Jt(L,r.axis,h,!0).hi+1,e?0:Jt(t,c,r.getPixelForValue(h),!0).hi+1);if(l){let m=L.slice(g-1).findIndex(p=>!st(p[a.axis]));g+=Math.max(0,m)}o=mt(g,n,i)-n}else o=i-n}return{start:n,count:o}}function so(s){let{xScale:t,yScale:e,_scaleRanges:i}=s,n={xmin:t.min,xmax:t.max,ymin:e.min,ymax:e.max};if(!i)return s._scaleRanges=n,!0;let o=i.xmin!==t.min||i.xmax!==t.max||i.ymin!==e.min||i.ymax!==e.max;return Object.assign(i,n),o}function io(s){if(s&&typeof s=="object"){let t=s.toString();return t==="[object CanvasPattern]"||t==="[object CanvasGradient]"}return!1}function no(s){return io(s)?s:new Us(s)}function Hn(s){return io(s)?s:new Us(s).saturate(.5).darken(.1).hexString()}function Zc(s){s.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),s.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>t!=="onProgress"&&t!=="onComplete"&&t!=="fn"}),s.set("animations",{colors:{type:"color",properties:Hc},numbers:{type:"number",properties:zc}}),s.describe("animations",{_fallback:"animation"}),s.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>t|0}}}})}function Wc(s){s.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}function jc(s,t){t=t||{};let e=s+JSON.stringify(t),i=zr.get(e);return i||(i=new Intl.NumberFormat(s,t),zr.set(e,i)),i}function ys(s,t,e){return jc(t,e).format(s)}function Uc(s,t){let e=t.length>3?t[2].value-t[1].value:t[1].value-t[0].value;return Math.abs(e)>=1&&s!==Math.floor(s)&&(e=s-Math.floor(s)),e}function Yc(s){s.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:xs.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),s.route("scale.ticks","color","","color"),s.route("scale.grid","color","","borderColor"),s.route("scale.border","color","","borderColor"),s.route("scale.title","color","","color"),s.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&t!=="callback"&&t!=="parser",_indexable:t=>t!=="borderDash"&&t!=="tickBorderDash"&&t!=="dash"}),s.describe("scales",{_fallback:"scale"}),s.describe("scale.ticks",{_scriptable:t=>t!=="backdropPadding"&&t!=="callback",_indexable:t=>t!=="backdropPadding"})}function Gs(s,t){if(!t)return s;let e=t.split(".");for(let i=0,n=e.length;ii&&(i=o),i}function aa(s,t,e,i){i=i||{};let n=i.data=i.data||{},o=i.garbageCollect=i.garbageCollect||[];i.font!==t&&(n=i.data={},o=i.garbageCollect=[],i.font=t),s.save(),s.font=t;let r=0,a=e.length,L,l,c,d,h;for(L=0;Le.length){for(L=0;L0&&s.stroke()}}function te(s,t,e){return e=e||.5,!t||s&&s.x>t.left-e&&s.xt.top-e&&s.y0&&o.strokeColor!=="",L,l;for(s.save(),s.font=n.string,Kc(s,o),L=0;Ltt(s[r],s[t[r]]):r=>s[r]:()=>s;for(let r of n)e[r]=e2(o(r));return e}function ao(s){return Zi(s,{top:"y",right:"x",bottom:"y",left:"x"})}function Me(s){return Zi(s,["topLeft","topRight","bottomLeft","bottomRight"])}function Ct(s){let t=ao(s);return t.width=t.left+t.right,t.height=t.top+t.bottom,t}function gt(s,t){s=s||{},t=t||ut.font;let e=tt(s.size,t.size);typeof e=="string"&&(e=parseInt(e,10));let i=tt(s.style,t.style);i&&!(""+i).match(Jc)&&(console.warn('Invalid font style specified: "'+i+'"'),i=void 0);let n={family:tt(s.family,t.family),lineHeight:t2(tt(s.lineHeight,t.lineHeight),e),size:e,style:i,weight:tt(s.weight,t.weight),string:""};return n.string=Gc(n),n}function _s(s,t,e,i){let n=!0,o,r,a;for(o=0,r=s.length;oe&&a===0?0:a+L;return{min:r(i,-Math.abs(o)),max:r(n,o)}}function he(s,t){return Object.assign(Object.create(s),t)}function Wi(s,t=[""],e,i,n=()=>s[0]){let o=e||s;typeof i=="undefined"&&(i=ua("_fallback",s));let r={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:s,_rootScopes:o,_fallback:i,_getTarget:n,override:a=>Wi([a,...s],t,o,i)};return new Proxy(r,{deleteProperty(a,L){return delete a[L],delete a._keys,delete s[0][L],!0},get(a,L){return da(a,L,()=>l2(L,t,s,a))},getOwnPropertyDescriptor(a,L){return Reflect.getOwnPropertyDescriptor(a._scopes[0],L)},getPrototypeOf(){return Reflect.getPrototypeOf(s[0])},has(a,L){return Zr(a).includes(L)},ownKeys(a){return Zr(a)},set(a,L,l){let c=a._storage||(a._storage=n());return a[L]=c[L]=l,delete a._keys,!0}})}function He(s,t,e,i){let n={_cacheable:!1,_proxy:s,_context:t,_subProxy:e,_stack:new Set,_descriptors:Lo(s,i),setContext:o=>He(s,o,e,i),override:o=>He(s.override(o),t,e,i)};return new Proxy(n,{deleteProperty(o,r){return delete o[r],delete s[r],!0},get(o,r,a){return da(o,r,()=>i2(o,r,a))},getOwnPropertyDescriptor(o,r){return o._descriptors.allKeys?Reflect.has(s,r)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(s,r)},getPrototypeOf(){return Reflect.getPrototypeOf(s)},has(o,r){return Reflect.has(s,r)},ownKeys(){return Reflect.ownKeys(s)},set(o,r,a){return s[r]=a,delete o[r],!0}})}function Lo(s,t={scriptable:!0,indexable:!0}){let{_scriptable:e=t.scriptable,_indexable:i=t.indexable,_allKeys:n=t.allKeys}=s;return{allKeys:n,scriptable:e,indexable:i,isScriptable:le(e)?e:()=>e,isIndexable:le(i)?i:()=>i}}function da(s,t,e){if(Object.prototype.hasOwnProperty.call(s,t)||t==="constructor")return s[t];let i=e();return s[t]=i,i}function i2(s,t,e){let{_proxy:i,_context:n,_subProxy:o,_descriptors:r}=s,a=i[t];return le(a)&&r.isScriptable(t)&&(a=n2(t,a,s,e)),dt(a)&&a.length&&(a=o2(t,a,s,r.isIndexable)),lo(t,a)&&(a=He(a,n,o&&o[t],r)),a}function n2(s,t,e,i){let{_proxy:n,_context:o,_subProxy:r,_stack:a}=e;if(a.has(s))throw new Error("Recursion detected: "+Array.from(a).join("->")+"->"+s);a.add(s);let L=t(o,r||i);return a.delete(s),lo(s,L)&&(L=co(n._scopes,n,s,L)),L}function o2(s,t,e,i){let{_proxy:n,_context:o,_subProxy:r,_descriptors:a}=e;if(typeof o.index!="undefined"&&i(s))return t[o.index%t.length];if(it(t[0])){let L=t,l=n._scopes.filter(c=>c!==L);t=[];for(let c of L){let d=co(l,n,s,c);t.push(He(d,o,r&&r[s],a))}}return t}function ha(s,t,e){return le(s)?s(t,e):s}function a2(s,t,e,i,n){for(let o of t){let r=r2(e,o);if(r){s.add(r);let a=ha(r._fallback,e,n);if(typeof a!="undefined"&&a!==e&&a!==i)return a}else if(r===!1&&typeof i!="undefined"&&e!==i)return null}return!1}function co(s,t,e,i){let n=t._rootScopes,o=ha(t._fallback,e,i),r=[...s,...n],a=new Set;a.add(i);let L=Hr(a,r,e,o||e,i);return L===null||typeof o!="undefined"&&o!==e&&(L=Hr(a,r,o,L,i),L===null)?!1:Wi(Array.from(a),[""],n,o,()=>L2(t,e,i))}function Hr(s,t,e,i,n){for(;e;)e=a2(s,t,e,i,n);return e}function L2(s,t,e){let i=s._getTarget();t in i||(i[t]={});let n=i[t];return dt(n)&&it(e)?e:n||{}}function l2(s,t,e,i){let n;for(let o of t)if(n=ua(s2(o,s),e),typeof n!="undefined")return lo(s,n)?co(e,i,s,n):n}function ua(s,t){for(let e of t){if(!e)continue;let i=e[s];if(typeof i!="undefined")return i}}function Zr(s){let t=s._keys;return t||(t=s._keys=c2(s._scopes)),t}function c2(s){let t=new Set;for(let e of s)for(let i of Object.keys(e).filter(n=>!n.startsWith("_")))t.add(i);return Array.from(t)}function ho(s,t,e,i){let{iScale:n}=s,{key:o="r"}=this._parsing,r=new Array(i),a,L,l,c;for(a=0,L=i;a!l.skip)),t.cubicInterpolationMode==="monotone")p2(s,n);else{let l=i?s[s.length-1]:s[0];for(o=0,r=s.length;oL.height&&(c=L.height,l=_e(Math.floor(c*i))),{width:l,height:c}}function uo(s,t,e){let i=t||1,n=_e(s.height*i),o=_e(s.width*i);s.height=_e(s.height),s.width=_e(s.width);let r=s.canvas;return r.style&&(e||!r.style.height&&!r.style.width)&&(r.style.height=`${s.height}px`,r.style.width=`${s.width}px`),s.currentDevicePixelRatio!==i||r.height!==n||r.width!==o?(s.currentDevicePixelRatio=i,r.height=n,r.width=o,s.ctx.setTransform(i,0,0,i,0,0),!0):!1}function fo(s,t){let e=m2(s,t),i=e&&e.match(/^(\d+)(\.\d+)?px$/);return i?+i[1]:void 0}function Ce(s,t,e,i){return{x:s.x+e*(t.x-s.x),y:s.y+e*(t.y-s.y)}}function ba(s,t,e,i){return{x:s.x+e*(t.x-s.x),y:i==="middle"?e<.5?s.y:t.y:i==="after"?e<1?s.y:t.y:e>0?t.y:s.y}}function va(s,t,e,i){let n={x:s.cp2x,y:s.cp2y},o={x:t.cp1x,y:t.cp1y},r=Ce(s,n,e),a=Ce(n,o,e),L=Ce(o,t,e),l=Ce(r,a,e),c=Ce(a,L,e);return Ce(l,c,e)}function We(s,t,e){return s?C2(t,e):_2()}function po(s,t){let e,i;(t==="ltr"||t==="rtl")&&(e=s.canvas.style,i=[e.getPropertyValue("direction"),e.getPropertyPriority("direction")],e.setProperty("direction",t,"important"),s.prevTextDirection=i)}function go(s,t){t!==void 0&&(delete s.prevTextDirection,s.canvas.style.setProperty("direction",t[0],t[1]))}function ya(s){return s==="angle"?{between:vs,compare:$c,normalize:yt}:{between:se,compare:(t,e)=>t-e,normalize:t=>t}}function Wr({start:s,end:t,count:e,loop:i,style:n}){return{start:s%e,end:t%e,loop:i&&(t-s+1)%e===0,style:n}}function S2(s,t,e){let{property:i,start:n,end:o}=e,{between:r,normalize:a}=ya(i),L=t.length,{start:l,end:c,loop:d}=s,h,u;if(d){for(l+=L,c+=L,h=0,u=L;hL(n,C,p)&&a(n,C)!==0,_=()=>a(o,p)===0||L(o,C,p),y=()=>g||S(),v=()=>!g||_();for(let x=c,k=c;x<=d;++x)b=t[x%r],!b.skip&&(p=l(b[i]),p!==C&&(g=L(p,n,o),m===null&&y()&&(m=a(p,n)===0?x:k),m!==null&&v()&&(f.push(Wr({start:m,end:x,loop:h,count:r,style:u})),m=null),k=x,C=p));return m!==null&&f.push(Wr({start:m,end:d,loop:h,count:r,style:u})),f}function bo(s,t){let e=[],i=s.segments;for(let n=0;nn&&s[o%t].skip;)o--;return o%=t,{start:n,end:o}}function E2(s,t,e,i){let n=s.length,o=[],r=t,a=s[t],L;for(L=t+1;L<=e;++L){let l=s[L%n];l.skip||l.stop?a.skip||(i=!1,o.push({start:t%n,end:(L-1)%n,loop:i}),t=r=l.stop?L:null):(r=L,a.skip&&(t=L)),a=l}return r!==null&&o.push({start:t%n,end:r%n,loop:i}),o}function xa(s,t){let e=s.points,i=s.options.spanGaps,n=e.length;if(!n)return[];let o=!!s._loop,{start:r,end:a}=k2(e,n,o,i);if(i===!0)return jr(s,[{start:r,end:a,loop:o}],e,t);let L=a{Ir();Yr=(()=>{let s=0;return()=>s++})();Gr=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100:+s/t,jn=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100*t:+s;Vr={"":s=>s,x:s=>s.x,y:s=>s.y};ms=s=>typeof s!="undefined",le=s=>typeof s=="function",Un=(s,t)=>{if(s.size!==t.size)return!1;for(let e of s)if(!t.has(e))return!1;return!0};rt=Math.PI,ht=2*rt,Vc=ht+rt,Oi=Number.POSITIVE_INFINITY,Nc=rt/180,pt=rt/2,$e=rt/4,Nr=rt*2/3,ce=Math.log10,Ut=Math.sign;Jt=(s,t,e,i)=>Bi(s,e,i?n=>{let o=s[n][t];return os[n][t]Bi(s,e,i=>s[i][t]>=e);sa=["push","pop","shift","splice","unshift"];Jn=function(){return typeof window=="undefined"?function(s){return s()}:window.requestAnimationFrame}();$i=s=>s==="start"?"left":s==="end"?"right":"center",xt=(s,t,e)=>s==="start"?t:s==="end"?e:(t+e)/2,oa=(s,t,e,i)=>s===(i?"left":"right")?e:s==="center"?(t+e)/2:t;Ti=s=>s===0||s===1,Br=(s,t,e)=>-(Math.pow(2,10*(s-=1))*Math.sin((s-t)*ht/e)),$r=(s,t,e)=>Math.pow(2,-10*s)*Math.sin((s-t)*ht/e)+1,us={linear:s=>s,easeInQuad:s=>s*s,easeOutQuad:s=>-s*(s-2),easeInOutQuad:s=>(s/=.5)<1?.5*s*s:-.5*(--s*(s-2)-1),easeInCubic:s=>s*s*s,easeOutCubic:s=>(s-=1)*s*s+1,easeInOutCubic:s=>(s/=.5)<1?.5*s*s*s:.5*((s-=2)*s*s+2),easeInQuart:s=>s*s*s*s,easeOutQuart:s=>-((s-=1)*s*s*s-1),easeInOutQuart:s=>(s/=.5)<1?.5*s*s*s*s:-.5*((s-=2)*s*s*s-2),easeInQuint:s=>s*s*s*s*s,easeOutQuint:s=>(s-=1)*s*s*s*s+1,easeInOutQuint:s=>(s/=.5)<1?.5*s*s*s*s*s:.5*((s-=2)*s*s*s*s+2),easeInSine:s=>-Math.cos(s*pt)+1,easeOutSine:s=>Math.sin(s*pt),easeInOutSine:s=>-.5*(Math.cos(rt*s)-1),easeInExpo:s=>s===0?0:Math.pow(2,10*(s-1)),easeOutExpo:s=>s===1?1:-Math.pow(2,-10*s)+1,easeInOutExpo:s=>Ti(s)?s:s<.5?.5*Math.pow(2,10*(s*2-1)):.5*(-Math.pow(2,-10*(s*2-1))+2),easeInCirc:s=>s>=1?s:-(Math.sqrt(1-s*s)-1),easeOutCirc:s=>Math.sqrt(1-(s-=1)*s),easeInOutCirc:s=>(s/=.5)<1?-.5*(Math.sqrt(1-s*s)-1):.5*(Math.sqrt(1-(s-=2)*s)+1),easeInElastic:s=>Ti(s)?s:Br(s,.075,.3),easeOutElastic:s=>Ti(s)?s:$r(s,.075,.3),easeInOutElastic(s){return Ti(s)?s:s<.5?.5*Br(s*2,.1125,.45):.5+.5*$r(s*2-1,.1125,.45)},easeInBack(s){return s*s*((1.70158+1)*s-1.70158)},easeOutBack(s){return(s-=1)*s*((1.70158+1)*s+1.70158)+1},easeInOutBack(s){let t=1.70158;return(s/=.5)<1?.5*(s*s*(((t*=1.525)+1)*s-t)):.5*((s-=2)*s*(((t*=1.525)+1)*s+t)+2)},easeInBounce:s=>1-us.easeOutBounce(1-s),easeOutBounce(s){return s<1/2.75?7.5625*s*s:s<2/2.75?7.5625*(s-=1.5/2.75)*s+.75:s<2.5/2.75?7.5625*(s-=2.25/2.75)*s+.9375:7.5625*(s-=2.625/2.75)*s+.984375},easeInOutBounce:s=>s<.5?us.easeInBounce(s*2)*.5:us.easeOutBounce(s*2-1)*.5+.5};zc=["x","y","borderWidth","radius","tension"],Hc=["color","borderColor","backgroundColor"];zr=new Map;ra={values(s){return dt(s)?s:""+s},numeric(s,t,e){if(s===0)return"0";let i=this.chart.options.locale,n,o=s;if(e.length>1){let l=Math.max(Math.abs(e[0].value),Math.abs(e[e.length-1].value));(l<1e-4||l>1e15)&&(n="scientific"),o=Uc(s,e)}let r=ce(Math.abs(o)),a=isNaN(r)?1:Math.max(Math.min(-1*Math.floor(r),20),0),L={notation:n,minimumFractionDigits:a,maximumFractionDigits:a};return Object.assign(L,this.options.ticks.format),ys(s,i,L)},logarithmic(s,t,e){if(s===0)return"0";let i=e[t].significand||s/Math.pow(10,Math.floor(ce(s)));return[1,2,3,5,10,15].includes(i)||t>.8*e.length?ra.numeric.call(this,s,t,e):""}};xs={formatters:ra};Se=Object.create(null),zi=Object.create(null);Wn=class{constructor(t,e){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=i=>i.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(i,n)=>Hn(n.backgroundColor),this.hoverBorderColor=(i,n)=>Hn(n.borderColor),this.hoverColor=(i,n)=>Hn(n.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return Zn(this,t,e)}get(t){return Gs(this,t)}describe(t,e){return Zn(zi,t,e)}override(t,e){return Zn(Se,t,e)}route(t,e,i,n){let o=Gs(this,t),r=Gs(this,i),a="_"+e;Object.defineProperties(o,{[a]:{value:o[e],writable:!0},[e]:{enumerable:!0,get(){let L=this[a],l=r[n];return it(L)?Object.assign({},l,L):tt(L,l)},set(L){this[a]=L}}})}apply(t){t.forEach(e=>e(this))}},ut=new Wn({_scriptable:s=>!s.startsWith("on"),_indexable:s=>s!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[Zc,Wc,Yc]);Qc=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,Jc=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;e2=s=>+s||0;s2=(s,t)=>s?s+Vi(t):t,lo=(s,t)=>it(t)&&s!=="adapters"&&(Object.getPrototypeOf(t)===null||t.constructor===Object);r2=(s,t)=>s===!0?t:typeof s=="string"?de(t,s):void 0;d2=Number.EPSILON||1e-14,ps=(s,t)=>ts==="x"?"y":"x";Yi=s=>s.ownerDocument.defaultView.getComputedStyle(s,null);b2=["top","right","bottom","left"];v2=(s,t,e)=>(s>0||t>0)&&(!e||!e.shadowRoot);_e=s=>Math.round(s*10)/10;ma=function(){let s=!1;try{let t={get passive(){return s=!0,!1}};ji()&&(window.addEventListener("test",null,t),window.removeEventListener("test",null,t))}catch(t){}return s}();C2=function(s,t){return{x(e){return s+s+t-e},setWidth(e){t=e},textAlign(e){return e==="center"?e:e==="right"?"left":"right"},xPlus(e,i){return e-i},leftForLtr(e,i){return e-i}}},_2=function(){return{x(s){return s},setWidth(s){},textAlign(s){return s},xPlus(s,t){return s+t},leftForLtr(s,t){return s}}}});var sl={};sr(sl,{Animation:()=>sn,Animations:()=>ai,ArcElement:()=>De,BarController:()=>Ye,BarElement:()=>Je,BasePlatform:()=>Li,BasicPlatform:()=>nn,BubbleController:()=>Ge,CategoryScale:()=>Ms,Chart:()=>oe,Colors:()=>HL,DatasetController:()=>It,Decimation:()=>WL,DomPlatform:()=>rn,DoughnutController:()=>re,Element:()=>Nt,Filler:()=>UL,Interaction:()=>EL,Legend:()=>GL,LineController:()=>Ke,LineElement:()=>Gt,LinearScale:()=>ws,LogarithmicScale:()=>Ds,PieController:()=>ks,PointElement:()=>Qe,PolarAreaController:()=>Ae,RadarController:()=>qe,RadialLinearScale:()=>Te,Scale:()=>Oe,ScatterController:()=>Xe,SubTitle:()=>qL,Ticks:()=>xs,TimeScale:()=>Pe,TimeSeriesScale:()=>Ts,Title:()=>KL,Tooltip:()=>QL,_adapters:()=>kL,_detectPlatform:()=>AL,animator:()=>ne,controllers:()=>SL,defaults:()=>ut,elements:()=>BL,layouts:()=>_t,plugins:()=>JL,registerables:()=>D5,registry:()=>Yt,scales:()=>el});function A2(s,t){let e=[],i=Object.keys(t);for(let n=0;n0||!e&&o<0)return n.index}return null}function Ma(s,t){let{chart:e,_cachedMeta:i}=s,n=e._stacks||(e._stacks={}),{iScale:o,vScale:r,index:a}=i,L=o.axis,l=r.axis,c=I2(o,r,i),d=t.length,h;for(let u=0;ue[i].axis===t).shift()}function B2(s,t){return he(s,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function $2(s,t,e){return he(s,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:e,index:t,mode:"default",type:"data"})}function Js(s,t){let e=s.controller.index,i=s.vScale&&s.vScale.axis;if(i){t=t||s._parsed;for(let n of t){let o=n._stacks;if(!o||o[i]===void 0||o[i][e]===void 0)return;delete o[i][e],o[i]._visualValues!==void 0&&o[i]._visualValues[e]!==void 0&&delete o[i]._visualValues[e]}}}function H2(s,t){if(!s._cache.$bar){let e=s.getMatchingVisibleMetas(t),i=[];for(let n=0,o=e.length;nn-o))}return s._cache.$bar}function Z2(s){let t=s.iScale,e=H2(t,s.type),i=t._length,n,o,r,a,L=()=>{r===32767||r===-32768||(ms(a)&&(i=Math.min(i,Math.abs(r-a)||i)),a=r)};for(n=0,o=e.length;n0?n[s-1]:null,a=sMath.abs(a)&&(L=a,l=r),t[e.axis]=l,t._custom={barStart:L,barEnd:l,start:n,end:o,min:r,max:a}}function _L(s,t,e,i){return dt(s)?U2(s,t,e,i):t[e.axis]=e.parse(s,i),t}function Da(s,t,e,i){let n=s.iScale,o=s.vScale,r=n.getLabels(),a=n===o,L=[],l,c,d,h;for(l=e,c=e+i;l=e?1:-1)}function G2(s){let t,e,i,n,o;return s.horizontal?(t=s.base>s.x,e="left",i="right"):(t=s.basevs(C,a,L,!0)?1:Math.max(S,S*e,_,_*e),f=(C,S,_)=>vs(C,a,L,!0)?-1:Math.min(S,S*e,_,_*e),g=u(0,l,d),m=u(pt,c,h),p=f(rt,l,d),b=f(rt+pt,c,h);i=(g-p)/2,n=(m-b)/2,o=-(g+p)/2,r=-(m+b)/2}return{ratioX:i,ratioY:n,offsetX:o,offsetY:r}}function je(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}function J2(s,t,e,i){let{controller:n,data:o,_sorted:r}=s,a=n._cachedMeta.iScale,L=s.dataset&&s.dataset.options?s.dataset.options.spanGaps:null;if(a&&t===a.axis&&t!=="r"&&r&&o.length){let l=a._reversePixels?ta:Jt;if(i){if(n._sharedOptions){let c=o[0],d=typeof c.getRange=="function"&&c.getRange(t);if(d){let h=l(o,t,e-d),u=l(o,t,e+d);return{lo:h.lo,hi:u.hi}}}}else{let c=l(o,t,e);if(L){let{vScale:d}=n._cachedMeta,{_parsed:h}=s,u=h.slice(0,c.lo+1).reverse().findIndex(g=>!st(g[d.axis]));c.lo-=Math.max(0,u);let f=h.slice(c.hi).findIndex(g=>!st(g[d.axis]));c.hi+=Math.max(0,f)}return c}}return{lo:0,hi:o.length-1}}function hi(s,t,e,i,n){let o=s.getSortedVisibleDatasetMetas(),r=e[t];for(let a=0,L=o.length;a{L[r]&&L[r](t[e],n)&&(o.push({element:L,datasetIndex:l,index:c}),a=a||L.inRange(t.x,t.y,n))}),i&&!a?[]:o}function ti(s,t){return s.filter(e=>e.pos===t)}function Pa(s,t){return s.filter(e=>ML.indexOf(e.pos)===-1&&e.box.axis===t)}function ei(s,t){return s.sort((e,i)=>{let n=t?i:e,o=t?e:i;return n.weight===o.weight?n.index-o.index:n.weight-o.weight})}function i1(s){let t=[],e,i,n,o,r,a;for(e=0,i=(s||[]).length;el.box.fullSize),!0),i=ei(ti(t,"left"),!0),n=ei(ti(t,"right")),o=ei(ti(t,"top"),!0),r=ei(ti(t,"bottom")),a=Pa(t,"x"),L=Pa(t,"y");return{fullSize:e,leftAndTop:i.concat(o),rightAndBottom:n.concat(L).concat(r).concat(a),chartArea:ti(t,"chartArea"),vertical:i.concat(n).concat(L),horizontal:o.concat(r).concat(a)}}function Oa(s,t,e,i){return Math.max(s[e],t[e])+Math.max(s[i],t[i])}function wL(s,t){s.top=Math.max(s.top,t.top),s.left=Math.max(s.left,t.left),s.bottom=Math.max(s.bottom,t.bottom),s.right=Math.max(s.right,t.right)}function a1(s,t,e,i){let{pos:n,box:o}=e,r=s.maxPadding;if(!it(n)){e.size&&(s[n]-=e.size);let d=i[e.stack]||{size:0,count:1};d.size=Math.max(d.size,e.horizontal?o.height:o.width),e.size=d.size/d.count,s[n]+=e.size}o.getPadding&&wL(r,o.getPadding());let a=Math.max(0,t.outerWidth-Oa(r,s,"left","right")),L=Math.max(0,t.outerHeight-Oa(r,s,"top","bottom")),l=a!==s.w,c=L!==s.h;return s.w=a,s.h=L,e.horizontal?{same:l,other:c}:{same:c,other:l}}function L1(s){let t=s.maxPadding;function e(i){let n=Math.max(t[i]-s[i],0);return s[i]+=n,n}s.y+=e("top"),s.x+=e("left"),e("right"),e("bottom")}function l1(s,t){let e=t.maxPadding;function i(n){let o={left:0,top:0,right:0,bottom:0};return n.forEach(r=>{o[r]=Math.max(t[r],e[r])}),o}return i(s?["left","right"]:["top","bottom"])}function ni(s,t,e,i){let n=[],o,r,a,L,l,c;for(o=0,r=s.length,l=0;o{let r=!1;for(let a of o)r=r||on(a.addedNodes,i),r=r&&!on(a.removedNodes,i);r&&e()});return n.observe(document,{childList:!0,subtree:!0}),n}function g1(s,t,e){let i=s.canvas,n=new MutationObserver(o=>{let r=!1;for(let a of o)r=r||on(a.removedNodes,i),r=r&&!on(a.addedNodes,i);r&&e()});return n.observe(document,{childList:!0,subtree:!0}),n}function TL(){let s=window.devicePixelRatio;s!==Va&&(Va=s,li.forEach((t,e)=>{e.currentDevicePixelRatio!==s&&t()}))}function m1(s,t){li.size||window.addEventListener("resize",TL),li.set(s,t)}function b1(s){li.delete(s),li.size||window.removeEventListener("resize",TL)}function v1(s,t,e){let i=s.canvas,n=i&&Ui(i);if(!n)return;let o=to((a,L)=>{let l=n.clientWidth;e(a,L),l{let L=a[0],l=L.contentRect.width,c=L.contentRect.height;l===0&&c===0||o(l,c)});return r.observe(n),m1(s,o),r}function Eo(s,t,e){e&&e.disconnect(),t==="resize"&&b1(s)}function y1(s,t,e){let i=s.canvas,n=to(o=>{s.ctx!==null&&e(f1(o,s))},s);return h1(i,t,n),n}function AL(s){return!ji()||typeof OffscreenCanvas!="undefined"&&s instanceof OffscreenCanvas?nn:rn}function x1(s,t){let e=s.options.ticks,i=C1(s),n=Math.min(e.maxTicksLimit||i,i),o=e.major.enabled?S1(t):[],r=o.length,a=o[0],L=o[r-1],l=[];if(r>n)return k1(t,l,o,r/n),l;let c=_1(o,t,n);if(r>0){let d,h,u=r>1?Math.round((L-a)/(r-1)):null;for(Ki(t,l,c,st(u)?0:a-u,a),d=0,h=r-1;dn)return L}return Math.max(n,1)}function S1(s){let t=[],e,i;for(e=0,i=s.length;er+a)))return L}function D1(s,t){Lt(s,e=>{let i=e.gc,n=i.length/2,o;if(n>t){for(o=0;o{let i=e.split("."),n=i.pop(),o=[s].concat(i).join("."),r=t[e].split("."),a=r.pop(),L=r.join(".");ut.route(o,n,L,a)})}function I1(s){return"id"in s&&"defaults"in s}function V1(s){let t={},e=[],i=Object.keys(Yt.plugins.items);for(let o=0;o1&&Ha(s[0].toLowerCase());if(i)return i}throw new Error(`Cannot determine type of '${s}' axis. Please provide 'axis' or 'position' option.`)}function Za(s,t,e){if(e[t+"AxisID"]===s)return{axis:t}}function W1(s,t){if(t.data&&t.data.datasets){let e=t.data.datasets.filter(i=>i.xAxisID===s||i.yAxisID===s);if(e.length)return Za(s,"x",e[0])||Za(s,"y",e[0])}return{}}function j1(s,t){let e=Se[s.type]||{scales:{}},i=t.scales||{},n=Fo(s.type,t),o=Object.create(null);return Object.keys(i).forEach(r=>{let a=i[r];if(!it(a))return console.error(`Invalid scale configuration for scale: ${r}`);if(a._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${r}`);let L=Io(r,a,W1(r,s),ut.scales[a.type]),l=H1(L,n),c=e.scales||{};o[r]=gs(Object.create(null),[{axis:L},a,c[L],c[l]])}),s.data.datasets.forEach(r=>{let a=r.type||s.type,L=r.indexAxis||Fo(a,t),c=(Se[a]||{}).scales||{};Object.keys(c).forEach(d=>{let h=z1(d,L),u=r[h+"AxisID"]||h;o[u]=o[u]||Object.create(null),gs(o[u],[{axis:h},i[u],c[d]])})}),Object.keys(o).forEach(r=>{let a=o[r];gs(a,[ut.scales[a.type],ut.scale])}),o}function RL(s){let t=s.options||(s.options={});t.plugins=tt(t.plugins,{}),t.scales=j1(s,t)}function PL(s){return s=s||{},s.datasets=s.datasets||[],s.labels=s.labels||[],s}function U1(s){return s=s||{},s.data=PL(s.data),RL(s),s}function qi(s,t){let e=Wa.get(s);return e||(e=t(),Wa.set(s,e),OL.add(e)),e}function ja(s,t,e){let i=s.get(t);i||(i=new Map,s.set(t,i));let n=e.join(),o=i.get(n);return o||(o={resolver:Wi(t,e),subPrefixes:e.filter(a=>!a.toLowerCase().includes("hover"))},i.set(n,o)),o}function G1(s,t){let{isScriptable:e,isIndexable:i}=Lo(s);for(let n of t){let o=e(n),r=i(n),a=(r||o)&&s[n];if(o&&(le(a)||Y1(a))||r&&dt(a))return!0}return!1}function Ua(s,t){return s==="top"||s==="bottom"||q1.indexOf(s)===-1&&t==="x"}function Ya(s,t){return function(e,i){return e[s]===i[s]?e[t]-i[t]:e[s]-i[s]}}function Ga(s){let t=s.chart,e=t.options.animation;t.notifyPlugins("afterRender"),ct(e&&e.onComplete,[s],t)}function X1(s){let t=s.chart,e=t.options.animation;ct(e&&e.onProgress,[s],t)}function FL(s){return ji()&&typeof s=="string"?s=document.getElementById(s):s&&s.length&&(s=s[0]),s&&s.canvas&&(s=s.canvas),s}function Q1(s,t,e){let i=Object.keys(s);for(let n of i){let o=+n;if(o>=t){let r=s[n];delete s[n],(e>0||o>t)&&(s[o+e]=r)}}}function J1(s,t,e,i){return!e||s.type==="mouseout"?null:i?t:s}function qa(){return Lt(oe.instances,s=>s._plugins.invalidate())}function td(s,t,e){let{startAngle:i,x:n,y:o,outerRadius:r,innerRadius:a,options:L}=t,{borderWidth:l,borderJoinStyle:c}=L,d=Math.min(l/r,yt(i-e));if(s.beginPath(),s.arc(n,o,r-l/2,i+d/2,e-d/2),a>0){let h=Math.min(l/a,yt(i-e));s.arc(n,o,a+l/2,e-h/2,i+h/2,!0)}else{let h=Math.min(l/2,r*yt(i-e));if(c==="round")s.arc(n,o,h,e-rt/2,i+rt/2,!0);else if(c==="bevel"){let u=2*h*h,f=-u*Math.cos(e+rt/2)+n,g=-u*Math.sin(e+rt/2)+o,m=u*Math.cos(i+rt/2)+n,p=u*Math.sin(i+rt/2)+o;s.lineTo(f,g),s.lineTo(m,p)}}s.closePath(),s.moveTo(0,0),s.rect(0,0,s.canvas.width,s.canvas.height),s.clip("evenodd")}function ed(s,t,e){let{startAngle:i,pixelMargin:n,x:o,y:r,outerRadius:a,innerRadius:L}=t,l=n/a;s.beginPath(),s.arc(o,r,a,i-l,e+l),L>n?(l=n/L,s.arc(o,r,L,e+l,i-l,!0)):s.arc(o,r,n,e+pt,i-pt),s.closePath(),s.clip()}function sd(s){return Zi(s,["outerStart","outerEnd","innerStart","innerEnd"])}function id(s,t,e,i){let n=sd(s.options.borderRadius),o=(e-t)/2,r=Math.min(o,i*t/2),a=L=>{let l=(e-Math.min(o,L))*i/2;return mt(L,0,Math.min(o,l))};return{outerStart:a(n.outerStart),outerEnd:a(n.outerEnd),innerStart:mt(n.innerStart,0,r),innerEnd:mt(n.innerEnd,0,r)}}function Ss(s,t,e,i){return{x:e+s*Math.cos(t),y:i+s*Math.sin(t)}}function an(s,t,e,i,n,o){let{x:r,y:a,startAngle:L,pixelMargin:l,innerRadius:c}=t,d=Math.max(t.outerRadius+i+e-l,0),h=c>0?c+i+e+l:0,u=0,f=n-L;if(i){let I=c>0?c-i:0,P=d>0?d-i:0,w=(I+P)/2,U=w!==0?f*w/(w+i):f;u=(f-U)/2}let g=Math.max(.001,f*d-e/rt)/d,m=(f-g)/2,p=L+m+u,b=n-m-u,{outerStart:C,outerEnd:S,innerStart:_,innerEnd:y}=id(t,h,d,b-p),v=d-C,x=d-S,k=p+C/v,E=b-S/x,M=h+_,D=h+y,A=p+_/M,N=b-y/D;if(s.beginPath(),o){let I=(k+E)/2;if(s.arc(r,a,d,k,I),s.arc(r,a,d,I,E),S>0){let O=Ss(x,E,r,a);s.arc(O.x,O.y,S,E,b+pt)}let P=Ss(D,b,r,a);if(s.lineTo(P.x,P.y),y>0){let O=Ss(D,N,r,a);s.arc(O.x,O.y,y,b+pt,N+Math.PI)}let w=(b-y/h+(p+_/h))/2;if(s.arc(r,a,h,b-y/h,w,!0),s.arc(r,a,h,w,p+_/h,!0),_>0){let O=Ss(M,A,r,a);s.arc(O.x,O.y,_,A+Math.PI,p-pt)}let U=Ss(v,p,r,a);if(s.lineTo(U.x,U.y),C>0){let O=Ss(v,k,r,a);s.arc(O.x,O.y,C,p-pt,k)}}else{s.moveTo(r,a);let I=Math.cos(k)*d+r,P=Math.sin(k)*d+a;s.lineTo(I,P);let w=Math.cos(E)*d+r,U=Math.sin(E)*d+a;s.lineTo(w,U)}s.closePath()}function nd(s,t,e,i,n){let{fullCircles:o,startAngle:r,circumference:a}=t,L=t.endAngle;if(o){an(s,t,e,i,L,n);for(let l=0;l=rt&&u===0&&c!=="miter"&&td(s,t,g),o||(an(s,t,e,i,g,n),s.stroke())}function IL(s,t,e=t){s.lineCap=tt(e.borderCapStyle,t.borderCapStyle),s.setLineDash(tt(e.borderDash,t.borderDash)),s.lineDashOffset=tt(e.borderDashOffset,t.borderDashOffset),s.lineJoin=tt(e.borderJoinStyle,t.borderJoinStyle),s.lineWidth=tt(e.borderWidth,t.borderWidth),s.strokeStyle=tt(e.borderColor,t.borderColor)}function rd(s,t,e){s.lineTo(e.x,e.y)}function ad(s){return s.stepped?La:s.tension||s.cubicInterpolationMode==="monotone"?la:rd}function VL(s,t,e={}){let i=s.length,{start:n=0,end:o=i-1}=e,{start:r,end:a}=t,L=Math.max(n,r),l=Math.min(o,a),c=na&&o>a;return{count:i,start:L,loop:t.loop,ilen:l(r+(l?a-S:S))%o,C=()=>{g!==m&&(s.lineTo(c,m),s.lineTo(c,g),s.lineTo(c,p))};for(L&&(u=n[b(0)],s.moveTo(u.x,u.y)),h=0;h<=a;++h){if(u=n[b(h)],u.skip)continue;let S=u.x,_=u.y,y=S|0;y===f?(_m&&(m=_),c=(d*c+S)/++d):(C(),s.lineTo(S,_),f=y,d=0,g=m=_),p=_}C()}function No(s){let t=s.options,e=t.borderDash&&t.borderDash.length;return!s._decimated&&!s._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!e?ld:Ld}function cd(s){return s.stepped?ba:s.tension||s.cubicInterpolationMode==="monotone"?va:Ce}function dd(s,t,e,i){let n=t._path;n||(n=t._path=new Path2D,t.path(n,e,i)&&n.closePath()),IL(s,t.options),s.stroke(n)}function hd(s,t,e,i){let{segments:n,options:o}=t,r=No(t);for(let a of n)IL(s,o,a.style),s.beginPath(),r(s,t,a,{start:e,end:e+i-1})&&s.closePath(),s.stroke()}function fd(s,t,e,i){ud&&!t.options.segment?dd(s,t,e,i):hd(s,t,e,i)}function Xa(s,t,e,i){let n=s.options,{[e]:o}=s.getProps([e],i);return Math.abs(t-o)$L(t++)),t}function Cd(s,t){return s.backgroundColor=s.data.map(()=>zL(t++)),t}function _d(s){let t=0;return(e,i)=>{let n=s.getDatasetMeta(i).controller;n instanceof re?t=xd(e,t):n instanceof Ae?t=Cd(e,t):n&&(t=yd(e,t))}}function Ja(s){let t;for(t in s)if(s[t].borderColor||s[t].backgroundColor)return!0;return!1}function Sd(s){return s&&(s.borderColor||s.backgroundColor)}function kd(){return ut.borderColor!=="rgba(0,0,0,0.1)"||ut.backgroundColor!=="rgba(0,0,0,0.1)"}function Ed(s,t,e,i,n){let o=n.samples||i;if(o>=e)return s.slice(t,t+e);let r=[],a=(e-2)/(o-2),L=0,l=t+e-1,c=t,d,h,u,f,g;for(r[L++]=s[c],d=0;du&&(u=f,h=s[b],g=b);r[L++]=h,c=g}return r[L++]=s[l],r}function Md(s,t,e,i){let n=0,o=0,r,a,L,l,c,d,h,u,f,g,m=[],p=t+e-1,b=s[t].x,S=s[p].x-b;for(r=t;rg&&(g=l,h=r),n=(o*n+a.x)/++o;else{let y=r-1;if(!st(d)&&!st(h)){let v=Math.min(d,h),x=Math.max(d,h);v!==u&&v!==y&&m.push({...s[v],x:n}),x!==u&&x!==y&&m.push({...s[x],x:n})}r>0&&y!==u&&m.push(s[y]),m.push(a),c=_,o=0,f=g=l,d=h=u=r}}return m}function ZL(s){if(s._decimated){let t=s._data;delete s._decimated,delete s._data,Object.defineProperty(s,"data",{configurable:!0,enumerable:!0,writable:!0,value:t})}}function tL(s){s.data.datasets.forEach(t=>{ZL(t)})}function wd(s,t){let e=t.length,i=0,n,{iScale:o}=s,{min:r,max:a,minDefined:L,maxDefined:l}=o.getUserBounds();return L&&(i=mt(Jt(t,o.axis,r).lo,0,e-1)),l?n=mt(Jt(t,o.axis,a).hi+1,i,e)-i:n=e-i,{start:i,count:n}}function Dd(s,t,e){let i=s.segments,n=s.points,o=t.points,r=[];for(let a of i){let{start:L,end:l}=a;l=cn(L,l,n);let c=$o(e,n[L],n[l],a.loop);if(!t.segments){r.push({source:a,target:c,start:n[L],end:n[l]});continue}let d=bo(t,c);for(let h of d){let u=$o(e,o[h.start],o[h.end],h.loop),f=mo(a,n,u);for(let g of f)r.push({source:g,target:h,start:{[e]:eL(c,u,"start",Math.max)},end:{[e]:eL(c,u,"end",Math.min)}})}}return r}function $o(s,t,e,i){if(i)return;let n=t[s],o=e[s];return s==="angle"&&(n=yt(n),o=yt(o)),{property:s,start:n,end:o}}function Td(s,t){let{x:e=null,y:i=null}=s||{},n=t.points,o=[];return t.segments.forEach(({start:r,end:a})=>{a=cn(r,a,n);let L=n[r],l=n[a];i!==null?(o.push({x:L.x,y:i}),o.push({x:l.x,y:i})):e!==null&&(o.push({x:e,y:L.y}),o.push({x:e,y:l.y}))}),o}function cn(s,t,e){for(;t>s;t--){let i=e[t];if(!isNaN(i.x)&&!isNaN(i.y))break}return t}function eL(s,t,e,i){return s&&t?i(s[e],t[e]):s?s[e]:t?t[e]:0}function jL(s,t){let e=[],i=!1;return dt(s)?(i=!0,e=s):e=Td(s,t),e.length?new Gt({points:e,options:{tension:0},_loop:i,_fullLoop:i}):null}function sL(s){return s&&s.fill!==!1}function Ad(s,t,e){let n=s[t].fill,o=[t],r;if(!e)return n;for(;n!==!1&&o.indexOf(n)===-1;){if(!ft(n))return n;if(r=s[n],!r)return!1;if(r.visible)return n;o.push(n),n=r.fill}return!1}function Rd(s,t,e){let i=Id(s);if(it(i))return isNaN(i.value)?!1:i;let n=parseFloat(i);return ft(n)&&Math.floor(n)===n?Pd(i[0],t,n,e):["origin","start","end","stack","shape"].indexOf(i)>=0&&i}function Pd(s,t,e,i){return(s==="-"||s==="+")&&(e=t+e),e===t||e<0||e>=i?!1:e}function Od(s,t){let e=null;return s==="start"?e=t.bottom:s==="end"?e=t.top:it(s)?e=t.getPixelForValue(s.value):t.getBasePixel&&(e=t.getBasePixel()),e}function Fd(s,t,e){let i;return s==="start"?i=e:s==="end"?i=t.options.reverse?t.min:t.max:it(s)?i=s.value:i=t.getBaseValue(),i}function Id(s){let t=s.options,e=t.fill,i=tt(e&&e.target,e);return i===void 0&&(i=!!t.backgroundColor),i===!1||i===null?!1:i===!0?"origin":i}function Vd(s){let{scale:t,index:e,line:i}=s,n=[],o=i.segments,r=i.points,a=Nd(t,e);a.push(jL({x:null,y:t.bottom},i));for(let L=0;Lo.length>r.length?o:r)),t+e.size/2+i.measureText(n).width}function Xd(s,t,e){let i=s;return typeof t.text!="string"&&(i=YL(t,e)),i}function YL(s,t){let e=s.text?s.text.length:0;return t*e}function Qd(s,t){return!!((s==="mousemove"||s==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(s==="click"||s==="mouseup"))}function Jd(s,t){let e=new ci({ctx:s.ctx,options:t,chart:s});_t.configure(s,e,t),_t.addBox(s,e),s.titleBlock=e}function ie(s,t){return t&&(dt(t)?Array.prototype.push.apply(s,t):s.push(t)),s}function ue(s){return(typeof s=="string"||s instanceof String)&&s.indexOf(` `)>-1?s.split(` -`):s}function Qd(s,t){let{element:e,datasetIndex:i,index:n}=t,o=s.getDatasetMeta(i).controller,{label:r,value:a}=o.getLabelAndValue(n);return{chart:s,label:r,parsed:o.getParsed(n),raw:s.data.datasets[i].data[n],formattedValue:a,dataset:o.getDataset(),dataIndex:n,datasetIndex:i,element:e}}function oL(s,t){let e=s.chart.ctx,{body:i,footer:n,title:o}=s,{boxWidth:r,boxHeight:a}=t,L=gt(t.bodyFont),l=gt(t.titleFont),c=gt(t.footerFont),d=o.length,h=n.length,u=i.length,f=Ct(t.padding),g=f.height,m=0,p=i.reduce((S,_)=>S+_.before.length+_.lines.length+_.after.length,0);if(p+=s.beforeBody.length+s.afterBody.length,d&&(g+=d*l.lineHeight+(d-1)*t.titleSpacing+t.titleMarginBottom),p){let S=t.displayColors?Math.max(a,L.lineHeight):L.lineHeight;g+=u*S+(p-u)*L.lineHeight+(p-1)*t.bodySpacing}h&&(g+=t.footerMarginTop+h*c.lineHeight+(h-1)*t.footerSpacing);let b=0,C=function(S){m=Math.max(m,e.measureText(S).width+b)};return e.save(),e.font=l.string,Lt(s.title,C),e.font=L.string,Lt(s.beforeBody.concat(s.afterBody),C),b=t.displayColors?r+2+t.boxPadding:0,Lt(i,S=>{Lt(S.before,C),Lt(S.lines,C),Lt(S.after,C)}),b=0,e.font=c.string,Lt(s.footer,C),e.restore(),m+=f.width,{width:m,height:g}}function Jd(s,t){let{y:e,height:i}=t;return es.height-i/2?"bottom":"center"}function t5(s,t,e,i){let{x:n,width:o}=i,r=e.caretSize+e.caretPadding;if(s==="left"&&n+o+r>t.width||s==="right"&&n-o-r<0)return!0}function e5(s,t,e,i){let{x:n,width:o}=e,{width:r,chartArea:{left:a,right:L}}=s,l="center";return i==="center"?l=n<=(a+L)/2?"left":"right":n<=o/2?l="left":n>=r-o/2&&(l="right"),t5(l,s,t,e)&&(l="center"),l}function rL(s,t,e){let i=e.yAlign||t.yAlign||Jd(s,e);return{xAlign:e.xAlign||t.xAlign||e5(s,t,e,i),yAlign:i}}function s5(s,t){let{x:e,width:i}=s;return t==="right"?e-=i:t==="center"&&(e-=i/2),e}function i5(s,t,e){let{y:i,height:n}=s;return t==="top"?i+=e:t==="bottom"?i-=n+e:i-=n/2,i}function aL(s,t,e,i){let{caretSize:n,caretPadding:o,cornerRadius:r}=s,{xAlign:a,yAlign:L}=e,l=n+o,{topLeft:c,topRight:d,bottomLeft:h,bottomRight:u}=Me(r),f=s5(t,a),g=i5(t,L,l);return L==="center"?a==="left"?f+=l:a==="right"&&(f-=l):a==="left"?f-=Math.max(c,h)+n:a==="right"&&(f+=Math.max(d,u)+n),{x:mt(f,0,i.width-t.width),y:mt(g,0,i.height-t.height)}}function Qi(s,t,e){let i=Ct(e.padding);return t==="center"?s.x+s.width/2:t==="right"?s.x+s.width-i.right:s.x+i.left}function LL(s){return se([],ue(s))}function n5(s,t,e){return he(s,{tooltip:t,tooltipItems:e,type:"tooltip"})}function lL(s,t){let e=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return e?s.override(e):s}function Ot(s,t,e,i){let n=s[t].call(e,i);return typeof n=="undefined"?KL[t].call(e,i):n}function r5(s,t,e,i){let n=s.indexOf(t);if(n===-1)return o5(s,t,e,i);let o=s.lastIndexOf(t);return n!==o?e:n}function cL(s){let t=this.getLabels();return s>=0&&sf&&(_=Un(k*_/f/u)*u),st(L)||(y=Math.pow(10,L),_=Math.ceil(_*y)/y),n==="ticks"?(v=Math.floor(g/_)*_,x=Math.ceil(m/_)*_):(v=g,x=m),p&&b&&o&&qr((a-r)/o,_/1e3)?(k=Math.round(Math.min((a-r)/_,c)),_=(a-r)/k,v=r,x=a):C?(v=p?r:v,x=b?a:x,k=l-1,_=(x-v)/k):(k=(x-v)/_,bs(k,Math.round(k),_/1e3)?k=Math.round(k):k=Math.ceil(k));let E=Math.max(Gn(_),Gn(v));y=Math.pow(10,st(L)?E:L),v=Math.round(v*y)/y,x=Math.round(x*y)/y;let M=0;for(p&&(h&&v!==r?(e.push({value:r}),va)break;e.push({value:D})}return b&&h&&x!==a?e.length&&bs(e[e.length-1].value,a,dL(a,S,s))?e[e.length-1].value=a:e.push({value:a}):(!b||x===a)&&e.push({value:x}),e}function dL(s,t,{horizontal:e,minRotation:i}){let n=Zt(i),o=(e?Math.sin(n):Math.cos(n))||.001,r=.75*t*(""+s).length;return Math.min(t/o,r)}function hL(s){return s/Math.pow(10,di(s))===1}function uL(s,t,e){let i=Math.pow(10,e),n=Math.floor(s/i);return Math.ceil(t/i)-n}function l5(s,t){let e=t-s,i=di(e);for(;uL(s,t,i)>10;)i++;for(;uL(s,t,i)<10;)i--;return Math.min(i,di(s))}function c5(s,{min:t,max:e}){t=Pt(s.min,t);let i=[],n=di(t),o=l5(t,e),r=o<0?Math.pow(10,Math.abs(o)):1,a=Math.pow(10,o),L=n>o?Math.pow(10,n):0,l=Math.round((t-L)*r)/r,c=Math.floor((t-L)/a/10)*a*10,d=Math.floor((l-c)/Math.pow(10,o)),h=Pt(s.min,Math.round((L+c+d*Math.pow(10,o))*r)/r);for(;h=10?d=d<15?15:20:d++,d>=20&&(o++,d=2,r=o>=0?1:r),h=Math.round((L+c+d*Math.pow(10,o))*r)/r;let u=Pt(s.max,h);return i.push({value:u,major:hL(u),significand:d}),i}function $o(s){let t=s.ticks;if(t.display&&s.display){let e=Ct(t.backdropPadding);return tt(t.font&&t.font.size,ut.font.size)+e.height}return 0}function d5(s,t,e){return e=dt(e)?e:[e],{w:oa(s,t.string,e),h:e.length*t.lineHeight}}function fL(s,t,e,i,n){return s===i||s===n?{start:t-e/2,end:t+e/2}:sn?{start:t-e,end:t}:{start:t,end:t+e}}function h5(s){let t={l:s.left+s._padding.left,r:s.right-s._padding.right,t:s.top+s._padding.top,b:s.bottom-s._padding.bottom},e=Object.assign({},t),i=[],n=[],o=s._pointLabels.length,r=s.options.pointLabels,a=r.centerPointLabels?rt/o:0;for(let L=0;Lt.r&&(a=(i.end-t.r)/o,s.r=Math.max(s.r,t.r+a)),n.startt.b&&(L=(n.end-t.b)/r,s.b=Math.max(s.b,t.b+L))}function f5(s,t,e){let i=s.drawingArea,{extra:n,additionalAngle:o,padding:r,size:a}=e,L=s.getPointPosition(t,i+n+r,o),l=Math.round(Ni(yt(L.angle+pt))),c=v5(L.y,a.h,l),d=m5(l),h=b5(L.x,a.w,d);return{visible:!0,x:L.x,y:c,textAlign:d,left:h,top:c,right:h+a.w,bottom:c+a.h}}function p5(s,t){if(!t)return!0;let{left:e,top:i,right:n,bottom:o}=s;return!(Jt({x:e,y:i},t)||Jt({x:e,y:o},t)||Jt({x:n,y:i},t)||Jt({x:n,y:o},t))}function g5(s,t,e){let i=[],n=s._pointLabels.length,o=s.options,{centerPointLabels:r,display:a}=o.pointLabels,L={extra:$o(o)/2,additionalAngle:r?rt/n:0},l;for(let c=0;c270||e<90)&&(s-=t),s}function y5(s,t,e){let{left:i,top:n,right:o,bottom:r}=e,{backdropColor:a}=t;if(!st(a)){let L=Me(t.borderRadius),l=Ct(t.backdropPadding);s.fillStyle=a;let c=i-l.left,d=n-l.top,h=o-i+l.width,u=r-n+l.height;Object.values(L).some(f=>f!==0)?(s.beginPath(),Cs(s,{x:c,y:d,w:h,h:u,radius:L}),s.fill()):s.fillRect(c,d,h,u)}}function x5(s,t){let{ctx:e,options:{pointLabels:i}}=s;for(let n=t-1;n>=0;n--){let o=s._pointLabelItems[n];if(!o.visible)continue;let r=i.setContext(s.getPointLabelContext(n));y5(e,r,o);let a=gt(r.font),{x:L,y:l,textAlign:c}=o;Ee(e,s._pointLabels[n],L,l+a.lineHeight/2,a,{color:r.color,textAlign:c,textBaseline:"middle"})}}function QL(s,t,e,i){let{ctx:n}=s;if(e)n.arc(s.xCenter,s.yCenter,t,0,ht);else{let o=s.getPointPosition(0,t);n.moveTo(o.x,o.y);for(let r=1;r=It.indexOf(e);o--){let r=It[o];if(dn[r].common&&s._adapter.diff(n,i,r)>=t-1)return r}return It[e?It.indexOf(e):0]}function k5(s){for(let t=It.indexOf(s)+1,e=It.length;t=t?e[i]:e[n];s[o]=!0}}function E5(s,t,e,i){let n=s._adapter,o=+n.startOf(t[0].value,i),r=t[t.length-1].value,a,L;for(a=o;a<=r;a=+n.add(a,1,i))L=e[a],L>=0&&(t[L].major=!0);return t}function vL(s,t,e){let i=[],n={},o=t.length,r,a;for(r=0;r=s[i].pos&&t<=s[n].pos&&({lo:i,hi:n}=Qt(s,"pos",t)),{pos:o,time:a}=s[i],{pos:r,time:L}=s[n]):(t>=s[i].time&&t<=s[n].time&&({lo:i,hi:n}=Qt(s,"time",t)),{time:o,pos:a}=s[i],{time:r,pos:L}=s[n]);let l=r-o;return l?a+(L-a)*(t-o)/l:a}var To,ie,xa,w2,sn,ai,xo,Ea,B2,Ft,Ye,Ge,oe,Ke,Ae,ks,qe,Xe,CL,Ao,_L,SL,kL,_t,Li,nn,tn,L1,Oa,ML,li,Fa,rn,Vt,k1,Ia,Va,Oe,Es,Ro,Ut,Po,Ha,RL,ii,Io,j1,Y1,G1,en,Ya,ne,De,dd,Yt,Qe,Je,VL,No,qa,$L,HL,Ln,WL,nL,Ud,ln,UL,ci,YL,Xi,GL,oi,KL,ri,qL,XL,o5,a5,Ms,As,ws,di,Ue,Ds,Te,dn,It,Pe,Ts,JL,M5,el=En(()=>{ya();To=class{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,n){let o=e.listeners[n],r=e.duration;o.forEach(a=>a({chart:t,initial:e.initial,numSteps:r,currentStep:Math.min(i-e.start,r)}))}_refresh(){this._request||(this._running=!0,this._request=Qn.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(t=Date.now()){let e=0;this._charts.forEach((i,n)=>{if(!i.running||!i.items.length)return;let o=i.items,r=o.length-1,a=!1,L;for(;r>=0;--r)L=o[r],L._active?(L._total>i.duration&&(i.duration=L._total),L.tick(t),a=!0):(o[r]=o[o.length-1],o.pop());a&&(n.draw(),this._notify(n,i,t,"progress")),o.length||(i.running=!1,this._notify(n,i,t,"complete"),i.initial=!1),e+=o.length}),this._lastDate=t,e===0&&(this._running=!1)}_getAnims(t){let e=this._charts,i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){!e||!e.length||this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){let e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce((i,n)=>Math.max(i,n._duration),0),this._refresh())}running(t){if(!this._running)return!1;let e=this._charts.get(t);return!(!e||!e.running||!e.items.length)}stop(t){let e=this._charts.get(t);if(!e||!e.items.length)return;let i=e.items,n=i.length-1;for(;n>=0;--n)i[n].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}},ie=new To,xa="transparent",w2={boolean(s,t,e){return e>.5?t:s},color(s,t,e){let i=io(s||xa),n=i.valid&&io(t||xa);return n&&n.valid?n.mix(i,e).hexString():t},number(s,t,e){return s+(t-s)*e}},sn=class{constructor(t,e,i,n){let o=e[i];n=_s([t.to,n,o,t.from]);let r=_s([t.from,o,n]);this._active=!0,this._fn=t.fn||w2[t.type||typeof r],this._easing=us[t.easing]||us.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=r,this._to=n,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);let n=this._target[this._prop],o=i-this._start,r=this._duration-o;this._start=i,this._duration=Math.floor(Math.max(r,t.duration)),this._total+=o,this._loop=!!t.loop,this._to=_s([t.to,e,n,t.from]),this._from=_s([t.from,n,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){let e=t-this._start,i=this._duration,n=this._prop,o=this._from,r=this._loop,a=this._to,L;if(this._active=o!==a&&(r||e1?2-L:L,L=this._easing(Math.min(1,Math.max(0,L))),this._target[n]=this._fn(o,a,L)}wait(){let t=this._promises||(this._promises=[]);return new Promise((e,i)=>{t.push({res:e,rej:i})})}_notify(t){let e=t?"res":"rej",i=this._promises||[];for(let n=0;n{let o=t[n];if(!it(o))return;let r={};for(let a of e)r[a]=o[a];(dt(o.properties)&&o.properties||[n]).forEach(a=>{(a===n||!i.has(a))&&i.set(a,r)})})}_animateOptions(t,e){let i=e.options,n=T2(t,i);if(!n)return[];let o=this._createAnimations(n,i);return i.$shared&&D2(t.options.$animations,i).then(()=>{t.options=i},()=>{}),o}_createAnimations(t,e){let i=this._properties,n=[],o=t.$animations||(t.$animations={}),r=Object.keys(e),a=Date.now(),L;for(L=r.length-1;L>=0;--L){let l=r[L];if(l.charAt(0)==="$")continue;if(l==="options"){n.push(...this._animateOptions(t,e));continue}let c=e[l],d=o[l],h=i.get(l);if(d)if(h&&d.active()){d.update(h,c,a);continue}else d.cancel();if(!h||!h.duration){t[l]=c;continue}o[l]=d=new sn(h,t,l,c),n.push(d)}return n}update(t,e){if(this._properties.size===0){Object.assign(t,e);return}let i=this._createAnimations(t,e);if(i.length)return ie.add(this._chart,i),!0}};xo=s=>s==="reset"||s==="none",Ea=(s,t)=>t?s:Object.assign({},s),B2=(s,t,e)=>s&&!t.hidden&&t._stacked&&{keys:yL(e,!0),values:null},Ft=class{constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){let t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=vo(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Js(this._cachedMeta),this.index=t}linkScales(){let t=this.chart,e=this._cachedMeta,i=this.getDataset(),n=(d,h,u,f)=>d==="x"?h:d==="r"?f:u,o=e.xAxisID=tt(i.xAxisID,yo(t,"x")),r=e.yAxisID=tt(i.yAxisID,yo(t,"y")),a=e.rAxisID=tt(i.rAxisID,yo(t,"r")),L=e.indexAxis,l=e.iAxisID=n(L,o,r,a),c=e.vAxisID=n(L,r,o,a);e.xScale=this.getScaleForId(o),e.yScale=this.getScaleForId(r),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(l),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){let e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){let t=this._cachedMeta;this._data&&qn(this._data,this),t._stacked&&Js(t)}_dataCheck(){let t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(it(e)){let n=this._cachedMeta;this._data=P2(e,n)}else if(i!==e){if(i){qn(i,this);let n=this._cachedMeta;Js(n),n._parsed=[]}e&&Object.isExtensible(e)&&ea(e,this),this._syncList=[],this._data=e}}addElements(){let t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){let e=this._cachedMeta,i=this.getDataset(),n=!1;this._dataCheck();let o=e._stacked;e._stacked=vo(e.vScale,e),e.stack!==i.stack&&(n=!0,Js(e),e.stack=i.stack),this._resyncElements(t),(n||o!==e._stacked)&&(ka(this,e._parsed),e._stacked=vo(e.vScale,e))}configure(){let t=this.chart.config,e=t.datasetScopeKeys(this._type),i=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(i,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){let{_cachedMeta:i,_data:n}=this,{iScale:o,_stacked:r}=i,a=o.axis,L=t===0&&e===n.length?!0:i._sorted,l=t>0&&i._parsed[t-1],c,d,h;if(this._parsing===!1)i._parsed=n,i._sorted=!0,h=n;else{dt(n[t])?h=this.parseArrayData(i,n,t,e):it(n[t])?h=this.parseObjectData(i,n,t,e):h=this.parsePrimitiveData(i,n,t,e);let u=()=>d[a]===null||l&&d[a]g||d=0;--h)if(!f()){this.updateRangeFromParsed(l,t,u,L);break}}return l}getAllParsedValues(t){let e=this._cachedMeta._parsed,i=[],n,o,r;for(n=0,o=e.length;n=0&&tthis.getContext(i,n,e),g=l.resolveNamedOptions(h,u,f,d);return g.$shared&&(g.$shared=L,o[r]=Object.freeze(Ea(g,L))),g}_resolveAnimations(t,e,i){let n=this.chart,o=this._cachedDataOpts,r=`animation-${e}`,a=o[r];if(a)return a;let L;if(n.options.animation!==!1){let c=this.chart.config,d=c.datasetAnimationScopeKeys(this._type,e),h=c.getOptionScopes(this.getDataset(),d);L=c.createResolver(h,this.getContext(t,i,e))}let l=new ai(n,L&&L.animations);return L&&L._cacheable&&(o[r]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||xo(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){let i=this.resolveDataElementOptions(t,e),n=this._sharedOptions,o=this.getSharedOptions(i),r=this.includeOptions(e,o)||o!==n;return this.updateSharedOptions(o,e,i),{sharedOptions:o,includeOptions:r}}updateElement(t,e,i,n){xo(n)?Object.assign(t,i):this._resolveAnimations(e,n).update(t,i)}updateSharedOptions(t,e,i){t&&!xo(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,n){t.active=n;let o=this.getStyle(e,n);this._resolveAnimations(e,i,n).update(t,{options:!n&&this.getSharedOptions(o)||o})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){let t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){let t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){let e=this._data,i=this._cachedMeta.data;for(let[a,L,l]of this._syncList)this[a](L,l);this._syncList=[];let n=i.length,o=e.length,r=Math.min(o,n);r&&this.parse(0,r),o>n?this._insertElements(n,o-n,t):o{for(l.length+=e,a=l.length-1;a>=r;a--)l[a]=l[a-e]};for(L(o),a=t;ac.controller.options.grouped),o=i.options.stacked,r=[],a=this._cachedMeta.controller.getParsed(e),L=a&&a[i.axis],l=c=>{let d=c._parsed.find(u=>u[i.axis]===L),h=d&&d[c.vScale.axis];if(st(h)||isNaN(h))return!0};for(let c of n)if(!(e!==void 0&&l(c))&&((o===!1||r.indexOf(c.stack)===-1||o===void 0&&c.stack===void 0)&&r.push(c.stack),c.index===t))break;return r.length||r.push(void 0),r}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){let t=this.chart.scales,e=this.chart.options.indexAxis;return Object.keys(t).filter(i=>t[i].axis===e).shift()}_getAxis(){let t={},e=this.getFirstScaleIdForIndexAxis();for(let i of this.chart.data.datasets)t[tt(this.chart.options.indexAxis==="x"?i.xAxisID:i.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,i){let n=this._getStacks(t,i),o=e!==void 0?n.indexOf(e):-1;return o===-1?n.length-1:o}_getRuler(){let t=this.options,e=this._cachedMeta,i=e.iScale,n=[],o,r;for(o=0,r=e.data.length;o=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){let e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:n,yScale:o}=e,r=this.getParsed(t),a=n.getLabelForValue(r.x),L=o.getLabelForValue(r.y),l=r._custom;return{label:i[t]||"",value:"("+a+", "+L+(l?", "+l:"")+")"}}update(t){let e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,n){let o=n==="reset",{iScale:r,vScale:a}=this._cachedMeta,{sharedOptions:L,includeOptions:l}=this._getSharedOptions(e,n),c=r.axis,d=a.axis;for(let h=e;h+i[L];if(it(i[t])){let{key:L="value"}=this._parsing;o=l=>+de(i[l],L)}let r,a;for(r=t,a=t+e;r0&&!isNaN(t)?ht*(Math.abs(t)/e):0}getLabelAndValue(t){let e=this._cachedMeta,i=this.chart,n=i.data.labels||[],o=ys(e._parsed[t],i.options.locale);return{label:n[t]||"",value:o}}getMaxBorderWidth(t){let e=0,i=this.chart,n,o,r,a,L;if(!t){for(n=0,o=i.data.datasets.length;nt!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),Y(oe,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data,{labels:{pointStyle:i,textAlign:n,color:o,useBorderRadius:r,borderRadius:a}}=t.legend.options;return e.labels.length&&e.datasets.length?e.labels.map((L,l)=>{let d=t.getDatasetMeta(0).controller.getStyle(l);return{text:L,fillStyle:d.backgroundColor,fontColor:o,hidden:!t.getDataVisibility(l),lineDash:d.borderDash,lineDashOffset:d.borderDashOffset,lineJoin:d.borderJoinStyle,lineWidth:d.borderWidth,strokeStyle:d.borderColor,textAlign:n,pointStyle:i,borderRadius:r&&(a||d.borderRadius),index:l}}):[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}});Ke=class extends Ft{initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){let e=this._cachedMeta,{dataset:i,data:n=[],_dataset:o}=e,r=this.chart._animationsDisabled,{start:a,count:L}=to(e,n,r);this._drawStart=a,this._drawCount=L,eo(e)&&(a=0,L=n.length),i._chart=this.chart,i._datasetIndex=this.index,i._decimated=!!o._decimated,i.points=n;let l=this.resolveDatasetElementOptions(t);this.options.showLine||(l.borderWidth=0),l.segment=this.options.segment,this.updateElement(i,void 0,{animated:!r,options:l},t),this.updateElements(n,a,L,t)}updateElements(t,e,i,n){let o=n==="reset",{iScale:r,vScale:a,_stacked:L,_dataset:l}=this._cachedMeta,{sharedOptions:c,includeOptions:d}=this._getSharedOptions(e,n),h=r.axis,u=a.axis,{spanGaps:f,segment:g}=this.options,m=Ze(f)?f:Number.POSITIVE_INFINITY,p=this.chart._animationsDisabled||o||n==="none",b=e+i,C=t.length,S=e>0&&this.getParsed(e-1);for(let _=0;_=b){v.skip=!0;continue}let x=this.getParsed(_),k=st(x[u]),E=v[h]=r.getPixelForValue(x[h],_),M=v[u]=o||k?a.getBasePixel():a.getPixelForValue(L?this.applyStack(a,x,L):x[u],_);v.skip=isNaN(E)||isNaN(M)||k,v.stop=_>0&&Math.abs(x[h]-S[h])>m,g&&(v.parsed=x,v.raw=l.data[_]),d&&(v.options=c||this.resolveDataElementOptions(_,y.active?"active":n)),p||this.updateElement(y,_,v,n),S=x}}getMaxOverflow(){let t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,n=t.data||[];if(!n.length)return i;let o=n[0].size(this.resolveDataElementOptions(0)),r=n[n.length-1].size(this.resolveDataElementOptions(n.length-1));return Math.max(i,o,r)/2}draw(){let t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}};Y(Ke,"id","line"),Y(Ke,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),Y(Ke,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});Ae=class extends Ft{constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){let e=this._cachedMeta,i=this.chart,n=i.data.labels||[],o=ys(e._parsed[t].r,i.options.locale);return{label:n[t]||"",value:o}}parseObjectData(t,e,i,n){return co.bind(this)(t,e,i,n)}update(t){let e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){let t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach((i,n)=>{let o=this.getParsed(n).r;!isNaN(o)&&this.chart.getDataVisibility(n)&&(oe.max&&(e.max=o))}),e}_updateRadius(){let t=this.chart,e=t.chartArea,i=t.options,n=Math.min(e.right-e.left,e.bottom-e.top),o=Math.max(n/2,0),r=Math.max(i.cutoutPercentage?o/100*i.cutoutPercentage:1,0),a=(o-r)/t.getVisibleDatasetCount();this.outerRadius=o-a*this.index,this.innerRadius=this.outerRadius-a}updateElements(t,e,i,n){let o=n==="reset",r=this.chart,L=r.options.animation,l=this._cachedMeta.rScale,c=l.xCenter,d=l.yCenter,h=l.getIndexAngle(0)-.5*rt,u=h,f,g=360/this.countVisibleElements();for(f=0;f{!isNaN(this.getParsed(n).r)&&this.chart.getDataVisibility(n)&&e++}),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?Zt(this.resolveDataElementOptions(t,e).angle||i):0}};Y(Ae,"id","polarArea"),Y(Ae,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),Y(Ae,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data;if(e.labels.length&&e.datasets.length){let{labels:{pointStyle:i,color:n}}=t.legend.options;return e.labels.map((o,r)=>{let L=t.getDatasetMeta(0).controller.getStyle(r);return{text:o,fillStyle:L.backgroundColor,strokeStyle:L.borderColor,fontColor:n,lineWidth:L.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(r),index:r}})}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}});ks=class extends oe{};Y(ks,"id","pie"),Y(ks,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});qe=class extends Ft{getLabelAndValue(t){let e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,n){return co.bind(this)(t,e,i,n)}update(t){let e=this._cachedMeta,i=e.dataset,n=e.data||[],o=e.iScale.getLabels();if(i.points=n,t!=="resize"){let r=this.resolveDatasetElementOptions(t);this.options.showLine||(r.borderWidth=0);let a={_loop:!0,_fullLoop:o.length===n.length,options:r};this.updateElement(i,void 0,a,t)}this.updateElements(n,0,n.length,t)}updateElements(t,e,i,n){let o=this._cachedMeta.rScale,r=n==="reset";for(let a=e;a0&&this.getParsed(e-1);for(let S=e;S0&&Math.abs(y[u]-C[u])>p,m&&(v.parsed=y,v.raw=l.data[S]),h&&(v.options=d||this.resolveDataElementOptions(S,_.active?"active":n)),b||this.updateElement(_,S,v,n),C=y}this.updateSharedOptions(d,n,c)}getMaxOverflow(){let t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let a=0;for(let L=e.length-1;L>=0;--L)a=Math.max(a,e[L].size(this.resolveDataElementOptions(L))/2);return a>0&&a}let i=t.dataset,n=i.options&&i.options.borderWidth||0;if(!e.length)return n;let o=e[0].size(this.resolveDataElementOptions(0)),r=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(n,o,r)/2}};Y(Xe,"id","scatter"),Y(Xe,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),Y(Xe,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});CL=Object.freeze({__proto__:null,BarController:Ye,BubbleController:Ge,DoughnutController:oe,LineController:Ke,PieController:ks,PolarAreaController:Ae,RadarController:qe,ScatterController:Xe});Ao=class s{constructor(t){Y(this,"options");this.options=t||{}}static override(t){Object.assign(s.prototype,t)}init(){}formats(){return je()}parse(){return je()}format(){return je()}add(){return je()}diff(){return je()}startOf(){return je()}endOf(){return je()}},_L={_date:Ao};SL={evaluateInteractionItems:hi,modes:{index(s,t,e,i){let n=we(t,s),o=e.axis||"x",r=e.includeInvisible||!1,a=e.intersect?_o(s,n,o,i,r):So(s,n,o,!1,i,r),L=[];return a.length?(s.getSortedVisibleDatasetMetas().forEach(l=>{let c=a[0].index,d=l.data[c];d&&!d.skip&&L.push({element:d,datasetIndex:l.index,index:c})}),L):[]},dataset(s,t,e,i){let n=we(t,s),o=e.axis||"xy",r=e.includeInvisible||!1,a=e.intersect?_o(s,n,o,i,r):So(s,n,o,!1,i,r);if(a.length>0){let L=a[0].datasetIndex,l=s.getDatasetMeta(L).data;a=[];for(let c=0;c{typeof g.beforeLayout=="function"&&g.beforeLayout()});let c=L.reduce((g,m)=>m.box.options&&m.box.options.display===!1?g:g+1,0)||1,d=Object.freeze({outerWidth:t,outerHeight:e,padding:n,availableWidth:o,availableHeight:r,vBoxMaxWidth:o/2/c,hBoxMaxHeight:r/2}),h=Object.assign({},n);EL(h,Ct(i));let u=Object.assign({maxPadding:h,w:o,h:r,x:n.left,y:n.top},n),f=i1(L.concat(l),d);ni(a.fullSize,u,d,f),ni(L,u,d,f),ni(l,u,d,f)&&ni(L,u,d,f),r1(u),Pa(a.leftAndTop,u,d,f),u.x+=u.w,u.y+=u.h,Pa(a.rightAndBottom,u,d,f),s.chartArea={left:u.left,top:u.top,right:u.left+u.w,bottom:u.top+u.h,height:u.h,width:u.w},Lt(a.chartArea,g=>{let m=g.box;Object.assign(m,s.chartArea),m.update(u.w,u.h,{left:0,top:0,right:0,bottom:0})})}},Li=class{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,n){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,n?Math.floor(e/n):i)}}isAttached(t){return!0}updateConfig(t){}},nn=class extends Li{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}},tn="$chartjs",L1={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},Oa=s=>s===null||s==="";ML=pa?{passive:!0}:!1;li=new Map,Fa=0;rn=class extends Li{acquireContext(t,e){let i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(l1(t,e),i):null}releaseContext(t){let e=t.canvas;if(!e[tn])return!1;let i=e[tn].initial;["height","width"].forEach(o=>{let r=i[o];st(r)?e.removeAttribute(o):e.setAttribute(o,r)});let n=i.style||{};return Object.keys(n).forEach(o=>{e.style[o]=n[o]}),e.width=e.width,delete e[tn],!0}addEventListener(t,e,i){this.removeEventListener(t,e);let n=t.$proxies||(t.$proxies={}),r={attach:u1,detach:f1,resize:m1}[e]||b1;n[e]=r(t,e,i)}removeEventListener(t,e){let i=t.$proxies||(t.$proxies={}),n=i[e];if(!n)return;({attach:ko,detach:ko,resize:ko}[e]||d1)(t,e,n),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,n){return fa(t,e,i,n)}isAttached(t){let e=t&&Ui(t);return!!(e&&e.isConnected)}};Vt=class{constructor(){Y(this,"x");Y(this,"y");Y(this,"active",!1);Y(this,"options");Y(this,"$animations")}tooltipPosition(t){let{x:e,y:i}=this.getProps(["x","y"],t);return{x:e,y:i}}hasValue(){return Ze(this.x)&&Ze(this.y)}getProps(t,e){let i=this.$animations;if(!e||!i)return this;let n={};return t.forEach(o=>{n[o]=i[o]&&i[o].active()?i[o]._to:this[o]}),n}};Y(Vt,"defaults",{}),Y(Vt,"defaultRoutes");k1=s=>s==="left"?"right":s==="right"?"left":s,Ia=(s,t,e)=>t==="top"||t==="left"?s[t]+e:s[t]-e,Va=(s,t)=>Math.min(t||s,s);Oe=class s extends Vt{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:n}=this;return t=Pt(t,Number.POSITIVE_INFINITY),e=Pt(e,Number.NEGATIVE_INFINITY),i=Pt(i,Number.POSITIVE_INFINITY),n=Pt(n,Number.NEGATIVE_INFINITY),{min:Pt(t,i),max:Pt(e,n),minDefined:ft(t),maxDefined:ft(e)}}getMinMax(t){let{min:e,max:i,minDefined:n,maxDefined:o}=this.getUserBounds(),r;if(n&&o)return{min:e,max:i};let a=this.getMatchingVisibleMetas();for(let L=0,l=a.length;Li?i:e,i=n&&e>i?e:i,{min:Pt(e,Pt(i,e)),max:Pt(i,Pt(e,i))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){let t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){ct(this.options.beforeUpdate,[this])}update(t,e,i){let{beginAtZero:n,grace:o,ticks:r}=this.options,a=r.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=La(this,o,n),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();let L=a=o||i<=1||!this.isHorizontal()){this.labelRotation=n;return}let c=this._getLabelSizes(),d=c.widest.width,h=c.highest.height,u=mt(this.chart.width-d,0,this.maxWidth);a=t.offset?this.maxWidth/i:u/(i-1),d+6>a&&(a=u/(i-(t.offset?.5:1)),L=this.maxHeight-si(t.grid)-e.padding-Ba(t.title,this.chart.options.font),l=Math.sqrt(d*d+h*h),r=Ni(Math.min(Math.asin(mt((c.highest.height+6)/a,-1,1)),Math.asin(mt(L/l,-1,1))-Math.asin(mt(h/l,-1,1)))),r=Math.max(n,Math.min(o,r))),this.labelRotation=r}afterCalculateLabelRotation(){ct(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){ct(this.options.beforeFit,[this])}fit(){let t={width:0,height:0},{chart:e,options:{ticks:i,title:n,grid:o}}=this,r=this._isVisible(),a=this.isHorizontal();if(r){let L=Ba(n,e.options.font);if(a?(t.width=this.maxWidth,t.height=si(o)+L):(t.height=this.maxHeight,t.width=si(o)+L),i.display&&this.ticks.length){let{first:l,last:c,widest:d,highest:h}=this._getLabelSizes(),u=i.padding*2,f=Zt(this.labelRotation),g=Math.cos(f),m=Math.sin(f);if(a){let p=i.mirror?0:m*d.width+g*h.height;t.height=Math.min(this.maxHeight,t.height+p+u)}else{let p=i.mirror?0:g*d.width+m*h.height;t.width=Math.min(this.maxWidth,t.width+p+u)}this._calculatePadding(l,c,m,g)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,n){let{ticks:{align:o,padding:r},position:a}=this.options,L=this.labelRotation!==0,l=a!=="top"&&this.axis==="x";if(this.isHorizontal()){let c=this.getPixelForTick(0)-this.left,d=this.right-this.getPixelForTick(this.ticks.length-1),h=0,u=0;L?l?(h=n*t.width,u=i*e.height):(h=i*t.height,u=n*e.width):o==="start"?u=e.width:o==="end"?h=t.width:o!=="inner"&&(h=t.width/2,u=e.width/2),this.paddingLeft=Math.max((h-c+r)*this.width/(this.width-c),0),this.paddingRight=Math.max((u-d+r)*this.width/(this.width-d),0)}else{let c=e.height/2,d=t.height/2;o==="start"?(c=0,d=t.height):o==="end"&&(c=e.height,d=0),this.paddingTop=c+r,this.paddingBottom=d+r}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){ct(this.options.afterFit,[this])}isHorizontal(){let{axis:t,position:e}=this.options;return e==="top"||e==="bottom"||t==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){this.beforeTickToLabelConversion(),this.generateTickLabels(t);let e,i;for(e=0,i=t.length;e({width:r[k]||0,height:a[k]||0});return{first:x(0),last:x(e-1),widest:x(y),highest:x(v),widths:r,heights:a}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){let e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);let e=this._startPixel+t*this._length;return Xr(this._alignToPixels?ke(this.chart,e,0):e)}getDecimalForPixel(t){let e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){let{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){let e=this.ticks||[];if(t>=0&&ta*n?a/i:L/n:L*n0}_computeGridLineItems(t){let e=this.axis,i=this.chart,n=this.options,{grid:o,position:r,border:a}=n,L=o.offset,l=this.isHorizontal(),d=this.ticks.length+(L?1:0),h=si(o),u=[],f=a.setContext(this.getContext()),g=f.display?f.width:0,m=g/2,p=function(P){return ke(i,P,g)},b,C,S,_,y,v,x,k,E,M,D,A;if(r==="top")b=p(this.bottom),v=this.bottom-h,k=b-m,M=p(t.top)+m,A=t.bottom;else if(r==="bottom")b=p(this.top),M=t.top,A=p(t.bottom)-m,v=b+m,k=this.top+h;else if(r==="left")b=p(this.right),y=this.right-h,x=b-m,E=p(t.left)+m,D=t.right;else if(r==="right")b=p(this.left),E=t.left,D=p(t.right)-m,y=b+m,x=this.left+h;else if(e==="x"){if(r==="center")b=p((t.top+t.bottom)/2+.5);else if(it(r)){let P=Object.keys(r)[0],w=r[P];b=p(this.chart.scales[P].getPixelForValue(w))}M=t.top,A=t.bottom,v=b+m,k=v+h}else if(e==="y"){if(r==="center")b=p((t.left+t.right)/2);else if(it(r)){let P=Object.keys(r)[0],w=r[P];b=p(this.chart.scales[P].getPixelForValue(w))}y=b-m,x=y-h,E=t.left,D=t.right}let N=tt(n.ticks.maxTicksLimit,d),I=Math.max(1,Math.ceil(d/N));for(C=0;C0&&(T-=W/2);break}B={left:T,top:K,width:W+G.width,height:R+G.height,color:I.backdropColor}}m.push({label:S,font:k,textOffset:D,options:{rotation:g,color:w,strokeColor:U,strokeWidth:O,textAlign:Z,textBaseline:A,translation:[_,y],backdrop:B}})}return m}_getXAxisLabelAlignment(){let{position:t,ticks:e}=this.options;if(-Zt(this.labelRotation))return t==="top"?"left":"right";let n="center";return e.align==="start"?n="left":e.align==="end"?n="right":e.align==="inner"&&(n="inner"),n}_getYAxisLabelAlignment(t){let{position:e,ticks:{crossAlign:i,mirror:n,padding:o}}=this.options,r=this._getLabelSizes(),a=t+o,L=r.widest.width,l,c;return e==="left"?n?(c=this.right+o,i==="near"?l="left":i==="center"?(l="center",c+=L/2):(l="right",c+=L)):(c=this.right-a,i==="near"?l="right":i==="center"?(l="center",c-=L/2):(l="left",c=this.left)):e==="right"?n?(c=this.left+o,i==="near"?l="right":i==="center"?(l="center",c-=L/2):(l="left",c-=L)):(c=this.left+a,i==="near"?l="left":i==="center"?(l="center",c+=L/2):(l="right",c=this.right)):l="right",{textAlign:l,x:c}}_computeLabelArea(){if(this.options.ticks.mirror)return;let t=this.chart,e=this.options.position;if(e==="left"||e==="right")return{top:0,left:this.left,bottom:t.height,right:this.right};if(e==="top"||e==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:t.width}}drawBackground(){let{ctx:t,options:{backgroundColor:e},left:i,top:n,width:o,height:r}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,n,o,r),t.restore())}getLineWidthForValue(t){let e=this.options.grid;if(!this._isVisible()||!e.display)return 0;let n=this.ticks.findIndex(o=>o.value===t);return n>=0?e.setContext(this.getContext(n)).lineWidth:0}drawGrid(t){let e=this.options.grid,i=this.ctx,n=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t)),o,r,a=(L,l,c)=>{!c.width||!c.color||(i.save(),i.lineWidth=c.width,i.strokeStyle=c.color,i.setLineDash(c.borderDash||[]),i.lineDashOffset=c.borderDashOffset,i.beginPath(),i.moveTo(L.x,L.y),i.lineTo(l.x,l.y),i.stroke(),i.restore())};if(e.display)for(o=0,r=n.length;o{this.draw(o)}}]:[{z:i,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:n,draw:()=>{this.drawBorder()}},{z:e,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(t){let e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",n=[],o,r;for(o=0,r=e.length;o{let o=i||this._getRegistryForType(n);i||o.isForType(n)||o===this.plugins&&n.id?this._exec(t,o,n):Lt(n,r=>{let a=i||this._getRegistryForType(r);this._exec(t,a,r)})})}_exec(t,e,i){let n=Vi(t);ct(i["before"+n],[],i),e[t](i),ct(i["after"+n],[],i)}_getRegistryForType(t){for(let e=0;eo.filter(a=>!r.some(L=>a.plugin.id===L.plugin.id));this._notify(n(e,i),t,"stop"),this._notify(n(i,e),t,"start")}};Ha=new Map,RL=new Set;ii=(s,t,e)=>{let i=de(t,e);i!==void 0&&s.add(i)},Io=class{constructor(t){this._config=W1(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=AL(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){let t=this._config;this.clearCache(),TL(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return qi(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,e){return qi(`${t}.transition.${e}`,()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,e){return qi(`${t}-${e}`,()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]])}pluginScopeKeys(t){let e=t.id,i=this.type;return qi(`${i}-plugin-${e}`,()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]])}_cachedScopes(t,e){let i=this._scopeCache,n=i.get(t);return(!n||e)&&(n=new Map,i.set(t,n)),n}getOptionScopes(t,e,i){let{options:n,type:o}=this,r=this._cachedScopes(t,i),a=r.get(e);if(a)return a;let L=new Set;e.forEach(c=>{t&&(L.add(t),c.forEach(d=>ii(L,t,d))),c.forEach(d=>ii(L,n,d)),c.forEach(d=>ii(L,Se[o]||{},d)),c.forEach(d=>ii(L,ut,d)),c.forEach(d=>ii(L,zi,d))});let l=Array.from(L);return l.length===0&&l.push(Object.create(null)),RL.has(e)&&r.set(e,l),l}chartOptionScopes(){let{options:t,type:e}=this;return[t,Se[e]||{},ut.datasets[e]||{},{type:e},ut,zi]}resolveNamedOptions(t,e,i,n=[""]){let o={$shared:!0},{resolver:r,subPrefixes:a}=Za(this._resolverCache,t,n),L=r;if(U1(r,e)){o.$shared=!1,i=le(i)?i():i;let l=this.createResolver(t,i,a);L=He(r,i,l)}for(let l of e)o[l]=L[l];return o}createResolver(t,e,i=[""],n){let{resolver:o}=Za(this._resolverCache,t,i);return it(e)?He(o,e,void 0,n):o}};j1=s=>it(s)&&Object.getOwnPropertyNames(s).some(t=>le(s[t]));Y1="4.5.1",G1=["top","bottom","left","right","chartArea"];en={},Ya=s=>{let t=PL(s);return Object.values(en).filter(e=>e.canvas===t).pop()};ne=class{static register(...t){Ut.add(...t),Ga()}static unregister(...t){Ut.remove(...t),Ga()}constructor(t,e){let i=this.config=new Io(e),n=PL(t),o=Ya(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");let r=i.createResolver(i.chartOptionScopes(),this.getContext());this.platform=new(i.platform||DL(n)),this.platform.updateConfig(i);let a=this.platform.acquireContext(n,r.aspectRatio),L=a&&a.canvas,l=L&&L.height,c=L&&L.width;if(this.id=jr(),this.ctx=a,this.canvas=L,this.width=c,this.height=l,this._options=r,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new Po,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=sa(d=>this.update(d),r.resizeDelay||0),this._dataChanges=[],en[this.id]=this,!a||!L){console.error("Failed to create chart: can't acquire context from the given item");return}ie.listen(this,"complete",Ua),ie.listen(this,"progress",K1),this._initialize(),this.attached&&this.update()}get aspectRatio(){let{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return st(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return Ut}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ho(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return no(this.canvas,this.ctx),this}stop(){return ie.stop(this),this}resize(t,e){ie.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){let i=this.options,n=this.canvas,o=i.maintainAspectRatio&&this.aspectRatio,r=this.platform.getMaximumSize(n,t,e,o),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),L=this.width?"resize":"attach";this.width=r.width,this.height=r.height,this._aspectRatio=this.aspectRatio,ho(this,a,!0)&&(this.notifyPlugins("resize",{size:r}),ct(i.onResize,[this,r],this),this.attached&&this._doResize(L)&&this.render())}ensureScalesHaveIDs(){let e=this.options.scales||{};Lt(e,(i,n)=>{i.id=n})}buildOrUpdateScales(){let t=this.options,e=t.scales,i=this.scales,n=Object.keys(i).reduce((r,a)=>(r[a]=!1,r),{}),o=[];e&&(o=o.concat(Object.keys(e).map(r=>{let a=e[r],L=Fo(r,a),l=L==="r",c=L==="x";return{options:a,dposition:l?"chartArea":c?"bottom":"left",dtype:l?"radialLinear":c?"category":"linear"}}))),Lt(o,r=>{let a=r.options,L=a.id,l=Fo(L,a),c=tt(a.type,r.dtype);(a.position===void 0||Wa(a.position,l)!==Wa(r.dposition))&&(a.position=r.dposition),n[L]=!0;let d=null;if(L in i&&i[L].type===c)d=i[L];else{let h=Ut.getScale(c);d=new h({id:L,type:c,ctx:this.ctx,chart:this}),i[d.id]=d}d.init(a,t)}),Lt(n,(r,a)=>{r||delete i[a]}),Lt(i,r=>{_t.configure(this,r,r.options),_t.addBox(this,r)})}_updateMetasets(){let t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort((n,o)=>n.index-o.index),i>e){for(let n=e;ne.length&&delete this._stacks,t.forEach((i,n)=>{e.filter(o=>o===i._dataset).length===0&&this._destroyDatasetMeta(n)})}buildOrUpdateControllers(){let t=[],e=this.data.datasets,i,n;for(this._removeUnreferencedMetasets(),i=0,n=e.length;i{this.getDatasetMeta(e).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){let e=this.config;e.update();let i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),n=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0})===!1)return;let o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let r=0;for(let l=0,c=this.data.datasets.length;l{l.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(ja("z","_idx"));let{_active:a,_lastEvent:L}=this;L?this._eventHandler(L,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){Lt(this.scales,t=>{_t.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){let t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);(!jn(e,i)||!!this._responsiveListeners!==t.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){let{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(let{method:i,start:n,count:o}of e){let r=i==="_removeElements"?-o:o;q1(t,n,r)}}_getUniformDataChanges(){let t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];let e=this.data.datasets.length,i=o=>new Set(t.filter(r=>r[0]===o).map((r,a)=>a+","+r.splice(1).join(","))),n=i(0);for(let o=1;oo.split(",")).map(o=>({method:o[1],start:+o[2],count:+o[3]}))}_updateLayout(t){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;_t.update(this,this.width,this.height,t);let e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],Lt(this.boxes,n=>{i&&n.position==="chartArea"||(n.configure&&n.configure(),this._layers.push(...n._layers()))},this),this._layers.forEach((n,o)=>{n._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})!==!1){for(let e=0,i=this.data.datasets.length;e=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){let e=this.ctx,i={meta:t,index:t.index,cancelable:!0},n=bo(this,t);this.notifyPlugins("beforeDatasetDraw",i)!==!1&&(n&&Xs(e,n),t.controller.draw(),n&&Qs(e),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return Jt(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,n){let o=SL.modes[e];return typeof o=="function"?o(this,t,i,n):[]}getDatasetMeta(t){let e=this.data.datasets[t],i=this._metasets,n=i.filter(o=>o&&o._dataset===e).pop();return n||(n={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(n)),n}getContext(){return this.$context||(this.$context=he(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){let e=this.data.datasets[t];if(!e)return!1;let i=this.getDatasetMeta(t);return typeof i.hidden=="boolean"?!i.hidden:!e.hidden}setDatasetVisibility(t,e){let i=this.getDatasetMeta(t);i.hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){let n=i?"show":"hide",o=this.getDatasetMeta(t),r=o.controller._resolveAnimations(void 0,n);ms(e)?(o.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),r.update(o,{visible:i}),this.update(a=>a.datasetIndex===t?n:void 0))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){let e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),ie.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,o,r),t[o]=r},n=(o,r,a)=>{o.offsetX=r,o.offsetY=a,this._eventHandler(o)};Lt(this.options.events,o=>i(o,n))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});let t=this._responsiveListeners,e=this.platform,i=(L,l)=>{e.addEventListener(this,L,l),t[L]=l},n=(L,l)=>{t[L]&&(e.removeEventListener(this,L,l),delete t[L])},o=(L,l)=>{this.canvas&&this.resize(L,l)},r,a=()=>{n("attach",a),this.attached=!0,this.resize(),i("resize",o),i("detach",r)};r=()=>{this.attached=!1,n("resize",o),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():r()}unbindEvents(){Lt(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},Lt(this._responsiveListeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){let n=i?"set":"remove",o,r,a,L;for(e==="dataset"&&(o=this.getDatasetMeta(t[0].datasetIndex),o.controller["_"+n+"DatasetHoverStyle"]()),a=0,L=t.length;a{let a=this.getDatasetMeta(o);if(!a)throw new Error("No dataset found at index "+o);return{datasetIndex:o,element:a.data[r],index:r}});!qs(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return this._plugins._cache.filter(e=>e.plugin.id===t).length===1}_updateHoverStyles(t,e,i){let n=this.options.hover,o=(L,l)=>L.filter(c=>!l.some(d=>c.datasetIndex===d.datasetIndex&&c.index===d.index)),r=o(e,t),a=i?t:o(t,e);r.length&&this.updateHoverStyle(r,n.mode,!1),a.length&&n.mode&&this.updateHoverStyle(a,n.mode,!0)}_eventHandler(t,e){let i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},n=r=>(r.options.events||this.options.events).includes(t.native.type);if(this.notifyPlugins("beforeEvent",i,n)===!1)return;let o=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,n),(o||i.changed)&&this.render(),this}_handleEvent(t,e,i){let{_active:n=[],options:o}=this,r=e,a=this._getActiveElements(t,n,i,r),L=Gr(t),l=X1(t,this._lastEvent,i,L);i&&(this._lastEvent=null,ct(o.onHover,[t,a,this],this),L&&ct(o.onClick,[t,a,this],this));let c=!qs(a,n);return(c||e)&&(this._active=a,this._updateHoverStyles(a,n,e)),this._lastEvent=l,c}_getActiveElements(t,e,i,n){if(t.type==="mouseout")return[];if(!i)return e;let o=this.options.hover;return this.getElementsAtEventForMode(t,o.mode,o,n)}};Y(ne,"defaults",ut),Y(ne,"instances",en),Y(ne,"overrides",Se),Y(ne,"registry",Ut),Y(ne,"version",Y1),Y(ne,"getChart",Ya);De=class extends Vt{constructor(e){super();Y(this,"circumference");Y(this,"endAngle");Y(this,"fullCircles");Y(this,"innerRadius");Y(this,"outerRadius");Y(this,"pixelMargin");Y(this,"startAngle");this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,e&&Object.assign(this,e)}inRange(e,i,n){let o=this.getProps(["x","y"],n),{angle:r,distance:a}=Kn(o,{x:e,y:i}),{startAngle:L,endAngle:l,innerRadius:c,outerRadius:d,circumference:h}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],n),u=(this.options.spacing+this.options.borderWidth)/2,f=tt(h,l-L),g=vs(r,L,l)&&L!==l,m=f>=ht||g,p=ee(a,c+u,d+u);return m&&p}getCenterPoint(e){let{x:i,y:n,startAngle:o,endAngle:r,innerRadius:a,outerRadius:L}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],e),{offset:l,spacing:c}=this.options,d=(o+r)/2,h=(a+L+c+l)/2;return{x:i+Math.cos(d)*h,y:n+Math.sin(d)*h}}tooltipPosition(e){return this.getCenterPoint(e)}draw(e){let{options:i,circumference:n}=this,o=(i.offset||0)/4,r=(i.spacing||0)/2,a=i.circular;if(this.pixelMargin=i.borderAlign==="inner"?.33:0,this.fullCircles=n>ht?Math.floor(n/ht):0,n===0||this.innerRadius<0||this.outerRadius<0)return;e.save();let L=(this.startAngle+this.endAngle)/2;e.translate(Math.cos(L)*o,Math.sin(L)*o);let l=1-Math.sin(Math.min(rt,n||0)),c=o*l;e.fillStyle=i.backgroundColor,e.strokeStyle=i.borderColor,sd(e,this,c,r,a),id(e,this,c,r,a),e.restore()}};Y(De,"id","arc"),Y(De,"defaults",{borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0,selfJoin:!1}),Y(De,"defaultRoutes",{backgroundColor:"backgroundColor"}),Y(De,"descriptors",{_scriptable:!0,_indexable:e=>e!=="borderDash"});dd=typeof Path2D=="function";Yt=class extends Vt{constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){let i=this.options;if((i.tension||i.cubicInterpolationMode==="monotone")&&!i.stepped&&!this._pointsUpdated){let n=i.spanGaps?this._loop:this._fullLoop;ua(this._points,i,t,n,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=va(this,this.options.segment))}first(){let t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){let t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){let i=this.options,n=t[e],o=this.points,r=mo(this,{property:e,start:n,end:n});if(!r.length)return;let a=[],L=Ld(i),l,c;for(l=0,c=r.length;lt!=="borderDash"&&t!=="fill"});Qe=class extends Vt{constructor(e){super();Y(this,"parsed");Y(this,"skip");Y(this,"stop");this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,e&&Object.assign(this,e)}inRange(e,i,n){let o=this.options,{x:r,y:a}=this.getProps(["x","y"],n);return Math.pow(e-r,2)+Math.pow(i-a,2)s.replace("rgb(","rgba(").replace(")",", 0.5)"));$L={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(s,t,e){if(!e.enabled)return;let{data:{datasets:i},options:n}=s.config,{elements:o}=n,r=Xa(i)||Cd(n)||o&&Xa(o)||_d();if(!e.forceOverride&&r)return;let a=xd(s);i.forEach(a)}};HL={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(s,t,e)=>{if(!e.enabled){Qa(s);return}let i=s.width;s.data.datasets.forEach((n,o)=>{let{_data:r,indexAxis:a}=n,L=s.getDatasetMeta(o),l=r||n.data;if(_s([a,s.options.indexAxis])==="y"||!L.controller.supportsDecimation)return;let c=s.scales[L.xAxisID];if(c.type!=="linear"&&c.type!=="time"||s.options.parsing)return;let{start:d,count:h}=Ed(L,l),u=e.threshold||4*i;if(h<=u){zL(n);return}st(r)&&(n._data=l,delete n.data,Object.defineProperty(n,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(g){this._data=g}}));let f;switch(e.algorithm){case"lttb":f=Sd(l,d,h,i,e);break;case"min-max":f=kd(l,d,h,i);break;default:throw new Error(`Unsupported decimation algorithm '${e.algorithm}'`)}n._decimated=f})},destroy(s){Qa(s)}};Ln=class{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,i){let{x:n,y:o,radius:r}=this;return e=e||{start:0,end:ht},t.arc(n,o,r,e.end,e.start,!0),!i.bounds}interpolate(t){let{x:e,y:i,radius:n}=this,o=t.angle;return{x:e+Math.cos(o)*n,y:i+Math.sin(o)*n,angle:o}}};WL={id:"filler",afterDatasetsUpdate(s,t,e){let i=(s.data.datasets||[]).length,n=[],o,r,a,L;for(r=0;r=0;--r){let a=n[r].$filler;a&&(a.line.updateControlPoints(o,a.axis),i&&a.fill&&wo(s.ctx,a,o))}},beforeDatasetsDraw(s,t,e){if(e.drawTime!=="beforeDatasetsDraw")return;let i=s.getSortedVisibleDatasetMetas();for(let n=i.length-1;n>=0;--n){let o=i[n].$filler;tL(o)&&wo(s.ctx,o,s.chartArea)}},beforeDatasetDraw(s,t,e){let i=t.meta.$filler;!tL(i)||e.drawTime!=="beforeDatasetDraw"||wo(s.ctx,i,s.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}},nL=(s,t)=>{let{boxHeight:e=t,boxWidth:i=t}=s;return s.usePointStyle&&(e=Math.min(e,t),i=s.pointStyleWidth||Math.min(i,t)),{boxWidth:i,boxHeight:e,itemHeight:Math.max(t,e)}},Ud=(s,t)=>s!==null&&t!==null&&s.datasetIndex===t.datasetIndex&&s.index===t.index,ln=class extends Vt{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){let t=this.options.labels||{},e=ct(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter(i=>t.filter(i,this.chart.data))),t.sort&&(e=e.sort((i,n)=>t.sort(i,n,this.chart.data))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){let{options:t,ctx:e}=this;if(!t.display){this.width=this.height=0;return}let i=t.labels,n=gt(i.font),o=n.size,r=this._computeTitleHeight(),{boxWidth:a,itemHeight:L}=nL(i,o),l,c;e.font=n.string,this.isHorizontal()?(l=this.maxWidth,c=this._fitRows(r,o,a,L)+10):(c=this.maxHeight,l=this._fitCols(r,n,a,L)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(c,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,n){let{ctx:o,maxWidth:r,options:{labels:{padding:a}}}=this,L=this.legendHitBoxes=[],l=this.lineWidths=[0],c=n+a,d=t;o.textAlign="left",o.textBaseline="middle";let h=-1,u=-c;return this.legendItems.forEach((f,g)=>{let m=i+e/2+o.measureText(f.text).width;(g===0||l[l.length-1]+m+2*a>r)&&(d+=c,l[l.length-(g>0?0:1)]=0,u+=c,h++),L[g]={left:0,top:u,row:h,width:m,height:n},l[l.length-1]+=m+a}),d}_fitCols(t,e,i,n){let{ctx:o,maxHeight:r,options:{labels:{padding:a}}}=this,L=this.legendHitBoxes=[],l=this.columnSizes=[],c=r-t,d=a,h=0,u=0,f=0,g=0;return this.legendItems.forEach((m,p)=>{let{itemWidth:b,itemHeight:C}=Yd(i,e,o,m,n);p>0&&u+C+2*a>c&&(d+=h+a,l.push({width:h,height:u}),f+=h+a,g++,h=u=0),L[p]={left:f,top:u,col:g,width:b,height:C},h=Math.max(h,b),u+=C+a}),d+=h,l.push({width:h,height:u}),d}adjustHitBoxes(){if(!this.options.display)return;let t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:n},rtl:o}}=this,r=We(o,this.left,this.width);if(this.isHorizontal()){let a=0,L=xt(i,this.left+n,this.right-this.lineWidths[a]);for(let l of e)a!==l.row&&(a=l.row,L=xt(i,this.left+n,this.right-this.lineWidths[a])),l.top+=this.top+t+n,l.left=r.leftForLtr(r.x(L),l.width),L+=l.width+n}else{let a=0,L=xt(i,this.top+t+n,this.bottom-this.columnSizes[a].height);for(let l of e)l.col!==a&&(a=l.col,L=xt(i,this.top+t+n,this.bottom-this.columnSizes[a].height)),l.top=L,l.left+=this.left+n,l.left=r.leftForLtr(r.x(l.left),l.width),L+=l.height+n}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){let t=this.ctx;Xs(t,this),this._draw(),Qs(t)}}_draw(){let{options:t,columnSizes:e,lineWidths:i,ctx:n}=this,{align:o,labels:r}=t,a=ut.color,L=We(t.rtl,this.left,this.width),l=gt(r.font),{padding:c}=r,d=l.size,h=d/2,u;this.drawTitle(),n.textAlign=L.textAlign("left"),n.textBaseline="middle",n.lineWidth=.5,n.font=l.string;let{boxWidth:f,boxHeight:g,itemHeight:m}=nL(r,d),p=function(y,v,x){if(isNaN(f)||f<=0||isNaN(g)||g<0)return;n.save();let k=tt(x.lineWidth,1);if(n.fillStyle=tt(x.fillStyle,a),n.lineCap=tt(x.lineCap,"butt"),n.lineDashOffset=tt(x.lineDashOffset,0),n.lineJoin=tt(x.lineJoin,"miter"),n.lineWidth=k,n.strokeStyle=tt(x.strokeStyle,a),n.setLineDash(tt(x.lineDash,[])),r.usePointStyle){let E={radius:g*Math.SQRT2/2,pointStyle:x.pointStyle,rotation:x.rotation,borderWidth:k},M=L.xPlus(y,f/2),D=v+h;oo(n,E,M,D,r.pointStyleWidth&&f)}else{let E=v+Math.max((d-g)/2,0),M=L.leftForLtr(y,f),D=Me(x.borderRadius);n.beginPath(),Object.values(D).some(A=>A!==0)?Cs(n,{x:M,y:E,w:f,h:g,radius:D}):n.rect(M,E,f,g),n.fill(),k!==0&&n.stroke()}n.restore()},b=function(y,v,x){Ee(n,x.text,y,v+m/2,l,{strikethrough:x.hidden,textAlign:L.textAlign(x.textAlign)})},C=this.isHorizontal(),S=this._computeTitleHeight();C?u={x:xt(o,this.left+c,this.right-i[0]),y:this.top+c+S,line:0}:u={x:this.left+c,y:xt(o,this.top+S+c,this.bottom-e[0].height),line:0},fo(this.ctx,t.textDirection);let _=m+c;this.legendItems.forEach((y,v)=>{n.strokeStyle=y.fontColor,n.fillStyle=y.fontColor;let x=n.measureText(y.text).width,k=L.textAlign(y.textAlign||(y.textAlign=r.textAlign)),E=f+h+x,M=u.x,D=u.y;L.setWidth(this.width),C?v>0&&M+E+c>this.right&&(D=u.y+=_,u.line++,M=u.x=xt(o,this.left+c,this.right-i[u.line])):v>0&&D+_>this.bottom&&(M=u.x=M+e[u.line].width+c,u.line++,D=u.y=xt(o,this.top+S+c,this.bottom-e[u.line].height));let A=L.x(M);if(p(A,D,y),M=ia(k,M+f+h,C?M+E:this.right,t.rtl),b(L.x(M),D,y),C)u.x+=E+c;else if(typeof y.text!="string"){let N=l.lineHeight;u.y+=jL(y,N)+c}else u.y+=_}),po(this.ctx,t.textDirection)}drawTitle(){let t=this.options,e=t.title,i=gt(e.font),n=Ct(e.padding);if(!e.display)return;let o=We(t.rtl,this.left,this.width),r=this.ctx,a=e.position,L=i.size/2,l=n.top+L,c,d=this.left,h=this.width;if(this.isHorizontal())h=Math.max(...this.lineWidths),c=this.top+l,d=xt(t.align,d,this.right-h);else{let f=this.columnSizes.reduce((g,m)=>Math.max(g,m.height),0);c=l+xt(t.align,this.top,this.bottom-f-t.labels.padding-this._computeTitleHeight())}let u=xt(a,d,d+h);r.textAlign=o.textAlign($i(a)),r.textBaseline="middle",r.strokeStyle=e.color,r.fillStyle=e.color,r.font=i.string,Ee(r,e.text,u,c,i)}_computeTitleHeight(){let t=this.options.title,e=gt(t.font),i=Ct(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,n,o;if(ee(t,this.left,this.right)&&ee(e,this.top,this.bottom)){for(o=this.legendHitBoxes,i=0;is.chart.options.color,boxWidth:40,padding:10,generateLabels(s){let t=s.data.datasets,{labels:{usePointStyle:e,pointStyle:i,textAlign:n,color:o,useBorderRadius:r,borderRadius:a}}=s.legend.options;return s._getSortedDatasetMetas().map(L=>{let l=L.controller.getStyle(e?0:void 0),c=Ct(l.borderWidth);return{text:t[L.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!L.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(c.width+c.height)/4,strokeStyle:l.borderColor,pointStyle:i||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:r&&(a||l.borderRadius),datasetIndex:L.index}},this)}},title:{color:s=>s.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:s=>!s.startsWith("on"),labels:{_scriptable:s=>!["generateLabels","filter","sort"].includes(s)}}},ci=class extends Vt{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){let i=this.options;if(this.left=0,this.top=0,!i.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=t,this.height=this.bottom=e;let n=dt(i.text)?i.text.length:1;this._padding=Ct(i.padding);let o=n*gt(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){let t=this.options.position;return t==="top"||t==="bottom"}_drawArgs(t){let{top:e,left:i,bottom:n,right:o,options:r}=this,a=r.align,L=0,l,c,d;return this.isHorizontal()?(c=xt(a,i,o),d=e+t,l=o-i):(r.position==="left"?(c=i+t,d=xt(a,n,e),L=rt*-.5):(c=o-t,d=xt(a,e,n),L=rt*.5),l=n-e),{titleX:c,titleY:d,maxWidth:l,rotation:L}}draw(){let t=this.ctx,e=this.options;if(!e.display)return;let i=gt(e.font),o=i.lineHeight/2+this._padding.top,{titleX:r,titleY:a,maxWidth:L,rotation:l}=this._drawArgs(o);Ee(t,e.text,0,0,i,{color:e.color,maxWidth:L,rotation:l,textAlign:$i(e.align),textBaseline:"middle",translation:[r,a]})}};YL={id:"title",_element:ci,start(s,t,e){Xd(s,e)},stop(s){let t=s.titleBlock;_t.removeBox(s,t),delete s.titleBlock},beforeUpdate(s,t,e){let i=s.titleBlock;_t.configure(s,i,e),i.options=e},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}},Xi=new WeakMap,GL={id:"subtitle",start(s,t,e){let i=new ci({ctx:s.ctx,options:e,chart:s});_t.configure(s,i,e),_t.addBox(s,i),Xi.set(s,i)},stop(s){_t.removeBox(s,Xi.get(s)),Xi.delete(s)},beforeUpdate(s,t,e){let i=Xi.get(s);_t.configure(s,i,e),i.options=e},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}},oi={average(s){if(!s.length)return!1;let t,e,i=new Set,n=0,o=0;for(t=0,e=s.length;ta+L)/i.size,y:n/o}},nearest(s,t){if(!s.length)return!1;let e=t.x,i=t.y,n=Number.POSITIVE_INFINITY,o,r,a;for(o=0,r=s.length;o0){let t=s[0],e=t.chart.data.labels,i=e?e.length:0;if(this&&this.options&&this.options.mode==="dataset")return t.dataset.label||"";if(t.label)return t.label;if(i>0&&t.dataIndex{let r={before:[],lines:[],after:[]},a=lL(i,o);se(r.before,ue(Ot(a,"beforeLabel",this,o))),se(r.lines,Ot(a,"label",this,o)),se(r.after,ue(Ot(a,"afterLabel",this,o))),n.push(r)}),n}getAfterBody(t,e){return LL(Ot(e.callbacks,"afterBody",this,t))}getFooter(t,e){let{callbacks:i}=e,n=Ot(i,"beforeFooter",this,t),o=Ot(i,"footer",this,t),r=Ot(i,"afterFooter",this,t),a=[];return a=se(a,ue(n)),a=se(a,ue(o)),a=se(a,ue(r)),a}_createItems(t){let e=this._active,i=this.chart.data,n=[],o=[],r=[],a=[],L,l;for(L=0,l=e.length;Lt.filter(c,d,h,i))),t.itemSort&&(a=a.sort((c,d)=>t.itemSort(c,d,i))),Lt(a,c=>{let d=lL(t.callbacks,c);n.push(Ot(d,"labelColor",this,c)),o.push(Ot(d,"labelPointStyle",this,c)),r.push(Ot(d,"labelTextColor",this,c))}),this.labelColors=n,this.labelPointStyles=o,this.labelTextColors=r,this.dataPoints=a,a}update(t,e){let i=this.options.setContext(this.getContext()),n=this._active,o,r=[];if(!n.length)this.opacity!==0&&(o={opacity:0});else{let a=oi[i.position].call(this,n,this._eventPosition);r=this._createItems(i),this.title=this.getTitle(r,i),this.beforeBody=this.getBeforeBody(r,i),this.body=this.getBody(r,i),this.afterBody=this.getAfterBody(r,i),this.footer=this.getFooter(r,i);let L=this._size=oL(this,i),l=Object.assign({},a,L),c=rL(this.chart,i,l),d=aL(i,l,c,this.chart);this.xAlign=c.xAlign,this.yAlign=c.yAlign,o={opacity:1,x:d.x,y:d.y,width:L.width,height:L.height,caretX:a.x,caretY:a.y}}this._tooltipItems=r,this.$context=void 0,o&&this._resolveAnimations().update(this,o),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,n){let o=this.getCaretPosition(t,i,n);e.lineTo(o.x1,o.y1),e.lineTo(o.x2,o.y2),e.lineTo(o.x3,o.y3)}getCaretPosition(t,e,i){let{xAlign:n,yAlign:o}=this,{caretSize:r,cornerRadius:a}=i,{topLeft:L,topRight:l,bottomLeft:c,bottomRight:d}=Me(a),{x:h,y:u}=t,{width:f,height:g}=e,m,p,b,C,S,_;return o==="center"?(S=u+g/2,n==="left"?(m=h,p=m-r,C=S+r,_=S-r):(m=h+f,p=m+r,C=S-r,_=S+r),b=m):(n==="left"?p=h+Math.max(L,c)+r:n==="right"?p=h+f-Math.max(l,d)-r:p=this.caretX,o==="top"?(C=u,S=C-r,m=p-r,b=p+r):(C=u+g,S=C+r,m=p+r,b=p-r),_=C),{x1:m,x2:p,x3:b,y1:C,y2:S,y3:_}}drawTitle(t,e,i){let n=this.title,o=n.length,r,a,L;if(o){let l=We(i.rtl,this.x,this.width);for(t.x=Qi(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",r=gt(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=r.string,L=0;Lb!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,Cs(t,{x:g,y:f,w:l,h:L,radius:p}),t.fill(),t.stroke(),t.fillStyle=r.backgroundColor,t.beginPath(),Cs(t,{x:m,y:f+1,w:l-2,h:L-2,radius:p}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(g,f,l,L),t.strokeRect(g,f,l,L),t.fillStyle=r.backgroundColor,t.fillRect(m,f+1,l-2,L-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){let{body:n}=this,{bodySpacing:o,bodyAlign:r,displayColors:a,boxHeight:L,boxWidth:l,boxPadding:c}=i,d=gt(i.bodyFont),h=d.lineHeight,u=0,f=We(i.rtl,this.x,this.width),g=function(x){e.fillText(x,f.x(t.x+u),t.y+h/2),t.y+=h+o},m=f.textAlign(r),p,b,C,S,_,y,v;for(e.textAlign=r,e.textBaseline="middle",e.font=d.string,t.x=Qi(this,m,i),e.fillStyle=i.bodyColor,Lt(this.beforeBody,g),u=a&&m!=="right"?r==="center"?l/2+c:l+2+c:0,S=0,y=n.length;S0&&e.stroke()}_updateAnimationTarget(t){let e=this.chart,i=this.$animations,n=i&&i.x,o=i&&i.y;if(n||o){let r=oi[t.position].call(this,this._active,this._eventPosition);if(!r)return;let a=this._size=oL(this,t),L=Object.assign({},r,this._size),l=rL(e,t,L),c=aL(t,L,l,e);(n._to!==c.x||o._to!==c.y)&&(this.xAlign=l.xAlign,this.yAlign=l.yAlign,this.width=a.width,this.height=a.height,this.caretX=r.x,this.caretY=r.y,this._resolveAnimations().update(this,c))}}_willRender(){return!!this.opacity}draw(t){let e=this.options.setContext(this.getContext()),i=this.opacity;if(!i)return;this._updateAnimationTarget(e);let n={width:this.width,height:this.height},o={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;let r=Ct(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(o,t,n,e),fo(t,e.textDirection),o.y+=r.top,this.drawTitle(o,t,e),this.drawBody(o,t,e),this.drawFooter(o,t,e),po(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){let i=this._active,n=t.map(({datasetIndex:a,index:L})=>{let l=this.chart.getDatasetMeta(a);if(!l)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:l.data[L],index:L}}),o=!qs(i,n),r=this._positionChanged(n,e);(o||r)&&(this._active=n,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;let n=this.options,o=this._active||[],r=this._getActiveElements(t,o,e,i),a=this._positionChanged(r,t),L=e||!qs(r,o)||a;return L&&(this._active=r,(n.enabled||n.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),L}_getActiveElements(t,e,i,n){let o=this.options;if(t.type==="mouseout")return[];if(!n)return e.filter(a=>this.chart.data.datasets[a.datasetIndex]&&this.chart.getDatasetMeta(a.datasetIndex).controller.getParsed(a.index)!==void 0);let r=this.chart.getElementsAtEventForMode(t,o.mode,o,i);return o.reverse&&r.reverse(),r}_positionChanged(t,e){let{caretX:i,caretY:n,options:o}=this,r=oi[o.position].call(this,t,e);return r!==!1&&(i!==r.x||n!==r.y)}};Y(ri,"positioners",oi);qL={id:"tooltip",_element:ri,positioners:oi,afterInit(s,t,e){e&&(s.tooltip=new ri({chart:s,options:e}))},beforeUpdate(s,t,e){s.tooltip&&s.tooltip.initialize(e)},reset(s,t,e){s.tooltip&&s.tooltip.initialize(e)},afterDraw(s){let t=s.tooltip;if(t&&t._willRender()){let e={tooltip:t};if(s.notifyPlugins("beforeTooltipDraw",{...e,cancelable:!0})===!1)return;t.draw(s.ctx),s.notifyPlugins("afterTooltipDraw",e)}},afterEvent(s,t){if(s.tooltip){let e=t.replay;s.tooltip.handleEvent(t.event,e,t.inChartArea)&&(t.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(s,t)=>t.bodyFont.size,boxWidth:(s,t)=>t.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:KL},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:s=>s!=="filter"&&s!=="itemSort"&&s!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]},XL=Object.freeze({__proto__:null,Colors:$L,Decimation:HL,Filler:WL,Legend:UL,SubTitle:GL,Title:YL,Tooltip:qL}),o5=(s,t,e,i)=>(typeof t=="string"?(e=s.push(t)-1,i.unshift({index:e,label:t})):isNaN(t)&&(e=null),e);a5=(s,t)=>s===null?null:mt(Math.round(s),0,t);Ms=class extends Oe{constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){let e=this._addedLabels;if(e.length){let i=this.getLabels();for(let{index:n,label:o}of e)i[n]===o&&i.splice(n,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(st(t))return null;let i=this.getLabels();return e=isFinite(e)&&i[e]===t?e:r5(i,t,tt(e,t),this._addedLabels),a5(e,i.length-1)}determineDataLimits(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),{min:i,max:n}=this.getMinMax(!0);this.options.bounds==="ticks"&&(t||(i=0),e||(n=this.getLabels().length-1)),this.min=i,this.max=n}buildTicks(){let t=this.min,e=this.max,i=this.options.offset,n=[],o=this.getLabels();o=t===0&&e===o.length-1?o:o.slice(t,e+1),this._valueRange=Math.max(o.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let r=t;r<=e;r++)n.push({value:r});return n}getLabelForValue(t){return cL.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return typeof t!="number"&&(t=this.parse(t)),t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){let e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}};Y(Ms,"id","category"),Y(Ms,"defaults",{ticks:{callback:cL}});As=class extends Oe{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return st(t)||(typeof t=="number"||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){let{beginAtZero:t}=this.options,{minDefined:e,maxDefined:i}=this.getUserBounds(),{min:n,max:o}=this,r=L=>n=e?n:L,a=L=>o=i?o:L;if(t){let L=jt(n),l=jt(o);L<0&&l<0?a(0):L>0&&l>0&&r(0)}if(n===o){let L=o===0?1:Math.abs(o*.05);a(o+L),t||r(n-L)}this.min=n,this.max=o}getTickLimit(){let t=this.options.ticks,{maxTicksLimit:e,stepSize:i}=t,n;return i?(n=Math.ceil(this.max/i)-Math.floor(this.min/i)+1,n>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${i} would result generating up to ${n} ticks. Limiting to 1000.`),n=1e3)):(n=this.computeTickLimit(),e=e||11),e&&(n=Math.min(e,n)),n}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){let t=this.options,e=t.ticks,i=this.getTickLimit();i=Math.max(2,i);let n={maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:e.includeBounds!==!1},o=this._range||this,r=L5(n,o);return t.bounds==="ticks"&&Yn(r,this,"value"),t.reverse?(r.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),r}configure(){let t=this.ticks,e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){let n=(i-e)/Math.max(t.length-1,1)/2;e-=n,i+=n}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ys(t,this.chart.options.locale,this.options.ticks.format)}},ws=class extends As{determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=ft(t)?t:0,this.max=ft(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){let t=this.isHorizontal(),e=t?this.width:this.height,i=Zt(this.options.ticks.minRotation),n=(t?Math.sin(i):Math.cos(i))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,o.lineHeight/n))}getPixelForValue(t){return t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}};Y(ws,"id","linear"),Y(ws,"defaults",{ticks:{callback:xs.formatters.numeric}});di=s=>Math.floor(ce(s)),Ue=(s,t)=>Math.pow(10,di(s)+t);Ds=class extends Oe{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){let i=As.prototype.parse.apply(this,[t,e]);if(i===0){this._zero=!0;return}return ft(i)&&i>0?i:null}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=ft(t)?Math.max(0,t):null,this.max=ft(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!ft(this._userMin)&&(this.min=t===Ue(this.min,0)?Ue(this.min,-1):Ue(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),i=this.min,n=this.max,o=a=>i=t?i:a,r=a=>n=e?n:a;i===n&&(i<=0?(o(1),r(10)):(o(Ue(i,-1)),r(Ue(n,1)))),i<=0&&o(Ue(n,-1)),n<=0&&r(Ue(i,1)),this.min=i,this.max=n}buildTicks(){let t=this.options,e={min:this._userMin,max:this._userMax},i=c5(e,this);return t.bounds==="ticks"&&Yn(i,this,"value"),t.reverse?(i.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),i}getLabelForValue(t){return t===void 0?"0":ys(t,this.chart.options.locale,this.options.ticks.format)}configure(){let t=this.min;super.configure(),this._startValue=ce(t),this._valueRange=ce(this.max)-ce(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(ce(t)-this._startValue)/this._valueRange)}getValueForPixel(t){let e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}};Y(Ds,"id","logarithmic"),Y(Ds,"defaults",{ticks:{callback:xs.formatters.logarithmic,major:{enabled:!0}}});Te=class extends As{constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){let t=this._padding=Ct($o(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!1);this.min=ft(t)&&!isNaN(t)?t:0,this.max=ft(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/$o(this.options))}generateTickLabels(t){As.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((e,i)=>{let n=ct(this.options.pointLabels.callback,[e,i],this);return n||n===0?n:""}).filter((e,i)=>this.chart.getDataVisibility(i))}fit(){let t=this.options;t.display&&t.pointLabels.display?h5(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,n){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-n)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,n))}getIndexAngle(t){let e=ht/(this._pointLabels.length||1),i=this.options.startAngle||0;return yt(t*e+Zt(i))}getDistanceFromCenterForValue(t){if(st(t))return NaN;let e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(st(t))return NaN;let e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){let e=this._pointLabels||[];if(t>=0&&t{if(d!==0||d===0&&this.min<0){L=this.getDistanceFromCenterForValue(c.value);let h=this.getContext(d),u=n.setContext(h),f=o.setContext(h);C5(this,u,L,r,f)}}),i.display){for(t.save(),a=r-1;a>=0;a--){let c=i.setContext(this.getPointLabelContext(a)),{color:d,lineWidth:h}=c;!h||!d||(t.lineWidth=h,t.strokeStyle=d,t.setLineDash(c.borderDash),t.lineDashOffset=c.borderDashOffset,L=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,L),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){let t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;let n=this.getIndexAngle(0),o,r;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(n),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach((a,L)=>{if(L===0&&this.min>=0&&!e.reverse)return;let l=i.setContext(this.getContext(L)),c=gt(l.font);if(o=this.getDistanceFromCenterForValue(this.ticks[L].value),l.showLabelBackdrop){t.font=c.string,r=t.measureText(a.label).width,t.fillStyle=l.backdropColor;let d=Ct(l.backdropPadding);t.fillRect(-r/2-d.left,-o-c.size/2-d.top,r+d.width,c.size+d.height)}Ee(t,a.label,0,-o,c,{color:l.color,strokeColor:l.textStrokeColor,strokeWidth:l.textStrokeWidth})}),t.restore()}drawTitle(){}};Y(Te,"id","radialLinear"),Y(Te,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:xs.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),Y(Te,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),Y(Te,"descriptors",{angleLines:{_fallback:"grid"}});dn={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},It=Object.keys(dn);Pe=class extends Oe{constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){let i=t.time||(t.time={}),n=this._adapter=new _L._date(t.adapters.date);n.init(e),gs(i.displayFormats,n.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return t===void 0?null:gL(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){let t=this.options,e=this._adapter,i=t.time.unit||"day",{min:n,max:o,minDefined:r,maxDefined:a}=this.getUserBounds();function L(l){!r&&!isNaN(l.min)&&(n=Math.min(n,l.min)),!a&&!isNaN(l.max)&&(o=Math.max(o,l.max))}(!r||!a)&&(L(this._getLabelBounds()),(t.bounds!=="ticks"||t.ticks.source!=="labels")&&L(this.getMinMax(!1))),n=ft(n)&&!isNaN(n)?n:+e.startOf(Date.now(),i),o=ft(o)&&!isNaN(o)?o:+e.endOf(Date.now(),i)+1,this.min=Math.min(n,o-1),this.max=Math.max(n+1,o)}_getLabelBounds(){let t=this.getLabelTimestamps(),e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){let t=this.options,e=t.time,i=t.ticks,n=i.source==="labels"?this.getLabelTimestamps():this._generate();t.bounds==="ticks"&&n.length&&(this.min=this._userMin||n[0],this.max=this._userMax||n[n.length-1]);let o=this.min,r=this.max,a=Jr(n,o,r);return this._unit=e.unit||(i.autoSkip?mL(e.minUnit,this.min,this.max,this._getLabelCapacity(o)):S5(this,a.length,e.minUnit,this.min,this.max)),this._majorUnit=!i.major.enabled||this._unit==="year"?void 0:k5(this._unit),this.initOffsets(n),t.reverse&&a.reverse(),vL(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(t=>+t.value))}initOffsets(t=[]){let e=0,i=0,n,o;this.options.offset&&t.length&&(n=this.getDecimalForValue(t[0]),t.length===1?e=1-n:e=(this.getDecimalForValue(t[1])-n)/2,o=this.getDecimalForValue(t[t.length-1]),t.length===1?i=o:i=(o-this.getDecimalForValue(t[t.length-2]))/2);let r=t.length<3?.5:.25;e=mt(e,0,r),i=mt(i,0,r),this._offsets={start:e,end:i,factor:1/(e+1+i)}}_generate(){let t=this._adapter,e=this.min,i=this.max,n=this.options,o=n.time,r=o.unit||mL(o.minUnit,e,i,this._getLabelCapacity(e)),a=tt(n.ticks.stepSize,1),L=r==="week"?o.isoWeekday:!1,l=Ze(L)||L===!0,c={},d=e,h,u;if(l&&(d=+t.startOf(d,"isoWeek",L)),d=+t.startOf(d,l?"day":r),t.diff(i,e,r)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+r);let f=n.ticks.source==="data"&&this.getDataTimestamps();for(h=d,u=0;h+g)}getLabelForValue(t){let e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){let n=this.options.time.displayFormats,o=this._unit,r=e||n[o];return this._adapter.format(t,r)}_tickFormatFunction(t,e,i,n){let o=this.options,r=o.ticks.callback;if(r)return ct(r,[t,e,i],this);let a=o.time.displayFormats,L=this._unit,l=this._majorUnit,c=L&&a[L],d=l&&a[l],h=i[e],u=l&&d&&h&&h.major;return this._adapter.format(t,n||(u?d:c))}generateTickLabels(t){let e,i,n;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t=this._cache.data||[],e,i;if(t.length)return t;let n=this.getMatchingVisibleMetas();if(this._normalized&&n.length)return this._cache.data=n[0].controller.getAllParsedValues(this);for(e=0,i=n.length;e=e&&l<=i&&n.push(l);if(n.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(r=0,a=n.length;rn-o)}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;let e=this.getDataTimestamps(),i=this.getLabelTimestamps();return e.length&&i.length?t=this.normalize(e.concat(i)):t=e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(Ji(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){let e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return Ji(this._table,i*this._tableRange+this._minPos,!0)}};Y(Ts,"id","timeseries"),Y(Ts,"defaults",Pe.defaults);JL=Object.freeze({__proto__:null,CategoryScale:Ms,LinearScale:ws,LogarithmicScale:Ds,RadialLinearScale:Te,TimeScale:Pe,TimeSeriesScale:Ts}),M5=[CL,VL,XL,JL]});var sh={};tr(sh,{CardView:()=>Fs,default:()=>Sn});module.exports=Il(sh);var at=require("obsidian"),wl=Ns(is());var Vl=["AT","BE","CZ","DK","EE","FI","FR","DE","GR","HU","IS","IT","LV","LI","LT","LU","MT","NL","NO","PL","PT","SK","SI","ES","SE","CH"],Nl=[{label:"\u{1F1EA}\u{1F1FA} Schengen 90/180 (example)",scope:{countries:Vl},window:{type:"rolling",days:180},threshold:90,note:"Example rule \u2014 add your own in Settings \u2192 CSV Card View."}],Dn={defaultMode:"kanban-genre",notesColumns:["notes","note","Notes","Note","description","Description","review","Review"],statusColumn:"status",categoryColumn:"category",notesSubfolder:"Notes",columnWidths:{},selectColumns:["Category","Type","Rating","Status","rating","type","category","status","Score /5"],fileConfigs:{},residencyRules:Nl,showResidency:!0},ui="xlsx-card-view";var sr=Ns(is()),fi=require("obsidian"),ns=["Image","image","Cover","cover","Poster","poster","Thumbnail","thumbnail","Thumb","thumb","Photo","photo","Picture","picture","Img","img"],fe=["Title","title","Name","name"],os=["Category","category","Categories","categories","Genre","genre","Genres","genres","Type","type","Types","types","Tag","tag","Tags","tags","Topic","topic","Topics","topics","Subject","subject","Section","section"],rs=["Status","status","State","state","Progress","progress","Stage","stage","Read","read","Watched","watched","Seen","seen","Done","done","Completed","completed"],pe=["Notes","notes","Note","note","Summary","summary","Review","review","Quote","quote","Quotes","quotes","Comment","comment","Comments","comments","Description","description","Annotation","annotation"],pi=["Price","price","Cost","cost","Amount","amount","Total","total","Spend","spend","Spent","spent","Value","value"];function gi(s,t,e){let i=(t!=null?t:"").trim();if(!i)return null;if(/^(https?:|data:)/i.test(i))return i;let n=i.match(/!?\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/);if(n)i=n[1].trim();else{let r=i.match(/!\[[^\]]*\]\(([^)]+)\)/);r&&(i=r[1].trim())}if(/^(https?:|data:)/i.test(i))return i;let o=s.metadataCache.getFirstLinkpathDest(i,e);return o instanceof fi.TFile?s.vault.getResourcePath(o):null}var Bl=15;function qt(s){return s>=1&&s<=Bl}var $l=["0","1","true","false","yes","no",""];function as(s){return s.length>0&&s.every(t=>$l.includes(t))}function Ls(s){let t=(s!=null?s:"").toLowerCase().trim();return t==="1"||t==="true"||t==="yes"}function ge(s=new Date){return`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`}function Ve(s){return s.replace(/[\\/:*?"<>|#^[\]]/g,"").replace(/\s+/g," ").trim().slice(0,100)}function ir(s){return s.toLowerCase().replace(/[^\p{L}\p{N}/_-]+/gu,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function kt(s){var n,o;if(!s||!s.trim())return{headers:[],rows:[]};let t=sr.default.parse(s,{header:!0,skipEmptyLines:!0}),e=((n=t.meta.fields)!=null?n:[]).map(String),i=((o=t.data)!=null?o:[]).map(r=>{let a={};return e.forEach(L=>{a[L]=r[L]!=null?String(r[L]):""}),a});return{headers:e,rows:i}}function Xt(s,t){if(!s)return s;let e=s.startsWith("./")||s.startsWith("../")||s==="."||s==="..";if(!e&&s.includes("/"))return s;if(!e)return t?`${t}/${s}`:s;let i=t?t.split("/").filter(Boolean):[];for(let n of s.split("/"))if(!(n===""||n===".")){if(n===".."){i.pop();continue}i.push(n)}return i.join("/")}function nr(s,t,e){let i=e==="asc"?1:-1;return[...s].sort((n,o)=>{var h,u;let r=((h=n[t])!=null?h:"").trim(),a=((u=o[t])!=null?u:"").trim();if(!r&&!a)return 0;if(!r)return 1;if(!a)return-1;let L=parseFloat(r),l=parseFloat(a);return(!isNaN(L)&&!isNaN(l)&&/^-?[\d.]/.test(r)&&/^-?[\d.]/.test(a)?L-l:r.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"}))*i})}function Dt(s){return s.split(/[\s_-]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function or(s,t){let e=(s!=null?s:"").trim();if(!e||e.toLowerCase()==="unrated"||e==="\u2014"||e==="-")return"";if(/[★⭐☆]/.test(e))return e;if(/^\d+$/.test(e)){let o=parseInt(e,10);if(o>=1&&o<=5)return"\u2605".repeat(o)}let n=zl(e,t);return n&&n!==e&&n!=="\u2014"?n:""}function zl(s,t){var o;let e=t.toLowerCase();if(!["rating","score","score /5"].includes(e))return s;let i=s.toLowerCase().trim();return(o={excellent:"\u2605\u2605\u2605\u2605\u2605",great:"\u2605\u2605\u2605\u2605\u2605",good:"\u2605\u2605\u2605\u2605\u2606",fair:"\u2605\u2605\u2605\u2606\u2606",poor:"\u2605\u2605\u2606\u2606\u2606",bad:"\u2605\u2606\u2606\u2606\u2606",5:"\u2605\u2605\u2605\u2605\u2605",4:"\u2605\u2605\u2605\u2605\u2606",3:"\u2605\u2605\u2605\u2606\u2606",2:"\u2605\u2605\u2606\u2606\u2606",1:"\u2605\u2606\u2606\u2606\u2606",0:"\u2606\u2606\u2606\u2606\u2606",unrated:"\u2014","":"\u2014"}[i])!=null?o:s}function rr(s,t){if(/^(year|released|decade)$/i.test((s!=null?s:"").trim()))return!0;let e=t.map(n=>(n!=null?n:"").trim()).filter(Boolean);return e.length<3?!1:e.filter(n=>/^(1[89]|20)\d{2}$/.test(n)).length/e.length>=.8}function ar(s){let t=(s!=null?s:"").match(/\b(1[89]\d{2}|20\d{2})\b/);return t?`${Math.floor(parseInt(t[1],10)/10)*10}s`:null}function Lr(s,t,e){var r;if(!t.length)return null;let i=Math.max(12,t.length/3),n=null,o=1/0;for(let a of s){if(e.has(a))continue;let L=new Set;for(let c of t)((r=c[a])!=null?r:"").split(",").forEach(d=>{let h=d.trim();h&&L.add(h)});if(L.size<2||L.size>i)continue;let l=Math.abs(Math.log(L.size/8));lM.remove());let r=document.body.createDiv({cls:"csv-select-picker"}),a=()=>{let M=s.getBoundingClientRect(),D=r.offsetHeight||280,A=M.bottom+4+D>window.innerHeight&&M.top-4-D>0;r.style.left=M.left+"px",r.style.top=A?M.top-4-D+"px":M.bottom+4+"px"};a();let L=M=>{!r.contains(M.target)&&M.target!==s&&c()},l=M=>{r.contains(M.target)||c()},c=()=>{r.remove(),document.removeEventListener("mousedown",L),window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",c)},d=r.createEl("input",{cls:"csv-picker-search",type:"text",placeholder:"Search or add\u2026"});d.focus();let h=r.createDiv({cls:"csv-picker-list"}),u=!!(o!=null&&o.multi),f=M=>M.split(",").map(D=>D.trim()).filter(Boolean),g=new Set(u?f(t):[]),m=()=>i([...g].join(", ")),p=u?Array.from(new Set(e.flatMap(f))):Array.from(new Set(e.filter(Boolean))),b=[],C=0,S=()=>{h.querySelectorAll(".csv-picker-item").forEach((M,D)=>{M.toggleClass("csv-picker-item--hover",D===C),D===C&&M.scrollIntoView({block:"nearest"})})},_=M=>{if(!u){i(M.isClear?"":M.value),c();return}M.isClear?g.clear():(g.has(M.value)?g.delete(M.value):g.add(M.value),M.isAdd&&!p.includes(M.value)&&p.push(M.value)),m(),M.isAdd?(d.value="",x("")):x(d.value)},y=M=>u?g.has(M):M===t.trim(),v=()=>u?g.size>0:!!t,x=M=>{h.empty(),b=[];let D=M?p.filter(A=>A.toLowerCase().includes(M.toLowerCase())):p;if(v()){b.push({value:"",isClear:!0});let A=h.createDiv({cls:"csv-picker-item csv-picker-clear"});A.setText(u?"\u2715 Clear all":"\u2715 Clear"),A.addEventListener("mousedown",N=>{N.preventDefault(),_({value:"",isClear:!0})})}if(D.forEach(A=>{b.push({value:A});let N=h.createDiv({cls:`csv-picker-item ${y(A)?"active":""}`});N.setText(u?`${g.has(A)?"\u2713 ":""}${A}`:A),N.addEventListener("mousedown",I=>{I.preventDefault(),_({value:A})})}),M&&!p.some(A=>A.toLowerCase()===M.toLowerCase())){b.push({value:M,isAdd:!0});let A=h.createDiv({cls:"csv-picker-item csv-picker-add"});A.setText(`+ Add "${M}"`),A.addEventListener("mousedown",N=>{N.preventDefault(),_({value:M,isAdd:!0})})}!D.length&&!M&&h.createDiv({cls:"csv-picker-empty",text:"No options yet. Type to add."}),C=Math.min(C,Math.max(b.length-1,0)),S()};u&&r.createEl("button",{cls:"csv-picker-done",text:"Done"}).addEventListener("mousedown",M=>{M.preventDefault(),c()}),x(""),a(),d.addEventListener("input",()=>{C=0,x(d.value),a()});let k=typeof window!="undefined"&&((E=window.matchMedia)==null?void 0:E.call(window,"(pointer: coarse)").matches);window.setTimeout(()=>{document.addEventListener("mousedown",L),k||(window.addEventListener("scroll",l,!0),window.addEventListener("resize",c))},0),d.addEventListener("keydown",M=>{if(M.key==="Escape"){c();return}if(M.key==="ArrowDown"){M.preventDefault(),b.length&&(C=(C+1)%b.length,S());return}if(M.key==="ArrowUp"){M.preventDefault(),b.length&&(C=(C-1+b.length)%b.length,S());return}if(M.key==="Enter")if(M.preventDefault(),b[C])_(b[C]);else{let D=d.value.trim();D&&(i(D),c())}})}async function ls(s,t,e){var L,l;let i=(l=(L=t.parent)==null?void 0:L.path)!=null?l:"",n=i?`${i}/Archive`:"Archive";await s.vault.adapter.exists(n)||await s.vault.adapter.mkdir(n);let o=new Date,r=`${ge(o)} ${String(o.getHours()).padStart(2,"0")}${String(o.getMinutes()).padStart(2,"0")}${String(o.getSeconds()).padStart(2,"0")}`,a=`${n}/${t.basename} sync-conflict ${r}.csv`;return await s.vault.adapter.write(a,e),new fi.Notice(`"${t.name}" changed on disk while you were editing (another device?). That version was saved to ${a} \u2014 your edits won.`,1e4),a}function lr(s,t,e){return!s[t]||t===e||(s[e]||(s[e]=s[t]),delete s[t]),s}var Hl={source:["confirmed","inferred","conflict"],resolved:["yes","no"]};function cr(s){var t;return(t=Hl[s.trim().toLowerCase()])!=null?t:null}function Et(s){return/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(s.trim())}var mi=/^\d{4}-\d{2}-\d{2}$/;var Tt=require("obsidian");function yi(s,t,e,i,n=Et){let o=n(t)&&(e===""||mi.test(e.slice(0,10))),r=o?e.slice(0,10):e,a=s.createEl("input",{cls:i,type:o?"date":"text",value:r});o||(a.placeholder=t);let L=cr(t);if(L){let l=`csv-dl-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-${Math.random().toString(36).slice(2,7)}`,c=s.createEl("datalist");c.id=l,L.forEach(d=>c.createEl("option",{value:d})),a.setAttr("list",l)}return a}var cs=class extends Tt.Modal{constructor(t,e,i,n,o,r,a={},L=()=>!1,l,c,d=Et){super(t),this.headers=e,this.isNotesCol=i,this.isSelectCol=n,this.getColumnValues=o,this.onSubmit=r,this.optionPresets=a,this.isBooleanCol=L,this.isCategoricalCol=l!=null?l:h=>this.isSelectCol(h)||qt(this.getColumnValues(h).length),this.titleCol=c!=null?c:this.headers.find(h=>["title","name"].includes(h.toLowerCase())),this.isDateCol=d}onOpen(){let{contentEl:t}=this;t.empty(),t.addClass("csv-add-modal"),t.createEl("h2",{text:"Add new entry",cls:"csv-modal-title"});let e=t.createDiv({cls:"csv-modal-form"}),i={};this.headers.forEach(c=>i[c]="");let n=this.titleCol,o=new Map;n&&this.getColumnValues(n).forEach(c=>{let d=c.trim().toLowerCase();d&&!o.has(d)&&o.set(d,c.trim())}),this.headers.forEach(c=>{var m;let d=e.createDiv({cls:"csv-modal-row"});d.createEl("label",{text:Dt(c),cls:"csv-modal-label"});let h=(m=this.optionPresets[c])!=null?m:[],u=c===n,f=vt(c),g=!u&&!this.isNotesCol(c)&&!f&&(h.length>0||this.isCategoricalCol(c));if(this.isBooleanCol(c)){i[c]="0";let p=d.createDiv({cls:"csv-toggle"});p.createDiv({cls:"csv-toggle-knob"}),p.addEventListener("click",()=>{let b=!p.hasClass("is-on");p.toggleClass("is-on",b),i[c]=b?"1":"0"})}else if(this.isNotesCol(c)){let p=d.createEl("textarea",{cls:"csv-modal-textarea",placeholder:"Markdown supported\u2026"});p.addEventListener("input",()=>{i[c]=p.value})}else if(g){let p="__custom__",b=[];[...h,...this.getColumnValues(c)].forEach(_=>{let y=(_!=null?_:"").trim();y&&!b.some(v=>v.toLowerCase()===y.toLowerCase())&&b.push(y)});let C=d.createEl("select",{cls:"csv-modal-select"});C.createEl("option",{text:"\u2014",value:""}),b.forEach(_=>C.createEl("option",{text:_,value:_})),C.createEl("option",{text:"+ custom\u2026",value:p});let S=d.createEl("input",{cls:"csv-modal-input csv-modal-custom",type:"text",placeholder:`Custom ${Dt(c).toLowerCase()}`});S.hide(),S.addEventListener("input",()=>{i[c]=S.value}),S.addEventListener("keydown",_=>{_.key==="Enter"&&l()}),C.addEventListener("change",()=>{C.value===p?(S.show(),S.focus(),i[c]=S.value):(S.hide(),i[c]=C.value)})}else if(!u&&f&&this.isSelectCol(c)){let b=d.createDiv({cls:"csv-modal-select-wrap"}).createDiv({cls:"csv-select-chip empty"});b.setText("\u2014 click to select \u2014"),b.addEventListener("click",C=>{C.stopPropagation(),$t(b,i[c],this.getColumnValues(c),S=>{i[c]=S,b.setText(S||"\u2014 click to select \u2014"),b.toggleClass("empty",!S)},t,{multi:vt(c)})})}else{let p=yi(d,c,"","csv-modal-input",b=>this.isDateCol(b));if(p.addEventListener("input",()=>{i[c]=p.value}),p.addEventListener("keydown",b=>{b.key==="Enter"&&l()}),c===n&&o.size){let b=d.createDiv({cls:"csv-modal-dup-hint"});b.hide(),p.addEventListener("input",()=>{let C=o.get(p.value.trim().toLowerCase());C?(b.setText(`\u26A0 \u201C${C}\u201D is already in this file`),b.show()):b.hide()})}}});let r=t.createDiv({cls:"csv-modal-btns"});r.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),r.createEl("button",{text:"Add entry",cls:"csv-modal-submit"}).addEventListener("click",()=>l());let l=()=>{if(!Object.values(i).some(d=>d.trim())){new Tt.Notice("Fill in at least one field.");return}this.onSubmit(i),this.close()}}onClose(){this.contentEl.empty()}},me=class extends Tt.Modal{constructor(e,i,n,o,r,a,L,l,c,d,h,u,f=()=>!1,g=Et){super(e);this.vvHandler=null;this.row={...i},this.notesCol=n,this.headers=o,this.filePath=r,this.renderComponent=new Tt.Component,this.isNotesCol=a,this.isSelectCol=L,this.getColumnValues=l,this.onSave=c,this.onDelete=d,this.isCategoricalCol=h!=null?h:m=>this.isSelectCol(m)||!Et(m)&&qt(this.getColumnValues(m).length),this.titleCol=u!=null?u:this.headers.find(m=>["title","name","Title","Name"].includes(m)),this.isBooleanCol=f,this.isDateCol=g,this.modalEl.addClass("csv-note-expander-modal")}onOpen(){var h,u,f,g,m;this.renderComponent.load();let{contentEl:e}=this;e.empty(),e.addClass("csv-note-expander");let i=window.visualViewport;if(i){let p=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${i.height}px`)};p(),i.addEventListener("resize",p),i.addEventListener("scroll",p),this.vvHandler=p}e.createDiv({cls:"csv-expander-header"}).createDiv({cls:"csv-expander-title",text:(u=this.row[(h=this.titleCol)!=null?h:this.headers[0]])!=null?u:"\u2014"});let o=e.createDiv({cls:"csv-expander-fields"}),r=this.titleCol;this.headers.forEach(p=>{var _;if(this.isNotesCol(p))return;let b=o.createDiv({cls:"csv-expander-field-row"});if(b.createDiv({cls:"csv-expander-field-label",text:Dt(p)}),this.isBooleanCol(p)){let y=Ls((_=this.row[p])!=null?_:""),v=b.createDiv({cls:`csv-toggle ${y?"is-on":""}`});v.createDiv({cls:"csv-toggle-knob"}),v.addEventListener("click",()=>{let x=!v.hasClass("is-on");v.toggleClass("is-on",x),this.row[p]=x?"1":"0"});return}let C=vt(p);if(p!==r&&(C?this.isSelectCol(p):this.isCategoricalCol(p))){let y=b.createDiv({cls:`csv-select-chip ${this.row[p]?"":"empty"}`});y.setText(this.row[p]||"\u2014"),y.addEventListener("click",v=>{v.stopPropagation(),$t(y,this.row[p],this.getColumnValues(p),x=>{this.row[p]=x,y.setText(x||"\u2014"),y.toggleClass("empty",!x)},e,{multi:vt(p)})})}else{let y=b.createDiv({cls:"csv-expander-field-value",text:this.row[p]||"\u2014"});y.addEventListener("click",()=>{var k;if(y.querySelector("input"))return;y.empty();let v=yi(y,p,(k=this.row[p])!=null?k:"","csv-inline-input",this.isDateCol);v.focus(),v.type==="text"&&v.select(),v.addEventListener("click",E=>E.stopPropagation());let x=()=>{this.row[p]=v.value,y.empty(),y.setText(v.value||"\u2014")};v.addEventListener("blur",x),v.addEventListener("keydown",E=>{E.key==="Enter"&&v.blur(),E.key==="Escape"&&(y.empty(),y.setText(this.row[p]||"\u2014"))})})}});let a=!1,L=this.notesCol&&(f=this.row[this.notesCol])!=null?f:"",l=null;if(this.notesCol){e.createDiv({cls:"csv-expander-divider"}).createDiv({cls:"csv-expander-notes-label",text:this.notesCol});let b=e.createDiv({cls:"csv-expander-rendered markdown-rendered"});b.title="Click to edit";let C=e.createDiv({cls:"csv-expander-editor is-hidden"}),S=()=>{b.empty(),L.trim()?Tt.MarkdownRenderer.render(this.app,L,b,this.filePath,this.renderComponent):b.createDiv({cls:"csv-notes-empty",text:"+ add note"})};S(),l=C.createEl("textarea",{cls:"csv-expander-textarea"}),l.value=L,l.addEventListener("input",()=>{L=l.value});let _=()=>{a||(a=!0,b.classList.add("is-hidden"),C.classList.remove("is-hidden"),l.value=L,l.focus())},y=()=>{a&&(a=!1,C.classList.add("is-hidden"),b.classList.remove("is-hidden"),L=l.value,S())};b.addEventListener("click",v=>{if(v.target.closest("a, button, input, textarea, [contenteditable]"))return;let k=window.getSelection();k&&k.toString().length>0||_()}),l.addEventListener("keydown",v=>{v.key==="Escape"&&(v.preventDefault(),l.blur())}),l.addEventListener("blur",y)}let c=e.createDiv({cls:"csv-expander-footer"});if(this.onDelete){let p=String((m=this.row[(g=this.titleCol)!=null?g:this.headers[0]])!=null?m:"").trim(),b=c.createEl("button",{cls:"csv-expander-delete-btn",text:"Delete",attr:{title:`Delete "${p||"this entry"}"? This can't be undone.`}});b.addEventListener("click",()=>{if(b.hasClass("confirm")){this.onDelete(),this.close();return}b.addClass("confirm"),b.setText("Confirm?"),window.setTimeout(()=>{b.isConnected&&(b.removeClass("confirm"),b.setText("Delete"))},3e3)})}let d=c.createDiv({cls:"csv-expander-footer-right"});d.createEl("button",{cls:"csv-modal-cancel",text:"Cancel"}).addEventListener("click",()=>this.close()),d.createEl("button",{cls:"csv-expander-save-btn",text:"Save & close"}).addEventListener("click",()=>{this.notesCol&&(a&&l&&(L=l.value),this.row[this.notesCol]=L),this.onSave(this.row),this.close()})}onClose(){let e=window.visualViewport;e&&this.vvHandler&&(e.removeEventListener("resize",this.vvHandler),e.removeEventListener("scroll",this.vvHandler)),this.vvHandler=null,this.renderComponent.unload(),this.contentEl.empty()}},bi=class extends Tt.Modal{constructor(e,i,n,o,r,a){super(e);this.vvHandler=null;this.initialQuery=i,this.onInput=n,this.resultCount=o,this.getMatches=r,this.onPick=a,this.modalEl.addClass("csv-search-modal")}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("csv-search-modal-content"),this.containerEl.addClass("mod-csv-search-bg");let i=window.visualViewport;if(i){let h=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${i.height}px`)};h(),i.addEventListener("resize",h),i.addEventListener("scroll",h),this.vvHandler=h}let n=e.createDiv({cls:"csv-search-modal-row"}),o=n.createEl("input",{cls:"csv-search-modal-input",type:"text",placeholder:"Search\u2026",value:this.initialQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}});n.createEl("button",{cls:"csv-search-modal-close",text:"\u2715",title:"Close"}).addEventListener("click",()=>this.close());let a=e.createDiv({cls:"csv-search-modal-count"}),L=e.createDiv({cls:"csv-search-modal-list"}),l=40,c=()=>{let{matched:h,total:u}=this.resultCount();if(a.setText(o.value.trim()?`${h} of ${u} entries match`:`${u} entries \u2014 start typing to search`),L.empty(),!o.value.trim())return;this.getMatches().slice(0,l).forEach(({title:g,subtitle:m,row:p})=>{let b=L.createDiv({cls:"csv-search-modal-item"});b.createDiv({cls:"csv-search-modal-item-title",text:g||"\u2014"}),m&&b.createDiv({cls:"csv-search-modal-item-sub",text:m}),b.addEventListener("click",()=>{this.close(),this.onPick(p)})}),h>l&&L.createDiv({cls:"csv-search-modal-more",text:`+ ${h-l} more \u2014 close to see all in the view`})};c();let d=null;o.addEventListener("input",()=>{d!==null&&window.clearTimeout(d),d=window.setTimeout(()=>{d=null,this.onInput(o.value),c()},120)}),o.addEventListener("keydown",h=>{h.key==="Enter"&&this.close()}),window.requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(o.value.length,o.value.length)})}onClose(){let e=window.visualViewport;e&&this.vvHandler&&(e.removeEventListener("resize",this.vvHandler),e.removeEventListener("scroll",this.vvHandler)),this.vvHandler=null,this.contentEl.empty()}},vi=class extends Tt.Modal{constructor(t,e,i,n,o,r,a,L,l,c,d,h,u,f=()=>0){super(t),this.headers=e,this.filePath=i,this.current={...n,habitColumns:n.habitColumns?[...n.habitColumns]:void 0,categoricalColumns:n.categoricalColumns?[...n.categoricalColumns]:void 0},this.autoDetectedHabits=o,this.autoDetectedCategorical=r,this.autoDetectedRoles=a,this.availableModes=L,this.onSave=l,this.getHeaders=c,this.getFileCfg=d,this.onAddColumn=h,this.onRemoveColumn=u,this.onCleanupBooleanColumn=f}onOpen(){var N,I,P;let{contentEl:t}=this;t.empty(),t.addClass("csv-add-modal"),t.createEl("h2",{text:"View settings for this file",cls:"csv-modal-title"}),t.createEl("p",{text:"These settings apply only to this file and override the global defaults.",cls:"csv-modal-desc"});let e=t.createDiv({cls:"csv-modal-form"}),i=()=>{this.headers=this.getHeaders();let w=this.getFileCfg();this.current={...w,habitColumns:w.habitColumns?[...w.habitColumns]:void 0,categoricalColumns:w.categoricalColumns?[...w.categoricalColumns]:void 0},this.onOpen()},n=e.createDiv({cls:"csv-modal-row"});n.createEl("label",{text:"Columns",cls:"csv-modal-label"}),n.createEl("p",{cls:"csv-modal-hint",text:`Type and function are each exclusive per column \u2014 picking one clears it from whichever column held it before. "auto" means it's already doing that by column name, with nothing saved here yet. Card field is independent and can combine with anything. Checkbox columns get a "clean up" action that rewrites every row to strict 1/0 right away \u2014 not deferred to save.`});let o=[{value:"text",label:"Text"},{value:"checkbox",label:"Checkbox"},{value:"categorical",label:"Categorical"},{value:"date",label:"Date"}],r=[{value:"",label:"\u2014 no function \u2014"},{value:"title",label:"Title"},{value:"category",label:"Column group (Kanban lanes)"},{value:"status",label:"Row group / Status / Checkmark"},{value:"notes",label:"Notes"},{value:"image",label:"Image (card / kanban thumbnail)"},{value:"anki",label:"Anki card front"},{value:"price",label:"Price (Budget view)"}],a=w=>{var B,G,R;let U=(B=this.current.habitColumns)!=null?B:this.autoDetectedHabits,O=(G=this.current.categoricalColumns)!=null?G:this.autoDetectedCategorical,Z=(R=this.current.dateColumns)!=null?R:this.headers.filter(W=>Et(W));return U.includes(w)?{type:"checkbox",auto:!this.current.habitColumns}:O.includes(w)?{type:"categorical",auto:!this.current.categoricalColumns}:Z.includes(w)?{type:"date",auto:!this.current.dateColumns}:{type:"text",auto:!1}},L=(w,U)=>{this.current.habitColumns||(this.current.habitColumns=[...this.autoDetectedHabits]),this.current.categoricalColumns||(this.current.categoricalColumns=[...this.autoDetectedCategorical]),this.current.dateColumns||(this.current.dateColumns=this.headers.filter(O=>Et(O))),this.current.habitColumns=this.current.habitColumns.filter(O=>O!==w),this.current.categoricalColumns=this.current.categoricalColumns.filter(O=>O!==w),this.current.dateColumns=this.current.dateColumns.filter(O=>O!==w),U==="checkbox"?this.current.habitColumns.push(w):U==="categorical"?this.current.categoricalColumns.push(w):U==="date"&&this.current.dateColumns.push(w)},l=(I=(N=this.current.titleColumn)!=null?N:this.autoDetectedRoles.title)!=null?I:this.headers[0],d=n.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),h=d.createEl("thead").createEl("tr");["Column","Type","Visibility"].forEach(w=>h.createEl("th",{text:w}));let u=d.createEl("tbody"),f=()=>{var U;u.empty();let w=new Set((U=this.current.cardFields)!=null?U:this.headers);this.headers.forEach(O=>{let Z=u.createEl("tr"),B=Z.createEl("td",{cls:"csv-modal-colcfg-name"});B.createSpan({text:O});let G=B.createEl("button",{cls:"csv-modal-column-remove",text:"\u2715",attr:{title:`Remove "${O}" \u2014 deletes this column's data from every row`}});G.addEventListener("click",()=>{if(G.hasClass("confirm")){this.onRemoveColumn(O),i();return}u.querySelectorAll(".csv-modal-column-remove.confirm").forEach(T=>{T.removeClass("confirm"),T.setText("\u2715")}),G.addClass("confirm"),G.setText("Confirm?"),window.setTimeout(()=>{G.isConnected&&(G.removeClass("confirm"),G.setText("\u2715"))},3e3)});let R=Z.createEl("td",{cls:"csv-modal-colcfg-type-cell"});if(O===l)R.createSpan({cls:"csv-modal-colcfg-fixed",text:"Text"});else{let T=R.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-type"}),{type:F,auto:H}=a(O);if(o.forEach($=>{let z=T.createEl("option",{text:$.label,value:$.value});$.value===F&&(z.selected=!0)}),H&&T.addClass("auto-detected"),T.addEventListener("change",()=>{L(O,T.value),f()}),H&&R.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"}),F==="checkbox"){let $=R.createEl("button",{cls:"csv-modal-colcfg-cleanup-btn",text:"Clean up",attr:{title:`Rewrite every row in "${O}" to strict 1/0 (yes/true/1 \u2192 1, everything else \u2192 0)`}});$.addEventListener("click",()=>{if($.hasClass("confirm")){let z=this.onCleanupBooleanColumn(O);new Tt.Notice(z>0?`"${O}": normalized ${z} row${z===1?"":"s"} to 1/0.`:`"${O}" is already strict 1/0 \u2014 nothing to change.`);return}u.querySelectorAll(".csv-modal-colcfg-cleanup-btn.confirm").forEach(z=>{z.removeClass("confirm"),z.setText("Clean up")}),$.addClass("confirm"),$.setText("Confirm?"),window.setTimeout(()=>{$.isConnected&&($.removeClass("confirm"),$.setText("Clean up"))},3e3)})}}let K=Z.createEl("td",{cls:"csv-modal-colcfg-card-cell"}).createEl("input",{type:"checkbox"});K.checked=w.has(O),K.addEventListener("change",()=>{this.current.cardFields||(this.current.cardFields=[...this.headers]),K.checked?this.current.cardFields.includes(O)||this.current.cardFields.push(O):this.current.cardFields=this.current.cardFields.filter(T=>T!==O)})})};f();let g=t.createDiv({cls:"csv-modal-section",attr:{style:"margin-top: 24px;"}});g.createEl("h3",{text:"Column functions",cls:"csv-modal-h3"}),g.createEl("p",{cls:"csv-modal-desc",text:"Assign specific roles to your columns. 'auto' means it's already doing that by column name. Selecting '\u2014 none \u2014' disables the function entirely."});let p=g.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),b=p.createEl("thead").createEl("tr");["Function","Column"].forEach(w=>b.createEl("th",{text:w}));let C=p.createEl("tbody"),S=()=>{C.empty(),r.forEach(w=>{var W,K,T,F,H,$,z,V,j,X,q,nt,Q,et;if(w.value==="")return;let U=C.createEl("tr");U.createEl("td",{cls:"csv-modal-colcfg-name"}).setText(w.label);let Z=U.createEl("td",{cls:"csv-modal-colcfg-type-cell"}),B=Z.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-role"});B.createEl("option",{text:"\u2014 none \u2014",value:""});let G="",R=!1;w.value==="title"?(G=(K=(W=this.current.titleColumn)!=null?W:this.autoDetectedRoles.title)!=null?K:"",R=this.current.titleColumn===void 0&&!!this.autoDetectedRoles.title):w.value==="category"?(G=(F=(T=this.current.categoryColumn)!=null?T:this.autoDetectedRoles.category)!=null?F:"",R=this.current.categoryColumn===void 0&&!!this.autoDetectedRoles.category):w.value==="status"?(G=($=(H=this.current.statusColumn)!=null?H:this.autoDetectedRoles.status)!=null?$:"",R=this.current.statusColumn===void 0&&!!this.autoDetectedRoles.status):w.value==="notes"?(G=(V=(z=this.current.notesColumn)!=null?z:this.autoDetectedRoles.notes)!=null?V:"",R=this.current.notesColumn===void 0&&!!this.autoDetectedRoles.notes):w.value==="image"?(G=(X=(j=this.current.imageColumn)!=null?j:this.autoDetectedRoles.image)!=null?X:"",R=this.current.imageColumn===void 0&&!!this.autoDetectedRoles.image):w.value==="anki"?(G=(nt=(q=this.current.ankiFrontCol)!=null?q:this.autoDetectedRoles.anki)!=null?nt:"",R=this.current.ankiFrontCol===void 0&&!!this.autoDetectedRoles.anki):w.value==="price"&&(G=(et=(Q=this.current.budgetPriceCol)!=null?Q:this.autoDetectedRoles.price)!=null?et:"",R=this.current.budgetPriceCol===void 0&&!!this.autoDetectedRoles.price),this.headers.forEach(J=>{let ot=B.createEl("option",{text:J,value:J});J===G&&(ot.selected=!0)}),R&&G!==""&&B.addClass("auto-detected"),B.addEventListener("change",()=>{let J=B.value;J&&(w.value!=="title"&&this.current.titleColumn===J&&(this.current.titleColumn=void 0),w.value!=="category"&&this.current.categoryColumn===J&&(this.current.categoryColumn=void 0),w.value!=="status"&&this.current.statusColumn===J&&(this.current.statusColumn=void 0),w.value!=="notes"&&this.current.notesColumn===J&&(this.current.notesColumn=void 0),w.value!=="image"&&this.current.imageColumn===J&&(this.current.imageColumn=void 0),w.value!=="anki"&&this.current.ankiFrontCol===J&&(this.current.ankiFrontCol=void 0),w.value!=="price"&&this.current.budgetPriceCol===J&&(this.current.budgetPriceCol=void 0)),w.value==="title"?this.current.titleColumn=J:w.value==="category"?this.current.categoryColumn=J:w.value==="status"?this.current.statusColumn=J:w.value==="notes"?this.current.notesColumn=J:w.value==="image"?this.current.imageColumn=J:w.value==="anki"?this.current.ankiFrontCol=J:w.value==="price"&&(this.current.budgetPriceCol=J),S()}),R&&G!==""&&Z.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"})})};S();let _=n.createDiv({cls:"csv-modal-add-column"}),y=_.createEl("input",{cls:"csv-modal-input",type:"text",placeholder:"New column name"}),v=_.createEl("button",{cls:"csv-modal-cancel",text:"+ add column"}),x=()=>{let w=this.onAddColumn(y.value);if(w){new Tt.Notice(w);return}i()};v.addEventListener("click",x),y.addEventListener("keydown",w=>{w.key==="Enter"&&(w.preventDefault(),x())});let k=e.createDiv({cls:"csv-modal-row"});k.createEl("label",{text:"Default view",cls:"csv-modal-label"});let E=k.createEl("select",{cls:"csv-modal-select"}),M=[["\u2014 use global default \u2014",""],...this.availableModes.map(w=>[w.label,w.id])],D=(P=this.current.defaultMode)!=null?P:"";D&&!this.availableModes.some(w=>w.id===D)&&M.push([`${D} (no longer available)`,D]),M.forEach(([w,U])=>{let O=E.createEl("option",{text:w,value:U});D===U&&(O.selected=!0)}),E.addEventListener("change",()=>{this.current.defaultMode=E.value?E.value:void 0});let A=t.createDiv({cls:"csv-modal-btns"});A.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),A.createEl("button",{text:"Save",cls:"csv-modal-submit"}).addEventListener("click",()=>{this.onSave(this.current),this.close()})}onClose(){this.contentEl.empty()}},Ne=class extends Tt.Modal{constructor(e,i,n,o,r,a="Create",L="text"){super(e);this.title=i;this.initial=n;this.placeholder=o;this.onSubmit=r;this.submitLabel=a;this.inputType=L}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("csv-add-modal"),e.createEl("h2",{text:this.title,cls:"csv-modal-title"});let i=e.createEl("input",{cls:"csv-modal-field",type:this.inputType});i.value=this.initial,i.placeholder=this.placeholder,window.setTimeout(()=>{i.focus(),i.select()},0);let n=()=>{let r=i.value.trim();r&&(this.onSubmit(r),this.close())};i.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),n())});let o=e.createDiv({cls:"csv-modal-btns"});o.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),o.createEl("button",{text:this.submitLabel,cls:"csv-modal-submit"}).addEventListener("click",n)}onClose(){this.contentEl.empty()}};var Tn=195,Zl={AF:"Afghanistan",AL:"Albania",DZ:"Algeria",AD:"Andorra",AO:"Angola",AR:"Argentina",AM:"Armenia",AU:"Australia",AT:"Austria",AZ:"Azerbaijan",BD:"Bangladesh",BY:"Belarus",BE:"Belgium",BO:"Bolivia",BA:"Bosnia",BW:"Botswana",BR:"Brazil",BG:"Bulgaria",KH:"Cambodia",CM:"Cameroon",CA:"Canada",CL:"Chile",CN:"China",CO:"Colombia",HR:"Croatia",CU:"Cuba",CY:"Cyprus",CZ:"Czechia",DK:"Denmark",DO:"Dominican Rep.",EC:"Ecuador",EG:"Egypt",ET:"Ethiopia",FI:"Finland",FR:"France",GE:"Georgia",DE:"Germany",GH:"Ghana",GR:"Greece",GT:"Guatemala",GY:"Guyana",HT:"Haiti",HN:"Honduras",HU:"Hungary",IS:"Iceland",IN:"India",ID:"Indonesia",IR:"Iran",IQ:"Iraq",IE:"Ireland",IL:"Israel",IT:"Italy",JP:"Japan",JO:"Jordan",KZ:"Kazakhstan",KE:"Kenya",KP:"N. Korea",KR:"S. Korea",KW:"Kuwait",KG:"Kyrgyzstan",LA:"Laos",LV:"Latvia",LB:"Lebanon",LY:"Libya",LI:"Liechtenstein",LT:"Lithuania",LU:"Luxembourg",MY:"Malaysia",ML:"Mali",MT:"Malta",MR:"Mauritania",MX:"Mexico",MD:"Moldova",MN:"Mongolia",ME:"Montenegro",MA:"Morocco",MZ:"Mozambique",MM:"Myanmar",NA:"Namibia",NP:"Nepal",NL:"Netherlands",NZ:"New Zealand",NI:"Nicaragua",NE:"Niger",NG:"Nigeria",NO:"Norway",OM:"Oman",PK:"Pakistan",PA:"Panama",PG:"Papua New Guinea",PY:"Paraguay",PE:"Peru",PH:"Philippines",PL:"Poland",PT:"Portugal",QA:"Qatar",RO:"Romania",RU:"Russia",RW:"Rwanda",SA:"Saudi Arabia",SN:"Senegal",RS:"Serbia",SG:"Singapore",SK:"Slovakia",SI:"Slovenia",SO:"Somalia",ZA:"South Africa",SS:"South Sudan",ES:"Spain",LK:"Sri Lanka",SD:"Sudan",SE:"Sweden",CH:"Switzerland",SY:"Syria",TJ:"Tajikistan",TZ:"Tanzania",TH:"Thailand",TN:"Tunisia",TR:"Turkey",TM:"Turkmenistan",UG:"Uganda",UA:"Ukraine",AE:"UAE",GB:"United Kingdom",US:"United States",UY:"Uruguay",UZ:"Uzbekistan",VN:"Vietnam",YE:"Yemen",ZM:"Zambia",ZW:"Zimbabwe",MC:"Monaco",BZ:"Belize"},Wl={AF:["DZ","AO","BJ","BW","BF","BI","CM","CV","CF","TD","KM","CD","CG","CI","DJ","EG","GQ","ER","ET","GA","GM","GH","GN","GW","KE","LS","LR","LY","MG","MW","ML","MR","MU","MA","MZ","NA","NE","NG","RE","RW","ST","SN","SC","SL","SO","ZA","SS","SD","TZ","TG","TN","UG","ZM","ZW"],AN:["AQ"],AS:["AF","AM","AZ","BH","BD","BT","BN","KH","CN","CY","GE","IN","ID","IR","IQ","IL","JP","JO","KZ","KW","KG","LA","LB","MY","MV","MN","MM","NP","KP","OM","PK","PS","PH","QA","RU","SA","SG","KR","LK","SY","TW","TJ","TH","TL","TR","TM","AE","UZ","VN","YE"],EU:["AL","AD","AT","BY","BE","BA","BG","HR","CZ","DK","EE","FI","FR","DE","GR","HU","IS","IE","IT","XK","LV","LI","LT","LU","MT","MD","MC","ME","NL","MK","NO","PL","PT","RO","RU","SM","RS","SK","SI","ES","SE","CH","UA","GB","VA"],NA:["AG","BS","BB","BZ","CA","CR","CU","DM","DO","SV","GD","GT","HT","HN","JM","MX","NI","PA","KN","LC","VC","TT","US"],OC:["AU","FJ","KI","MH","FM","NR","NZ","PW","PG","WS","SB","TO","TV","VU"],SA:["AR","BO","BR","CL","CO","EC","GY","PY","PE","SR","UY","VE"]},dr={AF:"Africa",AN:"Antarctica",AS:"Asia",EU:"Europe",NA:"N. America",OC:"Oceania",SA:"S. America"},hr={};for(let[s,t]of Object.entries(Wl))for(let e of t)hr[e]=s;function Mt(s){return Zl[s]||s}function Wt(s){return!s||s.length!==2?"":String.fromCodePoint(...s.toUpperCase().split("").map(t=>t.charCodeAt(0)+127397))}function zt(s){if(!s||s.indexOf("?")!==-1)return null;let t=new Date(s+"T12:00:00Z");return isNaN(t.getTime())?null:t}function Bs(s){let t=zt(s.date_entered),e=zt(s.date_left);return!t||!e?0:Math.max(Math.round((e.getTime()-t.getTime())/864e5),1)}function ur(s,t=new Date){let e=t.getTime(),i=null,n=-1/0;for(let o of s){let r=zt(o.date_entered);if(!(!r||r.getTime()>e)){if(o.date_left.trim()!==""){let a=zt(o.date_left);if(!a||a.getTime()n&&(i=o,n=r.getTime())}}return i}function fr(s){let t=p=>{var b,C,S,_,y,v,x,k;return{date_entered:(b=p.date_entered)!=null?b:"",date_left:(C=p.date_left)!=null?C:"",country:((S=p.country)!=null?S:"").trim().toUpperCase(),city:(_=p.city)!=null?_:"",visa_status:(y=p.visa_status)!=null?y:"",notes:(v=p.notes)!=null?v:"",source:((x=p.source)!=null?x:"").trim().toLowerCase(),resolved:(k=p.resolved)!=null?k:"",_src:p}},e=s.map(t).filter(p=>p.country),i=e.filter(p=>p.source==="confirmed"),n=e.filter(p=>p.source==="inferred"),o=e.filter(p=>p.source==="conflict"),r=[];for(let p of i){let b=zt(p.date_entered),C=zt(p.date_left);b&&C&&r.push([b.getTime(),C.getTime()])}let a=p=>{let b=zt(p.date_entered),C=zt(p.date_left);if(!b||!C)return!1;let S=b.getTime(),_=C.getTime();return r.some(([y,v])=>S<=v&&_>=y)},L=n.filter(p=>zt(p.date_entered)&&zt(p.date_left)&&!a(p)),l=new Set(i.map(p=>p.country)),c=new Set(n.map(p=>p.country)),d=new Set([...c].filter(p=>!l.has(p))),h=new Set([...l,...c]),u=new Map;for(let p of i)u.set(p.country,(u.get(p.country)||0)+Bs(p));let f=[...u.entries()].map(([p,b])=>({iso:p,days:b})).sort((p,b)=>b.days-p.days||Mt(p.iso).localeCompare(Mt(b.iso))),g=f.reduce((p,b)=>p+b.days,0),m=new Set;for(let p of l){let b=hr[p];b&&m.add(b)}return{confirmed:i,inferred:n,conflicts:o,inferredVisible:L,confRanges:r,confirmedCountries:l,inferredOnlyCountries:d,allCountries:h,countryDays:f,totalConfirmedDays:g,visitedContinents:m,worldPct:Math.round(l.size/Tn*100)}}var An=864e5;function pr(s){if(!s||s.indexOf("?")!==-1)return null;let t=Date.parse(s+"T00:00:00Z");return isNaN(t)?null:t}function jl(s,t,e,i){let n=Math.max(s,e),o=Math.min(t,i);return o<=n?0:Math.round((o-n)/An)}function Ul(s,t){var n;let e=s.window;if(e.type==="all-time")return{start:-1/0,end:1/0,label:"all time"};if(e.type==="calendar-year"){let o=new Date(t).getUTCFullYear();return{start:Date.UTC(o,0,1),end:Date.UTC(o+1,0,1),label:`in ${o}`}}let i=(n=e.days)!=null?n:180;return{start:t-i*An,end:t+An,label:`in last ${i} days`}}function gr(s,t,e=Date.now()){var c,d,h;let i=(c=s.scope.countries)!=null?c:s.scope.country?[s.scope.country]:[],n=new Set(i.map(u=>u.toUpperCase())),o=new Set(((h=(d=s.exempt)==null?void 0:d.visa_status)!=null?h:[]).map(u=>u.toLowerCase().trim())),r=Ul(s,e),a=0;for(let u of t){if(!n.has((u.country||"").toUpperCase())||o.has((u.visa_status||"").toLowerCase().trim()))continue;let f=pr(u.date_entered),g=pr(u.date_left);f===null||g===null||(a+=jl(f,g,r.start,r.end))}let L=s.threshold-a,l=a>=s.threshold?"over":a/s.threshold>=.8?"warn":"ok";return{rule:s,used:a,threshold:s.threshold,remaining:L,windowLabel:r.label,status:l}}var mr=["#c9a96e","#4a6fa5","#5ba06e","#a05b8a","#6ea0a0","#a0855b","#7a6ea0","#a06e6e","#6e8fa0","#a09e5b"],Yl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Gl(){let s=new Map,t=0;return e=>(s.has(e)||s.set(e,mr[t++%mr.length]),s.get(e))}function Kl(s){let t=document.body.createDiv({cls:"csv-tv-tooltip"}),e=null,i=(r,a)=>{let l=r+14,c=a+16,d=t.offsetWidth,h=t.offsetHeight;l+d+8>window.innerWidth&&(l=r-d-14),c+h+8>window.innerHeight&&(c=a-h-16),t.style.left=`${Math.max(8,l)}px`,t.style.top=`${Math.max(8,c)}px`},n=r=>{var l,c;let a=(c=(l=r.target)==null?void 0:l.closest("[data-tip]"))!=null?c:null,L=(a==null?void 0:a.getAttribute("data-tip"))||"";if(!a||!L){e&&(e=null,t.removeClass("is-on"));return}a!==e&&(e=a,t.setText(L),t.addClass("is-on")),i(r.clientX,r.clientY)},o=()=>{e=null,t.removeClass("is-on")};return s.addEventListener("pointermove",n),s.addEventListener("pointerleave",o),()=>{s.removeEventListener("pointermove",n),s.removeEventListener("pointerleave",o),t.remove()}}function Rn(s){let t=Bs(s);return t?`${t}d`:"\u2014"}function ds(s){return s||"\u2014"}function zs(s){return s.createDiv({cls:"csv-tv-table-wrap"}).createEl("table",{cls:"csv-tv-table"})}function $s(s,t,e,i){s.addClass("csv-tv-editable"),s.title="Click to edit";let n=()=>{s.empty(),s.setText(t[e]?t[e]:"\u2014")};n(),s.addEventListener("click",()=>{var r;if(s.querySelector("input"))return;s.empty();let o=yi(s,e,(r=t[e])!=null?r:"","csv-inline-input");o.focus(),o.type==="text"&&o.select(),o.addEventListener("blur",()=>{t[e]=o.value,i(),n()}),o.addEventListener("keydown",a=>{var L;a.key==="Enter"&&o.blur(),a.key==="Escape"&&(o.value=(L=t[e])!=null?L:"",o.blur())})})}async function br(s,t,e,i=()=>{},n=null,o=()=>{}){let r=fr(t),a=s.createDiv({cls:"csv-tv"});if(!r.confirmed.length&&!r.inferred.length){a.createDiv({cls:"csv-empty-state",text:"No travel rows found. Expected columns: country, date_entered, date_left, source."});return}o(Kl(a));let L=null,l=()=>{a.querySelectorAll(".country-path").forEach(u=>{let f=(u.getAttribute("data-iso")||"").toUpperCase();u.classList.toggle("cp-selected",!!L&&f===L)}),a.querySelectorAll(".csv-tv-seg").forEach(u=>{u.classList.toggle("is-dim",!!L&&u.getAttribute("data-iso")!==L)}),a.querySelectorAll("tr[data-iso]").forEach(u=>{u.classList.toggle("is-selected",!!L&&u.getAttribute("data-iso")===L)}),h.empty(),L&&(Ql(h,r,L,()=>c(null)),h.scrollIntoView({behavior:"smooth",block:"nearest"}))},c=u=>{L=u&&u!==L?u:null,l()};ql(a,r);let d=a.createDiv({cls:"csv-tv-mapwrap"});d.createDiv({cls:"csv-tv-map-loading",text:"Loading map\u2026"});let h=a.createDiv({cls:"csv-tv-detailwrap"});n&&n.length&&Jl(a,r.confirmed,n),tc(a,r,c),ec(a,r,c),sc(a,r,i);try{let u=await e();d.empty(),u?Xl(d,u,r,c):d.createDiv({cls:"csv-tv-map-loading",text:"World map asset not found (world-map.svg)."})}catch(u){d.empty(),d.createDiv({cls:"csv-tv-map-loading",text:"Couldn't load world map."})}}function ql(s,t){let e=s.createDiv({cls:"csv-tv-stats"}),i=(l,c,d="")=>{let h=e.createDiv({cls:"csv-tv-stat"});h.createDiv({cls:"csv-tv-stat-label",text:l}),h.createDiv({cls:"csv-tv-stat-value",text:c}),d&&h.createDiv({cls:"csv-tv-stat-sub",text:d})},n=Math.round(t.allCountries.size/Tn*100);i("Countries",String(t.confirmedCountries.size),`${t.worldPct}% of world`),i("Incl. photos",String(t.allCountries.size),`${n}% of world`),i("Continents",`${t.visitedContinents.size} / 7`,[...t.visitedContinents].map(l=>dr[l]||l).sort().join(", ")),i("Confirmed trips",String(t.confirmed.length)),i("Confirmed days",String(t.totalConfirmedDays));let o=new Set(t.confirmed.map(l=>l.city.trim().toLowerCase()).filter(Boolean));o.size&&i("Cities",String(o.size));let r=null,a=0;for(let l of t.confirmed){let c=Bs(l);c>a&&(a=c,r=l)}if(r){let l=r.date_entered.slice(0,4);i("Longest trip",`${a}d`,`${Wt(r.country)} ${Mt(r.country)}${l?` \xB7 ${l}`:""}`)}let L=ur(t.confirmed);if(L){let l=zt(L.date_entered),c=Math.max(1,Math.round((Date.now()-l.getTime())/864e5)+1),d=s.createDiv({cls:"csv-tv-now"});d.createSpan({cls:"csv-tv-now-loc",text:`\u{1F4CD} Currently in ${Wt(L.country)} ${Mt(L.country)}`}),d.createSpan({cls:"csv-tv-now-sub",text:` \u2014 since ${L.date_entered} (day ${c})${L.city?` \xB7 ${L.city}`:""}`})}}function Xl(s,t,e,i){let n=s.createDiv({cls:"csv-tv-map"}),o=new DOMParser().parseFromString(t,"image/svg+xml").documentElement;n.appendChild(o),n.querySelectorAll(".country-path").forEach(l=>{let c=(l.getAttribute("data-iso")||"").toUpperCase();if(l.classList.remove("cp-unvisited","cp-confirmed","cp-inferred"),c&&e.confirmedCountries.has(c)){l.classList.add("cp-confirmed");let d=e.countryDays.find(h=>h.iso===c);l.setAttr("aria-label",`${Mt(c)} \u2014 ${d&&d.days?d.days+"d confirmed":"confirmed"}`),l.setAttr("data-tip",`${Mt(c)}${d&&d.days?" \xB7 "+d.days+"d":""} \xB7 click for trips`)}else c&&e.inferredOnlyCountries.has(c)?(l.classList.add("cp-inferred"),l.setAttr("aria-label",`${Mt(c)} \u2014 photo evidence`),l.setAttr("data-tip",`${Mt(c)} \xB7 photo evidence \xB7 click for trips`)):c?(l.classList.add("cp-unvisited"),l.setAttr("data-tip",Mt(c))):l.classList.add("cp-unvisited");c&&l.addEventListener("click",()=>{e.allCountries.has(c)?i(c):i(null)})}),n.querySelectorAll(".country-path").forEach(l=>{try{let c=l.getBoundingClientRect();c.width&&c.height&&Math.max(c.width,c.height)<12&&l.classList.add("cp-tiny")}catch(c){}});let r=s.createDiv({cls:"csv-tv-map-legend"}),a=r.createSpan({cls:"csv-tv-leg"});a.createSpan({cls:"csv-tv-dot cp-confirmed"}),a.appendText(" Confirmed");let L=r.createSpan({cls:"csv-tv-leg"});L.createSpan({cls:"csv-tv-dot cp-inferred"}),L.appendText(" Photo evidence")}function Ql(s,t,e,i){var m,p;let n=s.createDiv({cls:"csv-tv-detail"}),o=n.createDiv({cls:"csv-tv-detail-head"});o.createSpan({cls:"csv-tv-detail-flag",text:Wt(e)});let r=o.createDiv({cls:"csv-tv-detail-titles"});r.createDiv({cls:"csv-tv-detail-name",text:Mt(e)});let a=t.confirmed.filter(b=>b.country===e),L=t.inferred.filter(b=>b.country===e),l=(p=(m=t.countryDays.find(b=>b.iso===e))==null?void 0:m.days)!=null?p:0,c=new Set([...a,...L].map(b=>b.city.trim()).filter(Boolean)),d=[];a.length&&d.push(`${a.length} confirmed trip${a.length===1?"":"s"}`),l&&d.push(`${l}d total`),L.length&&d.push(`${L.length} photo-inferred`),c.size&&d.push(`${c.size} cit${c.size===1?"y":"ies"}`),r.createDiv({cls:"csv-tv-detail-sub",text:d.join(" \xB7 ")}),o.createEl("button",{cls:"csv-tv-detail-close",text:"\u2715",title:"Close"}).addEventListener("click",i);let h=xi([...a.map(b=>({r:b,inf:!1,date_entered:b.date_entered})),...L.map(b=>({r:b,inf:!0,date_entered:b.date_entered}))]);if(!h.length)return;let u=zs(n),f=u.createEl("thead").createEl("tr");["","Entered","Left","Days","City","Visa"].forEach(b=>f.createEl("th",{text:b}));let g=u.createEl("tbody");for(let{r:b,inf:C}of h){let S=g.createEl("tr");S.createEl("td",{text:C?"\u{1F4F7}":"",cls:"csv-tv-flag",attr:C?{"data-tip":"Photo-inferred"}:{}}),S.createEl("td",{text:ds(b.date_entered)}),S.createEl("td",{text:ds(b.date_left)}),S.createEl("td",{text:Rn(b)}),S.createEl("td",{text:b.city}),S.createEl("td",{text:b.visa_status})}}function Jl(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Residency counters"});let i=s.createDiv({cls:"csv-tv-res-grid"});for(let n of e){let o=gr(n,t),r=i.createDiv({cls:`csv-tv-res-card csv-tv-res-${o.status}`});r.createDiv({cls:"csv-tv-res-label",text:n.label});let a=r.createDiv({cls:"csv-tv-res-nums"});a.createSpan({cls:"csv-tv-res-used",text:String(o.used)}),a.createSpan({cls:"csv-tv-res-thresh",text:` / ${o.threshold}`}),a.createSpan({cls:"csv-tv-res-window",text:` ${o.windowLabel}`});let L=r.createDiv({cls:"csv-tv-res-bar"});L.createDiv({cls:"csv-tv-res-fill"}).style.width=`${Math.min(100,Math.round(o.used/o.threshold*100))}%`;let l=o.status==="over"?n.onExceed?`Over \u2014 ${n.onExceed}`:"Limit reached":`${o.remaining} day${o.remaining===1?"":"s"} left`;r.createDiv({cls:"csv-tv-res-status",text:l}),n.note&&r.createDiv({cls:"csv-tv-res-note",text:n.note})}s.createDiv({cls:"csv-tv-res-disclaimer",text:"Indicators only \u2014 not legal or tax advice. Based on confirmed trips."})}function tc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Countries visited"});let i=zs(s),n=i.createEl("thead").createEl("tr");["","Country","Total days"].forEach(r=>n.createEl("th",{text:r}));let o=i.createEl("tbody");for(let{iso:r,days:a}of t.countryDays){let L=o.createEl("tr",{cls:"csv-tv-row-click",attr:{"data-iso":r}});L.createEl("td",{text:Wt(r),cls:"csv-tv-flag"}),L.createEl("td",{text:Mt(r)}),L.createEl("td",{text:a?`${a}d`:"\u2014"}),L.addEventListener("click",()=>e(r))}if(t.inferredOnlyCountries.size){let r=s.createDiv({cls:"csv-tv-photo-only"});r.createSpan({text:"\u{1F4F7} Photo evidence only: "}),r.createSpan({text:[...t.inferredOnlyCountries].sort().map(Wt).join(" ")})}}function ec(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Timeline"});let i=Gl(),n=[...t.confirmed.map(l=>({...l,_inf:!1})),...t.inferredVisible.map(l=>({...l,_inf:!0}))].filter(l=>l.date_entered&&l.date_left&&l.date_entered.indexOf("?")===-1),o=new Map;for(let l of n){let c=parseInt(l.date_entered.slice(0,4)),d=parseInt(l.date_left.slice(0,4));if(!(isNaN(c)||isNaN(d)))for(let h=c;h<=d;h++)o.has(h)||o.set(h,[]),o.get(h).push(l)}let r=[...o.keys()].sort((l,c)=>c-l),a=s.createDiv({cls:"csv-tv-timeline"});for(let l of r){let c=new Date(`${l}-01-01T12:00:00Z`).getTime(),d=new Date(`${l}-12-31T12:00:00Z`).getTime(),h=d-c,u=a.createDiv({cls:"csv-tv-tl-year"}),f=0,g=new Set;for(let C of o.get(l)){if(g.add(C.country),C._inf)continue;let S=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),c),_=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),d);S<=_&&(f+=Math.max(Math.round((_-S)/864e5)+1,1))}let m=u.createDiv({cls:"csv-tv-tl-label"});m.createSpan({text:String(l)}),m.createSpan({cls:"csv-tv-tl-sub",text:`${f?`${f}d \xB7 `:""}${g.size} ${g.size===1?"country":"countries"}`});let p=u.createDiv({cls:"csv-tv-month-row"});Yl.forEach(C=>p.createDiv({cls:"csv-tv-month-tick",text:C}));let b=u.createDiv({cls:"csv-tv-track"});for(let C of o.get(l)){let S=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),c),_=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),d);if(S>_)continue;let y=(S-c)/h*100,v=Math.max((_-S+864e5)/h*100,.5),x=i(C.country),k=b.createDiv({cls:`csv-tv-seg${C._inf?" csv-tv-seg-inf":""}`});k.style.left=`${y}%`,k.style.width=`${v}%`,C._inf?(k.style.borderColor=x,k.style.background=x+"22",k.style.color=x):k.style.background=x,k.setAttr("data-iso",C.country),k.setAttr("data-tip",`${Mt(C.country)} ${C.date_entered} \u2192 ${C.date_left} (${Bs(C)}d)${C.visa_status?" ["+C.visa_status+"]":""}${C._inf?" [photo]":""}`),k.addEventListener("click",()=>e(C.country)),v>4?k.createSpan({cls:"csv-tv-seg-lbl",text:`${Wt(C.country)} ${C.country}`}):v>2&&k.createSpan({cls:"csv-tv-seg-lbl",text:Wt(C.country)})}}a.createDiv({cls:"csv-tv-tl-legend"}).setText("Confirmed (solid) \xB7 photo inferred (outlined)")}function xi(s){return[...s].sort((t,e)=>!t.date_entered&&!e.date_entered?0:t.date_entered?e.date_entered?e.date_entered.localeCompare(t.date_entered):-1:1)}function sc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Confirmed trips"}),s.createDiv({cls:"csv-tv-edit-hint",text:"Dates, city, visa and notes are editable \u2014 click a cell. Edit country in Table view."});let i=zs(s),n=i.createEl("thead").createEl("tr");["","Country","Entered","Left","Duration","City","Visa","Notes"].forEach(r=>n.createEl("th",{text:r}));let o=i.createEl("tbody");for(let r of xi(t.confirmed)){let a=o.createEl("tr");a.createEl("td",{text:Wt(r.country),cls:"csv-tv-flag"}),a.createEl("td",{text:Mt(r.country)}),$s(a.createEl("td"),r._src,"date_entered",e),$s(a.createEl("td"),r._src,"date_left",e),a.createEl("td",{text:Rn(r)}),$s(a.createEl("td"),r._src,"city",e),$s(a.createEl("td"),r._src,"visa_status",e),$s(a.createEl("td"),r._src,"notes",e)}if(t.inferred.length){let r=s.createEl("details",{cls:"csv-tv-details"});r.createEl("summary",{text:`\u{1F4F7} Photo inferred trips (${t.inferred.length})`});let a=zs(r),L=a.createEl("thead").createEl("tr");["","Country","Entered","Left","Days","City"].forEach(c=>L.createEl("th",{text:c}));let l=a.createEl("tbody");for(let c of xi(t.inferred)){let d=l.createEl("tr");d.createEl("td",{text:Wt(c.country),cls:"csv-tv-flag"}),d.createEl("td",{text:Mt(c.country)}),d.createEl("td",{text:ds(c.date_entered)}),d.createEl("td",{text:ds(c.date_left)}),d.createEl("td",{text:Rn(c)}),d.createEl("td",{text:c.city})}}if(t.conflicts.length){let r=s.createEl("details",{cls:"csv-tv-details csv-tv-details-warn"});r.createEl("summary",{text:`\u26A0 ${t.conflicts.length} conflict(s) \u2014 photo evidence contradicts a confirmed entry`});let a=zs(r),L=a.createEl("thead").createEl("tr");["","Country (photos)","Dates","Detail"].forEach(c=>L.createEl("th",{text:c}));let l=a.createEl("tbody");for(let c of xi(t.conflicts)){let d=l.createEl("tr");d.createEl("td",{text:Wt(c.country),cls:"csv-tv-flag"}),d.createEl("td",{text:c.country}),d.createEl("td",{text:`${ds(c.date_entered)} \u2192 ${ds(c.date_left)}`}),d.createEl("td",{text:c.notes})}}}var At=require("obsidian"),Ci=class extends At.PluginSettingTab{constructor(t,e){super(t,e),this.plugin=e}display(){let{containerEl:t}=this;t.empty(),new At.Setting(t).setName("Default view mode").addDropdown(i=>i.addOption("kanban-genre","Kanban").addOption("table","Table").setValue(this.plugin.settings.defaultMode).onChange(async n=>{this.plugin.settings.defaultMode=n,await this.plugin.saveSettings()})),new At.Setting(t).setName("Status column name").addText(i=>i.setValue(this.plugin.settings.statusColumn).onChange(async n=>{this.plugin.settings.statusColumn=n,await this.plugin.saveSettings()})),new At.Setting(t).setName("Category/genre column name").addText(i=>i.setValue(this.plugin.settings.categoryColumn).onChange(async n=>{this.plugin.settings.categoryColumn=n,await this.plugin.saveSettings()})),new At.Setting(t).setName("Notes column names").setDesc("Comma-separated.").addText(i=>i.setValue(this.plugin.settings.notesColumns.join(", ")).onChange(async n=>{this.plugin.settings.notesColumns=n.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new At.Setting(t).setName("Select/dropdown columns").setDesc("Comma-separated column names that use a dropdown picker.").addText(i=>i.setValue(this.plugin.settings.selectColumns.join(", ")).onChange(async n=>{this.plugin.settings.selectColumns=n.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new At.Setting(t).setName("Notes subfolder").addText(i=>i.setPlaceholder("Notes").setValue(this.plugin.settings.notesSubfolder).onChange(async n=>{this.plugin.settings.notesSubfolder=n,await this.plugin.saveSettings()})),new At.Setting(t).setName("Reset column widths").addButton(i=>i.setButtonText("Reset").onClick(async()=>{this.plugin.settings.columnWidths={},await this.plugin.saveSettings(),new At.Notice("Column widths reset.")})),new At.Setting(t).setName("Residency counters (travel view)").setDesc("Show residency / tax day-gauges in the travel view.").addToggle(i=>i.setValue(this.plugin.settings.showResidency!==!1).onChange(async n=>{this.plugin.settings.showResidency=n,await this.plugin.saveSettings()})),new At.Setting(t).setName("Residency rules").setHeading(),t.createEl("p",{cls:"setting-item-description",text:"Each rule counts days in the listed countries within the window, minus exempt visa rows, against the threshold. Counts confirmed trips only. Indicators, not legal/tax advice."});let e=t.createDiv({cls:"csv-rr-wrap"});this.renderResidencyRules(e)}renderResidencyRules(t){var o;t.empty();let e=(o=this.plugin.settings.residencyRules)!=null?o:this.plugin.settings.residencyRules=[],i=()=>void this.plugin.saveSettings();e.forEach((r,a)=>{var p,b,C,S,_,y;let L=t.createDiv({cls:"csv-rr-card"}),l=L.createDiv({cls:"csv-rr-head"}),c=l.createEl("input",{cls:"csv-rr-label",type:"text",value:r.label});c.placeholder="Label (e.g. \u{1F1EA}\u{1F1FA} Schengen 90/180)",c.addEventListener("input",()=>{r.label=c.value,i()});let d=l.createEl("button",{cls:"csv-rr-del",text:"\u2715"});d.setAttr("aria-label","Remove rule"),d.addEventListener("click",()=>{(async()=>(e.splice(a,1),await this.plugin.saveSettings(),this.renderResidencyRules(t)))()});let h=L.createDiv({cls:"csv-rr-grid"}),u=(v,x,k,E="")=>{let M=h.createDiv({cls:"csv-rr-field"});M.createEl("label",{text:v});let D=M.createEl("input",{type:"text",value:x});E&&(D.placeholder=E),D.addEventListener("input",()=>{k(D.value),i()})},f=(p=r.scope.countries)!=null?p:r.scope.country?[r.scope.country]:[];u("Countries (ISO-2, comma)",f.join(", "),v=>{r.scope={countries:v.split(",").map(x=>x.trim().toUpperCase()).filter(Boolean)}},"US, GB");let g=h.createDiv({cls:"csv-rr-field"});g.createEl("label",{text:"Window"});let m=g.createEl("select");[["calendar-year","Calendar year"],["rolling","Rolling N days"],["all-time","All time"]].forEach(([v,x])=>{let k=m.createEl("option",{text:x,value:v});r.window.type===v&&(k.selected=!0)}),m.addEventListener("change",()=>{r.window={type:m.value,days:r.window.days},i(),this.renderResidencyRules(t)}),r.window.type==="rolling"&&u("Rolling days",String((b=r.window.days)!=null?b:180),v=>{let x=parseInt(v,10);r.window.days=isNaN(x)?void 0:x},"180"),u("Threshold (days)",String(r.threshold),v=>{let x=parseInt(v,10);r.threshold=isNaN(x)?0:x},"183"),u("Exempt visas (comma)",((S=(C=r.exempt)==null?void 0:C.visa_status)!=null?S:[]).join(", "),v=>{let x=v.split(",").map(k=>k.trim()).filter(Boolean);r.exempt=x.length?{visa_status:x}:void 0},"F-1, J-1"),u("On-exceed label",(_=r.onExceed)!=null?_:"",v=>{r.onExceed=v||void 0},"tax resident"),u("Note",(y=r.note)!=null?y:"",v=>{r.note=v||void 0},"optional caveat")}),t.createDiv({cls:"csv-rr-btns"}).createEl("button",{cls:"csv-rr-add",text:"+ add rule"}).addEventListener("click",()=>{(async()=>(e.push({label:"New rule",scope:{countries:[]},window:{type:"calendar-year"},threshold:183}),await this.plugin.saveSettings(),this.renderResidencyRules(t)))()})}};var be=require("obsidian"),vr=Ns(is());async function yr(s,t,e,i,n={}){var Z,B,G;let o=t.split(` -`).map(R=>R.trim()).filter(Boolean),r="";for(let R of o)if(R.startsWith("file:")){r=R.replace("file:","").trim();break}if(!r){e.createEl("p",{text:"Error: No file specified. Use: file: yourfile.csv",cls:"csv-add-error"});return}let a=s.vault.getAbstractFileByPath(i.sourcePath),L=(B=(Z=a==null?void 0:a.parent)==null?void 0:Z.path)!=null?B:"",l=Xt(r,L),c=s.vault.getAbstractFileByPath(l);if(!c||!(c instanceof be.TFile)){e.createEl("p",{text:`Error: File not found: ${l}`,cls:"csv-add-error"});return}let d=(G=n[l])!=null?G:{},h=[],u=[];try{let R=await s.vault.read(c),W=kt(R);h=W.headers,u=W.rows}catch(R){e.createEl("p",{text:`Error reading file: ${R instanceof Error?R.message:String(R)}`,cls:"csv-add-error"});return}if(!h.length){e.createEl("p",{text:"Error: No columns found in file",cls:"csv-add-error"});return}let f=R=>{let W=R.toLowerCase();if(["date","day","datum"].includes(W))return!0;let K=u.slice(0,5).map(T=>{var F;return(F=T[R])!=null?F:""});return K.length>0&&K.every(T=>/^\d{4}-\d{2}-\d{2}$/.test(T))},g=R=>{let W=R.toLowerCase();return["notes","note","comments","description","journal"].includes(W)},m=d.habitColumns?d.habitColumns.filter(R=>h.includes(R)):h.filter(R=>!f(R)&&as(u.map(W=>{var K;return((K=W[R])!=null?K:"").toLowerCase().trim()}))),p=h.filter(R=>f(R)),b=h.filter(R=>g(R)),C=h.filter(R=>!m.includes(R)&&!p.includes(R)&&!b.includes(R)),S=d.titleColumn?h.find(R=>R.toLowerCase()===d.titleColumn.toLowerCase()):h.find(R=>["title","name"].includes(R.toLowerCase())),_=e.createDiv({cls:"csv-add-form csv-add-compact"}),y=_.createEl("button",{cls:"csv-add-trigger is-hidden",text:"+ new entry"}),v=_.createDiv({cls:"csv-add-card"}),x=v.createDiv({cls:"csv-add-card-header"});x.createSpan({cls:"csv-add-card-title",text:"New entry"});let k=x.createEl("button",{cls:"csv-add-card-close",text:"\xD7"}),E=v.createDiv({cls:"csv-add-rows"}),M={},D={},A=(R,W)=>{let K=E.createDiv({cls:`csv-add-row csv-add-row-${W}`});return K.createSpan({cls:"csv-add-row-label",text:Dt(R)}),K};p.forEach(R=>{let K=A(R,"date").createEl("input",{cls:"csv-add-row-control",type:"date"});K.value=ge(),M[R]=K}),m.forEach(R=>{D[R]=!1;let K=A(R,"toggle").createEl("label",{cls:"csv-add-switch"}),T=K.createEl("input",{type:"checkbox",cls:"csv-add-switch-input"});K.createSpan({cls:"csv-add-switch-track"}),T.addEventListener("change",()=>{D[R]=T.checked}),M[R]=T}),C.forEach(R=>{let W=A(R,"field"),K=new Set(u.map(F=>{var H;return((H=F[R])!=null?H:"").trim()}).filter(Boolean));if(R!==S&&(d.categoricalColumns?d.categoricalColumns.includes(R):qt(K.size))){let F=W.createEl("select",{cls:"csv-add-row-control"});F.createEl("option",{text:"\u2014",value:""}),Array.from(K).sort().forEach(z=>F.createEl("option",{text:z,value:z})),F.createEl("option",{text:"+ custom",value:"__custom__"});let H=E.createDiv({cls:"csv-add-row csv-add-row-custom is-hidden"}),$=H.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:`Custom ${Dt(R).toLowerCase()}`});E.insertBefore(H,W.nextSibling),F.addEventListener("change",()=>{H.classList.toggle("is-hidden",F.value!=="__custom__"),F.value==="__custom__"&&$.focus()}),M[R]=F,M[`${R}__custom`]=$}else M[R]=W.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:Dt(R)})}),b.forEach(R=>{let W=E.createDiv({cls:"csv-add-row csv-add-row-notes"});W.createSpan({cls:"csv-add-row-label",text:Dt(R)}),M[R]=W.createEl("textarea",{cls:"csv-add-row-textarea",placeholder:"Optional notes\u2026"})});let N=v.createEl("button",{text:"Add",cls:"csv-add-submit"}),I=x.querySelector(".csv-add-card-title"),P=()=>{if(!p.length)return;let R=M[p[0]];if(!R)return;let W=R.value,K=u.find(T=>T[p[0]]===W);I&&I.setText(K?`Updating ${W}`:"New entry"),v.classList.toggle("is-updating",!!K),N.setText(K?"Update":"Add"),m.forEach(T=>{var $;let F=M[T];if(!F)return;let H=Ls(($=K==null?void 0:K[T])!=null?$:"");F.checked=H,D[T]=H}),[...C,...b].forEach(T=>{var $;let F=M[T];if(!F)return;let H=($=K==null?void 0:K[T])!=null?$:"";if(F instanceof HTMLSelectElement){let z=Array.from(F.options).find(X=>X.value===H),V=M[`${T}__custom`],j=V==null?void 0:V.closest(".csv-add-row-custom");z?(F.value=H,j&&j.classList.add("is-hidden"),V&&(V.value="")):H?(F.value="__custom__",V&&(V.value=H),j&&j.classList.remove("is-hidden")):(F.value="",j&&j.classList.add("is-hidden"),V&&(V.value=""))}else F.instanceOf(HTMLTextAreaElement),F.value=H})};if(P(),p.length){let R=M[p[0]];R==null||R.addEventListener("change",P)}let w=()=>{v.classList.remove("is-hidden"),y.classList.add("is-hidden");let R=v.querySelector(".csv-add-row-control");R==null||R.focus()},U=()=>{v.classList.add("is-hidden"),y.classList.remove("is-hidden")};y.addEventListener("click",w),k.addEventListener("click",U);let O=async()=>{let R={};h.forEach(z=>{var V,j,X,q;m.includes(z)?R[z]=D[z]?"1":"0":M[z]instanceof HTMLSelectElement&&M[z].value==="__custom__"?R[z]=(j=(V=M[`${z}__custom`])==null?void 0:V.value)!=null?j:"":M[z]instanceof HTMLTextAreaElement?R[z]=M[z].value:R[z]=(q=(X=M[z])==null?void 0:X.value)!=null?q:""});let W=p.length>0&&p.some(z=>{var V;return((V=R[z])!=null?V:"").trim()}),K=[...C,...b].some(z=>{var V;return((V=R[z])!=null?V:"").trim()}),T=m.some(z=>D[z]);if(!W&&!K&&!T){new be.Notice("Please fill at least one field");return}let F=[];try{let z=await s.vault.read(c);F=kt(z).rows}catch(z){new be.Notice(`Error reading file: ${z instanceof Error?z.message:String(z)}`);return}let H=!1,$=-1;if(p.length>0){let z=p[0],V=R[z];if($=F.findIndex(j=>j[z]===V),$>=0){H=!0;let j=F[$];h.forEach(X=>{var q;(m.includes(X)||((q=R[X])!=null?q:"").trim())&&(j[X]=R[X])})}else F.push(R)}else F.push(R);try{let z=vr.default.unparse(F,{columns:h});await s.vault.modify(c,z),new be.Notice(H?`Updated entry for ${R[p[0]]||""}`:`Added entry to ${c.basename}`),u.length=0,u.push(...F),p.length>0?P():(m.forEach(V=>{D[V]=!1;let j=M[V];j&&(j.checked=!1)}),[...C,...b].forEach(V=>{let j=M[V];j instanceof HTMLSelectElement?j.selectedIndex=0:(j.instanceOf(HTMLTextAreaElement)||j)&&(j.value="");let X=M[`${V}__custom`];if(X){X.value="";let q=X.closest(".csv-add-row-custom");q&&q.classList.add("is-hidden")}})),window.setTimeout(()=>{(async()=>{let V=s.vault.getAbstractFileByPath(i.sourcePath);V instanceof be.TFile&&await s.workspace.getLeaf(!1).openFile(V,{state:{mode:"preview"}})})()},300)}catch(z){new be.Notice(`Error saving: ${z instanceof Error?z.message:String(z)}`)}};N.addEventListener("click",()=>{O()})}function _i(s,t){let e=s.getFilteredRows();s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${e.length} of ${s.rows.length} entries`});let n=t.createDiv({cls:"csv-table-wrapper"}).createEl("table",{cls:"csv-table"}),o=n.createEl("thead").createEl("tr");s.headers.forEach(L=>{let l=o.createEl("th");l.setText(L),l.addClass("csv-th-sortable"),s.tableSortCol===L&&l.createSpan({cls:"csv-th-sort-indicator",text:s.tableSortDir==="asc"?" \u25B2":" \u25BC"}),l.title="Click to sort",l.addEventListener("click",f=>{f.target.closest(".csv-col-resize-handle")||(s.tableSortCol!==L?(s.tableSortCol=L,s.tableSortDir="asc"):s.tableSortDir==="asc"?s.tableSortDir="desc":s.tableSortCol=null,s.renderView())});let c=s.settings.columnWidths[L];c&&(l.style.width=c+"px");let d=l.createDiv({cls:"csv-col-resize-handle"}),h=0,u=0;d.addEventListener("pointerdown",f=>{f.preventDefault(),f.stopPropagation(),d.setPointerCapture(f.pointerId),h=f.clientX,u=l.offsetWidth;let g=p=>{l.style.width=Math.max(60,u+p.clientX-h)+"px"},m=p=>{s.settings.columnWidths[L]=Math.max(60,u+p.clientX-h),d.removeEventListener("pointermove",g),d.removeEventListener("pointerup",m),s.persistSettings()};d.addEventListener("pointermove",g),d.addEventListener("pointerup",m)})}),o.createEl("th",{text:""});let r=matchMedia("(pointer: coarse)").matches,a=n.createEl("tbody");e.forEach(L=>{let l=a.createEl("tr");l.addEventListener("contextmenu",h=>s.openRowContextMenu(L,h)),s.headers.forEach(h=>{var f,g;let u=l.createEl("td");if(s.isNotesCol(h)){u.addClass("csv-table-notes-cell");let m=((f=L[h])!=null?f:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").split(` -`).filter(C=>C.trim()).slice(0,3).join(" \xB7 "),p=m?m.slice(0,200)+(m.length>200?"\u2026":""):"+ Add note",b=u.createSpan({text:p});m||b.addClass("csv-table-notes-empty"),u.title="Click to open note",u.addEventListener("click",C=>{C.stopPropagation(),s.openNoteExpander(L,h)})}else if(s.isSelectCol(h))s.renderSelectField(u,L,h);else{let m=(g=L[h])!=null?g:"";u.setText(m),m.length>80&&(u.title=m),Be(s,u,L,h)}});let c=l.createEl("td",{cls:"csv-table-action"}),d=s.notesFileExists(L);c.createEl("button",{cls:`csv-table-notes-btn ${d?"exists":""}`,text:d?"\u{1F4C4}":"\u271A",title:d?"Open notes":"Create notes"}).addEventListener("click",()=>void s.openOrCreateNotes(L)),c.createEl("button",{cls:"csv-table-del-btn",text:"\u2715",title:"Delete row (undo available)"}).addEventListener("click",()=>s.deleteWithUndo(L))}),r||window.requestAnimationFrame(()=>{a.querySelectorAll("td:not(.csv-table-notes-cell):not(.csv-table-action)").forEach(L=>{L.scrollHeight>L.clientHeight+1&&L.addClass("csv-cell--clipped")})})}function Be(s,t,e,i){t.addEventListener("click",n=>{var d,h;if(t.querySelector("input"))return;t.empty();let o=(d=s.fileCfg.dateColumns)==null?void 0:d.includes(i),r=((h=e[i])!=null?h:"").trim(),a=o||Et(i)&&(r===""||mi.test(r)),L=a?r.slice(0,10):r,l=t.createEl("input",{cls:"csv-inline-input",value:L,type:a?"date":"text"});l.focus(),a||l.select(),l.addEventListener("click",u=>u.stopPropagation());let c=!1;l.addEventListener("blur",()=>{var u;!c&&l.value!==L&&(e[i]=l.value,s.scheduleSave()),t.empty(),t.setText(((u=e[i])!=null?u:"")||"\u2014")}),l.addEventListener("keydown",u=>{u.key==="Enter"&&l.blur(),u.key==="Escape"&&(c=!0,l.blur())})})}function Si(s){return!!(s.getCategoryCol()||s.getStatusCol()||xr(s)||s.authorKey())}function xr(s){return s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"])}function Ws(s){var n;let t=(s!=null?s:"").trim();if(!t)return null;let e=((n=t.match(/★/g))!=null?n:[]).length;if(e>0)return e;let i=parseFloat(t);return isNaN(i)||i<=0?null:Math.min(5,i)}var Cr=["watched","read","finished","completed","done","yes","seen"],_r=["watching","reading","in progress","in-progress"],ic=["dropped","abandoned","dnf"];function nc(s){let t=s.toLowerCase();return Cr.includes(t)?"is-done":_r.includes(t)?"is-progress":ic.includes(t)?"is-dropped":""}function Hs(s,t){let e=new Map;return s.forEach(i=>t(i).forEach(n=>{var o;return e.set(n,((o=e.get(n))!=null?o:0)+1)})),e}function Zs(s,t,e,i){if(!e.length)return;let n=s.createDiv({cls:"csv-stats-section"});n.createDiv({cls:"csv-stats-section-title",text:t});let o=Math.max(...e.map(r=>r.count));e.forEach(r=>{var d;let a=n.createDiv({cls:"csv-stats-bar-row"});a.createDiv({cls:"csv-stats-bar-label",text:r.label,attr:{title:r.label}});let l=a.createDiv({cls:"csv-stats-bar-track"}).createDiv({cls:`csv-stats-bar-fill ${(d=r.cls)!=null?d:""}`});l.style.width=`${Math.max(2,Math.round(r.count/o*100))}%`;let c=i>0?Math.round(r.count/i*100):0;a.createDiv({cls:"csv-stats-bar-count",text:`${r.count} \xB7 ${c}%`}),r.onClick&&(a.addClass("is-clickable"),a.title=`Show "${r.label}" in the library`,a.addEventListener("click",r.onClick))})}function Sr(s,t){let e=s.getFilteredRows();if(s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Stats over ${e.length} of ${s.rows.length} entries`}),!e.length){t.createEl("p",{text:"No entries to chart.",cls:"csv-empty-state"});return}let i=t.createDiv({cls:"csv-stats-wrap"}),n=s.getStatusCol(),o=s.getCategoryCol(),r=xr(s),a=s.authorKey(),L=s.resolveCol(["Year","year"]),l=i.createDiv({cls:"csv-stats-overview"}),c=(h,u)=>{let f=l.createDiv({cls:"csv-stats-chip"});f.createDiv({cls:"csv-stats-chip-value",text:h}),f.createDiv({cls:"csv-stats-chip-label",text:u})};if(c(String(e.length),"entries"),n){let h=e.filter(f=>{var g;return Cr.includes(((g=f[n])!=null?g:"").toLowerCase().trim())}).length;h>0&&c(`${h} \xB7 ${Math.round(h/e.length*100)}%`,"done");let u=e.filter(f=>{var g;return _r.includes(((g=f[n])!=null?g:"").toLowerCase().trim())}).length;u>0&&c(String(u),"in progress")}if(o){let h=Hs(e,u=>{var f;return((f=u[o])!=null?f:"").split(",").map(g=>g.trim()).filter(Boolean)});h.size>0&&c(String(h.size),o.toLowerCase()==="genre"||o.toLowerCase()==="genres"?"genres":"categories")}if(r){let h=e.map(u=>Ws(u[r])).filter(u=>u!==null);if(h.length){let u=h.reduce((f,g)=>f+g,0)/h.length;c(`\u2605 ${u.toFixed(1)}`,`avg of ${h.length} rated`)}}let d=(h,u)=>{s.libraryStatusFilter=h!=null?h:"all",s.libraryGenreFilter=u!=null?u:"all",s.mode="library",s.renderView()};if(n){let h=Hs(e,f=>{var m;let g=((m=f[n])!=null?m:"").trim();return g?[g]:[]}),u=Array.from(h.entries()).sort((f,g)=>g[1]-f[1]).map(([f,g])=>({label:f,count:g,cls:nc(f),onClick:o?()=>d(f,null):void 0}));Zs(i,`By ${n.toLowerCase()}`,u,e.length)}if(o){let h=Hs(e,f=>{var g;return((g=f[o])!=null?g:"").split(",").map(m=>m.trim()).filter(Boolean)}),u=Array.from(h.entries()).sort((f,g)=>g[1]-f[1]||f[0].localeCompare(g[0])).slice(0,12).map(([f,g])=>({label:f,count:g,onClick:()=>d(null,f)}));Zs(i,`By ${o.toLowerCase()}`,u,e.length)}if(r){let h=new Map,u=0;if(e.forEach(f=>{var p;let g=Ws(f[r]);if(g===null)return;let m=Math.min(5,Math.max(1,Math.round(g)));h.set(m,((p=h.get(m))!=null?p:0)+1),u++}),u>0){let f=[5,4,3,2,1].filter(g=>{var m;return((m=h.get(g))!=null?m:0)>0}).map(g=>({label:"\u2605".repeat(g),count:h.get(g),cls:"is-rating"}));Zs(i,"Ratings",f,u)}}if(L){let h=Hs(e,u=>{var g;let f=((g=u[L])!=null?g:"").match(/\d{4}/);return f?[f[0]]:[]});if(h.size>1){let u=Array.from(h.entries()).sort((f,g)=>f[0].localeCompare(g[0])).map(([f,g])=>({label:f,count:g}));Zs(i,"By year",u,e.length)}}if(a){let h=Hs(e,f=>{var m;let g=((m=f[a])!=null?m:"").trim();return g?[g]:[]}),u=Array.from(h.entries()).filter(([,f])=>f>1);if(u.length>=2){let f=u.sort((g,m)=>m[1]-g[1]||g[0].localeCompare(m[0])).slice(0,8).map(([g,m])=>({label:g,count:m}));Zs(i,`Top ${a.toLowerCase()}s`,f,e.length)}}}function Rt(s){let t=s.fileCfg.kanbanGroupCol;if(t&&s.headers.includes(t))return t;let e=s.getCategoryCol();if(e)return e;let i=new Set;s.headers.forEach(r=>{s.isNotesCol(r)&&i.add(r)});let n=s.getDateCol();n&&i.add(n);let o=s.titleKey();return o&&i.add(o),Lr(s.headers,s.rows,i)}function ki(s,t){let e=Rt(s);if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let i=s.getCategoryCol(),n=s.getStatusCol(),o=n===e?null:n,r=s.getFilteredRows();s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${r.length} of ${s.rows.length} entries`});let a=t.createDiv({cls:"csv-kanban-groupbar"});a.createSpan({cls:"csv-kanban-groupbar-label",text:"Group by"});let L=a.createEl("select",{cls:"csv-library-filter-select"});s.headers.filter(m=>!s.isNotesCol(m)).forEach(m=>{let p=L.createEl("option",{text:m===i?`${m} (default)`:m,value:m});m===e&&(p.selected=!0)}),L.addEventListener("change",()=>{let m=s.fileCfg;m.kanbanGroupCol=L.value===i?void 0:L.value,s.saveFileCfg(m),s.renderView(!0)});let l=rr(e,r.map(m=>{var p;return(p=m[e])!=null?p:""})),c=m=>{var C;let p=(C=m[e])!=null?C:"",b;if(l){let S=ar(p);b=S?[S]:[]}else b=p.split(",").map(S=>S.trim()).filter(Boolean);return b.length||(b=["\u2014"]),b},d=new Set;r.forEach(m=>c(m).forEach(p=>d.add(p)));let h=Array.from(d).sort();if(!h.length){let m=t.createDiv({cls:"csv-empty-state"});m.createEl("p",{text:s.searchQuery?"No matching entries found.":`No "${e}" values found.`}),s.searchQuery&&m.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear search"}).addEventListener("click",()=>{s.searchQuery="",s.renderView()});return}let u=["In progress","Finished","Not started"],f=o?Array.from(new Set([...u,...r.map(m=>{var p;return(p=m[o])!=null?p:""}).filter(Boolean)])).filter(m=>r.some(p=>{var b;return((b=p[o])!=null?b:"")==m})):[],g=t.createDiv({cls:"csv-kanban-board"});h.forEach(m=>{let p=r.filter(_=>c(_).includes(m));if(!p.length)return;let b=g.createDiv({cls:"csv-kanban-col"}),C=b.createDiv({cls:"csv-kanban-col-header"});C.createDiv({cls:"csv-kanban-col-title",text:m}),C.createDiv({cls:"csv-kanban-col-count",text:String(p.length)});let S=b.createDiv({cls:"csv-kanban-col-body"});if(o&&f.length){f.forEach(v=>{let x=p.filter(E=>{var M;return((M=E[o])!=null?M:"")===v});if(!x.length)return;let k=S.createDiv({cls:"csv-kanban-status-group"});k.createDiv({cls:`csv-kanban-status-label status-${v.toLowerCase().replace(/\s+/g,"-")}`,text:v}),x.forEach(E=>Pn(s,k,E,o,e))});let _=new Set(f),y=p.filter(v=>{var x;return!_.has((x=v[o])!=null?x:"")});if(y.length){let v=S.createDiv({cls:"csv-kanban-status-group"});v.createDiv({cls:"csv-kanban-status-label",text:"\u2014"}),y.forEach(x=>Pn(s,v,x,o,e))}}else p.forEach(_=>Pn(s,S,_,o,e))})}function Pn(s,t,e,i,n){var x,k,E,M,D,A,N,I;let o=t.createDiv({cls:"csv-kanban-card"}),r=s.getNotesCol(),a=(k=(x=s.getImageCol)==null?void 0:x.call(s))!=null?k:null;if(a){let P=gi(s.app,(E=e[a])!=null?E:"",(D=(M=s.file)==null?void 0:M.path)!=null?D:"");if(P){let w=o.createEl("img",{cls:"csv-kanban-card-img",attr:{src:P,loading:"lazy",alt:""}});w.addEventListener("error",()=>w.remove())}}let L=o.createDiv({cls:"csv-kanban-card-title-row"});L.createDiv({cls:`csv-kanban-card-title ${(A=s.isHighlighted)!=null&&A.call(s,e)?"csv-title-highlight":""}`,text:s.getTitle(e)}).addEventListener("click",P=>{P.stopPropagation(),s.openNoteExpander(e,r!=null?r:"")});let c=s.notesFileExists(e);L.createEl("button",{cls:`csv-kanban-notes-icon ${c?"exists":""}`,text:c?"\u{1F4C4}":"+",title:c?"Open notes file":"Create notes file"}).addEventListener("click",P=>{P.stopPropagation(),s.openOrCreateNotes(e)});let h=s.getSubtitle(e);h&&o.createDiv({cls:"csv-kanban-card-sub",text:h});let u=s.titleKey(),f=s.authorKey(),g=new Set([i,u,f,n].filter(Boolean)),m=o.createDiv({cls:"csv-kanban-card-meta"});((N=s.fileCfg.cardFields)!=null?N:s.headers).forEach(P=>{if(!s.headers.includes(P)||g.has(P)||s.isNotesCol(P))return;let w=m.createDiv({cls:"csv-kanban-chip"});if(w.createSpan({cls:"csv-chip-label",text:P+": "}),s.isSelectCol(P)){let U=w.createSpan({cls:`csv-chip-value csv-chip-select${e[P]?"":" csv-chip-value--empty"}`,text:e[P]||"\u2014"});U.addEventListener("click",O=>{O.stopPropagation(),$t(U,e[P],s.getColumnValues(P),Z=>{e[P]=Z,U.setText(Z||"\u2014"),U.classList.toggle("csv-chip-value--empty",!Z),s.scheduleSave()},s.contentEl,{multi:vt(P)})})}else{let U=e[P]?e[P].length>40?e[P].slice(0,38)+"\u2026":e[P]:"\u2014",O=w.createSpan({cls:`csv-chip-value${e[P]?"":" csv-chip-value--empty"}`,text:U});e[P]&&e[P].length>40&&(O.title=e[P])}});let b=s.getNotesCol(),C=!!(b&&((I=e[b])!=null&&I.trim())),S=o.createDiv({cls:"csv-kanban-notes-preview"});if(C&&b){let P=e[b].replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();S.setText(P.slice(0,120)+(P.length>120?"\u2026":"")),S.title="Click to edit"}else S.addClass("csv-kanban-notes-preview--empty"),b&&S.setText("+ add note");let _=o.createDiv({cls:"csv-kanban-notes-editor is-hidden"}),y=()=>{var R,W,K;let P=s.contentEl.querySelector(".csv-content-area"),w=(R=P==null?void 0:P.scrollLeft)!=null?R:0,U=(W=P==null?void 0:P.scrollTop)!=null?W:0;S.classList.add("is-hidden"),_.classList.remove("is-hidden"),_.empty();let O=_.createEl("textarea",{cls:"csv-notes-textarea"});O.value=(K=b?e[b]:"")!=null?K:"",O.addEventListener("click",T=>T.stopPropagation()),O.addEventListener("mousedown",T=>T.stopPropagation()),O.addEventListener("input",()=>{O.style.removeProperty("height"),O.style.height=O.scrollHeight+"px"});let Z=O.value,B=!1,G=T=>{B||(B=!0,v(T,P,w,U))};O.addEventListener("keydown",T=>{T.key==="Escape"&&G(Z)}),O.addEventListener("blur",()=>G(O.value)),O.focus({preventScroll:!0}),O.setSelectionRange(0,0),O.scrollTop=0,window.requestAnimationFrame(()=>{O.style.removeProperty("height"),O.style.height=Math.max(120,O.scrollHeight)+"px"})},v=(P,w,U,O)=>{var Z;if(b&&P!==((Z=e[b])!=null?Z:"")&&(e[b]=P,s.scheduleSave()),_.classList.add("is-hidden"),S.classList.remove("is-hidden"),P.trim()){let B=P.replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();S.setText(B.slice(0,120)+(B.length>120?"\u2026":"")),S.removeClass("csv-kanban-notes-preview--empty"),S.title="Click to edit"}else S.addClass("csv-kanban-notes-preview--empty"),S.setText(b?"+ add note":""),S.removeAttribute("title");w&&(w.scrollLeft=U,w.scrollTop=O,window.requestAnimationFrame(()=>{w.scrollLeft=U,w.scrollTop=O,window.requestAnimationFrame(()=>{w.scrollLeft=U,w.scrollTop=O})}),window.setTimeout(()=>{w.scrollLeft=U,w.scrollTop=O},50))};S.addEventListener("click",P=>{if(P.stopPropagation(),b&&matchMedia("(pointer: coarse)").matches){s.openNoteExpander(e,b);return}y()}),o.addEventListener("contextmenu",P=>s.openRowContextMenu(e,P))}function Ei(s,t){var x,k;let e=Rt(s),i=s.getStatusCol(),n=(x=s.titleKey())!=null?x:s.headers[0];if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let o=new Set;s.rows.forEach(E=>{var D;((D=E[e])!=null?D:"").split(",").map(A=>A.trim()).filter(Boolean).forEach(A=>o.add(A))});let r=new Set;i&&s.rows.forEach(E=>{var D;let M=((D=E[i])!=null?D:"").trim();M&&r.add(M)});let a=t.createDiv({cls:"csv-library-filters"}),L=a.createEl("select",{cls:"csv-library-filter-select"});L.createEl("option",{text:"All",value:"all"});let l=["watched","read","finished","completed","done","yes","seen"],c=["watching","reading","in progress","in-progress"],d=Array.from(r).some(E=>l.includes(E.toLowerCase())),h=Array.from(r).some(E=>c.includes(E.toLowerCase()));(d||h)&&(L.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),d&&L.createEl("option",{text:"\u2713 done",value:"__done__"}),h&&L.createEl("option",{text:"\u25D0 in progress",value:"__inprogress__"}),L.createEl("option",{text:"\u25CB not started",value:"__notstarted__"})),r.size>0&&(L.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),Array.from(r).sort().forEach(E=>{L.createEl("option",{text:E,value:E})})),L.value=s.libraryStatusFilter;let u=a.createEl("select",{cls:"csv-library-filter-select"});u.createEl("option",{text:"All genres",value:"all"}),Array.from(o).sort().forEach(E=>{u.createEl("option",{text:E,value:E})}),u.value=s.libraryGenreFilter;let f=s.resolveCol(["Year","year","Date","date"]),g=s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"]),m=s.resolveCol(["Theme","theme","Tags","tags","Tag","tag","Mood","mood"]),p=(k=s.fileCfg.librarySort)!=null?k:"status",b=a.createEl("select",{cls:"csv-library-filter-select"}),C=[["status","Sort: Status"],["title","Sort: Title"]];g&&C.push(["rating","Sort: Rating"]),f&&C.push(["year","Sort: Year"]),C.forEach(([E,M])=>{let D=b.createEl("option",{text:M,value:E});E===p&&(D.selected=!0)}),b.addEventListener("change",()=>{let E=s.fileCfg;E.librarySort=b.value==="status"?void 0:b.value,s.saveFileCfg(E),s.renderView(!0)});let S=()=>{s.libraryStatusFilter=L.value,s.libraryGenreFilter=u.value,s.renderView(!0)};L.addEventListener("change",S),u.addEventListener("change",S);let _=s.rows.filter(E=>{var M,D;if(s.libraryStatusFilter!=="all"&&i){let A=((M=E[i])!=null?M:"").toLowerCase();if(s.libraryStatusFilter==="__done__"){if(!l.includes(A))return!1}else if(s.libraryStatusFilter==="__inprogress__"){if(!c.includes(A))return!1}else if(s.libraryStatusFilter==="__notstarted__"){if(l.includes(A)||c.includes(A))return!1}else if(A!==s.libraryStatusFilter.toLowerCase())return!1}if(s.libraryGenreFilter!=="all"&&!((D=E[e])!=null?D:"").split(",").map(N=>N.trim().toLowerCase()).includes(s.libraryGenreFilter.toLowerCase()))return!1;if(s.searchQuery.trim()){let A=s.searchQuery.toLowerCase().trim();if(!s.headers.some(N=>{var I;return((I=E[N])!=null?I:"").toLowerCase().includes(A)}))return!1}return!0});(s.libraryStatusFilter!=="all"||s.libraryGenreFilter!=="all"||s.searchQuery.trim())&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${_.length} of ${s.rows.length} entries`});let y={};_.forEach(E=>{var D;let M=s.libraryGenreFilter!=="all"?[s.libraryGenreFilter]:((D=E[e])!=null?D:"Uncategorized").split(",").map(A=>A.trim()).filter(Boolean);M.length===0&&M.push("Uncategorized"),M.forEach(A=>{y[A]||(y[A]=[]),y[A].push(E)})});let v=t.createDiv({cls:"csv-library-sections"});if(Object.keys(y).sort().forEach(E=>{var B,G,R,W,K;let M=y[E],D=v.createEl("details",{cls:"csv-library-section"}),A=E.toLowerCase(),N=((B=s.fileCfg.collapsedGroups)!=null?B:[]).map(T=>T.toLowerCase());D.open=!((G=s.collapsedGroups)!=null&&G.has(A)||N.includes(A)),D.addEventListener("toggle",()=>{var z;let T=s.fileCfg,F=((z=T.collapsedGroups)!=null?z:[]).map(V=>V.toLowerCase()),H=new Set(F);D.open?H.delete(A):H.add(A);let $=Array.from(H);$.length===F.length&&$.every(V=>F.includes(V))||(T.collapsedGroups=$,s.saveFileCfg(T))});let I=D.createEl("summary",{cls:"csv-library-section-header"});I.createSpan({cls:"csv-library-arrow",text:"\u25B6"}),I.createSpan({text:` ${E} `}),I.createSpan({cls:"csv-library-count",text:String(M.length)});let P=D.createDiv({cls:"csv-library-grid"}),w=(T,F)=>{var H,$;return((H=T[n])!=null?H:"").localeCompare(($=F[n])!=null?$:"")},U=(T,F)=>T===null&&F===null?0:T===null?1:F===null?-1:F-T;M.sort((T,F)=>{var H,$,z,V;if(p==="title")return w(T,F);if(p==="rating"&&g)return U(Ws((H=T[g])!=null?H:""),Ws(($=F[g])!=null?$:""))||w(T,F);if(p==="year"&&f){let j=X=>{var nt;let q=((nt=X[f])!=null?nt:"").match(/\d{4}/);return q?parseInt(q[0],10):null};return U(j(T),j(F))||w(T,F)}if(i){let j=((z=T[i])!=null?z:"").toLowerCase(),X=((V=F[i])!=null?V:"").toLowerCase(),q=l.includes(j),nt=l.includes(X);if(q!==nt)return q?-1:1;let Q=c.includes(j),et=c.includes(X);if(Q!==et)return Q?-1:1}return w(T,F)});let O=(R=s.fileCfg.cardFields)!=null?R:s.headers,Z=(K=(W=s.getImageCol)==null?void 0:W.call(s))!=null?K:null;M.forEach(T=>{var V,j,X,q,nt,Q,et,J;let F=P.createDiv({cls:"csv-library-card"});if(Z){let ot=gi(s.app,(V=T[Z])!=null?V:"",(X=(j=s.file)==null?void 0:j.path)!=null?X:"");if(ot){let lt=F.createEl("img",{cls:"csv-library-card-img",attr:{src:ot,loading:"lazy",alt:""}});lt.addEventListener("error",()=>lt.remove())}}let H=F.createDiv({cls:`csv-library-card-title ${(q=s.isHighlighted)!=null&&q.call(s,T)?"csv-title-highlight":""}`});if(i){let ot=((nt=T[i])!=null?nt:"").toLowerCase();l.includes(ot)&&H.createSpan({cls:"csv-library-done-dot"})}H.createSpan({text:(Q=T[n])!=null?Q:"Untitled"});let $=[],z=[];for(let ot of O){if(!ot)continue;let lt=String((et=T[ot])!=null?et:"").trim();if(lt)if(ot===g){let Bt=or(lt,ot);Bt&&F.createDiv({cls:"csv-library-card-rating",text:Bt})}else if(ot===m)z.push(...lt.split(",").map(Bt=>Bt.trim()).filter(Boolean));else if(ot===f){let Bt=lt.match(/\d{4}/);$.push(Bt?Bt[0]:lt)}else $.push(lt)}if($.length&&F.createDiv({cls:"csv-library-card-meta",text:$.join(" \xB7 ")}),s.libraryGenreFilter!=="all"){let ot=((J=T[e])!=null?J:"").split(",").map(lt=>lt.trim()).filter(lt=>lt&<.toLowerCase()!==s.libraryGenreFilter.toLowerCase());z.push(...ot)}if(z.length){let ot=F.createDiv({cls:"csv-library-card-tags"});z.slice(0,3).forEach(lt=>{ot.createSpan({cls:"csv-library-card-tag",text:lt})})}F.addEventListener("click",()=>{var ot;s.openNoteExpander(T,(ot=s.getNotesCol())!=null?ot:"")}),F.addEventListener("contextmenu",ot=>s.openRowContextMenu(T,ot))})}),Object.keys(y).length===0){let E=v.createDiv({cls:"csv-empty-state"});E.createEl("p",{text:"No entries match your filters."}),E.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.libraryStatusFilter="all",s.libraryGenreFilter="all",s.searchQuery="",s.renderView()})}}var Cn=require("obsidian");var ve=require("obsidian"),oc="http://127.0.0.1:8765",rc=6;async function kr(s,t){let e;try{e=await(0,ve.requestUrl)({url:oc,method:"POST",contentType:"application/json",body:JSON.stringify({action:s,version:rc,params:t}),throw:!1})}catch(n){throw new Error("Couldn't reach Anki. Is the desktop app open with the AnkiConnect add-on installed?")}let i=e.json;if(i.error)throw new Error(i.error);return i.result}function Fn(s){var t,e,i;return(i=(e=(t=s.titleKey())!=null?t:s.resolveCol(["Quote","Headline","Phrase","Term","Word","Question","Front","Name","Title"]))!=null?e:s.headers[0])!=null?i:null}function ac(s){let t=s.fileCfg.ankiFrontCol;return t&&s.headers.includes(t)?t:Fn(s)}function On(s){return s.replace(/&/g,"&").replace(//g,">")}function Lc(s,t,e){return s.headers.filter(i=>{var n;return i!==e&&((n=t[i])!=null?n:"").trim()}).map(i=>`${On(i)}: ${On(t[i].trim())}`).join("
")}async function Er(s){if(!s.file)return;let t=ac(s);if(!t){new ve.Notice("No column to use as the Anki card front.",6e3);return}let e=s.file.basename,i=s.rows.filter(o=>{var r;return((r=o[t])!=null?r:"").trim()});if(!i.length){new ve.Notice(`Nothing to sync \u2014 no rows with a "${t}" value.`,6e3);return}let n=new ve.Notice(`Syncing ${i.length} cards to Anki deck \u201C${e}\u201D\u2026`,0);try{await kr("createDeck",{deck:e});let o=i.map(l=>({deckName:e,modelName:"Basic",fields:{Front:On(l[t].trim()),Back:Lc(s,l,t)},options:{allowDuplicate:!1,duplicateScope:"deck"},tags:["datadeck"]})),r=await kr("addNotes",{notes:o}),a=r.filter(l=>l!=null).length,L=r.length-a;n.hide(),new ve.Notice(`Anki sync: ${a} added${L?`, ${L} already present`:""} (deck \u201C${e}\u201D).`,6e3)}catch(o){n.hide(),new ve.Notice(`Anki sync failed: ${o instanceof Error?o.message:String(o)}`,8e3)}}var es=require("obsidian");var zo=null;async function ts(){if(zo)return zo;let s=await Promise.resolve().then(()=>(el(),tl));return s.Chart.register(s.LineController,s.ScatterController,s.BarController,s.LineElement,s.PointElement,s.BarElement,s.LinearScale,s.CategoryScale,s.Filler,s.Tooltip,s.Legend),zo=s,s}var sl={pi:Math.PI,e:Math.E},il={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sqrt:Math.sqrt,log:Math.log10,ln:Math.log,exp:Math.exp,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,sign:Math.sign},Ho={min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2};function w5(s){let t=[],e=0;for(;e{var h;return(h=e[i])!=null?h:null},o=()=>{var h;return(h=e[i++])!=null?h:null};function r(){let h=a();for(;;){let u=n();if((u==null?void 0:u.kind)==="op"&&(u.op==="+"||u.op==="-")){i++;let f=a(),g=h;h=u.op==="+"?p=>g(p)+f(p):p=>g(p)-f(p)}else return h}}function a(){let h=L();for(;;){let u=n();if((u==null?void 0:u.kind)==="op"&&(u.op==="*"||u.op==="/"||u.op==="%")){i++;let f=L(),g=h,m=u.op;h=m==="*"?p=>g(p)*f(p):m==="/"?p=>g(p)/f(p):p=>g(p)%f(p)}else if(u&&(u.kind==="num"||u.kind==="ident"||u.kind==="lparen")){let f=L(),g=h;h=m=>g(m)*f(m)}else return h}}function L(){let h=n();if((h==null?void 0:h.kind)==="op"&&h.op==="-"){i++;let u=L();return f=>-u(f)}return(h==null?void 0:h.kind)==="op"&&h.op==="+"?(i++,L()):l()}function l(){let h=c(),u=n();if((u==null?void 0:u.kind)==="op"&&u.op==="^"){i++;let f=L();return g=>Math.pow(h(g),f(g))}return h}function c(){var u,f,g,m,p;let h=o();if(!h)throw new Error("Unexpected end of formula");if(h.kind==="num"){let b=h.value;return()=>b}if(h.kind==="lparen"){let b=r();if(((u=o())==null?void 0:u.kind)!=="rparen")throw new Error("Missing closing )");return b}if(h.kind==="ident"){if(h.name==="x")return C=>C;if(h.name in sl){let C=sl[h.name];return()=>C}let b=((f=n())==null?void 0:f.kind)==="lparen";if(h.name in il||h.name in Ho){if(!b)throw new Error(`${h.name} needs parentheses, e.g. ${h.name}(x)`);i++;let C=r();if(h.name in Ho){if(((g=o())==null?void 0:g.kind)!=="comma")throw new Error(`${h.name}(a, b) needs two arguments`);let _=r();if(((m=o())==null?void 0:m.kind)!=="rparen")throw new Error("Missing closing )");let y=Ho[h.name];return v=>y(C(v),_(v))}if(((p=o())==null?void 0:p.kind)!=="rparen")throw new Error("Missing closing )");let S=il[h.name];return _=>S(C(_))}throw new Error(`Unknown name "${h.name}" \u2014 use x, pi, e, or a function like sin()`)}throw new Error(`Unexpected "${h.kind==="op"?h.op:h.kind}"`)}let d=r();if(i{var o;let i=0,n=0;for(let r of t){let a=((o=r[e])!=null?o:"").trim();a&&(i++,Fe(a)!==null&&n++)}return n>=2&&n/i>=.7})}function D5(s){let t=s.length;if(t<2)return null;let e=0,i=0,n=0,o=0;for(let h of s)e+=h.x,i+=h.y,n+=h.x*h.x,o+=h.x*h.y;let r=t*n-e*e;if(r===0)return null;let a=(t*o-e*i)/r,L=(i-a*e)/t,l=i/t,c=0,d=0;for(let h of s){let u=h.y-(a*h.x+L);c+=u*u,d+=(h.y-l)*(h.y-l)}return{slope:a,intercept:L,r2:d===0?1:1-c/d}}function T5(s,t){let e=[...s].sort((o,r)=>o.x-r.x),i=t/2,n=0;return e.map(o=>{for(;n{let r=new Date(o);if(t==="month")return new Date(r.getFullYear(),r.getMonth(),1).getTime();let a=(r.getDay()+6)%7;return new Date(r.getFullYear(),r.getMonth(),r.getDate()-a).getTime()},n=new Map;return s.forEach(o=>{var L;let r=i(o.x),a=(L=n.get(r))!=null?L:{sum:0,n:0};a.sum+=o.y,a.n+=1,n.set(r,a)}),[...n.entries()].sort((o,r)=>o[0]-r[0]).map(([o,r])=>({x:o,y:e==="count"?r.n:e==="sum"?r.sum:r.sum/r.n}))}function Ps(s){var i;let t=(i=s.ownerDocument.defaultView)==null?void 0:i.getComputedStyle(s),e=(n,o)=>(t==null?void 0:t.getPropertyValue(n).trim())||o;return{accent:e("--interactive-accent","#378ADD"),muted:e("--text-muted","#888888"),grid:e("--background-modifier-border","rgba(128,128,128,0.25)"),fitLine:e("--text-faint","#999999"),formula:e("--color-orange","#e0883a"),series:[e("--color-blue","#4e79a7"),e("--color-green","#59a14f"),e("--color-red","#e15759"),e("--color-purple","#b07aa1"),e("--color-cyan","#76b7b2"),e("--color-pink","#ff9da7"),e("--color-yellow","#edc948")]}}var Rs=s=>{if(!Number.isFinite(s))return String(s);let t=Math.abs(s);return t!==0&&(t>=1e6||t<.001)?s.toExponential(2):String(Math.round(s*1e3)/1e3)},ol=s=>{let t=new Date(s);return isNaN(t.getTime())?String(s):ge(t)};function fn(s,t){var m,p;let e=[],i=s.series.length>1,n=s.series.flatMap(b=>b.points),o=n.map(b=>b.x),r=n.length?Math.min(...o):(m=s.xMin)!=null?m:0,a=n.length?Math.max(...o):(p=s.xMax)!=null?p:10,L=n.filter(b=>b.size!==void 0),l=L.length?Math.min(...L.map(b=>b.size)):0,c=L.length?Math.max(...L.map(b=>b.size)):0,d=(b,C)=>b.size===void 0?C:c===l?7:3+11*Math.sqrt((b.size-l)/(c-l)),h=[];s.series.forEach((b,C)=>{var v;let S=s.connect?[...b.points].sort((x,k)=>x.x-k.x):b.points;if(!S.length)return;let _=i?t.series[C%t.series.length]:t.accent,y=s.connect?3:4;if(((v=s.smoothDays)!=null?v:0)>0?(e.push({type:"scatter",label:b.label||s.yLabel,csvSkipLegend:!0,data:S,backgroundColor:_,borderColor:_,pointRadius:2.5,pointHoverRadius:5}),e.push({type:"line",label:b.label||s.yLabel,data:T5(S,s.smoothDays*864e5),borderColor:_,backgroundColor:_,borderWidth:2,pointRadius:0,pointHitRadius:0,tension:.3})):e.push({type:s.connect?"line":"scatter",label:b.label||s.yLabel,data:S,backgroundColor:_,borderColor:_,borderWidth:1.5,pointRadius:L.length?S.map(x=>d(x,y)):y,pointHoverRadius:L.length?S.map(x=>d(x,y)+2):6,tension:.3}),s.fit==="linear"){let x=D5(S),k=S.map(D=>D.x),E=Math.min(...k),M=Math.max(...k);if(x&&M>E){e.push({type:"line",label:`${b.label||"Best"} fit`,csvIsFit:!0,data:[{x:E,y:x.slope*E+x.intercept},{x:M,y:x.slope*M+x.intercept}],borderColor:i?_:t.fitLine,borderDash:[6,4],borderWidth:1.5,pointRadius:0,pointHitRadius:0});let D=` \xB7 R\xB2 = ${(Math.round(x.r2*1e3)/1e3).toFixed(3)}`,A=s.xIsDate?`${x.slope*864e5>=0?"+":""}${Rs(x.slope*864e5)} ${s.yLabel}/day${D}`:`y = ${Rs(x.slope)}x ${x.intercept>=0?"+":"\u2212"} ${Rs(Math.abs(x.intercept))}${D}`;h.push(i?`${b.label}: ${A}`:s.xIsDate?`Trend: ${A}`:A)}}});let u=h.length?h.join(" \xB7 "):null,f=null;if(s.formula.trim())try{let b=nl(s.formula),C=[],S=160;for(let _=0;_<=S;_++){let y=r+(a-r)*_/S,v=b(y);Number.isFinite(v)&&C.push({x:y,y:v})}C.length&&e.push({type:"line",label:s.formula.trim(),data:C,borderColor:t.formula,borderWidth:1.5,pointRadius:0,pointHitRadius:0,tension:0})}catch(b){f=b instanceof Error?b.message:String(b)}return{config:{type:"scatter",data:{datasets:e},options:{responsive:!0,maintainAspectRatio:!1,scales:{x:{type:"linear",title:{display:!s.xIsDate&&!!s.xLabel,text:s.xLabel,color:t.muted},ticks:{color:t.muted,...s.xIsDate?{callback:b=>ol(Number(b)),maxTicksLimit:8}:{}},grid:{color:t.grid}},y:{title:{display:!!s.yLabel,text:s.yLabel,color:t.muted},ticks:{color:t.muted},grid:{color:t.grid}}},plugins:{legend:{display:e.filter(b=>!b.csvIsFit&&!b.csvSkipLegend).length>1,labels:{color:t.muted,boxWidth:12,filter:b=>{var S;let C=e[(S=b.datasetIndex)!=null?S:-1];return!(C!=null&&C.csvIsFit||C!=null&&C.csvSkipLegend)}}},tooltip:{callbacks:{label:b=>{let C=b.raw,S=s.xIsDate?ol(C.x):Rs(C.x),_=i&&b.dataset.label?`[${b.dataset.label}] `:"",y=C.label?`${C.label}: `:"",v=C.size!==void 0&&s.sizeLabel?` \xB7 ${s.sizeLabel}: ${Rs(C.size)}`:"";return`${_}${y}(${S}, ${Rs(C.y)})${v}`}}}}}},fitText:u,formulaError:f}}var hn="(row number)";function Wo(s,t,e,i,n,o,r,a){let L=new Map,l=0;return s.forEach((d,h)=>{var b,C,S,_,y;let u=Fe((b=d[e])!=null?b:""),f;if(t===hn)f=h+1;else if(o){let v=r((C=d[t])!=null?C:"");f=v?v.getTime():null}else f=Fe((S=d[t])!=null?S:"");if(f===null||u===null){l++;return}let g=i?((_=d[i])!=null?_:"").trim()||"\u2014":"",m=L.get(g);m||(m=[],L.set(g,m));let p={x:f,y:u,label:a(d)};if(n){let v=Fe((y=d[n])!=null?y:"");v!==null&&(p.size=v)}m.push(p)}),{series:[...L.entries()].sort((d,h)=>d[0]==="\u2014"?1:h[0]==="\u2014"?-1:d[0].localeCompare(h[0])).map(([d,h])=>({label:d,points:h})),skipped:l}}function A5(s,t,e){return s.filter(i=>{if(e.has(i))return!1;let n=new Set(t.map(o=>{var r;return((r=o[i])!=null?r:"").trim()}).filter(Boolean));return n.size>=2&&n.size<=10})}function R5(s,t,e){return s.filter(i=>{if(e.has(i))return!1;let n=new Set(t.map(o=>{var r;return((r=o[i])!=null?r:"").trim()}).filter(Boolean));return n.size>=1&&n.size<=30})}function jo(s,t,e,i,n){let o=new Map,r=new Set,a=0,L=vt(t);s.forEach(h=>{var p,b,C;let u=0;if(n!=="count"){let S=Fe((p=h[e!=null?e:""])!=null?p:"");if(S===null){a++;return}u=S}let f=((b=h[t])!=null?b:"").trim(),g=L?f?f.split(",").map(S=>S.trim()).filter(Boolean):["\u2014"]:[f||"\u2014"],m=i?((C=h[i])!=null?C:"").trim()||"\u2014":"";r.add(m),g.forEach(S=>{var v;let _=o.get(S);_||(_=new Map,o.set(S,_));let y=(v=_.get(m))!=null?v:{sum:0,n:0};y.sum+=u,y.n+=1,_.set(m,y)})});let l=(h,u)=>h==="\u2014"?1:u==="\u2014"?-1:h.localeCompare(u,void 0,{numeric:!0}),c=[...o.keys()].sort(l),d=[...r].sort(l).map(h=>({label:h,values:c.map(u=>{var g;let f=(g=o.get(u))==null?void 0:g.get(h);return!f||f.n===0?0:n==="count"?f.n:n==="sum"?f.sum:f.sum/f.n})}));return{categories:c,series:d,skipped:a}}function Uo(s,t,e,i){let n=s.series.length>1;return{type:"bar",data:{labels:s.categories,datasets:s.series.map((o,r)=>({label:o.label||e,data:o.values,backgroundColor:n?i.series[r%i.series.length]:i.accent,borderRadius:3}))},options:{responsive:!0,maintainAspectRatio:!1,scales:{x:{title:{display:!!t,text:t,color:i.muted},ticks:{color:i.muted,autoSkip:!1,maxRotation:60},grid:{display:!1}},y:{beginAtZero:!0,title:{display:!!e,text:e,color:i.muted},ticks:{color:i.muted},grid:{color:i.grid}}},plugins:{legend:{display:n,labels:{color:i.muted,boxWidth:12}}}}}}async function P5(s,t){var e,i,n,o,r,a;try{let L=t.ownerDocument.createElement("canvas");L.width=t.width,L.height=t.height;let l=L.getContext("2d");if(!l||!L.toBlob){new es.Notice("PNG export isn't available here.");return}let c=(e=t.ownerDocument.defaultView)==null?void 0:e.getComputedStyle(t.ownerDocument.body);l.fillStyle=(c==null?void 0:c.getPropertyValue("--background-primary").trim())||"#ffffff",l.fillRect(0,0,L.width,L.height),l.drawImage(t,0,0);let d=await new Promise(p=>L.toBlob(p,"image/png"));if(!d){new es.Notice("PNG export failed.");return}let h=(o=(n=(i=s.file)==null?void 0:i.parent)==null?void 0:n.path)!=null?o:"",u=new Date,f=`${ge(u)} ${String(u.getHours()).padStart(2,"0")}${String(u.getMinutes()).padStart(2,"0")}`,g=`${(a=(r=s.file)==null?void 0:r.basename)!=null?a:"chart"} chart ${f}.png`,m=(0,es.normalizePath)(h?`${h}/${g}`:g);await s.app.vault.createBinary(m,await d.arrayBuffer()),new es.Notice(`Saved ${m}`)}catch(L){new es.Notice(`PNG export failed: ${L instanceof Error?L.message:String(L)}`,6e3)}}function rl(s,t,e){t.createEl("button",{cls:"csv-cfg-btn csv-chart-export-btn",text:"\u2B07 PNG",title:"Save this chart as a PNG next to the CSV"}).addEventListener("click",()=>{P5(s,e)})}function pn(s){return s.rows.length>=2&&un(s.headers,s.rows).length>=1}async function al(s,t){var H,$,z;let e=s.getFilteredRows(),i=un(s.headers,s.rows);if(!i.length){t.createEl("p",{text:"No numeric column to chart.",cls:"csv-empty-state"});return}s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Chart over ${e.length} of ${s.rows.length} entries`});let n=s.fileCfg,o=s.getDateCol(),r=(H=s.titleKey())!=null?H:s.headers[0],a=new Set([r,...i,...o?[o]:[]]);s.headers.forEach(V=>{s.isNotesCol(V)&&a.add(V)});let L=R5(s.headers,s.rows,a),l=[...o?[o]:[],...i.filter(V=>V!==o),hn,...L],c=n.chartXCol&&l.includes(n.chartXCol)?n.chartXCol:l[0],d=L.includes(c),h=n.chartAgg==="sum"||n.chartAgg==="avg"?n.chartAgg:"count",u=i,f=n.chartYCol&&u.includes(n.chartYCol)?n.chartYCol:($=u.find(V=>V!==c))!=null?$:u[0],g=n.chartFit==="linear"?"linear":"none",m=(z=n.chartFormula)!=null?z:"",p=t.createDiv({cls:"csv-chart-view"}),b=p.createDiv({cls:"csv-chart-controls"}),C=V=>{s.saveFileCfg({...s.fileCfg,...V}),s.renderViewPreservingScroll()},S=(V,j,X,q)=>{let nt=b.createDiv({cls:"csv-chart-control"});nt.createSpan({cls:"csv-chart-control-label",text:V});let Q=nt.createEl("select",{cls:"csv-chart-select",attr:{"aria-label":V}});return j.forEach(et=>{let J=Q.createEl("option",{text:et,value:et});et===X&&(J.selected=!0)}),Q.addEventListener("change",()=>q(Q.value)),Q};S("X",l,c,V=>C({chartXCol:V})),(!d||h!=="count")&&S(d?`Y (${h})`:"Y",u,f,V=>C({chartYCol:V})),d&&S("Agg",["count","sum","avg"],h,V=>C({chartAgg:V}));let _=new Set([c,f,r]);s.headers.forEach(V=>{s.isNotesCol(V)&&_.add(V)});let y=A5(s.headers,s.rows,_),v="\u2014",x=n.chartHueCol&&y.includes(n.chartHueCol)?n.chartHueCol:null;y.length&&S("Color",[v,...y],x!=null?x:v,V=>C({chartHueCol:V===v?void 0:V}));let k=!d&&c!==hn&&(c===o||s.isDateCol(c)),E=k&&(n.chartBucket==="week"||n.chartBucket==="month")?n.chartBucket:null,M=n.chartAgg==="avg"||n.chartAgg==="count"?n.chartAgg:"sum",D=k&&!E&&!!n.chartSmooth;k&&(S("By",["day","week","month"],E!=null?E:"day",V=>C({chartBucket:V==="day"?void 0:V})),E&&S("Agg",["sum","avg","count"],M,V=>C({chartAgg:V})));let A=i.filter(V=>V!==f&&V!==c),N=!d&&!E&&n.chartSizeCol&&A.includes(n.chartSizeCol)?n.chartSizeCol:null;if(!d&&!E&&A.length&&S("Size",[v,...A],N!=null?N:v,V=>C({chartSizeCol:V===v?void 0:V})),d){let V=jo(e,c,h==="count"?null:f,x,h),j=p.createDiv({cls:"csv-chart-wrap"}),X=j.createEl("canvas",{cls:"csv-chart-canvas"});if(!V.categories.length){j.remove(),p.createEl("p",{text:`No rows with a "${c}" value to chart.`,cls:"csv-empty-state"});return}V.skipped>0&&p.createDiv({cls:"csv-chart-footer"}).createSpan({cls:"csv-chart-skipped",text:`${V.skipped} row${V.skipped===1?"":"s"} skipped (no numeric value)`});let q=h==="count"?"count":`${h}(${f})`,nt=Uo(V,c,q,Ps(t));s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:Q}=await ts();if(!X.isConnected)return;s.chartInstance=new Q(X,nt),rl(s,b,X);return}b.createEl("button",{cls:`csv-cfg-btn csv-chart-fit-btn ${g==="linear"?"active":""}`,text:"Best fit",title:"Toggle a least-squares fit line"}).addEventListener("click",()=>C({chartFit:g==="linear"?"none":"linear"})),k&&!E&&b.createEl("button",{cls:`csv-cfg-btn csv-chart-smooth-btn ${D?"active":""}`,text:"Smooth",title:"Toggle a 7-day rolling average (raw values stay as dots)"}).addEventListener("click",()=>C({chartSmooth:D?void 0:!0}));let P=b.createDiv({cls:"csv-chart-control csv-chart-formula-wrap"});P.createSpan({cls:"csv-chart-control-label",text:"y ="});let w=P.createEl("input",{cls:"csv-chart-formula-input",type:"text",value:m,placeholder:"overlay, e.g. 2x + 1",attr:{spellcheck:"false",autocomplete:"off",enterkeyhint:"done"}}),U=()=>{w.value.trim()!==m.trim()&&C({chartFormula:w.value})};w.addEventListener("change",U),w.addEventListener("keydown",V=>{V.key==="Enter"&&(V.preventDefault(),w.blur())});let O=Wo(e,c,f,x,N,k,V=>s.parseDate(V),V=>s.getTitle(V)),Z=O.skipped,B=E?O.series.map(V=>({label:V.label,points:Zo(V.points,E,M)})):O.series,G=p.createDiv({cls:"csv-chart-wrap"}),R=G.createEl("canvas",{cls:"csv-chart-canvas"}),W=p.createDiv({cls:"csv-chart-footer"});if(!B.some(V=>V.points.length)){G.remove(),W.remove(),p.createEl("p",{text:`No rows with both "${c}" and "${f}" values to plot.`,cls:"csv-empty-state"});return}let K={series:B,xIsDate:k,xLabel:c===hn?"row":c,yLabel:E?M==="count"?`count / ${E}`:`${M}(${f}) / ${E}`:f,connect:k,fit:g,formula:m,sizeLabel:N!=null?N:"",smoothDays:D?7:0},T=fn(K,Ps(t));T.fitText&&W.createSpan({cls:"csv-chart-fit-text",text:T.fitText}),T.formulaError&&W.createSpan({cls:"csv-chart-formula-error",text:`formula: ${T.formulaError}`}),Z>0&&W.createSpan({cls:"csv-chart-skipped",text:`${Z} row${Z===1?"":"s"} skipped (no numeric value)`}),s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:F}=await ts();R.isConnected&&(s.chartInstance=new F(R,T.config),rl(s,b,R))}function gn(s){return s.resolveCol(["Type","type","Kind","kind","Item","item"])}function Go(s){var t;return(t=s.resolveCol(["Project","project","Projects","projects","Area","area"]))!=null?t:Rt(s)}function cl(s){return s.resolveCol(["Due","due","Deadline","deadline","Due Date","Due date","due date"])}function mn(s){return s.resolveCol(["Priority","priority","Prio","prio","Importance","importance"])}var O5=["task","todo","to-do","action",""],F5=["task","todo","to-do","action","note","idea","reference","ref"],dl=["done","complete","completed","finished","closed","resolved","yes","x","\u2713","true","1"],I5={high:0,med:1,medium:1,normal:1,low:2};function Ie(s){if(cl(s)||mn(s))return!0;let t=gn(s);return t?s.rows.some(e=>{var i;return F5.includes(((i=e[t])!=null?i:"").trim().toLowerCase())}):!1}function Yo(s,t,e){var i;return e?dl.includes(((i=t[e])!=null?i:"").trim().toLowerCase()):!1}function Ll(s){let t=I5[(s!=null?s:"").trim().toLowerCase()];return t===void 0?3:t}function ll(s){return(s!=null?s:"").trim()?0:1}function V5(){return ge()}function N5(s,t){let e=new Map;s.rows.forEach(o=>{var a,L;let r=((a=o[t])!=null?a:"").trim();r&&dl.includes(r.toLowerCase())&&e.set(r,((L=e.get(r))!=null?L:0)+1)});let i="done",n=0;return e.forEach((o,r)=>{o>n&&(i=r,n=o)}),i}function bn(s,t){var E,M;let e=Go(s),i=gn(s),n=s.getStatusCol(),o=cl(s),r=mn(s),a=(E=s.titleKey())!=null?E:s.headers[0],L=t.createDiv({cls:"csv-library-filters"}),l=new Set;e&&s.rows.forEach(D=>{var A;((A=D[e])!=null?A:"").split(",").map(N=>N.trim()).filter(Boolean).forEach(N=>l.add(N))});let c=L.createEl("select",{cls:"csv-library-filter-select"});c.createEl("option",{text:e?"All projects":"All",value:"all"}),Array.from(l).sort().forEach(D=>c.createEl("option",{text:D,value:D})),c.value=s.taskProjectFilter;let d=new Set;i&&s.rows.forEach(D=>{var N;let A=((N=D[i])!=null?N:"").trim();A&&d.add(A)});let h=null;d.size>0&&(h=L.createEl("select",{cls:"csv-library-filter-select"}),h.createEl("option",{text:"All types",value:"all"}),Array.from(d).sort().forEach(D=>h.createEl("option",{text:D,value:D})),h.value=s.taskTypeFilter);let u=()=>{s.taskProjectFilter=c.value,h&&(s.taskTypeFilter=h.value),s.renderView(!0)};c.addEventListener("change",u),h==null||h.addEventListener("change",u);let f=s.searchQuery.toLowerCase().trim(),g=s.rows.filter(D=>{var A,N;return!(s.taskProjectFilter!=="all"&&e&&!((A=D[e])!=null?A:"").split(",").map(P=>P.trim().toLowerCase()).includes(s.taskProjectFilter.toLowerCase())||s.taskTypeFilter!=="all"&&i&&((N=D[i])!=null?N:"").trim().toLowerCase()!==s.taskTypeFilter.toLowerCase()||f&&!s.headers.some(I=>{var P;return((P=D[I])!=null?P:"").toLowerCase().includes(f)}))});(s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"||f)&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${g.length} of ${s.rows.length} entries`});let m={},p=D=>{var N;return e&&((N=D[e])!=null?N:"").split(",").map(I=>I.trim()).filter(Boolean)[0]||"\u2014"};g.forEach(D=>{var P,w,U;let A=i?((P=D[i])!=null?P:"").trim():"",N=O5.includes(A.toLowerCase())?"Tasks":A,I=p(D);m[N]||(m[N]={}),((U=(w=m[N])[I])!=null?U:w[I]=[]).push(D)});let b=t.createDiv({cls:"csv-tasks"}),C=V5(),S=n?N5(s,n):"done",y=((M=s.fileCfg.cardFields)!=null?M:s.headers).filter(D=>D!==e&&D!==i&&D!==n),v=[];n&&v.push({name:"",cls:"csv-tasks-check-cell"}),y.forEach(D=>{let A="";D===a?A="csv-tasks-name-cell":D===o?A="csv-tasks-due":D===r?A="csv-tasks-priority":s.isNotesCol(D)?A="csv-tasks-generic-cell csv-tasks-notes-cell":A="csv-tasks-generic-cell",v.push({name:D,cls:A})});let x=(D,A)=>{A.sort((N,I)=>{var U,O,Z,B,G,R;let P=Yo(s,N,n),w=Yo(s,I,n);if(P!==w)return P?1:-1;if(r){let W=Ll((U=N[r])!=null?U:"")-Ll((O=I[r])!=null?O:"");if(W)return W}if(o){let W=ll((Z=N[o])!=null?Z:"")-ll((B=I[o])!=null?B:"");if(W)return W;let K=((G=N[o])!=null?G:"").localeCompare((R=I[o])!=null?R:"");if(K)return K}return s.getTitle(N).localeCompare(s.getTitle(I))}),A.forEach(N=>{let I=Yo(s,N,n),P=D.createEl("tr");if(n){let U=P.createEl("td",{cls:"csv-tasks-check-cell"}).createSpan({cls:`csv-tasks-check ${I?"is-done":""}`,text:I?"\u2713":""});U.setAttr("title",I?"Mark not done":"Mark done"),U.addEventListener("click",O=>{O.stopPropagation(),N[n]=I?"":S,s.scheduleSave(),s.renderView(!0)})}y.forEach(w=>{var U,O,Z;if(w===a)$5(s,P,N,a,I);else if(w===o){let B=P.createEl("td",{cls:"csv-tasks-due csv-tasks-editable"}),G=o?((U=N[o])!=null?U:"").slice(0,10):"";B.setText(G||"\u2014"),G&&!I&&G{var W;G.stopPropagation();let R=Array.from(new Set([...s.getColumnValues(r),"high","medium","low"]));$t(B,(W=N[r])!=null?W:"",R,K=>{N[r]=K,s.scheduleSave(),s.renderView(!0)},s.contentEl)})}else if(s.isNotesCol(w)){let B=((O=N[w])!=null?O:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim(),G=B?B.length>50?B.slice(0,48)+"\u2026":B:"\u2014",R=P.createEl("td",{text:G,cls:"csv-tasks-generic-cell csv-tasks-notes-cell csv-tasks-editable"});Be(s,R,N,w)}else{let B=(Z=N[w])!=null?Z:"",G=B.length>40?B.slice(0,38)+"\u2026":B,R=P.createEl("td",{text:G||"\u2014",cls:"csv-tasks-generic-cell csv-tasks-editable"});Be(s,R,N,w)}}),P.addEventListener("contextmenu",w=>s.openRowContextMenu(N,w))})},k=Object.keys(m).sort((D,A)=>D==="Tasks"?-1:A==="Tasks"?1:D.localeCompare(A));if(k.forEach(D=>{B5(s,b,D==="Tasks"?D:Dt(D),m[D],x,v)}),k.length===0){let D=b.createDiv({cls:"csv-empty-state"});D.createEl("p",{text:f||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"?"No entries match your filters.":"No tasks yet."}),(f||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all")&&D.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.taskProjectFilter="all",s.taskTypeFilter="all",s.searchQuery="",s.renderView()})}}function B5(s,t,e,i,n,o){if(Object.keys(i).length===0)return;t.createDiv({cls:"csv-tasks-section-header",text:e});let r=t.createDiv({cls:"csv-tasks-section"});Object.keys(i).sort().forEach(a=>{let L=i[a],l=r.createEl("details",{cls:"csv-tasks-group"});l.open=!0;let c=l.createEl("summary",{cls:"csv-tasks-group-header"});c.createSpan({cls:"csv-tasks-arrow",text:"\u25B6"}),c.createSpan({text:` ${a} `}),c.createSpan({cls:"csv-tasks-count",text:String(L.length)});let h=l.createDiv({cls:"csv-tasks-table-wrapper"}).createEl("table",{cls:"csv-tasks-table"}),u=120;o.forEach(p=>{p.cls.includes("check-cell")?u+=30:p.cls.includes("priority")?u+=90:p.cls.includes("due")?u+=150:p.cls.includes("notes-cell")?u+=140:p.cls.includes("generic-cell")&&(u+=150)}),h.style.minWidth=`${u}px`;let g=h.createEl("thead").createEl("tr");o.forEach(p=>g.createEl("th",{text:p.name,cls:p.cls}));let m=h.createEl("tbody");n(m,L)})}function $5(s,t,e,i,n){var d;let o=t.createEl("td",{cls:"csv-tasks-name-cell"}),r=(d=s.isHighlighted)!=null&&d.call(s,e)?"csv-title-highlight":"",a=o.createSpan({cls:`csv-tasks-link ${n?"csv-tasks-done":""} ${r}`,text:e[i]||"Untitled"}),L=s.getNotesCol();a.addEventListener("click",()=>{L?s.openNoteExpander(e,L):s.openOrCreateNotes(e)});let l=s.notesFileExists(e),c=o.createEl("button",{cls:`csv-tasks-page-icon ${l?"exists":""}`,text:l?"\u{1F4C4}":"+"});c.setAttr("title",l?"Open page":"Create page"),c.addEventListener("click",h=>{h.stopPropagation(),s.openOrCreateNotes(e)})}var vn="\u2014";function hl(s){var t;return s.fileCfg.budgetPriceCol!==void 0?s.fileCfg.budgetPriceCol===""?null:(t=s.headers.find(e=>e.toLowerCase()===s.fileCfg.budgetPriceCol.toLowerCase()))!=null?t:null:s.resolveCol(pi)}function yn(s){return hl(s)!==null}function Os(s){return s.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}function ul(s,t){var v,x;let e=hl(s);if(!e){t.createEl("p",{text:"No price/amount column found. Assign one via \u2699 config \u2192 column functions.",cls:"csv-empty-state"});return}let i=Rt(s),n=i===e?null:i,o=(v=s.titleKey())!=null?v:s.headers[0],r=s.getFilteredRows(),a=k=>{var E;return n&&((E=k[n])!=null?E:"").trim()||vn},L=new Map,l=0;r.forEach(k=>{var M,D,A;let E=(D=Fe((M=k[e])!=null?M:""))!=null?D:0;l+=E,L.set(a(k),((A=L.get(a(k)))!=null?A:0)+E)});let c=t.createDiv({cls:"csv-budget"}),d=s.fileCfg.budgetLimit,h=d!==void 0&&d>0,u=h&&l>d,f=c.createDiv({cls:"csv-budget-summary"}),g=f.createDiv({cls:"csv-budget-total-row"});g.createSpan({cls:"csv-budget-total-label",text:"Total"}),g.createSpan({cls:`csv-budget-total-value ${h?u?"is-over":"is-under":""}`,text:Os(l)}),h&&g.createSpan({cls:"csv-budget-total-limit",text:` / ${Os(d)}`});let m=f.createDiv({cls:"csv-budget-limit-row"});m.createSpan({cls:"csv-budget-limit-label",text:"Limit"});let p=k=>{k!==s.fileCfg.budgetLimit&&(s.saveFileCfg({...s.fileCfg,budgetLimit:k}),s.renderViewPreservingScroll())};if(m.createEl("button",{cls:"csv-budget-limit-btn",text:h?Os(d):"No limit set"}).addEventListener("click",()=>{new Ne(s.app,"Set spending limit",d!==void 0?String(d):"","e.g. 2000",k=>{let E=parseFloat(k.trim());Number.isFinite(E)&&E>=0&&p(E)},"Set","number").open()}),h&&m.createEl("button",{cls:"csv-budget-limit-clear",text:"\xD7",attr:{"aria-label":"Clear limit",title:"Clear limit"}}).addEventListener("click",()=>p(void 0)),h){let E=f.createDiv({cls:"csv-budget-bar"}).createDiv({cls:`csv-budget-bar-fill ${u?"is-over":"is-under"}`});E.style.width=`${Math.min(100,Math.round(l/d*100))}%`}if(n&&L.size>1){let k=c.createDiv({cls:"csv-budget-cats"});Array.from(L.entries()).sort((E,M)=>M[1]-E[1]).forEach(([E,M])=>{let D=k.createDiv({cls:"csv-budget-cat-chip"});D.createSpan({cls:"csv-budget-cat-name",text:E}),D.createSpan({cls:"csv-budget-cat-sum",text:Os(M)})})}if(!r.length){c.createDiv({cls:"csv-empty-state",text:"No entries yet."});return}let S=((x=s.fileCfg.cardFields)!=null?x:s.headers).filter(k=>k!==n&&k!==e&&k!==o),_=c.createDiv({cls:"csv-tasks"});Array.from(L.keys()).sort((k,E)=>k===vn?1:E===vn?-1:k.localeCompare(E)).forEach(k=>{var U;let E=r.filter(O=>a(O)===k);if(!E.length)return;let D=_.createDiv({cls:"csv-tasks-section"}).createEl("details",{cls:"csv-tasks-group"});D.open=!0;let A=D.createEl("summary",{cls:"csv-tasks-group-header"});A.createSpan({cls:"csv-tasks-arrow",text:"\u25B6"}),A.createSpan({text:` ${k} `}),A.createSpan({cls:"csv-tasks-count",text:String(E.length)}),A.createSpan({cls:"csv-budget-cat-subtotal",text:Os((U=L.get(k))!=null?U:0)});let I=D.createDiv({cls:"csv-tasks-table-wrapper"}).createEl("table",{cls:"csv-tasks-table"});I.style.minWidth=`${180+S.length*150+110}px`;let P=I.createEl("thead").createEl("tr");P.createEl("th",{text:"Item",cls:"csv-tasks-name-cell"}),S.forEach(O=>P.createEl("th",{text:O,cls:"csv-tasks-generic-cell"})),P.createEl("th",{text:"Price",cls:"csv-budget-price-cell"});let w=I.createEl("tbody");E.forEach(O=>{var G,R;let Z=w.createEl("tr");z5(s,Z,O,o),S.forEach(W=>{var H;let K=(H=O[W])!=null?H:"",T=K.length>40?K.slice(0,38)+"\u2026":K,F=Z.createEl("td",{text:T||"\u2014",cls:"csv-tasks-generic-cell csv-tasks-editable"});Be(s,F,O,W)}),Z.createEl("td",{cls:"csv-budget-price-cell csv-tasks-editable",text:Os((R=Fe((G=O[e])!=null?G:""))!=null?R:0)}).addEventListener("click",()=>{var W;new Ne(s.app,"Edit price",(W=O[e])!=null?W:"","0.00",K=>{O[e]=K.trim(),s.scheduleSave(),s.renderViewPreservingScroll()},"Save","number").open()}),Z.addEventListener("contextmenu",W=>s.openRowContextMenu(O,W))})})}function z5(s,t,e,i){let n=t.createEl("td",{cls:"csv-tasks-name-cell"}),o=n.createSpan({cls:"csv-tasks-link",text:e[i]||"Untitled"}),r=s.getNotesCol();o.addEventListener("click",()=>{r?s.openNoteExpander(e,r):s.openOrCreateNotes(e)});let a=s.notesFileExists(e),L=n.createEl("button",{cls:`csv-tasks-page-icon ${a?"exists":""}`,text:a?"\u{1F4C4}":"+"});L.setAttr("title",a?"Open page":"Create page"),L.addEventListener("click",l=>{l.stopPropagation(),s.openOrCreateNotes(e)})}function xn(s){let t=[];return s.isTravelFile()&&t.push({id:"travel",label:"Travel"}),s.hasDateColumn()&&t.push({id:"dashboard",label:"Dashboard"}),Ie(s)&&t.push({id:"tasks",label:"Tasks"}),yn(s)&&t.push({id:"budget",label:"Budget"}),Rt(s)&&(t.push({id:"library",label:"Cards"}),t.push({id:"kanban-genre",label:"Kanban"})),t.push({id:"table",label:"Table"}),s.rows.length>0&&t.push({id:"focus",label:"Focus"}),Si(s)&&t.push({id:"stats",label:"Stats"}),pn(s)&&t.push({id:"chart",label:"Chart"}),t}function fl(s,t){var h,u,f,g;let e=t.createDiv({cls:"csv-toolbar"});e.createDiv({cls:"csv-toolbar-title",text:(u=(h=s.file)==null?void 0:h.basename)!=null?u:""});let i=e.createDiv({cls:"csv-toolbar-controls"});i.createDiv({cls:"csv-row-count",text:`${s.rows.length} entries`});let n=i.createDiv({cls:"csv-mode-group"}),o=xn(s),r=n.createEl("select",{cls:"csv-mode-select",attr:{"aria-label":"View mode"}});if(o.forEach(({id:m,label:p})=>{let b=r.createEl("option",{text:p,value:m});s.mode===m&&(b.selected=!0)}),r.addEventListener("change",()=>{s.mode=r.value,s.renderView()}),s.mode!=="dashboard"){let m=i.createEl("button",{cls:"csv-cfg-btn csv-search-toggle",text:"\u{1F50D}",title:"Search"}),p=i.createDiv({cls:"csv-search-wrap"}),b=p.createDiv({cls:"csv-search-input-wrap"}),C=b.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search...",value:s.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),S=b.createEl("button",{cls:"csv-search-clear",text:"\xD7",title:"Clear search"});S.toggleClass("is-hidden",!s.searchQuery),p.createEl("button",{cls:"csv-search-done",text:"Done",title:"Dismiss keyboard"}).addEventListener("click",x=>{if(x.preventDefault(),!C.value){e.removeClass("csv-toolbar--search-expanded"),m.removeClass("has-query"),s.searchQuery="",s.renderView(!0);return}C.blur()});let y=null;C.addEventListener("input",x=>{s.searchQuery=x.target.value,S.toggleClass("is-hidden",!s.searchQuery),m.toggleClass("has-query",!!s.searchQuery),y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>{y=null,s.renderView(!0)},120)}),C.addEventListener("keydown",x=>{x.key==="Enter"&&(x.preventDefault(),C.blur())}),S.addEventListener("click",()=>{s.searchQuery="",C.value="",S.addClass("is-hidden"),m.removeClass("has-query"),C.focus({preventScroll:!0}),s.renderView(!0)}),s.searchQuery&&m.addClass("has-query");let v=typeof window!="undefined"&&((f=window.matchMedia)==null?void 0:f.call(window,"(pointer: coarse)").matches);m.addEventListener("click",()=>{if(v){let x=s.getNotesCol();new bi(s.app,s.searchQuery,k=>{s.searchQuery=k,s.renderView()},()=>({matched:s.getFilteredRows().length,total:s.rows.length}),()=>s.getFilteredRows().map(k=>({title:s.getTitle(k),subtitle:s.getSubtitle(k)||void 0,row:k})),k=>{x?s.openNoteExpander(k,x):s.openOrCreateNotes(k)}).open();return}e.addClass("csv-toolbar--search-expanded"),C.focus({preventScroll:!0})})}if(s.mode==="table"&&s.hasDateColumn()){let m=(g=s.fileCfg.sortNewestFirst)!=null?g:!0;i.createEl("button",{cls:`csv-cfg-btn ${m?"active":""}`,text:m?"\u2193 Newest":"\u2191 Oldest",title:"Toggle sort order"}).addEventListener("click",()=>{var C;let b=s.fileCfg;b.sortNewestFirst=!((C=b.sortNewestFirst)==null||C),s.saveFileCfg(b),s.tableSortCol=null,s.renderViewPreservingScroll()})}let a=()=>{var p,b;let m={title:s.resolveCol(fe),category:s.resolveCol(os),status:s.resolveCol(rs),notes:s.resolveCol(pe),image:s.resolveCol(ns),anki:Fn(s),price:s.resolveCol(pi)};new vi(s.app,s.headers,(b=(p=s.file)==null?void 0:p.path)!=null?b:"",s.fileCfg,s.autoDetectBooleanColumns(),s.autoDetectCategoricalColumns(),m,xn(s),C=>{s.saveFileCfg(C),C.defaultMode&&(s.mode=C.defaultMode),s.renderView()},()=>s.headers,()=>s.fileCfg,C=>s.addColumn(C),C=>s.removeColumn(C),C=>s.cleanupBooleanColumn(C)).open()},L=()=>{s.backupToArchive()},l=()=>{Er(s)};i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u2699 Config",title:"Configure this file's columns and views"}).addEventListener("click",a),i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F4BE} Backup",title:"Copy this file to archive/ with today's date"}).addEventListener("click",L),i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F3B4} Anki",title:"Sync rows to Anki (needs Anki desktop + AnkiConnect)"}).addEventListener("click",l),i.createEl("button",{cls:"csv-add-btn",text:"+ add"}).addEventListener("click",()=>s.openAddModal()),i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-overflow",text:"\u22EF",title:"More actions"}).addEventListener("click",m=>{let p=new Cn.Menu;p.addItem(b=>b.setTitle("Config").setIcon("settings").onClick(a)),p.addItem(b=>b.setTitle("Backup").setIcon("save").onClick(L)),p.addItem(b=>b.setTitle("Sync to Anki").setIcon("layers").onClick(l)),p.addSeparator(),p.addItem(b=>b.setTitle("Built 2026-07-17 23:29").setIcon("info").setDisabled(!0)),p.showAtMouseEvent(m)}),i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary csv-info-btn",text:"\u24D8",title:"Built 2026-07-17 23:29 \u2014 click to confirm"}).addEventListener("click",()=>new Cn.Notice("datadeck \u2014 built 2026-07-17 23:29",4e3))}function H5(s){return s&&typeof s=="object"&&"basename"in s?s:null}var Z5=["Author","author","By","by","Source","source","Speaker","speaker","Artist","artist","Director","director"];async function pl(s,t,e,i){var b,C,S;let n=t.split(` -`).map(_=>_.trim()).filter(Boolean),o=_=>{var y,v;return(v=(y=n.find(x=>x.startsWith(_+":")))==null?void 0:y.slice(_.length+1).trim())!=null?v:""},r=o("file");if(!r){e.createEl("p",{text:"Error: No file specified. Use: file: yourfile.csv",cls:"csv-add-error"});return}let a=s.vault.getAbstractFileByPath(i.sourcePath),L=(C=(b=a==null?void 0:a.parent)==null?void 0:b.path)!=null?C:"",l=Xt(r,L),c=H5(s.vault.getAbstractFileByPath(l));if(!c){e.createEl("p",{text:`Error: File not found: ${l}`,cls:"csv-add-error"});return}let d=[],h=[];try{let _=kt(await s.vault.read(c));d=_.headers,h=_.rows}catch(_){e.createEl("p",{text:`Error reading file: ${_ instanceof Error?_.message:String(_)}`,cls:"csv-add-error"});return}if(!h.length){e.createEl("p",{text:"No entries in file.",cls:"csv-add-error"});return}let u=o("field"),f=(S=d.find(_=>_.toLowerCase()===u.toLowerCase()))!=null?S:d[0],g=Z5.map(_=>d.find(y=>y===_)).find(Boolean),m=e.createDiv({cls:"csv-random-card"}),p=()=>{var M;m.empty();let _=h.filter(D=>{var A;return((A=D[f])!=null?A:"").trim()}),y=_.length?_:h,v=y[Math.floor(Math.random()*y.length)];m.createDiv({cls:"csv-random-text",text:v[f]||"\u2014"});let x=g?((M=v[g])!=null?M:"").trim():"";x&&m.createDiv({cls:"csv-random-sub",text:`\u2014 ${x}`});let k=m.createDiv({cls:"csv-random-foot"});k.createSpan({cls:"csv-random-src",text:c.basename}),k.createEl("button",{cls:"csv-random-btn",text:"\u21BB",title:"Another one"}).addEventListener("click",p)};p()}async function gl(s,t){var R,W,K;let e=s.getDateCol();if(!e){t.createEl("p",{text:"No date column detected.",cls:"csv-empty-state"});return}let i=s.getBooleanColumns(),n=s.getNotesCol(),o=s.formatDate(new Date),r=[...s.rows].sort((T,F)=>{var H,$;return((H=T[e])!=null?H:"").localeCompare(($=F[e])!=null?$:"")});s.selectedDate||(s.selectedDate=o);let a=r.find(T=>T[e]===s.selectedDate),L=s.selectedDate===o;t.addClass("csv-dashboard");let l=[...new Set([...r.map(T=>T[e]),o])].filter(Boolean).sort(),c=t.createDiv({cls:"csv-dash-nav"});c.createEl("button",{cls:"csv-dash-nav-btn csv-dash-back-btn",text:"\u25C0"}).addEventListener("click",()=>{let T=l.indexOf(s.selectedDate);if(T>0)s.selectedDate=l[T-1],s.renderView();else if(T===-1&&l.length>0){let F=l.filter(H=>H0&&(s.selectedDate=F[F.length-1],s.renderView())}});let h=c.createDiv({cls:"csv-dash-date"});L&&h.createSpan({cls:"csv-dash-today-dot"});let u=h.createEl("select",{cls:"csv-dash-date-select"});if(l.forEach(T=>{let F=u.createEl("option",{text:T,value:T});T===s.selectedDate&&(F.selected=!0)}),u.addEventListener("change",()=>{s.selectedDate=u.value,s.renderView()}),c.createEl("button",{cls:"csv-dash-nav-btn",text:"\u25B6"}).addEventListener("click",()=>{let T=l.indexOf(s.selectedDate);if(T>=0&&TH>s.selectedDate);F.length>0&&(s.selectedDate=F[0],s.renderView())}}),L||c.createEl("button",{cls:"csv-dash-today-btn",text:"Today"}).addEventListener("click",()=>{s.selectedDate=o,s.renderView()}),!a){let T=t.createDiv({cls:"csv-dash-add-section"});T.createEl("p",{text:`No entry for ${s.selectedDate}`}),T.createEl("button",{cls:"csv-dash-add-btn",text:`+ Add entry for ${s.selectedDate}`}).addEventListener("click",()=>{let H={};s.headers.forEach($=>H[$]=""),H[e]=s.selectedDate,s.rows.push(H),s.scheduleSave(),s.renderView()})}if(a){let T=t.createDiv({cls:"csv-dash-habits"});T.createEl("h3",{text:s.selectedDate===o?"Today":s.selectedDate,cls:"csv-dash-section-title"});let F=T.createDiv({cls:"csv-dash-habits-grid"});i.forEach($=>{let z=s.isTruthy(a[$]),V=F.createDiv({cls:`csv-dash-habit ${z?"checked":""}`}),j=V.createEl("button",{cls:"csv-dash-habit-check",text:z?"\u25CF":"\u25CB"});V.createSpan({cls:"csv-dash-habit-label",text:$}),j.addEventListener("click",()=>{a[$]=z?"0":"1",s.scheduleSave(),s.renderViewPreservingScroll()})});let H=i.filter($=>s.isTruthy(a[$])).length;if(T.createDiv({cls:"csv-dash-habits-count",text:`${H} of ${i.length} complete`}),n&&((R=a[n])!=null&&R.trim())){let $=T.createDiv({cls:"csv-dash-notes-preview"});$.createEl("strong",{text:"Notes: "}),$.createSpan({text:a[n].slice(0,200)+(a[n].length>200?"\u2026":"")})}}let g=t.createDiv({cls:"csv-dash-chart-section"});g.createEl("h3",{text:"Progress",cls:"csv-dash-section-title"});let p=g.createDiv({cls:"csv-dash-chart-wrap"}).createEl("canvas",{cls:"csv-dash-chart"}),b=r.map(T=>{var H;return((H=T[e])!=null?H:"").slice(5)}),C=r.map(T=>i.filter(F=>s.isTruthy(T[F])).length);s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:S}=await ts();if(!p.isConnected)return;s.chartInstance=new S(p,{type:"line",data:{labels:b,datasets:[{label:"Habits done",data:C,borderColor:"#378ADD",backgroundColor:"rgba(55,138,221,0.08)",borderWidth:1.5,pointRadius:3,tension:.3,fill:!0}]},options:{responsive:!0,maintainAspectRatio:!1,scales:{y:{min:0,max:i.length||8,ticks:{stepSize:1}}},plugins:{tooltip:{enabled:!0}}}});let _=t.createDiv({cls:"csv-dash-stats-section"});_.createEl("h3",{text:"Stats",cls:"csv-dash-section-title"});let y=r.length,v=r.reduce((T,F)=>T+i.filter(H=>s.isTruthy(F[H])).length,0),x=y>0?(v/y).toFixed(1):"0",k=r.filter(T=>i.every(F=>s.isTruthy(T[F]))).length,E=0,M=0,D=null;for(let T of r){let F=i.filter(z=>s.isTruthy(T[z])).length,H=s.parseDate((W=T[e])!=null?W:""),$=!0;D&&H&&Math.round((H.getTime()-D.getTime())/864e5)!==1&&($=!1),F>=1&&($||D===null)?(M++,M>E&&(E=M)):F>=1?(M=1,M>E&&(E=M)):M=0,D=H}let A=0,N=new Date;N.setHours(0,0,0,0);let I=N;for(let T=r.length-1;T>=0;T--){let F=s.parseDate((K=r[T][e])!=null?K:"");if(!F)break;let H=Math.round((I.getTime()-F.getTime())/(1e3*60*60*24));if(A===0&&H>1||A>0&&H!==1)break;if(i.filter(z=>s.isTruthy(r[T][z])).length>=1)A++,I=F;else break}let P=_.createDiv({cls:"csv-dash-stats-bar"}),w=(T,F)=>{P.createEl("strong",{text:T}),P.appendText(` ${F}`)};w(String(y),"days logged"),P.appendText(" \xB7 "),w(String(x),"avg/day"),P.appendText(" \xB7 "),w(String(k),"perfect days"),P.appendText(" \xB7 current streak "),P.createEl("strong",{text:`${A}d`}),P.appendText(" \xB7 best streak "),P.createEl("strong",{text:`${E}d`});let O=t.createDiv({cls:"csv-dash-cards-section"}).createDiv({cls:"csv-dash-cards-grid"}),Z=new Date().getFullYear(),B={language:"\u25CB",read:"\u2261",gym:"\u229E",vitamins:"\u2299",cardio:"\u2191",meditate:"\u25CE",challenge:"\u273F",journal:"\u270E",exercise:"\u229E",water:"\u{1F4A7}",sleep:"\u{1F319}",study:"\u{1F4DA}"};i.map(T=>{let F=r.filter(j=>s.isTruthy(j[T])),H=F.length>0?F[F.length-1][e]:null,$=new Set;F.forEach(j=>{var q;let X=s.parseDate((q=j[e])!=null?q:"");X&&$.add(X.getFullYear())});let z=r.filter(j=>{var q;let X=s.parseDate((q=j[e])!=null?q:"");return X&&X.getFullYear()===Z}),V=z.filter(j=>s.isTruthy(j[T])).length;return{habit:T,doneCount:F.length,doneThisYear:V,totalThisYear:z.length,lastDone:H,years:Array.from($).sort()}}).sort((T,F)=>!T.lastDone&&!F.lastDone?0:T.lastDone?F.lastDone?F.lastDone.localeCompare(T.lastDone):-1:1).forEach(({habit:T,doneCount:F,doneThisYear:H,totalThisYear:$,lastDone:z,years:V})=>{var J;let j=O.createDiv({cls:"csv-dash-habit-card"}),X=(J=B[T.toLowerCase()])!=null?J:"\u25CB",q=j.createDiv({cls:"csv-dash-habit-card-header"});if(q.createSpan({cls:"csv-dash-habit-icon",text:X}),q.createSpan({cls:"csv-dash-habit-card-name",text:Dt(T)}),V.length>0&&j.createDiv({cls:"csv-dash-habit-years"}).setText(V.join(" \xB7 ")),j.createDiv({cls:"csv-dash-habit-card-thisyear",text:`${H} of ${$} complete this year`}),j.createDiv({cls:"csv-dash-habit-card-alltime",text:`${F} of ${y} all time`}),z){let ot=s.parseDate(z),lt=ot?ot.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):z;j.createDiv({cls:"csv-dash-habit-card-last",text:`Last logged: ${lt}`})}else j.createDiv({cls:"csv-dash-habit-card-last",text:"Never logged"});let nt=y>0?F/y*100:0,et=j.createDiv({cls:"csv-dash-habit-progress"}).createDiv({cls:"csv-dash-habit-progress-bar"});et.style.width=`${nt}%`,j.addEventListener("click",()=>{s.selectedHabit=s.selectedHabit===T?null:T,s.renderViewPreservingScroll()}),s.selectedHabit===T&&j.addClass("selected")}),s.selectedHabit&&i.includes(s.selectedHabit)&&W5(s,t,r,e,s.selectedHabit)}function W5(s,t,e,i,n){var E,M,D;let o=t.createDiv({cls:"csv-dash-timeline-section"}),r=o.createDiv({cls:"csv-dash-timeline-header"});r.createEl("h3",{text:`${Dt(n)} Timeline`,cls:"csv-dash-section-title"});let a=r.createEl("select",{cls:"csv-dash-year-select"}),L=new Set;e.forEach(A=>{var I;let N=s.parseDate((I=A[i])!=null?I:"");N&&L.add(N.getFullYear())}),L.add(new Date().getFullYear()),Array.from(L).sort().reverse().forEach(A=>{let N=a.createEl("option",{text:String(A),value:String(A)});A===s.timelineYear&&(N.selected=!0)}),a.addEventListener("change",()=>{s.timelineYear=parseInt(a.value),s.renderViewPreservingScroll()}),r.createEl("button",{cls:"csv-dash-timeline-close",text:"\u2715"}).addEventListener("click",()=>{s.selectedHabit=null,s.renderViewPreservingScroll()});let c=new Map;e.forEach(A=>{var N;c.set((N=A[i])!=null?N:"",s.isTruthy(A[n]))});let d=o.createDiv({cls:"csv-dash-timeline-grid-wrap"}),h=d.createDiv({cls:"csv-dash-timeline-months"});["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].forEach(A=>h.createSpan({cls:"csv-dash-timeline-month-label",text:A}));let f=d.createDiv({cls:"csv-dash-timeline-calendar"}),g=f.createDiv({cls:"csv-dash-timeline-day-labels"});for(let A=1;A<=31;A++)g.createDiv({cls:"csv-dash-timeline-day-label",text:A%5===0||A===1?String(A):""});for(let A=0;A<12;A++){let N=f.createDiv({cls:"csv-dash-timeline-month-col"}),I=new Date(s.timelineYear,A+1,0).getDate();for(let P=1;P<=31;P++){if(P>I){N.createDiv({cls:"csv-dash-timeline-cell empty"});continue}let w=`${s.timelineYear}-${String(A+1).padStart(2,"0")}-${String(P).padStart(2,"0")}`,U=(E=c.get(w))!=null?E:!1,O=c.has(w),Z=new Date(s.timelineYear,A,P)>new Date,B=N.createDiv({cls:`csv-dash-timeline-cell ${Z?"future":""} ${U?"done":""} ${O&&!U?"missed":""} ${!O&&!Z?"no-entry":""}`});B.title=`${w}: ${Z?"Future":U?"\u2713 Done":O?"\u2717 Missed":"No entry"}`}}let m=e.filter(A=>{var I;let N=s.parseDate((I=A[i])!=null?I:"");return N&&N.getFullYear()===s.timelineYear}),p=m.filter(A=>s.isTruthy(A[n])).length,b=m.length,C=0,S=0,_=0,y=null;for(let A of e){let N=s.isTruthy(A[n]),I=s.parseDate((M=A[i])!=null?M:""),P=!0;y&&I&&Math.round((I.getTime()-y.getTime())/864e5)!==1&&(P=!1),N&&(P||y===null)?(_++,_>S&&(S=_)):N?_=1:_=0,y=I}let v=new Date;v.setHours(0,0,0,0);let x=v;for(let A=e.length-1;A>=0;A--){let N=s.parseDate((D=e[A][i])!=null?D:"");if(!N)break;let I=Math.round((x.getTime()-N.getTime())/(1e3*60*60*24));if(C===0&&I>1||C>0&&I!==1)break;if(s.isTruthy(e[A][n]))C++,x=N;else break}let k=o.createDiv({cls:"csv-dash-timeline-stats"});k.createEl("strong",{text:String(p)}),k.appendText(` of ${b} in ${s.timelineYear} \xB7 current streak `),k.createEl("strong",{text:`${C}d`}),k.appendText(" \xB7 best streak "),k.createEl("strong",{text:`${S}d`})}function ml(s,t){var b,C,S;let e=s.getFilteredRows();if(s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${e.length} of ${s.rows.length} entries`}),!e.length){let _=t.createDiv({cls:"csv-empty-state"});_.createEl("p",{text:s.searchQuery?"No matching entries found.":"No entries yet."}),s.searchQuery&&_.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear search"}).addEventListener("click",()=>{s.searchQuery="",s.renderView()});return}s.focusIndex>=e.length&&(s.focusIndex=e.length-1),s.focusIndex<0&&(s.focusIndex=0);let i=e[s.focusIndex],n=(b=s.titleKey())!=null?b:s.headers[0],o=s.getNotesCol(),r=s.authorKey(),a=t.createDiv({cls:"csv-focus-wrap",attr:{tabindex:"0"}}),L=_=>{s.focusIndex=(_%e.length+e.length)%e.length,s.focusNavPending=!0,s.renderView(!0)},l=a.createDiv({cls:"csv-focus-card"});l.createDiv({cls:"csv-focus-position",text:`${s.focusIndex+1} / ${e.length}`});let c=l.createDiv({cls:`csv-focus-title ${(C=s.isHighlighted)!=null&&C.call(s,i)?"csv-title-highlight":""}`,text:s.getTitle(i)});o&&(c.addClass("is-clickable"),c.title="Open entry",c.addEventListener("click",()=>s.openNoteExpander(i,o)));let d=s.getSubtitle(i);if(d&&l.createDiv({cls:"csv-focus-sub",text:d}),o&&o!==n&&((S=i[o])!=null&&S.trim())){let _=l.createDiv({cls:"csv-focus-notes"});s.renderMarkdownInto(_,i[o])}let h=new Set([n,o,r].filter(Boolean)),u=s.headers.filter(_=>{var y;return!h.has(_)&&((y=i[_])!=null?y:"").trim()});if(u.length){let _=l.createDiv({cls:"csv-focus-meta"});u.forEach(y=>{let v=_.createDiv({cls:"csv-kanban-chip"});if(v.createSpan({cls:"csv-chip-label",text:y+": "}),s.isSelectCol(y)){let x=v.createSpan({cls:"csv-chip-value csv-chip-select",text:i[y]});x.addEventListener("click",k=>{k.stopPropagation(),$t(x,i[y],s.getColumnValues(y),E=>{i[y]=E,x.setText(E||"\u2014"),s.scheduleSave()},s.contentEl,{multi:vt(y)})})}else v.createSpan({cls:"csv-chip-value",text:i[y]})})}l.addEventListener("contextmenu",_=>s.openRowContextMenu(i,_));let f=a.createDiv({cls:"csv-focus-nav"}),g=f.createEl("button",{cls:"csv-focus-nav-btn",text:"\u2039",title:"Previous (\u2190)"}),m=f.createEl("button",{cls:"csv-focus-nav-btn csv-focus-nav-rand",text:"\u{1F500}",title:"Random entry"}),p=f.createEl("button",{cls:"csv-focus-nav-btn",text:"\u203A",title:"Next (\u2192)"});g.addEventListener("click",()=>L(s.focusIndex-1)),p.addEventListener("click",()=>L(s.focusIndex+1)),m.addEventListener("click",()=>{if(e.length<2)return;let _=s.focusIndex;for(;_===s.focusIndex;)_=Math.floor(Math.random()*e.length);L(_)}),a.addEventListener("keydown",_=>{_.key==="ArrowLeft"?(_.preventDefault(),L(s.focusIndex-1)):_.key==="ArrowRight"&&(_.preventDefault(),L(s.focusIndex+1))}),(s.focusNavPending||document.activeElement===document.body)&&(s.focusNavPending=!1,a.focus({preventScroll:!0}))}var Nt=require("obsidian"),vl=Ns(is());var j5=[{id:"table",label:"Table"},{id:"library",label:"Cards"},{id:"kanban-genre",label:"Kanban"}];function bl(s){return s&&typeof s=="object"&&"basename"in s?s:null}function U5(s){let t=s.split(` -`).map(r=>r.trim()).filter(Boolean),e=r=>{var a,L;return(L=(a=t.find(l=>l.toLowerCase().startsWith(r+":")))==null?void 0:a.slice(r.length+1).trim())!=null?L:""},i=e("mode").toLowerCase(),n=i==="kanban"||i==="kanban-genre"?"kanban-genre":i==="cards"||i==="card"||i==="library"?"library":"table",o=parseInt(e("height"),10);return{file:e("file"),mode:n,height:Number.isFinite(o)&&o>0?o:null,collapse:e("collapse").split(",").map(r=>r.trim()).filter(Boolean)}}var Ko=class extends Nt.MarkdownRenderChild{constructor(e,i,n,o,r){super(e);this.file=null;this.headers=[];this.rows=[];this.searchQuery="";this.tableSortCol=null;this.tableSortDir="asc";this.libraryStatusFilter="all";this.libraryGenreFilter="all";this.collapsedGroups=new Set;this.saveTimer=null;this.lastWritten=null;this.contentArea=null;this.app=i,this.settings=n,this.persistSettings=o,this.opts=r,this.mode=r.mode,this.collapsedGroups=new Set(r.collapse.map(a=>a.toLowerCase()))}get renderComponent(){return this}get contentEl(){return this.containerEl}get asView(){return this}onload(){if(this.containerEl.addClass("csv-inline-view"),!this.opts.file){this.renderError("No file specified. Use: file: yourfile.csv");return}(async()=>await this.reload()&&(this.renderView(),this.registerEvent(this.app.vault.on("modify",async e=>{if(!this.file||e.path!==this.file.path)return;let i=await this.app.vault.read(this.file);if(i===this.lastWritten)return;this.lastWritten=i;let n=kt(i);this.headers=n.headers,this.rows=n.rows,this.renderView()})),this.registerEvent(this.app.vault.on("rename",(e,i)=>{this.file&&i===this.file.path&&(this.file=bl(e))}))))()}onunload(){this.saveTimer&&window.clearTimeout(this.saveTimer)}async reload(){let e=bl(this.app.vault.getAbstractFileByPath(this.opts.file));if(!e)return this.renderError(`File not found: ${this.opts.file}`),!1;this.file=e;try{let i=await this.app.vault.read(e),n=kt(i);this.headers=n.headers,this.rows=n.rows,this.lastWritten=i}catch(i){return this.renderError(`Error reading file: ${i instanceof Error?i.message:String(i)}`),!1}return!0}renderError(e){this.containerEl.empty(),this.containerEl.createEl("p",{text:`csv-view: ${e}`,cls:"csv-add-error"})}scheduleSave(){this.saveTimer&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>void this.doSave(),600)}async doSave(){if(this.file)try{let e=vl.default.unparse(this.rows,{columns:this.headers});try{let i=await this.app.vault.read(this.file);this.lastWritten!==null&&i!==this.lastWritten&&i!==e&&await ls(this.app,this.file,i)}catch(i){}this.lastWritten=e,await this.app.vault.modify(this.file,e)}catch(e){new Nt.Notice(`Couldn't save ${this.file.name}: ${e instanceof Error?e.message:String(e)}`,8e3)}}get fileCfg(){var e;return this.file?(e=this.settings.fileConfigs[this.file.path])!=null?e:{}:{}}saveFileCfg(e){this.file&&(this.settings.fileConfigs[this.file.path]=e,this.persistSettings())}isHighlighted(e){var i;return((i=this.fileCfg.highlightedTitles)!=null?i:[]).includes(this.getTitle(e))}toggleHighlight(e){let i=this.getTitle(e),n=this.fileCfg,o=n.highlightedTitles?[...n.highlightedTitles]:[],r=o.indexOf(i);r>=0?o.splice(r,1):o.push(i),n.highlightedTitles=o,this.saveFileCfg(n)}resolveCol(e){for(let i of e){let n=this.headers.find(o=>o.toLowerCase()===i.toLowerCase());if(n)return n}return null}getNotesCol(){return this.fileCfg.notesColumn!==void 0?this.fileCfg.notesColumn===""?null:this.fileCfg.notesColumn:this.resolveCol(pe)}isNotesCol(e){let i=this.getNotesCol();return i?e===i:this.settings.notesColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var n;let i=(n=this.titleKey())!=null?n:this.headers[0];return e===i||this.getDateCol()===e||vt(e)?!1:this.fileCfg.categoricalColumns?this.fileCfg.categoricalColumns.includes(e):this.isSelectCol(e)||qt(this.getColumnValues(e).length)}getStatusCol(){var e;return this.fileCfg.statusColumn!==void 0?this.fileCfg.statusColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(rs)}getCategoryCol(){var e;return this.fileCfg.categoryColumn!==void 0?this.fileCfg.categoryColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(os)}titleKey(){var e,i;return this.fileCfg.titleColumn!==void 0?this.fileCfg.titleColumn===""?void 0:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(i=this.resolveCol(fe))!=null?i:void 0}authorKey(){var e;return(e=this.resolveCol(["Author","author","Authors","authors","Director","director","Artist","artist","Creator","creator","By","by"]))!=null?e:void 0}getTitle(e){var n;let i=this.titleKey();return(n=i?e[i]:e[this.headers[0]])!=null?n:"\u2014"}getSubtitle(e){var n;let i=this.authorKey();return i&&(n=e[i])!=null?n:""}getColumnValues(e){return Array.from(new Set(this.rows.map(i=>{var n;return(n=i[e])!=null?n:""}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn!==void 0?this.fileCfg.imageColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(ns)}getBooleanColumns(){return this.fileCfg.habitColumns?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.headers.filter(e=>{if(e===this.getDateCol()||this.isNotesCol(e))return!1;let i=this.rows.map(n=>{var o;return((o=n[e])!=null?o:"").toLowerCase().trim()});return as(i)})}getDateCol(){var o,r;if(this.fileCfg.dateColumns&&this.fileCfg.dateColumns.length>0){let a=this.fileCfg.dateColumns[0];return(o=this.headers.find(L=>L===a))!=null?o:null}if(this.headers.length===0)return null;let e=this.headers[0];if(["date","day","datum"].includes(e.toLowerCase()))return e;let i=/^\d{4}-\d{2}-\d{2}$/,n=this.rows.slice(0,5);return n.length>0&&n.every(a=>{var L;return i.test((L=a[e])!=null?L:"")})?e:(r=this.headers.find(a=>this.isDateCol(a)))!=null?r:null}isDateCol(e){var i;return(i=this.fileCfg.dateColumns)!=null&&i.includes(e)?!0:Et(e)}getFilteredRows(){var n;let e=this.rows;if(this.searchQuery.trim()){let o=this.searchQuery.toLowerCase().trim();e=e.filter(r=>this.headers.some(a=>{var L;return((L=r[a])!=null?L:"").toLowerCase().includes(o)}))}if(this.mode==="table"&&this.tableSortCol&&this.headers.includes(this.tableSortCol)){let o=this.tableSortCol,r=this.tableSortDir;return[...e].sort((a,L)=>{var c,d;let l=((c=a[o])!=null?c:"").localeCompare((d=L[o])!=null?d:"",void 0,{numeric:!0});return r==="asc"?l:-l})}let i=this.getDateCol();if(this.mode==="table"&&i){let o=(n=this.fileCfg.sortNewestFirst)!=null?n:!0;e=[...e].sort((r,a)=>{var l,c;let L=((l=r[i])!=null?l:"").localeCompare((c=a[i])!=null?c:"");return o?-L:L})}return e}notesFilePath(e){var a,L,l;let i=Ve(this.getTitle(e)),n=(l=(L=(a=this.file)==null?void 0:a.parent)==null?void 0:L.path)!=null?l:"",o=this.settings.notesSubfolder.trim(),r=o?n?`${n}/${o}`:o:n;return(0,Nt.normalizePath)(`${r}/${i}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}async openOrCreateNotes(e){var o;let i=this.notesFilePath(e),n=this.app.vault.getAbstractFileByPath(i);if(!n){let a=["---",...this.headers.filter(d=>!this.isNotesCol(d)&&e[d]).map(d=>`${d}: "${e[d].replace(/"/g,'\\"')}"`),"---","",`# ${this.getTitle(e)}`,"",""].join(` -`),L=this.headers.find(d=>this.isNotesCol(d)),l=a+(L&&((o=e[L])!=null&&o.trim())?e[L]:""),c=i.substring(0,i.lastIndexOf("/"));c&&!this.app.vault.getAbstractFileByPath(c)&&await this.app.vault.createFolder(c),n=await this.app.vault.create(i,l),new Nt.Notice(`Created: ${n.name}`)}await this.app.workspace.getLeaf("tab").openFile(n)}deleteWithUndo(e){let i=this.rows.indexOf(e);if(i<0)return;this.rows.splice(i,1),this.scheduleSave(),this.renderView();let n=this.getTitle(e)||"entry",o=createFragment();o.createSpan({text:`Deleted \u201C${n}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new Nt.Notice(o,6e3);r.addEventListener("click",()=>{r.hasAttribute("disabled")||(r.setAttribute("disabled","true"),this.rows.splice(Math.min(i,this.rows.length),0,e),this.scheduleSave(),this.renderView(),a.hide(),new Nt.Notice(`Restored \u201C${n}\u201D`,2500))})}openRowContextMenu(e,i){let n=new Nt.Menu;n.addItem(a=>a.setTitle("Open / create notes file").setIcon("file-text").onClick(()=>void this.openOrCreateNotes(e))),n.addItem(a=>a.setTitle("Open entry").setIcon("maximize").onClick(()=>{var L;return this.openNoteExpander(e,(L=this.getNotesCol())!=null?L:"")}));let o=this.getStatusCol();if(o){let a=this.getColumnValues(o);a.length&&(n.addSeparator(),a.forEach(L=>{L!==e[o]&&n.addItem(l=>l.setTitle(`Mark as: ${L}`).onClick(()=>{e[o]=L,this.scheduleSave(),this.renderView()}))}))}n.addSeparator();let r=this.isHighlighted(e);n.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderView()})),n.addSeparator(),n.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),n.showAtMouseEvent(i)}openNoteExpander(e,i){var n,o;new me(this.app,e,i,this.headers,(o=(n=this.file)==null?void 0:n.path)!=null?o:"",this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),r=>{Object.assign(e,r),this.scheduleSave(),this.renderView()},()=>this.deleteWithUndo(e),this.isCategoricalCol.bind(this),this.titleKey(),r=>this.getBooleanColumns().includes(r),r=>this.isDateCol(r)).open()}openAddModal(){new cs(this.app,this.headers,this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),e=>{this.rows.push(e),this.scheduleSave(),this.renderView(),new Nt.Notice(`Added: ${this.getTitle(e)}`)},{},e=>this.getBooleanColumns().includes(e),e=>this.isCategoricalCol(e),this.titleKey(),e=>this.isDateCol(e)).open()}renderSelectField(e,i,n){var a;let o=(a=i[n])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),n.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",L=>{var l;L.stopPropagation(),$t(r,(l=i[n])!=null?l:"",this.getColumnValues(n),c=>{i[n]=c,r.setText(c||"\u2014"),this.scheduleSave()},this.contentEl)}),r}renderMarkdownInto(e,i){var n,o;Nt.MarkdownRenderer.render(this.app,i,e,(o=(n=this.file)==null?void 0:n.path)!=null?o:"",this.renderComponent)}renderViewPreservingScroll(){this.renderView()}renderView(e=!1){let i=this.containerEl;e?this.contentArea&&this.contentArea.empty():(i.empty(),this.renderToolbar(i),this.contentArea=i.createDiv({cls:"csv-content-area"}),this.opts.height&&(this.contentArea.style.maxHeight=this.opts.height+"px"));let n=this.contentArea;if(n){if(n.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){n.createDiv({cls:"csv-empty-state"}).createEl("p",{text:"This file is empty."});return}if(this.rows.length===0){let o=n.createDiv({cls:"csv-empty-state"});o.createEl("p",{text:"No entries yet."}),o.createEl("button",{cls:"csv-empty-state-action",text:"+ add the first entry"}).addEventListener("click",()=>this.openAddModal());return}(this.mode==="library"||this.mode==="kanban-genre")&&!Rt(this.asView)&&(this.mode="table"),this.mode==="library"?Ei(this.asView,n):this.mode==="kanban-genre"?ki(this.asView,n):_i(this.asView,n)}}renderToolbar(e){var l,c;let i=e.createDiv({cls:"csv-toolbar csv-inline-toolbar"});i.createDiv({cls:"csv-toolbar-title",text:(c=(l=this.file)==null?void 0:l.basename)!=null?c:""}).addEventListener("click",()=>{this.file&&this.app.workspace.getLeaf("tab").openFile(this.file)});let n=i.createDiv({cls:"csv-toolbar-controls"});n.createDiv({cls:"csv-row-count",text:`${this.rows.length} entries`});let o=!!Rt(this.asView),r=n.createDiv({cls:"csv-mode-group"});j5.forEach(({id:d,label:h})=>{if((d==="library"||d==="kanban-genre")&&!o)return;r.createEl("button",{cls:`csv-mode-btn ${this.mode===d?"active":""}`,text:h}).addEventListener("click",()=>{this.mode=d,this.renderView()})});let a=n.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search\u2026",value:this.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),L=null;a.addEventListener("input",d=>{this.searchQuery=d.target.value,L!==null&&window.clearTimeout(L),L=window.setTimeout(()=>{L=null,this.renderView(!0)},120)}),n.createEl("button",{cls:"csv-add-btn",text:"+ add"}).addEventListener("click",()=>this.openAddModal())}};function yl(s,t,e,i){i("csv-view",(n,o,r)=>{var d,h,u;let a=U5(n),L=(u=(h=(d=s.vault.getAbstractFileByPath(r.sourcePath))==null?void 0:d.parent)==null?void 0:h.path)!=null?u:"",l=a.file?Xt(a.file,L):a.file,c=new Ko(o,s,t,e,{...a,file:l});r.addChild(c)})}var Cl=require("obsidian");function Y5(s){let t=s.split(` -`).map(n=>n.trim()).filter(Boolean),e=n=>{var o,r;return(r=(o=t.find(a=>a.toLowerCase().startsWith(n+":")))==null?void 0:o.slice(n.length+1).trim())!=null?r:""},i=n=>{let o=parseFloat(e(n));return Number.isFinite(o)?o:null};return{file:e("file"),x:e("x"),y:e("y"),hue:e("hue")||e("color"),size:e("size"),agg:["count","sum","avg"].includes(e("agg").toLowerCase())?e("agg").toLowerCase():"",bucket:["week","month"].includes(e("bucket").toLowerCase())?e("bucket").toLowerCase():"",smooth:e("smooth").toLowerCase()==="true"?7:Math.max(0,parseInt(e("smooth"),10)||0),fit:e("fit").toLowerCase()==="linear"?"linear":"none",formula:e("formula"),xmin:i("xmin"),xmax:i("xmax"),height:i("height")}}function G5(s){return s&&typeof s=="object"&&"basename"in s?s:null}function xl(s){let t=(s!=null?s:"").trim().match(/^(\d{4})-(\d{2})-(\d{2})/);return t?new Date(parseInt(t[1]),parseInt(t[2])-1,parseInt(t[3])):null}var qo=class extends Cl.MarkdownRenderChild{constructor(e,i,n){super(e);this.app=i;this.opts=n;this.chart=null}onload(){this.containerEl.addClass("csv-chart-block"),(async()=>(await this.render(),this.opts.file&&(this.registerEvent(this.app.vault.on("modify",e=>{e.path===this.opts.file&&this.render()})),this.registerEvent(this.app.vault.on("rename",(e,i)=>{i===this.opts.file&&(this.opts.file=e.path)})))))()}onunload(){this.chart&&(this.chart.destroy(),this.chart=null)}renderError(e){this.containerEl.empty(),this.containerEl.createEl("p",{text:`csv-chart: ${e}`,cls:"csv-add-error"})}async render(){var L,l,c,d,h;let e=this.containerEl;this.chart&&(this.chart.destroy(),this.chart=null),e.empty();let i,n=0;if(this.opts.file){let u=G5(this.app.vault.getAbstractFileByPath(this.opts.file));if(!u)return this.renderError(`File not found: ${this.opts.file}`);let f,g;try{({headers:f,rows:g}=kt(await this.app.vault.read(u)))}catch(x){return this.renderError(`Error reading file: ${x instanceof Error?x.message:String(x)}`)}let m=x=>{var k;return(k=f.find(E=>E.toLowerCase()===x.toLowerCase()))!=null?k:null},p=un(f,g),b=(L=f.find(x=>Et(x)))!=null?L:g.slice(0,5).length&&g.slice(0,5).every(x=>{var k;return xl((k=x[f[0]])!=null?k:"")})?f[0]:null,C=this.opts.x?m(this.opts.x):(l=b!=null?b:p[0])!=null?l:null;if(this.opts.x&&!C)return this.renderError(`No column "${this.opts.x}" in ${u.basename}`);let S=this.opts.y?m(this.opts.y):(c=p.find(x=>x!==C))!=null?c:null;if(this.opts.y&&!S)return this.renderError(`No column "${this.opts.y}" in ${u.basename}`);if(!C||!S)return this.renderError(`Couldn't auto-pick x/y columns \u2014 add "x:" and "y:" lines`);let _=this.opts.hue?m(this.opts.hue):null;if(this.opts.hue&&!_)return this.renderError(`No column "${this.opts.hue}" in ${u.basename}`);let y=this.opts.size?m(this.opts.size):null;if(this.opts.size&&!y)return this.renderError(`No column "${this.opts.size}" in ${u.basename}`);let v=C===b||Et(C);if(!v&&!p.includes(C)){let x=this.opts.agg||"count",k=jo(g,C,x==="count"?null:S,_,x);if(n=k.skipped,!k.categories.length)return this.renderError(`No rows with a "${C}" value to chart`);let E=x==="count"?"count":`${x}(${S})`;i={config:Uo(k,C,E,Ps(e)),fitText:null,formulaError:null}}else{let x=Wo(g,C,S,_,y,v,xl,A=>{var N;return(N=A[f[0]])!=null?N:""});if(n=x.skipped,!x.series.some(A=>A.points.length))return this.renderError(`No rows with numeric "${C}" and "${S}" values`);let k=v?this.opts.bucket:"",E=this.opts.agg||"sum",D={series:k?x.series.map(A=>({label:A.label,points:Zo(A.points,k,E)})):x.series,xIsDate:v,xLabel:C,yLabel:k?E==="count"?`count / ${k}`:`${E}(${S}) / ${k}`:S,connect:v,fit:this.opts.fit,formula:this.opts.formula,sizeLabel:k?"":y!=null?y:"",smoothDays:v&&!k?this.opts.smooth:0};i=fn(D,Ps(e))}}else{if(!this.opts.formula.trim())return this.renderError('Give a "file:" line, a "formula:" line, or both');i=fn({series:[],xIsDate:!1,xLabel:"x",yLabel:"y",connect:!1,fit:"none",formula:this.opts.formula,xMin:(d=this.opts.xmin)!=null?d:-10,xMax:(h=this.opts.xmax)!=null?h:10},Ps(e))}if(i.formulaError)return this.renderError(`formula: ${i.formulaError}`);let o=e.createDiv({cls:"csv-chart-wrap"});this.opts.height&&(o.style.height=this.opts.height+"px");let r=o.createEl("canvas",{cls:"csv-chart-canvas"});if(i.fitText||n>0){let u=e.createDiv({cls:"csv-chart-footer"});i.fitText&&u.createSpan({cls:"csv-chart-fit-text",text:i.fitText}),n>0&&u.createSpan({cls:"csv-chart-skipped",text:`${n} row${n===1?"":"s"} skipped (no numeric value)`})}let{Chart:a}=await ts();r.isConnected&&(this.chart=new a(r,i.config))}};function _l(s,t){t("csv-chart",(e,i,n)=>{var L,l,c;let o=Y5(e),r=(c=(l=(L=s.vault.getAbstractFileByPath(n.sourcePath))==null?void 0:L.parent)==null?void 0:l.path)!=null?c:"",a=o.file?Xt(o.file,r):o.file;n.addChild(new qo(i,s,{...o,file:a}))})}var re=require("obsidian"),kl=Ns(is());var _n=["Title","Type","Project","Priority","Due","Status","Notes"],K5={Title:fe,Type:["Type","type","Kind","kind","Item","item"],Project:["Project","project","Projects","projects","Area","area"],Priority:["Priority","priority","Prio","prio","Importance","importance"],Due:["Due","due","Deadline","deadline","Due Date","Due date","due date"],Status:["Status","status","State","state","Done","done"],Notes:pe};function q5(s){let t={};for(let e of _n)for(let i of K5[e]){let n=s.find(o=>o.toLowerCase()===i.toLowerCase());if(n){t[e]=n;break}}return!t.Title&&s.length&&(t.Title=s[0]),t}function X5(s){let t=[],e=[];return s.forEach((i,n)=>{let o=q5(i.headers);i.rows.forEach(r=>{var L;let a={};for(let l of _n)a[l]=o[l]&&(L=r[o[l]])!=null?L:"";o.Project||(a.Project=i.basename),t.push(a),e.push({sourceIndex:n,srcRow:r,map:o})})}),{headers:[..._n],rows:t,refs:e}}function Q5(s,t){var e;for(let i of _n){let n=t.map[i];n&&(t.srcRow[n]=(e=s[i])!=null?e:"")}}function J5(s){let t=s.split(` -`).map(n=>n.trim()).filter(Boolean),e=n=>{var o,r;return(r=(o=t.find(a=>a.toLowerCase().startsWith(n+":")))==null?void 0:o.slice(n.length+1).trim())!=null?r:""},i=parseInt(e("height"),10);return{folder:e("folder"),files:e("files").split(",").map(n=>n.trim()).filter(Boolean),height:Number.isFinite(i)&&i>0?i:null}}function Sl(s){return s&&typeof s=="object"&&"basename"in s?s:null}var Xo=class extends re.MarkdownRenderChild{constructor(e,i,n,o,r){super(e);this.app=i;this.settings=n;this.opts=o;this.notePath=r;this.headers=[];this.rows=[];this.searchQuery="";this.taskProjectFilter="all";this.taskTypeFilter="all";this.fileCfg={};this.sources=[];this.refs=[];this.saveTimer=null;this.contentArea=null}get contentEl(){return this.containerEl}get asView(){return this}onload(){if(this.containerEl.addClass("csv-inline-view","csv-tasks-block"),!this.opts.folder&&!this.opts.files.length){this.renderError('Give a "folder:" line ("/" = whole vault) and/or a "files:" list.');return}(async()=>(await this.reload(),this.renderView(),this.registerEvent(this.app.vault.on("modify",async e=>{let i=this.sources.find(r=>r.file.path===e.path);if(!i||this.saveTimer)return;let n=await this.app.vault.read(i.file);if(n===i.lastText)return;i.lastText=n;let o=kt(n);i.headers=o.headers,i.rows=o.rows,this.rebuild(),this.renderView()}))))()}onunload(){this.saveTimer&&window.clearTimeout(this.saveTimer)}renderError(e){this.containerEl.empty(),this.containerEl.createEl("p",{text:`csv-tasks: ${e}`,cls:"csv-add-error"})}async reload(){var n,o,r;let e=(r=(o=(n=this.app.vault.getAbstractFileByPath(this.notePath))==null?void 0:n.parent)==null?void 0:o.path)!=null?r:"",i=new Map;for(let a of this.opts.files){let L=Sl(this.app.vault.getAbstractFileByPath(Xt(a,e)));if(!L){this.renderError(`File not found: ${a}`);continue}i.set(L.path,{file:L,explicit:!0})}if(this.opts.folder){let a=this.opts.folder==="/"?"":this.opts.folder.replace(/\/$/,"")+"/";for(let L of this.app.vault.getFiles())L.extension==="csv"&&(a&&!L.path.startsWith(a)||i.has(L.path)||i.set(L.path,{file:L,explicit:!1}))}this.sources=[];for(let{file:a,explicit:L}of i.values())try{let l=await this.app.vault.read(a),{headers:c,rows:d}=kt(l);(L||Ie({headers:c,rows:d,resolveCol:u=>{var f;return(f=u.map(g=>c.find(m=>m.toLowerCase()===g.toLowerCase())).find(Boolean))!=null?f:null}}))&&this.sources.push({file:a,headers:c,rows:d,lastText:l})}catch(l){}this.rebuild()}rebuild(){let e=X5(this.sources.map(i=>({basename:i.file.basename,headers:i.headers,rows:i.rows})));this.headers=e.headers,this.rows=e.rows,this.refs=e.refs}refOf(e){let i=this.rows.indexOf(e);return i>=0?this.refs[i]:null}sourceOf(e){var n;let i=this.refOf(e);return i&&(n=this.sources[i.sourceIndex])!=null?n:null}scheduleSave(){this.saveTimer&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>void this.doSave(),600)}async doSave(){this.saveTimer=null,this.rows.forEach((e,i)=>Q5(e,this.refs[i]));for(let e of this.sources){let i=kl.default.unparse(e.rows,{columns:e.headers});if(i!==e.lastText)try{try{let n=await this.app.vault.read(e.file);n!==e.lastText&&n!==i&&await ls(this.app,e.file,n)}catch(n){}e.lastText=i,await this.app.vault.modify(e.file,i)}catch(n){new re.Notice(`Couldn't save ${e.file.name}: ${n instanceof Error?n.message:String(n)}`,8e3)}}}resolveCol(e){for(let i of e){let n=this.headers.find(o=>o.toLowerCase()===i.toLowerCase());if(n)return n}return null}titleKey(){return"Title"}getStatusCol(){return"Status"}getCategoryCol(){return null}getDateCol(){return null}getNotesCol(){return"Notes"}isNotesCol(e){return e==="Notes"}isDateCol(e){return e==="Due"}getTitle(e){return e.Title||"\u2014"}getColumnValues(e){return Array.from(new Set(this.rows.map(i=>{var n;return(n=i[e])!=null?n:""}).filter(Boolean))).sort()}renderViewPreservingScroll(){this.renderView()}renderView(e=!1){let i=this.containerEl;if(e)this.contentArea&&this.contentArea.empty();else{i.empty();let n=i.createDiv({cls:"csv-toolbar csv-inline-toolbar"});n.createDiv({cls:"csv-toolbar-title",text:"Tasks"}),n.createDiv({cls:"csv-row-count",text:`${this.rows.length} entries \xB7 ${this.sources.length} file${this.sources.length===1?"":"s"}`}),this.contentArea=i.createDiv({cls:"csv-content-area"}),this.opts.height&&(this.contentArea.style.maxHeight=this.opts.height+"px")}if(this.contentArea){if(!this.sources.length){this.contentArea.createEl("p",{text:"No task-shaped CSV files found.",cls:"csv-empty-state"});return}bn(this.asView,this.contentArea)}}openNoteExpander(e,i){var L;let n=this.refOf(e),o=this.sourceOf(e);if(!n||!o)return;let r=(L=n.map.Notes)!=null?L:"",a=l=>l===n.map.Notes;new me(this.app,n.srcRow,r,o.headers,o.file.path,a,()=>!1,l=>Array.from(new Set(o.rows.map(c=>{var d;return(d=c[l])!=null?d:""}).filter(Boolean))).sort(),l=>{var c;Object.assign(n.srcRow,l);for(let d of Object.keys(e)){let h=n.map[d];h&&(e[d]=(c=n.srcRow[h])!=null?c:"")}this.scheduleSave(),this.renderView()},()=>this.deleteRow(e),void 0,n.map.Title,void 0,l=>/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(l)).open()}async openOrCreateNotes(e){let i=this.sourceOf(e);if(!i)return;let n=this.notesFilePath(e,i),o=Sl(this.app.vault.getAbstractFileByPath(n));if(!o){let r=["---",`source: "[[${i.file.path}]]"`,"---","",`# ${this.getTitle(e)}`,"",""].join(` -`),a=n.substring(0,n.lastIndexOf("/"));a&&!this.app.vault.getAbstractFileByPath(a)&&await this.app.vault.createFolder(a),o=await this.app.vault.create(n,r),new re.Notice(`Created: ${o.name}`)}await this.app.workspace.getLeaf("tab").openFile(o)}notesFileExists(e){let i=this.sourceOf(e);return!!i&&!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e,i))}notesFilePath(e,i){var L,l;let n=Ve(this.getTitle(e)),o=(l=(L=i.file.parent)==null?void 0:L.path)!=null?l:"",r=this.settings.notesSubfolder.trim(),a=r?o?`${o}/${r}`:r:o;return(0,re.normalizePath)(`${a}/${n}.md`)}deleteRow(e){let i=this.refOf(e),n=this.sourceOf(e);if(!i||!n)return;let o=n.rows.indexOf(i.srcRow);o>=0&&n.rows.splice(o,1);let r=this.rows.indexOf(e);r>=0&&(this.rows.splice(r,1),this.refs.splice(r,1)),this.scheduleSave(),this.renderView(),new re.Notice(`Deleted \u201C${this.getTitle(e)}\u201D from ${n.file.name}`)}openRowContextMenu(e,i){let n=this.sourceOf(e),o=new re.Menu;o.addItem(r=>r.setTitle("Open entry").setIcon("maximize").onClick(()=>this.openNoteExpander(e,"Notes"))),n&&o.addItem(r=>r.setTitle(`Open source: ${n.file.name}`).setIcon("file-spreadsheet").onClick(()=>void this.app.workspace.getLeaf("tab").openFile(n.file))),o.addSeparator(),o.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteRow(e))),o.showAtMouseEvent(i)}};function El(s,t,e){e("csv-tasks",(i,n,o)=>{o.addChild(new Xo(n,s,t,J5(i),o.sourcePath))})}var Ml='';var Fs=class extends at.FileView{constructor(e,i,n){super(e);this.headers=[];this.rows=[];this.saveTimer=null;this.searchQuery="";this.lastDiskContent=null;this.contentArea=null;this.selectedDate=null;this.selectedHabit=null;this.chartInstance=null;this.timelineYear=new Date().getFullYear();this.libraryStatusFilter="all";this.libraryGenreFilter="all";this.collapsedGroups=new Set;this.taskProjectFilter="all";this.taskTypeFilter="all";this.focusIndex=0;this.focusNavPending=!1;this.tableSortCol=null;this.tableSortDir="asc";this.settings=i,this.persistSettings=n,this.mode=i.defaultMode,this.renderComponent=new at.Component,this.renderComponent.load()}getViewType(){return ui}getDisplayText(){var e,i;return(i=(e=this.file)==null?void 0:e.basename)!=null?i:"Card View"}getIcon(){return"table"}onload(){super.onload(),this.registerEvent(this.app.vault.on("modify",e=>{!this.file||e.path!==this.file.path||this.syncFromDisk()}))}async syncFromDisk(){if(!this.file)return;let e=await this.app.vault.read(this.file);if(e===this.lastDiskContent||this.saveTimer)return;this.lastDiskContent=e;let i=kt(e);this.headers=i.headers,this.rows=i.rows,this.renderViewPreservingScroll()}async onLoadFile(e){var o;try{let r=await this.app.vault.read(e),a=kt(r);this.headers=a.headers,this.rows=a.rows,this.lastDiskContent=r}catch(r){console.error("CardView load error",r),this.headers=[],this.rows=[],this.lastDiskContent=null,new at.Notice(`Couldn't read ${e.name}: ${r instanceof Error?r.message:String(r)}`,8e3)}this.file&&((o=this.settings.fileConfigs[this.file.path])!=null&&o.defaultMode)?this.mode=this.settings.fileConfigs[this.file.path].defaultMode:this.isTravelFile()?this.mode="travel":this.hasDateColumn()?this.mode="dashboard":this.mode=this.settings.defaultMode;let i=this.mode==="kanban-genre"||this.mode==="library",n=this.mode==="dashboard";(i&&!Rt(this)||n&&!this.hasDateColumn()||this.mode==="travel"&&!this.isTravelFile()||this.mode==="stats"&&!Si(this)||this.mode==="chart"&&!pn(this)||this.mode==="tasks"&&!Ie(this)||this.mode==="budget"&&!yn(this))&&(this.mode="table"),this.selectedDate=null,this.focusIndex=0,this.tableSortCol=null,this.renderView()}async onUnloadFile(e){this.chartInstance&&(this.chartInstance.destroy(),this.chartInstance=null),this.headers=[],this.rows=[],this.contentEl.empty()}scheduleSave(){this.saveTimer&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.doSave()},600)}async doSave(){if(this.file)try{let e=wl.default.unparse(this.rows,{columns:this.headers});try{let i=await this.app.vault.read(this.file);this.lastDiskContent!==null&&i!==this.lastDiskContent&&i!==e&&await ls(this.app,this.file,i)}catch(i){}this.lastDiskContent=e,await this.app.vault.modify(this.file,e)}catch(e){console.error("CardView save error",e),new at.Notice(`Couldn't save ${this.file.name}: ${e instanceof Error?e.message:String(e)}`,8e3)}}get fileCfg(){var e;return this.file?(e=this.settings.fileConfigs[this.file.path])!=null?e:{}:{}}saveFileCfg(e){this.file&&(this.settings.fileConfigs[this.file.path]=e,this.persistSettings())}isHighlighted(e){var i;return((i=this.fileCfg.highlightedTitles)!=null?i:[]).includes(this.getTitle(e))}toggleHighlight(e){let i=this.getTitle(e),n=this.fileCfg,o=n.highlightedTitles?[...n.highlightedTitles]:[],r=o.indexOf(i);r>=0?o.splice(r,1):o.push(i),n.highlightedTitles=o,this.saveFileCfg(n)}addColumn(e){let i=e.trim();return i?this.headers.some(n=>n.toLowerCase()===i.toLowerCase())?`"${i}" already exists.`:(this.headers.push(i),this.rows.forEach(n=>{n[i]=""}),this.scheduleSave(),this.renderViewPreservingScroll(),null):"Column name can't be empty."}removeColumn(e){this.headers=this.headers.filter(n=>n!==e),this.rows.forEach(n=>{delete n[e]});let i=this.fileCfg;i.categoryColumn===e&&(i.categoryColumn=void 0),i.statusColumn===e&&(i.statusColumn=void 0),i.notesColumn===e&&(i.notesColumn=void 0),i.ankiFrontCol===e&&(i.ankiFrontCol=void 0),i.kanbanGroupCol===e&&(i.kanbanGroupCol=void 0),i.habitColumns&&(i.habitColumns=i.habitColumns.filter(n=>n!==e)),i.cardFields&&(i.cardFields=i.cardFields.filter(n=>n!==e)),i.categoricalColumns&&(i.categoricalColumns=i.categoricalColumns.filter(n=>n!==e)),this.saveFileCfg(i),this.scheduleSave(),this.renderViewPreservingScroll()}resolveCol(e){for(let i of e){let n=this.headers.find(o=>o.toLowerCase()===i.toLowerCase());if(n)return n}return null}getNotesCol(){return this.fileCfg.notesColumn!==void 0?this.fileCfg.notesColumn===""?null:this.fileCfg.notesColumn:this.resolveCol(pe)}isNotesCol(e){let i=this.getNotesCol();return i?e===i:this.settings.notesColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var n;let i=(n=this.titleKey())!=null?n:this.headers[0];return e===i||this.isDateCol(e)||vt(e)?!1:this.fileCfg.categoricalColumns?this.fileCfg.categoricalColumns.includes(e):this.isSelectCol(e)||qt(this.getColumnValues(e).length)}autoDetectCategoricalColumns(){var i;let e=(i=this.titleKey())!=null?i:this.headers[0];return this.headers.filter(n=>n===e||this.isDateCol(n)||vt(n)||this.isNotesCol(n)?!1:this.isSelectCol(n)||qt(this.getColumnValues(n).length))}isDateCol(e){var i;return(i=this.fileCfg.dateColumns)!=null&&i.includes(e)?!0:Et(e)}getStatusCol(){var e;return this.fileCfg.statusColumn!==void 0?this.fileCfg.statusColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(rs)}getCategoryCol(){var e;return this.fileCfg.categoryColumn!==void 0?this.fileCfg.categoryColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(os)}titleKey(){var e,i;return this.fileCfg.titleColumn!==void 0?this.fileCfg.titleColumn===""?void 0:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(i=this.resolveCol(fe))!=null?i:void 0}authorKey(){var e;return(e=this.resolveCol(["Author","author","Authors","authors","Director","director","Artist","artist","Creator","creator","By","by"]))!=null?e:void 0}getTitle(e){var n;let i=this.titleKey();return(n=i?e[i]:e[this.headers[0]])!=null?n:"\u2014"}getSubtitle(e){var n;let i=this.authorKey();return i&&(n=e[i])!=null?n:""}getColumnValues(e){return Array.from(new Set(this.rows.map(i=>{var n;return((n=i[e])!=null?n:"").trim()}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn!==void 0?this.fileCfg.imageColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(ns)}notesFilePath(e){var a,L,l;let i=Ve(this.getTitle(e)),n=(l=(L=(a=this.file)==null?void 0:a.parent)==null?void 0:L.path)!=null?l:"",o=this.settings.notesSubfolder.trim(),r=o?n?`${n}/${o}`:o:n;return(0,at.normalizePath)(`${r}/${i}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}deleteWithUndo(e){let i=this.rows.indexOf(e);if(i<0)return;this.rows.splice(i,1),this.scheduleSave(),this.renderViewPreservingScroll();let n=this.getTitle(e)||"entry",o=createFragment();o.createSpan({text:`Deleted \u201C${n}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new at.Notice(o,6e3);r.addEventListener("click",()=>{if(r.hasAttribute("disabled"))return;r.setAttribute("disabled","true");let L=Math.min(i,this.rows.length);this.rows.splice(L,0,e),this.scheduleSave(),this.renderViewPreservingScroll(),a.hide(),new at.Notice(`Restored \u201C${n}\u201D`,2500)})}openRowContextMenu(e,i){let n=new at.Menu;n.addItem(a=>a.setTitle("Open / create notes file").setIcon("file-text").onClick(()=>this.openOrCreateNotes(e))),n.addItem(a=>a.setTitle("Open entry").setIcon("maximize").onClick(()=>{var L;return this.openNoteExpander(e,(L=this.getNotesCol())!=null?L:"")}));let o=this.getStatusCol();if(o){let a=this.getColumnValues(o);a.length&&(n.addSeparator(),a.forEach(L=>{L!==e[o]&&n.addItem(l=>l.setTitle(`Mark as: ${L}`).onClick(()=>{e[o]=L,this.scheduleSave(),this.renderViewPreservingScroll()}))}))}n.addSeparator();let r=this.isHighlighted(e);n.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderViewPreservingScroll()})),n.addSeparator(),n.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),n.showAtMouseEvent(i)}async openOrCreateNotes(e){var o,r;let i=this.notesFilePath(e),n=this.app.vault.getAbstractFileByPath(i);if(!n){let a={},L=Ie(this)?Go(this):null,l=L?((o=e[L])!=null?o:"").split(",").map(f=>ir(f.trim())).filter(Boolean).map(f=>`project-${f}`):[];l.length&&(a.tags=l);for(let f of this.headers)!this.isNotesCol(f)&&e[f]&&(a[f]=e[f]);this.file&&!Object.keys(a).some(f=>f.toLowerCase()==="source")&&(a.source=`[[${this.file.path}]]`);let c=["---",(0,at.stringifyYaml)(a).trimEnd(),"---","",`# ${this.getTitle(e)}`,"",""].join(` -`),d=this.headers.find(f=>this.isNotesCol(f)),h=c+(d&&((r=e[d])!=null&&r.trim())?e[d]:""),u=i.substring(0,i.lastIndexOf("/"));u&&!this.app.vault.getAbstractFileByPath(u)&&await this.app.vault.createFolder(u),n=await this.app.vault.create(i,h),new at.Notice(`Created: ${n.name}`)}await this.app.workspace.getLeaf("tab").openFile(n)}openNoteExpander(e,i){var n,o;new me(this.app,e,i,this.headers,(o=(n=this.file)==null?void 0:n.path)!=null?o:"",this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),r=>{Object.assign(e,r),this.scheduleSave(),this.renderViewPreservingScroll()},()=>this.deleteWithUndo(e),r=>this.isCategoricalCol(r),this.titleKey(),r=>this.getBooleanColumns().includes(r),r=>this.isDateCol(r)).open()}renderViewPreservingScroll(){var L,l,c,d,h;let e=this.contentEl,i=e.querySelector(".csv-content-area"),n=e.querySelector(".csv-table-wrapper"),o=e.querySelector(".csv-kanban-board"),r={contentTop:(L=i==null?void 0:i.scrollTop)!=null?L:0,contentLeft:(l=i==null?void 0:i.scrollLeft)!=null?l:0,tableLeft:(c=n==null?void 0:n.scrollLeft)!=null?c:0,tableTop:(d=n==null?void 0:n.scrollTop)!=null?d:0,boardLeft:(h=o==null?void 0:o.scrollLeft)!=null?h:0,cols:new Map};e.querySelectorAll(".csv-kanban-col").forEach(u=>{var m,p;let f=(p=(m=u.querySelector(".csv-kanban-col-title"))==null?void 0:m.textContent)!=null?p:"",g=u.querySelector(".csv-kanban-col-body");f&&g&&r.cols.set(f,g.scrollTop)}),this.renderView();let a=()=>{let u=this.contentEl.querySelector(".csv-content-area"),f=this.contentEl.querySelector(".csv-table-wrapper"),g=this.contentEl.querySelector(".csv-kanban-board");u&&(u.scrollTop=r.contentTop,u.scrollLeft=r.contentLeft),f&&(f.scrollLeft=r.tableLeft,f.scrollTop=r.tableTop),g&&(g.scrollLeft=r.boardLeft),this.contentEl.querySelectorAll(".csv-kanban-col").forEach(m=>{var S,_;let p=(_=(S=m.querySelector(".csv-kanban-col-title"))==null?void 0:S.textContent)!=null?_:"",b=m.querySelector(".csv-kanban-col-body"),C=r.cols.get(p);b&&C!=null&&(b.scrollTop=C)})};a(),window.requestAnimationFrame(()=>{a(),window.requestAnimationFrame(a)}),window.setTimeout(a,50)}openAddModal(){let e={};if(Ie(this)){let i=gn(this);i&&(e[i]=["Task","Note","Idea"]);let n=mn(this);n&&(e[n]=["Low","Medium","High"])}new cs(this.app,this.headers,this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),i=>{this.rows.push(i),this.scheduleSave(),this.renderViewPreservingScroll(),new at.Notice(`Added: ${this.getTitle(i)}`)},e,i=>this.getBooleanColumns().includes(i),i=>this.isCategoricalCol(i),this.titleKey(),i=>this.isDateCol(i)).open()}renderSelectField(e,i,n){var a;let o=(a=i[n])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),n.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",L=>{var l;L.stopPropagation(),$t(r,(l=i[n])!=null?l:"",this.getColumnValues(n),c=>{i[n]=c,r.setText(c||"\u2014"),r.className=`csv-select-chip ${c?"":"empty"}`,n.toLowerCase()==="status"&&c&&r.addClass(`status-chip-${c.toLowerCase().replace(/\s+/g,"-")}`),this.scheduleSave()},this.contentEl,{multi:vt(n)})}),r}renderView(e=!1){var o;let i=this.contentEl;e?this.contentArea&&this.contentArea.empty():(i.empty(),i.addClass("datadeck-root"),this.renderComponent.unload(),this.renderComponent=new at.Component,this.renderComponent.load(),fl(this,i),this.contentArea=i.createDiv({cls:"csv-content-area"}),this.installTouchScrollGuard(this.contentArea));let n=this.contentArea;if(n){if(n.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){let r=n.createDiv({cls:"csv-empty-state csv-empty-state--big"});r.createEl("h3",{text:"This file is empty"}),r.createEl("p",{text:"Add a header row in your spreadsheet app, then come back \u2014 or click + add in the toolbar to start fresh."});return}if(this.rows.length===0){let r=n.createDiv({cls:"csv-empty-state csv-empty-state--big"});r.createEl("h3",{text:"No entries yet"}),r.createEl("button",{cls:"csv-empty-state-action",text:"+ add the first entry"}).addEventListener("click",()=>this.openAddModal()),r.createEl("p",{cls:"csv-empty-state-hint",text:`${this.headers.length} column${this.headers.length===1?"":"s"} detected: ${this.headers.slice(0,5).join(", ")}${this.headers.length>5?"\u2026":""}`});return}this.mode==="travel"?br(n,this.rows,()=>this.loadMapSvg(),()=>this.scheduleSave(),this.settings.showResidency===!1?null:(o=this.settings.residencyRules)!=null?o:null,r=>this.renderComponent.register(r)):this.mode==="dashboard"?gl(this,n):this.mode==="library"?Ei(this,n):this.mode==="kanban-genre"?ki(this,n):this.mode==="stats"?Sr(this,n):this.mode==="chart"?al(this,n):this.mode==="focus"?ml(this,n):this.mode==="tasks"?bn(this,n):this.mode==="budget"?ul(this,n):_i(this,n)}}installTouchScrollGuard(e){if(!matchMedia("(pointer: coarse)").matches)return;let i=0,n=0,o=!1;e.addEventListener("touchstart",r=>{r.touches.length===1&&(i=r.touches[0].clientX,n=r.touches[0].clientY,o=!1)},{capture:!0,passive:!0}),e.addEventListener("touchmove",r=>{if(r.touches.length!==1||o)return;let a=Math.abs(r.touches[0].clientX-i),L=Math.abs(r.touches[0].clientY-n);(a>10||L>10)&&(o=!0)},{capture:!0,passive:!0}),e.addEventListener("click",r=>{o&&(r.preventDefault(),r.stopImmediatePropagation())},!0)}async backupToArchive(){var a,L;if(!this.file)return;let e=(L=(a=this.file.parent)==null?void 0:a.path)!=null?L:"",i=e?`${e}/Archive`:"Archive";await this.app.vault.adapter.exists(i)||await this.app.vault.adapter.mkdir(i);let n=this.formatDate(new Date),o=`${i}/${this.file.basename}_${n}.${this.file.extension}`;if(await this.app.vault.adapter.exists(o)){new at.Notice(`Backup already exists for today: ${o}`);return}let r=await this.app.vault.readBinary(this.file);await this.app.vault.adapter.writeBinary(o,r),new at.Notice(`Backed up to ${o}`)}hasDateColumn(){return this.getDateCol()!==null}isTravelFile(){let e=new Set(this.headers.map(i=>i.toLowerCase()));return e.has("country")&&e.has("date_entered")&&e.has("date_left")&&e.has("source")}async loadMapSvg(){return Ml}getFilteredRows(){var n;let e=this.rows;if(this.searchQuery.trim()){let o=this.searchQuery.toLowerCase().trim();e=e.filter(r=>this.headers.some(a=>{var l;return((l=r[a])!=null?l:"").toLowerCase().includes(o)}))}if(this.mode==="table"&&this.tableSortCol&&this.headers.includes(this.tableSortCol))return nr(e,this.tableSortCol,this.tableSortDir);let i=this.getDateCol();if(this.mode==="table"&&i){let o=(n=this.fileCfg.sortNewestFirst)!=null?n:!0;e=[...e].sort((r,a)=>{var d,h;let L=(d=r[i])!=null?d:"",l=(h=a[i])!=null?h:"",c=L.localeCompare(l);return o?-c:c})}return e}getDateCol(){var a;if(this.fileCfg.dateColumns&&this.fileCfg.dateColumns.length>0){let L=this.fileCfg.dateColumns[0];return(a=this.headers.find(l=>l===L))!=null?a:null}if(this.headers.length===0)return null;let e=this.headers[0],i=e.toLowerCase();if(["date","day","datum"].includes(i))return e;let n=this.rows.slice(0,5),o=/^\d{4}-\d{2}-\d{2}$/;return n.length>0&&n.every(L=>{var l;return o.test((l=L[e])!=null?l:"")})?e:null}getBooleanColumns(){return this.fileCfg.habitColumns?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.autoDetectBooleanColumns()}cleanupBooleanColumn(e){let i=0;return this.rows.forEach(n=>{var r;let o=this.isTruthy((r=n[e])!=null?r:"")?"1":"0";n[e]!==o&&i++,n[e]=o}),i>0&&(this.scheduleSave(),this.renderViewPreservingScroll()),i}autoDetectBooleanColumns(){return this.headers.filter(e=>{if(e===this.getDateCol()||this.isNotesCol(e))return!1;let i=this.rows.map(n=>{var o;return((o=n[e])!=null?o:"").toLowerCase().trim()});return as(i)})}parseDate(e){let i=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);return i?new Date(parseInt(i[1]),parseInt(i[2])-1,parseInt(i[3])):null}formatDate(e){let i=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${i}-${n}-${o}`}isTruthy(e){return Ls(e)}renderMarkdownInto(e,i){var n,o;at.MarkdownRenderer.render(this.app,i,e,(o=(n=this.file)==null?void 0:n.path)!=null?o:"",this.renderComponent)}cycleMode(){let e=xn(this);if(e.length<2)return;let i=e.findIndex(n=>n.id===this.mode);this.mode=e[(i+1)%e.length].id,this.renderView()}onunload(){this.renderComponent.unload(),this.saveTimer&&window.clearTimeout(this.saveTimer)}},eh=[{id:"tasks",command:"Create tasks file",defaultName:"Tasks",headers:["Title","Type","Project","Priority","Due","Status","Notes"],mode:"tasks",configOverrides:{categoricalColumns:["Type","Priority"],dateColumns:["Due"],statusColumn:"Status",notesColumn:"Notes"}},{id:"travel",command:"Create travel file",defaultName:"Travel",headers:["date_entered","date_left","country","city","visa_status","notes","source","resolved"],mode:"travel"},{id:"habits",command:"Create habit tracker file",defaultName:"Habits",headers:["Date","Exercise","Meditate","Read","Notes"],mode:"dashboard",configOverrides:{habitColumns:["Exercise","Meditate","Read"],notesColumn:"Notes",statusColumn:""}},{id:"chart",command:"Create chart file",defaultName:"Measurements",headers:["Date","Value","Notes"],mode:"chart",configOverrides:{chartYCol:"Value",chartFit:"linear",notesColumn:"Notes"}},{id:"budget",command:"Create budget file",defaultName:"Budget",headers:["Date","Item","Type","Price","Notes"],mode:"budget",configOverrides:{titleColumn:"Item",categoricalColumns:["Type"],notesColumn:"Notes",habitColumns:[]}}],Sn=class extends at.Plugin{constructor(){super(...arguments);this.settings=Dn}async onload(){await this.loadSettings(),this.registerView(ui,e=>new Fs(e,this.settings,()=>this.saveSettings())),this.registerExtensions(["csv"],ui),this.addSettingTab(new Ci(this.app,this)),this.registerMarkdownCodeBlockProcessor("csv-add",async(e,i,n)=>{await yr(this.app,e.trim(),i,n,this.settings.fileConfigs)}),this.registerMarkdownCodeBlockProcessor("csv-random",async(e,i,n)=>{await pl(this.app,e.trim(),i,n)}),yl(this.app,this.settings,()=>this.saveSettings(),(e,i)=>this.registerMarkdownCodeBlockProcessor(e,i)),_l(this.app,(e,i)=>this.registerMarkdownCodeBlockProcessor(e,i)),El(this.app,this.settings,(e,i)=>this.registerMarkdownCodeBlockProcessor(e,i)),this.addCommand({id:"add-entry",name:"Add entry to current CSV",checkCallback:e=>{let i=this.app.workspace.getActiveViewOfType(Fs);return i?(e||i.openAddModal(),!0):!1}}),this.addCommand({id:"cycle-view-mode",name:"Cycle view mode",checkCallback:e=>{let i=this.app.workspace.getActiveViewOfType(Fs);return i?(e||i.cycleMode(),!0):!1}});for(let e of eh)this.addCommand({id:`create-${e.id}`,name:e.command,callback:()=>this.createTemplateFile(e)});this.registerEvent(this.app.vault.on("rename",async(e,i)=>{e instanceof at.TFile&&e.extension==="csv"&&this.settings.fileConfigs[i]&&(lr(this.settings.fileConfigs,i,e.path),await this.saveSettings())})),this.registerEvent(this.app.vault.on("delete",async e=>{e instanceof at.TFile&&this.settings.fileConfigs[e.path]&&(delete this.settings.fileConfigs[e.path],await this.saveSettings())})),this.registerMarkdownCodeBlockProcessor("csv-refresh",(e,i,n)=>{i.createEl("button",{cls:"csv-refresh-btn",text:"\u21BB refresh"}).addEventListener("click",()=>{(async()=>{let r=n.sourcePath,a=this.app.vault.getAbstractFileByPath(r);a instanceof at.TFile&&await this.app.workspace.getLeaf(!1).openFile(a,{state:{mode:"preview"}})})()})})}async createTemplateFile(e){new Ne(this.app,e.command,e.defaultName,"File name (without .csv)",i=>{(async()=>{let n=this.app.workspace.getActiveFile(),o=n!=null&&n.parent&&n.parent.path!=="/"?`${n.parent.path}/`:"",r=Ve(i),a=(0,at.normalizePath)(`${o}${r}.csv`);for(let c=2;this.app.vault.getAbstractFileByPath(a);c++)a=(0,at.normalizePath)(`${o}${r} ${c}.csv`);let L=await this.app.vault.create(a,e.headers.join(",")+` -`),l=this.settings.fileConfigs[L.path]||{};this.settings.fileConfigs[L.path]={...l,defaultMode:e.mode,...e.configOverrides||{}},await this.saveSettings(),await this.app.workspace.getLeaf("tab").openFile(L),new at.Notice(`Created: ${L.name}`)})()}).open()}async loadSettings(){var i;let e=await this.loadData();this.settings=Object.assign({},Dn,e),this.settings.residencyRules=JSON.parse(JSON.stringify((i=this.settings.residencyRules)!=null?i:[]))}async saveSettings(){await this.saveData(this.settings)}}; +`):s}function t5(s,t){let{element:e,datasetIndex:i,index:n}=t,o=s.getDatasetMeta(i).controller,{label:r,value:a}=o.getLabelAndValue(n);return{chart:s,label:r,parsed:o.getParsed(n),raw:s.data.datasets[i].data[n],formattedValue:a,dataset:o.getDataset(),dataIndex:n,datasetIndex:i,element:e}}function aL(s,t){let e=s.chart.ctx,{body:i,footer:n,title:o}=s,{boxWidth:r,boxHeight:a}=t,L=gt(t.bodyFont),l=gt(t.titleFont),c=gt(t.footerFont),d=o.length,h=n.length,u=i.length,f=Ct(t.padding),g=f.height,m=0,p=i.reduce((S,_)=>S+_.before.length+_.lines.length+_.after.length,0);if(p+=s.beforeBody.length+s.afterBody.length,d&&(g+=d*l.lineHeight+(d-1)*t.titleSpacing+t.titleMarginBottom),p){let S=t.displayColors?Math.max(a,L.lineHeight):L.lineHeight;g+=u*S+(p-u)*L.lineHeight+(p-1)*t.bodySpacing}h&&(g+=t.footerMarginTop+h*c.lineHeight+(h-1)*t.footerSpacing);let b=0,C=function(S){m=Math.max(m,e.measureText(S).width+b)};return e.save(),e.font=l.string,Lt(s.title,C),e.font=L.string,Lt(s.beforeBody.concat(s.afterBody),C),b=t.displayColors?r+2+t.boxPadding:0,Lt(i,S=>{Lt(S.before,C),Lt(S.lines,C),Lt(S.after,C)}),b=0,e.font=c.string,Lt(s.footer,C),e.restore(),m+=f.width,{width:m,height:g}}function e5(s,t){let{y:e,height:i}=t;return es.height-i/2?"bottom":"center"}function s5(s,t,e,i){let{x:n,width:o}=i,r=e.caretSize+e.caretPadding;if(s==="left"&&n+o+r>t.width||s==="right"&&n-o-r<0)return!0}function i5(s,t,e,i){let{x:n,width:o}=e,{width:r,chartArea:{left:a,right:L}}=s,l="center";return i==="center"?l=n<=(a+L)/2?"left":"right":n<=o/2?l="left":n>=r-o/2&&(l="right"),s5(l,s,t,e)&&(l="center"),l}function LL(s,t,e){let i=e.yAlign||t.yAlign||e5(s,e);return{xAlign:e.xAlign||t.xAlign||i5(s,t,e,i),yAlign:i}}function n5(s,t){let{x:e,width:i}=s;return t==="right"?e-=i:t==="center"&&(e-=i/2),e}function o5(s,t,e){let{y:i,height:n}=s;return t==="top"?i+=e:t==="bottom"?i-=n+e:i-=n/2,i}function lL(s,t,e,i){let{caretSize:n,caretPadding:o,cornerRadius:r}=s,{xAlign:a,yAlign:L}=e,l=n+o,{topLeft:c,topRight:d,bottomLeft:h,bottomRight:u}=Me(r),f=n5(t,a),g=o5(t,L,l);return L==="center"?a==="left"?f+=l:a==="right"&&(f-=l):a==="left"?f-=Math.max(c,h)+n:a==="right"&&(f+=Math.max(d,u)+n),{x:mt(f,0,i.width-t.width),y:mt(g,0,i.height-t.height)}}function Qi(s,t,e){let i=Ct(e.padding);return t==="center"?s.x+s.width/2:t==="right"?s.x+s.width-i.right:s.x+i.left}function cL(s){return ie([],ue(s))}function r5(s,t,e){return he(s,{tooltip:t,tooltipItems:e,type:"tooltip"})}function dL(s,t){let e=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return e?s.override(e):s}function Ft(s,t,e,i){let n=s[t].call(e,i);return typeof n=="undefined"?XL[t].call(e,i):n}function L5(s,t,e,i){let n=s.indexOf(t);if(n===-1)return a5(s,t,e,i);let o=s.lastIndexOf(t);return n!==o?e:n}function hL(s){let t=this.getLabels();return s>=0&&sf&&(_=Yn(k*_/f/u)*u),st(L)||(y=Math.pow(10,L),_=Math.ceil(_*y)/y),n==="ticks"?(v=Math.floor(g/_)*_,x=Math.ceil(m/_)*_):(v=g,x=m),p&&b&&o&&Qr((a-r)/o,_/1e3)?(k=Math.round(Math.min((a-r)/_,c)),_=(a-r)/k,v=r,x=a):C?(v=p?r:v,x=b?a:x,k=l-1,_=(x-v)/k):(k=(x-v)/_,bs(k,Math.round(k),_/1e3)?k=Math.round(k):k=Math.ceil(k));let E=Math.max(Kn(_),Kn(v));y=Math.pow(10,st(L)?E:L),v=Math.round(v*y)/y,x=Math.round(x*y)/y;let M=0;for(p&&(h&&v!==r?(e.push({value:r}),va)break;e.push({value:D})}return b&&h&&x!==a?e.length&&bs(e[e.length-1].value,a,uL(a,S,s))?e[e.length-1].value=a:e.push({value:a}):(!b||x===a)&&e.push({value:x}),e}function uL(s,t,{horizontal:e,minRotation:i}){let n=Zt(i),o=(e?Math.sin(n):Math.cos(n))||.001,r=.75*t*(""+s).length;return Math.min(t/o,r)}function fL(s){return s/Math.pow(10,di(s))===1}function pL(s,t,e){let i=Math.pow(10,e),n=Math.floor(s/i);return Math.ceil(t/i)-n}function d5(s,t){let e=t-s,i=di(e);for(;pL(s,t,i)>10;)i++;for(;pL(s,t,i)<10;)i--;return Math.min(i,di(s))}function h5(s,{min:t,max:e}){t=Ot(s.min,t);let i=[],n=di(t),o=d5(t,e),r=o<0?Math.pow(10,Math.abs(o)):1,a=Math.pow(10,o),L=n>o?Math.pow(10,n):0,l=Math.round((t-L)*r)/r,c=Math.floor((t-L)/a/10)*a*10,d=Math.floor((l-c)/Math.pow(10,o)),h=Ot(s.min,Math.round((L+c+d*Math.pow(10,o))*r)/r);for(;h=10?d=d<15?15:20:d++,d>=20&&(o++,d=2,r=o>=0?1:r),h=Math.round((L+c+d*Math.pow(10,o))*r)/r;let u=Ot(s.max,h);return i.push({value:u,major:fL(u),significand:d}),i}function zo(s){let t=s.ticks;if(t.display&&s.display){let e=Ct(t.backdropPadding);return tt(t.font&&t.font.size,ut.font.size)+e.height}return 0}function u5(s,t,e){return e=dt(e)?e:[e],{w:aa(s,t.string,e),h:e.length*t.lineHeight}}function gL(s,t,e,i,n){return s===i||s===n?{start:t-e/2,end:t+e/2}:sn?{start:t-e,end:t}:{start:t,end:t+e}}function f5(s){let t={l:s.left+s._padding.left,r:s.right-s._padding.right,t:s.top+s._padding.top,b:s.bottom-s._padding.bottom},e=Object.assign({},t),i=[],n=[],o=s._pointLabels.length,r=s.options.pointLabels,a=r.centerPointLabels?rt/o:0;for(let L=0;Lt.r&&(a=(i.end-t.r)/o,s.r=Math.max(s.r,t.r+a)),n.startt.b&&(L=(n.end-t.b)/r,s.b=Math.max(s.b,t.b+L))}function g5(s,t,e){let i=s.drawingArea,{extra:n,additionalAngle:o,padding:r,size:a}=e,L=s.getPointPosition(t,i+n+r,o),l=Math.round(Ni(yt(L.angle+pt))),c=x5(L.y,a.h,l),d=v5(l),h=y5(L.x,a.w,d);return{visible:!0,x:L.x,y:c,textAlign:d,left:h,top:c,right:h+a.w,bottom:c+a.h}}function m5(s,t){if(!t)return!0;let{left:e,top:i,right:n,bottom:o}=s;return!(te({x:e,y:i},t)||te({x:e,y:o},t)||te({x:n,y:i},t)||te({x:n,y:o},t))}function b5(s,t,e){let i=[],n=s._pointLabels.length,o=s.options,{centerPointLabels:r,display:a}=o.pointLabels,L={extra:zo(o)/2,additionalAngle:r?rt/n:0},l;for(let c=0;c270||e<90)&&(s-=t),s}function C5(s,t,e){let{left:i,top:n,right:o,bottom:r}=e,{backdropColor:a}=t;if(!st(a)){let L=Me(t.borderRadius),l=Ct(t.backdropPadding);s.fillStyle=a;let c=i-l.left,d=n-l.top,h=o-i+l.width,u=r-n+l.height;Object.values(L).some(f=>f!==0)?(s.beginPath(),Cs(s,{x:c,y:d,w:h,h:u,radius:L}),s.fill()):s.fillRect(c,d,h,u)}}function _5(s,t){let{ctx:e,options:{pointLabels:i}}=s;for(let n=t-1;n>=0;n--){let o=s._pointLabelItems[n];if(!o.visible)continue;let r=i.setContext(s.getPointLabelContext(n));C5(e,r,o);let a=gt(r.font),{x:L,y:l,textAlign:c}=o;Ee(e,s._pointLabels[n],L,l+a.lineHeight/2,a,{color:r.color,textAlign:c,textBaseline:"middle"})}}function tl(s,t,e,i){let{ctx:n}=s;if(e)n.arc(s.xCenter,s.yCenter,t,0,ht);else{let o=s.getPointPosition(0,t);n.moveTo(o.x,o.y);for(let r=1;r=Vt.indexOf(e);o--){let r=Vt[o];if(dn[r].common&&s._adapter.diff(n,i,r)>=t-1)return r}return Vt[e?Vt.indexOf(e):0]}function M5(s){for(let t=Vt.indexOf(s)+1,e=Vt.length;t=t?e[i]:e[n];s[o]=!0}}function w5(s,t,e,i){let n=s._adapter,o=+n.startOf(t[0].value,i),r=t[t.length-1].value,a,L;for(a=o;a<=r;a=+n.add(a,1,i))L=e[a],L>=0&&(t[L].major=!0);return t}function xL(s,t,e){let i=[],n={},o=t.length,r,a;for(r=0;r=s[i].pos&&t<=s[n].pos&&({lo:i,hi:n}=Jt(s,"pos",t)),{pos:o,time:a}=s[i],{pos:r,time:L}=s[n]):(t>=s[i].time&&t<=s[n].time&&({lo:i,hi:n}=Jt(s,"time",t)),{time:o,pos:a}=s[i],{time:r,pos:L}=s[n]);let l=r-o;return l?a+(L-a)*(t-o)/l:a}var Ao,ne,_a,T2,sn,ai,Co,wa,z2,It,Ye,Ge,re,Ke,Ae,ks,qe,Xe,SL,Ro,kL,EL,ML,_t,Li,nn,tn,c1,Ia,DL,li,Va,rn,Nt,M1,Na,Ba,Oe,Es,Po,Yt,Oo,Wa,OL,ii,Vo,Y1,K1,q1,en,Ka,oe,De,ud,Gt,Qe,Je,BL,Bo,Qa,HL,WL,Ln,UL,rL,Gd,ln,GL,ci,KL,Xi,qL,oi,XL,ri,QL,JL,a5,l5,Ms,As,ws,di,Ue,Ds,Te,dn,Vt,Pe,Ts,el,D5,il=Mn(()=>{Ca();Ao=class{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,n){let o=e.listeners[n],r=e.duration;o.forEach(a=>a({chart:t,initial:e.initial,numSteps:r,currentStep:Math.min(i-e.start,r)}))}_refresh(){this._request||(this._running=!0,this._request=Jn.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(t=Date.now()){let e=0;this._charts.forEach((i,n)=>{if(!i.running||!i.items.length)return;let o=i.items,r=o.length-1,a=!1,L;for(;r>=0;--r)L=o[r],L._active?(L._total>i.duration&&(i.duration=L._total),L.tick(t),a=!0):(o[r]=o[o.length-1],o.pop());a&&(n.draw(),this._notify(n,i,t,"progress")),o.length||(i.running=!1,this._notify(n,i,t,"complete"),i.initial=!1),e+=o.length}),this._lastDate=t,e===0&&(this._running=!1)}_getAnims(t){let e=this._charts,i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){!e||!e.length||this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){let e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce((i,n)=>Math.max(i,n._duration),0),this._refresh())}running(t){if(!this._running)return!1;let e=this._charts.get(t);return!(!e||!e.running||!e.items.length)}stop(t){let e=this._charts.get(t);if(!e||!e.items.length)return;let i=e.items,n=i.length-1;for(;n>=0;--n)i[n].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}},ne=new Ao,_a="transparent",T2={boolean(s,t,e){return e>.5?t:s},color(s,t,e){let i=no(s||_a),n=i.valid&&no(t||_a);return n&&n.valid?n.mix(i,e).hexString():t},number(s,t,e){return s+(t-s)*e}},sn=class{constructor(t,e,i,n){let o=e[i];n=_s([t.to,n,o,t.from]);let r=_s([t.from,o,n]);this._active=!0,this._fn=t.fn||T2[t.type||typeof r],this._easing=us[t.easing]||us.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=r,this._to=n,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);let n=this._target[this._prop],o=i-this._start,r=this._duration-o;this._start=i,this._duration=Math.floor(Math.max(r,t.duration)),this._total+=o,this._loop=!!t.loop,this._to=_s([t.to,e,n,t.from]),this._from=_s([t.from,n,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){let e=t-this._start,i=this._duration,n=this._prop,o=this._from,r=this._loop,a=this._to,L;if(this._active=o!==a&&(r||e1?2-L:L,L=this._easing(Math.min(1,Math.max(0,L))),this._target[n]=this._fn(o,a,L)}wait(){let t=this._promises||(this._promises=[]);return new Promise((e,i)=>{t.push({res:e,rej:i})})}_notify(t){let e=t?"res":"rej",i=this._promises||[];for(let n=0;n{let o=t[n];if(!it(o))return;let r={};for(let a of e)r[a]=o[a];(dt(o.properties)&&o.properties||[n]).forEach(a=>{(a===n||!i.has(a))&&i.set(a,r)})})}_animateOptions(t,e){let i=e.options,n=R2(t,i);if(!n)return[];let o=this._createAnimations(n,i);return i.$shared&&A2(t.options.$animations,i).then(()=>{t.options=i},()=>{}),o}_createAnimations(t,e){let i=this._properties,n=[],o=t.$animations||(t.$animations={}),r=Object.keys(e),a=Date.now(),L;for(L=r.length-1;L>=0;--L){let l=r[L];if(l.charAt(0)==="$")continue;if(l==="options"){n.push(...this._animateOptions(t,e));continue}let c=e[l],d=o[l],h=i.get(l);if(d)if(h&&d.active()){d.update(h,c,a);continue}else d.cancel();if(!h||!h.duration){t[l]=c;continue}o[l]=d=new sn(h,t,l,c),n.push(d)}return n}update(t,e){if(this._properties.size===0){Object.assign(t,e);return}let i=this._createAnimations(t,e);if(i.length)return ne.add(this._chart,i),!0}};Co=s=>s==="reset"||s==="none",wa=(s,t)=>t?s:Object.assign({},s),z2=(s,t,e)=>s&&!t.hidden&&t._stacked&&{keys:CL(e,!0),values:null},It=class{constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){let t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=yo(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Js(this._cachedMeta),this.index=t}linkScales(){let t=this.chart,e=this._cachedMeta,i=this.getDataset(),n=(d,h,u,f)=>d==="x"?h:d==="r"?f:u,o=e.xAxisID=tt(i.xAxisID,xo(t,"x")),r=e.yAxisID=tt(i.yAxisID,xo(t,"y")),a=e.rAxisID=tt(i.rAxisID,xo(t,"r")),L=e.indexAxis,l=e.iAxisID=n(L,o,r,a),c=e.vAxisID=n(L,r,o,a);e.xScale=this.getScaleForId(o),e.yScale=this.getScaleForId(r),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(l),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){let e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){let t=this._cachedMeta;this._data&&Xn(this._data,this),t._stacked&&Js(t)}_dataCheck(){let t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(it(e)){let n=this._cachedMeta;this._data=F2(e,n)}else if(i!==e){if(i){Xn(i,this);let n=this._cachedMeta;Js(n),n._parsed=[]}e&&Object.isExtensible(e)&&ia(e,this),this._syncList=[],this._data=e}}addElements(){let t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){let e=this._cachedMeta,i=this.getDataset(),n=!1;this._dataCheck();let o=e._stacked;e._stacked=yo(e.vScale,e),e.stack!==i.stack&&(n=!0,Js(e),e.stack=i.stack),this._resyncElements(t),(n||o!==e._stacked)&&(Ma(this,e._parsed),e._stacked=yo(e.vScale,e))}configure(){let t=this.chart.config,e=t.datasetScopeKeys(this._type),i=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(i,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){let{_cachedMeta:i,_data:n}=this,{iScale:o,_stacked:r}=i,a=o.axis,L=t===0&&e===n.length?!0:i._sorted,l=t>0&&i._parsed[t-1],c,d,h;if(this._parsing===!1)i._parsed=n,i._sorted=!0,h=n;else{dt(n[t])?h=this.parseArrayData(i,n,t,e):it(n[t])?h=this.parseObjectData(i,n,t,e):h=this.parsePrimitiveData(i,n,t,e);let u=()=>d[a]===null||l&&d[a]g||d=0;--h)if(!f()){this.updateRangeFromParsed(l,t,u,L);break}}return l}getAllParsedValues(t){let e=this._cachedMeta._parsed,i=[],n,o,r;for(n=0,o=e.length;n=0&&tthis.getContext(i,n,e),g=l.resolveNamedOptions(h,u,f,d);return g.$shared&&(g.$shared=L,o[r]=Object.freeze(wa(g,L))),g}_resolveAnimations(t,e,i){let n=this.chart,o=this._cachedDataOpts,r=`animation-${e}`,a=o[r];if(a)return a;let L;if(n.options.animation!==!1){let c=this.chart.config,d=c.datasetAnimationScopeKeys(this._type,e),h=c.getOptionScopes(this.getDataset(),d);L=c.createResolver(h,this.getContext(t,i,e))}let l=new ai(n,L&&L.animations);return L&&L._cacheable&&(o[r]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Co(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){let i=this.resolveDataElementOptions(t,e),n=this._sharedOptions,o=this.getSharedOptions(i),r=this.includeOptions(e,o)||o!==n;return this.updateSharedOptions(o,e,i),{sharedOptions:o,includeOptions:r}}updateElement(t,e,i,n){Co(n)?Object.assign(t,i):this._resolveAnimations(e,n).update(t,i)}updateSharedOptions(t,e,i){t&&!Co(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,n){t.active=n;let o=this.getStyle(e,n);this._resolveAnimations(e,i,n).update(t,{options:!n&&this.getSharedOptions(o)||o})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){let t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){let t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){let e=this._data,i=this._cachedMeta.data;for(let[a,L,l]of this._syncList)this[a](L,l);this._syncList=[];let n=i.length,o=e.length,r=Math.min(o,n);r&&this.parse(0,r),o>n?this._insertElements(n,o-n,t):o{for(l.length+=e,a=l.length-1;a>=r;a--)l[a]=l[a-e]};for(L(o),a=t;ac.controller.options.grouped),o=i.options.stacked,r=[],a=this._cachedMeta.controller.getParsed(e),L=a&&a[i.axis],l=c=>{let d=c._parsed.find(u=>u[i.axis]===L),h=d&&d[c.vScale.axis];if(st(h)||isNaN(h))return!0};for(let c of n)if(!(e!==void 0&&l(c))&&((o===!1||r.indexOf(c.stack)===-1||o===void 0&&c.stack===void 0)&&r.push(c.stack),c.index===t))break;return r.length||r.push(void 0),r}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){let t=this.chart.scales,e=this.chart.options.indexAxis;return Object.keys(t).filter(i=>t[i].axis===e).shift()}_getAxis(){let t={},e=this.getFirstScaleIdForIndexAxis();for(let i of this.chart.data.datasets)t[tt(this.chart.options.indexAxis==="x"?i.xAxisID:i.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,i){let n=this._getStacks(t,i),o=e!==void 0?n.indexOf(e):-1;return o===-1?n.length-1:o}_getRuler(){let t=this.options,e=this._cachedMeta,i=e.iScale,n=[],o,r;for(o=0,r=e.data.length;o=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){let e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:n,yScale:o}=e,r=this.getParsed(t),a=n.getLabelForValue(r.x),L=o.getLabelForValue(r.y),l=r._custom;return{label:i[t]||"",value:"("+a+", "+L+(l?", "+l:"")+")"}}update(t){let e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,n){let o=n==="reset",{iScale:r,vScale:a}=this._cachedMeta,{sharedOptions:L,includeOptions:l}=this._getSharedOptions(e,n),c=r.axis,d=a.axis;for(let h=e;h+i[L];if(it(i[t])){let{key:L="value"}=this._parsing;o=l=>+de(i[l],L)}let r,a;for(r=t,a=t+e;r0&&!isNaN(t)?ht*(Math.abs(t)/e):0}getLabelAndValue(t){let e=this._cachedMeta,i=this.chart,n=i.data.labels||[],o=ys(e._parsed[t],i.options.locale);return{label:n[t]||"",value:o}}getMaxBorderWidth(t){let e=0,i=this.chart,n,o,r,a,L;if(!t){for(n=0,o=i.data.datasets.length;nt!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),Y(re,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data,{labels:{pointStyle:i,textAlign:n,color:o,useBorderRadius:r,borderRadius:a}}=t.legend.options;return e.labels.length&&e.datasets.length?e.labels.map((L,l)=>{let d=t.getDatasetMeta(0).controller.getStyle(l);return{text:L,fillStyle:d.backgroundColor,fontColor:o,hidden:!t.getDataVisibility(l),lineDash:d.borderDash,lineDashOffset:d.borderDashOffset,lineJoin:d.borderJoinStyle,lineWidth:d.borderWidth,strokeStyle:d.borderColor,textAlign:n,pointStyle:i,borderRadius:r&&(a||d.borderRadius),index:l}}):[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}});Ke=class extends It{initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){let e=this._cachedMeta,{dataset:i,data:n=[],_dataset:o}=e,r=this.chart._animationsDisabled,{start:a,count:L}=eo(e,n,r);this._drawStart=a,this._drawCount=L,so(e)&&(a=0,L=n.length),i._chart=this.chart,i._datasetIndex=this.index,i._decimated=!!o._decimated,i.points=n;let l=this.resolveDatasetElementOptions(t);this.options.showLine||(l.borderWidth=0),l.segment=this.options.segment,this.updateElement(i,void 0,{animated:!r,options:l},t),this.updateElements(n,a,L,t)}updateElements(t,e,i,n){let o=n==="reset",{iScale:r,vScale:a,_stacked:L,_dataset:l}=this._cachedMeta,{sharedOptions:c,includeOptions:d}=this._getSharedOptions(e,n),h=r.axis,u=a.axis,{spanGaps:f,segment:g}=this.options,m=Ze(f)?f:Number.POSITIVE_INFINITY,p=this.chart._animationsDisabled||o||n==="none",b=e+i,C=t.length,S=e>0&&this.getParsed(e-1);for(let _=0;_=b){v.skip=!0;continue}let x=this.getParsed(_),k=st(x[u]),E=v[h]=r.getPixelForValue(x[h],_),M=v[u]=o||k?a.getBasePixel():a.getPixelForValue(L?this.applyStack(a,x,L):x[u],_);v.skip=isNaN(E)||isNaN(M)||k,v.stop=_>0&&Math.abs(x[h]-S[h])>m,g&&(v.parsed=x,v.raw=l.data[_]),d&&(v.options=c||this.resolveDataElementOptions(_,y.active?"active":n)),p||this.updateElement(y,_,v,n),S=x}}getMaxOverflow(){let t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,n=t.data||[];if(!n.length)return i;let o=n[0].size(this.resolveDataElementOptions(0)),r=n[n.length-1].size(this.resolveDataElementOptions(n.length-1));return Math.max(i,o,r)/2}draw(){let t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}};Y(Ke,"id","line"),Y(Ke,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),Y(Ke,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});Ae=class extends It{constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){let e=this._cachedMeta,i=this.chart,n=i.data.labels||[],o=ys(e._parsed[t].r,i.options.locale);return{label:n[t]||"",value:o}}parseObjectData(t,e,i,n){return ho.bind(this)(t,e,i,n)}update(t){let e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){let t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach((i,n)=>{let o=this.getParsed(n).r;!isNaN(o)&&this.chart.getDataVisibility(n)&&(oe.max&&(e.max=o))}),e}_updateRadius(){let t=this.chart,e=t.chartArea,i=t.options,n=Math.min(e.right-e.left,e.bottom-e.top),o=Math.max(n/2,0),r=Math.max(i.cutoutPercentage?o/100*i.cutoutPercentage:1,0),a=(o-r)/t.getVisibleDatasetCount();this.outerRadius=o-a*this.index,this.innerRadius=this.outerRadius-a}updateElements(t,e,i,n){let o=n==="reset",r=this.chart,L=r.options.animation,l=this._cachedMeta.rScale,c=l.xCenter,d=l.yCenter,h=l.getIndexAngle(0)-.5*rt,u=h,f,g=360/this.countVisibleElements();for(f=0;f{!isNaN(this.getParsed(n).r)&&this.chart.getDataVisibility(n)&&e++}),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?Zt(this.resolveDataElementOptions(t,e).angle||i):0}};Y(Ae,"id","polarArea"),Y(Ae,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),Y(Ae,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data;if(e.labels.length&&e.datasets.length){let{labels:{pointStyle:i,color:n}}=t.legend.options;return e.labels.map((o,r)=>{let L=t.getDatasetMeta(0).controller.getStyle(r);return{text:o,fillStyle:L.backgroundColor,strokeStyle:L.borderColor,fontColor:n,lineWidth:L.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(r),index:r}})}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}});ks=class extends re{};Y(ks,"id","pie"),Y(ks,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});qe=class extends It{getLabelAndValue(t){let e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,n){return ho.bind(this)(t,e,i,n)}update(t){let e=this._cachedMeta,i=e.dataset,n=e.data||[],o=e.iScale.getLabels();if(i.points=n,t!=="resize"){let r=this.resolveDatasetElementOptions(t);this.options.showLine||(r.borderWidth=0);let a={_loop:!0,_fullLoop:o.length===n.length,options:r};this.updateElement(i,void 0,a,t)}this.updateElements(n,0,n.length,t)}updateElements(t,e,i,n){let o=this._cachedMeta.rScale,r=n==="reset";for(let a=e;a0&&this.getParsed(e-1);for(let S=e;S0&&Math.abs(y[u]-C[u])>p,m&&(v.parsed=y,v.raw=l.data[S]),h&&(v.options=d||this.resolveDataElementOptions(S,_.active?"active":n)),b||this.updateElement(_,S,v,n),C=y}this.updateSharedOptions(d,n,c)}getMaxOverflow(){let t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let a=0;for(let L=e.length-1;L>=0;--L)a=Math.max(a,e[L].size(this.resolveDataElementOptions(L))/2);return a>0&&a}let i=t.dataset,n=i.options&&i.options.borderWidth||0;if(!e.length)return n;let o=e[0].size(this.resolveDataElementOptions(0)),r=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(n,o,r)/2}};Y(Xe,"id","scatter"),Y(Xe,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),Y(Xe,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});SL=Object.freeze({__proto__:null,BarController:Ye,BubbleController:Ge,DoughnutController:re,LineController:Ke,PieController:ks,PolarAreaController:Ae,RadarController:qe,ScatterController:Xe});Ro=class s{constructor(t){Y(this,"options");this.options=t||{}}static override(t){Object.assign(s.prototype,t)}init(){}formats(){return je()}parse(){return je()}format(){return je()}add(){return je()}diff(){return je()}startOf(){return je()}endOf(){return je()}},kL={_date:Ro};EL={evaluateInteractionItems:hi,modes:{index(s,t,e,i){let n=we(t,s),o=e.axis||"x",r=e.includeInvisible||!1,a=e.intersect?So(s,n,o,i,r):ko(s,n,o,!1,i,r),L=[];return a.length?(s.getSortedVisibleDatasetMetas().forEach(l=>{let c=a[0].index,d=l.data[c];d&&!d.skip&&L.push({element:d,datasetIndex:l.index,index:c})}),L):[]},dataset(s,t,e,i){let n=we(t,s),o=e.axis||"xy",r=e.includeInvisible||!1,a=e.intersect?So(s,n,o,i,r):ko(s,n,o,!1,i,r);if(a.length>0){let L=a[0].datasetIndex,l=s.getDatasetMeta(L).data;a=[];for(let c=0;c{typeof g.beforeLayout=="function"&&g.beforeLayout()});let c=L.reduce((g,m)=>m.box.options&&m.box.options.display===!1?g:g+1,0)||1,d=Object.freeze({outerWidth:t,outerHeight:e,padding:n,availableWidth:o,availableHeight:r,vBoxMaxWidth:o/2/c,hBoxMaxHeight:r/2}),h=Object.assign({},n);wL(h,Ct(i));let u=Object.assign({maxPadding:h,w:o,h:r,x:n.left,y:n.top},n),f=o1(L.concat(l),d);ni(a.fullSize,u,d,f),ni(L,u,d,f),ni(l,u,d,f)&&ni(L,u,d,f),L1(u),Fa(a.leftAndTop,u,d,f),u.x+=u.w,u.y+=u.h,Fa(a.rightAndBottom,u,d,f),s.chartArea={left:u.left,top:u.top,right:u.left+u.w,bottom:u.top+u.h,height:u.h,width:u.w},Lt(a.chartArea,g=>{let m=g.box;Object.assign(m,s.chartArea),m.update(u.w,u.h,{left:0,top:0,right:0,bottom:0})})}},Li=class{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,n){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,n?Math.floor(e/n):i)}}isAttached(t){return!0}updateConfig(t){}},nn=class extends Li{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}},tn="$chartjs",c1={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},Ia=s=>s===null||s==="";DL=ma?{passive:!0}:!1;li=new Map,Va=0;rn=class extends Li{acquireContext(t,e){let i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(d1(t,e),i):null}releaseContext(t){let e=t.canvas;if(!e[tn])return!1;let i=e[tn].initial;["height","width"].forEach(o=>{let r=i[o];st(r)?e.removeAttribute(o):e.setAttribute(o,r)});let n=i.style||{};return Object.keys(n).forEach(o=>{e.style[o]=n[o]}),e.width=e.width,delete e[tn],!0}addEventListener(t,e,i){this.removeEventListener(t,e);let n=t.$proxies||(t.$proxies={}),r={attach:p1,detach:g1,resize:v1}[e]||y1;n[e]=r(t,e,i)}removeEventListener(t,e){let i=t.$proxies||(t.$proxies={}),n=i[e];if(!n)return;({attach:Eo,detach:Eo,resize:Eo}[e]||u1)(t,e,n),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,n){return ga(t,e,i,n)}isAttached(t){let e=t&&Ui(t);return!!(e&&e.isConnected)}};Nt=class{constructor(){Y(this,"x");Y(this,"y");Y(this,"active",!1);Y(this,"options");Y(this,"$animations")}tooltipPosition(t){let{x:e,y:i}=this.getProps(["x","y"],t);return{x:e,y:i}}hasValue(){return Ze(this.x)&&Ze(this.y)}getProps(t,e){let i=this.$animations;if(!e||!i)return this;let n={};return t.forEach(o=>{n[o]=i[o]&&i[o].active()?i[o]._to:this[o]}),n}};Y(Nt,"defaults",{}),Y(Nt,"defaultRoutes");M1=s=>s==="left"?"right":s==="right"?"left":s,Na=(s,t,e)=>t==="top"||t==="left"?s[t]+e:s[t]-e,Ba=(s,t)=>Math.min(t||s,s);Oe=class s extends Nt{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:n}=this;return t=Ot(t,Number.POSITIVE_INFINITY),e=Ot(e,Number.NEGATIVE_INFINITY),i=Ot(i,Number.POSITIVE_INFINITY),n=Ot(n,Number.NEGATIVE_INFINITY),{min:Ot(t,i),max:Ot(e,n),minDefined:ft(t),maxDefined:ft(e)}}getMinMax(t){let{min:e,max:i,minDefined:n,maxDefined:o}=this.getUserBounds(),r;if(n&&o)return{min:e,max:i};let a=this.getMatchingVisibleMetas();for(let L=0,l=a.length;Li?i:e,i=n&&e>i?e:i,{min:Ot(e,Ot(i,e)),max:Ot(i,Ot(e,i))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){let t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){ct(this.options.beforeUpdate,[this])}update(t,e,i){let{beginAtZero:n,grace:o,ticks:r}=this.options,a=r.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=ca(this,o,n),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();let L=a=o||i<=1||!this.isHorizontal()){this.labelRotation=n;return}let c=this._getLabelSizes(),d=c.widest.width,h=c.highest.height,u=mt(this.chart.width-d,0,this.maxWidth);a=t.offset?this.maxWidth/i:u/(i-1),d+6>a&&(a=u/(i-(t.offset?.5:1)),L=this.maxHeight-si(t.grid)-e.padding-za(t.title,this.chart.options.font),l=Math.sqrt(d*d+h*h),r=Ni(Math.min(Math.asin(mt((c.highest.height+6)/a,-1,1)),Math.asin(mt(L/l,-1,1))-Math.asin(mt(h/l,-1,1)))),r=Math.max(n,Math.min(o,r))),this.labelRotation=r}afterCalculateLabelRotation(){ct(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){ct(this.options.beforeFit,[this])}fit(){let t={width:0,height:0},{chart:e,options:{ticks:i,title:n,grid:o}}=this,r=this._isVisible(),a=this.isHorizontal();if(r){let L=za(n,e.options.font);if(a?(t.width=this.maxWidth,t.height=si(o)+L):(t.height=this.maxHeight,t.width=si(o)+L),i.display&&this.ticks.length){let{first:l,last:c,widest:d,highest:h}=this._getLabelSizes(),u=i.padding*2,f=Zt(this.labelRotation),g=Math.cos(f),m=Math.sin(f);if(a){let p=i.mirror?0:m*d.width+g*h.height;t.height=Math.min(this.maxHeight,t.height+p+u)}else{let p=i.mirror?0:g*d.width+m*h.height;t.width=Math.min(this.maxWidth,t.width+p+u)}this._calculatePadding(l,c,m,g)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,n){let{ticks:{align:o,padding:r},position:a}=this.options,L=this.labelRotation!==0,l=a!=="top"&&this.axis==="x";if(this.isHorizontal()){let c=this.getPixelForTick(0)-this.left,d=this.right-this.getPixelForTick(this.ticks.length-1),h=0,u=0;L?l?(h=n*t.width,u=i*e.height):(h=i*t.height,u=n*e.width):o==="start"?u=e.width:o==="end"?h=t.width:o!=="inner"&&(h=t.width/2,u=e.width/2),this.paddingLeft=Math.max((h-c+r)*this.width/(this.width-c),0),this.paddingRight=Math.max((u-d+r)*this.width/(this.width-d),0)}else{let c=e.height/2,d=t.height/2;o==="start"?(c=0,d=t.height):o==="end"&&(c=e.height,d=0),this.paddingTop=c+r,this.paddingBottom=d+r}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){ct(this.options.afterFit,[this])}isHorizontal(){let{axis:t,position:e}=this.options;return e==="top"||e==="bottom"||t==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){this.beforeTickToLabelConversion(),this.generateTickLabels(t);let e,i;for(e=0,i=t.length;e({width:r[k]||0,height:a[k]||0});return{first:x(0),last:x(e-1),widest:x(y),highest:x(v),widths:r,heights:a}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){let e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);let e=this._startPixel+t*this._length;return Jr(this._alignToPixels?ke(this.chart,e,0):e)}getDecimalForPixel(t){let e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){let{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){let e=this.ticks||[];if(t>=0&&ta*n?a/i:L/n:L*n0}_computeGridLineItems(t){let e=this.axis,i=this.chart,n=this.options,{grid:o,position:r,border:a}=n,L=o.offset,l=this.isHorizontal(),d=this.ticks.length+(L?1:0),h=si(o),u=[],f=a.setContext(this.getContext()),g=f.display?f.width:0,m=g/2,p=function(P){return ke(i,P,g)},b,C,S,_,y,v,x,k,E,M,D,A;if(r==="top")b=p(this.bottom),v=this.bottom-h,k=b-m,M=p(t.top)+m,A=t.bottom;else if(r==="bottom")b=p(this.top),M=t.top,A=p(t.bottom)-m,v=b+m,k=this.top+h;else if(r==="left")b=p(this.right),y=this.right-h,x=b-m,E=p(t.left)+m,D=t.right;else if(r==="right")b=p(this.left),E=t.left,D=p(t.right)-m,y=b+m,x=this.left+h;else if(e==="x"){if(r==="center")b=p((t.top+t.bottom)/2+.5);else if(it(r)){let P=Object.keys(r)[0],w=r[P];b=p(this.chart.scales[P].getPixelForValue(w))}M=t.top,A=t.bottom,v=b+m,k=v+h}else if(e==="y"){if(r==="center")b=p((t.left+t.right)/2);else if(it(r)){let P=Object.keys(r)[0],w=r[P];b=p(this.chart.scales[P].getPixelForValue(w))}y=b-m,x=y-h,E=t.left,D=t.right}let N=tt(n.ticks.maxTicksLimit,d),I=Math.max(1,Math.ceil(d/N));for(C=0;C0&&(T-=W/2);break}B={left:T,top:K,width:W+G.width,height:R+G.height,color:I.backdropColor}}m.push({label:S,font:k,textOffset:D,options:{rotation:g,color:w,strokeColor:U,strokeWidth:O,textAlign:Z,textBaseline:A,translation:[_,y],backdrop:B}})}return m}_getXAxisLabelAlignment(){let{position:t,ticks:e}=this.options;if(-Zt(this.labelRotation))return t==="top"?"left":"right";let n="center";return e.align==="start"?n="left":e.align==="end"?n="right":e.align==="inner"&&(n="inner"),n}_getYAxisLabelAlignment(t){let{position:e,ticks:{crossAlign:i,mirror:n,padding:o}}=this.options,r=this._getLabelSizes(),a=t+o,L=r.widest.width,l,c;return e==="left"?n?(c=this.right+o,i==="near"?l="left":i==="center"?(l="center",c+=L/2):(l="right",c+=L)):(c=this.right-a,i==="near"?l="right":i==="center"?(l="center",c-=L/2):(l="left",c=this.left)):e==="right"?n?(c=this.left+o,i==="near"?l="right":i==="center"?(l="center",c-=L/2):(l="left",c-=L)):(c=this.left+a,i==="near"?l="left":i==="center"?(l="center",c+=L/2):(l="right",c=this.right)):l="right",{textAlign:l,x:c}}_computeLabelArea(){if(this.options.ticks.mirror)return;let t=this.chart,e=this.options.position;if(e==="left"||e==="right")return{top:0,left:this.left,bottom:t.height,right:this.right};if(e==="top"||e==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:t.width}}drawBackground(){let{ctx:t,options:{backgroundColor:e},left:i,top:n,width:o,height:r}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,n,o,r),t.restore())}getLineWidthForValue(t){let e=this.options.grid;if(!this._isVisible()||!e.display)return 0;let n=this.ticks.findIndex(o=>o.value===t);return n>=0?e.setContext(this.getContext(n)).lineWidth:0}drawGrid(t){let e=this.options.grid,i=this.ctx,n=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t)),o,r,a=(L,l,c)=>{!c.width||!c.color||(i.save(),i.lineWidth=c.width,i.strokeStyle=c.color,i.setLineDash(c.borderDash||[]),i.lineDashOffset=c.borderDashOffset,i.beginPath(),i.moveTo(L.x,L.y),i.lineTo(l.x,l.y),i.stroke(),i.restore())};if(e.display)for(o=0,r=n.length;o{this.draw(o)}}]:[{z:i,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:n,draw:()=>{this.drawBorder()}},{z:e,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(t){let e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",n=[],o,r;for(o=0,r=e.length;o{let o=i||this._getRegistryForType(n);i||o.isForType(n)||o===this.plugins&&n.id?this._exec(t,o,n):Lt(n,r=>{let a=i||this._getRegistryForType(r);this._exec(t,a,r)})})}_exec(t,e,i){let n=Vi(t);ct(i["before"+n],[],i),e[t](i),ct(i["after"+n],[],i)}_getRegistryForType(t){for(let e=0;eo.filter(a=>!r.some(L=>a.plugin.id===L.plugin.id));this._notify(n(e,i),t,"stop"),this._notify(n(i,e),t,"start")}};Wa=new Map,OL=new Set;ii=(s,t,e)=>{let i=de(t,e);i!==void 0&&s.add(i)},Vo=class{constructor(t){this._config=U1(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=PL(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){let t=this._config;this.clearCache(),RL(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return qi(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,e){return qi(`${t}.transition.${e}`,()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,e){return qi(`${t}-${e}`,()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]])}pluginScopeKeys(t){let e=t.id,i=this.type;return qi(`${i}-plugin-${e}`,()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]])}_cachedScopes(t,e){let i=this._scopeCache,n=i.get(t);return(!n||e)&&(n=new Map,i.set(t,n)),n}getOptionScopes(t,e,i){let{options:n,type:o}=this,r=this._cachedScopes(t,i),a=r.get(e);if(a)return a;let L=new Set;e.forEach(c=>{t&&(L.add(t),c.forEach(d=>ii(L,t,d))),c.forEach(d=>ii(L,n,d)),c.forEach(d=>ii(L,Se[o]||{},d)),c.forEach(d=>ii(L,ut,d)),c.forEach(d=>ii(L,zi,d))});let l=Array.from(L);return l.length===0&&l.push(Object.create(null)),OL.has(e)&&r.set(e,l),l}chartOptionScopes(){let{options:t,type:e}=this;return[t,Se[e]||{},ut.datasets[e]||{},{type:e},ut,zi]}resolveNamedOptions(t,e,i,n=[""]){let o={$shared:!0},{resolver:r,subPrefixes:a}=ja(this._resolverCache,t,n),L=r;if(G1(r,e)){o.$shared=!1,i=le(i)?i():i;let l=this.createResolver(t,i,a);L=He(r,i,l)}for(let l of e)o[l]=L[l];return o}createResolver(t,e,i=[""],n){let{resolver:o}=ja(this._resolverCache,t,i);return it(e)?He(o,e,void 0,n):o}};Y1=s=>it(s)&&Object.getOwnPropertyNames(s).some(t=>le(s[t]));K1="4.5.1",q1=["top","bottom","left","right","chartArea"];en={},Ka=s=>{let t=FL(s);return Object.values(en).filter(e=>e.canvas===t).pop()};oe=class{static register(...t){Yt.add(...t),qa()}static unregister(...t){Yt.remove(...t),qa()}constructor(t,e){let i=this.config=new Vo(e),n=FL(t),o=Ka(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");let r=i.createResolver(i.chartOptionScopes(),this.getContext());this.platform=new(i.platform||AL(n)),this.platform.updateConfig(i);let a=this.platform.acquireContext(n,r.aspectRatio),L=a&&a.canvas,l=L&&L.height,c=L&&L.width;if(this.id=Yr(),this.ctx=a,this.canvas=L,this.width=c,this.height=l,this._options=r,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new Oo,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=na(d=>this.update(d),r.resizeDelay||0),this._dataChanges=[],en[this.id]=this,!a||!L){console.error("Failed to create chart: can't acquire context from the given item");return}ne.listen(this,"complete",Ga),ne.listen(this,"progress",X1),this._initialize(),this.attached&&this.update()}get aspectRatio(){let{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return st(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return Yt}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():uo(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return oo(this.canvas,this.ctx),this}stop(){return ne.stop(this),this}resize(t,e){ne.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){let i=this.options,n=this.canvas,o=i.maintainAspectRatio&&this.aspectRatio,r=this.platform.getMaximumSize(n,t,e,o),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),L=this.width?"resize":"attach";this.width=r.width,this.height=r.height,this._aspectRatio=this.aspectRatio,uo(this,a,!0)&&(this.notifyPlugins("resize",{size:r}),ct(i.onResize,[this,r],this),this.attached&&this._doResize(L)&&this.render())}ensureScalesHaveIDs(){let e=this.options.scales||{};Lt(e,(i,n)=>{i.id=n})}buildOrUpdateScales(){let t=this.options,e=t.scales,i=this.scales,n=Object.keys(i).reduce((r,a)=>(r[a]=!1,r),{}),o=[];e&&(o=o.concat(Object.keys(e).map(r=>{let a=e[r],L=Io(r,a),l=L==="r",c=L==="x";return{options:a,dposition:l?"chartArea":c?"bottom":"left",dtype:l?"radialLinear":c?"category":"linear"}}))),Lt(o,r=>{let a=r.options,L=a.id,l=Io(L,a),c=tt(a.type,r.dtype);(a.position===void 0||Ua(a.position,l)!==Ua(r.dposition))&&(a.position=r.dposition),n[L]=!0;let d=null;if(L in i&&i[L].type===c)d=i[L];else{let h=Yt.getScale(c);d=new h({id:L,type:c,ctx:this.ctx,chart:this}),i[d.id]=d}d.init(a,t)}),Lt(n,(r,a)=>{r||delete i[a]}),Lt(i,r=>{_t.configure(this,r,r.options),_t.addBox(this,r)})}_updateMetasets(){let t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort((n,o)=>n.index-o.index),i>e){for(let n=e;ne.length&&delete this._stacks,t.forEach((i,n)=>{e.filter(o=>o===i._dataset).length===0&&this._destroyDatasetMeta(n)})}buildOrUpdateControllers(){let t=[],e=this.data.datasets,i,n;for(this._removeUnreferencedMetasets(),i=0,n=e.length;i{this.getDatasetMeta(e).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){let e=this.config;e.update();let i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),n=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0})===!1)return;let o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let r=0;for(let l=0,c=this.data.datasets.length;l{l.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(Ya("z","_idx"));let{_active:a,_lastEvent:L}=this;L?this._eventHandler(L,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){Lt(this.scales,t=>{_t.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){let t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);(!Un(e,i)||!!this._responsiveListeners!==t.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){let{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(let{method:i,start:n,count:o}of e){let r=i==="_removeElements"?-o:o;Q1(t,n,r)}}_getUniformDataChanges(){let t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];let e=this.data.datasets.length,i=o=>new Set(t.filter(r=>r[0]===o).map((r,a)=>a+","+r.splice(1).join(","))),n=i(0);for(let o=1;oo.split(",")).map(o=>({method:o[1],start:+o[2],count:+o[3]}))}_updateLayout(t){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;_t.update(this,this.width,this.height,t);let e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],Lt(this.boxes,n=>{i&&n.position==="chartArea"||(n.configure&&n.configure(),this._layers.push(...n._layers()))},this),this._layers.forEach((n,o)=>{n._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})!==!1){for(let e=0,i=this.data.datasets.length;e=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){let e=this.ctx,i={meta:t,index:t.index,cancelable:!0},n=vo(this,t);this.notifyPlugins("beforeDatasetDraw",i)!==!1&&(n&&Xs(e,n),t.controller.draw(),n&&Qs(e),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return te(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,n){let o=EL.modes[e];return typeof o=="function"?o(this,t,i,n):[]}getDatasetMeta(t){let e=this.data.datasets[t],i=this._metasets,n=i.filter(o=>o&&o._dataset===e).pop();return n||(n={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(n)),n}getContext(){return this.$context||(this.$context=he(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){let e=this.data.datasets[t];if(!e)return!1;let i=this.getDatasetMeta(t);return typeof i.hidden=="boolean"?!i.hidden:!e.hidden}setDatasetVisibility(t,e){let i=this.getDatasetMeta(t);i.hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){let n=i?"show":"hide",o=this.getDatasetMeta(t),r=o.controller._resolveAnimations(void 0,n);ms(e)?(o.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),r.update(o,{visible:i}),this.update(a=>a.datasetIndex===t?n:void 0))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){let e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),ne.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,o,r),t[o]=r},n=(o,r,a)=>{o.offsetX=r,o.offsetY=a,this._eventHandler(o)};Lt(this.options.events,o=>i(o,n))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});let t=this._responsiveListeners,e=this.platform,i=(L,l)=>{e.addEventListener(this,L,l),t[L]=l},n=(L,l)=>{t[L]&&(e.removeEventListener(this,L,l),delete t[L])},o=(L,l)=>{this.canvas&&this.resize(L,l)},r,a=()=>{n("attach",a),this.attached=!0,this.resize(),i("resize",o),i("detach",r)};r=()=>{this.attached=!1,n("resize",o),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():r()}unbindEvents(){Lt(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},Lt(this._responsiveListeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){let n=i?"set":"remove",o,r,a,L;for(e==="dataset"&&(o=this.getDatasetMeta(t[0].datasetIndex),o.controller["_"+n+"DatasetHoverStyle"]()),a=0,L=t.length;a{let a=this.getDatasetMeta(o);if(!a)throw new Error("No dataset found at index "+o);return{datasetIndex:o,element:a.data[r],index:r}});!qs(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return this._plugins._cache.filter(e=>e.plugin.id===t).length===1}_updateHoverStyles(t,e,i){let n=this.options.hover,o=(L,l)=>L.filter(c=>!l.some(d=>c.datasetIndex===d.datasetIndex&&c.index===d.index)),r=o(e,t),a=i?t:o(t,e);r.length&&this.updateHoverStyle(r,n.mode,!1),a.length&&n.mode&&this.updateHoverStyle(a,n.mode,!0)}_eventHandler(t,e){let i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},n=r=>(r.options.events||this.options.events).includes(t.native.type);if(this.notifyPlugins("beforeEvent",i,n)===!1)return;let o=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,n),(o||i.changed)&&this.render(),this}_handleEvent(t,e,i){let{_active:n=[],options:o}=this,r=e,a=this._getActiveElements(t,n,i,r),L=qr(t),l=J1(t,this._lastEvent,i,L);i&&(this._lastEvent=null,ct(o.onHover,[t,a,this],this),L&&ct(o.onClick,[t,a,this],this));let c=!qs(a,n);return(c||e)&&(this._active=a,this._updateHoverStyles(a,n,e)),this._lastEvent=l,c}_getActiveElements(t,e,i,n){if(t.type==="mouseout")return[];if(!i)return e;let o=this.options.hover;return this.getElementsAtEventForMode(t,o.mode,o,n)}};Y(oe,"defaults",ut),Y(oe,"instances",en),Y(oe,"overrides",Se),Y(oe,"registry",Yt),Y(oe,"version",K1),Y(oe,"getChart",Ka);De=class extends Nt{constructor(e){super();Y(this,"circumference");Y(this,"endAngle");Y(this,"fullCircles");Y(this,"innerRadius");Y(this,"outerRadius");Y(this,"pixelMargin");Y(this,"startAngle");this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,e&&Object.assign(this,e)}inRange(e,i,n){let o=this.getProps(["x","y"],n),{angle:r,distance:a}=qn(o,{x:e,y:i}),{startAngle:L,endAngle:l,innerRadius:c,outerRadius:d,circumference:h}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],n),u=(this.options.spacing+this.options.borderWidth)/2,f=tt(h,l-L),g=vs(r,L,l)&&L!==l,m=f>=ht||g,p=se(a,c+u,d+u);return m&&p}getCenterPoint(e){let{x:i,y:n,startAngle:o,endAngle:r,innerRadius:a,outerRadius:L}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],e),{offset:l,spacing:c}=this.options,d=(o+r)/2,h=(a+L+c+l)/2;return{x:i+Math.cos(d)*h,y:n+Math.sin(d)*h}}tooltipPosition(e){return this.getCenterPoint(e)}draw(e){let{options:i,circumference:n}=this,o=(i.offset||0)/4,r=(i.spacing||0)/2,a=i.circular;if(this.pixelMargin=i.borderAlign==="inner"?.33:0,this.fullCircles=n>ht?Math.floor(n/ht):0,n===0||this.innerRadius<0||this.outerRadius<0)return;e.save();let L=(this.startAngle+this.endAngle)/2;e.translate(Math.cos(L)*o,Math.sin(L)*o);let l=1-Math.sin(Math.min(rt,n||0)),c=o*l;e.fillStyle=i.backgroundColor,e.strokeStyle=i.borderColor,nd(e,this,c,r,a),od(e,this,c,r,a),e.restore()}};Y(De,"id","arc"),Y(De,"defaults",{borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0,selfJoin:!1}),Y(De,"defaultRoutes",{backgroundColor:"backgroundColor"}),Y(De,"descriptors",{_scriptable:!0,_indexable:e=>e!=="borderDash"});ud=typeof Path2D=="function";Gt=class extends Nt{constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){let i=this.options;if((i.tension||i.cubicInterpolationMode==="monotone")&&!i.stepped&&!this._pointsUpdated){let n=i.spanGaps?this._loop:this._fullLoop;pa(this._points,i,t,n,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=xa(this,this.options.segment))}first(){let t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){let t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){let i=this.options,n=t[e],o=this.points,r=bo(this,{property:e,start:n,end:n});if(!r.length)return;let a=[],L=cd(i),l,c;for(l=0,c=r.length;lt!=="borderDash"&&t!=="fill"});Qe=class extends Nt{constructor(e){super();Y(this,"parsed");Y(this,"skip");Y(this,"stop");this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,e&&Object.assign(this,e)}inRange(e,i,n){let o=this.options,{x:r,y:a}=this.getProps(["x","y"],n);return Math.pow(e-r,2)+Math.pow(i-a,2)s.replace("rgb(","rgba(").replace(")",", 0.5)"));HL={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(s,t,e){if(!e.enabled)return;let{data:{datasets:i},options:n}=s.config,{elements:o}=n,r=Ja(i)||Sd(n)||o&&Ja(o)||kd();if(!e.forceOverride&&r)return;let a=_d(s);i.forEach(a)}};WL={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(s,t,e)=>{if(!e.enabled){tL(s);return}let i=s.width;s.data.datasets.forEach((n,o)=>{let{_data:r,indexAxis:a}=n,L=s.getDatasetMeta(o),l=r||n.data;if(_s([a,s.options.indexAxis])==="y"||!L.controller.supportsDecimation)return;let c=s.scales[L.xAxisID];if(c.type!=="linear"&&c.type!=="time"||s.options.parsing)return;let{start:d,count:h}=wd(L,l),u=e.threshold||4*i;if(h<=u){ZL(n);return}st(r)&&(n._data=l,delete n.data,Object.defineProperty(n,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(g){this._data=g}}));let f;switch(e.algorithm){case"lttb":f=Ed(l,d,h,i,e);break;case"min-max":f=Md(l,d,h,i);break;default:throw new Error(`Unsupported decimation algorithm '${e.algorithm}'`)}n._decimated=f})},destroy(s){tL(s)}};Ln=class{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,i){let{x:n,y:o,radius:r}=this;return e=e||{start:0,end:ht},t.arc(n,o,r,e.end,e.start,!0),!i.bounds}interpolate(t){let{x:e,y:i,radius:n}=this,o=t.angle;return{x:e+Math.cos(o)*n,y:i+Math.sin(o)*n,angle:o}}};UL={id:"filler",afterDatasetsUpdate(s,t,e){let i=(s.data.datasets||[]).length,n=[],o,r,a,L;for(r=0;r=0;--r){let a=n[r].$filler;a&&(a.line.updateControlPoints(o,a.axis),i&&a.fill&&Do(s.ctx,a,o))}},beforeDatasetsDraw(s,t,e){if(e.drawTime!=="beforeDatasetsDraw")return;let i=s.getSortedVisibleDatasetMetas();for(let n=i.length-1;n>=0;--n){let o=i[n].$filler;sL(o)&&Do(s.ctx,o,s.chartArea)}},beforeDatasetDraw(s,t,e){let i=t.meta.$filler;!sL(i)||e.drawTime!=="beforeDatasetDraw"||Do(s.ctx,i,s.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}},rL=(s,t)=>{let{boxHeight:e=t,boxWidth:i=t}=s;return s.usePointStyle&&(e=Math.min(e,t),i=s.pointStyleWidth||Math.min(i,t)),{boxWidth:i,boxHeight:e,itemHeight:Math.max(t,e)}},Gd=(s,t)=>s!==null&&t!==null&&s.datasetIndex===t.datasetIndex&&s.index===t.index,ln=class extends Nt{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){let t=this.options.labels||{},e=ct(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter(i=>t.filter(i,this.chart.data))),t.sort&&(e=e.sort((i,n)=>t.sort(i,n,this.chart.data))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){let{options:t,ctx:e}=this;if(!t.display){this.width=this.height=0;return}let i=t.labels,n=gt(i.font),o=n.size,r=this._computeTitleHeight(),{boxWidth:a,itemHeight:L}=rL(i,o),l,c;e.font=n.string,this.isHorizontal()?(l=this.maxWidth,c=this._fitRows(r,o,a,L)+10):(c=this.maxHeight,l=this._fitCols(r,n,a,L)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(c,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,n){let{ctx:o,maxWidth:r,options:{labels:{padding:a}}}=this,L=this.legendHitBoxes=[],l=this.lineWidths=[0],c=n+a,d=t;o.textAlign="left",o.textBaseline="middle";let h=-1,u=-c;return this.legendItems.forEach((f,g)=>{let m=i+e/2+o.measureText(f.text).width;(g===0||l[l.length-1]+m+2*a>r)&&(d+=c,l[l.length-(g>0?0:1)]=0,u+=c,h++),L[g]={left:0,top:u,row:h,width:m,height:n},l[l.length-1]+=m+a}),d}_fitCols(t,e,i,n){let{ctx:o,maxHeight:r,options:{labels:{padding:a}}}=this,L=this.legendHitBoxes=[],l=this.columnSizes=[],c=r-t,d=a,h=0,u=0,f=0,g=0;return this.legendItems.forEach((m,p)=>{let{itemWidth:b,itemHeight:C}=Kd(i,e,o,m,n);p>0&&u+C+2*a>c&&(d+=h+a,l.push({width:h,height:u}),f+=h+a,g++,h=u=0),L[p]={left:f,top:u,col:g,width:b,height:C},h=Math.max(h,b),u+=C+a}),d+=h,l.push({width:h,height:u}),d}adjustHitBoxes(){if(!this.options.display)return;let t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:n},rtl:o}}=this,r=We(o,this.left,this.width);if(this.isHorizontal()){let a=0,L=xt(i,this.left+n,this.right-this.lineWidths[a]);for(let l of e)a!==l.row&&(a=l.row,L=xt(i,this.left+n,this.right-this.lineWidths[a])),l.top+=this.top+t+n,l.left=r.leftForLtr(r.x(L),l.width),L+=l.width+n}else{let a=0,L=xt(i,this.top+t+n,this.bottom-this.columnSizes[a].height);for(let l of e)l.col!==a&&(a=l.col,L=xt(i,this.top+t+n,this.bottom-this.columnSizes[a].height)),l.top=L,l.left+=this.left+n,l.left=r.leftForLtr(r.x(l.left),l.width),L+=l.height+n}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){let t=this.ctx;Xs(t,this),this._draw(),Qs(t)}}_draw(){let{options:t,columnSizes:e,lineWidths:i,ctx:n}=this,{align:o,labels:r}=t,a=ut.color,L=We(t.rtl,this.left,this.width),l=gt(r.font),{padding:c}=r,d=l.size,h=d/2,u;this.drawTitle(),n.textAlign=L.textAlign("left"),n.textBaseline="middle",n.lineWidth=.5,n.font=l.string;let{boxWidth:f,boxHeight:g,itemHeight:m}=rL(r,d),p=function(y,v,x){if(isNaN(f)||f<=0||isNaN(g)||g<0)return;n.save();let k=tt(x.lineWidth,1);if(n.fillStyle=tt(x.fillStyle,a),n.lineCap=tt(x.lineCap,"butt"),n.lineDashOffset=tt(x.lineDashOffset,0),n.lineJoin=tt(x.lineJoin,"miter"),n.lineWidth=k,n.strokeStyle=tt(x.strokeStyle,a),n.setLineDash(tt(x.lineDash,[])),r.usePointStyle){let E={radius:g*Math.SQRT2/2,pointStyle:x.pointStyle,rotation:x.rotation,borderWidth:k},M=L.xPlus(y,f/2),D=v+h;ro(n,E,M,D,r.pointStyleWidth&&f)}else{let E=v+Math.max((d-g)/2,0),M=L.leftForLtr(y,f),D=Me(x.borderRadius);n.beginPath(),Object.values(D).some(A=>A!==0)?Cs(n,{x:M,y:E,w:f,h:g,radius:D}):n.rect(M,E,f,g),n.fill(),k!==0&&n.stroke()}n.restore()},b=function(y,v,x){Ee(n,x.text,y,v+m/2,l,{strikethrough:x.hidden,textAlign:L.textAlign(x.textAlign)})},C=this.isHorizontal(),S=this._computeTitleHeight();C?u={x:xt(o,this.left+c,this.right-i[0]),y:this.top+c+S,line:0}:u={x:this.left+c,y:xt(o,this.top+S+c,this.bottom-e[0].height),line:0},po(this.ctx,t.textDirection);let _=m+c;this.legendItems.forEach((y,v)=>{n.strokeStyle=y.fontColor,n.fillStyle=y.fontColor;let x=n.measureText(y.text).width,k=L.textAlign(y.textAlign||(y.textAlign=r.textAlign)),E=f+h+x,M=u.x,D=u.y;L.setWidth(this.width),C?v>0&&M+E+c>this.right&&(D=u.y+=_,u.line++,M=u.x=xt(o,this.left+c,this.right-i[u.line])):v>0&&D+_>this.bottom&&(M=u.x=M+e[u.line].width+c,u.line++,D=u.y=xt(o,this.top+S+c,this.bottom-e[u.line].height));let A=L.x(M);if(p(A,D,y),M=oa(k,M+f+h,C?M+E:this.right,t.rtl),b(L.x(M),D,y),C)u.x+=E+c;else if(typeof y.text!="string"){let N=l.lineHeight;u.y+=YL(y,N)+c}else u.y+=_}),go(this.ctx,t.textDirection)}drawTitle(){let t=this.options,e=t.title,i=gt(e.font),n=Ct(e.padding);if(!e.display)return;let o=We(t.rtl,this.left,this.width),r=this.ctx,a=e.position,L=i.size/2,l=n.top+L,c,d=this.left,h=this.width;if(this.isHorizontal())h=Math.max(...this.lineWidths),c=this.top+l,d=xt(t.align,d,this.right-h);else{let f=this.columnSizes.reduce((g,m)=>Math.max(g,m.height),0);c=l+xt(t.align,this.top,this.bottom-f-t.labels.padding-this._computeTitleHeight())}let u=xt(a,d,d+h);r.textAlign=o.textAlign($i(a)),r.textBaseline="middle",r.strokeStyle=e.color,r.fillStyle=e.color,r.font=i.string,Ee(r,e.text,u,c,i)}_computeTitleHeight(){let t=this.options.title,e=gt(t.font),i=Ct(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,n,o;if(se(t,this.left,this.right)&&se(e,this.top,this.bottom)){for(o=this.legendHitBoxes,i=0;is.chart.options.color,boxWidth:40,padding:10,generateLabels(s){let t=s.data.datasets,{labels:{usePointStyle:e,pointStyle:i,textAlign:n,color:o,useBorderRadius:r,borderRadius:a}}=s.legend.options;return s._getSortedDatasetMetas().map(L=>{let l=L.controller.getStyle(e?0:void 0),c=Ct(l.borderWidth);return{text:t[L.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!L.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(c.width+c.height)/4,strokeStyle:l.borderColor,pointStyle:i||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:r&&(a||l.borderRadius),datasetIndex:L.index}},this)}},title:{color:s=>s.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:s=>!s.startsWith("on"),labels:{_scriptable:s=>!["generateLabels","filter","sort"].includes(s)}}},ci=class extends Nt{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){let i=this.options;if(this.left=0,this.top=0,!i.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=t,this.height=this.bottom=e;let n=dt(i.text)?i.text.length:1;this._padding=Ct(i.padding);let o=n*gt(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){let t=this.options.position;return t==="top"||t==="bottom"}_drawArgs(t){let{top:e,left:i,bottom:n,right:o,options:r}=this,a=r.align,L=0,l,c,d;return this.isHorizontal()?(c=xt(a,i,o),d=e+t,l=o-i):(r.position==="left"?(c=i+t,d=xt(a,n,e),L=rt*-.5):(c=o-t,d=xt(a,e,n),L=rt*.5),l=n-e),{titleX:c,titleY:d,maxWidth:l,rotation:L}}draw(){let t=this.ctx,e=this.options;if(!e.display)return;let i=gt(e.font),o=i.lineHeight/2+this._padding.top,{titleX:r,titleY:a,maxWidth:L,rotation:l}=this._drawArgs(o);Ee(t,e.text,0,0,i,{color:e.color,maxWidth:L,rotation:l,textAlign:$i(e.align),textBaseline:"middle",translation:[r,a]})}};KL={id:"title",_element:ci,start(s,t,e){Jd(s,e)},stop(s){let t=s.titleBlock;_t.removeBox(s,t),delete s.titleBlock},beforeUpdate(s,t,e){let i=s.titleBlock;_t.configure(s,i,e),i.options=e},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}},Xi=new WeakMap,qL={id:"subtitle",start(s,t,e){let i=new ci({ctx:s.ctx,options:e,chart:s});_t.configure(s,i,e),_t.addBox(s,i),Xi.set(s,i)},stop(s){_t.removeBox(s,Xi.get(s)),Xi.delete(s)},beforeUpdate(s,t,e){let i=Xi.get(s);_t.configure(s,i,e),i.options=e},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}},oi={average(s){if(!s.length)return!1;let t,e,i=new Set,n=0,o=0;for(t=0,e=s.length;ta+L)/i.size,y:n/o}},nearest(s,t){if(!s.length)return!1;let e=t.x,i=t.y,n=Number.POSITIVE_INFINITY,o,r,a;for(o=0,r=s.length;o0){let t=s[0],e=t.chart.data.labels,i=e?e.length:0;if(this&&this.options&&this.options.mode==="dataset")return t.dataset.label||"";if(t.label)return t.label;if(i>0&&t.dataIndex{let r={before:[],lines:[],after:[]},a=dL(i,o);ie(r.before,ue(Ft(a,"beforeLabel",this,o))),ie(r.lines,Ft(a,"label",this,o)),ie(r.after,ue(Ft(a,"afterLabel",this,o))),n.push(r)}),n}getAfterBody(t,e){return cL(Ft(e.callbacks,"afterBody",this,t))}getFooter(t,e){let{callbacks:i}=e,n=Ft(i,"beforeFooter",this,t),o=Ft(i,"footer",this,t),r=Ft(i,"afterFooter",this,t),a=[];return a=ie(a,ue(n)),a=ie(a,ue(o)),a=ie(a,ue(r)),a}_createItems(t){let e=this._active,i=this.chart.data,n=[],o=[],r=[],a=[],L,l;for(L=0,l=e.length;Lt.filter(c,d,h,i))),t.itemSort&&(a=a.sort((c,d)=>t.itemSort(c,d,i))),Lt(a,c=>{let d=dL(t.callbacks,c);n.push(Ft(d,"labelColor",this,c)),o.push(Ft(d,"labelPointStyle",this,c)),r.push(Ft(d,"labelTextColor",this,c))}),this.labelColors=n,this.labelPointStyles=o,this.labelTextColors=r,this.dataPoints=a,a}update(t,e){let i=this.options.setContext(this.getContext()),n=this._active,o,r=[];if(!n.length)this.opacity!==0&&(o={opacity:0});else{let a=oi[i.position].call(this,n,this._eventPosition);r=this._createItems(i),this.title=this.getTitle(r,i),this.beforeBody=this.getBeforeBody(r,i),this.body=this.getBody(r,i),this.afterBody=this.getAfterBody(r,i),this.footer=this.getFooter(r,i);let L=this._size=aL(this,i),l=Object.assign({},a,L),c=LL(this.chart,i,l),d=lL(i,l,c,this.chart);this.xAlign=c.xAlign,this.yAlign=c.yAlign,o={opacity:1,x:d.x,y:d.y,width:L.width,height:L.height,caretX:a.x,caretY:a.y}}this._tooltipItems=r,this.$context=void 0,o&&this._resolveAnimations().update(this,o),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,n){let o=this.getCaretPosition(t,i,n);e.lineTo(o.x1,o.y1),e.lineTo(o.x2,o.y2),e.lineTo(o.x3,o.y3)}getCaretPosition(t,e,i){let{xAlign:n,yAlign:o}=this,{caretSize:r,cornerRadius:a}=i,{topLeft:L,topRight:l,bottomLeft:c,bottomRight:d}=Me(a),{x:h,y:u}=t,{width:f,height:g}=e,m,p,b,C,S,_;return o==="center"?(S=u+g/2,n==="left"?(m=h,p=m-r,C=S+r,_=S-r):(m=h+f,p=m+r,C=S-r,_=S+r),b=m):(n==="left"?p=h+Math.max(L,c)+r:n==="right"?p=h+f-Math.max(l,d)-r:p=this.caretX,o==="top"?(C=u,S=C-r,m=p-r,b=p+r):(C=u+g,S=C+r,m=p+r,b=p-r),_=C),{x1:m,x2:p,x3:b,y1:C,y2:S,y3:_}}drawTitle(t,e,i){let n=this.title,o=n.length,r,a,L;if(o){let l=We(i.rtl,this.x,this.width);for(t.x=Qi(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",r=gt(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=r.string,L=0;Lb!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,Cs(t,{x:g,y:f,w:l,h:L,radius:p}),t.fill(),t.stroke(),t.fillStyle=r.backgroundColor,t.beginPath(),Cs(t,{x:m,y:f+1,w:l-2,h:L-2,radius:p}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(g,f,l,L),t.strokeRect(g,f,l,L),t.fillStyle=r.backgroundColor,t.fillRect(m,f+1,l-2,L-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){let{body:n}=this,{bodySpacing:o,bodyAlign:r,displayColors:a,boxHeight:L,boxWidth:l,boxPadding:c}=i,d=gt(i.bodyFont),h=d.lineHeight,u=0,f=We(i.rtl,this.x,this.width),g=function(x){e.fillText(x,f.x(t.x+u),t.y+h/2),t.y+=h+o},m=f.textAlign(r),p,b,C,S,_,y,v;for(e.textAlign=r,e.textBaseline="middle",e.font=d.string,t.x=Qi(this,m,i),e.fillStyle=i.bodyColor,Lt(this.beforeBody,g),u=a&&m!=="right"?r==="center"?l/2+c:l+2+c:0,S=0,y=n.length;S0&&e.stroke()}_updateAnimationTarget(t){let e=this.chart,i=this.$animations,n=i&&i.x,o=i&&i.y;if(n||o){let r=oi[t.position].call(this,this._active,this._eventPosition);if(!r)return;let a=this._size=aL(this,t),L=Object.assign({},r,this._size),l=LL(e,t,L),c=lL(t,L,l,e);(n._to!==c.x||o._to!==c.y)&&(this.xAlign=l.xAlign,this.yAlign=l.yAlign,this.width=a.width,this.height=a.height,this.caretX=r.x,this.caretY=r.y,this._resolveAnimations().update(this,c))}}_willRender(){return!!this.opacity}draw(t){let e=this.options.setContext(this.getContext()),i=this.opacity;if(!i)return;this._updateAnimationTarget(e);let n={width:this.width,height:this.height},o={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;let r=Ct(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(o,t,n,e),po(t,e.textDirection),o.y+=r.top,this.drawTitle(o,t,e),this.drawBody(o,t,e),this.drawFooter(o,t,e),go(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){let i=this._active,n=t.map(({datasetIndex:a,index:L})=>{let l=this.chart.getDatasetMeta(a);if(!l)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:l.data[L],index:L}}),o=!qs(i,n),r=this._positionChanged(n,e);(o||r)&&(this._active=n,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;let n=this.options,o=this._active||[],r=this._getActiveElements(t,o,e,i),a=this._positionChanged(r,t),L=e||!qs(r,o)||a;return L&&(this._active=r,(n.enabled||n.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),L}_getActiveElements(t,e,i,n){let o=this.options;if(t.type==="mouseout")return[];if(!n)return e.filter(a=>this.chart.data.datasets[a.datasetIndex]&&this.chart.getDatasetMeta(a.datasetIndex).controller.getParsed(a.index)!==void 0);let r=this.chart.getElementsAtEventForMode(t,o.mode,o,i);return o.reverse&&r.reverse(),r}_positionChanged(t,e){let{caretX:i,caretY:n,options:o}=this,r=oi[o.position].call(this,t,e);return r!==!1&&(i!==r.x||n!==r.y)}};Y(ri,"positioners",oi);QL={id:"tooltip",_element:ri,positioners:oi,afterInit(s,t,e){e&&(s.tooltip=new ri({chart:s,options:e}))},beforeUpdate(s,t,e){s.tooltip&&s.tooltip.initialize(e)},reset(s,t,e){s.tooltip&&s.tooltip.initialize(e)},afterDraw(s){let t=s.tooltip;if(t&&t._willRender()){let e={tooltip:t};if(s.notifyPlugins("beforeTooltipDraw",{...e,cancelable:!0})===!1)return;t.draw(s.ctx),s.notifyPlugins("afterTooltipDraw",e)}},afterEvent(s,t){if(s.tooltip){let e=t.replay;s.tooltip.handleEvent(t.event,e,t.inChartArea)&&(t.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(s,t)=>t.bodyFont.size,boxWidth:(s,t)=>t.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:XL},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:s=>s!=="filter"&&s!=="itemSort"&&s!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]},JL=Object.freeze({__proto__:null,Colors:HL,Decimation:WL,Filler:UL,Legend:GL,SubTitle:qL,Title:KL,Tooltip:QL}),a5=(s,t,e,i)=>(typeof t=="string"?(e=s.push(t)-1,i.unshift({index:e,label:t})):isNaN(t)&&(e=null),e);l5=(s,t)=>s===null?null:mt(Math.round(s),0,t);Ms=class extends Oe{constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){let e=this._addedLabels;if(e.length){let i=this.getLabels();for(let{index:n,label:o}of e)i[n]===o&&i.splice(n,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(st(t))return null;let i=this.getLabels();return e=isFinite(e)&&i[e]===t?e:L5(i,t,tt(e,t),this._addedLabels),l5(e,i.length-1)}determineDataLimits(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),{min:i,max:n}=this.getMinMax(!0);this.options.bounds==="ticks"&&(t||(i=0),e||(n=this.getLabels().length-1)),this.min=i,this.max=n}buildTicks(){let t=this.min,e=this.max,i=this.options.offset,n=[],o=this.getLabels();o=t===0&&e===o.length-1?o:o.slice(t,e+1),this._valueRange=Math.max(o.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let r=t;r<=e;r++)n.push({value:r});return n}getLabelForValue(t){return hL.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return typeof t!="number"&&(t=this.parse(t)),t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){let e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}};Y(Ms,"id","category"),Y(Ms,"defaults",{ticks:{callback:hL}});As=class extends Oe{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return st(t)||(typeof t=="number"||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){let{beginAtZero:t}=this.options,{minDefined:e,maxDefined:i}=this.getUserBounds(),{min:n,max:o}=this,r=L=>n=e?n:L,a=L=>o=i?o:L;if(t){let L=Ut(n),l=Ut(o);L<0&&l<0?a(0):L>0&&l>0&&r(0)}if(n===o){let L=o===0?1:Math.abs(o*.05);a(o+L),t||r(n-L)}this.min=n,this.max=o}getTickLimit(){let t=this.options.ticks,{maxTicksLimit:e,stepSize:i}=t,n;return i?(n=Math.ceil(this.max/i)-Math.floor(this.min/i)+1,n>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${i} would result generating up to ${n} ticks. Limiting to 1000.`),n=1e3)):(n=this.computeTickLimit(),e=e||11),e&&(n=Math.min(e,n)),n}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){let t=this.options,e=t.ticks,i=this.getTickLimit();i=Math.max(2,i);let n={maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:e.includeBounds!==!1},o=this._range||this,r=c5(n,o);return t.bounds==="ticks"&&Gn(r,this,"value"),t.reverse?(r.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),r}configure(){let t=this.ticks,e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){let n=(i-e)/Math.max(t.length-1,1)/2;e-=n,i+=n}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ys(t,this.chart.options.locale,this.options.ticks.format)}},ws=class extends As{determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=ft(t)?t:0,this.max=ft(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){let t=this.isHorizontal(),e=t?this.width:this.height,i=Zt(this.options.ticks.minRotation),n=(t?Math.sin(i):Math.cos(i))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,o.lineHeight/n))}getPixelForValue(t){return t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}};Y(ws,"id","linear"),Y(ws,"defaults",{ticks:{callback:xs.formatters.numeric}});di=s=>Math.floor(ce(s)),Ue=(s,t)=>Math.pow(10,di(s)+t);Ds=class extends Oe{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){let i=As.prototype.parse.apply(this,[t,e]);if(i===0){this._zero=!0;return}return ft(i)&&i>0?i:null}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=ft(t)?Math.max(0,t):null,this.max=ft(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!ft(this._userMin)&&(this.min=t===Ue(this.min,0)?Ue(this.min,-1):Ue(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),i=this.min,n=this.max,o=a=>i=t?i:a,r=a=>n=e?n:a;i===n&&(i<=0?(o(1),r(10)):(o(Ue(i,-1)),r(Ue(n,1)))),i<=0&&o(Ue(n,-1)),n<=0&&r(Ue(i,1)),this.min=i,this.max=n}buildTicks(){let t=this.options,e={min:this._userMin,max:this._userMax},i=h5(e,this);return t.bounds==="ticks"&&Gn(i,this,"value"),t.reverse?(i.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),i}getLabelForValue(t){return t===void 0?"0":ys(t,this.chart.options.locale,this.options.ticks.format)}configure(){let t=this.min;super.configure(),this._startValue=ce(t),this._valueRange=ce(this.max)-ce(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(ce(t)-this._startValue)/this._valueRange)}getValueForPixel(t){let e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}};Y(Ds,"id","logarithmic"),Y(Ds,"defaults",{ticks:{callback:xs.formatters.logarithmic,major:{enabled:!0}}});Te=class extends As{constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){let t=this._padding=Ct(zo(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!1);this.min=ft(t)&&!isNaN(t)?t:0,this.max=ft(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/zo(this.options))}generateTickLabels(t){As.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((e,i)=>{let n=ct(this.options.pointLabels.callback,[e,i],this);return n||n===0?n:""}).filter((e,i)=>this.chart.getDataVisibility(i))}fit(){let t=this.options;t.display&&t.pointLabels.display?f5(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,n){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-n)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,n))}getIndexAngle(t){let e=ht/(this._pointLabels.length||1),i=this.options.startAngle||0;return yt(t*e+Zt(i))}getDistanceFromCenterForValue(t){if(st(t))return NaN;let e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(st(t))return NaN;let e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){let e=this._pointLabels||[];if(t>=0&&t{if(d!==0||d===0&&this.min<0){L=this.getDistanceFromCenterForValue(c.value);let h=this.getContext(d),u=n.setContext(h),f=o.setContext(h);S5(this,u,L,r,f)}}),i.display){for(t.save(),a=r-1;a>=0;a--){let c=i.setContext(this.getPointLabelContext(a)),{color:d,lineWidth:h}=c;!h||!d||(t.lineWidth=h,t.strokeStyle=d,t.setLineDash(c.borderDash),t.lineDashOffset=c.borderDashOffset,L=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,L),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){let t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;let n=this.getIndexAngle(0),o,r;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(n),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach((a,L)=>{if(L===0&&this.min>=0&&!e.reverse)return;let l=i.setContext(this.getContext(L)),c=gt(l.font);if(o=this.getDistanceFromCenterForValue(this.ticks[L].value),l.showLabelBackdrop){t.font=c.string,r=t.measureText(a.label).width,t.fillStyle=l.backdropColor;let d=Ct(l.backdropPadding);t.fillRect(-r/2-d.left,-o-c.size/2-d.top,r+d.width,c.size+d.height)}Ee(t,a.label,0,-o,c,{color:l.color,strokeColor:l.textStrokeColor,strokeWidth:l.textStrokeWidth})}),t.restore()}drawTitle(){}};Y(Te,"id","radialLinear"),Y(Te,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:xs.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),Y(Te,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),Y(Te,"descriptors",{angleLines:{_fallback:"grid"}});dn={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Vt=Object.keys(dn);Pe=class extends Oe{constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){let i=t.time||(t.time={}),n=this._adapter=new kL._date(t.adapters.date);n.init(e),gs(i.displayFormats,n.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return t===void 0?null:bL(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){let t=this.options,e=this._adapter,i=t.time.unit||"day",{min:n,max:o,minDefined:r,maxDefined:a}=this.getUserBounds();function L(l){!r&&!isNaN(l.min)&&(n=Math.min(n,l.min)),!a&&!isNaN(l.max)&&(o=Math.max(o,l.max))}(!r||!a)&&(L(this._getLabelBounds()),(t.bounds!=="ticks"||t.ticks.source!=="labels")&&L(this.getMinMax(!1))),n=ft(n)&&!isNaN(n)?n:+e.startOf(Date.now(),i),o=ft(o)&&!isNaN(o)?o:+e.endOf(Date.now(),i)+1,this.min=Math.min(n,o-1),this.max=Math.max(n+1,o)}_getLabelBounds(){let t=this.getLabelTimestamps(),e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){let t=this.options,e=t.time,i=t.ticks,n=i.source==="labels"?this.getLabelTimestamps():this._generate();t.bounds==="ticks"&&n.length&&(this.min=this._userMin||n[0],this.max=this._userMax||n[n.length-1]);let o=this.min,r=this.max,a=ea(n,o,r);return this._unit=e.unit||(i.autoSkip?vL(e.minUnit,this.min,this.max,this._getLabelCapacity(o)):E5(this,a.length,e.minUnit,this.min,this.max)),this._majorUnit=!i.major.enabled||this._unit==="year"?void 0:M5(this._unit),this.initOffsets(n),t.reverse&&a.reverse(),xL(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(t=>+t.value))}initOffsets(t=[]){let e=0,i=0,n,o;this.options.offset&&t.length&&(n=this.getDecimalForValue(t[0]),t.length===1?e=1-n:e=(this.getDecimalForValue(t[1])-n)/2,o=this.getDecimalForValue(t[t.length-1]),t.length===1?i=o:i=(o-this.getDecimalForValue(t[t.length-2]))/2);let r=t.length<3?.5:.25;e=mt(e,0,r),i=mt(i,0,r),this._offsets={start:e,end:i,factor:1/(e+1+i)}}_generate(){let t=this._adapter,e=this.min,i=this.max,n=this.options,o=n.time,r=o.unit||vL(o.minUnit,e,i,this._getLabelCapacity(e)),a=tt(n.ticks.stepSize,1),L=r==="week"?o.isoWeekday:!1,l=Ze(L)||L===!0,c={},d=e,h,u;if(l&&(d=+t.startOf(d,"isoWeek",L)),d=+t.startOf(d,l?"day":r),t.diff(i,e,r)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+r);let f=n.ticks.source==="data"&&this.getDataTimestamps();for(h=d,u=0;h+g)}getLabelForValue(t){let e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){let n=this.options.time.displayFormats,o=this._unit,r=e||n[o];return this._adapter.format(t,r)}_tickFormatFunction(t,e,i,n){let o=this.options,r=o.ticks.callback;if(r)return ct(r,[t,e,i],this);let a=o.time.displayFormats,L=this._unit,l=this._majorUnit,c=L&&a[L],d=l&&a[l],h=i[e],u=l&&d&&h&&h.major;return this._adapter.format(t,n||(u?d:c))}generateTickLabels(t){let e,i,n;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t=this._cache.data||[],e,i;if(t.length)return t;let n=this.getMatchingVisibleMetas();if(this._normalized&&n.length)return this._cache.data=n[0].controller.getAllParsedValues(this);for(e=0,i=n.length;e=e&&l<=i&&n.push(l);if(n.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(r=0,a=n.length;rn-o)}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;let e=this.getDataTimestamps(),i=this.getLabelTimestamps();return e.length&&i.length?t=this.normalize(e.concat(i)):t=e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(Ji(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){let e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return Ji(this._table,i*this._tableRange+this._minPos,!0)}};Y(Ts,"id","timeseries"),Y(Ts,"defaults",Pe.defaults);el=Object.freeze({__proto__:null,CategoryScale:Ms,LinearScale:ws,LogarithmicScale:Ds,RadialLinearScale:Te,TimeScale:Pe,TimeSeriesScale:Ts}),D5=[SL,BL,JL,el]});var nh={};sr(nh,{CardView:()=>Fs,default:()=>kn});module.exports=Nl(nh);var at=require("obsidian"),Tl=Ns(is());var Bl=["AT","BE","CZ","DK","EE","FI","FR","DE","GR","HU","IS","IT","LV","LI","LT","LU","MT","NL","NO","PL","PT","SK","SI","ES","SE","CH"],$l=[{label:"\u{1F1EA}\u{1F1FA} Schengen 90/180 (example)",scope:{countries:Bl},window:{type:"rolling",days:180},threshold:90,note:"Example rule \u2014 add your own in Settings \u2192 CSV Card View."}],Tn={defaultMode:"kanban-genre",notesColumns:["notes","note","Notes","Note","description","Description","review","Review"],statusColumn:"status",categoryColumn:"category",notesSubfolder:"Notes",columnWidths:{},selectColumns:["Category","Type","Rating","Status","rating","type","category","status","Score /5"],fileConfigs:{},residencyRules:$l,showResidency:!0},ui="xlsx-card-view";var nr=Ns(is()),fi=require("obsidian");var ns=["Image","image","Cover","cover","Poster","poster","Thumbnail","thumbnail","Thumb","thumb","Photo","photo","Picture","picture","Img","img"],fe=["Title","title","Name","name"],os=["Category","category","Categories","categories","Genre","genre","Genres","genres","Type","type","Types","types","Tag","tag","Tags","tags","Topic","topic","Topics","topics","Subject","subject","Section","section"],rs=["Status","status","State","state","Progress","progress","Stage","stage","Read","read","Watched","watched","Seen","seen","Done","done","Completed","completed"],pe=["Notes","notes","Note","note","Summary","summary","Review","review","Quote","quote","Quotes","quotes","Comment","comment","Comments","comments","Description","description","Annotation","annotation"],pi=["Price","price","Cost","cost","Amount","amount","Total","total","Spend","spend","Spent","spent","Value","value"];function gi(s,t,e){let i=(t!=null?t:"").trim();if(!i)return null;if(/^(https?:|data:)/i.test(i))return i;let n=i.match(/!?\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/);if(n)i=n[1].trim();else{let r=i.match(/!\[[^\]]*\]\(([^)]+)\)/);r&&(i=r[1].trim())}if(/^(https?:|data:)/i.test(i))return i;let o=s.metadataCache.getFirstLinkpathDest(i,e);return o instanceof fi.TFile?s.vault.getResourcePath(o):null}var zl=15;function Xt(s){return s>=1&&s<=zl}var Hl=["0","1","true","false","yes","no",""];function as(s){return s.length>0&&s.every(t=>Hl.includes(t))}function Ls(s){let t=(s!=null?s:"").toLowerCase().trim();return t==="1"||t==="true"||t==="yes"}function ge(s=new Date){return`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`}function Ve(s){return s.replace(/[\\/:*?"<>|#^[\]]/g,"").replace(/\s+/g," ").trim().slice(0,100)}function or(s){return s.toLowerCase().replace(/[^\p{L}\p{N}/_-]+/gu,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function kt(s){var n,o;if(!s||!s.trim())return{headers:[],rows:[]};let t=nr.default.parse(s,{header:!0,skipEmptyLines:!0}),e=((n=t.meta.fields)!=null?n:[]).map(String),i=((o=t.data)!=null?o:[]).map(r=>{let a={};return e.forEach(L=>{a[L]=r[L]!=null?String(r[L]):""}),a});return{headers:e,rows:i}}function Qt(s,t){if(!s)return s;let e=s.startsWith("./")||s.startsWith("../")||s==="."||s==="..";if(!e&&s.includes("/"))return s;if(!e)return t?`${t}/${s}`:s;let i=t?t.split("/").filter(Boolean):[];for(let n of s.split("/"))if(!(n===""||n===".")){if(n===".."){i.pop();continue}i.push(n)}return i.join("/")}function rr(s,t,e){let i=e==="asc"?1:-1;return[...s].sort((n,o)=>{var h,u;let r=((h=n[t])!=null?h:"").trim(),a=((u=o[t])!=null?u:"").trim();if(!r&&!a)return 0;if(!r)return 1;if(!a)return-1;let L=parseFloat(r),l=parseFloat(a);return(!isNaN(L)&&!isNaN(l)&&/^-?[\d.]/.test(r)&&/^-?[\d.]/.test(a)?L-l:r.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"}))*i})}function Tt(s){return s.split(/[\s_-]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function ar(s,t){let e=(s!=null?s:"").trim();if(!e||e.toLowerCase()==="unrated"||e==="\u2014"||e==="-")return"";if(/[★⭐☆]/.test(e))return e;if(/^\d+$/.test(e)){let o=parseInt(e,10);if(o>=1&&o<=5)return"\u2605".repeat(o)}let n=Zl(e,t);return n&&n!==e&&n!=="\u2014"?n:""}function Zl(s,t){var o;let e=t.toLowerCase();if(!["rating","score","score /5"].includes(e))return s;let i=s.toLowerCase().trim();return(o={excellent:"\u2605\u2605\u2605\u2605\u2605",great:"\u2605\u2605\u2605\u2605\u2605",good:"\u2605\u2605\u2605\u2605\u2606",fair:"\u2605\u2605\u2605\u2606\u2606",poor:"\u2605\u2605\u2606\u2606\u2606",bad:"\u2605\u2606\u2606\u2606\u2606",5:"\u2605\u2605\u2605\u2605\u2605",4:"\u2605\u2605\u2605\u2605\u2606",3:"\u2605\u2605\u2605\u2606\u2606",2:"\u2605\u2605\u2606\u2606\u2606",1:"\u2605\u2606\u2606\u2606\u2606",0:"\u2606\u2606\u2606\u2606\u2606",unrated:"\u2014","":"\u2014"}[i])!=null?o:s}function Lr(s,t){if(/^(year|released|decade)$/i.test((s!=null?s:"").trim()))return!0;let e=t.map(n=>(n!=null?n:"").trim()).filter(Boolean);return e.length<3?!1:e.filter(n=>/^(1[89]|20)\d{2}$/.test(n)).length/e.length>=.8}function lr(s){let t=(s!=null?s:"").match(/\b(1[89]\d{2}|20\d{2})\b/);return t?`${Math.floor(parseInt(t[1],10)/10)*10}s`:null}function cr(s,t,e){var r;if(!t.length)return null;let i=Math.max(12,t.length/3),n=null,o=1/0;for(let a of s){if(e.has(a))continue;let L=new Set;for(let c of t)((r=c[a])!=null?r:"").split(",").forEach(d=>{let h=d.trim();h&&L.add(h)});if(L.size<2||L.size>i)continue;let l=Math.abs(Math.log(L.size/8));lM.remove());let r=document.body.createDiv({cls:"csv-select-picker"}),a=()=>{let M=s.getBoundingClientRect(),D=r.offsetHeight||280,A=M.bottom+4+D>window.innerHeight&&M.top-4-D>0;r.style.left=M.left+"px",r.style.top=A?M.top-4-D+"px":M.bottom+4+"px"};a();let L=M=>{!r.contains(M.target)&&M.target!==s&&c()},l=M=>{r.contains(M.target)||c()},c=()=>{r.remove(),document.removeEventListener("mousedown",L),window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",c)},d=r.createEl("input",{cls:"csv-picker-search",type:"text",placeholder:"Search or add\u2026"});d.focus();let h=r.createDiv({cls:"csv-picker-list"}),u=!!(o!=null&&o.multi),f=M=>M.split(",").map(D=>D.trim()).filter(Boolean),g=new Set(u?f(t):[]),m=()=>i([...g].join(", ")),p=u?Array.from(new Set(e.flatMap(f))):Array.from(new Set(e.filter(Boolean))),b=[],C=0,S=()=>{h.querySelectorAll(".csv-picker-item").forEach((M,D)=>{M.toggleClass("csv-picker-item--hover",D===C),D===C&&M.scrollIntoView({block:"nearest"})})},_=M=>{if(!u){i(M.isClear?"":M.value),c();return}M.isClear?g.clear():(g.has(M.value)?g.delete(M.value):g.add(M.value),M.isAdd&&!p.includes(M.value)&&p.push(M.value)),m(),M.isAdd?(d.value="",x("")):x(d.value)},y=M=>u?g.has(M):M===t.trim(),v=()=>u?g.size>0:!!t,x=M=>{h.empty(),b=[];let D=M?p.filter(A=>A.toLowerCase().includes(M.toLowerCase())):p;if(v()){b.push({value:"",isClear:!0});let A=h.createDiv({cls:"csv-picker-item csv-picker-clear"});A.setText(u?"\u2715 Clear all":"\u2715 Clear"),A.addEventListener("mousedown",N=>{N.preventDefault(),_({value:"",isClear:!0})})}if(D.forEach(A=>{b.push({value:A});let N=h.createDiv({cls:`csv-picker-item ${y(A)?"active":""}`});N.setText(u?`${g.has(A)?"\u2713 ":""}${A}`:A),N.addEventListener("mousedown",I=>{I.preventDefault(),_({value:A})})}),M&&!p.some(A=>A.toLowerCase()===M.toLowerCase())){b.push({value:M,isAdd:!0});let A=h.createDiv({cls:"csv-picker-item csv-picker-add"});A.setText(`+ Add "${M}"`),A.addEventListener("mousedown",N=>{N.preventDefault(),_({value:M,isAdd:!0})})}!D.length&&!M&&h.createDiv({cls:"csv-picker-empty",text:"No options yet. Type to add."}),C=Math.min(C,Math.max(b.length-1,0)),S()};u&&r.createEl("button",{cls:"csv-picker-done",text:"Done"}).addEventListener("mousedown",M=>{M.preventDefault(),c()}),x(""),a(),d.addEventListener("input",()=>{C=0,x(d.value),a()});let k=typeof window!="undefined"&&((E=window.matchMedia)==null?void 0:E.call(window,"(pointer: coarse)").matches);window.setTimeout(()=>{document.addEventListener("mousedown",L),k||(window.addEventListener("scroll",l,!0),window.addEventListener("resize",c))},0),d.addEventListener("keydown",M=>{if(M.key==="Escape"){c();return}if(M.key==="ArrowDown"){M.preventDefault(),b.length&&(C=(C+1)%b.length,S());return}if(M.key==="ArrowUp"){M.preventDefault(),b.length&&(C=(C-1+b.length)%b.length,S());return}if(M.key==="Enter")if(M.preventDefault(),b[C])_(b[C]);else{let D=d.value.trim();D&&(i(D),c())}})}async function ls(s,t,e){var L,l;let i=(l=(L=t.parent)==null?void 0:L.path)!=null?l:"",n=i?`${i}/Archive`:"Archive";await s.vault.adapter.exists(n)||await s.vault.adapter.mkdir(n);let o=new Date,r=`${ge(o)} ${String(o.getHours()).padStart(2,"0")}${String(o.getMinutes()).padStart(2,"0")}${String(o.getSeconds()).padStart(2,"0")}`,a=`${n}/${t.basename} sync-conflict ${r}.csv`;return await s.vault.adapter.write(a,e),new fi.Notice(`"${t.name}" changed on disk while you were editing (another device?). That version was saved to ${a} \u2014 your edits won.`,1e4),a}function dr(s,t,e){return!s[t]||t===e||(s[e]||(s[e]=s[t]),delete s[t]),s}var Wl={source:["confirmed","inferred","conflict"],resolved:["yes","no"]};function hr(s){var t;return(t=Wl[s.trim().toLowerCase()])!=null?t:null}function Et(s){return/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(s.trim())}var mi=/^\d{4}-\d{2}-\d{2}$/;var At=require("obsidian");function yi(s,t,e,i,n=Et){let o=n(t)&&(e===""||mi.test(e.slice(0,10))),r=o?e.slice(0,10):e,a=s.createEl("input",{cls:i,type:o?"date":"text",value:r});o||(a.placeholder=t);let L=hr(t);if(L){let l=`csv-dl-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-${Math.random().toString(36).slice(2,7)}`,c=s.createEl("datalist");c.id=l,L.forEach(d=>c.createEl("option",{value:d})),a.setAttr("list",l)}return a}var cs=class extends At.Modal{constructor(t,e,i,n,o,r,a={},L=()=>!1,l,c,d=Et){super(t),this.headers=e,this.isNotesCol=i,this.isSelectCol=n,this.getColumnValues=o,this.onSubmit=r,this.optionPresets=a,this.isBooleanCol=L,this.isCategoricalCol=l!=null?l:h=>this.isSelectCol(h)||Xt(this.getColumnValues(h).length),this.titleCol=c!=null?c:this.headers.find(h=>["title","name"].includes(h.toLowerCase())),this.isDateCol=d}onOpen(){let{contentEl:t}=this;t.empty(),t.addClass("csv-add-modal"),t.createEl("h2",{text:"Add new entry",cls:"csv-modal-title"});let e=t.createDiv({cls:"csv-modal-form"}),i={};this.headers.forEach(c=>i[c]="");let n=this.titleCol,o=new Map;n&&this.getColumnValues(n).forEach(c=>{let d=c.trim().toLowerCase();d&&!o.has(d)&&o.set(d,c.trim())}),this.headers.forEach(c=>{var m;let d=e.createDiv({cls:"csv-modal-row"});d.createEl("label",{text:Tt(c),cls:"csv-modal-label"});let h=(m=this.optionPresets[c])!=null?m:[],u=c===n,f=vt(c),g=!u&&!this.isNotesCol(c)&&!f&&(h.length>0||this.isCategoricalCol(c));if(this.isBooleanCol(c)){i[c]="0";let p=d.createDiv({cls:"csv-toggle"});p.createDiv({cls:"csv-toggle-knob"}),p.addEventListener("click",()=>{let b=!p.hasClass("is-on");p.toggleClass("is-on",b),i[c]=b?"1":"0"})}else if(this.isNotesCol(c)){let p=d.createEl("textarea",{cls:"csv-modal-textarea",placeholder:"Markdown supported\u2026"});p.addEventListener("input",()=>{i[c]=p.value})}else if(g){let p="__custom__",b=[];[...h,...this.getColumnValues(c)].forEach(_=>{let y=(_!=null?_:"").trim();y&&!b.some(v=>v.toLowerCase()===y.toLowerCase())&&b.push(y)});let C=d.createEl("select",{cls:"csv-modal-select"});C.createEl("option",{text:"\u2014",value:""}),b.forEach(_=>C.createEl("option",{text:_,value:_})),C.createEl("option",{text:"+ custom\u2026",value:p});let S=d.createEl("input",{cls:"csv-modal-input csv-modal-custom",type:"text",placeholder:`Custom ${Tt(c).toLowerCase()}`});S.hide(),S.addEventListener("input",()=>{i[c]=S.value}),S.addEventListener("keydown",_=>{_.key==="Enter"&&l()}),C.addEventListener("change",()=>{C.value===p?(S.show(),S.focus(),i[c]=S.value):(S.hide(),i[c]=C.value)})}else if(!u&&f&&this.isSelectCol(c)){let b=d.createDiv({cls:"csv-modal-select-wrap"}).createDiv({cls:"csv-select-chip empty"});b.setText("\u2014 click to select \u2014"),b.addEventListener("click",C=>{C.stopPropagation(),$t(b,i[c],this.getColumnValues(c),S=>{i[c]=S,b.setText(S||"\u2014 click to select \u2014"),b.toggleClass("empty",!S)},t,{multi:vt(c)})})}else{let p=yi(d,c,"","csv-modal-input",b=>this.isDateCol(b));if(p.addEventListener("input",()=>{i[c]=p.value}),p.addEventListener("keydown",b=>{b.key==="Enter"&&l()}),c===n&&o.size){let b=d.createDiv({cls:"csv-modal-dup-hint"});b.hide(),p.addEventListener("input",()=>{let C=o.get(p.value.trim().toLowerCase());C?(b.setText(`\u26A0 \u201C${C}\u201D is already in this file`),b.show()):b.hide()})}}});let r=t.createDiv({cls:"csv-modal-btns"});r.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),r.createEl("button",{text:"Add entry",cls:"csv-modal-submit"}).addEventListener("click",()=>l());let l=()=>{if(!Object.values(i).some(d=>d.trim())){new At.Notice("Fill in at least one field.");return}this.onSubmit(i),this.close()}}onClose(){this.contentEl.empty()}},me=class extends At.Modal{constructor(e,i,n,o,r,a,L,l,c,d,h,u,f=()=>!1,g=Et){super(e);this.vvHandler=null;this.row={...i},this.notesCol=n,this.headers=o,this.filePath=r,this.renderComponent=new At.Component,this.isNotesCol=a,this.isSelectCol=L,this.getColumnValues=l,this.onSave=c,this.onDelete=d,this.isCategoricalCol=h!=null?h:m=>this.isSelectCol(m)||!Et(m)&&Xt(this.getColumnValues(m).length),this.titleCol=u!=null?u:this.headers.find(m=>["title","name","Title","Name"].includes(m)),this.isBooleanCol=f,this.isDateCol=g,this.modalEl.addClass("csv-note-expander-modal")}onOpen(){var h,u,f,g,m;this.renderComponent.load();let{contentEl:e}=this;e.empty(),e.addClass("csv-note-expander");let i=window.visualViewport;if(i){let p=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${i.height}px`)};p(),i.addEventListener("resize",p),i.addEventListener("scroll",p),this.vvHandler=p}e.createDiv({cls:"csv-expander-header"}).createDiv({cls:"csv-expander-title",text:(u=this.row[(h=this.titleCol)!=null?h:this.headers[0]])!=null?u:"\u2014"});let o=e.createDiv({cls:"csv-expander-fields"}),r=this.titleCol;this.headers.forEach(p=>{var _;if(this.isNotesCol(p))return;let b=o.createDiv({cls:"csv-expander-field-row"});if(b.createDiv({cls:"csv-expander-field-label",text:Tt(p)}),this.isBooleanCol(p)){let y=Ls((_=this.row[p])!=null?_:""),v=b.createDiv({cls:`csv-toggle ${y?"is-on":""}`});v.createDiv({cls:"csv-toggle-knob"}),v.addEventListener("click",()=>{let x=!v.hasClass("is-on");v.toggleClass("is-on",x),this.row[p]=x?"1":"0"});return}let C=vt(p);if(p!==r&&(C?this.isSelectCol(p):this.isCategoricalCol(p))){let y=b.createDiv({cls:`csv-select-chip ${this.row[p]?"":"empty"}`});y.setText(this.row[p]||"\u2014"),y.addEventListener("click",v=>{v.stopPropagation(),$t(y,this.row[p],this.getColumnValues(p),x=>{this.row[p]=x,y.setText(x||"\u2014"),y.toggleClass("empty",!x)},e,{multi:vt(p)})})}else{let y=b.createDiv({cls:"csv-expander-field-value",text:this.row[p]||"\u2014"});y.addEventListener("click",()=>{var k;if(y.querySelector("input"))return;y.empty();let v=yi(y,p,(k=this.row[p])!=null?k:"","csv-inline-input",this.isDateCol);v.focus(),v.type==="text"&&v.select(),v.addEventListener("click",E=>E.stopPropagation());let x=()=>{this.row[p]=v.value,y.empty(),y.setText(v.value||"\u2014")};v.addEventListener("blur",x),v.addEventListener("keydown",E=>{E.key==="Enter"&&v.blur(),E.key==="Escape"&&(y.empty(),y.setText(this.row[p]||"\u2014"))})})}});let a=!1,L=this.notesCol&&(f=this.row[this.notesCol])!=null?f:"",l=null;if(this.notesCol){e.createDiv({cls:"csv-expander-divider"}).createDiv({cls:"csv-expander-notes-label",text:this.notesCol});let b=e.createDiv({cls:"csv-expander-rendered markdown-rendered"});b.title="Click to edit";let C=e.createDiv({cls:"csv-expander-editor is-hidden"}),S=()=>{b.empty(),L.trim()?At.MarkdownRenderer.render(this.app,L,b,this.filePath,this.renderComponent):b.createDiv({cls:"csv-notes-empty",text:"+ add note"})};S(),l=C.createEl("textarea",{cls:"csv-expander-textarea"}),l.value=L,l.addEventListener("input",()=>{L=l.value});let _=()=>{a||(a=!0,b.classList.add("is-hidden"),C.classList.remove("is-hidden"),l.value=L,l.focus())},y=()=>{a&&(a=!1,C.classList.add("is-hidden"),b.classList.remove("is-hidden"),L=l.value,S())};b.addEventListener("click",v=>{if(v.target.closest("a, button, input, textarea, [contenteditable]"))return;let k=window.getSelection();k&&k.toString().length>0||_()}),l.addEventListener("keydown",v=>{v.key==="Escape"&&(v.preventDefault(),l.blur())}),l.addEventListener("blur",y)}let c=e.createDiv({cls:"csv-expander-footer"});if(this.onDelete){let p=String((m=this.row[(g=this.titleCol)!=null?g:this.headers[0]])!=null?m:"").trim(),b=c.createEl("button",{cls:"csv-expander-delete-btn",text:"Delete",attr:{title:`Delete "${p||"this entry"}"? This can't be undone.`}});b.addEventListener("click",()=>{if(b.hasClass("confirm")){this.onDelete(),this.close();return}b.addClass("confirm"),b.setText("Confirm?"),window.setTimeout(()=>{b.isConnected&&(b.removeClass("confirm"),b.setText("Delete"))},3e3)})}let d=c.createDiv({cls:"csv-expander-footer-right"});d.createEl("button",{cls:"csv-modal-cancel",text:"Cancel"}).addEventListener("click",()=>this.close()),d.createEl("button",{cls:"csv-expander-save-btn",text:"Save & close"}).addEventListener("click",()=>{this.notesCol&&(a&&l&&(L=l.value),this.row[this.notesCol]=L),this.onSave(this.row),this.close()})}onClose(){let e=window.visualViewport;e&&this.vvHandler&&(e.removeEventListener("resize",this.vvHandler),e.removeEventListener("scroll",this.vvHandler)),this.vvHandler=null,this.renderComponent.unload(),this.contentEl.empty()}},bi=class extends At.Modal{constructor(e,i,n,o,r,a){super(e);this.vvHandler=null;this.initialQuery=i,this.onInput=n,this.resultCount=o,this.getMatches=r,this.onPick=a,this.modalEl.addClass("csv-search-modal")}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("csv-search-modal-content"),this.containerEl.addClass("mod-csv-search-bg");let i=window.visualViewport;if(i){let h=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${i.height}px`)};h(),i.addEventListener("resize",h),i.addEventListener("scroll",h),this.vvHandler=h}let n=e.createDiv({cls:"csv-search-modal-row"}),o=n.createEl("input",{cls:"csv-search-modal-input",type:"text",placeholder:"Search\u2026",value:this.initialQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}});n.createEl("button",{cls:"csv-search-modal-close",text:"\u2715",title:"Close"}).addEventListener("click",()=>this.close());let a=e.createDiv({cls:"csv-search-modal-count"}),L=e.createDiv({cls:"csv-search-modal-list"}),l=40,c=()=>{let{matched:h,total:u}=this.resultCount();if(a.setText(o.value.trim()?`${h} of ${u} entries match`:`${u} entries \u2014 start typing to search`),L.empty(),!o.value.trim())return;this.getMatches().slice(0,l).forEach(({title:g,subtitle:m,row:p})=>{let b=L.createDiv({cls:"csv-search-modal-item"});b.createDiv({cls:"csv-search-modal-item-title",text:g||"\u2014"}),m&&b.createDiv({cls:"csv-search-modal-item-sub",text:m}),b.addEventListener("click",()=>{this.close(),this.onPick(p)})}),h>l&&L.createDiv({cls:"csv-search-modal-more",text:`+ ${h-l} more \u2014 close to see all in the view`})};c();let d=null;o.addEventListener("input",()=>{d!==null&&window.clearTimeout(d),d=window.setTimeout(()=>{d=null,this.onInput(o.value),c()},120)}),o.addEventListener("keydown",h=>{h.key==="Enter"&&this.close()}),window.requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(o.value.length,o.value.length)})}onClose(){let e=window.visualViewport;e&&this.vvHandler&&(e.removeEventListener("resize",this.vvHandler),e.removeEventListener("scroll",this.vvHandler)),this.vvHandler=null,this.contentEl.empty()}},vi=class extends At.Modal{constructor(t,e,i,n,o,r,a,L,l,c,d,h,u,f=()=>0){super(t),this.headers=e,this.filePath=i,this.current={...n,habitColumns:n.habitColumns?[...n.habitColumns]:void 0,categoricalColumns:n.categoricalColumns?[...n.categoricalColumns]:void 0},this.autoDetectedHabits=o,this.autoDetectedCategorical=r,this.autoDetectedRoles=a,this.availableModes=L,this.onSave=l,this.getHeaders=c,this.getFileCfg=d,this.onAddColumn=h,this.onRemoveColumn=u,this.onCleanupBooleanColumn=f}onOpen(){var N,I,P;let{contentEl:t}=this;t.empty(),t.addClass("csv-add-modal"),t.createEl("h2",{text:"View settings for this file",cls:"csv-modal-title"}),t.createEl("p",{text:"These settings apply only to this file and override the global defaults.",cls:"csv-modal-desc"});let e=t.createDiv({cls:"csv-modal-form"}),i=()=>{this.headers=this.getHeaders();let w=this.getFileCfg();this.current={...w,habitColumns:w.habitColumns?[...w.habitColumns]:void 0,categoricalColumns:w.categoricalColumns?[...w.categoricalColumns]:void 0},this.onOpen()},n=e.createDiv({cls:"csv-modal-row"});n.createEl("label",{text:"Columns",cls:"csv-modal-label"}),n.createEl("p",{cls:"csv-modal-hint",text:`Type and function are each exclusive per column \u2014 picking one clears it from whichever column held it before. "auto" means it's already doing that by column name, with nothing saved here yet. Card field is independent and can combine with anything. Checkbox columns get a "clean up" action that rewrites every row to strict 1/0 right away \u2014 not deferred to save.`});let o=[{value:"text",label:"Text"},{value:"checkbox",label:"Checkbox"},{value:"categorical",label:"Categorical"},{value:"date",label:"Date"}],r=[{value:"",label:"\u2014 no function \u2014"},{value:"title",label:"Title"},{value:"category",label:"Column group (Kanban lanes)"},{value:"status",label:"Row group / Status / Checkmark"},{value:"notes",label:"Notes"},{value:"image",label:"Image (card / kanban thumbnail)"},{value:"anki",label:"Anki card front"},{value:"price",label:"Price (Budget view)"}],a=w=>{var B,G,R;let U=(B=this.current.habitColumns)!=null?B:this.autoDetectedHabits,O=(G=this.current.categoricalColumns)!=null?G:this.autoDetectedCategorical,Z=(R=this.current.dateColumns)!=null?R:this.headers.filter(W=>Et(W));return U.includes(w)?{type:"checkbox",auto:!this.current.habitColumns}:O.includes(w)?{type:"categorical",auto:!this.current.categoricalColumns}:Z.includes(w)?{type:"date",auto:!this.current.dateColumns}:{type:"text",auto:!1}},L=(w,U)=>{this.current.habitColumns||(this.current.habitColumns=[...this.autoDetectedHabits]),this.current.categoricalColumns||(this.current.categoricalColumns=[...this.autoDetectedCategorical]),this.current.dateColumns||(this.current.dateColumns=this.headers.filter(O=>Et(O))),this.current.habitColumns=this.current.habitColumns.filter(O=>O!==w),this.current.categoricalColumns=this.current.categoricalColumns.filter(O=>O!==w),this.current.dateColumns=this.current.dateColumns.filter(O=>O!==w),U==="checkbox"?this.current.habitColumns.push(w):U==="categorical"?this.current.categoricalColumns.push(w):U==="date"&&this.current.dateColumns.push(w)},l=(I=(N=this.current.titleColumn)!=null?N:this.autoDetectedRoles.title)!=null?I:this.headers[0],d=n.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),h=d.createEl("thead").createEl("tr");["Column","Type","Visibility"].forEach(w=>h.createEl("th",{text:w}));let u=d.createEl("tbody"),f=()=>{var U;u.empty();let w=new Set((U=this.current.cardFields)!=null?U:this.headers);this.headers.forEach(O=>{let Z=u.createEl("tr"),B=Z.createEl("td",{cls:"csv-modal-colcfg-name"});B.createSpan({text:O});let G=B.createEl("button",{cls:"csv-modal-column-remove",text:"\u2715",attr:{title:`Remove "${O}" \u2014 deletes this column's data from every row`}});G.addEventListener("click",()=>{if(G.hasClass("confirm")){this.onRemoveColumn(O),i();return}u.querySelectorAll(".csv-modal-column-remove.confirm").forEach(T=>{T.removeClass("confirm"),T.setText("\u2715")}),G.addClass("confirm"),G.setText("Confirm?"),window.setTimeout(()=>{G.isConnected&&(G.removeClass("confirm"),G.setText("\u2715"))},3e3)});let R=Z.createEl("td",{cls:"csv-modal-colcfg-type-cell"});if(O===l)R.createSpan({cls:"csv-modal-colcfg-fixed",text:"Text"});else{let T=R.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-type"}),{type:F,auto:H}=a(O);if(o.forEach($=>{let z=T.createEl("option",{text:$.label,value:$.value});$.value===F&&(z.selected=!0)}),H&&T.addClass("auto-detected"),T.addEventListener("change",()=>{L(O,T.value),f()}),H&&R.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"}),F==="checkbox"){let $=R.createEl("button",{cls:"csv-modal-colcfg-cleanup-btn",text:"Clean up",attr:{title:`Rewrite every row in "${O}" to strict 1/0 (yes/true/1 \u2192 1, everything else \u2192 0)`}});$.addEventListener("click",()=>{if($.hasClass("confirm")){let z=this.onCleanupBooleanColumn(O);new At.Notice(z>0?`"${O}": normalized ${z} row${z===1?"":"s"} to 1/0.`:`"${O}" is already strict 1/0 \u2014 nothing to change.`);return}u.querySelectorAll(".csv-modal-colcfg-cleanup-btn.confirm").forEach(z=>{z.removeClass("confirm"),z.setText("Clean up")}),$.addClass("confirm"),$.setText("Confirm?"),window.setTimeout(()=>{$.isConnected&&($.removeClass("confirm"),$.setText("Clean up"))},3e3)})}}let K=Z.createEl("td",{cls:"csv-modal-colcfg-card-cell"}).createEl("input",{type:"checkbox"});K.checked=w.has(O),K.addEventListener("change",()=>{this.current.cardFields||(this.current.cardFields=[...this.headers]),K.checked?this.current.cardFields.includes(O)||this.current.cardFields.push(O):this.current.cardFields=this.current.cardFields.filter(T=>T!==O)})})};f();let g=t.createDiv({cls:"csv-modal-section",attr:{style:"margin-top: 24px;"}});g.createEl("h3",{text:"Column functions",cls:"csv-modal-h3"}),g.createEl("p",{cls:"csv-modal-desc",text:"Assign specific roles to your columns. 'auto' means it's already doing that by column name. Selecting '\u2014 none \u2014' disables the function entirely."});let p=g.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),b=p.createEl("thead").createEl("tr");["Function","Column"].forEach(w=>b.createEl("th",{text:w}));let C=p.createEl("tbody"),S=()=>{C.empty(),r.forEach(w=>{var W,K,T,F,H,$,z,V,j,X,q,nt,Q,et;if(w.value==="")return;let U=C.createEl("tr");U.createEl("td",{cls:"csv-modal-colcfg-name"}).setText(w.label);let Z=U.createEl("td",{cls:"csv-modal-colcfg-type-cell"}),B=Z.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-role"});B.createEl("option",{text:"\u2014 none \u2014",value:""});let G="",R=!1;w.value==="title"?(G=(K=(W=this.current.titleColumn)!=null?W:this.autoDetectedRoles.title)!=null?K:"",R=this.current.titleColumn===void 0&&!!this.autoDetectedRoles.title):w.value==="category"?(G=(F=(T=this.current.categoryColumn)!=null?T:this.autoDetectedRoles.category)!=null?F:"",R=this.current.categoryColumn===void 0&&!!this.autoDetectedRoles.category):w.value==="status"?(G=($=(H=this.current.statusColumn)!=null?H:this.autoDetectedRoles.status)!=null?$:"",R=this.current.statusColumn===void 0&&!!this.autoDetectedRoles.status):w.value==="notes"?(G=(V=(z=this.current.notesColumn)!=null?z:this.autoDetectedRoles.notes)!=null?V:"",R=this.current.notesColumn===void 0&&!!this.autoDetectedRoles.notes):w.value==="image"?(G=(X=(j=this.current.imageColumn)!=null?j:this.autoDetectedRoles.image)!=null?X:"",R=this.current.imageColumn===void 0&&!!this.autoDetectedRoles.image):w.value==="anki"?(G=(nt=(q=this.current.ankiFrontCol)!=null?q:this.autoDetectedRoles.anki)!=null?nt:"",R=this.current.ankiFrontCol===void 0&&!!this.autoDetectedRoles.anki):w.value==="price"&&(G=(et=(Q=this.current.budgetPriceCol)!=null?Q:this.autoDetectedRoles.price)!=null?et:"",R=this.current.budgetPriceCol===void 0&&!!this.autoDetectedRoles.price),this.headers.forEach(J=>{let ot=B.createEl("option",{text:J,value:J});J===G&&(ot.selected=!0)}),R&&G!==""&&B.addClass("auto-detected"),B.addEventListener("change",()=>{let J=B.value;J&&(w.value!=="title"&&this.current.titleColumn===J&&(this.current.titleColumn=void 0),w.value!=="category"&&this.current.categoryColumn===J&&(this.current.categoryColumn=void 0),w.value!=="status"&&this.current.statusColumn===J&&(this.current.statusColumn=void 0),w.value!=="notes"&&this.current.notesColumn===J&&(this.current.notesColumn=void 0),w.value!=="image"&&this.current.imageColumn===J&&(this.current.imageColumn=void 0),w.value!=="anki"&&this.current.ankiFrontCol===J&&(this.current.ankiFrontCol=void 0),w.value!=="price"&&this.current.budgetPriceCol===J&&(this.current.budgetPriceCol=void 0)),w.value==="title"?this.current.titleColumn=J:w.value==="category"?this.current.categoryColumn=J:w.value==="status"?this.current.statusColumn=J:w.value==="notes"?this.current.notesColumn=J:w.value==="image"?this.current.imageColumn=J:w.value==="anki"?this.current.ankiFrontCol=J:w.value==="price"&&(this.current.budgetPriceCol=J),S()}),R&&G!==""&&Z.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"})})};S();let _=n.createDiv({cls:"csv-modal-add-column"}),y=_.createEl("input",{cls:"csv-modal-input",type:"text",placeholder:"New column name"}),v=_.createEl("button",{cls:"csv-modal-cancel",text:"+ add column"}),x=()=>{let w=this.onAddColumn(y.value);if(w){new At.Notice(w);return}i()};v.addEventListener("click",x),y.addEventListener("keydown",w=>{w.key==="Enter"&&(w.preventDefault(),x())});let k=e.createDiv({cls:"csv-modal-row"});k.createEl("label",{text:"Default view",cls:"csv-modal-label"});let E=k.createEl("select",{cls:"csv-modal-select"}),M=[["\u2014 use global default \u2014",""],...this.availableModes.map(w=>[w.label,w.id])],D=(P=this.current.defaultMode)!=null?P:"";D&&!this.availableModes.some(w=>w.id===D)&&M.push([`${D} (no longer available)`,D]),M.forEach(([w,U])=>{let O=E.createEl("option",{text:w,value:U});D===U&&(O.selected=!0)}),E.addEventListener("change",()=>{this.current.defaultMode=E.value?E.value:void 0});let A=t.createDiv({cls:"csv-modal-btns"});A.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),A.createEl("button",{text:"Save",cls:"csv-modal-submit"}).addEventListener("click",()=>{this.onSave(this.current),this.close()})}onClose(){this.contentEl.empty()}},Ne=class extends At.Modal{constructor(e,i,n,o,r,a="Create",L="text"){super(e);this.title=i;this.initial=n;this.placeholder=o;this.onSubmit=r;this.submitLabel=a;this.inputType=L}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("csv-add-modal"),e.createEl("h2",{text:this.title,cls:"csv-modal-title"});let i=e.createEl("input",{cls:"csv-modal-field",type:this.inputType});i.value=this.initial,i.placeholder=this.placeholder,window.setTimeout(()=>{i.focus(),i.select()},0);let n=()=>{let r=i.value.trim();r&&(this.onSubmit(r),this.close())};i.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),n())});let o=e.createDiv({cls:"csv-modal-btns"});o.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),o.createEl("button",{text:this.submitLabel,cls:"csv-modal-submit"}).addEventListener("click",n)}onClose(){this.contentEl.empty()}};var An=195,jl={AF:"Afghanistan",AL:"Albania",DZ:"Algeria",AD:"Andorra",AO:"Angola",AR:"Argentina",AM:"Armenia",AU:"Australia",AT:"Austria",AZ:"Azerbaijan",BD:"Bangladesh",BY:"Belarus",BE:"Belgium",BO:"Bolivia",BA:"Bosnia",BW:"Botswana",BR:"Brazil",BG:"Bulgaria",KH:"Cambodia",CM:"Cameroon",CA:"Canada",CL:"Chile",CN:"China",CO:"Colombia",HR:"Croatia",CU:"Cuba",CY:"Cyprus",CZ:"Czechia",DK:"Denmark",DO:"Dominican Rep.",EC:"Ecuador",EG:"Egypt",ET:"Ethiopia",FI:"Finland",FR:"France",GE:"Georgia",DE:"Germany",GH:"Ghana",GR:"Greece",GT:"Guatemala",GY:"Guyana",HT:"Haiti",HN:"Honduras",HU:"Hungary",IS:"Iceland",IN:"India",ID:"Indonesia",IR:"Iran",IQ:"Iraq",IE:"Ireland",IL:"Israel",IT:"Italy",JP:"Japan",JO:"Jordan",KZ:"Kazakhstan",KE:"Kenya",KP:"N. Korea",KR:"S. Korea",KW:"Kuwait",KG:"Kyrgyzstan",LA:"Laos",LV:"Latvia",LB:"Lebanon",LY:"Libya",LI:"Liechtenstein",LT:"Lithuania",LU:"Luxembourg",MY:"Malaysia",ML:"Mali",MT:"Malta",MR:"Mauritania",MX:"Mexico",MD:"Moldova",MN:"Mongolia",ME:"Montenegro",MA:"Morocco",MZ:"Mozambique",MM:"Myanmar",NA:"Namibia",NP:"Nepal",NL:"Netherlands",NZ:"New Zealand",NI:"Nicaragua",NE:"Niger",NG:"Nigeria",NO:"Norway",OM:"Oman",PK:"Pakistan",PA:"Panama",PG:"Papua New Guinea",PY:"Paraguay",PE:"Peru",PH:"Philippines",PL:"Poland",PT:"Portugal",QA:"Qatar",RO:"Romania",RU:"Russia",RW:"Rwanda",SA:"Saudi Arabia",SN:"Senegal",RS:"Serbia",SG:"Singapore",SK:"Slovakia",SI:"Slovenia",SO:"Somalia",ZA:"South Africa",SS:"South Sudan",ES:"Spain",LK:"Sri Lanka",SD:"Sudan",SE:"Sweden",CH:"Switzerland",SY:"Syria",TJ:"Tajikistan",TZ:"Tanzania",TH:"Thailand",TN:"Tunisia",TR:"Turkey",TM:"Turkmenistan",UG:"Uganda",UA:"Ukraine",AE:"UAE",GB:"United Kingdom",US:"United States",UY:"Uruguay",UZ:"Uzbekistan",VN:"Vietnam",YE:"Yemen",ZM:"Zambia",ZW:"Zimbabwe",MC:"Monaco",BZ:"Belize"},Ul={AF:["DZ","AO","BJ","BW","BF","BI","CM","CV","CF","TD","KM","CD","CG","CI","DJ","EG","GQ","ER","ET","GA","GM","GH","GN","GW","KE","LS","LR","LY","MG","MW","ML","MR","MU","MA","MZ","NA","NE","NG","RE","RW","ST","SN","SC","SL","SO","ZA","SS","SD","TZ","TG","TN","UG","ZM","ZW"],AN:["AQ"],AS:["AF","AM","AZ","BH","BD","BT","BN","KH","CN","CY","GE","IN","ID","IR","IQ","IL","JP","JO","KZ","KW","KG","LA","LB","MY","MV","MN","MM","NP","KP","OM","PK","PS","PH","QA","RU","SA","SG","KR","LK","SY","TW","TJ","TH","TL","TR","TM","AE","UZ","VN","YE"],EU:["AL","AD","AT","BY","BE","BA","BG","HR","CZ","DK","EE","FI","FR","DE","GR","HU","IS","IE","IT","XK","LV","LI","LT","LU","MT","MD","MC","ME","NL","MK","NO","PL","PT","RO","RU","SM","RS","SK","SI","ES","SE","CH","UA","GB","VA"],NA:["AG","BS","BB","BZ","CA","CR","CU","DM","DO","SV","GD","GT","HT","HN","JM","MX","NI","PA","KN","LC","VC","TT","US"],OC:["AU","FJ","KI","MH","FM","NR","NZ","PW","PG","WS","SB","TO","TV","VU"],SA:["AR","BO","BR","CL","CO","EC","GY","PY","PE","SR","UY","VE"]},ur={AF:"Africa",AN:"Antarctica",AS:"Asia",EU:"Europe",NA:"N. America",OC:"Oceania",SA:"S. America"},fr={};for(let[s,t]of Object.entries(Ul))for(let e of t)fr[e]=s;function wt(s){return jl[s]||s}function jt(s){return!s||s.length!==2?"":String.fromCodePoint(...s.toUpperCase().split("").map(t=>t.charCodeAt(0)+127397))}function zt(s){if(!s||s.indexOf("?")!==-1)return null;let t=new Date(s+"T12:00:00Z");return isNaN(t.getTime())?null:t}function Bs(s){let t=zt(s.date_entered),e=zt(s.date_left);return!t||!e?0:Math.max(Math.round((e.getTime()-t.getTime())/864e5),1)}function pr(s,t=new Date){let e=t.getTime(),i=null,n=-1/0;for(let o of s){let r=zt(o.date_entered);if(!(!r||r.getTime()>e)){if(o.date_left.trim()!==""){let a=zt(o.date_left);if(!a||a.getTime()n&&(i=o,n=r.getTime())}}return i}function gr(s){let t=p=>{var b,C,S,_,y,v,x,k;return{date_entered:(b=p.date_entered)!=null?b:"",date_left:(C=p.date_left)!=null?C:"",country:((S=p.country)!=null?S:"").trim().toUpperCase(),city:(_=p.city)!=null?_:"",visa_status:(y=p.visa_status)!=null?y:"",notes:(v=p.notes)!=null?v:"",source:((x=p.source)!=null?x:"").trim().toLowerCase(),resolved:(k=p.resolved)!=null?k:"",_src:p}},e=s.map(t).filter(p=>p.country),i=e.filter(p=>p.source==="confirmed"),n=e.filter(p=>p.source==="inferred"),o=e.filter(p=>p.source==="conflict"),r=[];for(let p of i){let b=zt(p.date_entered),C=zt(p.date_left);b&&C&&r.push([b.getTime(),C.getTime()])}let a=p=>{let b=zt(p.date_entered),C=zt(p.date_left);if(!b||!C)return!1;let S=b.getTime(),_=C.getTime();return r.some(([y,v])=>S<=v&&_>=y)},L=n.filter(p=>zt(p.date_entered)&&zt(p.date_left)&&!a(p)),l=new Set(i.map(p=>p.country)),c=new Set(n.map(p=>p.country)),d=new Set([...c].filter(p=>!l.has(p))),h=new Set([...l,...c]),u=new Map;for(let p of i)u.set(p.country,(u.get(p.country)||0)+Bs(p));let f=[...u.entries()].map(([p,b])=>({iso:p,days:b})).sort((p,b)=>b.days-p.days||wt(p.iso).localeCompare(wt(b.iso))),g=f.reduce((p,b)=>p+b.days,0),m=new Set;for(let p of l){let b=fr[p];b&&m.add(b)}return{confirmed:i,inferred:n,conflicts:o,inferredVisible:L,confRanges:r,confirmedCountries:l,inferredOnlyCountries:d,allCountries:h,countryDays:f,totalConfirmedDays:g,visitedContinents:m,worldPct:Math.round(l.size/An*100)}}var Rn=864e5;function mr(s){if(!s||s.indexOf("?")!==-1)return null;let t=Date.parse(s+"T00:00:00Z");return isNaN(t)?null:t}function Yl(s,t,e,i){let n=Math.max(s,e),o=Math.min(t,i);return o<=n?0:Math.round((o-n)/Rn)}function Gl(s,t){var n;let e=s.window;if(e.type==="all-time")return{start:-1/0,end:1/0,label:"all time"};if(e.type==="calendar-year"){let o=new Date(t).getUTCFullYear();return{start:Date.UTC(o,0,1),end:Date.UTC(o+1,0,1),label:`in ${o}`}}let i=(n=e.days)!=null?n:180;return{start:t-i*Rn,end:t+Rn,label:`in last ${i} days`}}function br(s,t,e=Date.now()){var c,d,h;let i=(c=s.scope.countries)!=null?c:s.scope.country?[s.scope.country]:[],n=new Set(i.map(u=>u.toUpperCase())),o=new Set(((h=(d=s.exempt)==null?void 0:d.visa_status)!=null?h:[]).map(u=>u.toLowerCase().trim())),r=Gl(s,e),a=0;for(let u of t){if(!n.has((u.country||"").toUpperCase())||o.has((u.visa_status||"").toLowerCase().trim()))continue;let f=mr(u.date_entered),g=mr(u.date_left);f===null||g===null||(a+=Yl(f,g,r.start,r.end))}let L=s.threshold-a,l=a>=s.threshold?"over":a/s.threshold>=.8?"warn":"ok";return{rule:s,used:a,threshold:s.threshold,remaining:L,windowLabel:r.label,status:l}}var vr=["#c9a96e","#4a6fa5","#5ba06e","#a05b8a","#6ea0a0","#a0855b","#7a6ea0","#a06e6e","#6e8fa0","#a09e5b"],Kl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ql(){let s=new Map,t=0;return e=>(s.has(e)||s.set(e,vr[t++%vr.length]),s.get(e))}function Xl(s){let t=document.body.createDiv({cls:"csv-tv-tooltip"}),e=null,i=(r,a)=>{let l=r+14,c=a+16,d=t.offsetWidth,h=t.offsetHeight;l+d+8>window.innerWidth&&(l=r-d-14),c+h+8>window.innerHeight&&(c=a-h-16),t.style.left=`${Math.max(8,l)}px`,t.style.top=`${Math.max(8,c)}px`},n=r=>{var l,c;let a=(c=(l=r.target)==null?void 0:l.closest("[data-tip]"))!=null?c:null,L=(a==null?void 0:a.getAttribute("data-tip"))||"";if(!a||!L){e&&(e=null,t.removeClass("is-on"));return}a!==e&&(e=a,t.setText(L),t.addClass("is-on")),i(r.clientX,r.clientY)},o=()=>{e=null,t.removeClass("is-on")};return s.addEventListener("pointermove",n),s.addEventListener("pointerleave",o),()=>{s.removeEventListener("pointermove",n),s.removeEventListener("pointerleave",o),t.remove()}}function Pn(s){let t=Bs(s);return t?`${t}d`:"\u2014"}function ds(s){return s||"\u2014"}function zs(s){return s.createDiv({cls:"csv-tv-table-wrap"}).createEl("table",{cls:"csv-tv-table"})}function $s(s,t,e,i){s.addClass("csv-tv-editable"),s.title="Click to edit";let n=()=>{s.empty(),s.setText(t[e]?t[e]:"\u2014")};n(),s.addEventListener("click",()=>{var r;if(s.querySelector("input"))return;s.empty();let o=yi(s,e,(r=t[e])!=null?r:"","csv-inline-input");o.focus(),o.type==="text"&&o.select(),o.addEventListener("blur",()=>{t[e]=o.value,i(),n()}),o.addEventListener("keydown",a=>{var L;a.key==="Enter"&&o.blur(),a.key==="Escape"&&(o.value=(L=t[e])!=null?L:"",o.blur())})})}async function yr(s,t,e,i=()=>{},n=null,o=()=>{}){let r=gr(t),a=s.createDiv({cls:"csv-tv"});if(!r.confirmed.length&&!r.inferred.length){a.createDiv({cls:"csv-empty-state",text:"No travel rows found. Expected columns: country, date_entered, date_left, source."});return}o(Xl(a));let L=null,l=()=>{a.querySelectorAll(".country-path").forEach(u=>{let f=(u.getAttribute("data-iso")||"").toUpperCase();u.classList.toggle("cp-selected",!!L&&f===L)}),a.querySelectorAll(".csv-tv-seg").forEach(u=>{u.classList.toggle("is-dim",!!L&&u.getAttribute("data-iso")!==L)}),a.querySelectorAll("tr[data-iso]").forEach(u=>{u.classList.toggle("is-selected",!!L&&u.getAttribute("data-iso")===L)}),h.empty(),L&&(tc(h,r,L,()=>c(null)),h.scrollIntoView({behavior:"smooth",block:"nearest"}))},c=u=>{L=u&&u!==L?u:null,l()};Ql(a,r);let d=a.createDiv({cls:"csv-tv-mapwrap"});d.createDiv({cls:"csv-tv-map-loading",text:"Loading map\u2026"});let h=a.createDiv({cls:"csv-tv-detailwrap"});n&&n.length&&ec(a,r.confirmed,n),sc(a,r,c),ic(a,r,c),nc(a,r,i);try{let u=await e();d.empty(),u?Jl(d,u,r,c):d.createDiv({cls:"csv-tv-map-loading",text:"World map asset not found (world-map.svg)."})}catch(u){d.empty(),d.createDiv({cls:"csv-tv-map-loading",text:"Couldn't load world map."})}}function Ql(s,t){let e=s.createDiv({cls:"csv-tv-stats"}),i=(l,c,d="")=>{let h=e.createDiv({cls:"csv-tv-stat"});h.createDiv({cls:"csv-tv-stat-label",text:l}),h.createDiv({cls:"csv-tv-stat-value",text:c}),d&&h.createDiv({cls:"csv-tv-stat-sub",text:d})},n=Math.round(t.allCountries.size/An*100);i("Countries",String(t.confirmedCountries.size),`${t.worldPct}% of world`),i("Incl. photos",String(t.allCountries.size),`${n}% of world`),i("Continents",`${t.visitedContinents.size} / 7`,[...t.visitedContinents].map(l=>ur[l]||l).sort().join(", ")),i("Confirmed trips",String(t.confirmed.length)),i("Confirmed days",String(t.totalConfirmedDays));let o=new Set(t.confirmed.map(l=>l.city.trim().toLowerCase()).filter(Boolean));o.size&&i("Cities",String(o.size));let r=null,a=0;for(let l of t.confirmed){let c=Bs(l);c>a&&(a=c,r=l)}if(r){let l=r.date_entered.slice(0,4);i("Longest trip",`${a}d`,`${jt(r.country)} ${wt(r.country)}${l?` \xB7 ${l}`:""}`)}let L=pr(t.confirmed);if(L){let l=zt(L.date_entered),c=Math.max(1,Math.round((Date.now()-l.getTime())/864e5)+1),d=s.createDiv({cls:"csv-tv-now"});d.createSpan({cls:"csv-tv-now-loc",text:`\u{1F4CD} Currently in ${jt(L.country)} ${wt(L.country)}`}),d.createSpan({cls:"csv-tv-now-sub",text:` \u2014 since ${L.date_entered} (day ${c})${L.city?` \xB7 ${L.city}`:""}`})}}function Jl(s,t,e,i){let n=s.createDiv({cls:"csv-tv-map"}),o=new DOMParser().parseFromString(t,"image/svg+xml").documentElement;n.appendChild(o),n.querySelectorAll(".country-path").forEach(l=>{let c=(l.getAttribute("data-iso")||"").toUpperCase();if(l.classList.remove("cp-unvisited","cp-confirmed","cp-inferred"),c&&e.confirmedCountries.has(c)){l.classList.add("cp-confirmed");let d=e.countryDays.find(h=>h.iso===c);l.setAttr("aria-label",`${wt(c)} \u2014 ${d&&d.days?d.days+"d confirmed":"confirmed"}`),l.setAttr("data-tip",`${wt(c)}${d&&d.days?" \xB7 "+d.days+"d":""} \xB7 click for trips`)}else c&&e.inferredOnlyCountries.has(c)?(l.classList.add("cp-inferred"),l.setAttr("aria-label",`${wt(c)} \u2014 photo evidence`),l.setAttr("data-tip",`${wt(c)} \xB7 photo evidence \xB7 click for trips`)):c?(l.classList.add("cp-unvisited"),l.setAttr("data-tip",wt(c))):l.classList.add("cp-unvisited");c&&l.addEventListener("click",()=>{e.allCountries.has(c)?i(c):i(null)})}),n.querySelectorAll(".country-path").forEach(l=>{try{let c=l.getBoundingClientRect();c.width&&c.height&&Math.max(c.width,c.height)<12&&l.classList.add("cp-tiny")}catch(c){}});let r=s.createDiv({cls:"csv-tv-map-legend"}),a=r.createSpan({cls:"csv-tv-leg"});a.createSpan({cls:"csv-tv-dot cp-confirmed"}),a.appendText(" Confirmed");let L=r.createSpan({cls:"csv-tv-leg"});L.createSpan({cls:"csv-tv-dot cp-inferred"}),L.appendText(" Photo evidence")}function tc(s,t,e,i){var m,p;let n=s.createDiv({cls:"csv-tv-detail"}),o=n.createDiv({cls:"csv-tv-detail-head"});o.createSpan({cls:"csv-tv-detail-flag",text:jt(e)});let r=o.createDiv({cls:"csv-tv-detail-titles"});r.createDiv({cls:"csv-tv-detail-name",text:wt(e)});let a=t.confirmed.filter(b=>b.country===e),L=t.inferred.filter(b=>b.country===e),l=(p=(m=t.countryDays.find(b=>b.iso===e))==null?void 0:m.days)!=null?p:0,c=new Set([...a,...L].map(b=>b.city.trim()).filter(Boolean)),d=[];a.length&&d.push(`${a.length} confirmed trip${a.length===1?"":"s"}`),l&&d.push(`${l}d total`),L.length&&d.push(`${L.length} photo-inferred`),c.size&&d.push(`${c.size} cit${c.size===1?"y":"ies"}`),r.createDiv({cls:"csv-tv-detail-sub",text:d.join(" \xB7 ")}),o.createEl("button",{cls:"csv-tv-detail-close",text:"\u2715",title:"Close"}).addEventListener("click",i);let h=xi([...a.map(b=>({r:b,inf:!1,date_entered:b.date_entered})),...L.map(b=>({r:b,inf:!0,date_entered:b.date_entered}))]);if(!h.length)return;let u=zs(n),f=u.createEl("thead").createEl("tr");["","Entered","Left","Days","City","Visa"].forEach(b=>f.createEl("th",{text:b}));let g=u.createEl("tbody");for(let{r:b,inf:C}of h){let S=g.createEl("tr");S.createEl("td",{text:C?"\u{1F4F7}":"",cls:"csv-tv-flag",attr:C?{"data-tip":"Photo-inferred"}:{}}),S.createEl("td",{text:ds(b.date_entered)}),S.createEl("td",{text:ds(b.date_left)}),S.createEl("td",{text:Pn(b)}),S.createEl("td",{text:b.city}),S.createEl("td",{text:b.visa_status})}}function ec(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Residency counters"});let i=s.createDiv({cls:"csv-tv-res-grid"});for(let n of e){let o=br(n,t),r=i.createDiv({cls:`csv-tv-res-card csv-tv-res-${o.status}`});r.createDiv({cls:"csv-tv-res-label",text:n.label});let a=r.createDiv({cls:"csv-tv-res-nums"});a.createSpan({cls:"csv-tv-res-used",text:String(o.used)}),a.createSpan({cls:"csv-tv-res-thresh",text:` / ${o.threshold}`}),a.createSpan({cls:"csv-tv-res-window",text:` ${o.windowLabel}`});let L=r.createDiv({cls:"csv-tv-res-bar"});L.createDiv({cls:"csv-tv-res-fill"}).style.width=`${Math.min(100,Math.round(o.used/o.threshold*100))}%`;let l=o.status==="over"?n.onExceed?`Over \u2014 ${n.onExceed}`:"Limit reached":`${o.remaining} day${o.remaining===1?"":"s"} left`;r.createDiv({cls:"csv-tv-res-status",text:l}),n.note&&r.createDiv({cls:"csv-tv-res-note",text:n.note})}s.createDiv({cls:"csv-tv-res-disclaimer",text:"Indicators only \u2014 not legal or tax advice. Based on confirmed trips."})}function sc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Countries visited"});let i=zs(s),n=i.createEl("thead").createEl("tr");["","Country","Total days"].forEach(r=>n.createEl("th",{text:r}));let o=i.createEl("tbody");for(let{iso:r,days:a}of t.countryDays){let L=o.createEl("tr",{cls:"csv-tv-row-click",attr:{"data-iso":r}});L.createEl("td",{text:jt(r),cls:"csv-tv-flag"}),L.createEl("td",{text:wt(r)}),L.createEl("td",{text:a?`${a}d`:"\u2014"}),L.addEventListener("click",()=>e(r))}if(t.inferredOnlyCountries.size){let r=s.createDiv({cls:"csv-tv-photo-only"});r.createSpan({text:"\u{1F4F7} Photo evidence only: "}),r.createSpan({text:[...t.inferredOnlyCountries].sort().map(jt).join(" ")})}}function ic(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Timeline"});let i=ql(),n=[...t.confirmed.map(l=>({...l,_inf:!1})),...t.inferredVisible.map(l=>({...l,_inf:!0}))].filter(l=>l.date_entered&&l.date_left&&l.date_entered.indexOf("?")===-1),o=new Map;for(let l of n){let c=parseInt(l.date_entered.slice(0,4)),d=parseInt(l.date_left.slice(0,4));if(!(isNaN(c)||isNaN(d)))for(let h=c;h<=d;h++)o.has(h)||o.set(h,[]),o.get(h).push(l)}let r=[...o.keys()].sort((l,c)=>c-l),a=s.createDiv({cls:"csv-tv-timeline"});for(let l of r){let c=new Date(`${l}-01-01T12:00:00Z`).getTime(),d=new Date(`${l}-12-31T12:00:00Z`).getTime(),h=d-c,u=a.createDiv({cls:"csv-tv-tl-year"}),f=0,g=new Set;for(let C of o.get(l)){if(g.add(C.country),C._inf)continue;let S=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),c),_=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),d);S<=_&&(f+=Math.max(Math.round((_-S)/864e5)+1,1))}let m=u.createDiv({cls:"csv-tv-tl-label"});m.createSpan({text:String(l)}),m.createSpan({cls:"csv-tv-tl-sub",text:`${f?`${f}d \xB7 `:""}${g.size} ${g.size===1?"country":"countries"}`});let p=u.createDiv({cls:"csv-tv-month-row"});Kl.forEach(C=>p.createDiv({cls:"csv-tv-month-tick",text:C}));let b=u.createDiv({cls:"csv-tv-track"});for(let C of o.get(l)){let S=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),c),_=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),d);if(S>_)continue;let y=(S-c)/h*100,v=Math.max((_-S+864e5)/h*100,.5),x=i(C.country),k=b.createDiv({cls:`csv-tv-seg${C._inf?" csv-tv-seg-inf":""}`});k.style.left=`${y}%`,k.style.width=`${v}%`,C._inf?(k.style.borderColor=x,k.style.background=x+"22",k.style.color=x):k.style.background=x,k.setAttr("data-iso",C.country),k.setAttr("data-tip",`${wt(C.country)} ${C.date_entered} \u2192 ${C.date_left} (${Bs(C)}d)${C.visa_status?" ["+C.visa_status+"]":""}${C._inf?" [photo]":""}`),k.addEventListener("click",()=>e(C.country)),v>4?k.createSpan({cls:"csv-tv-seg-lbl",text:`${jt(C.country)} ${C.country}`}):v>2&&k.createSpan({cls:"csv-tv-seg-lbl",text:jt(C.country)})}}a.createDiv({cls:"csv-tv-tl-legend"}).setText("Confirmed (solid) \xB7 photo inferred (outlined)")}function xi(s){return[...s].sort((t,e)=>!t.date_entered&&!e.date_entered?0:t.date_entered?e.date_entered?e.date_entered.localeCompare(t.date_entered):-1:1)}function nc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Confirmed trips"}),s.createDiv({cls:"csv-tv-edit-hint",text:"Dates, city, visa and notes are editable \u2014 click a cell. Edit country in Table view."});let i=zs(s),n=i.createEl("thead").createEl("tr");["","Country","Entered","Left","Duration","City","Visa","Notes"].forEach(r=>n.createEl("th",{text:r}));let o=i.createEl("tbody");for(let r of xi(t.confirmed)){let a=o.createEl("tr");a.createEl("td",{text:jt(r.country),cls:"csv-tv-flag"}),a.createEl("td",{text:wt(r.country)}),$s(a.createEl("td"),r._src,"date_entered",e),$s(a.createEl("td"),r._src,"date_left",e),a.createEl("td",{text:Pn(r)}),$s(a.createEl("td"),r._src,"city",e),$s(a.createEl("td"),r._src,"visa_status",e),$s(a.createEl("td"),r._src,"notes",e)}if(t.inferred.length){let r=s.createEl("details",{cls:"csv-tv-details"});r.createEl("summary",{text:`\u{1F4F7} Photo inferred trips (${t.inferred.length})`});let a=zs(r),L=a.createEl("thead").createEl("tr");["","Country","Entered","Left","Days","City"].forEach(c=>L.createEl("th",{text:c}));let l=a.createEl("tbody");for(let c of xi(t.inferred)){let d=l.createEl("tr");d.createEl("td",{text:jt(c.country),cls:"csv-tv-flag"}),d.createEl("td",{text:wt(c.country)}),d.createEl("td",{text:ds(c.date_entered)}),d.createEl("td",{text:ds(c.date_left)}),d.createEl("td",{text:Pn(c)}),d.createEl("td",{text:c.city})}}if(t.conflicts.length){let r=s.createEl("details",{cls:"csv-tv-details csv-tv-details-warn"});r.createEl("summary",{text:`\u26A0 ${t.conflicts.length} conflict(s) \u2014 photo evidence contradicts a confirmed entry`});let a=zs(r),L=a.createEl("thead").createEl("tr");["","Country (photos)","Dates","Detail"].forEach(c=>L.createEl("th",{text:c}));let l=a.createEl("tbody");for(let c of xi(t.conflicts)){let d=l.createEl("tr");d.createEl("td",{text:jt(c.country),cls:"csv-tv-flag"}),d.createEl("td",{text:c.country}),d.createEl("td",{text:`${ds(c.date_entered)} \u2192 ${ds(c.date_left)}`}),d.createEl("td",{text:c.notes})}}}var Rt=require("obsidian"),Ci=class extends Rt.PluginSettingTab{constructor(t,e){super(t,e),this.plugin=e}display(){let{containerEl:t}=this;t.empty(),new Rt.Setting(t).setName("Default view mode").addDropdown(i=>i.addOption("kanban-genre","Kanban").addOption("table","Table").setValue(this.plugin.settings.defaultMode).onChange(async n=>{this.plugin.settings.defaultMode=n,await this.plugin.saveSettings()})),new Rt.Setting(t).setName("Status column name").addText(i=>i.setValue(this.plugin.settings.statusColumn).onChange(async n=>{this.plugin.settings.statusColumn=n,await this.plugin.saveSettings()})),new Rt.Setting(t).setName("Category/genre column name").addText(i=>i.setValue(this.plugin.settings.categoryColumn).onChange(async n=>{this.plugin.settings.categoryColumn=n,await this.plugin.saveSettings()})),new Rt.Setting(t).setName("Notes column names").setDesc("Comma-separated.").addText(i=>i.setValue(this.plugin.settings.notesColumns.join(", ")).onChange(async n=>{this.plugin.settings.notesColumns=n.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new Rt.Setting(t).setName("Select/dropdown columns").setDesc("Comma-separated column names that use a dropdown picker.").addText(i=>i.setValue(this.plugin.settings.selectColumns.join(", ")).onChange(async n=>{this.plugin.settings.selectColumns=n.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new Rt.Setting(t).setName("Notes subfolder").addText(i=>i.setPlaceholder("Notes").setValue(this.plugin.settings.notesSubfolder).onChange(async n=>{this.plugin.settings.notesSubfolder=n,await this.plugin.saveSettings()})),new Rt.Setting(t).setName("Reset column widths").addButton(i=>i.setButtonText("Reset").onClick(async()=>{this.plugin.settings.columnWidths={},await this.plugin.saveSettings(),new Rt.Notice("Column widths reset.")})),new Rt.Setting(t).setName("Residency counters (travel view)").setDesc("Show residency / tax day-gauges in the travel view.").addToggle(i=>i.setValue(this.plugin.settings.showResidency!==!1).onChange(async n=>{this.plugin.settings.showResidency=n,await this.plugin.saveSettings()})),new Rt.Setting(t).setName("Residency rules").setHeading(),t.createEl("p",{cls:"setting-item-description",text:"Each rule counts days in the listed countries within the window, minus exempt visa rows, against the threshold. Counts confirmed trips only. Indicators, not legal/tax advice."});let e=t.createDiv({cls:"csv-rr-wrap"});this.renderResidencyRules(e)}renderResidencyRules(t){var o;t.empty();let e=(o=this.plugin.settings.residencyRules)!=null?o:this.plugin.settings.residencyRules=[],i=()=>void this.plugin.saveSettings();e.forEach((r,a)=>{var p,b,C,S,_,y;let L=t.createDiv({cls:"csv-rr-card"}),l=L.createDiv({cls:"csv-rr-head"}),c=l.createEl("input",{cls:"csv-rr-label",type:"text",value:r.label});c.placeholder="Label (e.g. \u{1F1EA}\u{1F1FA} Schengen 90/180)",c.addEventListener("input",()=>{r.label=c.value,i()});let d=l.createEl("button",{cls:"csv-rr-del",text:"\u2715"});d.setAttr("aria-label","Remove rule"),d.addEventListener("click",()=>{(async()=>(e.splice(a,1),await this.plugin.saveSettings(),this.renderResidencyRules(t)))()});let h=L.createDiv({cls:"csv-rr-grid"}),u=(v,x,k,E="")=>{let M=h.createDiv({cls:"csv-rr-field"});M.createEl("label",{text:v});let D=M.createEl("input",{type:"text",value:x});E&&(D.placeholder=E),D.addEventListener("input",()=>{k(D.value),i()})},f=(p=r.scope.countries)!=null?p:r.scope.country?[r.scope.country]:[];u("Countries (ISO-2, comma)",f.join(", "),v=>{r.scope={countries:v.split(",").map(x=>x.trim().toUpperCase()).filter(Boolean)}},"US, GB");let g=h.createDiv({cls:"csv-rr-field"});g.createEl("label",{text:"Window"});let m=g.createEl("select");[["calendar-year","Calendar year"],["rolling","Rolling N days"],["all-time","All time"]].forEach(([v,x])=>{let k=m.createEl("option",{text:x,value:v});r.window.type===v&&(k.selected=!0)}),m.addEventListener("change",()=>{r.window={type:m.value,days:r.window.days},i(),this.renderResidencyRules(t)}),r.window.type==="rolling"&&u("Rolling days",String((b=r.window.days)!=null?b:180),v=>{let x=parseInt(v,10);r.window.days=isNaN(x)?void 0:x},"180"),u("Threshold (days)",String(r.threshold),v=>{let x=parseInt(v,10);r.threshold=isNaN(x)?0:x},"183"),u("Exempt visas (comma)",((S=(C=r.exempt)==null?void 0:C.visa_status)!=null?S:[]).join(", "),v=>{let x=v.split(",").map(k=>k.trim()).filter(Boolean);r.exempt=x.length?{visa_status:x}:void 0},"F-1, J-1"),u("On-exceed label",(_=r.onExceed)!=null?_:"",v=>{r.onExceed=v||void 0},"tax resident"),u("Note",(y=r.note)!=null?y:"",v=>{r.note=v||void 0},"optional caveat")}),t.createDiv({cls:"csv-rr-btns"}).createEl("button",{cls:"csv-rr-add",text:"+ add rule"}).addEventListener("click",()=>{(async()=>(e.push({label:"New rule",scope:{countries:[]},window:{type:"calendar-year"},threshold:183}),await this.plugin.saveSettings(),this.renderResidencyRules(t)))()})}};var be=require("obsidian"),xr=Ns(is());async function Cr(s,t,e,i,n={}){var Z,B,G;let o=t.split(` +`).map(R=>R.trim()).filter(Boolean),r="";for(let R of o)if(R.startsWith("file:")){r=R.replace("file:","").trim();break}if(!r){e.createEl("p",{text:"Error: No file specified. Use: file: yourfile.csv",cls:"csv-add-error"});return}let a=s.vault.getAbstractFileByPath(i.sourcePath),L=(B=(Z=a==null?void 0:a.parent)==null?void 0:Z.path)!=null?B:"",l=Qt(r,L),c=s.vault.getAbstractFileByPath(l);if(!c||!(c instanceof be.TFile)){e.createEl("p",{text:`Error: File not found: ${l}`,cls:"csv-add-error"});return}let d=(G=n[l])!=null?G:{},h=[],u=[];try{let R=await s.vault.read(c),W=kt(R);h=W.headers,u=W.rows}catch(R){e.createEl("p",{text:`Error reading file: ${R instanceof Error?R.message:String(R)}`,cls:"csv-add-error"});return}if(!h.length){e.createEl("p",{text:"Error: No columns found in file",cls:"csv-add-error"});return}let f=R=>{let W=R.toLowerCase();if(["date","day","datum"].includes(W))return!0;let K=u.slice(0,5).map(T=>{var F;return(F=T[R])!=null?F:""});return K.length>0&&K.every(T=>/^\d{4}-\d{2}-\d{2}$/.test(T))},g=R=>{let W=R.toLowerCase();return["notes","note","comments","description","journal"].includes(W)},m=d.habitColumns?d.habitColumns.filter(R=>h.includes(R)):h.filter(R=>!f(R)&&as(u.map(W=>{var K;return((K=W[R])!=null?K:"").toLowerCase().trim()}))),p=h.filter(R=>f(R)),b=h.filter(R=>g(R)),C=h.filter(R=>!m.includes(R)&&!p.includes(R)&&!b.includes(R)),S=d.titleColumn?h.find(R=>R.toLowerCase()===d.titleColumn.toLowerCase()):h.find(R=>["title","name"].includes(R.toLowerCase())),_=e.createDiv({cls:"csv-add-form csv-add-compact"}),y=_.createEl("button",{cls:"csv-add-trigger is-hidden",text:"+ new entry"}),v=_.createDiv({cls:"csv-add-card"}),x=v.createDiv({cls:"csv-add-card-header"});x.createSpan({cls:"csv-add-card-title",text:"New entry"});let k=x.createEl("button",{cls:"csv-add-card-close",text:"\xD7"}),E=v.createDiv({cls:"csv-add-rows"}),M={},D={},A=(R,W)=>{let K=E.createDiv({cls:`csv-add-row csv-add-row-${W}`});return K.createSpan({cls:"csv-add-row-label",text:Tt(R)}),K};p.forEach(R=>{let K=A(R,"date").createEl("input",{cls:"csv-add-row-control",type:"date"});K.value=ge(),M[R]=K}),m.forEach(R=>{D[R]=!1;let K=A(R,"toggle").createEl("label",{cls:"csv-add-switch"}),T=K.createEl("input",{type:"checkbox",cls:"csv-add-switch-input"});K.createSpan({cls:"csv-add-switch-track"}),T.addEventListener("change",()=>{D[R]=T.checked}),M[R]=T}),C.forEach(R=>{let W=A(R,"field"),K=new Set(u.map(F=>{var H;return((H=F[R])!=null?H:"").trim()}).filter(Boolean));if(R!==S&&(d.categoricalColumns?d.categoricalColumns.includes(R):Xt(K.size))){let F=W.createEl("select",{cls:"csv-add-row-control"});F.createEl("option",{text:"\u2014",value:""}),Array.from(K).sort().forEach(z=>F.createEl("option",{text:z,value:z})),F.createEl("option",{text:"+ custom",value:"__custom__"});let H=E.createDiv({cls:"csv-add-row csv-add-row-custom is-hidden"}),$=H.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:`Custom ${Tt(R).toLowerCase()}`});E.insertBefore(H,W.nextSibling),F.addEventListener("change",()=>{H.classList.toggle("is-hidden",F.value!=="__custom__"),F.value==="__custom__"&&$.focus()}),M[R]=F,M[`${R}__custom`]=$}else M[R]=W.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:Tt(R)})}),b.forEach(R=>{let W=E.createDiv({cls:"csv-add-row csv-add-row-notes"});W.createSpan({cls:"csv-add-row-label",text:Tt(R)}),M[R]=W.createEl("textarea",{cls:"csv-add-row-textarea",placeholder:"Optional notes\u2026"})});let N=v.createEl("button",{text:"Add",cls:"csv-add-submit"}),I=x.querySelector(".csv-add-card-title"),P=()=>{if(!p.length)return;let R=M[p[0]];if(!R)return;let W=R.value,K=u.find(T=>T[p[0]]===W);I&&I.setText(K?`Updating ${W}`:"New entry"),v.classList.toggle("is-updating",!!K),N.setText(K?"Update":"Add"),m.forEach(T=>{var $;let F=M[T];if(!F)return;let H=Ls(($=K==null?void 0:K[T])!=null?$:"");F.checked=H,D[T]=H}),[...C,...b].forEach(T=>{var $;let F=M[T];if(!F)return;let H=($=K==null?void 0:K[T])!=null?$:"";if(F instanceof HTMLSelectElement){let z=Array.from(F.options).find(X=>X.value===H),V=M[`${T}__custom`],j=V==null?void 0:V.closest(".csv-add-row-custom");z?(F.value=H,j&&j.classList.add("is-hidden"),V&&(V.value="")):H?(F.value="__custom__",V&&(V.value=H),j&&j.classList.remove("is-hidden")):(F.value="",j&&j.classList.add("is-hidden"),V&&(V.value=""))}else F.instanceOf(HTMLTextAreaElement),F.value=H})};if(P(),p.length){let R=M[p[0]];R==null||R.addEventListener("change",P)}let w=()=>{v.classList.remove("is-hidden"),y.classList.add("is-hidden");let R=v.querySelector(".csv-add-row-control");R==null||R.focus()},U=()=>{v.classList.add("is-hidden"),y.classList.remove("is-hidden")};y.addEventListener("click",w),k.addEventListener("click",U);let O=async()=>{let R={};h.forEach(z=>{var V,j,X,q;m.includes(z)?R[z]=D[z]?"1":"0":M[z]instanceof HTMLSelectElement&&M[z].value==="__custom__"?R[z]=(j=(V=M[`${z}__custom`])==null?void 0:V.value)!=null?j:"":M[z]instanceof HTMLTextAreaElement?R[z]=M[z].value:R[z]=(q=(X=M[z])==null?void 0:X.value)!=null?q:""});let W=p.length>0&&p.some(z=>{var V;return((V=R[z])!=null?V:"").trim()}),K=[...C,...b].some(z=>{var V;return((V=R[z])!=null?V:"").trim()}),T=m.some(z=>D[z]);if(!W&&!K&&!T){new be.Notice("Please fill at least one field");return}let F=[];try{let z=await s.vault.read(c);F=kt(z).rows}catch(z){new be.Notice(`Error reading file: ${z instanceof Error?z.message:String(z)}`);return}let H=!1,$=-1;if(p.length>0){let z=p[0],V=R[z];if($=F.findIndex(j=>j[z]===V),$>=0){H=!0;let j=F[$];h.forEach(X=>{var q;(m.includes(X)||((q=R[X])!=null?q:"").trim())&&(j[X]=R[X])})}else F.push(R)}else F.push(R);try{let z=xr.default.unparse(F,{columns:h});await s.vault.modify(c,z),new be.Notice(H?`Updated entry for ${R[p[0]]||""}`:`Added entry to ${c.basename}`),u.length=0,u.push(...F),p.length>0?P():(m.forEach(V=>{D[V]=!1;let j=M[V];j&&(j.checked=!1)}),[...C,...b].forEach(V=>{let j=M[V];j instanceof HTMLSelectElement?j.selectedIndex=0:(j.instanceOf(HTMLTextAreaElement)||j)&&(j.value="");let X=M[`${V}__custom`];if(X){X.value="";let q=X.closest(".csv-add-row-custom");q&&q.classList.add("is-hidden")}})),window.setTimeout(()=>{(async()=>{let V=s.vault.getAbstractFileByPath(i.sourcePath);V instanceof be.TFile&&await s.workspace.getLeaf(!1).openFile(V,{state:{mode:"preview"}})})()},300)}catch(z){new be.Notice(`Error saving: ${z instanceof Error?z.message:String(z)}`)}};N.addEventListener("click",()=>{O()})}function _i(s,t){let e=s.getFilteredRows();s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${e.length} of ${s.rows.length} entries`});let n=t.createDiv({cls:"csv-table-wrapper"}).createEl("table",{cls:"csv-table"}),o=n.createEl("thead").createEl("tr");s.headers.forEach(L=>{let l=o.createEl("th");l.setText(L),l.addClass("csv-th-sortable"),s.tableSortCol===L&&l.createSpan({cls:"csv-th-sort-indicator",text:s.tableSortDir==="asc"?" \u25B2":" \u25BC"}),l.title="Click to sort",l.addEventListener("click",f=>{f.target.closest(".csv-col-resize-handle")||(s.tableSortCol!==L?(s.tableSortCol=L,s.tableSortDir="asc"):s.tableSortDir==="asc"?s.tableSortDir="desc":s.tableSortCol=null,s.renderView())});let c=s.settings.columnWidths[L];c&&(l.style.width=c+"px");let d=l.createDiv({cls:"csv-col-resize-handle"}),h=0,u=0;d.addEventListener("pointerdown",f=>{f.preventDefault(),f.stopPropagation(),d.setPointerCapture(f.pointerId),h=f.clientX,u=l.offsetWidth;let g=p=>{l.style.width=Math.max(60,u+p.clientX-h)+"px"},m=p=>{s.settings.columnWidths[L]=Math.max(60,u+p.clientX-h),d.removeEventListener("pointermove",g),d.removeEventListener("pointerup",m),s.persistSettings()};d.addEventListener("pointermove",g),d.addEventListener("pointerup",m)})}),o.createEl("th",{text:""});let r=matchMedia("(pointer: coarse)").matches,a=n.createEl("tbody");e.forEach(L=>{let l=a.createEl("tr");l.addEventListener("contextmenu",h=>s.openRowContextMenu(L,h)),s.headers.forEach(h=>{var f,g;let u=l.createEl("td");if(s.isNotesCol(h)){u.addClass("csv-table-notes-cell");let m=((f=L[h])!=null?f:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").split(` +`).filter(C=>C.trim()).slice(0,3).join(" \xB7 "),p=m?m.slice(0,200)+(m.length>200?"\u2026":""):"+ Add note",b=u.createSpan({text:p});m||b.addClass("csv-table-notes-empty"),u.title="Click to open note",u.addEventListener("click",C=>{C.stopPropagation(),s.openNoteExpander(L,h)})}else if(s.isSelectCol(h))s.renderSelectField(u,L,h);else{let m=(g=L[h])!=null?g:"";u.setText(m),m.length>80&&(u.title=m),Be(s,u,L,h)}});let c=l.createEl("td",{cls:"csv-table-action"}),d=s.notesFileExists(L);c.createEl("button",{cls:`csv-table-notes-btn ${d?"exists":""}`,text:d?"\u{1F4C4}":"\u271A",title:d?"Open notes":"Create notes"}).addEventListener("click",()=>void s.openOrCreateNotes(L)),c.createEl("button",{cls:"csv-table-del-btn",text:"\u2715",title:"Delete row (undo available)"}).addEventListener("click",()=>s.deleteWithUndo(L))}),r||window.requestAnimationFrame(()=>{a.querySelectorAll("td:not(.csv-table-notes-cell):not(.csv-table-action)").forEach(L=>{L.scrollHeight>L.clientHeight+1&&L.addClass("csv-cell--clipped")})})}function Be(s,t,e,i){t.addEventListener("click",n=>{var d,h;if(t.querySelector("input"))return;t.empty();let o=(d=s.fileCfg.dateColumns)==null?void 0:d.includes(i),r=((h=e[i])!=null?h:"").trim(),a=o||Et(i)&&(r===""||mi.test(r)),L=a?r.slice(0,10):r,l=t.createEl("input",{cls:"csv-inline-input",value:L,type:a?"date":"text"});l.focus(),a||l.select(),l.addEventListener("click",u=>u.stopPropagation());let c=!1;l.addEventListener("blur",()=>{var u;!c&&l.value!==L&&(e[i]=l.value,s.scheduleSave()),t.empty(),t.setText(((u=e[i])!=null?u:"")||"\u2014")}),l.addEventListener("keydown",u=>{u.key==="Enter"&&l.blur(),u.key==="Escape"&&(c=!0,l.blur())})})}function Si(s){return!!(s.getCategoryCol()||s.getStatusCol()||_r(s)||s.authorKey())}function _r(s){return s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"])}function Ws(s){var n;let t=(s!=null?s:"").trim();if(!t)return null;let e=((n=t.match(/★/g))!=null?n:[]).length;if(e>0)return e;let i=parseFloat(t);return isNaN(i)||i<=0?null:Math.min(5,i)}var Sr=["watched","read","finished","completed","done","yes","seen"],kr=["watching","reading","in progress","in-progress"],oc=["dropped","abandoned","dnf"];function rc(s){let t=s.toLowerCase();return Sr.includes(t)?"is-done":kr.includes(t)?"is-progress":oc.includes(t)?"is-dropped":""}function Hs(s,t){let e=new Map;return s.forEach(i=>t(i).forEach(n=>{var o;return e.set(n,((o=e.get(n))!=null?o:0)+1)})),e}function Zs(s,t,e,i){if(!e.length)return;let n=s.createDiv({cls:"csv-stats-section"});n.createDiv({cls:"csv-stats-section-title",text:t});let o=Math.max(...e.map(r=>r.count));e.forEach(r=>{var d;let a=n.createDiv({cls:"csv-stats-bar-row"});a.createDiv({cls:"csv-stats-bar-label",text:r.label,attr:{title:r.label}});let l=a.createDiv({cls:"csv-stats-bar-track"}).createDiv({cls:`csv-stats-bar-fill ${(d=r.cls)!=null?d:""}`});l.style.width=`${Math.max(2,Math.round(r.count/o*100))}%`;let c=i>0?Math.round(r.count/i*100):0;a.createDiv({cls:"csv-stats-bar-count",text:`${r.count} \xB7 ${c}%`}),r.onClick&&(a.addClass("is-clickable"),a.title=`Show "${r.label}" in the library`,a.addEventListener("click",r.onClick))})}function Er(s,t){let e=s.getFilteredRows();if(s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Stats over ${e.length} of ${s.rows.length} entries`}),!e.length){t.createEl("p",{text:"No entries to chart.",cls:"csv-empty-state"});return}let i=t.createDiv({cls:"csv-stats-wrap"}),n=s.getStatusCol(),o=s.getCategoryCol(),r=_r(s),a=s.authorKey(),L=s.resolveCol(["Year","year"]),l=i.createDiv({cls:"csv-stats-overview"}),c=(h,u)=>{let f=l.createDiv({cls:"csv-stats-chip"});f.createDiv({cls:"csv-stats-chip-value",text:h}),f.createDiv({cls:"csv-stats-chip-label",text:u})};if(c(String(e.length),"entries"),n){let h=e.filter(f=>{var g;return Sr.includes(((g=f[n])!=null?g:"").toLowerCase().trim())}).length;h>0&&c(`${h} \xB7 ${Math.round(h/e.length*100)}%`,"done");let u=e.filter(f=>{var g;return kr.includes(((g=f[n])!=null?g:"").toLowerCase().trim())}).length;u>0&&c(String(u),"in progress")}if(o){let h=Hs(e,u=>{var f;return((f=u[o])!=null?f:"").split(",").map(g=>g.trim()).filter(Boolean)});h.size>0&&c(String(h.size),o.toLowerCase()==="genre"||o.toLowerCase()==="genres"?"genres":"categories")}if(r){let h=e.map(u=>Ws(u[r])).filter(u=>u!==null);if(h.length){let u=h.reduce((f,g)=>f+g,0)/h.length;c(`\u2605 ${u.toFixed(1)}`,`avg of ${h.length} rated`)}}let d=(h,u)=>{s.libraryStatusFilter=h!=null?h:"all",s.libraryGenreFilter=u!=null?u:"all",s.mode="library",s.renderView()};if(n){let h=Hs(e,f=>{var m;let g=((m=f[n])!=null?m:"").trim();return g?[g]:[]}),u=Array.from(h.entries()).sort((f,g)=>g[1]-f[1]).map(([f,g])=>({label:f,count:g,cls:rc(f),onClick:o?()=>d(f,null):void 0}));Zs(i,`By ${n.toLowerCase()}`,u,e.length)}if(o){let h=Hs(e,f=>{var g;return((g=f[o])!=null?g:"").split(",").map(m=>m.trim()).filter(Boolean)}),u=Array.from(h.entries()).sort((f,g)=>g[1]-f[1]||f[0].localeCompare(g[0])).slice(0,12).map(([f,g])=>({label:f,count:g,onClick:()=>d(null,f)}));Zs(i,`By ${o.toLowerCase()}`,u,e.length)}if(r){let h=new Map,u=0;if(e.forEach(f=>{var p;let g=Ws(f[r]);if(g===null)return;let m=Math.min(5,Math.max(1,Math.round(g)));h.set(m,((p=h.get(m))!=null?p:0)+1),u++}),u>0){let f=[5,4,3,2,1].filter(g=>{var m;return((m=h.get(g))!=null?m:0)>0}).map(g=>({label:"\u2605".repeat(g),count:h.get(g),cls:"is-rating"}));Zs(i,"Ratings",f,u)}}if(L){let h=Hs(e,u=>{var g;let f=((g=u[L])!=null?g:"").match(/\d{4}/);return f?[f[0]]:[]});if(h.size>1){let u=Array.from(h.entries()).sort((f,g)=>f[0].localeCompare(g[0])).map(([f,g])=>({label:f,count:g}));Zs(i,"By year",u,e.length)}}if(a){let h=Hs(e,f=>{var m;let g=((m=f[a])!=null?m:"").trim();return g?[g]:[]}),u=Array.from(h.entries()).filter(([,f])=>f>1);if(u.length>=2){let f=u.sort((g,m)=>m[1]-g[1]||g[0].localeCompare(m[0])).slice(0,8).map(([g,m])=>({label:g,count:m}));Zs(i,`Top ${a.toLowerCase()}s`,f,e.length)}}}function Pt(s){let t=s.fileCfg.kanbanGroupCol;if(t&&s.headers.includes(t))return t;let e=s.getCategoryCol();if(e)return e;let i=new Set;s.headers.forEach(r=>{s.isNotesCol(r)&&i.add(r)});let n=s.getDateCol();n&&i.add(n);let o=s.titleKey();return o&&i.add(o),cr(s.headers,s.rows,i)}function ki(s,t){let e=Pt(s);if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let i=s.getCategoryCol(),n=s.getStatusCol(),o=n===e?null:n,r=s.getFilteredRows();s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${r.length} of ${s.rows.length} entries`});let a=t.createDiv({cls:"csv-kanban-groupbar"});a.createSpan({cls:"csv-kanban-groupbar-label",text:"Group by"});let L=a.createEl("select",{cls:"csv-library-filter-select"});s.headers.filter(m=>!s.isNotesCol(m)).forEach(m=>{let p=L.createEl("option",{text:m===i?`${m} (default)`:m,value:m});m===e&&(p.selected=!0)}),L.addEventListener("change",()=>{let m=s.fileCfg;m.kanbanGroupCol=L.value===i?void 0:L.value,s.saveFileCfg(m),s.renderView(!0)});let l=Lr(e,r.map(m=>{var p;return(p=m[e])!=null?p:""})),c=m=>{var C;let p=(C=m[e])!=null?C:"",b;if(l){let S=lr(p);b=S?[S]:[]}else b=p.split(",").map(S=>S.trim()).filter(Boolean);return b.length||(b=["\u2014"]),b},d=new Set;r.forEach(m=>c(m).forEach(p=>d.add(p)));let h=Array.from(d).sort();if(!h.length){let m=t.createDiv({cls:"csv-empty-state"});m.createEl("p",{text:s.searchQuery?"No matching entries found.":`No "${e}" values found.`}),s.searchQuery&&m.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear search"}).addEventListener("click",()=>{s.searchQuery="",s.renderView()});return}let u=["In progress","Finished","Not started"],f=o?Array.from(new Set([...u,...r.map(m=>{var p;return(p=m[o])!=null?p:""}).filter(Boolean)])).filter(m=>r.some(p=>{var b;return((b=p[o])!=null?b:"")==m})):[],g=t.createDiv({cls:"csv-kanban-board"});h.forEach(m=>{let p=r.filter(_=>c(_).includes(m));if(!p.length)return;let b=g.createDiv({cls:"csv-kanban-col"}),C=b.createDiv({cls:"csv-kanban-col-header"});C.createDiv({cls:"csv-kanban-col-title",text:m}),C.createDiv({cls:"csv-kanban-col-count",text:String(p.length)});let S=b.createDiv({cls:"csv-kanban-col-body"});if(o&&f.length){f.forEach(v=>{let x=p.filter(E=>{var M;return((M=E[o])!=null?M:"")===v});if(!x.length)return;let k=S.createDiv({cls:"csv-kanban-status-group"});k.createDiv({cls:`csv-kanban-status-label status-${v.toLowerCase().replace(/\s+/g,"-")}`,text:v}),x.forEach(E=>On(s,k,E,o,e))});let _=new Set(f),y=p.filter(v=>{var x;return!_.has((x=v[o])!=null?x:"")});if(y.length){let v=S.createDiv({cls:"csv-kanban-status-group"});v.createDiv({cls:"csv-kanban-status-label",text:"\u2014"}),y.forEach(x=>On(s,v,x,o,e))}}else p.forEach(_=>On(s,S,_,o,e))})}function On(s,t,e,i,n){var x,k,E,M,D,A,N,I;let o=t.createDiv({cls:"csv-kanban-card"}),r=s.getNotesCol(),a=(k=(x=s.getImageCol)==null?void 0:x.call(s))!=null?k:null;if(a){let P=gi(s.app,(E=e[a])!=null?E:"",(D=(M=s.file)==null?void 0:M.path)!=null?D:"");if(P){let w=o.createEl("img",{cls:"csv-kanban-card-img",attr:{src:P,loading:"lazy",alt:""}});w.addEventListener("error",()=>w.remove())}}let L=o.createDiv({cls:"csv-kanban-card-title-row"});L.createDiv({cls:`csv-kanban-card-title ${(A=s.isHighlighted)!=null&&A.call(s,e)?"csv-title-highlight":""}`,text:s.getTitle(e)}).addEventListener("click",P=>{P.stopPropagation(),s.openNoteExpander(e,r!=null?r:"")});let c=s.notesFileExists(e);L.createEl("button",{cls:`csv-kanban-notes-icon ${c?"exists":""}`,text:c?"\u{1F4C4}":"+",title:c?"Open notes file":"Create notes file"}).addEventListener("click",P=>{P.stopPropagation(),s.openOrCreateNotes(e)});let h=s.getSubtitle(e);h&&o.createDiv({cls:"csv-kanban-card-sub",text:h});let u=s.titleKey(),f=s.authorKey(),g=new Set([i,u,f,n].filter(Boolean)),m=o.createDiv({cls:"csv-kanban-card-meta"});((N=s.fileCfg.cardFields)!=null?N:s.headers).forEach(P=>{if(!s.headers.includes(P)||g.has(P)||s.isNotesCol(P))return;let w=m.createDiv({cls:"csv-kanban-chip"});if(w.createSpan({cls:"csv-chip-label",text:P+": "}),s.isSelectCol(P)){let U=w.createSpan({cls:`csv-chip-value csv-chip-select${e[P]?"":" csv-chip-value--empty"}`,text:e[P]||"\u2014"});U.addEventListener("click",O=>{O.stopPropagation(),$t(U,e[P],s.getColumnValues(P),Z=>{e[P]=Z,U.setText(Z||"\u2014"),U.classList.toggle("csv-chip-value--empty",!Z),s.scheduleSave()},s.contentEl,{multi:vt(P)})})}else{let U=e[P]?e[P].length>40?e[P].slice(0,38)+"\u2026":e[P]:"\u2014",O=w.createSpan({cls:`csv-chip-value${e[P]?"":" csv-chip-value--empty"}`,text:U});e[P]&&e[P].length>40&&(O.title=e[P])}});let b=s.getNotesCol(),C=!!(b&&((I=e[b])!=null&&I.trim())),S=o.createDiv({cls:"csv-kanban-notes-preview"});if(C&&b){let P=e[b].replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();S.setText(P.slice(0,120)+(P.length>120?"\u2026":"")),S.title="Click to edit"}else S.addClass("csv-kanban-notes-preview--empty"),b&&S.setText("+ add note");let _=o.createDiv({cls:"csv-kanban-notes-editor is-hidden"}),y=()=>{var R,W,K;let P=s.contentEl.querySelector(".csv-content-area"),w=(R=P==null?void 0:P.scrollLeft)!=null?R:0,U=(W=P==null?void 0:P.scrollTop)!=null?W:0;S.classList.add("is-hidden"),_.classList.remove("is-hidden"),_.empty();let O=_.createEl("textarea",{cls:"csv-notes-textarea"});O.value=(K=b?e[b]:"")!=null?K:"",O.addEventListener("click",T=>T.stopPropagation()),O.addEventListener("mousedown",T=>T.stopPropagation()),O.addEventListener("input",()=>{O.style.removeProperty("height"),O.style.height=O.scrollHeight+"px"});let Z=O.value,B=!1,G=T=>{B||(B=!0,v(T,P,w,U))};O.addEventListener("keydown",T=>{T.key==="Escape"&&G(Z)}),O.addEventListener("blur",()=>G(O.value)),O.focus({preventScroll:!0}),O.setSelectionRange(0,0),O.scrollTop=0,window.requestAnimationFrame(()=>{O.style.removeProperty("height"),O.style.height=Math.max(120,O.scrollHeight)+"px"})},v=(P,w,U,O)=>{var Z;if(b&&P!==((Z=e[b])!=null?Z:"")&&(e[b]=P,s.scheduleSave()),_.classList.add("is-hidden"),S.classList.remove("is-hidden"),P.trim()){let B=P.replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();S.setText(B.slice(0,120)+(B.length>120?"\u2026":"")),S.removeClass("csv-kanban-notes-preview--empty"),S.title="Click to edit"}else S.addClass("csv-kanban-notes-preview--empty"),S.setText(b?"+ add note":""),S.removeAttribute("title");w&&(w.scrollLeft=U,w.scrollTop=O,window.requestAnimationFrame(()=>{w.scrollLeft=U,w.scrollTop=O,window.requestAnimationFrame(()=>{w.scrollLeft=U,w.scrollTop=O})}),window.setTimeout(()=>{w.scrollLeft=U,w.scrollTop=O},50))};S.addEventListener("click",P=>{if(P.stopPropagation(),b&&matchMedia("(pointer: coarse)").matches){s.openNoteExpander(e,b);return}y()}),o.addEventListener("contextmenu",P=>s.openRowContextMenu(e,P))}function Ei(s,t){var x,k;let e=Pt(s),i=s.getStatusCol(),n=(x=s.titleKey())!=null?x:s.headers[0];if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let o=new Set;s.rows.forEach(E=>{var D;((D=E[e])!=null?D:"").split(",").map(A=>A.trim()).filter(Boolean).forEach(A=>o.add(A))});let r=new Set;i&&s.rows.forEach(E=>{var D;let M=((D=E[i])!=null?D:"").trim();M&&r.add(M)});let a=t.createDiv({cls:"csv-library-filters"}),L=a.createEl("select",{cls:"csv-library-filter-select"});L.createEl("option",{text:"All",value:"all"});let l=["watched","read","finished","completed","done","yes","seen"],c=["watching","reading","in progress","in-progress"],d=Array.from(r).some(E=>l.includes(E.toLowerCase())),h=Array.from(r).some(E=>c.includes(E.toLowerCase()));(d||h)&&(L.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),d&&L.createEl("option",{text:"\u2713 done",value:"__done__"}),h&&L.createEl("option",{text:"\u25D0 in progress",value:"__inprogress__"}),L.createEl("option",{text:"\u25CB not started",value:"__notstarted__"})),r.size>0&&(L.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),Array.from(r).sort().forEach(E=>{L.createEl("option",{text:E,value:E})})),L.value=s.libraryStatusFilter;let u=a.createEl("select",{cls:"csv-library-filter-select"});u.createEl("option",{text:"All genres",value:"all"}),Array.from(o).sort().forEach(E=>{u.createEl("option",{text:E,value:E})}),u.value=s.libraryGenreFilter;let f=s.resolveCol(["Year","year","Date","date"]),g=s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"]),m=s.resolveCol(["Theme","theme","Tags","tags","Tag","tag","Mood","mood"]),p=(k=s.fileCfg.librarySort)!=null?k:"status",b=a.createEl("select",{cls:"csv-library-filter-select"}),C=[["status","Sort: Status"],["title","Sort: Title"]];g&&C.push(["rating","Sort: Rating"]),f&&C.push(["year","Sort: Year"]),C.forEach(([E,M])=>{let D=b.createEl("option",{text:M,value:E});E===p&&(D.selected=!0)}),b.addEventListener("change",()=>{let E=s.fileCfg;E.librarySort=b.value==="status"?void 0:b.value,s.saveFileCfg(E),s.renderView(!0)});let S=()=>{s.libraryStatusFilter=L.value,s.libraryGenreFilter=u.value,s.renderView(!0)};L.addEventListener("change",S),u.addEventListener("change",S);let _=s.rows.filter(E=>{var M,D;if(s.libraryStatusFilter!=="all"&&i){let A=((M=E[i])!=null?M:"").toLowerCase();if(s.libraryStatusFilter==="__done__"){if(!l.includes(A))return!1}else if(s.libraryStatusFilter==="__inprogress__"){if(!c.includes(A))return!1}else if(s.libraryStatusFilter==="__notstarted__"){if(l.includes(A)||c.includes(A))return!1}else if(A!==s.libraryStatusFilter.toLowerCase())return!1}if(s.libraryGenreFilter!=="all"&&!((D=E[e])!=null?D:"").split(",").map(N=>N.trim().toLowerCase()).includes(s.libraryGenreFilter.toLowerCase()))return!1;if(s.searchQuery.trim()){let A=s.searchQuery.toLowerCase().trim();if(!s.headers.some(N=>{var I;return((I=E[N])!=null?I:"").toLowerCase().includes(A)}))return!1}return!0});(s.libraryStatusFilter!=="all"||s.libraryGenreFilter!=="all"||s.searchQuery.trim())&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${_.length} of ${s.rows.length} entries`});let y={};_.forEach(E=>{var D;let M=s.libraryGenreFilter!=="all"?[s.libraryGenreFilter]:((D=E[e])!=null?D:"Uncategorized").split(",").map(A=>A.trim()).filter(Boolean);M.length===0&&M.push("Uncategorized"),M.forEach(A=>{y[A]||(y[A]=[]),y[A].push(E)})});let v=t.createDiv({cls:"csv-library-sections"});if(Object.keys(y).sort().forEach(E=>{var B,G,R,W,K;let M=y[E],D=v.createEl("details",{cls:"csv-library-section"}),A=E.toLowerCase(),N=((B=s.fileCfg.collapsedGroups)!=null?B:[]).map(T=>T.toLowerCase());D.open=!((G=s.collapsedGroups)!=null&&G.has(A)||N.includes(A)),D.addEventListener("toggle",()=>{var z;let T=s.fileCfg,F=((z=T.collapsedGroups)!=null?z:[]).map(V=>V.toLowerCase()),H=new Set(F);D.open?H.delete(A):H.add(A);let $=Array.from(H);$.length===F.length&&$.every(V=>F.includes(V))||(T.collapsedGroups=$,s.saveFileCfg(T))});let I=D.createEl("summary",{cls:"csv-library-section-header"});I.createSpan({cls:"csv-library-arrow",text:"\u25B6"}),I.createSpan({text:` ${E} `}),I.createSpan({cls:"csv-library-count",text:String(M.length)});let P=D.createDiv({cls:"csv-library-grid"}),w=(T,F)=>{var H,$;return((H=T[n])!=null?H:"").localeCompare(($=F[n])!=null?$:"")},U=(T,F)=>T===null&&F===null?0:T===null?1:F===null?-1:F-T;M.sort((T,F)=>{var H,$,z,V;if(p==="title")return w(T,F);if(p==="rating"&&g)return U(Ws((H=T[g])!=null?H:""),Ws(($=F[g])!=null?$:""))||w(T,F);if(p==="year"&&f){let j=X=>{var nt;let q=((nt=X[f])!=null?nt:"").match(/\d{4}/);return q?parseInt(q[0],10):null};return U(j(T),j(F))||w(T,F)}if(i){let j=((z=T[i])!=null?z:"").toLowerCase(),X=((V=F[i])!=null?V:"").toLowerCase(),q=l.includes(j),nt=l.includes(X);if(q!==nt)return q?-1:1;let Q=c.includes(j),et=c.includes(X);if(Q!==et)return Q?-1:1}return w(T,F)});let O=(R=s.fileCfg.cardFields)!=null?R:s.headers,Z=(K=(W=s.getImageCol)==null?void 0:W.call(s))!=null?K:null;M.forEach(T=>{var V,j,X,q,nt,Q,et,J;let F=P.createDiv({cls:"csv-library-card"});if(Z){let ot=gi(s.app,(V=T[Z])!=null?V:"",(X=(j=s.file)==null?void 0:j.path)!=null?X:"");if(ot){let lt=F.createEl("img",{cls:"csv-library-card-img",attr:{src:ot,loading:"lazy",alt:""}});lt.addEventListener("error",()=>lt.remove())}}let H=F.createDiv({cls:`csv-library-card-title ${(q=s.isHighlighted)!=null&&q.call(s,T)?"csv-title-highlight":""}`});if(i){let ot=((nt=T[i])!=null?nt:"").toLowerCase();l.includes(ot)&&H.createSpan({cls:"csv-library-done-dot"})}H.createSpan({text:(Q=T[n])!=null?Q:"Untitled"});let $=[],z=[];for(let ot of O){if(!ot)continue;let lt=String((et=T[ot])!=null?et:"").trim();if(lt)if(ot===g){let Bt=ar(lt,ot);Bt&&F.createDiv({cls:"csv-library-card-rating",text:Bt})}else if(ot===m)z.push(...lt.split(",").map(Bt=>Bt.trim()).filter(Boolean));else if(ot===f){let Bt=lt.match(/\d{4}/);$.push(Bt?Bt[0]:lt)}else $.push(lt)}if($.length&&F.createDiv({cls:"csv-library-card-meta",text:$.join(" \xB7 ")}),s.libraryGenreFilter!=="all"){let ot=((J=T[e])!=null?J:"").split(",").map(lt=>lt.trim()).filter(lt=>lt&<.toLowerCase()!==s.libraryGenreFilter.toLowerCase());z.push(...ot)}if(z.length){let ot=F.createDiv({cls:"csv-library-card-tags"});z.slice(0,3).forEach(lt=>{ot.createSpan({cls:"csv-library-card-tag",text:lt})})}F.addEventListener("click",()=>{var ot;s.openNoteExpander(T,(ot=s.getNotesCol())!=null?ot:"")}),F.addEventListener("contextmenu",ot=>s.openRowContextMenu(T,ot))})}),Object.keys(y).length===0){let E=v.createDiv({cls:"csv-empty-state"});E.createEl("p",{text:"No entries match your filters."}),E.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.libraryStatusFilter="all",s.libraryGenreFilter="all",s.searchQuery="",s.renderView()})}}var Cn=require("obsidian");var ve=require("obsidian"),ac="http://127.0.0.1:8765",Lc=6;async function Mr(s,t){let e;try{e=await(0,ve.requestUrl)({url:ac,method:"POST",contentType:"application/json",body:JSON.stringify({action:s,version:Lc,params:t}),throw:!1})}catch(n){throw new Error("Couldn't reach Anki. Is the desktop app open with the AnkiConnect add-on installed?")}let i=e.json;if(i.error)throw new Error(i.error);return i.result}function In(s){var t,e,i;return(i=(e=(t=s.titleKey())!=null?t:s.resolveCol(["Quote","Headline","Phrase","Term","Word","Question","Front","Name","Title"]))!=null?e:s.headers[0])!=null?i:null}function lc(s){let t=s.fileCfg.ankiFrontCol;return t&&s.headers.includes(t)?t:In(s)}function Fn(s){return s.replace(/&/g,"&").replace(//g,">")}function cc(s,t,e){return s.headers.filter(i=>{var n;return i!==e&&((n=t[i])!=null?n:"").trim()}).map(i=>`${Fn(i)}: ${Fn(t[i].trim())}`).join("
")}async function wr(s){if(!s.file)return;let t=lc(s);if(!t){new ve.Notice("No column to use as the Anki card front.",6e3);return}let e=s.file.basename,i=s.rows.filter(o=>{var r;return((r=o[t])!=null?r:"").trim()});if(!i.length){new ve.Notice(`Nothing to sync \u2014 no rows with a "${t}" value.`,6e3);return}let n=new ve.Notice(`Syncing ${i.length} cards to Anki deck \u201C${e}\u201D\u2026`,0);try{await Mr("createDeck",{deck:e});let o=i.map(l=>({deckName:e,modelName:"Basic",fields:{Front:Fn(l[t].trim()),Back:cc(s,l,t)},options:{allowDuplicate:!1,duplicateScope:"deck"},tags:["datadeck"]})),r=await Mr("addNotes",{notes:o}),a=r.filter(l=>l!=null).length,L=r.length-a;n.hide(),new ve.Notice(`Anki sync: ${a} added${L?`, ${L} already present`:""} (deck \u201C${e}\u201D).`,6e3)}catch(o){n.hide(),new ve.Notice(`Anki sync failed: ${o instanceof Error?o.message:String(o)}`,8e3)}}var es=require("obsidian");var Ho=null;async function ts(){if(Ho)return Ho;let s=await Promise.resolve().then(()=>(il(),sl));return s.Chart.register(s.LineController,s.ScatterController,s.BarController,s.LineElement,s.PointElement,s.BarElement,s.LinearScale,s.CategoryScale,s.Filler,s.Tooltip,s.Legend),Ho=s,s}var nl={pi:Math.PI,e:Math.E},ol={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sqrt:Math.sqrt,log:Math.log10,ln:Math.log,exp:Math.exp,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,sign:Math.sign},Zo={min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2};function T5(s){let t=[],e=0;for(;e{var h;return(h=e[i])!=null?h:null},o=()=>{var h;return(h=e[i++])!=null?h:null};function r(){let h=a();for(;;){let u=n();if((u==null?void 0:u.kind)==="op"&&(u.op==="+"||u.op==="-")){i++;let f=a(),g=h;h=u.op==="+"?p=>g(p)+f(p):p=>g(p)-f(p)}else return h}}function a(){let h=L();for(;;){let u=n();if((u==null?void 0:u.kind)==="op"&&(u.op==="*"||u.op==="/"||u.op==="%")){i++;let f=L(),g=h,m=u.op;h=m==="*"?p=>g(p)*f(p):m==="/"?p=>g(p)/f(p):p=>g(p)%f(p)}else if(u&&(u.kind==="num"||u.kind==="ident"||u.kind==="lparen")){let f=L(),g=h;h=m=>g(m)*f(m)}else return h}}function L(){let h=n();if((h==null?void 0:h.kind)==="op"&&h.op==="-"){i++;let u=L();return f=>-u(f)}return(h==null?void 0:h.kind)==="op"&&h.op==="+"?(i++,L()):l()}function l(){let h=c(),u=n();if((u==null?void 0:u.kind)==="op"&&u.op==="^"){i++;let f=L();return g=>Math.pow(h(g),f(g))}return h}function c(){var u,f,g,m,p;let h=o();if(!h)throw new Error("Unexpected end of formula");if(h.kind==="num"){let b=h.value;return()=>b}if(h.kind==="lparen"){let b=r();if(((u=o())==null?void 0:u.kind)!=="rparen")throw new Error("Missing closing )");return b}if(h.kind==="ident"){if(h.name==="x")return C=>C;if(h.name in nl){let C=nl[h.name];return()=>C}let b=((f=n())==null?void 0:f.kind)==="lparen";if(h.name in ol||h.name in Zo){if(!b)throw new Error(`${h.name} needs parentheses, e.g. ${h.name}(x)`);i++;let C=r();if(h.name in Zo){if(((g=o())==null?void 0:g.kind)!=="comma")throw new Error(`${h.name}(a, b) needs two arguments`);let _=r();if(((m=o())==null?void 0:m.kind)!=="rparen")throw new Error("Missing closing )");let y=Zo[h.name];return v=>y(C(v),_(v))}if(((p=o())==null?void 0:p.kind)!=="rparen")throw new Error("Missing closing )");let S=ol[h.name];return _=>S(C(_))}throw new Error(`Unknown name "${h.name}" \u2014 use x, pi, e, or a function like sin()`)}throw new Error(`Unexpected "${h.kind==="op"?h.op:h.kind}"`)}let d=r();if(i{var o;let i=0,n=0;for(let r of t){let a=((o=r[e])!=null?o:"").trim();a&&(i++,Fe(a)!==null&&n++)}return n>=2&&n/i>=.7})}function A5(s){let t=s.length;if(t<2)return null;let e=0,i=0,n=0,o=0;for(let h of s)e+=h.x,i+=h.y,n+=h.x*h.x,o+=h.x*h.y;let r=t*n-e*e;if(r===0)return null;let a=(t*o-e*i)/r,L=(i-a*e)/t,l=i/t,c=0,d=0;for(let h of s){let u=h.y-(a*h.x+L);c+=u*u,d+=(h.y-l)*(h.y-l)}return{slope:a,intercept:L,r2:d===0?1:1-c/d}}function R5(s,t){let e=[...s].sort((o,r)=>o.x-r.x),i=t/2,n=0;return e.map(o=>{for(;n{let r=new Date(o);if(t==="month")return new Date(r.getFullYear(),r.getMonth(),1).getTime();let a=(r.getDay()+6)%7;return new Date(r.getFullYear(),r.getMonth(),r.getDate()-a).getTime()},n=new Map;return s.forEach(o=>{var L;let r=i(o.x),a=(L=n.get(r))!=null?L:{sum:0,n:0};a.sum+=o.y,a.n+=1,n.set(r,a)}),[...n.entries()].sort((o,r)=>o[0]-r[0]).map(([o,r])=>({x:o,y:e==="count"?r.n:e==="sum"?r.sum:r.sum/r.n}))}function Ps(s){var i;let t=(i=s.ownerDocument.defaultView)==null?void 0:i.getComputedStyle(s),e=(n,o)=>(t==null?void 0:t.getPropertyValue(n).trim())||o;return{accent:e("--interactive-accent","#378ADD"),muted:e("--text-muted","#888888"),grid:e("--background-modifier-border","rgba(128,128,128,0.25)"),fitLine:e("--text-faint","#999999"),formula:e("--color-orange","#e0883a"),series:[e("--color-blue","#4e79a7"),e("--color-green","#59a14f"),e("--color-red","#e15759"),e("--color-purple","#b07aa1"),e("--color-cyan","#76b7b2"),e("--color-pink","#ff9da7"),e("--color-yellow","#edc948")]}}var Rs=s=>{if(!Number.isFinite(s))return String(s);let t=Math.abs(s);return t!==0&&(t>=1e6||t<.001)?s.toExponential(2):String(Math.round(s*1e3)/1e3)},al=s=>{let t=new Date(s);return isNaN(t.getTime())?String(s):ge(t)};function fn(s,t){var m,p;let e=[],i=s.series.length>1,n=s.series.flatMap(b=>b.points),o=n.map(b=>b.x),r=n.length?Math.min(...o):(m=s.xMin)!=null?m:0,a=n.length?Math.max(...o):(p=s.xMax)!=null?p:10,L=n.filter(b=>b.size!==void 0),l=L.length?Math.min(...L.map(b=>b.size)):0,c=L.length?Math.max(...L.map(b=>b.size)):0,d=(b,C)=>b.size===void 0?C:c===l?7:3+11*Math.sqrt((b.size-l)/(c-l)),h=[];s.series.forEach((b,C)=>{var v;let S=s.connect?[...b.points].sort((x,k)=>x.x-k.x):b.points;if(!S.length)return;let _=i?t.series[C%t.series.length]:t.accent,y=s.connect?3:4;if(((v=s.smoothDays)!=null?v:0)>0?(e.push({type:"scatter",label:b.label||s.yLabel,csvSkipLegend:!0,data:S,backgroundColor:_,borderColor:_,pointRadius:2.5,pointHoverRadius:5}),e.push({type:"line",label:b.label||s.yLabel,data:R5(S,s.smoothDays*864e5),borderColor:_,backgroundColor:_,borderWidth:2,pointRadius:0,pointHitRadius:0,tension:.3})):e.push({type:s.connect?"line":"scatter",label:b.label||s.yLabel,data:S,backgroundColor:_,borderColor:_,borderWidth:1.5,pointRadius:L.length?S.map(x=>d(x,y)):y,pointHoverRadius:L.length?S.map(x=>d(x,y)+2):6,tension:.3}),s.fit==="linear"){let x=A5(S),k=S.map(D=>D.x),E=Math.min(...k),M=Math.max(...k);if(x&&M>E){e.push({type:"line",label:`${b.label||"Best"} fit`,csvIsFit:!0,data:[{x:E,y:x.slope*E+x.intercept},{x:M,y:x.slope*M+x.intercept}],borderColor:i?_:t.fitLine,borderDash:[6,4],borderWidth:1.5,pointRadius:0,pointHitRadius:0});let D=` \xB7 R\xB2 = ${(Math.round(x.r2*1e3)/1e3).toFixed(3)}`,A=s.xIsDate?`${x.slope*864e5>=0?"+":""}${Rs(x.slope*864e5)} ${s.yLabel}/day${D}`:`y = ${Rs(x.slope)}x ${x.intercept>=0?"+":"\u2212"} ${Rs(Math.abs(x.intercept))}${D}`;h.push(i?`${b.label}: ${A}`:s.xIsDate?`Trend: ${A}`:A)}}});let u=h.length?h.join(" \xB7 "):null,f=null;if(s.formula.trim())try{let b=rl(s.formula),C=[],S=160;for(let _=0;_<=S;_++){let y=r+(a-r)*_/S,v=b(y);Number.isFinite(v)&&C.push({x:y,y:v})}C.length&&e.push({type:"line",label:s.formula.trim(),data:C,borderColor:t.formula,borderWidth:1.5,pointRadius:0,pointHitRadius:0,tension:0})}catch(b){f=b instanceof Error?b.message:String(b)}return{config:{type:"scatter",data:{datasets:e},options:{responsive:!0,maintainAspectRatio:!1,scales:{x:{type:"linear",title:{display:!s.xIsDate&&!!s.xLabel,text:s.xLabel,color:t.muted},ticks:{color:t.muted,...s.xIsDate?{callback:b=>al(Number(b)),maxTicksLimit:8}:{}},grid:{color:t.grid}},y:{title:{display:!!s.yLabel,text:s.yLabel,color:t.muted},ticks:{color:t.muted},grid:{color:t.grid}}},plugins:{legend:{display:e.filter(b=>!b.csvIsFit&&!b.csvSkipLegend).length>1,labels:{color:t.muted,boxWidth:12,filter:b=>{var S;let C=e[(S=b.datasetIndex)!=null?S:-1];return!(C!=null&&C.csvIsFit||C!=null&&C.csvSkipLegend)}}},tooltip:{callbacks:{label:b=>{let C=b.raw,S=s.xIsDate?al(C.x):Rs(C.x),_=i&&b.dataset.label?`[${b.dataset.label}] `:"",y=C.label?`${C.label}: `:"",v=C.size!==void 0&&s.sizeLabel?` \xB7 ${s.sizeLabel}: ${Rs(C.size)}`:"";return`${_}${y}(${S}, ${Rs(C.y)})${v}`}}}}}},fitText:u,formulaError:f}}var hn="(row number)";function jo(s,t,e,i,n,o,r,a){let L=new Map,l=0;return s.forEach((d,h)=>{var b,C,S,_,y;let u=Fe((b=d[e])!=null?b:""),f;if(t===hn)f=h+1;else if(o){let v=r((C=d[t])!=null?C:"");f=v?v.getTime():null}else f=Fe((S=d[t])!=null?S:"");if(f===null||u===null){l++;return}let g=i?((_=d[i])!=null?_:"").trim()||"\u2014":"",m=L.get(g);m||(m=[],L.set(g,m));let p={x:f,y:u,label:a(d)};if(n){let v=Fe((y=d[n])!=null?y:"");v!==null&&(p.size=v)}m.push(p)}),{series:[...L.entries()].sort((d,h)=>d[0]==="\u2014"?1:h[0]==="\u2014"?-1:d[0].localeCompare(h[0])).map(([d,h])=>({label:d,points:h})),skipped:l}}function P5(s,t,e){return s.filter(i=>{if(e.has(i))return!1;let n=new Set(t.map(o=>{var r;return((r=o[i])!=null?r:"").trim()}).filter(Boolean));return n.size>=2&&n.size<=10})}function O5(s,t,e){return s.filter(i=>{if(e.has(i))return!1;let n=new Set(t.map(o=>{var r;return((r=o[i])!=null?r:"").trim()}).filter(Boolean));return n.size>=1&&n.size<=30})}function Uo(s,t,e,i,n){let o=new Map,r=new Set,a=0,L=vt(t);s.forEach(h=>{var p,b,C;let u=0;if(n!=="count"){let S=Fe((p=h[e!=null?e:""])!=null?p:"");if(S===null){a++;return}u=S}let f=((b=h[t])!=null?b:"").trim(),g=L?f?f.split(",").map(S=>S.trim()).filter(Boolean):["\u2014"]:[f||"\u2014"],m=i?((C=h[i])!=null?C:"").trim()||"\u2014":"";r.add(m),g.forEach(S=>{var v;let _=o.get(S);_||(_=new Map,o.set(S,_));let y=(v=_.get(m))!=null?v:{sum:0,n:0};y.sum+=u,y.n+=1,_.set(m,y)})});let l=(h,u)=>h==="\u2014"?1:u==="\u2014"?-1:h.localeCompare(u,void 0,{numeric:!0}),c=[...o.keys()].sort(l),d=[...r].sort(l).map(h=>({label:h,values:c.map(u=>{var g;let f=(g=o.get(u))==null?void 0:g.get(h);return!f||f.n===0?0:n==="count"?f.n:n==="sum"?f.sum:f.sum/f.n})}));return{categories:c,series:d,skipped:a}}function Yo(s,t,e,i){let n=s.series.length>1;return{type:"bar",data:{labels:s.categories,datasets:s.series.map((o,r)=>({label:o.label||e,data:o.values,backgroundColor:n?i.series[r%i.series.length]:i.accent,borderRadius:3}))},options:{responsive:!0,maintainAspectRatio:!1,scales:{x:{title:{display:!!t,text:t,color:i.muted},ticks:{color:i.muted,autoSkip:!1,maxRotation:60},grid:{display:!1}},y:{beginAtZero:!0,title:{display:!!e,text:e,color:i.muted},ticks:{color:i.muted},grid:{color:i.grid}}},plugins:{legend:{display:n,labels:{color:i.muted,boxWidth:12}}}}}}async function F5(s,t){var e,i,n,o,r,a;try{let L=t.ownerDocument.createElement("canvas");L.width=t.width,L.height=t.height;let l=L.getContext("2d");if(!l||!L.toBlob){new es.Notice("PNG export isn't available here.");return}let c=(e=t.ownerDocument.defaultView)==null?void 0:e.getComputedStyle(t.ownerDocument.body);l.fillStyle=(c==null?void 0:c.getPropertyValue("--background-primary").trim())||"#ffffff",l.fillRect(0,0,L.width,L.height),l.drawImage(t,0,0);let d=await new Promise(p=>L.toBlob(p,"image/png"));if(!d){new es.Notice("PNG export failed.");return}let h=(o=(n=(i=s.file)==null?void 0:i.parent)==null?void 0:n.path)!=null?o:"",u=new Date,f=`${ge(u)} ${String(u.getHours()).padStart(2,"0")}${String(u.getMinutes()).padStart(2,"0")}`,g=`${(a=(r=s.file)==null?void 0:r.basename)!=null?a:"chart"} chart ${f}.png`,m=(0,es.normalizePath)(h?`${h}/${g}`:g);await s.app.vault.createBinary(m,await d.arrayBuffer()),new es.Notice(`Saved ${m}`)}catch(L){new es.Notice(`PNG export failed: ${L instanceof Error?L.message:String(L)}`,6e3)}}function Ll(s,t,e){t.createEl("button",{cls:"csv-cfg-btn csv-chart-export-btn",text:"\u2B07 PNG",title:"Save this chart as a PNG next to the CSV"}).addEventListener("click",()=>{F5(s,e)})}function pn(s){return s.rows.length>=2&&un(s.headers,s.rows).length>=1}async function ll(s,t){var H,$,z;let e=s.getFilteredRows(),i=un(s.headers,s.rows);if(!i.length){t.createEl("p",{text:"No numeric column to chart.",cls:"csv-empty-state"});return}s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Chart over ${e.length} of ${s.rows.length} entries`});let n=s.fileCfg,o=s.getDateCol(),r=(H=s.titleKey())!=null?H:s.headers[0],a=new Set([r,...i,...o?[o]:[]]);s.headers.forEach(V=>{s.isNotesCol(V)&&a.add(V)});let L=O5(s.headers,s.rows,a),l=[...o?[o]:[],...i.filter(V=>V!==o),hn,...L],c=n.chartXCol&&l.includes(n.chartXCol)?n.chartXCol:l[0],d=L.includes(c),h=n.chartAgg==="sum"||n.chartAgg==="avg"?n.chartAgg:"count",u=i,f=n.chartYCol&&u.includes(n.chartYCol)?n.chartYCol:($=u.find(V=>V!==c))!=null?$:u[0],g=n.chartFit==="linear"?"linear":"none",m=(z=n.chartFormula)!=null?z:"",p=t.createDiv({cls:"csv-chart-view"}),b=p.createDiv({cls:"csv-chart-controls"}),C=V=>{s.saveFileCfg({...s.fileCfg,...V}),s.renderViewPreservingScroll()},S=(V,j,X,q)=>{let nt=b.createDiv({cls:"csv-chart-control"});nt.createSpan({cls:"csv-chart-control-label",text:V});let Q=nt.createEl("select",{cls:"csv-chart-select",attr:{"aria-label":V}});return j.forEach(et=>{let J=Q.createEl("option",{text:et,value:et});et===X&&(J.selected=!0)}),Q.addEventListener("change",()=>q(Q.value)),Q};S("X",l,c,V=>C({chartXCol:V})),(!d||h!=="count")&&S(d?`Y (${h})`:"Y",u,f,V=>C({chartYCol:V})),d&&S("Agg",["count","sum","avg"],h,V=>C({chartAgg:V}));let _=new Set([c,f,r]);s.headers.forEach(V=>{s.isNotesCol(V)&&_.add(V)});let y=P5(s.headers,s.rows,_),v="\u2014",x=n.chartHueCol&&y.includes(n.chartHueCol)?n.chartHueCol:null;y.length&&S("Color",[v,...y],x!=null?x:v,V=>C({chartHueCol:V===v?void 0:V}));let k=!d&&c!==hn&&(c===o||s.isDateCol(c)),E=k&&(n.chartBucket==="week"||n.chartBucket==="month")?n.chartBucket:null,M=n.chartAgg==="avg"||n.chartAgg==="count"?n.chartAgg:"sum",D=k&&!E&&!!n.chartSmooth;k&&(S("By",["day","week","month"],E!=null?E:"day",V=>C({chartBucket:V==="day"?void 0:V})),E&&S("Agg",["sum","avg","count"],M,V=>C({chartAgg:V})));let A=i.filter(V=>V!==f&&V!==c),N=!d&&!E&&n.chartSizeCol&&A.includes(n.chartSizeCol)?n.chartSizeCol:null;if(!d&&!E&&A.length&&S("Size",[v,...A],N!=null?N:v,V=>C({chartSizeCol:V===v?void 0:V})),d){let V=Uo(e,c,h==="count"?null:f,x,h),j=p.createDiv({cls:"csv-chart-wrap"}),X=j.createEl("canvas",{cls:"csv-chart-canvas"});if(!V.categories.length){j.remove(),p.createEl("p",{text:`No rows with a "${c}" value to chart.`,cls:"csv-empty-state"});return}V.skipped>0&&p.createDiv({cls:"csv-chart-footer"}).createSpan({cls:"csv-chart-skipped",text:`${V.skipped} row${V.skipped===1?"":"s"} skipped (no numeric value)`});let q=h==="count"?"count":`${h}(${f})`,nt=Yo(V,c,q,Ps(t));s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:Q}=await ts();if(!X.isConnected)return;s.chartInstance=new Q(X,nt),Ll(s,b,X);return}b.createEl("button",{cls:`csv-cfg-btn csv-chart-fit-btn ${g==="linear"?"active":""}`,text:"Best fit",title:"Toggle a least-squares fit line"}).addEventListener("click",()=>C({chartFit:g==="linear"?"none":"linear"})),k&&!E&&b.createEl("button",{cls:`csv-cfg-btn csv-chart-smooth-btn ${D?"active":""}`,text:"Smooth",title:"Toggle a 7-day rolling average (raw values stay as dots)"}).addEventListener("click",()=>C({chartSmooth:D?void 0:!0}));let P=b.createDiv({cls:"csv-chart-control csv-chart-formula-wrap"});P.createSpan({cls:"csv-chart-control-label",text:"y ="});let w=P.createEl("input",{cls:"csv-chart-formula-input",type:"text",value:m,placeholder:"overlay, e.g. 2x + 1",attr:{spellcheck:"false",autocomplete:"off",enterkeyhint:"done"}}),U=()=>{w.value.trim()!==m.trim()&&C({chartFormula:w.value})};w.addEventListener("change",U),w.addEventListener("keydown",V=>{V.key==="Enter"&&(V.preventDefault(),w.blur())});let O=jo(e,c,f,x,N,k,V=>s.parseDate(V),V=>s.getTitle(V)),Z=O.skipped,B=E?O.series.map(V=>({label:V.label,points:Wo(V.points,E,M)})):O.series,G=p.createDiv({cls:"csv-chart-wrap"}),R=G.createEl("canvas",{cls:"csv-chart-canvas"}),W=p.createDiv({cls:"csv-chart-footer"});if(!B.some(V=>V.points.length)){G.remove(),W.remove(),p.createEl("p",{text:`No rows with both "${c}" and "${f}" values to plot.`,cls:"csv-empty-state"});return}let K={series:B,xIsDate:k,xLabel:c===hn?"row":c,yLabel:E?M==="count"?`count / ${E}`:`${M}(${f}) / ${E}`:f,connect:k,fit:g,formula:m,sizeLabel:N!=null?N:"",smoothDays:D?7:0},T=fn(K,Ps(t));T.fitText&&W.createSpan({cls:"csv-chart-fit-text",text:T.fitText}),T.formulaError&&W.createSpan({cls:"csv-chart-formula-error",text:`formula: ${T.formulaError}`}),Z>0&&W.createSpan({cls:"csv-chart-skipped",text:`${Z} row${Z===1?"":"s"} skipped (no numeric value)`}),s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:F}=await ts();R.isConnected&&(s.chartInstance=new F(R,T.config),Ll(s,b,R))}function gn(s){return s.resolveCol(["Type","type","Kind","kind","Item","item"])}function Ko(s){var t;return(t=s.resolveCol(["Project","project","Projects","projects","Area","area"]))!=null?t:Pt(s)}function hl(s){return s.resolveCol(["Due","due","Deadline","deadline","Due Date","Due date","due date"])}function mn(s){return s.resolveCol(["Priority","priority","Prio","prio","Importance","importance"])}var I5=["task","todo","to-do","action",""],V5=["task","todo","to-do","action","note","idea","reference","ref"],ul=["done","complete","completed","finished","closed","resolved","yes","x","\u2713","true","1"],N5={high:0,med:1,medium:1,normal:1,low:2};function Ie(s){if(hl(s)||mn(s))return!0;let t=gn(s);return t?s.rows.some(e=>{var i;return V5.includes(((i=e[t])!=null?i:"").trim().toLowerCase())}):!1}function Go(s,t,e){var i;return e?ul.includes(((i=t[e])!=null?i:"").trim().toLowerCase()):!1}function cl(s){let t=N5[(s!=null?s:"").trim().toLowerCase()];return t===void 0?3:t}function dl(s){return(s!=null?s:"").trim()?0:1}function B5(){return ge()}function $5(s,t){let e=new Map;s.rows.forEach(o=>{var a,L;let r=((a=o[t])!=null?a:"").trim();r&&ul.includes(r.toLowerCase())&&e.set(r,((L=e.get(r))!=null?L:0)+1)});let i="done",n=0;return e.forEach((o,r)=>{o>n&&(i=r,n=o)}),i}function bn(s,t){var E,M;let e=Ko(s),i=gn(s),n=s.getStatusCol(),o=hl(s),r=mn(s),a=(E=s.titleKey())!=null?E:s.headers[0],L=t.createDiv({cls:"csv-library-filters"}),l=new Set;e&&s.rows.forEach(D=>{var A;((A=D[e])!=null?A:"").split(",").map(N=>N.trim()).filter(Boolean).forEach(N=>l.add(N))});let c=L.createEl("select",{cls:"csv-library-filter-select"});c.createEl("option",{text:e?"All projects":"All",value:"all"}),Array.from(l).sort().forEach(D=>c.createEl("option",{text:D,value:D})),c.value=s.taskProjectFilter;let d=new Set;i&&s.rows.forEach(D=>{var N;let A=((N=D[i])!=null?N:"").trim();A&&d.add(A)});let h=null;d.size>0&&(h=L.createEl("select",{cls:"csv-library-filter-select"}),h.createEl("option",{text:"All types",value:"all"}),Array.from(d).sort().forEach(D=>h.createEl("option",{text:D,value:D})),h.value=s.taskTypeFilter);let u=()=>{s.taskProjectFilter=c.value,h&&(s.taskTypeFilter=h.value),s.renderView(!0)};c.addEventListener("change",u),h==null||h.addEventListener("change",u);let f=s.searchQuery.toLowerCase().trim(),g=s.rows.filter(D=>{var A,N;return!(s.taskProjectFilter!=="all"&&e&&!((A=D[e])!=null?A:"").split(",").map(P=>P.trim().toLowerCase()).includes(s.taskProjectFilter.toLowerCase())||s.taskTypeFilter!=="all"&&i&&((N=D[i])!=null?N:"").trim().toLowerCase()!==s.taskTypeFilter.toLowerCase()||f&&!s.headers.some(I=>{var P;return((P=D[I])!=null?P:"").toLowerCase().includes(f)}))});(s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"||f)&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${g.length} of ${s.rows.length} entries`});let m={},p=D=>{var N;return e&&((N=D[e])!=null?N:"").split(",").map(I=>I.trim()).filter(Boolean)[0]||"\u2014"};g.forEach(D=>{var P,w,U;let A=i?((P=D[i])!=null?P:"").trim():"",N=I5.includes(A.toLowerCase())?"Tasks":A,I=p(D);m[N]||(m[N]={}),((U=(w=m[N])[I])!=null?U:w[I]=[]).push(D)});let b=t.createDiv({cls:"csv-tasks"}),C=B5(),S=n?$5(s,n):"done",y=((M=s.fileCfg.cardFields)!=null?M:s.headers).filter(D=>D!==e&&D!==i&&D!==n),v=[];n&&v.push({name:"",cls:"csv-tasks-check-cell"}),y.forEach(D=>{let A="";D===a?A="csv-tasks-name-cell":D===o?A="csv-tasks-due":D===r?A="csv-tasks-priority":s.isNotesCol(D)?A="csv-tasks-generic-cell csv-tasks-notes-cell":A="csv-tasks-generic-cell",v.push({name:D,cls:A})});let x=(D,A)=>{A.sort((N,I)=>{var U,O,Z,B,G,R;let P=Go(s,N,n),w=Go(s,I,n);if(P!==w)return P?1:-1;if(r){let W=cl((U=N[r])!=null?U:"")-cl((O=I[r])!=null?O:"");if(W)return W}if(o){let W=dl((Z=N[o])!=null?Z:"")-dl((B=I[o])!=null?B:"");if(W)return W;let K=((G=N[o])!=null?G:"").localeCompare((R=I[o])!=null?R:"");if(K)return K}return s.getTitle(N).localeCompare(s.getTitle(I))}),A.forEach(N=>{let I=Go(s,N,n),P=D.createEl("tr");if(n){let U=P.createEl("td",{cls:"csv-tasks-check-cell"}).createSpan({cls:`csv-tasks-check ${I?"is-done":""}`,text:I?"\u2713":""});U.setAttr("title",I?"Mark not done":"Mark done"),U.addEventListener("click",O=>{O.stopPropagation(),N[n]=I?"":S,s.scheduleSave(),s.renderView(!0)})}y.forEach(w=>{var U,O,Z;if(w===a)H5(s,P,N,a,I);else if(w===o){let B=P.createEl("td",{cls:"csv-tasks-due csv-tasks-editable"}),G=o?((U=N[o])!=null?U:"").slice(0,10):"";B.setText(G||"\u2014"),G&&!I&&G{var W;G.stopPropagation();let R=Array.from(new Set([...s.getColumnValues(r),"high","medium","low"]));$t(B,(W=N[r])!=null?W:"",R,K=>{N[r]=K,s.scheduleSave(),s.renderView(!0)},s.contentEl)})}else if(s.isNotesCol(w)){let B=((O=N[w])!=null?O:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim(),G=B?B.length>50?B.slice(0,48)+"\u2026":B:"\u2014",R=P.createEl("td",{text:G,cls:"csv-tasks-generic-cell csv-tasks-notes-cell csv-tasks-editable"});Be(s,R,N,w)}else{let B=(Z=N[w])!=null?Z:"",G=B.length>40?B.slice(0,38)+"\u2026":B,R=P.createEl("td",{text:G||"\u2014",cls:"csv-tasks-generic-cell csv-tasks-editable"});Be(s,R,N,w)}}),P.addEventListener("contextmenu",w=>s.openRowContextMenu(N,w))})},k=Object.keys(m).sort((D,A)=>D==="Tasks"?-1:A==="Tasks"?1:D.localeCompare(A));if(k.forEach(D=>{z5(s,b,D==="Tasks"?D:Tt(D),m[D],x,v)}),k.length===0){let D=b.createDiv({cls:"csv-empty-state"});D.createEl("p",{text:f||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"?"No entries match your filters.":"No tasks yet."}),(f||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all")&&D.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.taskProjectFilter="all",s.taskTypeFilter="all",s.searchQuery="",s.renderView()})}}function z5(s,t,e,i,n,o){if(Object.keys(i).length===0)return;t.createDiv({cls:"csv-tasks-section-header",text:e});let r=t.createDiv({cls:"csv-tasks-section"});Object.keys(i).sort().forEach(a=>{let L=i[a],l=r.createEl("details",{cls:"csv-tasks-group"});l.open=!0;let c=l.createEl("summary",{cls:"csv-tasks-group-header"});c.createSpan({cls:"csv-tasks-arrow",text:"\u25B6"}),c.createSpan({text:` ${a} `}),c.createSpan({cls:"csv-tasks-count",text:String(L.length)});let h=l.createDiv({cls:"csv-tasks-table-wrapper"}).createEl("table",{cls:"csv-tasks-table"}),u=120;o.forEach(p=>{p.cls.includes("check-cell")?u+=30:p.cls.includes("priority")?u+=90:p.cls.includes("due")?u+=150:p.cls.includes("notes-cell")?u+=140:p.cls.includes("generic-cell")&&(u+=150)}),h.style.minWidth=`${u}px`;let g=h.createEl("thead").createEl("tr");o.forEach(p=>g.createEl("th",{text:p.name,cls:p.cls}));let m=h.createEl("tbody");n(m,L)})}function H5(s,t,e,i,n){var d;let o=t.createEl("td",{cls:"csv-tasks-name-cell"}),r=(d=s.isHighlighted)!=null&&d.call(s,e)?"csv-title-highlight":"",a=o.createSpan({cls:`csv-tasks-link ${n?"csv-tasks-done":""} ${r}`,text:e[i]||"Untitled"}),L=s.getNotesCol();a.addEventListener("click",()=>{L?s.openNoteExpander(e,L):s.openOrCreateNotes(e)});let l=s.notesFileExists(e),c=o.createEl("button",{cls:`csv-tasks-page-icon ${l?"exists":""}`,text:l?"\u{1F4C4}":"+"});c.setAttr("title",l?"Open page":"Create page"),c.addEventListener("click",h=>{h.stopPropagation(),s.openOrCreateNotes(e)})}var vn="\u2014";function fl(s){var t;return s.fileCfg.budgetPriceCol!==void 0?s.fileCfg.budgetPriceCol===""?null:(t=s.headers.find(e=>e.toLowerCase()===s.fileCfg.budgetPriceCol.toLowerCase()))!=null?t:null:s.resolveCol(pi)}function yn(s){return fl(s)!==null}function Os(s){return s.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}function pl(s,t){var v,x;let e=fl(s);if(!e){t.createEl("p",{text:"No price/amount column found. Assign one via \u2699 config \u2192 column functions.",cls:"csv-empty-state"});return}let i=Pt(s),n=i===e?null:i,o=(v=s.titleKey())!=null?v:s.headers[0],r=s.getFilteredRows(),a=k=>{var E;return n&&((E=k[n])!=null?E:"").trim()||vn},L=new Map,l=0;r.forEach(k=>{var M,D,A;let E=(D=Fe((M=k[e])!=null?M:""))!=null?D:0;l+=E,L.set(a(k),((A=L.get(a(k)))!=null?A:0)+E)});let c=t.createDiv({cls:"csv-budget"}),d=s.fileCfg.budgetLimit,h=d!==void 0&&d>0,u=h&&l>d,f=c.createDiv({cls:"csv-budget-summary"}),g=f.createDiv({cls:"csv-budget-total-row"});g.createSpan({cls:"csv-budget-total-label",text:"Total"}),g.createSpan({cls:`csv-budget-total-value ${h?u?"is-over":"is-under":""}`,text:Os(l)}),h&&g.createSpan({cls:"csv-budget-total-limit",text:` / ${Os(d)}`});let m=f.createDiv({cls:"csv-budget-limit-row"});m.createSpan({cls:"csv-budget-limit-label",text:"Limit"});let p=k=>{k!==s.fileCfg.budgetLimit&&(s.saveFileCfg({...s.fileCfg,budgetLimit:k}),s.renderViewPreservingScroll())};if(m.createEl("button",{cls:"csv-budget-limit-btn",text:h?Os(d):"No limit set"}).addEventListener("click",()=>{new Ne(s.app,"Set spending limit",d!==void 0?String(d):"","e.g. 2000",k=>{let E=parseFloat(k.trim());Number.isFinite(E)&&E>=0&&p(E)},"Set","number").open()}),h&&m.createEl("button",{cls:"csv-budget-limit-clear",text:"\xD7",attr:{"aria-label":"Clear limit",title:"Clear limit"}}).addEventListener("click",()=>p(void 0)),h){let E=f.createDiv({cls:"csv-budget-bar"}).createDiv({cls:`csv-budget-bar-fill ${u?"is-over":"is-under"}`});E.style.width=`${Math.min(100,Math.round(l/d*100))}%`}if(n&&L.size>1){let k=c.createDiv({cls:"csv-budget-cats"});Array.from(L.entries()).sort((E,M)=>M[1]-E[1]).forEach(([E,M])=>{let D=k.createDiv({cls:"csv-budget-cat-chip"});D.createSpan({cls:"csv-budget-cat-name",text:E}),D.createSpan({cls:"csv-budget-cat-sum",text:Os(M)})})}if(!r.length){c.createDiv({cls:"csv-empty-state",text:"No entries yet."});return}let S=((x=s.fileCfg.cardFields)!=null?x:s.headers).filter(k=>k!==n&&k!==e&&k!==o),_=c.createDiv({cls:"csv-tasks"});Array.from(L.keys()).sort((k,E)=>k===vn?1:E===vn?-1:k.localeCompare(E)).forEach(k=>{var U;let E=r.filter(O=>a(O)===k);if(!E.length)return;let D=_.createDiv({cls:"csv-tasks-section"}).createEl("details",{cls:"csv-tasks-group"});D.open=!0;let A=D.createEl("summary",{cls:"csv-tasks-group-header"});A.createSpan({cls:"csv-tasks-arrow",text:"\u25B6"}),A.createSpan({text:` ${k} `}),A.createSpan({cls:"csv-tasks-count",text:String(E.length)}),A.createSpan({cls:"csv-budget-cat-subtotal",text:Os((U=L.get(k))!=null?U:0)});let I=D.createDiv({cls:"csv-tasks-table-wrapper"}).createEl("table",{cls:"csv-tasks-table"});I.style.minWidth=`${180+S.length*150+110}px`;let P=I.createEl("thead").createEl("tr");P.createEl("th",{text:"Item",cls:"csv-tasks-name-cell"}),S.forEach(O=>P.createEl("th",{text:O,cls:"csv-tasks-generic-cell"})),P.createEl("th",{text:"Price",cls:"csv-budget-price-cell"});let w=I.createEl("tbody");E.forEach(O=>{var G,R;let Z=w.createEl("tr");Z5(s,Z,O,o),S.forEach(W=>{var H;let K=(H=O[W])!=null?H:"",T=K.length>40?K.slice(0,38)+"\u2026":K,F=Z.createEl("td",{text:T||"\u2014",cls:"csv-tasks-generic-cell csv-tasks-editable"});Be(s,F,O,W)}),Z.createEl("td",{cls:"csv-budget-price-cell csv-tasks-editable",text:Os((R=Fe((G=O[e])!=null?G:""))!=null?R:0)}).addEventListener("click",()=>{var W;new Ne(s.app,"Edit price",(W=O[e])!=null?W:"","0.00",K=>{O[e]=K.trim(),s.scheduleSave(),s.renderViewPreservingScroll()},"Save","number").open()}),Z.addEventListener("contextmenu",W=>s.openRowContextMenu(O,W))})})}function Z5(s,t,e,i){let n=t.createEl("td",{cls:"csv-tasks-name-cell"}),o=n.createSpan({cls:"csv-tasks-link",text:e[i]||"Untitled"}),r=s.getNotesCol();o.addEventListener("click",()=>{r?s.openNoteExpander(e,r):s.openOrCreateNotes(e)});let a=s.notesFileExists(e),L=n.createEl("button",{cls:`csv-tasks-page-icon ${a?"exists":""}`,text:a?"\u{1F4C4}":"+"});L.setAttr("title",a?"Open page":"Create page"),L.addEventListener("click",l=>{l.stopPropagation(),s.openOrCreateNotes(e)})}function xn(s){let t=[];return s.isTravelFile()&&t.push({id:"travel",label:"Travel"}),s.hasDateColumn()&&t.push({id:"dashboard",label:"Dashboard"}),Ie(s)&&t.push({id:"tasks",label:"Tasks"}),yn(s)&&t.push({id:"budget",label:"Budget"}),Pt(s)&&(t.push({id:"library",label:"Cards"}),t.push({id:"kanban-genre",label:"Kanban"})),t.push({id:"table",label:"Table"}),s.rows.length>0&&t.push({id:"focus",label:"Focus"}),Si(s)&&t.push({id:"stats",label:"Stats"}),pn(s)&&t.push({id:"chart",label:"Chart"}),t}function gl(s,t){var h,u,f,g;t.removeClass("csv-toolbar--search-expanded");let e=t.createDiv({cls:"csv-toolbar"});e.createDiv({cls:"csv-toolbar-title",text:(u=(h=s.file)==null?void 0:h.basename)!=null?u:""});let i=e.createDiv({cls:"csv-toolbar-controls"});i.createDiv({cls:"csv-row-count",text:`${s.rows.length} entries`});let n=i.createDiv({cls:"csv-mode-group"}),o=xn(s),r=n.createEl("select",{cls:"csv-mode-select",attr:{"aria-label":"View mode"}});if(o.forEach(({id:m,label:p})=>{let b=r.createEl("option",{text:p,value:m});s.mode===m&&(b.selected=!0)}),r.addEventListener("change",()=>{s.mode=r.value,s.renderView()}),s.mode!=="dashboard"){let m=i.createEl("button",{cls:"csv-cfg-btn csv-search-toggle",text:"\u{1F50D}",title:"Search"}),p=i.createDiv({cls:"csv-search-wrap"}),b=p.createDiv({cls:"csv-search-input-wrap"}),C=b.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search...",value:s.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),S=b.createEl("button",{cls:"csv-search-clear",text:"\xD7",title:"Clear search"});S.toggleClass("is-hidden",!s.searchQuery),p.createEl("button",{cls:"csv-search-done",text:"Done",title:"Dismiss keyboard"}).addEventListener("click",x=>{if(x.preventDefault(),!C.value){e.removeClass("csv-toolbar--search-expanded"),t.removeClass("csv-toolbar--search-expanded"),m.removeClass("has-query"),s.searchQuery="",s.renderView(!0);return}C.blur()});let y=null;C.addEventListener("input",x=>{s.searchQuery=x.target.value,S.toggleClass("is-hidden",!s.searchQuery),m.toggleClass("has-query",!!s.searchQuery),y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>{y=null,s.renderView(!0)},120)}),C.addEventListener("keydown",x=>{x.key==="Enter"&&(x.preventDefault(),C.blur())}),S.addEventListener("click",()=>{s.searchQuery="",C.value="",S.addClass("is-hidden"),m.removeClass("has-query"),C.focus({preventScroll:!0}),s.renderView(!0)}),s.searchQuery&&m.addClass("has-query");let v=typeof window!="undefined"&&((f=window.matchMedia)==null?void 0:f.call(window,"(pointer: coarse)").matches);m.addEventListener("click",()=>{if(v){let x=s.getNotesCol();new bi(s.app,s.searchQuery,k=>{s.searchQuery=k,s.renderView()},()=>({matched:s.getFilteredRows().length,total:s.rows.length}),()=>s.getFilteredRows().map(k=>({title:s.getTitle(k),subtitle:s.getSubtitle(k)||void 0,row:k})),k=>{x?s.openNoteExpander(k,x):s.openOrCreateNotes(k)}).open();return}e.addClass("csv-toolbar--search-expanded"),t.addClass("csv-toolbar--search-expanded"),C.focus({preventScroll:!0})})}if(s.mode==="table"&&s.hasDateColumn()){let m=(g=s.fileCfg.sortNewestFirst)!=null?g:!0;i.createEl("button",{cls:`csv-cfg-btn ${m?"active":""}`,text:m?"\u2193 Newest":"\u2191 Oldest",title:"Toggle sort order"}).addEventListener("click",()=>{var C;let b=s.fileCfg;b.sortNewestFirst=!((C=b.sortNewestFirst)==null||C),s.saveFileCfg(b),s.tableSortCol=null,s.renderViewPreservingScroll()})}let a=()=>{var p,b;let m={title:s.resolveCol(fe),category:s.resolveCol(os),status:s.resolveCol(rs),notes:s.resolveCol(pe),image:s.resolveCol(ns),anki:In(s),price:s.resolveCol(pi)};new vi(s.app,s.headers,(b=(p=s.file)==null?void 0:p.path)!=null?b:"",s.fileCfg,s.autoDetectBooleanColumns(),s.autoDetectCategoricalColumns(),m,xn(s),C=>{s.saveFileCfg(C),C.defaultMode&&(s.mode=C.defaultMode),s.renderView()},()=>s.headers,()=>s.fileCfg,C=>s.addColumn(C),C=>s.removeColumn(C),C=>s.cleanupBooleanColumn(C)).open()},L=()=>{s.backupToArchive()},l=()=>{wr(s)};i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u2699 Config",title:"Configure this file's columns and views"}).addEventListener("click",a),i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F4BE} Backup",title:"Copy this file to archive/ with today's date"}).addEventListener("click",L),i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F3B4} Anki",title:"Sync rows to Anki (needs Anki desktop + AnkiConnect)"}).addEventListener("click",l),i.createEl("button",{cls:"csv-add-btn",text:"+ add"}).addEventListener("click",()=>s.openAddModal()),i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-overflow",text:"\u22EF",title:"More actions"}).addEventListener("click",m=>{let p=new Cn.Menu;p.addItem(b=>b.setTitle("Config").setIcon("settings").onClick(a)),p.addItem(b=>b.setTitle("Backup").setIcon("save").onClick(L)),p.addItem(b=>b.setTitle("Sync to Anki").setIcon("layers").onClick(l)),p.addSeparator(),p.addItem(b=>b.setTitle("Built 2026-07-18 13:08").setIcon("info").setDisabled(!0)),p.showAtMouseEvent(m)}),i.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary csv-info-btn",text:"\u24D8",title:"Built 2026-07-18 13:08 \u2014 click to confirm"}).addEventListener("click",()=>new Cn.Notice("datadeck \u2014 built 2026-07-18 13:08",4e3))}var ml=require("obsidian");function W5(s){return s instanceof ml.TFile?s:s&&typeof s=="object"&&"basename"in s?s:null}var j5=["Author","author","By","by","Source","source","Speaker","speaker","Artist","artist","Director","director"];async function bl(s,t,e,i){var b,C,S;let n=t.split(` +`).map(_=>_.trim()).filter(Boolean),o=_=>{var y,v;return(v=(y=n.find(x=>x.startsWith(_+":")))==null?void 0:y.slice(_.length+1).trim())!=null?v:""},r=o("file");if(!r){e.createEl("p",{text:"Error: No file specified. Use: file: yourfile.csv",cls:"csv-add-error"});return}let a=s.vault.getAbstractFileByPath(i.sourcePath),L=(C=(b=a==null?void 0:a.parent)==null?void 0:b.path)!=null?C:"",l=Qt(r,L),c=W5(s.vault.getAbstractFileByPath(l));if(!c){e.createEl("p",{text:`Error: File not found: ${l}`,cls:"csv-add-error"});return}let d=[],h=[];try{let _=kt(await s.vault.read(c));d=_.headers,h=_.rows}catch(_){e.createEl("p",{text:`Error reading file: ${_ instanceof Error?_.message:String(_)}`,cls:"csv-add-error"});return}if(!h.length){e.createEl("p",{text:"No entries in file.",cls:"csv-add-error"});return}let u=o("field"),f=(S=d.find(_=>_.toLowerCase()===u.toLowerCase()))!=null?S:d[0],g=j5.map(_=>d.find(y=>y===_)).find(Boolean),m=e.createDiv({cls:"csv-random-card"}),p=()=>{var M;m.empty();let _=h.filter(D=>{var A;return((A=D[f])!=null?A:"").trim()}),y=_.length?_:h,v=y[Math.floor(Math.random()*y.length)];m.createDiv({cls:"csv-random-text",text:v[f]||"\u2014"});let x=g?((M=v[g])!=null?M:"").trim():"";x&&m.createDiv({cls:"csv-random-sub",text:`\u2014 ${x}`});let k=m.createDiv({cls:"csv-random-foot"});k.createSpan({cls:"csv-random-src",text:c.basename}),k.createEl("button",{cls:"csv-random-btn",text:"\u21BB",title:"Another one"}).addEventListener("click",p)};p()}async function vl(s,t){var R,W,K;let e=s.getDateCol();if(!e){t.createEl("p",{text:"No date column detected.",cls:"csv-empty-state"});return}let i=s.getBooleanColumns(),n=s.getNotesCol(),o=s.formatDate(new Date),r=[...s.rows].sort((T,F)=>{var H,$;return((H=T[e])!=null?H:"").localeCompare(($=F[e])!=null?$:"")});s.selectedDate||(s.selectedDate=o);let a=r.find(T=>T[e]===s.selectedDate),L=s.selectedDate===o;t.addClass("csv-dashboard");let l=[...new Set([...r.map(T=>T[e]),o])].filter(Boolean).sort(),c=t.createDiv({cls:"csv-dash-nav"});c.createEl("button",{cls:"csv-dash-nav-btn csv-dash-back-btn",text:"\u25C0"}).addEventListener("click",()=>{let T=l.indexOf(s.selectedDate);if(T>0)s.selectedDate=l[T-1],s.renderView();else if(T===-1&&l.length>0){let F=l.filter(H=>H0&&(s.selectedDate=F[F.length-1],s.renderView())}});let h=c.createDiv({cls:"csv-dash-date"});L&&h.createSpan({cls:"csv-dash-today-dot"});let u=h.createEl("select",{cls:"csv-dash-date-select"});if(l.forEach(T=>{let F=u.createEl("option",{text:T,value:T});T===s.selectedDate&&(F.selected=!0)}),u.addEventListener("change",()=>{s.selectedDate=u.value,s.renderView()}),c.createEl("button",{cls:"csv-dash-nav-btn",text:"\u25B6"}).addEventListener("click",()=>{let T=l.indexOf(s.selectedDate);if(T>=0&&TH>s.selectedDate);F.length>0&&(s.selectedDate=F[0],s.renderView())}}),L||c.createEl("button",{cls:"csv-dash-today-btn",text:"Today"}).addEventListener("click",()=>{s.selectedDate=o,s.renderView()}),!a){let T=t.createDiv({cls:"csv-dash-add-section"});T.createEl("p",{text:`No entry for ${s.selectedDate}`}),T.createEl("button",{cls:"csv-dash-add-btn",text:`+ Add entry for ${s.selectedDate}`}).addEventListener("click",()=>{let H={};s.headers.forEach($=>H[$]=""),H[e]=s.selectedDate,s.rows.push(H),s.scheduleSave(),s.renderView()})}if(a){let T=t.createDiv({cls:"csv-dash-habits"});T.createEl("h3",{text:s.selectedDate===o?"Today":s.selectedDate,cls:"csv-dash-section-title"});let F=T.createDiv({cls:"csv-dash-habits-grid"});i.forEach($=>{let z=s.isTruthy(a[$]),V=F.createDiv({cls:`csv-dash-habit ${z?"checked":""}`}),j=V.createEl("button",{cls:"csv-dash-habit-check",text:z?"\u25CF":"\u25CB"});V.createSpan({cls:"csv-dash-habit-label",text:$}),j.addEventListener("click",()=>{a[$]=z?"0":"1",s.scheduleSave(),s.renderViewPreservingScroll()})});let H=i.filter($=>s.isTruthy(a[$])).length;if(T.createDiv({cls:"csv-dash-habits-count",text:`${H} of ${i.length} complete`}),n&&((R=a[n])!=null&&R.trim())){let $=T.createDiv({cls:"csv-dash-notes-preview"});$.createEl("strong",{text:"Notes: "}),$.createSpan({text:a[n].slice(0,200)+(a[n].length>200?"\u2026":"")})}}let g=t.createDiv({cls:"csv-dash-chart-section"});g.createEl("h3",{text:"Progress",cls:"csv-dash-section-title"});let p=g.createDiv({cls:"csv-dash-chart-wrap"}).createEl("canvas",{cls:"csv-dash-chart"}),b=r.map(T=>{var H;return((H=T[e])!=null?H:"").slice(5)}),C=r.map(T=>i.filter(F=>s.isTruthy(T[F])).length);s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:S}=await ts();if(!p.isConnected)return;s.chartInstance=new S(p,{type:"line",data:{labels:b,datasets:[{label:"Habits done",data:C,borderColor:"#378ADD",backgroundColor:"rgba(55,138,221,0.08)",borderWidth:1.5,pointRadius:3,tension:.3,fill:!0}]},options:{responsive:!0,maintainAspectRatio:!1,scales:{y:{min:0,max:i.length||8,ticks:{stepSize:1}}},plugins:{tooltip:{enabled:!0}}}});let _=t.createDiv({cls:"csv-dash-stats-section"});_.createEl("h3",{text:"Stats",cls:"csv-dash-section-title"});let y=r.length,v=r.reduce((T,F)=>T+i.filter(H=>s.isTruthy(F[H])).length,0),x=y>0?(v/y).toFixed(1):"0",k=r.filter(T=>i.every(F=>s.isTruthy(T[F]))).length,E=0,M=0,D=null;for(let T of r){let F=i.filter(z=>s.isTruthy(T[z])).length,H=s.parseDate((W=T[e])!=null?W:""),$=!0;D&&H&&Math.round((H.getTime()-D.getTime())/864e5)!==1&&($=!1),F>=1&&($||D===null)?(M++,M>E&&(E=M)):F>=1?(M=1,M>E&&(E=M)):M=0,D=H}let A=0,N=new Date;N.setHours(0,0,0,0);let I=N;for(let T=r.length-1;T>=0;T--){let F=s.parseDate((K=r[T][e])!=null?K:"");if(!F)break;let H=Math.round((I.getTime()-F.getTime())/(1e3*60*60*24));if(A===0&&H>1||A>0&&H!==1)break;if(i.filter(z=>s.isTruthy(r[T][z])).length>=1)A++,I=F;else break}let P=_.createDiv({cls:"csv-dash-stats-bar"}),w=(T,F)=>{P.createEl("strong",{text:T}),P.appendText(` ${F}`)};w(String(y),"days logged"),P.appendText(" \xB7 "),w(String(x),"avg/day"),P.appendText(" \xB7 "),w(String(k),"perfect days"),P.appendText(" \xB7 current streak "),P.createEl("strong",{text:`${A}d`}),P.appendText(" \xB7 best streak "),P.createEl("strong",{text:`${E}d`});let O=t.createDiv({cls:"csv-dash-cards-section"}).createDiv({cls:"csv-dash-cards-grid"}),Z=new Date().getFullYear(),B={language:"\u25CB",read:"\u2261",gym:"\u229E",vitamins:"\u2299",cardio:"\u2191",meditate:"\u25CE",challenge:"\u273F",journal:"\u270E",exercise:"\u229E",water:"\u{1F4A7}",sleep:"\u{1F319}",study:"\u{1F4DA}"};i.map(T=>{let F=r.filter(j=>s.isTruthy(j[T])),H=F.length>0?F[F.length-1][e]:null,$=new Set;F.forEach(j=>{var q;let X=s.parseDate((q=j[e])!=null?q:"");X&&$.add(X.getFullYear())});let z=r.filter(j=>{var q;let X=s.parseDate((q=j[e])!=null?q:"");return X&&X.getFullYear()===Z}),V=z.filter(j=>s.isTruthy(j[T])).length;return{habit:T,doneCount:F.length,doneThisYear:V,totalThisYear:z.length,lastDone:H,years:Array.from($).sort()}}).sort((T,F)=>!T.lastDone&&!F.lastDone?0:T.lastDone?F.lastDone?F.lastDone.localeCompare(T.lastDone):-1:1).forEach(({habit:T,doneCount:F,doneThisYear:H,totalThisYear:$,lastDone:z,years:V})=>{var J;let j=O.createDiv({cls:"csv-dash-habit-card"}),X=(J=B[T.toLowerCase()])!=null?J:"\u25CB",q=j.createDiv({cls:"csv-dash-habit-card-header"});if(q.createSpan({cls:"csv-dash-habit-icon",text:X}),q.createSpan({cls:"csv-dash-habit-card-name",text:Tt(T)}),V.length>0&&j.createDiv({cls:"csv-dash-habit-years"}).setText(V.join(" \xB7 ")),j.createDiv({cls:"csv-dash-habit-card-thisyear",text:`${H} of ${$} complete this year`}),j.createDiv({cls:"csv-dash-habit-card-alltime",text:`${F} of ${y} all time`}),z){let ot=s.parseDate(z),lt=ot?ot.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):z;j.createDiv({cls:"csv-dash-habit-card-last",text:`Last logged: ${lt}`})}else j.createDiv({cls:"csv-dash-habit-card-last",text:"Never logged"});let nt=y>0?F/y*100:0,et=j.createDiv({cls:"csv-dash-habit-progress"}).createDiv({cls:"csv-dash-habit-progress-bar"});et.style.width=`${nt}%`,j.addEventListener("click",()=>{s.selectedHabit=s.selectedHabit===T?null:T,s.renderViewPreservingScroll()}),s.selectedHabit===T&&j.addClass("selected")}),s.selectedHabit&&i.includes(s.selectedHabit)&&U5(s,t,r,e,s.selectedHabit)}function U5(s,t,e,i,n){var E,M,D;let o=t.createDiv({cls:"csv-dash-timeline-section"}),r=o.createDiv({cls:"csv-dash-timeline-header"});r.createEl("h3",{text:`${Tt(n)} Timeline`,cls:"csv-dash-section-title"});let a=r.createEl("select",{cls:"csv-dash-year-select"}),L=new Set;e.forEach(A=>{var I;let N=s.parseDate((I=A[i])!=null?I:"");N&&L.add(N.getFullYear())}),L.add(new Date().getFullYear()),Array.from(L).sort().reverse().forEach(A=>{let N=a.createEl("option",{text:String(A),value:String(A)});A===s.timelineYear&&(N.selected=!0)}),a.addEventListener("change",()=>{s.timelineYear=parseInt(a.value),s.renderViewPreservingScroll()}),r.createEl("button",{cls:"csv-dash-timeline-close",text:"\u2715"}).addEventListener("click",()=>{s.selectedHabit=null,s.renderViewPreservingScroll()});let c=new Map;e.forEach(A=>{var N;c.set((N=A[i])!=null?N:"",s.isTruthy(A[n]))});let d=o.createDiv({cls:"csv-dash-timeline-grid-wrap"}),h=d.createDiv({cls:"csv-dash-timeline-months"});["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].forEach(A=>h.createSpan({cls:"csv-dash-timeline-month-label",text:A}));let f=d.createDiv({cls:"csv-dash-timeline-calendar"}),g=f.createDiv({cls:"csv-dash-timeline-day-labels"});for(let A=1;A<=31;A++)g.createDiv({cls:"csv-dash-timeline-day-label",text:A%5===0||A===1?String(A):""});for(let A=0;A<12;A++){let N=f.createDiv({cls:"csv-dash-timeline-month-col"}),I=new Date(s.timelineYear,A+1,0).getDate();for(let P=1;P<=31;P++){if(P>I){N.createDiv({cls:"csv-dash-timeline-cell empty"});continue}let w=`${s.timelineYear}-${String(A+1).padStart(2,"0")}-${String(P).padStart(2,"0")}`,U=(E=c.get(w))!=null?E:!1,O=c.has(w),Z=new Date(s.timelineYear,A,P)>new Date,B=N.createDiv({cls:`csv-dash-timeline-cell ${Z?"future":""} ${U?"done":""} ${O&&!U?"missed":""} ${!O&&!Z?"no-entry":""}`});B.title=`${w}: ${Z?"Future":U?"\u2713 Done":O?"\u2717 Missed":"No entry"}`}}let m=e.filter(A=>{var I;let N=s.parseDate((I=A[i])!=null?I:"");return N&&N.getFullYear()===s.timelineYear}),p=m.filter(A=>s.isTruthy(A[n])).length,b=m.length,C=0,S=0,_=0,y=null;for(let A of e){let N=s.isTruthy(A[n]),I=s.parseDate((M=A[i])!=null?M:""),P=!0;y&&I&&Math.round((I.getTime()-y.getTime())/864e5)!==1&&(P=!1),N&&(P||y===null)?(_++,_>S&&(S=_)):N?_=1:_=0,y=I}let v=new Date;v.setHours(0,0,0,0);let x=v;for(let A=e.length-1;A>=0;A--){let N=s.parseDate((D=e[A][i])!=null?D:"");if(!N)break;let I=Math.round((x.getTime()-N.getTime())/(1e3*60*60*24));if(C===0&&I>1||C>0&&I!==1)break;if(s.isTruthy(e[A][n]))C++,x=N;else break}let k=o.createDiv({cls:"csv-dash-timeline-stats"});k.createEl("strong",{text:String(p)}),k.appendText(` of ${b} in ${s.timelineYear} \xB7 current streak `),k.createEl("strong",{text:`${C}d`}),k.appendText(" \xB7 best streak "),k.createEl("strong",{text:`${S}d`})}function yl(s,t){var b,C,S;let e=s.getFilteredRows();if(s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${e.length} of ${s.rows.length} entries`}),!e.length){let _=t.createDiv({cls:"csv-empty-state"});_.createEl("p",{text:s.searchQuery?"No matching entries found.":"No entries yet."}),s.searchQuery&&_.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear search"}).addEventListener("click",()=>{s.searchQuery="",s.renderView()});return}s.focusIndex>=e.length&&(s.focusIndex=e.length-1),s.focusIndex<0&&(s.focusIndex=0);let i=e[s.focusIndex],n=(b=s.titleKey())!=null?b:s.headers[0],o=s.getNotesCol(),r=s.authorKey(),a=t.createDiv({cls:"csv-focus-wrap",attr:{tabindex:"0"}}),L=_=>{s.focusIndex=(_%e.length+e.length)%e.length,s.focusNavPending=!0,s.renderView(!0)},l=a.createDiv({cls:"csv-focus-card"});l.createDiv({cls:"csv-focus-position",text:`${s.focusIndex+1} / ${e.length}`});let c=l.createDiv({cls:`csv-focus-title ${(C=s.isHighlighted)!=null&&C.call(s,i)?"csv-title-highlight":""}`,text:s.getTitle(i)});o&&(c.addClass("is-clickable"),c.title="Open entry",c.addEventListener("click",()=>s.openNoteExpander(i,o)));let d=s.getSubtitle(i);if(d&&l.createDiv({cls:"csv-focus-sub",text:d}),o&&o!==n&&((S=i[o])!=null&&S.trim())){let _=l.createDiv({cls:"csv-focus-notes"});s.renderMarkdownInto(_,i[o])}let h=new Set([n,o,r].filter(Boolean)),u=s.headers.filter(_=>{var y;return!h.has(_)&&((y=i[_])!=null?y:"").trim()});if(u.length){let _=l.createDiv({cls:"csv-focus-meta"});u.forEach(y=>{let v=_.createDiv({cls:"csv-kanban-chip"});if(v.createSpan({cls:"csv-chip-label",text:y+": "}),s.isSelectCol(y)){let x=v.createSpan({cls:"csv-chip-value csv-chip-select",text:i[y]});x.addEventListener("click",k=>{k.stopPropagation(),$t(x,i[y],s.getColumnValues(y),E=>{i[y]=E,x.setText(E||"\u2014"),s.scheduleSave()},s.contentEl,{multi:vt(y)})})}else v.createSpan({cls:"csv-chip-value",text:i[y]})})}l.addEventListener("contextmenu",_=>s.openRowContextMenu(i,_));let f=a.createDiv({cls:"csv-focus-nav"}),g=f.createEl("button",{cls:"csv-focus-nav-btn",text:"\u2039",title:"Previous (\u2190)"}),m=f.createEl("button",{cls:"csv-focus-nav-btn csv-focus-nav-rand",text:"\u{1F500}",title:"Random entry"}),p=f.createEl("button",{cls:"csv-focus-nav-btn",text:"\u203A",title:"Next (\u2192)"});g.addEventListener("click",()=>L(s.focusIndex-1)),p.addEventListener("click",()=>L(s.focusIndex+1)),m.addEventListener("click",()=>{if(e.length<2)return;let _=s.focusIndex;for(;_===s.focusIndex;)_=Math.floor(Math.random()*e.length);L(_)}),a.addEventListener("keydown",_=>{_.key==="ArrowLeft"?(_.preventDefault(),L(s.focusIndex-1)):_.key==="ArrowRight"&&(_.preventDefault(),L(s.focusIndex+1))}),(s.focusNavPending||document.activeElement===document.body)&&(s.focusNavPending=!1,a.focus({preventScroll:!0}))}var Mt=require("obsidian"),Cl=Ns(is());var Y5=[{id:"table",label:"Table"},{id:"library",label:"Cards"},{id:"kanban-genre",label:"Kanban"}];function xl(s){return s instanceof Mt.TFile?s:s&&typeof s=="object"&&"basename"in s?s:null}function G5(s){let t=s.split(` +`).map(r=>r.trim()).filter(Boolean),e=r=>{var a,L;return(L=(a=t.find(l=>l.toLowerCase().startsWith(r+":")))==null?void 0:a.slice(r.length+1).trim())!=null?L:""},i=e("mode").toLowerCase(),n=i==="kanban"||i==="kanban-genre"?"kanban-genre":i==="cards"||i==="card"||i==="library"?"library":"table",o=parseInt(e("height"),10);return{file:e("file"),mode:n,height:Number.isFinite(o)&&o>0?o:null,collapse:e("collapse").split(",").map(r=>r.trim()).filter(Boolean)}}var Xo=class extends Mt.MarkdownRenderChild{constructor(e,i,n,o,r){super(e);this.file=null;this.headers=[];this.rows=[];this.searchQuery="";this.tableSortCol=null;this.tableSortDir="asc";this.libraryStatusFilter="all";this.libraryGenreFilter="all";this.collapsedGroups=new Set;this.saveTimer=null;this.lastWritten=null;this.contentArea=null;this.app=i,this.settings=n,this.persistSettings=o,this.opts=r,this.mode=r.mode,this.collapsedGroups=new Set(r.collapse.map(a=>a.toLowerCase()))}get renderComponent(){return this}get contentEl(){return this.containerEl}get asView(){return this}onload(){if(this.containerEl.addClass("csv-inline-view"),!this.opts.file){this.renderError("No file specified. Use: file: yourfile.csv");return}(async()=>await this.reload()&&(this.renderView(),this.registerEvent(this.app.vault.on("modify",async e=>{if(!this.file||e.path!==this.file.path)return;let i=await this.app.vault.read(this.file);if(i===this.lastWritten)return;this.lastWritten=i;let n=kt(i);this.headers=n.headers,this.rows=n.rows,this.renderView()})),this.registerEvent(this.app.vault.on("rename",(e,i)=>{this.file&&i===this.file.path&&(this.file=xl(e))}))))()}onunload(){this.saveTimer&&window.clearTimeout(this.saveTimer)}async reload(){let e=xl(this.app.vault.getAbstractFileByPath(this.opts.file));if(!e)return this.renderError(`File not found: ${this.opts.file}`),!1;this.file=e;try{let i=await this.app.vault.read(e),n=kt(i);this.headers=n.headers,this.rows=n.rows,this.lastWritten=i}catch(i){return this.renderError(`Error reading file: ${i instanceof Error?i.message:String(i)}`),!1}return!0}renderError(e){this.containerEl.empty(),this.containerEl.createEl("p",{text:`csv-view: ${e}`,cls:"csv-add-error"})}scheduleSave(){this.saveTimer&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>void this.doSave(),600)}async doSave(){if(this.file)try{let e=Cl.default.unparse(this.rows,{columns:this.headers});try{let i=await this.app.vault.read(this.file);this.lastWritten!==null&&i!==this.lastWritten&&i!==e&&await ls(this.app,this.file,i)}catch(i){}this.lastWritten=e,await this.app.vault.modify(this.file,e)}catch(e){new Mt.Notice(`Couldn't save ${this.file.name}: ${e instanceof Error?e.message:String(e)}`,8e3)}}get fileCfg(){var e;return this.file?(e=this.settings.fileConfigs[this.file.path])!=null?e:{}:{}}saveFileCfg(e){this.file&&(this.settings.fileConfigs[this.file.path]=e,this.persistSettings())}isHighlighted(e){var i;return((i=this.fileCfg.highlightedTitles)!=null?i:[]).includes(this.getTitle(e))}toggleHighlight(e){let i=this.getTitle(e),n=this.fileCfg,o=n.highlightedTitles?[...n.highlightedTitles]:[],r=o.indexOf(i);r>=0?o.splice(r,1):o.push(i),n.highlightedTitles=o,this.saveFileCfg(n)}resolveCol(e){for(let i of e){let n=this.headers.find(o=>o.toLowerCase()===i.toLowerCase());if(n)return n}return null}getNotesCol(){return this.fileCfg.notesColumn!==void 0?this.fileCfg.notesColumn===""?null:this.fileCfg.notesColumn:this.resolveCol(pe)}isNotesCol(e){let i=this.getNotesCol();return i?e===i:this.settings.notesColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var n;let i=(n=this.titleKey())!=null?n:this.headers[0];return e===i||this.getDateCol()===e||vt(e)?!1:this.fileCfg.categoricalColumns?this.fileCfg.categoricalColumns.includes(e):this.isSelectCol(e)||Xt(this.getColumnValues(e).length)}getStatusCol(){var e;return this.fileCfg.statusColumn!==void 0?this.fileCfg.statusColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(rs)}getCategoryCol(){var e;return this.fileCfg.categoryColumn!==void 0?this.fileCfg.categoryColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(os)}titleKey(){var e,i;return this.fileCfg.titleColumn!==void 0?this.fileCfg.titleColumn===""?void 0:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(i=this.resolveCol(fe))!=null?i:void 0}authorKey(){var e;return(e=this.resolveCol(["Author","author","Authors","authors","Director","director","Artist","artist","Creator","creator","By","by"]))!=null?e:void 0}getTitle(e){var n;let i=this.titleKey();return(n=i?e[i]:e[this.headers[0]])!=null?n:"\u2014"}getSubtitle(e){var n;let i=this.authorKey();return i&&(n=e[i])!=null?n:""}getColumnValues(e){return Array.from(new Set(this.rows.map(i=>{var n;return(n=i[e])!=null?n:""}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn!==void 0?this.fileCfg.imageColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(ns)}getBooleanColumns(){return this.fileCfg.habitColumns?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.headers.filter(e=>{if(e===this.getDateCol()||this.isNotesCol(e))return!1;let i=this.rows.map(n=>{var o;return((o=n[e])!=null?o:"").toLowerCase().trim()});return as(i)})}getDateCol(){var o,r;if(this.fileCfg.dateColumns&&this.fileCfg.dateColumns.length>0){let a=this.fileCfg.dateColumns[0];return(o=this.headers.find(L=>L===a))!=null?o:null}if(this.headers.length===0)return null;let e=this.headers[0];if(["date","day","datum"].includes(e.toLowerCase()))return e;let i=/^\d{4}-\d{2}-\d{2}$/,n=this.rows.slice(0,5);return n.length>0&&n.every(a=>{var L;return i.test((L=a[e])!=null?L:"")})?e:(r=this.headers.find(a=>this.isDateCol(a)))!=null?r:null}isDateCol(e){var i;return(i=this.fileCfg.dateColumns)!=null&&i.includes(e)?!0:Et(e)}getFilteredRows(){var n;let e=this.rows;if(this.searchQuery.trim()){let o=this.searchQuery.toLowerCase().trim();e=e.filter(r=>this.headers.some(a=>{var L;return((L=r[a])!=null?L:"").toLowerCase().includes(o)}))}if(this.mode==="table"&&this.tableSortCol&&this.headers.includes(this.tableSortCol)){let o=this.tableSortCol,r=this.tableSortDir;return[...e].sort((a,L)=>{var c,d;let l=((c=a[o])!=null?c:"").localeCompare((d=L[o])!=null?d:"",void 0,{numeric:!0});return r==="asc"?l:-l})}let i=this.getDateCol();if(this.mode==="table"&&i){let o=(n=this.fileCfg.sortNewestFirst)!=null?n:!0;e=[...e].sort((r,a)=>{var l,c;let L=((l=r[i])!=null?l:"").localeCompare((c=a[i])!=null?c:"");return o?-L:L})}return e}notesFilePath(e){var a,L,l;let i=Ve(this.getTitle(e)),n=(l=(L=(a=this.file)==null?void 0:a.parent)==null?void 0:L.path)!=null?l:"",o=this.settings.notesSubfolder.trim(),r=o?n?`${n}/${o}`:o:n;return(0,Mt.normalizePath)(`${r}/${i}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}async openOrCreateNotes(e){var o;let i=this.notesFilePath(e),n=this.app.vault.getAbstractFileByPath(i);if(!n){let a=["---",...this.headers.filter(d=>!this.isNotesCol(d)&&e[d]).map(d=>`${d}: "${e[d].replace(/"/g,'\\"')}"`),"---","",`# ${this.getTitle(e)}`,"",""].join(` +`),L=this.headers.find(d=>this.isNotesCol(d)),l=a+(L&&((o=e[L])!=null&&o.trim())?e[L]:""),c=i.substring(0,i.lastIndexOf("/"));c&&!this.app.vault.getAbstractFileByPath(c)&&await this.app.vault.createFolder(c),n=await this.app.vault.create(i,l),new Mt.Notice(`Created: ${n.name}`)}await this.app.workspace.getLeaf("tab").openFile(n)}deleteWithUndo(e){let i=this.rows.indexOf(e);if(i<0)return;this.rows.splice(i,1),this.scheduleSave(),this.renderView();let n=this.getTitle(e)||"entry",o=createFragment();o.createSpan({text:`Deleted \u201C${n}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new Mt.Notice(o,6e3);r.addEventListener("click",()=>{r.hasAttribute("disabled")||(r.setAttribute("disabled","true"),this.rows.splice(Math.min(i,this.rows.length),0,e),this.scheduleSave(),this.renderView(),a.hide(),new Mt.Notice(`Restored \u201C${n}\u201D`,2500))})}openRowContextMenu(e,i){let n=new Mt.Menu;n.addItem(a=>a.setTitle("Open / create notes file").setIcon("file-text").onClick(()=>void this.openOrCreateNotes(e))),n.addItem(a=>a.setTitle("Open entry").setIcon("maximize").onClick(()=>{var L;return this.openNoteExpander(e,(L=this.getNotesCol())!=null?L:"")}));let o=this.getStatusCol();if(o){let a=this.getColumnValues(o);a.length&&(n.addSeparator(),a.forEach(L=>{L!==e[o]&&n.addItem(l=>l.setTitle(`Mark as: ${L}`).onClick(()=>{e[o]=L,this.scheduleSave(),this.renderView()}))}))}n.addSeparator();let r=this.isHighlighted(e);n.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderView()})),n.addSeparator(),n.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),n.showAtMouseEvent(i)}openNoteExpander(e,i){var n,o;new me(this.app,e,i,this.headers,(o=(n=this.file)==null?void 0:n.path)!=null?o:"",this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),r=>{Object.assign(e,r),this.scheduleSave(),this.renderView()},()=>this.deleteWithUndo(e),this.isCategoricalCol.bind(this),this.titleKey(),r=>this.getBooleanColumns().includes(r),r=>this.isDateCol(r)).open()}openAddModal(){new cs(this.app,this.headers,this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),e=>{this.rows.push(e),this.scheduleSave(),this.renderView(),new Mt.Notice(`Added: ${this.getTitle(e)}`)},{},e=>this.getBooleanColumns().includes(e),e=>this.isCategoricalCol(e),this.titleKey(),e=>this.isDateCol(e)).open()}renderSelectField(e,i,n){var a;let o=(a=i[n])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),n.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",L=>{var l;L.stopPropagation(),$t(r,(l=i[n])!=null?l:"",this.getColumnValues(n),c=>{i[n]=c,r.setText(c||"\u2014"),this.scheduleSave()},this.contentEl)}),r}renderMarkdownInto(e,i){var n,o;Mt.MarkdownRenderer.render(this.app,i,e,(o=(n=this.file)==null?void 0:n.path)!=null?o:"",this.renderComponent)}renderViewPreservingScroll(){this.renderView()}renderView(e=!1){let i=this.containerEl;e?this.contentArea&&this.contentArea.empty():(i.empty(),this.renderToolbar(i),this.contentArea=i.createDiv({cls:"csv-content-area"}),this.opts.height&&(this.contentArea.style.maxHeight=this.opts.height+"px"));let n=this.contentArea;if(n){if(n.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){n.createDiv({cls:"csv-empty-state"}).createEl("p",{text:"This file is empty."});return}if(this.rows.length===0){let o=n.createDiv({cls:"csv-empty-state"});o.createEl("p",{text:"No entries yet."}),o.createEl("button",{cls:"csv-empty-state-action",text:"+ add the first entry"}).addEventListener("click",()=>this.openAddModal());return}(this.mode==="library"||this.mode==="kanban-genre")&&!Pt(this.asView)&&(this.mode="table"),this.mode==="library"?Ei(this.asView,n):this.mode==="kanban-genre"?ki(this.asView,n):_i(this.asView,n)}}renderToolbar(e){var l,c;let i=e.createDiv({cls:"csv-toolbar csv-inline-toolbar"});i.createDiv({cls:"csv-toolbar-title",text:(c=(l=this.file)==null?void 0:l.basename)!=null?c:""}).addEventListener("click",()=>{this.file&&this.app.workspace.getLeaf("tab").openFile(this.file)});let n=i.createDiv({cls:"csv-toolbar-controls"});n.createDiv({cls:"csv-row-count",text:`${this.rows.length} entries`});let o=!!Pt(this.asView),r=n.createDiv({cls:"csv-mode-group"});Y5.forEach(({id:d,label:h})=>{if((d==="library"||d==="kanban-genre")&&!o)return;r.createEl("button",{cls:`csv-mode-btn ${this.mode===d?"active":""}`,text:h}).addEventListener("click",()=>{this.mode=d,this.renderView()})});let a=n.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search\u2026",value:this.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),L=null;a.addEventListener("input",d=>{this.searchQuery=d.target.value,L!==null&&window.clearTimeout(L),L=window.setTimeout(()=>{L=null,this.renderView(!0)},120)}),n.createEl("button",{cls:"csv-add-btn",text:"+ add"}).addEventListener("click",()=>this.openAddModal())}};function _l(s,t,e,i){i("csv-view",(n,o,r)=>{var d,h,u;let a=G5(n),L=(u=(h=(d=s.vault.getAbstractFileByPath(r.sourcePath))==null?void 0:d.parent)==null?void 0:h.path)!=null?u:"",l=a.file?Qt(a.file,L):a.file,c=new Xo(o,s,t,e,{...a,file:l});r.addChild(c)})}var _n=require("obsidian");function K5(s){let t=s.split(` +`).map(n=>n.trim()).filter(Boolean),e=n=>{var o,r;return(r=(o=t.find(a=>a.toLowerCase().startsWith(n+":")))==null?void 0:o.slice(n.length+1).trim())!=null?r:""},i=n=>{let o=parseFloat(e(n));return Number.isFinite(o)?o:null};return{file:e("file"),x:e("x"),y:e("y"),hue:e("hue")||e("color"),size:e("size"),agg:["count","sum","avg"].includes(e("agg").toLowerCase())?e("agg").toLowerCase():"",bucket:["week","month"].includes(e("bucket").toLowerCase())?e("bucket").toLowerCase():"",smooth:e("smooth").toLowerCase()==="true"?7:Math.max(0,parseInt(e("smooth"),10)||0),fit:e("fit").toLowerCase()==="linear"?"linear":"none",formula:e("formula"),xmin:i("xmin"),xmax:i("xmax"),height:i("height")}}function q5(s){return s instanceof _n.TFile?s:s&&typeof s=="object"&&"basename"in s?s:null}function Sl(s){let t=(s!=null?s:"").trim().match(/^(\d{4})-(\d{2})-(\d{2})/);return t?new Date(parseInt(t[1]),parseInt(t[2])-1,parseInt(t[3])):null}var Qo=class extends _n.MarkdownRenderChild{constructor(e,i,n){super(e);this.app=i;this.opts=n;this.chart=null}onload(){this.containerEl.addClass("csv-chart-block"),(async()=>(await this.render(),this.opts.file&&(this.registerEvent(this.app.vault.on("modify",e=>{e.path===this.opts.file&&this.render()})),this.registerEvent(this.app.vault.on("rename",(e,i)=>{i===this.opts.file&&(this.opts.file=e.path)})))))()}onunload(){this.chart&&(this.chart.destroy(),this.chart=null)}renderError(e){this.containerEl.empty(),this.containerEl.createEl("p",{text:`csv-chart: ${e}`,cls:"csv-add-error"})}async render(){var L,l,c,d,h;let e=this.containerEl;this.chart&&(this.chart.destroy(),this.chart=null),e.empty();let i,n=0;if(this.opts.file){let u=q5(this.app.vault.getAbstractFileByPath(this.opts.file));if(!u)return this.renderError(`File not found: ${this.opts.file}`);let f,g;try{({headers:f,rows:g}=kt(await this.app.vault.read(u)))}catch(x){return this.renderError(`Error reading file: ${x instanceof Error?x.message:String(x)}`)}let m=x=>{var k;return(k=f.find(E=>E.toLowerCase()===x.toLowerCase()))!=null?k:null},p=un(f,g),b=(L=f.find(x=>Et(x)))!=null?L:g.slice(0,5).length&&g.slice(0,5).every(x=>{var k;return Sl((k=x[f[0]])!=null?k:"")})?f[0]:null,C=this.opts.x?m(this.opts.x):(l=b!=null?b:p[0])!=null?l:null;if(this.opts.x&&!C)return this.renderError(`No column "${this.opts.x}" in ${u.basename}`);let S=this.opts.y?m(this.opts.y):(c=p.find(x=>x!==C))!=null?c:null;if(this.opts.y&&!S)return this.renderError(`No column "${this.opts.y}" in ${u.basename}`);if(!C||!S)return this.renderError(`Couldn't auto-pick x/y columns \u2014 add "x:" and "y:" lines`);let _=this.opts.hue?m(this.opts.hue):null;if(this.opts.hue&&!_)return this.renderError(`No column "${this.opts.hue}" in ${u.basename}`);let y=this.opts.size?m(this.opts.size):null;if(this.opts.size&&!y)return this.renderError(`No column "${this.opts.size}" in ${u.basename}`);let v=C===b||Et(C);if(!v&&!p.includes(C)){let x=this.opts.agg||"count",k=Uo(g,C,x==="count"?null:S,_,x);if(n=k.skipped,!k.categories.length)return this.renderError(`No rows with a "${C}" value to chart`);let E=x==="count"?"count":`${x}(${S})`;i={config:Yo(k,C,E,Ps(e)),fitText:null,formulaError:null}}else{let x=jo(g,C,S,_,y,v,Sl,A=>{var N;return(N=A[f[0]])!=null?N:""});if(n=x.skipped,!x.series.some(A=>A.points.length))return this.renderError(`No rows with numeric "${C}" and "${S}" values`);let k=v?this.opts.bucket:"",E=this.opts.agg||"sum",D={series:k?x.series.map(A=>({label:A.label,points:Wo(A.points,k,E)})):x.series,xIsDate:v,xLabel:C,yLabel:k?E==="count"?`count / ${k}`:`${E}(${S}) / ${k}`:S,connect:v,fit:this.opts.fit,formula:this.opts.formula,sizeLabel:k?"":y!=null?y:"",smoothDays:v&&!k?this.opts.smooth:0};i=fn(D,Ps(e))}}else{if(!this.opts.formula.trim())return this.renderError('Give a "file:" line, a "formula:" line, or both');i=fn({series:[],xIsDate:!1,xLabel:"x",yLabel:"y",connect:!1,fit:"none",formula:this.opts.formula,xMin:(d=this.opts.xmin)!=null?d:-10,xMax:(h=this.opts.xmax)!=null?h:10},Ps(e))}if(i.formulaError)return this.renderError(`formula: ${i.formulaError}`);let o=e.createDiv({cls:"csv-chart-wrap"});this.opts.height&&(o.style.height=this.opts.height+"px");let r=o.createEl("canvas",{cls:"csv-chart-canvas"});if(i.fitText||n>0){let u=e.createDiv({cls:"csv-chart-footer"});i.fitText&&u.createSpan({cls:"csv-chart-fit-text",text:i.fitText}),n>0&&u.createSpan({cls:"csv-chart-skipped",text:`${n} row${n===1?"":"s"} skipped (no numeric value)`})}let{Chart:a}=await ts();r.isConnected&&(this.chart=new a(r,i.config))}};function kl(s,t){t("csv-chart",(e,i,n)=>{var L,l,c;let o=K5(e),r=(c=(l=(L=s.vault.getAbstractFileByPath(n.sourcePath))==null?void 0:L.parent)==null?void 0:l.path)!=null?c:"",a=o.file?Qt(o.file,r):o.file;n.addChild(new Qo(i,s,{...o,file:a}))})}var Wt=require("obsidian"),Ml=Ns(is());var Sn=["Title","Type","Project","Priority","Due","Status","Notes"],X5={Title:fe,Type:["Type","type","Kind","kind","Item","item"],Project:["Project","project","Projects","projects","Area","area"],Priority:["Priority","priority","Prio","prio","Importance","importance"],Due:["Due","due","Deadline","deadline","Due Date","Due date","due date"],Status:["Status","status","State","state","Done","done"],Notes:pe};function Q5(s){let t={};for(let e of Sn)for(let i of X5[e]){let n=s.find(o=>o.toLowerCase()===i.toLowerCase());if(n){t[e]=n;break}}return!t.Title&&s.length&&(t.Title=s[0]),t}function J5(s){let t=[],e=[];return s.forEach((i,n)=>{let o=Q5(i.headers);i.rows.forEach(r=>{var L;let a={};for(let l of Sn)a[l]=o[l]&&(L=r[o[l]])!=null?L:"";o.Project||(a.Project=i.basename),t.push(a),e.push({sourceIndex:n,srcRow:r,map:o})})}),{headers:[...Sn],rows:t,refs:e}}function th(s,t){var e;for(let i of Sn){let n=t.map[i];n&&(t.srcRow[n]=(e=s[i])!=null?e:"")}}function eh(s){let t=s.split(` +`).map(n=>n.trim()).filter(Boolean),e=n=>{var o,r;return(r=(o=t.find(a=>a.toLowerCase().startsWith(n+":")))==null?void 0:o.slice(n.length+1).trim())!=null?r:""},i=parseInt(e("height"),10);return{folder:e("folder"),files:e("files").split(",").map(n=>n.trim()).filter(Boolean),height:Number.isFinite(i)&&i>0?i:null}}function El(s){return s instanceof Wt.TFile?s:s&&typeof s=="object"&&"basename"in s?s:null}var Jo=class extends Wt.MarkdownRenderChild{constructor(e,i,n,o,r){super(e);this.app=i;this.settings=n;this.opts=o;this.notePath=r;this.headers=[];this.rows=[];this.searchQuery="";this.taskProjectFilter="all";this.taskTypeFilter="all";this.fileCfg={};this.sources=[];this.refs=[];this.saveTimer=null;this.contentArea=null}get contentEl(){return this.containerEl}get asView(){return this}onload(){if(this.containerEl.addClass("csv-inline-view","csv-tasks-block"),!this.opts.folder&&!this.opts.files.length){this.renderError('Give a "folder:" line ("/" = whole vault) and/or a "files:" list.');return}(async()=>(await this.reload(),this.renderView(),this.registerEvent(this.app.vault.on("modify",async e=>{let i=this.sources.find(r=>r.file.path===e.path);if(!i||this.saveTimer)return;let n=await this.app.vault.read(i.file);if(n===i.lastText)return;i.lastText=n;let o=kt(n);i.headers=o.headers,i.rows=o.rows,this.rebuild(),this.renderView()}))))()}onunload(){this.saveTimer&&window.clearTimeout(this.saveTimer)}renderError(e){this.containerEl.empty(),this.containerEl.createEl("p",{text:`csv-tasks: ${e}`,cls:"csv-add-error"})}async reload(){var n,o,r;let e=(r=(o=(n=this.app.vault.getAbstractFileByPath(this.notePath))==null?void 0:n.parent)==null?void 0:o.path)!=null?r:"",i=new Map;for(let a of this.opts.files){let L=El(this.app.vault.getAbstractFileByPath(Qt(a,e)));if(!L){this.renderError(`File not found: ${a}`);continue}i.set(L.path,{file:L,explicit:!0})}if(this.opts.folder){let a=this.opts.folder==="/"?"":this.opts.folder.replace(/\/$/,"")+"/";for(let L of this.app.vault.getFiles())L.extension==="csv"&&(a&&!L.path.startsWith(a)||i.has(L.path)||i.set(L.path,{file:L,explicit:!1}))}this.sources=[];for(let{file:a,explicit:L}of i.values())try{let l=await this.app.vault.read(a),{headers:c,rows:d}=kt(l);(L||Ie({headers:c,rows:d,resolveCol:u=>{var f;return(f=u.map(g=>c.find(m=>m.toLowerCase()===g.toLowerCase())).find(Boolean))!=null?f:null}}))&&this.sources.push({file:a,headers:c,rows:d,lastText:l})}catch(l){}this.rebuild()}rebuild(){let e=J5(this.sources.map(i=>({basename:i.file.basename,headers:i.headers,rows:i.rows})));this.headers=e.headers,this.rows=e.rows,this.refs=e.refs}refOf(e){let i=this.rows.indexOf(e);return i>=0?this.refs[i]:null}sourceOf(e){var n;let i=this.refOf(e);return i&&(n=this.sources[i.sourceIndex])!=null?n:null}scheduleSave(){this.saveTimer&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>void this.doSave(),600)}async doSave(){this.saveTimer=null,this.rows.forEach((e,i)=>th(e,this.refs[i]));for(let e of this.sources){let i=Ml.default.unparse(e.rows,{columns:e.headers});if(i!==e.lastText)try{try{let n=await this.app.vault.read(e.file);n!==e.lastText&&n!==i&&await ls(this.app,e.file,n)}catch(n){}e.lastText=i,await this.app.vault.modify(e.file,i)}catch(n){new Wt.Notice(`Couldn't save ${e.file.name}: ${n instanceof Error?n.message:String(n)}`,8e3)}}}resolveCol(e){for(let i of e){let n=this.headers.find(o=>o.toLowerCase()===i.toLowerCase());if(n)return n}return null}titleKey(){return"Title"}getStatusCol(){return"Status"}getCategoryCol(){return null}getDateCol(){return null}getNotesCol(){return"Notes"}isNotesCol(e){return e==="Notes"}isDateCol(e){return e==="Due"}getTitle(e){return e.Title||"\u2014"}getColumnValues(e){return Array.from(new Set(this.rows.map(i=>{var n;return(n=i[e])!=null?n:""}).filter(Boolean))).sort()}renderViewPreservingScroll(){this.renderView()}renderView(e=!1){let i=this.containerEl;if(e)this.contentArea&&this.contentArea.empty();else{i.empty();let n=i.createDiv({cls:"csv-toolbar csv-inline-toolbar"});n.createDiv({cls:"csv-toolbar-title",text:"Tasks"}),n.createDiv({cls:"csv-row-count",text:`${this.rows.length} entries \xB7 ${this.sources.length} file${this.sources.length===1?"":"s"}`}),this.contentArea=i.createDiv({cls:"csv-content-area"}),this.opts.height&&(this.contentArea.style.maxHeight=this.opts.height+"px")}if(this.contentArea){if(!this.sources.length){this.contentArea.createEl("p",{text:"No task-shaped CSV files found.",cls:"csv-empty-state"});return}bn(this.asView,this.contentArea)}}openNoteExpander(e,i){var L;let n=this.refOf(e),o=this.sourceOf(e);if(!n||!o)return;let r=(L=n.map.Notes)!=null?L:"",a=l=>l===n.map.Notes;new me(this.app,n.srcRow,r,o.headers,o.file.path,a,()=>!1,l=>Array.from(new Set(o.rows.map(c=>{var d;return(d=c[l])!=null?d:""}).filter(Boolean))).sort(),l=>{var c;Object.assign(n.srcRow,l);for(let d of Object.keys(e)){let h=n.map[d];h&&(e[d]=(c=n.srcRow[h])!=null?c:"")}this.scheduleSave(),this.renderView()},()=>this.deleteRow(e),void 0,n.map.Title,void 0,l=>/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(l)).open()}async openOrCreateNotes(e){let i=this.sourceOf(e);if(!i)return;let n=this.notesFilePath(e,i),o=El(this.app.vault.getAbstractFileByPath(n));if(!o){let r=["---",`source: "[[${i.file.path}]]"`,"---","",`# ${this.getTitle(e)}`,"",""].join(` +`),a=n.substring(0,n.lastIndexOf("/"));a&&!this.app.vault.getAbstractFileByPath(a)&&await this.app.vault.createFolder(a),o=await this.app.vault.create(n,r),new Wt.Notice(`Created: ${o.name}`)}await this.app.workspace.getLeaf("tab").openFile(o)}notesFileExists(e){let i=this.sourceOf(e);return!!i&&!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e,i))}notesFilePath(e,i){var L,l;let n=Ve(this.getTitle(e)),o=(l=(L=i.file.parent)==null?void 0:L.path)!=null?l:"",r=this.settings.notesSubfolder.trim(),a=r?o?`${o}/${r}`:r:o;return(0,Wt.normalizePath)(`${a}/${n}.md`)}deleteRow(e){let i=this.refOf(e),n=this.sourceOf(e);if(!i||!n)return;let o=n.rows.indexOf(i.srcRow);o>=0&&n.rows.splice(o,1);let r=this.rows.indexOf(e);r>=0&&(this.rows.splice(r,1),this.refs.splice(r,1)),this.scheduleSave(),this.renderView(),new Wt.Notice(`Deleted \u201C${this.getTitle(e)}\u201D from ${n.file.name}`)}openRowContextMenu(e,i){let n=this.sourceOf(e),o=new Wt.Menu;o.addItem(r=>r.setTitle("Open entry").setIcon("maximize").onClick(()=>this.openNoteExpander(e,"Notes"))),n&&o.addItem(r=>r.setTitle(`Open source: ${n.file.name}`).setIcon("file-spreadsheet").onClick(()=>void this.app.workspace.getLeaf("tab").openFile(n.file))),o.addSeparator(),o.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteRow(e))),o.showAtMouseEvent(i)}};function wl(s,t,e){e("csv-tasks",(i,n,o)=>{o.addChild(new Jo(n,s,t,eh(i),o.sourcePath))})}var Dl='';var Fs=class extends at.FileView{constructor(e,i,n){super(e);this.headers=[];this.rows=[];this.saveTimer=null;this.searchQuery="";this.lastDiskContent=null;this.contentArea=null;this.selectedDate=null;this.selectedHabit=null;this.chartInstance=null;this.timelineYear=new Date().getFullYear();this.libraryStatusFilter="all";this.libraryGenreFilter="all";this.collapsedGroups=new Set;this.taskProjectFilter="all";this.taskTypeFilter="all";this.focusIndex=0;this.focusNavPending=!1;this.tableSortCol=null;this.tableSortDir="asc";this.settings=i,this.persistSettings=n,this.mode=i.defaultMode,this.renderComponent=new at.Component,this.renderComponent.load()}getViewType(){return ui}getDisplayText(){var e,i;return(i=(e=this.file)==null?void 0:e.basename)!=null?i:"Card View"}getIcon(){return"table"}onload(){super.onload(),this.registerEvent(this.app.vault.on("modify",e=>{!this.file||e.path!==this.file.path||this.syncFromDisk()}))}async syncFromDisk(){if(!this.file)return;let e=await this.app.vault.read(this.file);if(e===this.lastDiskContent||this.saveTimer)return;this.lastDiskContent=e;let i=kt(e);this.headers=i.headers,this.rows=i.rows,this.renderViewPreservingScroll()}async onLoadFile(e){var o;try{let r=await this.app.vault.read(e),a=kt(r);this.headers=a.headers,this.rows=a.rows,this.lastDiskContent=r}catch(r){console.error("CardView load error",r),this.headers=[],this.rows=[],this.lastDiskContent=null,new at.Notice(`Couldn't read ${e.name}: ${r instanceof Error?r.message:String(r)}`,8e3)}this.file&&((o=this.settings.fileConfigs[this.file.path])!=null&&o.defaultMode)?this.mode=this.settings.fileConfigs[this.file.path].defaultMode:this.isTravelFile()?this.mode="travel":this.hasDateColumn()?this.mode="dashboard":this.mode=this.settings.defaultMode;let i=this.mode==="kanban-genre"||this.mode==="library",n=this.mode==="dashboard";(i&&!Pt(this)||n&&!this.hasDateColumn()||this.mode==="travel"&&!this.isTravelFile()||this.mode==="stats"&&!Si(this)||this.mode==="chart"&&!pn(this)||this.mode==="tasks"&&!Ie(this)||this.mode==="budget"&&!yn(this))&&(this.mode="table"),this.selectedDate=null,this.focusIndex=0,this.tableSortCol=null,this.renderView()}async onUnloadFile(e){this.chartInstance&&(this.chartInstance.destroy(),this.chartInstance=null),this.headers=[],this.rows=[],this.contentEl.empty()}scheduleSave(){this.saveTimer&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.doSave()},600)}async doSave(){if(this.file)try{let e=Tl.default.unparse(this.rows,{columns:this.headers});try{let i=await this.app.vault.read(this.file);this.lastDiskContent!==null&&i!==this.lastDiskContent&&i!==e&&await ls(this.app,this.file,i)}catch(i){}this.lastDiskContent=e,await this.app.vault.modify(this.file,e)}catch(e){console.error("CardView save error",e),new at.Notice(`Couldn't save ${this.file.name}: ${e instanceof Error?e.message:String(e)}`,8e3)}}get fileCfg(){var e;return this.file?(e=this.settings.fileConfigs[this.file.path])!=null?e:{}:{}}saveFileCfg(e){this.file&&(this.settings.fileConfigs[this.file.path]=e,this.persistSettings())}isHighlighted(e){var i;return((i=this.fileCfg.highlightedTitles)!=null?i:[]).includes(this.getTitle(e))}toggleHighlight(e){let i=this.getTitle(e),n=this.fileCfg,o=n.highlightedTitles?[...n.highlightedTitles]:[],r=o.indexOf(i);r>=0?o.splice(r,1):o.push(i),n.highlightedTitles=o,this.saveFileCfg(n)}addColumn(e){let i=e.trim();return i?this.headers.some(n=>n.toLowerCase()===i.toLowerCase())?`"${i}" already exists.`:(this.headers.push(i),this.rows.forEach(n=>{n[i]=""}),this.scheduleSave(),this.renderViewPreservingScroll(),null):"Column name can't be empty."}removeColumn(e){this.headers=this.headers.filter(n=>n!==e),this.rows.forEach(n=>{delete n[e]});let i=this.fileCfg;i.categoryColumn===e&&(i.categoryColumn=void 0),i.statusColumn===e&&(i.statusColumn=void 0),i.notesColumn===e&&(i.notesColumn=void 0),i.ankiFrontCol===e&&(i.ankiFrontCol=void 0),i.kanbanGroupCol===e&&(i.kanbanGroupCol=void 0),i.habitColumns&&(i.habitColumns=i.habitColumns.filter(n=>n!==e)),i.cardFields&&(i.cardFields=i.cardFields.filter(n=>n!==e)),i.categoricalColumns&&(i.categoricalColumns=i.categoricalColumns.filter(n=>n!==e)),this.saveFileCfg(i),this.scheduleSave(),this.renderViewPreservingScroll()}resolveCol(e){for(let i of e){let n=this.headers.find(o=>o.toLowerCase()===i.toLowerCase());if(n)return n}return null}getNotesCol(){return this.fileCfg.notesColumn!==void 0?this.fileCfg.notesColumn===""?null:this.fileCfg.notesColumn:this.resolveCol(pe)}isNotesCol(e){let i=this.getNotesCol();return i?e===i:this.settings.notesColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var n;let i=(n=this.titleKey())!=null?n:this.headers[0];return e===i||this.isDateCol(e)||vt(e)?!1:this.fileCfg.categoricalColumns?this.fileCfg.categoricalColumns.includes(e):this.isSelectCol(e)||Xt(this.getColumnValues(e).length)}autoDetectCategoricalColumns(){var i;let e=(i=this.titleKey())!=null?i:this.headers[0];return this.headers.filter(n=>n===e||this.isDateCol(n)||vt(n)||this.isNotesCol(n)?!1:this.isSelectCol(n)||Xt(this.getColumnValues(n).length))}isDateCol(e){var i;return(i=this.fileCfg.dateColumns)!=null&&i.includes(e)?!0:Et(e)}getStatusCol(){var e;return this.fileCfg.statusColumn!==void 0?this.fileCfg.statusColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(rs)}getCategoryCol(){var e;return this.fileCfg.categoryColumn!==void 0?this.fileCfg.categoryColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(os)}titleKey(){var e,i;return this.fileCfg.titleColumn!==void 0?this.fileCfg.titleColumn===""?void 0:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(i=this.resolveCol(fe))!=null?i:void 0}authorKey(){var e;return(e=this.resolveCol(["Author","author","Authors","authors","Director","director","Artist","artist","Creator","creator","By","by"]))!=null?e:void 0}getTitle(e){var n;let i=this.titleKey();return(n=i?e[i]:e[this.headers[0]])!=null?n:"\u2014"}getSubtitle(e){var n;let i=this.authorKey();return i&&(n=e[i])!=null?n:""}getColumnValues(e){return Array.from(new Set(this.rows.map(i=>{var n;return((n=i[e])!=null?n:"").trim()}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn!==void 0?this.fileCfg.imageColumn===""?null:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(ns)}notesFilePath(e){var a,L,l;let i=Ve(this.getTitle(e)),n=(l=(L=(a=this.file)==null?void 0:a.parent)==null?void 0:L.path)!=null?l:"",o=this.settings.notesSubfolder.trim(),r=o?n?`${n}/${o}`:o:n;return(0,at.normalizePath)(`${r}/${i}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}deleteWithUndo(e){let i=this.rows.indexOf(e);if(i<0)return;this.rows.splice(i,1),this.scheduleSave(),this.renderViewPreservingScroll();let n=this.getTitle(e)||"entry",o=createFragment();o.createSpan({text:`Deleted \u201C${n}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new at.Notice(o,6e3);r.addEventListener("click",()=>{if(r.hasAttribute("disabled"))return;r.setAttribute("disabled","true");let L=Math.min(i,this.rows.length);this.rows.splice(L,0,e),this.scheduleSave(),this.renderViewPreservingScroll(),a.hide(),new at.Notice(`Restored \u201C${n}\u201D`,2500)})}openRowContextMenu(e,i){let n=new at.Menu;n.addItem(a=>a.setTitle("Open / create notes file").setIcon("file-text").onClick(()=>this.openOrCreateNotes(e))),n.addItem(a=>a.setTitle("Open entry").setIcon("maximize").onClick(()=>{var L;return this.openNoteExpander(e,(L=this.getNotesCol())!=null?L:"")}));let o=this.getStatusCol();if(o){let a=this.getColumnValues(o);a.length&&(n.addSeparator(),a.forEach(L=>{L!==e[o]&&n.addItem(l=>l.setTitle(`Mark as: ${L}`).onClick(()=>{e[o]=L,this.scheduleSave(),this.renderViewPreservingScroll()}))}))}n.addSeparator();let r=this.isHighlighted(e);n.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderViewPreservingScroll()})),n.addSeparator(),n.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),n.showAtMouseEvent(i)}async openOrCreateNotes(e){var o,r;let i=this.notesFilePath(e),n=this.app.vault.getAbstractFileByPath(i);if(!n){let a={},L=Ie(this)?Ko(this):null,l=L?((o=e[L])!=null?o:"").split(",").map(f=>or(f.trim())).filter(Boolean).map(f=>`project-${f}`):[];l.length&&(a.tags=l);for(let f of this.headers)!this.isNotesCol(f)&&e[f]&&(a[f]=e[f]);this.file&&!Object.keys(a).some(f=>f.toLowerCase()==="source")&&(a.source=`[[${this.file.path}]]`);let c=["---",(0,at.stringifyYaml)(a).trimEnd(),"---","",`# ${this.getTitle(e)}`,"",""].join(` +`),d=this.headers.find(f=>this.isNotesCol(f)),h=c+(d&&((r=e[d])!=null&&r.trim())?e[d]:""),u=i.substring(0,i.lastIndexOf("/"));u&&!this.app.vault.getAbstractFileByPath(u)&&await this.app.vault.createFolder(u),n=await this.app.vault.create(i,h),new at.Notice(`Created: ${n.name}`)}await this.app.workspace.getLeaf("tab").openFile(n)}openNoteExpander(e,i){var n,o;new me(this.app,e,i,this.headers,(o=(n=this.file)==null?void 0:n.path)!=null?o:"",this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),r=>{Object.assign(e,r),this.scheduleSave(),this.renderViewPreservingScroll()},()=>this.deleteWithUndo(e),r=>this.isCategoricalCol(r),this.titleKey(),r=>this.getBooleanColumns().includes(r),r=>this.isDateCol(r)).open()}renderViewPreservingScroll(){var L,l,c,d,h;let e=this.contentEl,i=e.querySelector(".csv-content-area"),n=e.querySelector(".csv-table-wrapper"),o=e.querySelector(".csv-kanban-board"),r={contentTop:(L=i==null?void 0:i.scrollTop)!=null?L:0,contentLeft:(l=i==null?void 0:i.scrollLeft)!=null?l:0,tableLeft:(c=n==null?void 0:n.scrollLeft)!=null?c:0,tableTop:(d=n==null?void 0:n.scrollTop)!=null?d:0,boardLeft:(h=o==null?void 0:o.scrollLeft)!=null?h:0,cols:new Map};e.querySelectorAll(".csv-kanban-col").forEach(u=>{var m,p;let f=(p=(m=u.querySelector(".csv-kanban-col-title"))==null?void 0:m.textContent)!=null?p:"",g=u.querySelector(".csv-kanban-col-body");f&&g&&r.cols.set(f,g.scrollTop)}),this.renderView();let a=()=>{let u=this.contentEl.querySelector(".csv-content-area"),f=this.contentEl.querySelector(".csv-table-wrapper"),g=this.contentEl.querySelector(".csv-kanban-board");u&&(u.scrollTop=r.contentTop,u.scrollLeft=r.contentLeft),f&&(f.scrollLeft=r.tableLeft,f.scrollTop=r.tableTop),g&&(g.scrollLeft=r.boardLeft),this.contentEl.querySelectorAll(".csv-kanban-col").forEach(m=>{var S,_;let p=(_=(S=m.querySelector(".csv-kanban-col-title"))==null?void 0:S.textContent)!=null?_:"",b=m.querySelector(".csv-kanban-col-body"),C=r.cols.get(p);b&&C!=null&&(b.scrollTop=C)})};a(),window.requestAnimationFrame(()=>{a(),window.requestAnimationFrame(a)}),window.setTimeout(a,50)}openAddModal(){let e={};if(Ie(this)){let i=gn(this);i&&(e[i]=["Task","Note","Idea"]);let n=mn(this);n&&(e[n]=["Low","Medium","High"])}new cs(this.app,this.headers,this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),i=>{this.rows.push(i),this.scheduleSave(),this.renderViewPreservingScroll(),new at.Notice(`Added: ${this.getTitle(i)}`)},e,i=>this.getBooleanColumns().includes(i),i=>this.isCategoricalCol(i),this.titleKey(),i=>this.isDateCol(i)).open()}renderSelectField(e,i,n){var a;let o=(a=i[n])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),n.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",L=>{var l;L.stopPropagation(),$t(r,(l=i[n])!=null?l:"",this.getColumnValues(n),c=>{i[n]=c,r.setText(c||"\u2014"),r.className=`csv-select-chip ${c?"":"empty"}`,n.toLowerCase()==="status"&&c&&r.addClass(`status-chip-${c.toLowerCase().replace(/\s+/g,"-")}`),this.scheduleSave()},this.contentEl,{multi:vt(n)})}),r}renderView(e=!1){var o;let i=this.contentEl;e?this.contentArea&&this.contentArea.empty():(i.empty(),i.addClass("datadeck-root"),this.renderComponent.unload(),this.renderComponent=new at.Component,this.renderComponent.load(),gl(this,i),this.contentArea=i.createDiv({cls:"csv-content-area"}),this.installTouchScrollGuard(this.contentArea));let n=this.contentArea;if(n){if(n.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){let r=n.createDiv({cls:"csv-empty-state csv-empty-state--big"});r.createEl("h3",{text:"This file is empty"}),r.createEl("p",{text:"Add a header row in your spreadsheet app, then come back \u2014 or click + add in the toolbar to start fresh."});return}if(this.rows.length===0){let r=n.createDiv({cls:"csv-empty-state csv-empty-state--big"});r.createEl("h3",{text:"No entries yet"}),r.createEl("button",{cls:"csv-empty-state-action",text:"+ add the first entry"}).addEventListener("click",()=>this.openAddModal()),r.createEl("p",{cls:"csv-empty-state-hint",text:`${this.headers.length} column${this.headers.length===1?"":"s"} detected: ${this.headers.slice(0,5).join(", ")}${this.headers.length>5?"\u2026":""}`});return}this.mode==="travel"?yr(n,this.rows,()=>this.loadMapSvg(),()=>this.scheduleSave(),this.settings.showResidency===!1?null:(o=this.settings.residencyRules)!=null?o:null,r=>this.renderComponent.register(r)):this.mode==="dashboard"?vl(this,n):this.mode==="library"?Ei(this,n):this.mode==="kanban-genre"?ki(this,n):this.mode==="stats"?Er(this,n):this.mode==="chart"?ll(this,n):this.mode==="focus"?yl(this,n):this.mode==="tasks"?bn(this,n):this.mode==="budget"?pl(this,n):_i(this,n)}}installTouchScrollGuard(e){if(!matchMedia("(pointer: coarse)").matches)return;let i=0,n=0,o=!1;e.addEventListener("touchstart",r=>{r.touches.length===1&&(i=r.touches[0].clientX,n=r.touches[0].clientY,o=!1)},{capture:!0,passive:!0}),e.addEventListener("touchmove",r=>{if(r.touches.length!==1||o)return;let a=Math.abs(r.touches[0].clientX-i),L=Math.abs(r.touches[0].clientY-n);(a>10||L>10)&&(o=!0)},{capture:!0,passive:!0}),e.addEventListener("click",r=>{o&&(r.preventDefault(),r.stopImmediatePropagation())},!0)}async backupToArchive(){var a,L;if(!this.file)return;let e=(L=(a=this.file.parent)==null?void 0:a.path)!=null?L:"",i=e?`${e}/Archive`:"Archive";await this.app.vault.adapter.exists(i)||await this.app.vault.adapter.mkdir(i);let n=this.formatDate(new Date),o=`${i}/${this.file.basename}_${n}.${this.file.extension}`;if(await this.app.vault.adapter.exists(o)){new at.Notice(`Backup already exists for today: ${o}`);return}let r=await this.app.vault.readBinary(this.file);await this.app.vault.adapter.writeBinary(o,r),new at.Notice(`Backed up to ${o}`)}hasDateColumn(){return this.getDateCol()!==null}isTravelFile(){let e=new Set(this.headers.map(i=>i.toLowerCase()));return e.has("country")&&e.has("date_entered")&&e.has("date_left")&&e.has("source")}async loadMapSvg(){return Dl}getFilteredRows(){var n;let e=this.rows;if(this.searchQuery.trim()){let o=this.searchQuery.toLowerCase().trim();e=e.filter(r=>this.headers.some(a=>{var l;return((l=r[a])!=null?l:"").toLowerCase().includes(o)}))}if(this.mode==="table"&&this.tableSortCol&&this.headers.includes(this.tableSortCol))return rr(e,this.tableSortCol,this.tableSortDir);let i=this.getDateCol();if(this.mode==="table"&&i){let o=(n=this.fileCfg.sortNewestFirst)!=null?n:!0;e=[...e].sort((r,a)=>{var d,h;let L=(d=r[i])!=null?d:"",l=(h=a[i])!=null?h:"",c=L.localeCompare(l);return o?-c:c})}return e}getDateCol(){var a;if(this.fileCfg.dateColumns&&this.fileCfg.dateColumns.length>0){let L=this.fileCfg.dateColumns[0];return(a=this.headers.find(l=>l===L))!=null?a:null}if(this.headers.length===0)return null;let e=this.headers[0],i=e.toLowerCase();if(["date","day","datum"].includes(i))return e;let n=this.rows.slice(0,5),o=/^\d{4}-\d{2}-\d{2}$/;return n.length>0&&n.every(L=>{var l;return o.test((l=L[e])!=null?l:"")})?e:null}getBooleanColumns(){return this.fileCfg.habitColumns?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.autoDetectBooleanColumns()}cleanupBooleanColumn(e){let i=0;return this.rows.forEach(n=>{var r;let o=this.isTruthy((r=n[e])!=null?r:"")?"1":"0";n[e]!==o&&i++,n[e]=o}),i>0&&(this.scheduleSave(),this.renderViewPreservingScroll()),i}autoDetectBooleanColumns(){return this.headers.filter(e=>{if(e===this.getDateCol()||this.isNotesCol(e))return!1;let i=this.rows.map(n=>{var o;return((o=n[e])!=null?o:"").toLowerCase().trim()});return as(i)})}parseDate(e){let i=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);return i?new Date(parseInt(i[1]),parseInt(i[2])-1,parseInt(i[3])):null}formatDate(e){let i=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${i}-${n}-${o}`}isTruthy(e){return Ls(e)}renderMarkdownInto(e,i){var n,o;at.MarkdownRenderer.render(this.app,i,e,(o=(n=this.file)==null?void 0:n.path)!=null?o:"",this.renderComponent)}cycleMode(){let e=xn(this);if(e.length<2)return;let i=e.findIndex(n=>n.id===this.mode);this.mode=e[(i+1)%e.length].id,this.renderView()}onunload(){this.renderComponent.unload(),this.saveTimer&&window.clearTimeout(this.saveTimer)}},ih=[{id:"tasks",command:"Create tasks file",defaultName:"Tasks",headers:["Title","Type","Project","Priority","Due","Status","Notes"],mode:"tasks",configOverrides:{categoricalColumns:["Type","Priority"],dateColumns:["Due"],statusColumn:"Status",notesColumn:"Notes"}},{id:"travel",command:"Create travel file",defaultName:"Travel",headers:["date_entered","date_left","country","city","visa_status","notes","source","resolved"],mode:"travel"},{id:"habits",command:"Create habit tracker file",defaultName:"Habits",headers:["Date","Exercise","Meditate","Read","Notes"],mode:"dashboard",configOverrides:{habitColumns:["Exercise","Meditate","Read"],notesColumn:"Notes",statusColumn:""}},{id:"chart",command:"Create chart file",defaultName:"Measurements",headers:["Date","Value","Notes"],mode:"chart",configOverrides:{chartYCol:"Value",chartFit:"linear",notesColumn:"Notes"}},{id:"budget",command:"Create budget file",defaultName:"Budget",headers:["Date","Item","Type","Price","Notes"],mode:"budget",configOverrides:{titleColumn:"Item",categoricalColumns:["Type"],notesColumn:"Notes",habitColumns:[]}}],kn=class extends at.Plugin{constructor(){super(...arguments);this.settings=Tn}async onload(){await this.loadSettings(),this.registerView(ui,e=>new Fs(e,this.settings,()=>this.saveSettings())),this.registerExtensions(["csv"],ui),this.addSettingTab(new Ci(this.app,this)),this.registerMarkdownCodeBlockProcessor("csv-add",async(e,i,n)=>{await Cr(this.app,e.trim(),i,n,this.settings.fileConfigs)}),this.registerMarkdownCodeBlockProcessor("csv-random",async(e,i,n)=>{await bl(this.app,e.trim(),i,n)}),_l(this.app,this.settings,()=>this.saveSettings(),(e,i)=>this.registerMarkdownCodeBlockProcessor(e,i)),kl(this.app,(e,i)=>this.registerMarkdownCodeBlockProcessor(e,i)),wl(this.app,this.settings,(e,i)=>this.registerMarkdownCodeBlockProcessor(e,i)),this.addCommand({id:"add-entry",name:"Add entry to current CSV",checkCallback:e=>{let i=this.app.workspace.getActiveViewOfType(Fs);return i?(e||i.openAddModal(),!0):!1}}),this.addCommand({id:"cycle-view-mode",name:"Cycle view mode",checkCallback:e=>{let i=this.app.workspace.getActiveViewOfType(Fs);return i?(e||i.cycleMode(),!0):!1}});for(let e of ih)this.addCommand({id:`create-${e.id}`,name:e.command,callback:()=>this.createTemplateFile(e)});this.registerEvent(this.app.vault.on("rename",async(e,i)=>{e instanceof at.TFile&&e.extension==="csv"&&this.settings.fileConfigs[i]&&(dr(this.settings.fileConfigs,i,e.path),await this.saveSettings())})),this.registerEvent(this.app.vault.on("delete",async e=>{e instanceof at.TFile&&this.settings.fileConfigs[e.path]&&(delete this.settings.fileConfigs[e.path],await this.saveSettings())})),this.registerMarkdownCodeBlockProcessor("csv-refresh",(e,i,n)=>{i.createEl("button",{cls:"csv-refresh-btn",text:"\u21BB refresh"}).addEventListener("click",()=>{(async()=>{let r=n.sourcePath,a=this.app.vault.getAbstractFileByPath(r);a instanceof at.TFile&&await this.app.workspace.getLeaf(!1).openFile(a,{state:{mode:"preview"}})})()})})}async createTemplateFile(e){new Ne(this.app,e.command,e.defaultName,"File name (without .csv)",i=>{(async()=>{let n=this.app.workspace.getActiveFile(),o=n!=null&&n.parent&&n.parent.path!=="/"?`${n.parent.path}/`:"",r=Ve(i),a=(0,at.normalizePath)(`${o}${r}.csv`);for(let c=2;this.app.vault.getAbstractFileByPath(a);c++)a=(0,at.normalizePath)(`${o}${r} ${c}.csv`);let L=await this.app.vault.create(a,e.headers.join(",")+` +`),l=this.settings.fileConfigs[L.path]||{};this.settings.fileConfigs[L.path]={...l,defaultMode:e.mode,...e.configOverrides||{}},await this.saveSettings(),await this.app.workspace.getLeaf("tab").openFile(L),new at.Notice(`Created: ${L.name}`)})()}).open()}async loadSettings(){var i;let e=await this.loadData();this.settings=Object.assign({},Tn,e),this.settings.residencyRules=JSON.parse(JSON.stringify((i=this.settings.residencyRules)!=null?i:[]))}async saveSettings(){await this.saveData(this.settings)}}; /*! Bundled license information: papaparse/papaparse.min.js: diff --git a/manifest.json b/manifest.json index c3e5ac9..c818e45 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "datadeck", "name": "DataDeck", - "version": "1.7.0", + "version": "1.7.1", "minAppVersion": "1.4.0", "description": "View and edit CSV files as cards, kanban, table, charts, a habit dashboard, a tasks board, a budget tracker, a focus reader, or an interactive travel map. Charts with best-fit lines, formulas, and color-by splits. Notes columns render as Markdown.", "author": "SVM0N", diff --git a/package-lock.json b/package-lock.json index 332e833..a4f6c79 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "datadeck", - "version": "1.6.0", + "version": "1.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "datadeck", - "version": "1.6.0", + "version": "1.7.0", "dependencies": { "@types/papaparse": "^5.5.2", "chart.js": "^4.5.1", @@ -19,7 +19,7 @@ "eslint": "^9.39.5", "eslint-plugin-obsidianmd": "^0.4.1", "jsdom": "^29.1.1", - "obsidian": "latest", + "obsidian": "^1.13.1", "typescript": "^5.0.0" } }, @@ -2713,6 +2713,21 @@ "undici-types": "~5.26.4" } }, + "node_modules/eslint-plugin-obsidianmd/node_modules/obsidian": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.12.3.tgz", + "integrity": "sha512-HxWqe763dOqzXjnNiHmAJTRERN8KILBSqxDSEqbeSr7W8R8Jxezzbca+nz1LiiqXnMpM8lV2jzAezw3CZ4xNUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/codemirror": "5.60.8", + "moment": "2.29.4" + }, + "peerDependencies": { + "@codemirror/state": "6.5.0", + "@codemirror/view": "6.38.6" + } + }, "node_modules/eslint-plugin-obsidianmd/node_modules/typescript": { "version": "5.4.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", @@ -4370,9 +4385,9 @@ } }, "node_modules/obsidian": { - "version": "1.12.3", - "resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.12.3.tgz", - "integrity": "sha512-HxWqe763dOqzXjnNiHmAJTRERN8KILBSqxDSEqbeSr7W8R8Jxezzbca+nz1LiiqXnMpM8lV2jzAezw3CZ4xNUw==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.13.1.tgz", + "integrity": "sha512-qtTEA2pmhJzhuhJqzbBFRYhpIOqvW+krDYjtFynv66KbxBbumHBlsJfWw3I4jtnK/6fZwbQhCrmmDdRwXmX56w==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 7acf6b8..ec12394 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "datadeck", - "version": "1.7.0", + "version": "1.7.1", "description": "DataDeck: XLSX/CSV multi-view plugin for Obsidian", "main": "main.js", "scripts": { @@ -25,7 +25,7 @@ "eslint": "^9.39.5", "eslint-plugin-obsidianmd": "^0.4.1", "jsdom": "^29.1.1", - "obsidian": "latest", + "obsidian": "^1.13.1", "typescript": "^5.0.0" }, "dependencies": { diff --git a/src/chart-block.ts b/src/chart-block.ts index 39e2ef9..74c6153 100644 --- a/src/chart-block.ts +++ b/src/chart-block.ts @@ -33,7 +33,7 @@ import { App, MarkdownPostProcessorContext, MarkdownRenderChild, TFile } from "obsidian"; import type { ChartConfiguration } from "chart.js"; import { CSVRow } from "./types"; -import { parseCSV, resolvePath } from "./utils"; +import { parseCSV, resolvePath, assumeShape } from "./utils"; import { isDateCol } from "./field-types"; import { loadChart } from "./chartjs-loader"; import { @@ -84,9 +84,14 @@ function parseBlockSource(source: string): ChartBlockOptions { }; } -/** Duck-typed TFile check — mirrors inline-view.ts (cross-bundle instanceof is unreliable). */ +/** + * `instanceof TFile` fast path for real vault files, falling back to duck- + * typing — mirrors inline-view.ts. The fallback matters across bundles + * (e.g. smoke tests with a stub vault), where instanceof identity breaks. + */ function asFile(f: unknown): TFile | null { - return f && typeof f === "object" && "basename" in (f) ? (f as TFile) : null; + if (f instanceof TFile) return f; + return f && typeof f === "object" && "basename" in (f) ? assumeShape(f) : null; } function parseIsoDate(s: string): Date | null { diff --git a/src/inline-view.ts b/src/inline-view.ts index e1945b3..affa1e3 100644 --- a/src/inline-view.ts +++ b/src/inline-view.ts @@ -33,7 +33,7 @@ import { import Papa from "papaparse"; import type { CardView } from "../main"; import { CSVRow, ViewMode, FileConfig, CardViewSettings } from "./types"; -import { parseCSV, resolvePath, sanitizeFilename, showSelectPicker, stashSyncConflict, IMAGE_COL_ALIASES, TITLE_COL_ALIASES, CATEGORY_COL_ALIASES, STATUS_COL_ALIASES, NOTES_COL_ALIASES, looksBoolean, looksCategorical, isMultiValueColName } from "./utils"; +import { parseCSV, resolvePath, sanitizeFilename, showSelectPicker, stashSyncConflict, IMAGE_COL_ALIASES, TITLE_COL_ALIASES, CATEGORY_COL_ALIASES, STATUS_COL_ALIASES, NOTES_COL_ALIASES, looksBoolean, looksCategorical, isMultiValueColName, assumeShape } from "./utils"; import { isDateCol } from "./field-types"; import { AddEntryModal, NoteExpanderModal } from "./modals"; import { renderTable } from "./view/table"; @@ -50,11 +50,13 @@ const MODE_LABELS: { id: InlineMode; label: string }[] = [ ]; /** - * Duck-typed TFile check — mirrors random-block.ts so the block is drivable - * with a stub vault in the smoke tests (cross-bundle instanceof is unreliable). + * `instanceof TFile` fast path for real vault files, falling back to duck- + * typing — mirrors random-block.ts so the block is still drivable with a + * stub vault in the smoke tests (cross-bundle instanceof identity breaks there). */ function asFile(f: unknown): TFile | null { - return f && typeof f === "object" && "basename" in (f) ? (f as TFile) : null; + if (f instanceof TFile) return f; + return f && typeof f === "object" && "basename" in (f) ? assumeShape(f) : null; } interface BlockOptions { diff --git a/src/random-block.ts b/src/random-block.ts index 7321cc5..0728ce4 100644 --- a/src/random-block.ts +++ b/src/random-block.ts @@ -14,16 +14,18 @@ import { App, TFile, MarkdownPostProcessorContext } from "obsidian"; /** - * Duck-typed TFile check (folders have `name`/`path` but no `extension`). - * Used instead of `instanceof TFile` so the block is drivable with a stub - * vault in the smoke tests — each test entry is bundled with its own copy of - * the obsidian stub, which breaks cross-bundle instanceof identity. + * `instanceof TFile` fast path for real vault files (folders have + * `name`/`path` but no `extension`), falling back to duck-typing so the + * block is still drivable with a stub vault in the smoke tests — each test + * entry is bundled with its own copy of the obsidian stub, which breaks + * cross-bundle instanceof identity. */ function asFile(f: unknown): TFile | null { - return f && typeof f === "object" && "basename" in (f) ? (f as TFile) : null; + if (f instanceof TFile) return f; + return f && typeof f === "object" && "basename" in (f) ? assumeShape(f) : null; } import { CSVRow } from "./types"; -import { parseCSV, resolvePath } from "./utils"; +import { parseCSV, resolvePath, assumeShape } from "./utils"; const ATTRIBUTION_COLS = ["Author", "author", "By", "by", "Source", "source", "Speaker", "speaker", "Artist", "artist", "Director", "director"]; diff --git a/src/tasks-block.ts b/src/tasks-block.ts index a3a5b55..d0a5865 100644 --- a/src/tasks-block.ts +++ b/src/tasks-block.ts @@ -24,7 +24,7 @@ import { App, Menu, MarkdownPostProcessorContext, MarkdownRenderChild, Notice, T import Papa from "papaparse"; import type { CardView } from "../main"; import { CSVRow, CardViewSettings } from "./types"; -import { parseCSV, resolvePath, sanitizeFilename, stashSyncConflict, TITLE_COL_ALIASES, NOTES_COL_ALIASES } from "./utils"; +import { parseCSV, resolvePath, sanitizeFilename, stashSyncConflict, TITLE_COL_ALIASES, NOTES_COL_ALIASES, assumeShape } from "./utils"; import { NoteExpanderModal } from "./modals"; import { renderTasks, hasTaskColumns } from "./view/tasks"; @@ -122,8 +122,10 @@ function parseBlockSource(source: string): TasksBlockOptions { }; } +/** `instanceof TFile` fast path, falling back to duck-typing for stub-vault smoke tests (cross-bundle instanceof identity breaks there). */ function asFile(f: unknown): TFile | null { - return f && typeof f === "object" && "basename" in (f) ? (f as TFile) : null; + if (f instanceof TFile) return f; + return f && typeof f === "object" && "basename" in (f) ? assumeShape(f) : null; } // ── The block host ─────────────────────────────────────────────────────────── diff --git a/src/utils.ts b/src/utils.ts index 2b855ea..e75783e 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -2,6 +2,18 @@ import Papa from "papaparse"; import { App, Notice, TFile } from "obsidian"; import { CSVRow } from "./types"; +/** + * Narrows an already-shape-checked value to `T`. Exists so the various + * `asFile()` duck-type fallbacks (chart-block.ts, inline-view.ts, + * random-block.ts, tasks-block.ts) don't write a literal `as TFile` — + * `obsidianmd/no-tfile-tfolder-cast` flags that pattern even when an + * `instanceof TFile` fast path already exists, and disabling the rule is + * itself disallowed by the shared eslint config. + */ +export function assumeShape(v: unknown): T { + return v as T; +} + // Column-name aliases that mark a cell as holding an image, for card/kanban // thumbnails. Matched case-insensitively against headers (see getImageCol). export const IMAGE_COL_ALIASES = ["Image", "image", "Cover", "cover", "Poster", "poster", "Thumbnail", "thumbnail", "Thumb", "thumb", "Photo", "photo", "Picture", "picture", "Img", "img"]; diff --git a/src/view/chart.ts b/src/view/chart.ts index 1b24fb8..fac3d61 100644 --- a/src/view/chart.ts +++ b/src/view/chart.ts @@ -585,6 +585,10 @@ export function buildBarConfig(data: BarData, xLabel: string, yLabel: string, co */ async function exportChartPng(view: CardView, canvas: HTMLCanvasElement): Promise { try { + // Deliberately plain createElement, not Obsidian's createEl: `out` is a + // detached scratch canvas for pixel compositing, never attached to the + // DOM, and `ownerDocument.win.createEl` isn't stubbed in the jsdom + // smoke-test environment (only Element.prototype.createEl is). const out = canvas.ownerDocument.createElement("canvas"); out.width = canvas.width; out.height = canvas.height; diff --git a/src/view/toolbar.ts b/src/view/toolbar.ts index 9f99bf3..229cef0 100644 --- a/src/view/toolbar.ts +++ b/src/view/toolbar.ts @@ -55,6 +55,12 @@ export function availableModes(view: CardView): {id: ViewMode, label: string}[] } export function renderToolbar(view: CardView, root: HTMLElement): void { + // The fresh `bar` below never starts expanded, so `root`'s mirror of that + // state (see the search-toggle handler) must reset here too — otherwise a + // full re-render while search was expanded (e.g. a command-palette action) + // would leave `root` stuck with the class and the "Found X of Y" header + // hidden for good. + root.removeClass("csv-toolbar--search-expanded"); const bar = root.createDiv({cls:"csv-toolbar"}); bar.createDiv({cls:"csv-toolbar-title", text: view.file?.basename??""}); const ctrl = bar.createDiv({cls:"csv-toolbar-controls"}); @@ -124,6 +130,7 @@ export function renderToolbar(view: CardView, root: HTMLElement): void { e.preventDefault(); if (!searchInput.value) { bar.removeClass("csv-toolbar--search-expanded"); + root.removeClass("csv-toolbar--search-expanded"); searchToggle.removeClass("has-query"); view.searchQuery = ""; view.renderView(true); @@ -191,8 +198,11 @@ export function renderToolbar(view: CardView, root: HTMLElement): void { return; } // Expand inline. CSS hides the other toolbar items while expanded - // so the input fills the row. + // so the input fills the row. Mirrored onto `root` too — the "Found + // X of Y" header it hides lives outside the toolbar, and toggling a + // class directly beats a `:has()` selector for that lookup. bar.addClass("csv-toolbar--search-expanded"); + root.addClass("csv-toolbar--search-expanded"); searchInput.focus({ preventScroll: true }); }); } diff --git a/styles.css b/styles.css index bbf9433..cd8429e 100644 --- a/styles.css +++ b/styles.css @@ -145,16 +145,20 @@ shrinks naturally when iOS opens the keyboard and the content area below filters live in whatever space is left above the keyboard. Tapping × clears + collapses back to the default toolbar. */ - .csv-search-toggle { display: inline-flex !important; } - .csv-search-wrap { display: none !important; } + /* `.csv-toolbar-controls` ancestor bumps specificity to (0,2,0) so these + mobile rules reliably beat the equal-specificity base rules declared + later in the file (.csv-search-wrap, .csv-search-toggle, etc.) without + needing `!important`. */ + .csv-toolbar-controls .csv-search-toggle { display: inline-flex; } + .csv-toolbar-controls .csv-search-wrap { display: none; } .csv-toolbar--search-expanded .csv-mode-group, .csv-toolbar--search-expanded .csv-add-btn, .csv-toolbar--search-expanded .csv-cfg-btn-overflow, .csv-toolbar--search-expanded .csv-search-toggle { - display: none !important; + display: none; } .csv-toolbar--search-expanded .csv-search-wrap { - display: flex !important; + display: flex; flex: 1 1 auto; min-width: 0; align-items: center; @@ -166,20 +170,29 @@ flex: 1 1 auto; min-width: 0; } - .csv-toolbar--search-expanded .csv-search-input { - width: 100% !important; + /* The extra `:focus` selector matches the desktop `.csv-search-input:focus + { width:220px }` rule's (0,2,0) specificity so this mobile override wins + in both states without `!important`. */ + .csv-toolbar--search-expanded .csv-search-input, + .csv-toolbar--search-expanded .csv-search-input:focus { + width: 100%; min-width: 0; } /* Hide the in-content "Found X of Y" header on mobile while the search is open. The input itself + the underlying filtered view convey the same info; the header clips weirdly when iOS shrinks the WebView for the keyboard. */ - .datadeck-root:has(.csv-toolbar--search-expanded) .csv-search-results { + .datadeck-root.csv-toolbar--search-expanded .csv-search-results { display: none; } - /* `!important` defeats the desktop `.csv-search-input:focus { width:220px }` + /* Same specificity trick as above: beats the desktop `:focus { width:220px }` rule which otherwise overflows the toolbar at mobile widths. */ - .csv-search-input { width: 100% !important; min-width: 0; max-width: 100%; } + .csv-toolbar-controls .csv-search-input, + .csv-toolbar-controls .csv-search-input:focus { + width: 100%; + min-width: 0; + max-width: 100%; + } /* Toolbar buttons go icon-tight on mobile */ .csv-cfg-btn, .csv-add-btn { padding: 6px 10px; font-size: 12px; } .csv-row-count { display: none; } @@ -411,9 +424,9 @@ } .csv-empty-state-action:hover { background: var(--csv-accent-hover); } .csv-empty-state-hint { - font-size: 11px !important; - color: var(--csv-text-faint) !important; - margin-top: 4px !important; + font-size: 11px; + color: var(--csv-text-faint); + margin-top: 4px; } /* ─── Grid View ───────────────────────────────────────────────────────────── */ @@ -1267,7 +1280,8 @@ td .csv-select-chip { /* Inline select in kanban chips */ .csv-chip-select { cursor: pointer; - text-decoration: underline dotted; + text-decoration-line: underline; + text-decoration-style: dotted; text-underline-offset: 2px; } @@ -1399,13 +1413,15 @@ td .csv-select-chip { /* Title is now the clickable nav element */ .csv-kanban-card-title { cursor: pointer; - text-decoration: underline dotted; + text-decoration-line: underline; + text-decoration-style: dotted; text-underline-offset: 2px; } .csv-kanban-card-title:hover { color: var(--interactive-accent); - text-decoration: underline solid; + text-decoration-line: underline; + text-decoration-style: solid; } .csv-kanban-notes-editor { @@ -1695,13 +1711,16 @@ td .csv-select-chip { width: min(780px, 90vw) !important; /* Keyboard-aware modal height. The JS in NoteExpanderModal sets --csv-modal-vh to visualViewport.height (the screen minus the iOS - keyboard, when it's open). When that variable is absent the modal - falls back to dvh, then vh — those work on desktop and on browsers - without the visualViewport API. The 85% factor leaves a margin - around the modal so it doesn't butt against the edges. */ + keyboard, when it's open). `vh` is the baseline for browsers without + dvh/custom-property-in-calc support; the @supports block below + upgrades browsers that have it. The 85% factor leaves a margin around + the modal so it doesn't butt against the edges. */ max-height: 85vh !important; - max-height: 85dvh !important; - max-height: calc(var(--csv-modal-vh, 100dvh) * 0.85) !important; +} +@supports (height: 100dvh) { + .csv-note-expander-modal { + max-height: calc(var(--csv-modal-vh, 100dvh) * 0.85) !important; + } } /* Mobile: dock the modal to the top of the visible viewport instead of @@ -1726,8 +1745,6 @@ td .csv-select-chip { display: flex; flex-direction: column; max-height: 85vh; - max-height: 85dvh; - max-height: calc(var(--csv-modal-vh, 100dvh) * 0.85); /* The modal-content itself scrolls when its body exceeds the keyboard- aware max-height. Combined with `position: sticky` on the footer, this guarantees the action bar stays reachable no matter what iOS does with @@ -1735,6 +1752,11 @@ td .csv-select-chip { overflow-y: auto; -webkit-overflow-scrolling: touch; } +@supports (height: 100dvh) { + .csv-note-expander-modal .modal-content { + max-height: calc(var(--csv-modal-vh, 100dvh) * 0.85); + } +} @media (max-width: 600px) { .csv-note-expander-modal .modal-content { @@ -2005,20 +2027,28 @@ td .csv-select-chip { } } +/* The `display: table*` declarations below guard against vault-wide CSS + snippets that force `table { display: block }` for markdown-table + overflow (a common Obsidian community fix). Scoping through the + `.csv-modal-colcfg-table-wrap` ancestor rather than relying on + `!important` keeps specificity ((0,2,1)+) high enough to win against a + bare/low-specificity snippet without fighting the cascade unconditionally. */ .csv-modal-colcfg-table { - display: table !important; width: 100%; border-collapse: collapse; font-size: 12px; } -.csv-modal-colcfg-table thead { - display: table-header-group !important; +.csv-modal-colcfg-table-wrap .csv-modal-colcfg-table { + display: table; } -.csv-modal-colcfg-table tbody { - display: table-row-group !important; +.csv-modal-colcfg-table-wrap .csv-modal-colcfg-table thead { + display: table-header-group; } -.csv-modal-colcfg-table tr { - display: table-row !important; +.csv-modal-colcfg-table-wrap .csv-modal-colcfg-table tbody { + display: table-row-group; +} +.csv-modal-colcfg-table-wrap .csv-modal-colcfg-table tr { + display: table-row; } .csv-modal-colcfg-table th { @@ -2032,16 +2062,20 @@ td .csv-select-chip { background: var(--background-secondary); border-bottom: 1px solid var(--csv-border); white-space: nowrap; - display: table-cell !important; +} +.csv-modal-colcfg-table-wrap .csv-modal-colcfg-table th { + display: table-cell; } .csv-modal-colcfg-table td { - display: table-cell !important; padding: 6px 8px; border-bottom: 1px solid var(--csv-border); white-space: nowrap; vertical-align: middle; } +.csv-modal-colcfg-table-wrap .csv-modal-colcfg-table td { + display: table-cell; +} .csv-modal-colcfg-table tbody tr:last-child td { border-bottom: none; @@ -2762,9 +2796,9 @@ td .csv-select-chip { white-space: nowrap; } -.csv-mobile-table th, -.csv-mobile-table td { - padding: 4px 8px !important; +.csv-mobile-table table th, +.csv-mobile-table table td { + padding: 4px 8px; font-size: 12px; } @@ -3958,7 +3992,8 @@ select.csv-add-row-control { .csv-tasks-table tr:last-child td { border-bottom: none; } .csv-tasks-table tbody tr:hover { background: var(--background-modifier-hover); } -.csv-tasks-check-cell { width: 22px; padding-right: 0 !important; } +.csv-tasks-table th.csv-tasks-check-cell, +.csv-tasks-table td.csv-tasks-check-cell { width: 22px; padding-right: 0; } .csv-tasks-check { display: inline-flex; align-items: center; diff --git a/versions.json b/versions.json index a145742..7e442c8 100644 --- a/versions.json +++ b/versions.json @@ -1,5 +1,6 @@ { "1.6.0": "1.4.0", "1.6.1": "1.4.0", - "1.7.0": "1.4.0" + "1.7.0": "1.4.0", + "1.7.1": "1.4.0" }