From 6cb2deccb227b86abee1463ed1d82c19f5a1b8d1 Mon Sep 17 00:00:00 2001 From: SVM0N <61781578+SVM0N@users.noreply.github.com> Date: Sat, 11 Jul 2026 15:32:30 +0000 Subject: [PATCH] feat(chart): Chart view + csv-chart block with best-fit and formula overlay MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New Chart view mode (scatter/line of any numeric column pair, X/Y pickers persisted per file) plus a csv-chart code block for embedding charts — or pure y=f(x) plots — in notes. Least-squares fit line with equation + R² (per-day trend phrasing on date X), formula overlay via a new eval-free expression parser (src/formula.ts). Chart.js lazy loader extracted from the dashboard into src/chartjs-loader.ts and shared by all three consumers. Co-Authored-By: Claude Fable 5 --- main.js | 39 ++-- main.ts | 12 + src/chart-block.ts | 201 +++++++++++++++++ src/chartjs-loader.ts | 23 ++ src/formula.ts | 176 +++++++++++++++ src/types.ts | 7 +- src/view/chart.ts | 402 ++++++++++++++++++++++++++++++++++ src/view/dashboard.ts | 16 +- src/view/toolbar.ts | 4 + styles.css | 79 +++++++ test-support/chartjs-stub.mjs | 16 +- test-view-smoke.mjs | 134 ++++++++++++ 12 files changed, 1072 insertions(+), 37 deletions(-) create mode 100644 src/chart-block.ts create mode 100644 src/chartjs-loader.ts create mode 100644 src/formula.ts create mode 100644 src/view/chart.ts diff --git a/main.js b/main.js index 51e949c..71c5b80 100644 --- a/main.js +++ b/main.js @@ -1,24 +1,24 @@ -"use strict";var Ql=Object.create;var ks=Object.defineProperty;var Zl=Object.getOwnPropertyDescriptor;var Jl=Object.getOwnPropertyNames;var tc=Object.getPrototypeOf,ec=Object.prototype.hasOwnProperty;var sc=(s,t,e)=>t in s?ks(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var li=(s,t)=>()=>(s&&(t=s(s=0)),t);var nc=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),Ao=(s,t)=>{for(var e in t)ks(s,e,{get:t[e],enumerable:!0})},Ro=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Jl(t))!ec.call(s,i)&&i!==e&&ks(s,i,{get:()=>t[i],enumerable:!(n=Zl(t,i))||n.enumerable});return s};var on=(s,t,e)=>(e=s!=null?Ql(tc(s)):{},Ro(t||!s||!s.__esModule?ks(e,"default",{value:s,enumerable:!0}):e,s)),ic=s=>Ro(ks({},"__esModule",{value:!0}),s);var j=(s,t,e)=>(sc(s,typeof t!="symbol"?t+"":t,e),e);var ws=nc((ci,di)=>{((s,t)=>{typeof define=="function"&&define.amd?define([],t):typeof di=="object"&&typeof ci!="undefined"?di.exports=t():s.Papa=t()})(ci,function s(){var t=typeof self!="undefined"?self:typeof window!="undefined"?window:t!==void 0?t:{},e,n=!t.document&&!!t.postMessage,i=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 _=C(v);_.chunkSize=parseInt(_.chunkSize),v.step||v.chunk||(_.chunkSize=null),this._handle=new f(_),(this._handle.streamer=this)._config=_}.call(this,y),this.parseChunk=function(v,_){var w=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview),i)t.postMessage({results:T,workerId:a.WORKER_ID,finished:w});else if(S(this._config.chunk)&&!_){if(this._config.chunk(T,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=T=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(T.data),this._completeResults.errors=this._completeResults.errors.concat(T.errors),this._completeResults.meta=T.meta),this._completed||!w||!S(this._config.complete)||T&&T.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),w||T&&T.meta.paused||this._nextChunk(),T}this._halted=!0},this._sendError=function(v){S(this._config.error)?this._config.error(v):i&&this._config.error&&t.postMessage({workerId:a.WORKER_ID,error:v,finished:!1})}}function c(y){var v;(y=y||{}).chunkSize||(y.chunkSize=a.RemoteChunkSize),l.call(this,y),this._nextChunk=n?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(_){this._input=_,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(v=new XMLHttpRequest,this._config.withCredentials&&(v.withCredentials=this._config.withCredentials),n||(v.onload=k(this._chunkLoaded,this),v.onerror=k(this._chunkError,this)),v.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var _,w=this._config.downloadRequestHeaders;for(_ in w)v.setRequestHeader(_,w[_])}var T;this._config.chunkSize&&(T=this._start+this._config.chunkSize-1,v.setRequestHeader("Range","bytes="+this._start+"-"+T));try{v.send(this._config.downloadRequestBody)}catch(E){this._chunkError(E.message)}n&&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>=(_=>(_=_.getResponseHeader("Content-Range"))!==null?parseInt(_.substring(_.lastIndexOf("/")+1)):-1)(v),this.parseChunk(v.responseText)))},this._chunkError=function(_){_=v.statusText||_,this._sendError(new Error(_))}}function d(y){(y=y||{}).chunkSize||(y.chunkSize=a.LocalChunkSize),l.call(this,y);var v,_,w=typeof FileReader!="undefined";this.stream=function(T){this._input=T,_=T.slice||T.webkitSlice||T.mozSlice,w?((v=new FileReader).onload=k(this._chunkLoaded,this),v.onerror=k(this._chunkError,this)):v=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(T.target.result)},this._chunkError=function(){this._sendError(v.error)}}function h(y){var v;l.call(this,y=y||{}),this.stream=function(_){return v=_,this._nextChunk()},this._nextChunk=function(){var _,w;if(!this._finished)return _=this._config.chunkSize,v=_?(w=v.substring(0,_),v.substring(_)):(w=v,""),this._finished=!v,this.parseChunk(w)}}function u(y){l.call(this,y=y||{});var v=[],_=!0,w=!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(T){this._input=T,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){w&&v.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),v.length?this.parseChunk(v.shift()):_=!0},this._streamData=k(function(T){try{v.push(typeof T=="string"?T:T.toString(this._config.encoding)),_&&(_=!1,this._checkIsFinished(),this.parseChunk(v.shift()))}catch(E){this._streamError(E)}},this),this._streamError=k(function(T){this._streamCleanUp(),this._sendError(T)},this),this._streamEnd=k(function(){this._streamCleanUp(),w=!0,this._streamData("")},this),this._streamCleanUp=k(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function f(y){var v,_,w,T,E=Math.pow(2,53),M=-E,L=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,I=/^((\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)))$/,F=this,R=0,D=0,W=!1,O=!1,K=[],z={data:[],errors:[],meta:{}};function A(P){return y.skipEmptyLines==="greedy"?P.join("").trim()==="":P.length===1&&P[0].length===0}function $(){if(z&&w&&(B("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),w=!1),y.skipEmptyLines&&(z.data=z.data.filter(function(U){return!A(U)})),G()){let U=function(Y,q){S(y.transformHeader)&&(Y=y.transformHeader(Y,q)),K.push(Y)};var V=U;if(z)if(Array.isArray(z.data[0])){for(var P=0;G()&&P(lt=>(y.dynamicTypingFunction&&y.dynamicTyping[lt]===void 0&&(y.dynamicTyping[lt]=y.dynamicTypingFunction(lt)),(y.dynamicTyping[lt]||y.dynamicTyping)===!0))(Q)?st==="true"||st==="TRUE"||st!=="false"&&st!=="FALSE"&&((lt=>{if(L.test(lt)&&(lt=parseFloat(lt),M=K.length?"__parsed_extra":K[X]:Z,at=y.transform?y.transform(at,Z):at);Z==="__parsed_extra"?(q[Z]=q[Z]||[],q[Z].push(at)):q[Z]=at}return y.header&&(X>K.length?B("FieldMismatch","TooManyFields","Too many fields: expected "+K.length+" fields but parsed "+X,D+Y):Xy.preview?_.abort():(z.data=z.data[0],T(z,F))))}),this.parse=function(P,N,H){var V=y.quoteChar||'"',V=(y.newline||(y.newline=this.guessLineEndings(P,V)),w=!1,y.delimiter?S(y.delimiter)&&(y.delimiter=y.delimiter(P),z.meta.delimiter=y.delimiter):((V=((U,Y,q,X,Z)=>{var at,Q,st,lt;Z=Z||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var $t=0;$tt in s?ws(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var fi=(s,t)=>()=>(s&&(t=s(s=0)),t);var _c=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),zo=(s,t)=>{for(var e in t)ws(s,e,{get:t[e],enumerable:!0})},Wo=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of vc(t))!xc.call(s,i)&&i!==e&&ws(s,i,{get:()=>t[i],enumerable:!(n=bc(t,i))||n.enumerable});return s};var an=(s,t,e)=>(e=s!=null?mc(yc(s)):{},Wo(t||!s||!s.__esModule?ws(e,"default",{value:s,enumerable:!0}):e,s)),Sc=s=>Wo(ws({},"__esModule",{value:!0}),s);var U=(s,t,e)=>(Cc(s,typeof t!="symbol"?t+"":t,e),e);var Ds=_c((pi,gi)=>{((s,t)=>{typeof define=="function"&&define.amd?define([],t):typeof gi=="object"&&typeof pi!="undefined"?gi.exports=t():s.Papa=t()})(pi,function s(){var t=typeof self!="undefined"?self:typeof window!="undefined"?window:t!==void 0?t:{},e,n=!t.document&&!!t.postMessage,i=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 _=C(v);_.chunkSize=parseInt(_.chunkSize),v.step||v.chunk||(_.chunkSize=null),this._handle=new f(_),(this._handle.streamer=this)._config=_}.call(this,y),this.parseChunk=function(v,_){var w=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview),i)t.postMessage({results:T,workerId:a.WORKER_ID,finished:w});else if(S(this._config.chunk)&&!_){if(this._config.chunk(T,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=T=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(T.data),this._completeResults.errors=this._completeResults.errors.concat(T.errors),this._completeResults.meta=T.meta),this._completed||!w||!S(this._config.complete)||T&&T.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),w||T&&T.meta.paused||this._nextChunk(),T}this._halted=!0},this._sendError=function(v){S(this._config.error)?this._config.error(v):i&&this._config.error&&t.postMessage({workerId:a.WORKER_ID,error:v,finished:!1})}}function c(y){var v;(y=y||{}).chunkSize||(y.chunkSize=a.RemoteChunkSize),l.call(this,y),this._nextChunk=n?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(_){this._input=_,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(v=new XMLHttpRequest,this._config.withCredentials&&(v.withCredentials=this._config.withCredentials),n||(v.onload=E(this._chunkLoaded,this),v.onerror=E(this._chunkError,this)),v.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var _,w=this._config.downloadRequestHeaders;for(_ in w)v.setRequestHeader(_,w[_])}var T;this._config.chunkSize&&(T=this._start+this._config.chunkSize-1,v.setRequestHeader("Range","bytes="+this._start+"-"+T));try{v.send(this._config.downloadRequestBody)}catch(k){this._chunkError(k.message)}n&&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>=(_=>(_=_.getResponseHeader("Content-Range"))!==null?parseInt(_.substring(_.lastIndexOf("/")+1)):-1)(v),this.parseChunk(v.responseText)))},this._chunkError=function(_){_=v.statusText||_,this._sendError(new Error(_))}}function d(y){(y=y||{}).chunkSize||(y.chunkSize=a.LocalChunkSize),l.call(this,y);var v,_,w=typeof FileReader!="undefined";this.stream=function(T){this._input=T,_=T.slice||T.webkitSlice||T.mozSlice,w?((v=new FileReader).onload=E(this._chunkLoaded,this),v.onerror=E(this._chunkError,this)):v=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(T.target.result)},this._chunkError=function(){this._sendError(v.error)}}function h(y){var v;l.call(this,y=y||{}),this.stream=function(_){return v=_,this._nextChunk()},this._nextChunk=function(){var _,w;if(!this._finished)return _=this._config.chunkSize,v=_?(w=v.substring(0,_),v.substring(_)):(w=v,""),this._finished=!v,this.parseChunk(w)}}function u(y){l.call(this,y=y||{});var v=[],_=!0,w=!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(T){this._input=T,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){w&&v.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),v.length?this.parseChunk(v.shift()):_=!0},this._streamData=E(function(T){try{v.push(typeof T=="string"?T:T.toString(this._config.encoding)),_&&(_=!1,this._checkIsFinished(),this.parseChunk(v.shift()))}catch(k){this._streamError(k)}},this),this._streamError=E(function(T){this._streamCleanUp(),this._sendError(T)},this),this._streamEnd=E(function(){this._streamCleanUp(),w=!0,this._streamData("")},this),this._streamCleanUp=E(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function f(y){var v,_,w,T,k=Math.pow(2,53),M=-k,L=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,I=/^((\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)))$/,P=this,R=0,D=0,W=!1,O=!1,j=[],$={data:[],errors:[],meta:{}};function A(F){return y.skipEmptyLines==="greedy"?F.join("").trim()==="":F.length===1&&F[0].length===0}function z(){if($&&w&&(B("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),w=!1),y.skipEmptyLines&&($.data=$.data.filter(function(K){return!A(K)})),G()){let K=function(Y,q){S(y.transformHeader)&&(Y=y.transformHeader(Y,q)),j.push(Y)};var V=K;if($)if(Array.isArray($.data[0])){for(var F=0;G()&&F<$.data.length;F++)$.data[F].forEach(K);$.data.splice(0,1)}else $.data.forEach(K)}function N(K,Y){for(var q=y.header?{}:[],X=0;X(lt=>(y.dynamicTypingFunction&&y.dynamicTyping[lt]===void 0&&(y.dynamicTyping[lt]=y.dynamicTypingFunction(lt)),(y.dynamicTyping[lt]||y.dynamicTyping)===!0))(Q)?st==="true"||st==="TRUE"||st!=="false"&&st!=="FALSE"&&((lt=>{if(L.test(lt)&&(lt=parseFloat(lt),M=j.length?"__parsed_extra":j[X]:Z,at=y.transform?y.transform(at,Z):at);Z==="__parsed_extra"?(q[Z]=q[Z]||[],q[Z].push(at)):q[Z]=at}return y.header&&(X>j.length?B("FieldMismatch","TooManyFields","Too many fields: expected "+j.length+" fields but parsed "+X,D+Y):Xy.preview?_.abort():($.data=$.data[0],T($,P))))}),this.parse=function(F,N,H){var V=y.quoteChar||'"',V=(y.newline||(y.newline=this.guessLineEndings(F,V)),w=!1,y.delimiter?S(y.delimiter)&&(y.delimiter=y.delimiter(F),$.meta.delimiter=y.delimiter):((V=((K,Y,q,X,Z)=>{var at,Q,st,lt;Z=Z||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var Wt=0;Wt=H.length/2?`\r -`:"\r"}}function g(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function p(y){var v=(y=y||{}).delimiter,_=y.newline,w=y.comments,T=y.step,E=y.preview,M=y.fastMode,L=null,I=!1,F=y.quoteChar==null?'"':y.quoteChar,R=F;if(y.escapeChar!==void 0&&(R=y.escapeChar),(typeof v!="string"||-1=E)return ft(!0);break}H.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:N.length,index:D}),Q++}}else if(w&&V.length===0&&O.substring(D,D+B)===w){if(Z===-1)return ft();D=Z+G,Z=O.indexOf(_,D),X=O.indexOf(v,D)}else if(X!==-1&&(X=E)return ft(!0)}return ot();function lt(yt){N.push(yt),U=D}function $t(yt){var wt=0;return wt=yt!==-1&&(yt=O.substring(Q+1,yt))&&yt.trim()===""?yt.length:wt}function ot(yt){return z||(yt===void 0&&(yt=O.substring(D)),V.push(yt),D=A,lt(V),P&&Yt()),ft()}function pt(yt){D=yt,lt(V),V=[],Z=O.indexOf(_,D)}function ft(yt){if(y.header&&!K&&N.length&&!I){var wt=N[0],oe=Object.create(null),ai=new Set(wt);let To=!1;for(let je=0;jew.charCodeAt(0)!==65279?w:w.slice(1))(y),_=new(v.download?c:h)(v)):y.readable===!0&&S(y.read)&&S(y.on)?_=new u(v):(t.File&&y instanceof File||y instanceof Object)&&(_=new d(v)),_.stream(y);(_=(()=>{var w;return!!a.WORKERS_SUPPORTED&&(w=(()=>{var T=t.URL||t.webkitURL||null,E=s.toString();return a.BLOB_URL||(a.BLOB_URL=T.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; ","(",E,")();"],{type:"text/javascript"})))})(),(w=new t.Worker(w)).onmessage=m,w.id=r++,o[w.id]=w)})()).userStep=v.step,_.userChunk=v.chunk,_.userComplete=v.complete,_.userError=v.error,v.step=S(v.step),v.chunk=S(v.chunk),v.complete=S(v.complete),v.error=S(v.error),delete v.worker,_.postMessage({input:y,config:v,workerId:_.id})},a.unparse=function(y,v){var _=!1,w=!0,T=",",E=`\r -`,M='"',L=M+M,I=!1,F=null,R=!1,D=((()=>{if(typeof v=="object"){if(typeof v.delimiter!="string"||a.BAD_DELIMITERS.filter(function(K){return v.delimiter.indexOf(K)!==-1}).length||(T=v.delimiter),typeof v.quotes!="boolean"&&typeof v.quotes!="function"&&!Array.isArray(v.quotes)||(_=v.quotes),typeof v.skipEmptyLines!="boolean"&&typeof v.skipEmptyLines!="string"||(I=v.skipEmptyLines),typeof v.newline=="string"&&(E=v.newline),typeof v.quoteChar=="string"&&(M=v.quoteChar),typeof v.header=="boolean"&&(w=v.header),Array.isArray(v.columns)){if(v.columns.length===0)throw new Error("Option columns is empty");F=v.columns}v.escapeChar!==void 0&&(L=v.escapeChar+M),v.escapeFormulae instanceof RegExp?R=v.escapeFormulae:typeof v.escapeFormulae=="boolean"&&v.escapeFormulae&&(R=/^[=+\-@\t\r].*$/)}})(),new RegExp(g(M),"g"));if(typeof y=="string"&&(y=JSON.parse(y)),Array.isArray(y)){if(!y.length||Array.isArray(y[0]))return W(null,y,I);if(typeof y[0]=="object")return W(F||Object.keys(y[0]),y,I)}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||F),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])),W(y.fields||[],y.data||[],I);throw new Error("Unable to serialize unrecognized input");function W(K,z,A){var $="",G=(typeof K=="string"&&(K=JSON.parse(K)),typeof z=="string"&&(z=JSON.parse(z)),Array.isArray(K)&&0{for(var P=0;Pe-n*Math.max(Math.min(r-3,9-r,1),-1);return[i(0),i(8),i(4)]}function Kc(s,t,e){let n=(i,o=(i+s/60)%6)=>e-e*t*Math.max(Math.min(o,4-o,1),0);return[n(5),n(3),n(1)]}function Yc(s,t,e){let n=xr(s,1,.5),i;for(t+e>1&&(i=1/(t+e),t*=i,e*=i),i=0;i<3;i++)n[i]*=1-t-e,n[i]+=t;return n}function Gc(s,t,e,n,i){return s===i?(t-e)/n+(t.5?d/(2-o-r):d/(o+r),l=Gc(e,n,i,d,o),l=l*60+.5),[l|0,c||0,a]}function ki(s,t,e,n){return(Array.isArray(t)?s(t[0],t[1],t[2]):s(t,e,n)).map(pe)}function wi(s,t,e){return ki(xr,s,t,e)}function qc(s,t,e){return ki(Yc,s,t,e)}function Xc(s,t,e){return ki(Kc,s,t,e)}function Cr(s){return(s%360+360)%360}function Qc(s){let t=Uc.exec(s),e=255,n;if(!t)return;t[5]!==n&&(e=t[6]?Is(+t[5]):pe(+t[5]));let i=Cr(+t[2]),o=+t[3]/100,r=+t[4]/100;return t[1]==="hwb"?n=qc(i,o,r):t[1]==="hsv"?n=Xc(i,o,r):n=wi(i,o,r),{r:n[0],g:n[1],b:n[2],a:e}}function Zc(s,t){var e=Ei(s);e[0]=Cr(e[0]+t),e=wi(e),s.r=e[0],s.g=e[1],s.b=e[2]}function Jc(s){if(!s)return;let t=Ei(s),e=t[0],n=mr(t[1]),i=mr(t[2]);return s.a<255?`hsla(${e}, ${n}%, ${i}%, ${re(s.a)})`:`hsl(${e}, ${n}%, ${i}%)`}function td(){let s={},t=Object.keys(vr),e=Object.keys(br),n,i,o,r,a;for(n=0;n>16&255,o>>8&255,o&255]}return s}function ed(s){Sn||(Sn=td(),Sn.transparent=[0,0,0,0]);let t=Sn[s.toLowerCase()];return t&&{r:t[0],g:t[1],b:t[2],a:t.length===4?t[3]:255}}function nd(s){let t=sd.exec(s),e=255,n,i,o;if(t){if(t[7]!==n){let r=+t[7];e=t[8]?Is(r):ge(r*255,0,255)}return n=+t[1],i=+t[3],o=+t[5],n=255&(t[2]?Is(n):ge(n,0,255)),i=255&(t[4]?Is(i):ge(i,0,255)),o=255&(t[6]?Is(o):ge(o,0,255)),{r:n,g:i,b:o,a:e}}}function id(s){return s&&(s.a<255?`rgba(${s.r}, ${s.g}, ${s.b}, ${re(s.a)})`:`rgb(${s.r}, ${s.g}, ${s.b})`)}function od(s,t,e){let n=ns(re(s.r)),i=ns(re(s.g)),o=ns(re(s.b));return{r:pe(_i(n+e*(ns(re(t.r))-n))),g:pe(_i(i+e*(ns(re(t.g))-i))),b:pe(_i(o+e*(ns(re(t.b))-o))),a:s.a+e*(t.a-s.a)}}function En(s,t,e){if(s){let n=Ei(s);n[t]=Math.max(0,Math.min(n[t]+n[t]*e,t===0?360:1)),n=wi(n),s.r=n[0],s.g=n[1],s.b=n[2]}}function _r(s,t){return s&&Object.assign(t||{},s)}function yr(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=pe(s[3]))):(t=_r(s,{r:0,g:0,b:0,a:1}),t.a=pe(t.a)),t}function rd(s){return s.charAt(0)==="r"?nd(s):Qc(s)}var ge,zt,Si,Bc,zc,_n,Hc,Wc,Uc,br,vr,Sn,sd,_i,ns,Fs,Sr=li(()=>{ge=(s,t,e)=>Math.max(Math.min(s,e),t);zt={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},Si=[..."0123456789ABCDEF"],Bc=s=>Si[s&15],zc=s=>Si[(s&240)>>4]+Si[s&15],_n=s=>(s&240)>>4===(s&15),Hc=s=>_n(s.r)&&_n(s.g)&&_n(s.b)&&_n(s.a);Wc=(s,t)=>s<255?t(s):"";Uc=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;br={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"},vr={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"};sd=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;_i=s=>s<=.0031308?s*12.92:Math.pow(s,1/2.4)*1.055-.055,ns=s=>s<=.04045?s/12.92:Math.pow((s+.055)/1.055,2.4);Fs=class s{constructor(t){if(t instanceof s)return t;let e=typeof t,n;e==="object"?n=yr(t):e==="string"&&(n=$c(t)||ed(t)||rd(t)),this._rgb=n,this._valid=!!n}get valid(){return this._valid}get rgb(){var t=_r(this._rgb);return t&&(t.a=re(t.a)),t}set rgb(t){this._rgb=yr(t)}rgbString(){return this._valid?id(this._rgb):void 0}hexString(){return this._valid?jc(this._rgb):void 0}hslString(){return this._valid?Jc(this._rgb):void 0}mix(t,e){if(t){let n=this.rgb,i=t.rgb,o,r=e===o?.5:e,a=2*r-1,l=n.a-i.a,c=((a*l===-1?a:(a+l)/(1+a*l))+1)/2;o=1-c,n.r=255&c*n.r+o*i.r+.5,n.g=255&c*n.g+o*i.g+.5,n.b=255&c*n.b+o*i.b+.5,n.a=r*n.a+(1-r)*i.a,this.rgb=n}return this}interpolate(t,e){return t&&(this._rgb=od(this._rgb,t._rgb,e)),this}clone(){return new s(this.rgb)}alpha(t){return this._rgb.a=pe(t),this}clearer(t){let e=this._rgb;return e.a*=1-t,this}greyscale(){let t=this._rgb,e=Vs(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 En(this._rgb,2,t),this}darken(t){return En(this._rgb,2,-t),this}saturate(t){return En(this._rgb,1,t),this}desaturate(t){return En(this._rgb,1,-t),this}rotate(t){return Zc(this._rgb,t),this}}});function Jt(){}function tt(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 et(s){return s!==null&&Object.prototype.toString.call(s)==="[object Object]"}function gt(s){return(typeof s=="number"||s instanceof Number)&&isFinite(+s)}function Mt(s,t){return gt(s)?s:t}function J(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 rt(s,t,e,n){let i,o,r;if(dt(s))if(o=s.length,n)for(i=o-1;i>=0;i--)t.call(e,s[i],i);else for(i=0;i{for(let n of t){if(n==="")break;e=e&&e[n]}return e}}function ce(s,t){return(Er[t]||(Er[t]=dd(t)))(s)}function Rn(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Vr(s){return s.type==="mouseup"||s.type==="click"||s.type==="contextmenu"}function cs(s,t,e){return Math.abs(s-t)i-o).pop(),t}function fd(s){return typeof s=="symbol"||typeof s=="object"&&s!==null&&!(Symbol.toPrimitive in s||"toString"in s||"valueOf"in s)}function Pe(s){return!fd(s)&&!isNaN(parseFloat(s))&&isFinite(s)}function Br(s,t){let e=Math.round(s);return e-t<=s&&e+t>=s}function Pi(s,t,e){let n,i,o;for(n=0,i=s.length;nl&&c=Math.min(t,e)-n&&s<=Math.max(t,e)+n}function On(s,t,e){e=e||(r=>s[r]1;)o=i+n>>1,e(o)?i=o:n=o;return{lo:i,hi:n}}function $r(s,t,e){let n=0,i=s.length;for(;nn&&s[i-1]>e;)i--;return n>0||i{let n="_onData"+Rn(e),i=s[e];Object.defineProperty(s,e,{configurable:!0,enumerable:!1,value(...o){let r=i.apply(this,o);return s._chartjs.listeners.forEach(a=>{typeof a[n]=="function"&&a[n](...o)}),r}})})}function Fi(s,t){let e=s._chartjs;if(!e)return;let n=e.listeners,i=n.indexOf(t);i!==-1&&n.splice(i,1),!(n.length>0)&&(Wr.forEach(o=>{delete s[o]}),delete s._chartjs)}function Vi(s){let t=new Set(s);return t.size===s.length?s:Array.from(t)}function Bi(s,t){let e=[],n=!1;return function(...i){e=i,n||(n=!0,Ni.call(window,()=>{n=!1,s.apply(t,e)}))}}function Ur(s,t){let e;return function(...n){return t?(clearTimeout(e),e=setTimeout(s,t,n)):s.apply(this,n),t}}function zi(s,t,e){let n=t.length,i=0,o=n;if(s._sorted){let{iScale:r,vScale:a,_parsed:l}=s,c=s.dataset&&s.dataset.options?s.dataset.options.spanGaps:null,d=r.axis,{min:h,max:u,minDefined:f,maxDefined:g}=r.getUserBounds();if(f){if(i=Math.min(Qt(l,d,h).lo,e?n:Qt(t,d,r.getPixelForValue(h)).lo),c){let p=l.slice(0,i+1).reverse().findIndex(m=>!tt(m[a.axis]));i-=Math.max(0,p)}i=vt(i,0,n-1)}if(g){let p=Math.max(Qt(l,r.axis,u,!0).hi+1,e?0:Qt(t,d,r.getPixelForValue(u),!0).hi+1);if(c){let m=l.slice(p-1).findIndex(b=>!tt(b[a.axis]));p+=Math.max(0,m)}o=vt(p,i,n)-i}else o=n-i}return{start:i,count:o}}function Hi(s){let{xScale:t,yScale:e,_scaleRanges:n}=s,i={xmin:t.min,xmax:t.max,ymin:e.min,ymax:e.max};if(!n)return s._scaleRanges=i,!0;let o=n.xmin!==t.min||n.xmax!==t.max||n.ymin!==e.min||n.ymax!==e.max;return Object.assign(n,i),o}function $i(s){if(s&&typeof s=="object"){let t=s.toString();return t==="[object CanvasPattern]"||t==="[object CanvasGradient]"}return!1}function Wi(s){return $i(s)?s:new Fs(s)}function Di(s){return $i(s)?s:new Fs(s).saturate(.5).darken(.1).hexString()}function bd(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:md},numbers:{type:"number",properties:pd}}),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 vd(s){s.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}function yd(s,t){t=t||{};let e=s+JSON.stringify(t),n=Mr.get(e);return n||(n=new Intl.NumberFormat(s,t),Mr.set(e,n)),n}function hs(s,t,e){return yd(t,e).format(s)}function xd(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 Cd(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:us.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 Ns(s,t){if(!t)return s;let e=t.split(".");for(let n=0,i=e.length;nn&&(n=o),n}function Gr(s,t,e,n){n=n||{};let i=n.data=n.data||{},o=n.garbageCollect=n.garbageCollect||[];n.font!==t&&(i=n.data={},o=n.garbageCollect=[],n.font=t),s.save(),s.font=t;let r=0,a=e.length,l,c,d,h,u;for(l=0;le.length){for(l=0;l0&&s.stroke()}}function Zt(s,t,e){return e=e||.5,!t||s&&s.x>t.left-e&&s.xt.top-e&&s.y0&&o.strokeColor!=="",l,c;for(s.save(),s.font=i.string,Sd(s,o),l=0;lJ(s[r],s[t[r]]):r=>s[r]:()=>s;for(let r of i)e[r]=Td(o(r));return e}function Ki(s){return Nn(s,{top:"y",right:"x",bottom:"y",left:"x"})}function Ce(s){return Nn(s,["topLeft","topRight","bottomLeft","bottomRight"])}function _t(s){let t=Ki(s);return t.width=t.left+t.right,t.height=t.top+t.bottom,t}function bt(s,t){s=s||{},t=t||ut.font;let e=J(s.size,t.size);typeof e=="string"&&(e=parseInt(e,10));let n=J(s.style,t.style);n&&!(""+n).match(Dd)&&(console.warn('Invalid font style specified: "'+n+'"'),n=void 0);let i={family:J(s.family,t.family),lineHeight:Md(J(s.lineHeight,t.lineHeight),e),size:e,style:n,weight:J(s.weight,t.weight),string:""};return i.string=_d(i),i}function gs(s,t,e,n){let i=!0,o,r,a;for(o=0,r=s.length;oe&&a===0?0:a+l;return{min:r(n,-Math.abs(o)),max:r(i,o)}}function de(s,t){return Object.assign(Object.create(s),t)}function Bn(s,t=[""],e,n,i=()=>s[0]){let o=e||s;typeof n=="undefined"&&(n=ta("_fallback",s));let r={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:s,_rootScopes:o,_fallback:n,_getTarget:i,override:a=>Bn([a,...s],t,o,n)};return new Proxy(r,{deleteProperty(a,l){return delete a[l],delete a._keys,delete s[0][l],!0},get(a,l){return Zr(a,l,()=>Vd(l,t,s,a))},getOwnPropertyDescriptor(a,l){return Reflect.getOwnPropertyDescriptor(a._scopes[0],l)},getPrototypeOf(){return Reflect.getPrototypeOf(s[0])},has(a,l){return Lr(a).includes(l)},ownKeys(a){return Lr(a)},set(a,l,c){let d=a._storage||(a._storage=i());return a[l]=d[l]=c,delete a._keys,!0}})}function Re(s,t,e,n){let i={_cacheable:!1,_proxy:s,_context:t,_subProxy:e,_stack:new Set,_descriptors:Yi(s,n),setContext:o=>Re(s,o,e,n),override:o=>Re(s.override(o),t,e,n)};return new Proxy(i,{deleteProperty(o,r){return delete o[r],delete s[r],!0},get(o,r,a){return Zr(o,r,()=>Ad(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 Yi(s,t={scriptable:!0,indexable:!0}){let{_scriptable:e=t.scriptable,_indexable:n=t.indexable,_allKeys:i=t.allKeys}=s;return{allKeys:i,scriptable:e,indexable:n,isScriptable:ae(e)?e:()=>e,isIndexable:ae(n)?n:()=>n}}function Zr(s,t,e){if(Object.prototype.hasOwnProperty.call(s,t)||t==="constructor")return s[t];let n=e();return s[t]=n,n}function Ad(s,t,e){let{_proxy:n,_context:i,_subProxy:o,_descriptors:r}=s,a=n[t];return ae(a)&&r.isScriptable(t)&&(a=Rd(t,a,s,e)),dt(a)&&a.length&&(a=Pd(t,a,s,r.isIndexable)),Gi(t,a)&&(a=Re(a,i,o&&o[t],r)),a}function Rd(s,t,e,n){let{_proxy:i,_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||n);return a.delete(s),Gi(s,l)&&(l=qi(i._scopes,i,s,l)),l}function Pd(s,t,e,n){let{_proxy:i,_context:o,_subProxy:r,_descriptors:a}=e;if(typeof o.index!="undefined"&&n(s))return t[o.index%t.length];if(et(t[0])){let l=t,c=i._scopes.filter(d=>d!==l);t=[];for(let d of l){let h=qi(c,i,s,d);t.push(Re(h,o,r&&r[s],a))}}return t}function Jr(s,t,e){return ae(s)?s(t,e):s}function Id(s,t,e,n,i){for(let o of t){let r=Od(e,o);if(r){s.add(r);let a=Jr(r._fallback,e,i);if(typeof a!="undefined"&&a!==e&&a!==n)return a}else if(r===!1&&typeof n!="undefined"&&e!==n)return null}return!1}function qi(s,t,e,n){let i=t._rootScopes,o=Jr(t._fallback,e,n),r=[...s,...i],a=new Set;a.add(n);let l=Tr(a,r,e,o||e,n);return l===null||typeof o!="undefined"&&o!==e&&(l=Tr(a,r,o,l,n),l===null)?!1:Bn(Array.from(a),[""],i,o,()=>Fd(t,e,n))}function Tr(s,t,e,n,i){for(;e;)e=Id(s,t,e,n,i);return e}function Fd(s,t,e){let n=s._getTarget();t in n||(n[t]={});let i=n[t];return dt(i)&&et(e)?e:i||{}}function Vd(s,t,e,n){let i;for(let o of t)if(i=ta(Ld(o,s),e),typeof i!="undefined")return Gi(s,i)?qi(e,n,s,i):i}function ta(s,t){for(let e of t){if(!e)continue;let n=e[s];if(typeof n!="undefined")return n}}function Lr(s){let t=s._keys;return t||(t=s._keys=Nd(s._scopes)),t}function Nd(s){let t=new Set;for(let e of s)for(let n of Object.keys(e).filter(i=>!i.startsWith("_")))t.add(n);return Array.from(t)}function Xi(s,t,e,n){let{iScale:i}=s,{key:o="r"}=this._parsing,r=new Array(n),a,l,c,d;for(a=0,l=n;a!c.skip)),t.cubicInterpolationMode==="monotone")Wd(s,i);else{let c=n?s[s.length-1]:s[0];for(o=0,r=s.length;ol.height&&(d=l.height,c=be(Math.floor(d*n))),{width:c,height:d}}function Qi(s,t,e){let n=t||1,i=be(s.height*n),o=be(s.width*n);s.height=be(s.height),s.width=be(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!==n||r.height!==i||r.width!==o?(s.currentDevicePixelRatio=n,r.height=i,r.width=o,s.ctx.setTransform(n,0,0,n,0,0),!0):!1}function Zi(s,t){let e=Ud(s,t),n=e&&e.match(/^(\d+)(\.\d+)?px$/);return n?+n[1]:void 0}function me(s,t,e,n){return{x:s.x+e*(t.x-s.x),y:s.y+e*(t.y-s.y)}}function oa(s,t,e,n){return{x:s.x+e*(t.x-s.x),y:n==="middle"?e<.5?s.y:t.y:n==="after"?e<1?s.y:t.y:e>0?t.y:s.y}}function ra(s,t,e,n){let i={x:s.cp2x,y:s.cp2y},o={x:t.cp1x,y:t.cp1y},r=me(s,i,e),a=me(i,o,e),l=me(o,t,e),c=me(r,a,e),d=me(a,l,e);return me(c,d,e)}function Oe(s,t,e){return s?Xd(t,e):Qd()}function Ji(s,t){let e,n;(t==="ltr"||t==="rtl")&&(e=s.canvas.style,n=[e.getPropertyValue("direction"),e.getPropertyPriority("direction")],e.setProperty("direction",t,"important"),s.prevTextDirection=n)}function to(s,t){t!==void 0&&(delete s.prevTextDirection,s.canvas.style.setProperty("direction",t[0],t[1]))}function aa(s){return s==="angle"?{between:ds,compare:gd,normalize:xt}:{between:te,compare:(t,e)=>t-e,normalize:t=>t}}function Ar({start:s,end:t,count:e,loop:n,style:i}){return{start:s%e,end:t%e,loop:n&&(t-s+1)%e===0,style:i}}function Zd(s,t,e){let{property:n,start:i,end:o}=e,{between:r,normalize:a}=aa(n),l=t.length,{start:c,end:d,loop:h}=s,u,f;if(h){for(c+=l,d+=l,u=0,f=l;ul(i,C,b)&&a(i,C)!==0,S=()=>a(o,b)===0||l(o,C,b),y=()=>p||k(),v=()=>!p||S();for(let _=d,w=d;_<=h;++_)x=t[_%r],!x.skip&&(b=c(x[n]),b!==C&&(p=l(b,i,o),m===null&&y()&&(m=a(b,i)===0?_:w),m!==null&&v()&&(g.push(Ar({start:m,end:_,loop:u,count:r,style:f})),m=null),w=_,C=b));return m!==null&&g.push(Ar({start:m,end:h,loop:u,count:r,style:f})),g}function so(s,t){let e=[],n=s.segments;for(let i=0;ii&&s[o%t].skip;)o--;return o%=t,{start:i,end:o}}function th(s,t,e,n){let i=s.length,o=[],r=t,a=s[t],l;for(l=t+1;l<=e;++l){let c=s[l%i];c.skip||c.stop?a.skip||(n=!1,o.push({start:t%i,end:(l-1)%i,loop:n}),t=r=c.stop?l:null):(r=l,a.skip&&(t=l)),a=c}return r!==null&&o.push({start:t%i,end:r%i,loop:n}),o}function la(s,t){let e=s.points,n=s.options.spanGaps,i=e.length;if(!i)return[];let o=!!s._loop,{start:r,end:a}=Jd(e,i,o,n);if(n===!0)return Rr(s,[{start:r,end:a,loop:o}],e,t);let l=a{Sr();Or=(()=>{let s=0;return()=>s++})();Ir=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100:+s/t,Li=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100*t:+s;Er={"":s=>s,x:s=>s.x,y:s=>s.y};ls=s=>typeof s!="undefined",ae=s=>typeof s=="function",Ai=(s,t)=>{if(s.size!==t.size)return!1;for(let e of s)if(!t.has(e))return!1;return!0};nt=Math.PI,ht=2*nt,hd=ht+nt,Tn=Number.POSITIVE_INFINITY,ud=nt/180,mt=nt/2,Le=nt/4,kr=nt*2/3,le=Math.log10,jt=Math.sign;Qt=(s,t,e,n)=>On(s,e,n?i=>{let o=s[i][t];return os[i][t]On(s,e,n=>s[n][t]>=e);Wr=["push","pop","shift","splice","unshift"];Ni=function(){return typeof window=="undefined"?function(s){return s()}:window.requestAnimationFrame}();In=s=>s==="start"?"left":s==="end"?"right":"center",Ct=(s,t,e)=>s==="start"?t:s==="end"?e:(t+e)/2,Kr=(s,t,e,n)=>s===(n?"left":"right")?e:s==="center"?(t+e)/2:t;kn=s=>s===0||s===1,wr=(s,t,e)=>-(Math.pow(2,10*(s-=1))*Math.sin((s-t)*ht/e)),Dr=(s,t,e)=>Math.pow(2,-10*s)*Math.sin((s-t)*ht/e)+1,is={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*mt)+1,easeOutSine:s=>Math.sin(s*mt),easeInOutSine:s=>-.5*(Math.cos(nt*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=>kn(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=>kn(s)?s:wr(s,.075,.3),easeOutElastic:s=>kn(s)?s:Dr(s,.075,.3),easeInOutElastic(s){return kn(s)?s:s<.5?.5*wr(s*2,.1125,.45):.5+.5*Dr(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-is.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?is.easeInBounce(s*2)*.5:is.easeOutBounce(s*2-1)*.5+.5};pd=["x","y","borderWidth","radius","tension"],md=["color","borderColor","backgroundColor"];Mr=new Map;Yr={values(s){return dt(s)?s:""+s},numeric(s,t,e){if(s===0)return"0";let n=this.chart.options.locale,i,o=s;if(e.length>1){let c=Math.max(Math.abs(e[0].value),Math.abs(e[e.length-1].value));(c<1e-4||c>1e15)&&(i="scientific"),o=xd(s,e)}let r=le(Math.abs(o)),a=isNaN(r)?1:Math.max(Math.min(-1*Math.floor(r),20),0),l={notation:i,minimumFractionDigits:a,maximumFractionDigits:a};return Object.assign(l,this.options.ticks.format),hs(s,n,l)},logarithmic(s,t,e){if(s===0)return"0";let n=e[t].significand||s/Math.pow(10,Math.floor(le(s)));return[1,2,3,5,10,15].includes(n)||t>.8*e.length?Yr.numeric.call(this,s,t,e):""}};us={formatters:Yr};ve=Object.create(null),Fn=Object.create(null);Ti=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=n=>n.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=(n,i)=>Di(i.backgroundColor),this.hoverBorderColor=(n,i)=>Di(i.borderColor),this.hoverColor=(n,i)=>Di(i.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 Mi(this,t,e)}get(t){return Ns(this,t)}describe(t,e){return Mi(Fn,t,e)}override(t,e){return Mi(ve,t,e)}route(t,e,n,i){let o=Ns(this,t),r=Ns(this,n),a="_"+e;Object.defineProperties(o,{[a]:{value:o[e],writable:!0},[e]:{enumerable:!0,get(){let l=this[a],c=r[i];return et(l)?Object.assign({},c,l):J(l,c)},set(l){this[a]=l}}})}apply(t){t.forEach(e=>e(this))}},ut=new Ti({_scriptable:s=>!s.startsWith("on"),_indexable:s=>s!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[bd,vd,Cd]);wd=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,Dd=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;Td=s=>+s||0;Ld=(s,t)=>s?s+Rn(t):t,Gi=(s,t)=>et(t)&&s!=="adapters"&&(Object.getPrototypeOf(t)===null||t.constructor===Object);Od=(s,t)=>s===!0?t:typeof s=="string"?ce(t,s):void 0;Bd=Number.EPSILON||1e-14,rs=(s,t)=>ts==="x"?"y":"x";$n=s=>s.ownerDocument.defaultView.getComputedStyle(s,null);Kd=["top","right","bottom","left"];Yd=(s,t,e)=>(s>0||t>0)&&(!e||!e.shadowRoot);be=s=>Math.round(s*10)/10;ia=function(){let s=!1;try{let t={get passive(){return s=!0,!1}};zn()&&(window.addEventListener("test",null,t),window.removeEventListener("test",null,t))}catch(t){}return s}();Xd=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,n){return e-n},leftForLtr(e,n){return e-n}}},Qd=function(){return{x(s){return s},setWidth(s){},textAlign(s){return s},xPlus(s,t){return s+t},leftForLtr(s,t){return s}}}});var Wl={};Ao(Wl,{Animation:()=>Qn,Animations:()=>Qs,ArcElement:()=>Se,BarController:()=>Ve,BarElement:()=>We,BasePlatform:()=>Zs,BasicPlatform:()=>Zn,BubbleController:()=>Ne,CategoryScale:()=>vs,Chart:()=>ne,Colors:()=>Tl,DatasetController:()=>Lt,Decimation:()=>Al,DomPlatform:()=>ti,DoughnutController:()=>ie,Element:()=>Rt,Filler:()=>Pl,Interaction:()=>fl,Legend:()=>Il,LineController:()=>Be,LineElement:()=>Kt,LinearScale:()=>ys,LogarithmicScale:()=>xs,PieController:()=>ms,PointElement:()=>$e,PolarAreaController:()=>ke,RadarController:()=>ze,RadialLinearScale:()=>Ee,Scale:()=>Me,ScatterController:()=>He,SubTitle:()=>Vl,Ticks:()=>us,TimeScale:()=>De,TimeSeriesScale:()=>Cs,Title:()=>Fl,Tooltip:()=>Bl,_adapters:()=>ul,_detectPlatform:()=>vl,animator:()=>se,controllers:()=>hl,defaults:()=>ut,elements:()=>wl,layouts:()=>St,plugins:()=>zl,registerables:()=>ig,registry:()=>Ut,scales:()=>$l});function oh(s,t){let e=[],n=Object.keys(t);for(let i=0;i0||!e&&o<0)return i.index}return null}function ga(s,t){let{chart:e,_cachedMeta:n}=s,i=e._stacks||(e._stacks={}),{iScale:o,vScale:r,index:a}=n,l=o.axis,c=r.axis,d=dh(o,r,n),h=t.length,u;for(let f=0;fe[n].axis===t).shift()}function fh(s,t){return de(s,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function gh(s,t,e){return de(s,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:e,index:t,mode:"default",type:"data"})}function Ws(s,t){let e=s.controller.index,n=s.vScale&&s.vScale.axis;if(n){t=t||s._parsed;for(let i of t){let o=i._stacks;if(!o||o[n]===void 0||o[n][e]===void 0)return;delete o[n][e],o[n]._visualValues!==void 0&&o[n]._visualValues[e]!==void 0&&delete o[n]._visualValues[e]}}}function mh(s,t){if(!s._cache.$bar){let e=s.getMatchingVisibleMetas(t),n=[];for(let i=0,o=e.length;ii-o))}return s._cache.$bar}function bh(s){let t=s.iScale,e=mh(t,s.type),n=t._length,i,o,r,a,l=()=>{r===32767||r===-32768||(ls(a)&&(n=Math.min(n,Math.abs(r-a)||n)),a=r)};for(i=0,o=e.length;i0?i[s-1]:null,a=sMath.abs(a)&&(l=a,c=r),t[e.axis]=c,t._custom={barStart:l,barEnd:c,start:i,end:o,min:r,max:a}}function dl(s,t,e,n){return dt(s)?xh(s,t,e,n):t[e.axis]=e.parse(s,n),t}function ma(s,t,e,n){let i=s.iScale,o=s.vScale,r=i.getLabels(),a=i===o,l=[],c,d,h,u;for(c=e,d=e+n;c=e?1:-1)}function _h(s){let t,e,n,i,o;return s.horizontal?(t=s.base>s.x,e="left",n="right"):(t=s.baseds(C,a,l,!0)?1:Math.max(k,k*e,S,S*e),g=(C,k,S)=>ds(C,a,l,!0)?-1:Math.min(k,k*e,S,S*e),p=f(0,c,h),m=f(mt,d,u),b=g(nt,c,h),x=g(nt+mt,d,u);n=(p-b)/2,i=(m-x)/2,o=-(p+b)/2,r=-(m+x)/2}return{ratioX:n,ratioY:i,offsetX:o,offsetY:r}}function Ie(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}function Dh(s,t,e,n){let{controller:i,data:o,_sorted:r}=s,a=i._cachedMeta.iScale,l=s.dataset&&s.dataset.options?s.dataset.options.spanGaps:null;if(a&&t===a.axis&&t!=="r"&&r&&o.length){let c=a._reversePixels?Hr:Qt;if(n){if(i._sharedOptions){let d=o[0],h=typeof d.getRange=="function"&&d.getRange(t);if(h){let u=c(o,t,e-h),f=c(o,t,e+h);return{lo:u.lo,hi:f.hi}}}}else{let d=c(o,t,e);if(l){let{vScale:h}=i._cachedMeta,{_parsed:u}=s,f=u.slice(0,d.lo+1).reverse().findIndex(p=>!tt(p[h.axis]));d.lo-=Math.max(0,f);let g=u.slice(d.hi).findIndex(p=>!tt(p[h.axis]));d.hi+=Math.max(0,g)}return d}}return{lo:0,hi:o.length-1}}function sn(s,t,e,n,i){let o=s.getSortedVisibleDatasetMetas(),r=e[t];for(let a=0,l=o.length;a{l[r]&&l[r](t[e],i)&&(o.push({element:l,datasetIndex:c,index:d}),a=a||l.inRange(t.x,t.y,i))}),n&&!a?[]:o}function js(s,t){return s.filter(e=>e.pos===t)}function xa(s,t){return s.filter(e=>gl.indexOf(e.pos)===-1&&e.box.axis===t)}function Us(s,t){return s.sort((e,n)=>{let i=t?n:e,o=t?e:n;return i.weight===o.weight?i.index-o.index:i.weight-o.weight})}function Ah(s){let t=[],e,n,i,o,r,a;for(e=0,n=(s||[]).length;ec.box.fullSize),!0),n=Us(js(t,"left"),!0),i=Us(js(t,"right")),o=Us(js(t,"top"),!0),r=Us(js(t,"bottom")),a=xa(t,"x"),l=xa(t,"y");return{fullSize:e,leftAndTop:n.concat(o),rightAndBottom:i.concat(l).concat(r).concat(a),chartArea:js(t,"chartArea"),vertical:n.concat(i).concat(l),horizontal:o.concat(r).concat(a)}}function Ca(s,t,e,n){return Math.max(s[e],t[e])+Math.max(s[n],t[n])}function pl(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 Ih(s,t,e,n){let{pos:i,box:o}=e,r=s.maxPadding;if(!et(i)){e.size&&(s[i]-=e.size);let h=n[e.stack]||{size:0,count:1};h.size=Math.max(h.size,e.horizontal?o.height:o.width),e.size=h.size/h.count,s[i]+=e.size}o.getPadding&&pl(r,o.getPadding());let a=Math.max(0,t.outerWidth-Ca(r,s,"left","right")),l=Math.max(0,t.outerHeight-Ca(r,s,"top","bottom")),c=a!==s.w,d=l!==s.h;return s.w=a,s.h=l,e.horizontal?{same:c,other:d}:{same:d,other:c}}function Fh(s){let t=s.maxPadding;function e(n){let i=Math.max(t[n]-s[n],0);return s[n]+=i,i}s.y+=e("top"),s.x+=e("left"),e("right"),e("bottom")}function Vh(s,t){let e=t.maxPadding;function n(i){let o={left:0,top:0,right:0,bottom:0};return i.forEach(r=>{o[r]=Math.max(t[r],e[r])}),o}return n(s?["left","right"]:["top","bottom"])}function Gs(s,t,e,n){let i=[],o,r,a,l,c,d;for(o=0,r=s.length,c=0;o{let r=!1;for(let a of o)r=r||Jn(a.addedNodes,n),r=r&&!Jn(a.removedNodes,n);r&&e()});return i.observe(document,{childList:!0,subtree:!0}),i}function jh(s,t,e){let n=s.canvas,i=new MutationObserver(o=>{let r=!1;for(let a of o)r=r||Jn(a.removedNodes,n),r=r&&!Jn(a.addedNodes,n);r&&e()});return i.observe(document,{childList:!0,subtree:!0}),i}function bl(){let s=window.devicePixelRatio;s!==Ea&&(Ea=s,Js.forEach((t,e)=>{e.currentDevicePixelRatio!==s&&t()}))}function Uh(s,t){Js.size||window.addEventListener("resize",bl),Js.set(s,t)}function Kh(s){Js.delete(s),Js.size||window.removeEventListener("resize",bl)}function Yh(s,t,e){let n=s.canvas,i=n&&Hn(n);if(!i)return;let o=Bi((a,l)=>{let c=i.clientWidth;e(a,l),c{let l=a[0],c=l.contentRect.width,d=l.contentRect.height;c===0&&d===0||o(c,d)});return r.observe(i),Uh(s,o),r}function ho(s,t,e){e&&e.disconnect(),t==="resize"&&Kh(s)}function Gh(s,t,e){let n=s.canvas,i=Bi(o=>{s.ctx!==null&&e($h(o,s))},s);return zh(n,t,i),i}function vl(s){return!zn()||typeof OffscreenCanvas!="undefined"&&s instanceof OffscreenCanvas?Zn:ti}function qh(s,t){let e=s.options.ticks,n=Xh(s),i=Math.min(e.maxTicksLimit||n,n),o=e.major.enabled?Zh(t):[],r=o.length,a=o[0],l=o[r-1],c=[];if(r>i)return Jh(t,c,o,r/i),c;let d=Qh(o,t,i);if(r>0){let h,u,f=r>1?Math.round((l-a)/(r-1)):null;for(jn(t,c,d,tt(f)?0:a-f,a),h=0,u=r-1;hi)return l}return Math.max(i,1)}function Zh(s){let t=[],e,n;for(e=0,n=s.length;er+a)))return l}function nu(s,t){rt(s,e=>{let n=e.gc,i=n.length/2,o;if(i>t){for(o=0;o{let n=e.split("."),i=n.pop(),o=[s].concat(n).join("."),r=t[e].split("."),a=r.pop(),l=r.join(".");ut.route(o,i,l,a)})}function du(s){return"id"in s&&"defaults"in s}function hu(s){let t={},e=[],n=Object.keys(Ut.plugins.items);for(let o=0;o1&&Ta(s[0].toLowerCase());if(n)return n}throw new Error(`Cannot determine type of '${s}' axis. Please provide 'axis' or 'position' option.`)}function La(s,t,e){if(e[t+"AxisID"]===s)return{axis:t}}function vu(s,t){if(t.data&&t.data.datasets){let e=t.data.datasets.filter(n=>n.xAxisID===s||n.yAxisID===s);if(e.length)return La(s,"x",e[0])||La(s,"y",e[0])}return{}}function yu(s,t){let e=ve[s.type]||{scales:{}},n=t.scales||{},i=xo(s.type,t),o=Object.create(null);return Object.keys(n).forEach(r=>{let a=n[r];if(!et(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=Co(r,a,vu(r,s),ut.scales[a.type]),c=mu(l,i),d=e.scales||{};o[r]=as(Object.create(null),[{axis:l},a,d[l],d[c]])}),s.data.datasets.forEach(r=>{let a=r.type||s.type,l=r.indexAxis||xo(a,t),d=(ve[a]||{}).scales||{};Object.keys(d).forEach(h=>{let u=pu(h,l),f=r[u+"AxisID"]||u;o[f]=o[f]||Object.create(null),as(o[f],[{axis:u},n[f],d[h]])})}),Object.keys(o).forEach(r=>{let a=o[r];as(a,[ut.scales[a.type],ut.scale])}),o}function yl(s){let t=s.options||(s.options={});t.plugins=J(t.plugins,{}),t.scales=yu(s,t)}function xl(s){return s=s||{},s.datasets=s.datasets||[],s.labels=s.labels||[],s}function xu(s){return s=s||{},s.data=xl(s.data),yl(s),s}function Un(s,t){let e=Aa.get(s);return e||(e=t(),Aa.set(s,e),Cl.add(e)),e}function Ra(s,t,e){let n=s.get(t);n||(n=new Map,s.set(t,n));let i=e.join(),o=n.get(i);return o||(o={resolver:Bn(t,e),subPrefixes:e.filter(a=>!a.toLowerCase().includes("hover"))},n.set(i,o)),o}function _u(s,t){let{isScriptable:e,isIndexable:n}=Yi(s);for(let i of t){let o=e(i),r=n(i),a=(r||o)&&s[i];if(o&&(ae(a)||Cu(a))||r&&dt(a))return!0}return!1}function Pa(s,t){return s==="top"||s==="bottom"||Eu.indexOf(s)===-1&&t==="x"}function Oa(s,t){return function(e,n){return e[s]===n[s]?e[t]-n[t]:e[s]-n[s]}}function Ia(s){let t=s.chart,e=t.options.animation;t.notifyPlugins("afterRender"),ct(e&&e.onComplete,[s],t)}function ku(s){let t=s.chart,e=t.options.animation;ct(e&&e.onProgress,[s],t)}function _l(s){return zn()&&typeof s=="string"?s=document.getElementById(s):s&&s.length&&(s=s[0]),s&&s.canvas&&(s=s.canvas),s}function wu(s,t,e){let n=Object.keys(s);for(let i of n){let o=+i;if(o>=t){let r=s[i];delete s[i],(e>0||o>t)&&(s[o+e]=r)}}}function Du(s,t,e,n){return!e||s.type==="mouseout"?null:n?t:s}function Va(){return rt(ne.instances,s=>s._plugins.invalidate())}function Mu(s,t,e){let{startAngle:n,x:i,y:o,outerRadius:r,innerRadius:a,options:l}=t,{borderWidth:c,borderJoinStyle:d}=l,h=Math.min(c/r,xt(n-e));if(s.beginPath(),s.arc(i,o,r-c/2,n+h/2,e-h/2),a>0){let u=Math.min(c/a,xt(n-e));s.arc(i,o,a+c/2,e-u/2,n+u/2,!0)}else{let u=Math.min(c/2,r*xt(n-e));if(d==="round")s.arc(i,o,u,e-nt/2,n+nt/2,!0);else if(d==="bevel"){let f=2*u*u,g=-f*Math.cos(e+nt/2)+i,p=-f*Math.sin(e+nt/2)+o,m=f*Math.cos(n+nt/2)+i,b=f*Math.sin(n+nt/2)+o;s.lineTo(g,p),s.lineTo(m,b)}}s.closePath(),s.moveTo(0,0),s.rect(0,0,s.canvas.width,s.canvas.height),s.clip("evenodd")}function Tu(s,t,e){let{startAngle:n,pixelMargin:i,x:o,y:r,outerRadius:a,innerRadius:l}=t,c=i/a;s.beginPath(),s.arc(o,r,a,n-c,e+c),l>i?(c=i/l,s.arc(o,r,l,e+c,n-c,!0)):s.arc(o,r,i,e+mt,n-mt),s.closePath(),s.clip()}function Lu(s){return Nn(s,["outerStart","outerEnd","innerStart","innerEnd"])}function Au(s,t,e,n){let i=Lu(s.options.borderRadius),o=(e-t)/2,r=Math.min(o,n*t/2),a=l=>{let c=(e-Math.min(o,l))*n/2;return vt(l,0,Math.min(o,c))};return{outerStart:a(i.outerStart),outerEnd:a(i.outerEnd),innerStart:vt(i.innerStart,0,r),innerEnd:vt(i.innerEnd,0,r)}}function ps(s,t,e,n){return{x:e+s*Math.cos(t),y:n+s*Math.sin(t)}}function ei(s,t,e,n,i,o){let{x:r,y:a,startAngle:l,pixelMargin:c,innerRadius:d}=t,h=Math.max(t.outerRadius+n+e-c,0),u=d>0?d+n+e+c:0,f=0,g=i-l;if(n){let F=d>0?d-n:0,R=h>0?h-n:0,D=(F+R)/2,W=D!==0?g*D/(D+n):g;f=(g-W)/2}let p=Math.max(.001,g*h-e/nt)/h,m=(g-p)/2,b=l+m+f,x=i-m-f,{outerStart:C,outerEnd:k,innerStart:S,innerEnd:y}=Au(t,u,h,x-b),v=h-C,_=h-k,w=b+C/v,T=x-k/_,E=u+S,M=u+y,L=b+S/E,I=x-y/M;if(s.beginPath(),o){let F=(w+T)/2;if(s.arc(r,a,h,w,F),s.arc(r,a,h,F,T),k>0){let O=ps(_,T,r,a);s.arc(O.x,O.y,k,T,x+mt)}let R=ps(M,x,r,a);if(s.lineTo(R.x,R.y),y>0){let O=ps(M,I,r,a);s.arc(O.x,O.y,y,x+mt,I+Math.PI)}let D=(x-y/u+(b+S/u))/2;if(s.arc(r,a,u,x-y/u,D,!0),s.arc(r,a,u,D,b+S/u,!0),S>0){let O=ps(E,L,r,a);s.arc(O.x,O.y,S,L+Math.PI,b-mt)}let W=ps(v,b,r,a);if(s.lineTo(W.x,W.y),C>0){let O=ps(v,w,r,a);s.arc(O.x,O.y,C,b-mt,w)}}else{s.moveTo(r,a);let F=Math.cos(w)*h+r,R=Math.sin(w)*h+a;s.lineTo(F,R);let D=Math.cos(T)*h+r,W=Math.sin(T)*h+a;s.lineTo(D,W)}s.closePath()}function Ru(s,t,e,n,i){let{fullCircles:o,startAngle:r,circumference:a}=t,l=t.endAngle;if(o){ei(s,t,e,n,l,i);for(let c=0;c=nt&&f===0&&d!=="miter"&&Mu(s,t,p),o||(ei(s,t,e,n,p,i),s.stroke())}function Sl(s,t,e=t){s.lineCap=J(e.borderCapStyle,t.borderCapStyle),s.setLineDash(J(e.borderDash,t.borderDash)),s.lineDashOffset=J(e.borderDashOffset,t.borderDashOffset),s.lineJoin=J(e.borderJoinStyle,t.borderJoinStyle),s.lineWidth=J(e.borderWidth,t.borderWidth),s.strokeStyle=J(e.borderColor,t.borderColor)}function Ou(s,t,e){s.lineTo(e.x,e.y)}function Iu(s){return s.stepped?qr:s.tension||s.cubicInterpolationMode==="monotone"?Xr:Ou}function El(s,t,e={}){let n=s.length,{start:i=0,end:o=n-1}=e,{start:r,end:a}=t,l=Math.max(i,r),c=Math.min(o,a),d=ia&&o>a;return{count:n,start:l,loop:t.loop,ilen:c(r+(c?a-k:k))%o,C=()=>{p!==m&&(s.lineTo(d,m),s.lineTo(d,p),s.lineTo(d,b))};for(l&&(f=i[x(0)],s.moveTo(f.x,f.y)),u=0;u<=a;++u){if(f=i[x(u)],f.skip)continue;let k=f.x,S=f.y,y=k|0;y===g?(Sm&&(m=S),d=(h*d+k)/++h):(C(),s.lineTo(k,S),g=y,h=0,p=m=S),b=S}C()}function So(s){let t=s.options,e=t.borderDash&&t.borderDash.length;return!s._decimated&&!s._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!e?Vu:Fu}function Nu(s){return s.stepped?oa:s.tension||s.cubicInterpolationMode==="monotone"?ra:me}function Bu(s,t,e,n){let i=t._path;i||(i=t._path=new Path2D,t.path(i,e,n)&&i.closePath()),Sl(s,t.options),s.stroke(i)}function zu(s,t,e,n){let{segments:i,options:o}=t,r=So(t);for(let a of i)Sl(s,o,a.style),s.beginPath(),r(s,t,a,{start:e,end:e+n-1})&&s.closePath(),s.stroke()}function $u(s,t,e,n){Hu&&!t.options.segment?Bu(s,t,e,n):zu(s,t,e,n)}function Na(s,t,e,n){let i=s.options,{[e]:o}=s.getProps([e],n);return Math.abs(t-o)Dl(t++)),t}function Xu(s,t){return s.backgroundColor=s.data.map(()=>Ml(t++)),t}function Qu(s){let t=0;return(e,n)=>{let i=s.getDatasetMeta(n).controller;i instanceof ie?t=qu(e,t):i instanceof ke?t=Xu(e,t):i&&(t=Gu(e,t))}}function za(s){let t;for(t in s)if(s[t].borderColor||s[t].backgroundColor)return!0;return!1}function Zu(s){return s&&(s.borderColor||s.backgroundColor)}function Ju(){return ut.borderColor!=="rgba(0,0,0,0.1)"||ut.backgroundColor!=="rgba(0,0,0,0.1)"}function tf(s,t,e,n,i){let o=i.samples||n;if(o>=e)return s.slice(t,t+e);let r=[],a=(e-2)/(o-2),l=0,c=t+e-1,d=t,h,u,f,g,p;for(r[l++]=s[d],h=0;hf&&(f=g,u=s[x],p=x);r[l++]=u,d=p}return r[l++]=s[c],r}function ef(s,t,e,n){let i=0,o=0,r,a,l,c,d,h,u,f,g,p,m=[],b=t+e-1,x=s[t].x,k=s[b].x-x;for(r=t;rp&&(p=c,u=r),i=(o*i+a.x)/++o;else{let y=r-1;if(!tt(h)&&!tt(u)){let v=Math.min(h,u),_=Math.max(h,u);v!==f&&v!==y&&m.push({...s[v],x:i}),_!==f&&_!==y&&m.push({...s[_],x:i})}r>0&&y!==f&&m.push(s[y]),m.push(a),d=S,o=0,g=p=c,h=u=f=r}}return m}function Ll(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 Ha(s){s.data.datasets.forEach(t=>{Ll(t)})}function sf(s,t){let e=t.length,n=0,i,{iScale:o}=s,{min:r,max:a,minDefined:l,maxDefined:c}=o.getUserBounds();return l&&(n=vt(Qt(t,o.axis,r).lo,0,e-1)),c?i=vt(Qt(t,o.axis,a).hi+1,n,e)-n:i=e-n,{start:n,count:i}}function nf(s,t,e){let n=s.segments,i=s.points,o=t.points,r=[];for(let a of n){let{start:l,end:c}=a;c=ii(l,c,i);let d=ko(e,i[l],i[c],a.loop);if(!t.segments){r.push({source:a,target:d,start:i[l],end:i[c]});continue}let h=so(t,d);for(let u of h){let f=ko(e,o[u.start],o[u.end],u.loop),g=eo(a,i,f);for(let p of g)r.push({source:p,target:u,start:{[e]:$a(d,f,"start",Math.max)},end:{[e]:$a(d,f,"end",Math.min)}})}}return r}function ko(s,t,e,n){if(n)return;let i=t[s],o=e[s];return s==="angle"&&(i=xt(i),o=xt(o)),{property:s,start:i,end:o}}function of(s,t){let{x:e=null,y:n=null}=s||{},i=t.points,o=[];return t.segments.forEach(({start:r,end:a})=>{a=ii(r,a,i);let l=i[r],c=i[a];n!==null?(o.push({x:l.x,y:n}),o.push({x:c.x,y:n})):e!==null&&(o.push({x:e,y:l.y}),o.push({x:e,y:c.y}))}),o}function ii(s,t,e){for(;t>s;t--){let n=e[t];if(!isNaN(n.x)&&!isNaN(n.y))break}return t}function $a(s,t,e,n){return s&&t?n(s[e],t[e]):s?s[e]:t?t[e]:0}function Rl(s,t){let e=[],n=!1;return dt(s)?(n=!0,e=s):e=of(s,t),e.length?new Kt({points:e,options:{tension:0},_loop:n,_fullLoop:n}):null}function Wa(s){return s&&s.fill!==!1}function rf(s,t,e){let i=s[t].fill,o=[t],r;if(!e)return i;for(;i!==!1&&o.indexOf(i)===-1;){if(!gt(i))return i;if(r=s[i],!r)return!1;if(r.visible)return i;o.push(i),i=r.fill}return!1}function af(s,t,e){let n=hf(s);if(et(n))return isNaN(n.value)?!1:n;let i=parseFloat(n);return gt(i)&&Math.floor(i)===i?lf(n[0],t,i,e):["origin","start","end","stack","shape"].indexOf(n)>=0&&n}function lf(s,t,e,n){return(s==="-"||s==="+")&&(e=t+e),e===t||e<0||e>=n?!1:e}function cf(s,t){let e=null;return s==="start"?e=t.bottom:s==="end"?e=t.top:et(s)?e=t.getPixelForValue(s.value):t.getBasePixel&&(e=t.getBasePixel()),e}function df(s,t,e){let n;return s==="start"?n=e:s==="end"?n=t.options.reverse?t.min:t.max:et(s)?n=s.value:n=t.getBaseValue(),n}function hf(s){let t=s.options,e=t.fill,n=J(e&&e.target,e);return n===void 0&&(n=!!t.backgroundColor),n===!1||n===null?!1:n===!0?"origin":n}function uf(s){let{scale:t,index:e,line:n}=s,i=[],o=n.segments,r=n.points,a=ff(t,e);a.push(Rl({x:null,y:t.bottom},n));for(let l=0;lo.length>r.length?o:r)),t+e.size/2+n.measureText(i).width}function wf(s,t,e){let n=s;return typeof t.text!="string"&&(n=Ol(t,e)),n}function Ol(s,t){let e=s.text?s.text.length:0;return t*e}function Df(s,t){return!!((s==="mousemove"||s==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(s==="click"||s==="mouseup"))}function Mf(s,t){let e=new tn({ctx:s.ctx,options:t,chart:s});St.configure(s,e,t),St.addBox(s,e),s.titleBlock=e}function ee(s,t){return t&&(dt(t)?Array.prototype.push.apply(s,t):s.push(t)),s}function he(s){return(typeof s=="string"||s instanceof String)&&s.indexOf(` +`);var D=0,W=!1;this.parse=function(O,j,$){if(typeof O!="string")throw new Error("Input must be a string");var A=O.length,z=v.length,G=_.length,B=w.length,F=S(T),N=[],H=[],V=[],K=D=0;if(!O)return ft();if(M||M!==!1&&O.indexOf(P)===-1){for(var Y=O.split(_),q=0;q=k)return ft(!0);break}H.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:N.length,index:D}),Q++}}else if(w&&V.length===0&&O.substring(D,D+B)===w){if(Z===-1)return ft();D=Z+G,Z=O.indexOf(_,D),X=O.indexOf(v,D)}else if(X!==-1&&(X=k)return ft(!0)}return ot();function lt(yt){N.push(yt),K=D}function Wt(yt){var Dt=0;return Dt=yt!==-1&&(yt=O.substring(Q+1,yt))&&yt.trim()===""?yt.length:Dt}function ot(yt){return $||(yt===void 0&&(yt=O.substring(D)),V.push(yt),D=A,lt(V),F&&Gt()),ft()}function gt(yt){D=yt,lt(V),V=[],Z=O.indexOf(_,D)}function ft(yt){if(y.header&&!j&&N.length&&!I){var Dt=N[0],oe=Object.create(null),ui=new Set(Dt);let $o=!1;for(let Ue=0;Uew.charCodeAt(0)!==65279?w:w.slice(1))(y),_=new(v.download?c:h)(v)):y.readable===!0&&S(y.read)&&S(y.on)?_=new u(v):(t.File&&y instanceof File||y instanceof Object)&&(_=new d(v)),_.stream(y);(_=(()=>{var w;return!!a.WORKERS_SUPPORTED&&(w=(()=>{var T=t.URL||t.webkitURL||null,k=s.toString();return a.BLOB_URL||(a.BLOB_URL=T.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; ","(",k,")();"],{type:"text/javascript"})))})(),(w=new t.Worker(w)).onmessage=m,w.id=r++,o[w.id]=w)})()).userStep=v.step,_.userChunk=v.chunk,_.userComplete=v.complete,_.userError=v.error,v.step=S(v.step),v.chunk=S(v.chunk),v.complete=S(v.complete),v.error=S(v.error),delete v.worker,_.postMessage({input:y,config:v,workerId:_.id})},a.unparse=function(y,v){var _=!1,w=!0,T=",",k=`\r +`,M='"',L=M+M,I=!1,P=null,R=!1,D=((()=>{if(typeof v=="object"){if(typeof v.delimiter!="string"||a.BAD_DELIMITERS.filter(function(j){return v.delimiter.indexOf(j)!==-1}).length||(T=v.delimiter),typeof v.quotes!="boolean"&&typeof v.quotes!="function"&&!Array.isArray(v.quotes)||(_=v.quotes),typeof v.skipEmptyLines!="boolean"&&typeof v.skipEmptyLines!="string"||(I=v.skipEmptyLines),typeof v.newline=="string"&&(k=v.newline),typeof v.quoteChar=="string"&&(M=v.quoteChar),typeof v.header=="boolean"&&(w=v.header),Array.isArray(v.columns)){if(v.columns.length===0)throw new Error("Option columns is empty");P=v.columns}v.escapeChar!==void 0&&(L=v.escapeChar+M),v.escapeFormulae instanceof RegExp?R=v.escapeFormulae:typeof v.escapeFormulae=="boolean"&&v.escapeFormulae&&(R=/^[=+\-@\t\r].*$/)}})(),new RegExp(p(M),"g"));if(typeof y=="string"&&(y=JSON.parse(y)),Array.isArray(y)){if(!y.length||Array.isArray(y[0]))return W(null,y,I);if(typeof y[0]=="object")return W(P||Object.keys(y[0]),y,I)}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||P),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])),W(y.fields||[],y.data||[],I);throw new Error("Unable to serialize unrecognized input");function W(j,$,A){var z="",G=(typeof j=="string"&&(j=JSON.parse(j)),typeof $=="string"&&($=JSON.parse($)),Array.isArray(j)&&0{for(var F=0;Fe-n*Math.max(Math.min(r-3,9-r,1),-1);return[i(0),i(8),i(4)]}function nd(s,t,e){let n=(i,o=(i+s/60)%6)=>e-e*t*Math.max(Math.min(o,4-o,1),0);return[n(5),n(3),n(1)]}function id(s,t,e){let n=Er(s,1,.5),i;for(t+e>1&&(i=1/(t+e),t*=i,e*=i),i=0;i<3;i++)n[i]*=1-t-e,n[i]+=t;return n}function od(s,t,e,n,i){return s===i?(t-e)/n+(t.5?d/(2-o-r):d/(o+r),l=od(e,n,i,d,o),l=l*60+.5),[l|0,c||0,a]}function Mi(s,t,e,n){return(Array.isArray(t)?s(t[0],t[1],t[2]):s(t,e,n)).map(me)}function Ti(s,t,e){return Mi(Er,s,t,e)}function rd(s,t,e){return Mi(id,s,t,e)}function ad(s,t,e){return Mi(nd,s,t,e)}function kr(s){return(s%360+360)%360}function ld(s){let t=sd.exec(s),e=255,n;if(!t)return;t[5]!==n&&(e=t[6]?Is(+t[5]):me(+t[5]));let i=kr(+t[2]),o=+t[3]/100,r=+t[4]/100;return t[1]==="hwb"?n=rd(i,o,r):t[1]==="hsv"?n=ad(i,o,r):n=Ti(i,o,r),{r:n[0],g:n[1],b:n[2],a:e}}function cd(s,t){var e=Di(s);e[0]=kr(e[0]+t),e=Ti(e),s.r=e[0],s.g=e[1],s.b=e[2]}function dd(s){if(!s)return;let t=Di(s),e=t[0],n=xr(t[1]),i=xr(t[2]);return s.a<255?`hsla(${e}, ${n}%, ${i}%, ${re(s.a)})`:`hsl(${e}, ${n}%, ${i}%)`}function hd(){let s={},t=Object.keys(_r),e=Object.keys(Cr),n,i,o,r,a;for(n=0;n>16&255,o>>8&255,o&255]}return s}function ud(s){Cn||(Cn=hd(),Cn.transparent=[0,0,0,0]);let t=Cn[s.toLowerCase()];return t&&{r:t[0],g:t[1],b:t[2],a:t.length===4?t[3]:255}}function pd(s){let t=fd.exec(s),e=255,n,i,o;if(t){if(t[7]!==n){let r=+t[7];e=t[8]?Is(r):ge(r*255,0,255)}return n=+t[1],i=+t[3],o=+t[5],n=255&(t[2]?Is(n):ge(n,0,255)),i=255&(t[4]?Is(i):ge(i,0,255)),o=255&(t[6]?Is(o):ge(o,0,255)),{r:n,g:i,b:o,a:e}}}function gd(s){return s&&(s.a<255?`rgba(${s.r}, ${s.g}, ${s.b}, ${re(s.a)})`:`rgb(${s.r}, ${s.g}, ${s.b})`)}function md(s,t,e){let n=ss(re(s.r)),i=ss(re(s.g)),o=ss(re(s.b));return{r:me(ki(n+e*(ss(re(t.r))-n))),g:me(ki(i+e*(ss(re(t.g))-i))),b:me(ki(o+e*(ss(re(t.b))-o))),a:s.a+e*(t.a-s.a)}}function _n(s,t,e){if(s){let n=Di(s);n[t]=Math.max(0,Math.min(n[t]+n[t]*e,t===0?360:1)),n=Ti(n),s.r=n[0],s.g=n[1],s.b=n[2]}}function wr(s,t){return s&&Object.assign(t||{},s)}function Sr(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=me(s[3]))):(t=wr(s,{r:0,g:0,b:0,a:1}),t.a=me(t.a)),t}function bd(s){return s.charAt(0)==="r"?pd(s):ld(s)}var ge,Ht,wi,Xc,Qc,xn,Zc,td,sd,Cr,_r,Cn,fd,ki,ss,Vs,Dr=fi(()=>{ge=(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},wi=[..."0123456789ABCDEF"],Xc=s=>wi[s&15],Qc=s=>wi[(s&240)>>4]+wi[s&15],xn=s=>(s&240)>>4===(s&15),Zc=s=>xn(s.r)&&xn(s.g)&&xn(s.b)&&xn(s.a);td=(s,t)=>s<255?t(s):"";sd=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;Cr={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"},_r={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"};fd=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;ki=s=>s<=.0031308?s*12.92:Math.pow(s,1/2.4)*1.055-.055,ss=s=>s<=.04045?s/12.92:Math.pow((s+.055)/1.055,2.4);Vs=class s{constructor(t){if(t instanceof s)return t;let e=typeof t,n;e==="object"?n=Sr(t):e==="string"&&(n=Jc(t)||ud(t)||bd(t)),this._rgb=n,this._valid=!!n}get valid(){return this._valid}get rgb(){var t=wr(this._rgb);return t&&(t.a=re(t.a)),t}set rgb(t){this._rgb=Sr(t)}rgbString(){return this._valid?gd(this._rgb):void 0}hexString(){return this._valid?ed(this._rgb):void 0}hslString(){return this._valid?dd(this._rgb):void 0}mix(t,e){if(t){let n=this.rgb,i=t.rgb,o,r=e===o?.5:e,a=2*r-1,l=n.a-i.a,c=((a*l===-1?a:(a+l)/(1+a*l))+1)/2;o=1-c,n.r=255&c*n.r+o*i.r+.5,n.g=255&c*n.g+o*i.g+.5,n.b=255&c*n.b+o*i.b+.5,n.a=r*n.a+(1-r)*i.a,this.rgb=n}return this}interpolate(t,e){return t&&(this._rgb=md(this._rgb,t._rgb,e)),this}clone(){return new s(this.rgb)}alpha(t){return this._rgb.a=me(t),this}clearer(t){let e=this._rgb;return e.a*=1-t,this}greyscale(){let t=this._rgb,e=Ns(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 _n(this._rgb,2,t),this}darken(t){return _n(this._rgb,2,-t),this}saturate(t){return _n(this._rgb,1,t),this}desaturate(t){return _n(this._rgb,1,-t),this}rotate(t){return cd(this._rgb,t),this}}});function Jt(){}function tt(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 et(s){return s!==null&&Object.prototype.toString.call(s)==="[object Object]"}function pt(s){return(typeof s=="number"||s instanceof Number)&&isFinite(+s)}function Tt(s,t){return pt(s)?s:t}function J(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 rt(s,t,e,n){let i,o,r;if(dt(s))if(o=s.length,n)for(i=o-1;i>=0;i--)t.call(e,s[i],i);else for(i=0;i{for(let n of t){if(n==="")break;e=e&&e[n]}return e}}function ce(s,t){return(Mr[t]||(Mr[t]=Cd(t)))(s)}function Ln(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Hr(s){return s.type==="mouseup"||s.type==="click"||s.type==="contextmenu"}function ls(s,t,e){return Math.abs(s-t)i-o).pop(),t}function Ed(s){return typeof s=="symbol"||typeof s=="object"&&s!==null&&!(Symbol.toPrimitive in s||"toString"in s||"valueOf"in s)}function Oe(s){return!Ed(s)&&!isNaN(parseFloat(s))&&isFinite(s)}function Wr(s,t){let e=Math.round(s);return e-t<=s&&e+t>=s}function Ii(s,t,e){let n,i,o;for(n=0,i=s.length;nl&&c=Math.min(t,e)-n&&s<=Math.max(t,e)+n}function Pn(s,t,e){e=e||(r=>s[r]1;)o=i+n>>1,e(o)?i=o:n=o;return{lo:i,hi:n}}function Kr(s,t,e){let n=0,i=s.length;for(;nn&&s[i-1]>e;)i--;return n>0||i{let n="_onData"+Ln(e),i=s[e];Object.defineProperty(s,e,{configurable:!0,enumerable:!1,value(...o){let r=i.apply(this,o);return s._chartjs.listeners.forEach(a=>{typeof a[n]=="function"&&a[n](...o)}),r}})})}function Bi(s,t){let e=s._chartjs;if(!e)return;let n=e.listeners,i=n.indexOf(t);i!==-1&&n.splice(i,1),!(n.length>0)&&(Yr.forEach(o=>{delete s[o]}),delete s._chartjs)}function $i(s){let t=new Set(s);return t.size===s.length?s:Array.from(t)}function zi(s,t){let e=[],n=!1;return function(...i){e=i,n||(n=!0,Hi.call(window,()=>{n=!1,s.apply(t,e)}))}}function qr(s,t){let e;return function(...n){return t?(clearTimeout(e),e=setTimeout(s,t,n)):s.apply(this,n),t}}function Wi(s,t,e){let n=t.length,i=0,o=n;if(s._sorted){let{iScale:r,vScale:a,_parsed:l}=s,c=s.dataset&&s.dataset.options?s.dataset.options.spanGaps:null,d=r.axis,{min:h,max:u,minDefined:f,maxDefined:p}=r.getUserBounds();if(f){if(i=Math.min(Qt(l,d,h).lo,e?n:Qt(t,d,r.getPixelForValue(h)).lo),c){let g=l.slice(0,i+1).reverse().findIndex(m=>!tt(m[a.axis]));i-=Math.max(0,g)}i=vt(i,0,n-1)}if(p){let g=Math.max(Qt(l,r.axis,u,!0).hi+1,e?0:Qt(t,d,r.getPixelForValue(u),!0).hi+1);if(c){let m=l.slice(g-1).findIndex(b=>!tt(b[a.axis]));g+=Math.max(0,m)}o=vt(g,i,n)-i}else o=n-i}return{start:i,count:o}}function ji(s){let{xScale:t,yScale:e,_scaleRanges:n}=s,i={xmin:t.min,xmax:t.max,ymin:e.min,ymax:e.max};if(!n)return s._scaleRanges=i,!0;let o=n.xmin!==t.min||n.xmax!==t.max||n.ymin!==e.min||n.ymax!==e.max;return Object.assign(n,i),o}function Ui(s){if(s&&typeof s=="object"){let t=s.toString();return t==="[object CanvasPattern]"||t==="[object CanvasGradient]"}return!1}function Ki(s){return Ui(s)?s:new Vs(s)}function Li(s){return Ui(s)?s:new Vs(s).saturate(.5).darken(.1).hexString()}function Md(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:Dd},numbers:{type:"number",properties:wd}}),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 Td(s){s.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}function Ld(s,t){t=t||{};let e=s+JSON.stringify(t),n=Pr.get(e);return n||(n=new Intl.NumberFormat(s,t),Pr.set(e,n)),n}function ds(s,t,e){return Ld(t,e).format(s)}function Ad(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 Pd(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:hs.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 Bs(s,t){if(!t)return s;let e=t.split(".");for(let n=0,i=e.length;nn&&(n=o),n}function Zr(s,t,e,n){n=n||{};let i=n.data=n.data||{},o=n.garbageCollect=n.garbageCollect||[];n.font!==t&&(i=n.data={},o=n.garbageCollect=[],n.font=t),s.save(),s.font=t;let r=0,a=e.length,l,c,d,h,u;for(l=0;le.length){for(l=0;l0&&s.stroke()}}function Zt(s,t,e){return e=e||.5,!t||s&&s.x>t.left-e&&s.xt.top-e&&s.y0&&o.strokeColor!=="",l,c;for(s.save(),s.font=i.string,Od(s,o),l=0;lJ(s[r],s[t[r]]):r=>s[r]:()=>s;for(let r of i)e[r]=$d(o(r));return e}function qi(s){return In(s,{top:"y",right:"x",bottom:"y",left:"x"})}function _e(s){return In(s,["topLeft","topRight","bottomLeft","bottomRight"])}function _t(s){let t=qi(s);return t.width=t.left+t.right,t.height=t.top+t.bottom,t}function bt(s,t){s=s||{},t=t||ut.font;let e=J(s.size,t.size);typeof e=="string"&&(e=parseInt(e,10));let n=J(s.style,t.style);n&&!(""+n).match(Nd)&&(console.warn('Invalid font style specified: "'+n+'"'),n=void 0);let i={family:J(s.family,t.family),lineHeight:Bd(J(s.lineHeight,t.lineHeight),e),size:e,style:n,weight:J(s.weight,t.weight),string:""};return i.string=Rd(i),i}function fs(s,t,e,n){let i=!0,o,r,a;for(o=0,r=s.length;oe&&a===0?0:a+l;return{min:r(n,-Math.abs(o)),max:r(i,o)}}function de(s,t){return Object.assign(Object.create(s),t)}function Vn(s,t=[""],e,n,i=()=>s[0]){let o=e||s;typeof n=="undefined"&&(n=ia("_fallback",s));let r={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:s,_rootScopes:o,_fallback:n,_getTarget:i,override:a=>Vn([a,...s],t,o,n)};return new Proxy(r,{deleteProperty(a,l){return delete a[l],delete a._keys,delete s[0][l],!0},get(a,l){return sa(a,l,()=>Gd(l,t,s,a))},getOwnPropertyDescriptor(a,l){return Reflect.getOwnPropertyDescriptor(a._scopes[0],l)},getPrototypeOf(){return Reflect.getPrototypeOf(s[0])},has(a,l){return Or(a).includes(l)},ownKeys(a){return Or(a)},set(a,l,c){let d=a._storage||(a._storage=i());return a[l]=d[l]=c,delete a._keys,!0}})}function Re(s,t,e,n){let i={_cacheable:!1,_proxy:s,_context:t,_subProxy:e,_stack:new Set,_descriptors:Xi(s,n),setContext:o=>Re(s,o,e,n),override:o=>Re(s.override(o),t,e,n)};return new Proxy(i,{deleteProperty(o,r){return delete o[r],delete s[r],!0},get(o,r,a){return sa(o,r,()=>zd(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 Xi(s,t={scriptable:!0,indexable:!0}){let{_scriptable:e=t.scriptable,_indexable:n=t.indexable,_allKeys:i=t.allKeys}=s;return{allKeys:i,scriptable:e,indexable:n,isScriptable:ae(e)?e:()=>e,isIndexable:ae(n)?n:()=>n}}function sa(s,t,e){if(Object.prototype.hasOwnProperty.call(s,t)||t==="constructor")return s[t];let n=e();return s[t]=n,n}function zd(s,t,e){let{_proxy:n,_context:i,_subProxy:o,_descriptors:r}=s,a=n[t];return ae(a)&&r.isScriptable(t)&&(a=Wd(t,a,s,e)),dt(a)&&a.length&&(a=jd(t,a,s,r.isIndexable)),Qi(t,a)&&(a=Re(a,i,o&&o[t],r)),a}function Wd(s,t,e,n){let{_proxy:i,_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||n);return a.delete(s),Qi(s,l)&&(l=Zi(i._scopes,i,s,l)),l}function jd(s,t,e,n){let{_proxy:i,_context:o,_subProxy:r,_descriptors:a}=e;if(typeof o.index!="undefined"&&n(s))return t[o.index%t.length];if(et(t[0])){let l=t,c=i._scopes.filter(d=>d!==l);t=[];for(let d of l){let h=Zi(c,i,s,d);t.push(Re(h,o,r&&r[s],a))}}return t}function na(s,t,e){return ae(s)?s(t,e):s}function Kd(s,t,e,n,i){for(let o of t){let r=Ud(e,o);if(r){s.add(r);let a=na(r._fallback,e,i);if(typeof a!="undefined"&&a!==e&&a!==n)return a}else if(r===!1&&typeof n!="undefined"&&e!==n)return null}return!1}function Zi(s,t,e,n){let i=t._rootScopes,o=na(t._fallback,e,n),r=[...s,...i],a=new Set;a.add(n);let l=Rr(a,r,e,o||e,n);return l===null||typeof o!="undefined"&&o!==e&&(l=Rr(a,r,o,l,n),l===null)?!1:Vn(Array.from(a),[""],i,o,()=>Yd(t,e,n))}function Rr(s,t,e,n,i){for(;e;)e=Kd(s,t,e,n,i);return e}function Yd(s,t,e){let n=s._getTarget();t in n||(n[t]={});let i=n[t];return dt(i)&&et(e)?e:i||{}}function Gd(s,t,e,n){let i;for(let o of t)if(i=ia(Hd(o,s),e),typeof i!="undefined")return Qi(s,i)?Zi(e,n,s,i):i}function ia(s,t){for(let e of t){if(!e)continue;let n=e[s];if(typeof n!="undefined")return n}}function Or(s){let t=s._keys;return t||(t=s._keys=qd(s._scopes)),t}function qd(s){let t=new Set;for(let e of s)for(let n of Object.keys(e).filter(i=>!i.startsWith("_")))t.add(n);return Array.from(t)}function Ji(s,t,e,n){let{iScale:i}=s,{key:o="r"}=this._parsing,r=new Array(n),a,l,c,d;for(a=0,l=n;a!c.skip)),t.cubicInterpolationMode==="monotone")th(s,i);else{let c=n?s[s.length-1]:s[0];for(o=0,r=s.length;ol.height&&(d=l.height,c=ve(Math.floor(d*n))),{width:c,height:d}}function to(s,t,e){let n=t||1,i=ve(s.height*n),o=ve(s.width*n);s.height=ve(s.height),s.width=ve(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!==n||r.height!==i||r.width!==o?(s.currentDevicePixelRatio=n,r.height=i,r.width=o,s.ctx.setTransform(n,0,0,n,0,0),!0):!1}function eo(s,t){let e=sh(s,t),n=e&&e.match(/^(\d+)(\.\d+)?px$/);return n?+n[1]:void 0}function be(s,t,e,n){return{x:s.x+e*(t.x-s.x),y:s.y+e*(t.y-s.y)}}function ca(s,t,e,n){return{x:s.x+e*(t.x-s.x),y:n==="middle"?e<.5?s.y:t.y:n==="after"?e<1?s.y:t.y:e>0?t.y:s.y}}function da(s,t,e,n){let i={x:s.cp2x,y:s.cp2y},o={x:t.cp1x,y:t.cp1y},r=be(s,i,e),a=be(i,o,e),l=be(o,t,e),c=be(r,a,e),d=be(a,l,e);return be(c,d,e)}function Fe(s,t,e){return s?ah(t,e):lh()}function so(s,t){let e,n;(t==="ltr"||t==="rtl")&&(e=s.canvas.style,n=[e.getPropertyValue("direction"),e.getPropertyPriority("direction")],e.setProperty("direction",t,"important"),s.prevTextDirection=n)}function no(s,t){t!==void 0&&(delete s.prevTextDirection,s.canvas.style.setProperty("direction",t[0],t[1]))}function ha(s){return s==="angle"?{between:cs,compare:kd,normalize:xt}:{between:te,compare:(t,e)=>t-e,normalize:t=>t}}function Fr({start:s,end:t,count:e,loop:n,style:i}){return{start:s%e,end:t%e,loop:n&&(t-s+1)%e===0,style:i}}function ch(s,t,e){let{property:n,start:i,end:o}=e,{between:r,normalize:a}=ha(n),l=t.length,{start:c,end:d,loop:h}=s,u,f;if(h){for(c+=l,d+=l,u=0,f=l;ul(i,C,b)&&a(i,C)!==0,S=()=>a(o,b)===0||l(o,C,b),y=()=>g||E(),v=()=>!g||S();for(let _=d,w=d;_<=h;++_)x=t[_%r],!x.skip&&(b=c(x[n]),b!==C&&(g=l(b,i,o),m===null&&y()&&(m=a(b,i)===0?_:w),m!==null&&v()&&(p.push(Fr({start:m,end:_,loop:u,count:r,style:f})),m=null),w=_,C=b));return m!==null&&p.push(Fr({start:m,end:h,loop:u,count:r,style:f})),p}function oo(s,t){let e=[],n=s.segments;for(let i=0;ii&&s[o%t].skip;)o--;return o%=t,{start:i,end:o}}function hh(s,t,e,n){let i=s.length,o=[],r=t,a=s[t],l;for(l=t+1;l<=e;++l){let c=s[l%i];c.skip||c.stop?a.skip||(n=!1,o.push({start:t%i,end:(l-1)%i,loop:n}),t=r=c.stop?l:null):(r=l,a.skip&&(t=l)),a=c}return r!==null&&o.push({start:t%i,end:r%i,loop:n}),o}function ua(s,t){let e=s.points,n=s.options.spanGaps,i=e.length;if(!i)return[];let o=!!s._loop,{start:r,end:a}=dh(e,i,o,n);if(n===!0)return Ir(s,[{start:r,end:a,loop:o}],e,t);let l=a{Dr();Nr=(()=>{let s=0;return()=>s++})();Br=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100:+s/t,Ri=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100*t:+s;Mr={"":s=>s,x:s=>s.x,y:s=>s.y};as=s=>typeof s!="undefined",ae=s=>typeof s=="function",Oi=(s,t)=>{if(s.size!==t.size)return!1;for(let e of s)if(!t.has(e))return!1;return!0};nt=Math.PI,ht=2*nt,_d=ht+nt,Dn=Number.POSITIVE_INFINITY,Sd=nt/180,mt=nt/2,Ae=nt/4,Tr=nt*2/3,le=Math.log10,Ut=Math.sign;Qt=(s,t,e,n)=>Pn(s,e,n?i=>{let o=s[i][t];return os[i][t]Pn(s,e,n=>s[n][t]>=e);Yr=["push","pop","shift","splice","unshift"];Hi=function(){return typeof window=="undefined"?function(s){return s()}:window.requestAnimationFrame}();Rn=s=>s==="start"?"left":s==="end"?"right":"center",Ct=(s,t,e)=>s==="start"?t:s==="end"?e:(t+e)/2,Xr=(s,t,e,n)=>s===(n?"left":"right")?e:s==="center"?(t+e)/2:t;Sn=s=>s===0||s===1,Lr=(s,t,e)=>-(Math.pow(2,10*(s-=1))*Math.sin((s-t)*ht/e)),Ar=(s,t,e)=>Math.pow(2,-10*s)*Math.sin((s-t)*ht/e)+1,ns={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*mt)+1,easeOutSine:s=>Math.sin(s*mt),easeInOutSine:s=>-.5*(Math.cos(nt*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=>Sn(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=>Sn(s)?s:Lr(s,.075,.3),easeOutElastic:s=>Sn(s)?s:Ar(s,.075,.3),easeInOutElastic(s){return Sn(s)?s:s<.5?.5*Lr(s*2,.1125,.45):.5+.5*Ar(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-ns.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?ns.easeInBounce(s*2)*.5:ns.easeOutBounce(s*2-1)*.5+.5};wd=["x","y","borderWidth","radius","tension"],Dd=["color","borderColor","backgroundColor"];Pr=new Map;Qr={values(s){return dt(s)?s:""+s},numeric(s,t,e){if(s===0)return"0";let n=this.chart.options.locale,i,o=s;if(e.length>1){let c=Math.max(Math.abs(e[0].value),Math.abs(e[e.length-1].value));(c<1e-4||c>1e15)&&(i="scientific"),o=Ad(s,e)}let r=le(Math.abs(o)),a=isNaN(r)?1:Math.max(Math.min(-1*Math.floor(r),20),0),l={notation:i,minimumFractionDigits:a,maximumFractionDigits:a};return Object.assign(l,this.options.ticks.format),ds(s,n,l)},logarithmic(s,t,e){if(s===0)return"0";let n=e[t].significand||s/Math.pow(10,Math.floor(le(s)));return[1,2,3,5,10,15].includes(n)||t>.8*e.length?Qr.numeric.call(this,s,t,e):""}};hs={formatters:Qr};ye=Object.create(null),On=Object.create(null);Pi=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=n=>n.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=(n,i)=>Li(i.backgroundColor),this.hoverBorderColor=(n,i)=>Li(i.borderColor),this.hoverColor=(n,i)=>Li(i.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 Ai(this,t,e)}get(t){return Bs(this,t)}describe(t,e){return Ai(On,t,e)}override(t,e){return Ai(ye,t,e)}route(t,e,n,i){let o=Bs(this,t),r=Bs(this,n),a="_"+e;Object.defineProperties(o,{[a]:{value:o[e],writable:!0},[e]:{enumerable:!0,get(){let l=this[a],c=r[i];return et(l)?Object.assign({},c,l):J(l,c)},set(l){this[a]=l}}})}apply(t){t.forEach(e=>e(this))}},ut=new Pi({_scriptable:s=>!s.startsWith("on"),_indexable:s=>s!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[Md,Td,Pd]);Vd=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,Nd=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;$d=s=>+s||0;Hd=(s,t)=>s?s+Ln(t):t,Qi=(s,t)=>et(t)&&s!=="adapters"&&(Object.getPrototypeOf(t)===null||t.constructor===Object);Ud=(s,t)=>s===!0?t:typeof s=="string"?ce(t,s):void 0;Xd=Number.EPSILON||1e-14,os=(s,t)=>ts==="x"?"y":"x";$n=s=>s.ownerDocument.defaultView.getComputedStyle(s,null);nh=["top","right","bottom","left"];ih=(s,t,e)=>(s>0||t>0)&&(!e||!e.shadowRoot);ve=s=>Math.round(s*10)/10;la=function(){let s=!1;try{let t={get passive(){return s=!0,!1}};Nn()&&(window.addEventListener("test",null,t),window.removeEventListener("test",null,t))}catch(t){}return s}();ah=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,n){return e-n},leftForLtr(e,n){return e-n}}},lh=function(){return{x(s){return s},setWidth(s){},textAlign(s){return s},xPlus(s,t){return s+t},leftForLtr(s,t){return s}}}});var Yl={};zo(Yl,{Animation:()=>qn,Animations:()=>Zs,ArcElement:()=>Ee,BarController:()=>Ne,BarElement:()=>je,BasePlatform:()=>Js,BasicPlatform:()=>Xn,BubbleController:()=>Be,CategoryScale:()=>bs,Chart:()=>ne,Colors:()=>Rl,DatasetController:()=>At,Decimation:()=>Fl,DomPlatform:()=>Zn,DoughnutController:()=>ie,Element:()=>Rt,Filler:()=>Vl,Interaction:()=>bl,Legend:()=>Bl,LineController:()=>$e,LineElement:()=>Yt,LinearScale:()=>vs,LogarithmicScale:()=>ys,PieController:()=>gs,PointElement:()=>We,PolarAreaController:()=>we,RadarController:()=>He,RadialLinearScale:()=>ke,Scale:()=>Te,ScatterController:()=>ze,SubTitle:()=>Hl,Ticks:()=>hs,TimeScale:()=>Me,TimeSeriesScale:()=>xs,Title:()=>$l,Tooltip:()=>Wl,_adapters:()=>ml,_detectPlatform:()=>_l,animator:()=>se,controllers:()=>gl,defaults:()=>ut,elements:()=>Ll,layouts:()=>St,plugins:()=>jl,registerables:()=>gp,registry:()=>Kt,scales:()=>Kl});function mh(s,t){let e=[],n=Object.keys(t);for(let i=0;i0||!e&&o<0)return i.index}return null}function va(s,t){let{chart:e,_cachedMeta:n}=s,i=e._stacks||(e._stacks={}),{iScale:o,vScale:r,index:a}=n,l=o.axis,c=r.axis,d=Ch(o,r,n),h=t.length,u;for(let f=0;fe[n].axis===t).shift()}function Eh(s,t){return de(s,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function kh(s,t,e){return de(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,n=s.vScale&&s.vScale.axis;if(n){t=t||s._parsed;for(let i of t){let o=i._stacks;if(!o||o[n]===void 0||o[n][e]===void 0)return;delete o[n][e],o[n]._visualValues!==void 0&&o[n]._visualValues[e]!==void 0&&delete o[n]._visualValues[e]}}}function Dh(s,t){if(!s._cache.$bar){let e=s.getMatchingVisibleMetas(t),n=[];for(let i=0,o=e.length;ii-o))}return s._cache.$bar}function Mh(s){let t=s.iScale,e=Dh(t,s.type),n=t._length,i,o,r,a,l=()=>{r===32767||r===-32768||(as(a)&&(n=Math.min(n,Math.abs(r-a)||n)),a=r)};for(i=0,o=e.length;i0?i[s-1]:null,a=sMath.abs(a)&&(l=a,c=r),t[e.axis]=c,t._custom={barStart:l,barEnd:c,start:i,end:o,min:r,max:a}}function pl(s,t,e,n){return dt(s)?Ah(s,t,e,n):t[e.axis]=e.parse(s,n),t}function xa(s,t,e,n){let i=s.iScale,o=s.vScale,r=i.getLabels(),a=i===o,l=[],c,d,h,u;for(c=e,d=e+n;c=e?1:-1)}function Rh(s){let t,e,n,i,o;return s.horizontal?(t=s.base>s.x,e="left",n="right"):(t=s.basecs(C,a,l,!0)?1:Math.max(E,E*e,S,S*e),p=(C,E,S)=>cs(C,a,l,!0)?-1:Math.min(E,E*e,S,S*e),g=f(0,c,h),m=f(mt,d,u),b=p(nt,c,h),x=p(nt+mt,d,u);n=(g-b)/2,i=(m-x)/2,o=-(g+b)/2,r=-(m+x)/2}return{ratioX:n,ratioY:i,offsetX:o,offsetY:r}}function Ie(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}function Nh(s,t,e,n){let{controller:i,data:o,_sorted:r}=s,a=i._cachedMeta.iScale,l=s.dataset&&s.dataset.options?s.dataset.options.spanGaps:null;if(a&&t===a.axis&&t!=="r"&&r&&o.length){let c=a._reversePixels?Ur:Qt;if(n){if(i._sharedOptions){let d=o[0],h=typeof d.getRange=="function"&&d.getRange(t);if(h){let u=c(o,t,e-h),f=c(o,t,e+h);return{lo:u.lo,hi:f.hi}}}}else{let d=c(o,t,e);if(l){let{vScale:h}=i._cachedMeta,{_parsed:u}=s,f=u.slice(0,d.lo+1).reverse().findIndex(g=>!tt(g[h.axis]));d.lo-=Math.max(0,f);let p=u.slice(d.hi).findIndex(g=>!tt(g[h.axis]));d.hi+=Math.max(0,p)}return d}}return{lo:0,hi:o.length-1}}function nn(s,t,e,n,i){let o=s.getSortedVisibleDatasetMetas(),r=e[t];for(let a=0,l=o.length;a{l[r]&&l[r](t[e],i)&&(o.push({element:l,datasetIndex:c,index:d}),a=a||l.inRange(t.x,t.y,i))}),n&&!a?[]:o}function Us(s,t){return s.filter(e=>e.pos===t)}function Ea(s,t){return s.filter(e=>vl.indexOf(e.pos)===-1&&e.box.axis===t)}function Ks(s,t){return s.sort((e,n)=>{let i=t?n:e,o=t?e:n;return i.weight===o.weight?i.index-o.index:i.weight-o.weight})}function zh(s){let t=[],e,n,i,o,r,a;for(e=0,n=(s||[]).length;ec.box.fullSize),!0),n=Ks(Us(t,"left"),!0),i=Ks(Us(t,"right")),o=Ks(Us(t,"top"),!0),r=Ks(Us(t,"bottom")),a=Ea(t,"x"),l=Ea(t,"y");return{fullSize:e,leftAndTop:n.concat(o),rightAndBottom:i.concat(l).concat(r).concat(a),chartArea:Us(t,"chartArea"),vertical:n.concat(i).concat(l),horizontal:o.concat(r).concat(a)}}function ka(s,t,e,n){return Math.max(s[e],t[e])+Math.max(s[n],t[n])}function yl(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 Kh(s,t,e,n){let{pos:i,box:o}=e,r=s.maxPadding;if(!et(i)){e.size&&(s[i]-=e.size);let h=n[e.stack]||{size:0,count:1};h.size=Math.max(h.size,e.horizontal?o.height:o.width),e.size=h.size/h.count,s[i]+=e.size}o.getPadding&&yl(r,o.getPadding());let a=Math.max(0,t.outerWidth-ka(r,s,"left","right")),l=Math.max(0,t.outerHeight-ka(r,s,"top","bottom")),c=a!==s.w,d=l!==s.h;return s.w=a,s.h=l,e.horizontal?{same:c,other:d}:{same:d,other:c}}function Yh(s){let t=s.maxPadding;function e(n){let i=Math.max(t[n]-s[n],0);return s[n]+=i,i}s.y+=e("top"),s.x+=e("left"),e("right"),e("bottom")}function Gh(s,t){let e=t.maxPadding;function n(i){let o={left:0,top:0,right:0,bottom:0};return i.forEach(r=>{o[r]=Math.max(t[r],e[r])}),o}return n(s?["left","right"]:["top","bottom"])}function qs(s,t,e,n){let i=[],o,r,a,l,c,d;for(o=0,r=s.length,c=0;o{let r=!1;for(let a of o)r=r||Qn(a.addedNodes,n),r=r&&!Qn(a.removedNodes,n);r&&e()});return i.observe(document,{childList:!0,subtree:!0}),i}function eu(s,t,e){let n=s.canvas,i=new MutationObserver(o=>{let r=!1;for(let a of o)r=r||Qn(a.removedNodes,n),r=r&&!Qn(a.addedNodes,n);r&&e()});return i.observe(document,{childList:!0,subtree:!0}),i}function Cl(){let s=window.devicePixelRatio;s!==Ma&&(Ma=s,tn.forEach((t,e)=>{e.currentDevicePixelRatio!==s&&t()}))}function su(s,t){tn.size||window.addEventListener("resize",Cl),tn.set(s,t)}function nu(s){tn.delete(s),tn.size||window.removeEventListener("resize",Cl)}function iu(s,t,e){let n=s.canvas,i=n&&Bn(n);if(!i)return;let o=zi((a,l)=>{let c=i.clientWidth;e(a,l),c{let l=a[0],c=l.contentRect.width,d=l.contentRect.height;c===0&&d===0||o(c,d)});return r.observe(i),su(s,o),r}function po(s,t,e){e&&e.disconnect(),t==="resize"&&nu(s)}function ou(s,t,e){let n=s.canvas,i=zi(o=>{s.ctx!==null&&e(Jh(o,s))},s);return Qh(n,t,i),i}function _l(s){return!Nn()||typeof OffscreenCanvas!="undefined"&&s instanceof OffscreenCanvas?Xn:Zn}function ru(s,t){let e=s.options.ticks,n=au(s),i=Math.min(e.maxTicksLimit||n,n),o=e.major.enabled?cu(t):[],r=o.length,a=o[0],l=o[r-1],c=[];if(r>i)return du(t,c,o,r/i),c;let d=lu(o,t,i);if(r>0){let h,u,f=r>1?Math.round((l-a)/(r-1)):null;for(zn(t,c,d,tt(f)?0:a-f,a),h=0,u=r-1;hi)return l}return Math.max(i,1)}function cu(s){let t=[],e,n;for(e=0,n=s.length;er+a)))return l}function pu(s,t){rt(s,e=>{let n=e.gc,i=n.length/2,o;if(i>t){for(o=0;o{let n=e.split("."),i=n.pop(),o=[s].concat(n).join("."),r=t[e].split("."),a=r.pop(),l=r.join(".");ut.route(o,i,l,a)})}function Cu(s){return"id"in s&&"defaults"in s}function _u(s){let t={},e=[],n=Object.keys(Kt.plugins.items);for(let o=0;o1&&Ra(s[0].toLowerCase());if(n)return n}throw new Error(`Cannot determine type of '${s}' axis. Please provide 'axis' or 'position' option.`)}function Oa(s,t,e){if(e[t+"AxisID"]===s)return{axis:t}}function Tu(s,t){if(t.data&&t.data.datasets){let e=t.data.datasets.filter(n=>n.xAxisID===s||n.yAxisID===s);if(e.length)return Oa(s,"x",e[0])||Oa(s,"y",e[0])}return{}}function Lu(s,t){let e=ye[s.type]||{scales:{}},n=t.scales||{},i=So(s.type,t),o=Object.create(null);return Object.keys(n).forEach(r=>{let a=n[r];if(!et(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=Eo(r,a,Tu(r,s),ut.scales[a.type]),c=Du(l,i),d=e.scales||{};o[r]=rs(Object.create(null),[{axis:l},a,d[l],d[c]])}),s.data.datasets.forEach(r=>{let a=r.type||s.type,l=r.indexAxis||So(a,t),d=(ye[a]||{}).scales||{};Object.keys(d).forEach(h=>{let u=wu(h,l),f=r[u+"AxisID"]||u;o[f]=o[f]||Object.create(null),rs(o[f],[{axis:u},n[f],d[h]])})}),Object.keys(o).forEach(r=>{let a=o[r];rs(a,[ut.scales[a.type],ut.scale])}),o}function Sl(s){let t=s.options||(s.options={});t.plugins=J(t.plugins,{}),t.scales=Lu(s,t)}function El(s){return s=s||{},s.datasets=s.datasets||[],s.labels=s.labels||[],s}function Au(s){return s=s||{},s.data=El(s.data),Sl(s),s}function Wn(s,t){let e=Fa.get(s);return e||(e=t(),Fa.set(s,e),kl.add(e)),e}function Ia(s,t,e){let n=s.get(t);n||(n=new Map,s.set(t,n));let i=e.join(),o=n.get(i);return o||(o={resolver:Vn(t,e),subPrefixes:e.filter(a=>!a.toLowerCase().includes("hover"))},n.set(i,o)),o}function Ru(s,t){let{isScriptable:e,isIndexable:n}=Xi(s);for(let i of t){let o=e(i),r=n(i),a=(r||o)&&s[i];if(o&&(ae(a)||Pu(a))||r&&dt(a))return!0}return!1}function Va(s,t){return s==="top"||s==="bottom"||Fu.indexOf(s)===-1&&t==="x"}function Na(s,t){return function(e,n){return e[s]===n[s]?e[t]-n[t]:e[s]-n[s]}}function Ba(s){let t=s.chart,e=t.options.animation;t.notifyPlugins("afterRender"),ct(e&&e.onComplete,[s],t)}function Iu(s){let t=s.chart,e=t.options.animation;ct(e&&e.onProgress,[s],t)}function wl(s){return Nn()&&typeof s=="string"?s=document.getElementById(s):s&&s.length&&(s=s[0]),s&&s.canvas&&(s=s.canvas),s}function Vu(s,t,e){let n=Object.keys(s);for(let i of n){let o=+i;if(o>=t){let r=s[i];delete s[i],(e>0||o>t)&&(s[o+e]=r)}}}function Nu(s,t,e,n){return!e||s.type==="mouseout"?null:n?t:s}function Ha(){return rt(ne.instances,s=>s._plugins.invalidate())}function Bu(s,t,e){let{startAngle:n,x:i,y:o,outerRadius:r,innerRadius:a,options:l}=t,{borderWidth:c,borderJoinStyle:d}=l,h=Math.min(c/r,xt(n-e));if(s.beginPath(),s.arc(i,o,r-c/2,n+h/2,e-h/2),a>0){let u=Math.min(c/a,xt(n-e));s.arc(i,o,a+c/2,e-u/2,n+u/2,!0)}else{let u=Math.min(c/2,r*xt(n-e));if(d==="round")s.arc(i,o,u,e-nt/2,n+nt/2,!0);else if(d==="bevel"){let f=2*u*u,p=-f*Math.cos(e+nt/2)+i,g=-f*Math.sin(e+nt/2)+o,m=f*Math.cos(n+nt/2)+i,b=f*Math.sin(n+nt/2)+o;s.lineTo(p,g),s.lineTo(m,b)}}s.closePath(),s.moveTo(0,0),s.rect(0,0,s.canvas.width,s.canvas.height),s.clip("evenodd")}function $u(s,t,e){let{startAngle:n,pixelMargin:i,x:o,y:r,outerRadius:a,innerRadius:l}=t,c=i/a;s.beginPath(),s.arc(o,r,a,n-c,e+c),l>i?(c=i/l,s.arc(o,r,l,e+c,n-c,!0)):s.arc(o,r,i,e+mt,n-mt),s.closePath(),s.clip()}function Hu(s){return In(s,["outerStart","outerEnd","innerStart","innerEnd"])}function zu(s,t,e,n){let i=Hu(s.options.borderRadius),o=(e-t)/2,r=Math.min(o,n*t/2),a=l=>{let c=(e-Math.min(o,l))*n/2;return vt(l,0,Math.min(o,c))};return{outerStart:a(i.outerStart),outerEnd:a(i.outerEnd),innerStart:vt(i.innerStart,0,r),innerEnd:vt(i.innerEnd,0,r)}}function ps(s,t,e,n){return{x:e+s*Math.cos(t),y:n+s*Math.sin(t)}}function Jn(s,t,e,n,i,o){let{x:r,y:a,startAngle:l,pixelMargin:c,innerRadius:d}=t,h=Math.max(t.outerRadius+n+e-c,0),u=d>0?d+n+e+c:0,f=0,p=i-l;if(n){let P=d>0?d-n:0,R=h>0?h-n:0,D=(P+R)/2,W=D!==0?p*D/(D+n):p;f=(p-W)/2}let g=Math.max(.001,p*h-e/nt)/h,m=(p-g)/2,b=l+m+f,x=i-m-f,{outerStart:C,outerEnd:E,innerStart:S,innerEnd:y}=zu(t,u,h,x-b),v=h-C,_=h-E,w=b+C/v,T=x-E/_,k=u+S,M=u+y,L=b+S/k,I=x-y/M;if(s.beginPath(),o){let P=(w+T)/2;if(s.arc(r,a,h,w,P),s.arc(r,a,h,P,T),E>0){let O=ps(_,T,r,a);s.arc(O.x,O.y,E,T,x+mt)}let R=ps(M,x,r,a);if(s.lineTo(R.x,R.y),y>0){let O=ps(M,I,r,a);s.arc(O.x,O.y,y,x+mt,I+Math.PI)}let D=(x-y/u+(b+S/u))/2;if(s.arc(r,a,u,x-y/u,D,!0),s.arc(r,a,u,D,b+S/u,!0),S>0){let O=ps(k,L,r,a);s.arc(O.x,O.y,S,L+Math.PI,b-mt)}let W=ps(v,b,r,a);if(s.lineTo(W.x,W.y),C>0){let O=ps(v,w,r,a);s.arc(O.x,O.y,C,b-mt,w)}}else{s.moveTo(r,a);let P=Math.cos(w)*h+r,R=Math.sin(w)*h+a;s.lineTo(P,R);let D=Math.cos(T)*h+r,W=Math.sin(T)*h+a;s.lineTo(D,W)}s.closePath()}function Wu(s,t,e,n,i){let{fullCircles:o,startAngle:r,circumference:a}=t,l=t.endAngle;if(o){Jn(s,t,e,n,l,i);for(let c=0;c=nt&&f===0&&d!=="miter"&&Bu(s,t,g),o||(Jn(s,t,e,n,g,i),s.stroke())}function Dl(s,t,e=t){s.lineCap=J(e.borderCapStyle,t.borderCapStyle),s.setLineDash(J(e.borderDash,t.borderDash)),s.lineDashOffset=J(e.borderDashOffset,t.borderDashOffset),s.lineJoin=J(e.borderJoinStyle,t.borderJoinStyle),s.lineWidth=J(e.borderWidth,t.borderWidth),s.strokeStyle=J(e.borderColor,t.borderColor)}function Uu(s,t,e){s.lineTo(e.x,e.y)}function Ku(s){return s.stepped?Jr:s.tension||s.cubicInterpolationMode==="monotone"?ta:Uu}function Ml(s,t,e={}){let n=s.length,{start:i=0,end:o=n-1}=e,{start:r,end:a}=t,l=Math.max(i,r),c=Math.min(o,a),d=ia&&o>a;return{count:n,start:l,loop:t.loop,ilen:c(r+(c?a-E:E))%o,C=()=>{g!==m&&(s.lineTo(d,m),s.lineTo(d,g),s.lineTo(d,b))};for(l&&(f=i[x(0)],s.moveTo(f.x,f.y)),u=0;u<=a;++u){if(f=i[x(u)],f.skip)continue;let E=f.x,S=f.y,y=E|0;y===p?(Sm&&(m=S),d=(h*d+E)/++h):(C(),s.lineTo(E,S),p=y,h=0,g=m=S),b=S}C()}function wo(s){let t=s.options,e=t.borderDash&&t.borderDash.length;return!s._decimated&&!s._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!e?Gu:Yu}function qu(s){return s.stepped?ca:s.tension||s.cubicInterpolationMode==="monotone"?da:be}function Xu(s,t,e,n){let i=t._path;i||(i=t._path=new Path2D,t.path(i,e,n)&&i.closePath()),Dl(s,t.options),s.stroke(i)}function Qu(s,t,e,n){let{segments:i,options:o}=t,r=wo(t);for(let a of i)Dl(s,o,a.style),s.beginPath(),r(s,t,a,{start:e,end:e+n-1})&&s.closePath(),s.stroke()}function Ju(s,t,e,n){Zu&&!t.options.segment?Xu(s,t,e,n):Qu(s,t,e,n)}function za(s,t,e,n){let i=s.options,{[e]:o}=s.getProps([e],n);return Math.abs(t-o)Al(t++)),t}function lf(s,t){return s.backgroundColor=s.data.map(()=>Pl(t++)),t}function cf(s){let t=0;return(e,n)=>{let i=s.getDatasetMeta(n).controller;i instanceof ie?t=af(e,t):i instanceof we?t=lf(e,t):i&&(t=rf(e,t))}}function ja(s){let t;for(t in s)if(s[t].borderColor||s[t].backgroundColor)return!0;return!1}function df(s){return s&&(s.borderColor||s.backgroundColor)}function hf(){return ut.borderColor!=="rgba(0,0,0,0.1)"||ut.backgroundColor!=="rgba(0,0,0,0.1)"}function uf(s,t,e,n,i){let o=i.samples||n;if(o>=e)return s.slice(t,t+e);let r=[],a=(e-2)/(o-2),l=0,c=t+e-1,d=t,h,u,f,p,g;for(r[l++]=s[d],h=0;hf&&(f=p,u=s[x],g=x);r[l++]=u,d=g}return r[l++]=s[c],r}function ff(s,t,e,n){let i=0,o=0,r,a,l,c,d,h,u,f,p,g,m=[],b=t+e-1,x=s[t].x,E=s[b].x-x;for(r=t;rg&&(g=c,u=r),i=(o*i+a.x)/++o;else{let y=r-1;if(!tt(h)&&!tt(u)){let v=Math.min(h,u),_=Math.max(h,u);v!==f&&v!==y&&m.push({...s[v],x:i}),_!==f&&_!==y&&m.push({...s[_],x:i})}r>0&&y!==f&&m.push(s[y]),m.push(a),d=S,o=0,p=g=c,h=u=f=r}}return m}function Ol(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 Ua(s){s.data.datasets.forEach(t=>{Ol(t)})}function pf(s,t){let e=t.length,n=0,i,{iScale:o}=s,{min:r,max:a,minDefined:l,maxDefined:c}=o.getUserBounds();return l&&(n=vt(Qt(t,o.axis,r).lo,0,e-1)),c?i=vt(Qt(t,o.axis,a).hi+1,n,e)-n:i=e-n,{start:n,count:i}}function gf(s,t,e){let n=s.segments,i=s.points,o=t.points,r=[];for(let a of n){let{start:l,end:c}=a;c=si(l,c,i);let d=Mo(e,i[l],i[c],a.loop);if(!t.segments){r.push({source:a,target:d,start:i[l],end:i[c]});continue}let h=oo(t,d);for(let u of h){let f=Mo(e,o[u.start],o[u.end],u.loop),p=io(a,i,f);for(let g of p)r.push({source:g,target:u,start:{[e]:Ka(d,f,"start",Math.max)},end:{[e]:Ka(d,f,"end",Math.min)}})}}return r}function Mo(s,t,e,n){if(n)return;let i=t[s],o=e[s];return s==="angle"&&(i=xt(i),o=xt(o)),{property:s,start:i,end:o}}function mf(s,t){let{x:e=null,y:n=null}=s||{},i=t.points,o=[];return t.segments.forEach(({start:r,end:a})=>{a=si(r,a,i);let l=i[r],c=i[a];n!==null?(o.push({x:l.x,y:n}),o.push({x:c.x,y:n})):e!==null&&(o.push({x:e,y:l.y}),o.push({x:e,y:c.y}))}),o}function si(s,t,e){for(;t>s;t--){let n=e[t];if(!isNaN(n.x)&&!isNaN(n.y))break}return t}function Ka(s,t,e,n){return s&&t?n(s[e],t[e]):s?s[e]:t?t[e]:0}function Il(s,t){let e=[],n=!1;return dt(s)?(n=!0,e=s):e=mf(s,t),e.length?new Yt({points:e,options:{tension:0},_loop:n,_fullLoop:n}):null}function Ya(s){return s&&s.fill!==!1}function bf(s,t,e){let i=s[t].fill,o=[t],r;if(!e)return i;for(;i!==!1&&o.indexOf(i)===-1;){if(!pt(i))return i;if(r=s[i],!r)return!1;if(r.visible)return i;o.push(i),i=r.fill}return!1}function vf(s,t,e){let n=_f(s);if(et(n))return isNaN(n.value)?!1:n;let i=parseFloat(n);return pt(i)&&Math.floor(i)===i?yf(n[0],t,i,e):["origin","start","end","stack","shape"].indexOf(n)>=0&&n}function yf(s,t,e,n){return(s==="-"||s==="+")&&(e=t+e),e===t||e<0||e>=n?!1:e}function xf(s,t){let e=null;return s==="start"?e=t.bottom:s==="end"?e=t.top:et(s)?e=t.getPixelForValue(s.value):t.getBasePixel&&(e=t.getBasePixel()),e}function Cf(s,t,e){let n;return s==="start"?n=e:s==="end"?n=t.options.reverse?t.min:t.max:et(s)?n=s.value:n=t.getBaseValue(),n}function _f(s){let t=s.options,e=t.fill,n=J(e&&e.target,e);return n===void 0&&(n=!!t.backgroundColor),n===!1||n===null?!1:n===!0?"origin":n}function Sf(s){let{scale:t,index:e,line:n}=s,i=[],o=n.segments,r=n.points,a=Ef(t,e);a.push(Il({x:null,y:t.bottom},n));for(let l=0;lo.length>r.length?o:r)),t+e.size/2+n.measureText(i).width}function Vf(s,t,e){let n=s;return typeof t.text!="string"&&(n=Nl(t,e)),n}function Nl(s,t){let e=s.text?s.text.length:0;return t*e}function Nf(s,t){return!!((s==="mousemove"||s==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(s==="click"||s==="mouseup"))}function Bf(s,t){let e=new en({ctx:s.ctx,options:t,chart:s});St.configure(s,e,t),St.addBox(s,e),s.titleBlock=e}function ee(s,t){return t&&(dt(t)?Array.prototype.push.apply(s,t):s.push(t)),s}function he(s){return(typeof s=="string"||s instanceof String)&&s.indexOf(` `)>-1?s.split(` -`):s}function Tf(s,t){let{element:e,datasetIndex:n,index:i}=t,o=s.getDatasetMeta(n).controller,{label:r,value:a}=o.getLabelAndValue(i);return{chart:s,label:r,parsed:o.getParsed(i),raw:s.data.datasets[n].data[i],formattedValue:a,dataset:o.getDataset(),dataIndex:i,datasetIndex:n,element:e}}function Ga(s,t){let e=s.chart.ctx,{body:n,footer:i,title:o}=s,{boxWidth:r,boxHeight:a}=t,l=bt(t.bodyFont),c=bt(t.titleFont),d=bt(t.footerFont),h=o.length,u=i.length,f=n.length,g=_t(t.padding),p=g.height,m=0,b=n.reduce((k,S)=>k+S.before.length+S.lines.length+S.after.length,0);if(b+=s.beforeBody.length+s.afterBody.length,h&&(p+=h*c.lineHeight+(h-1)*t.titleSpacing+t.titleMarginBottom),b){let k=t.displayColors?Math.max(a,l.lineHeight):l.lineHeight;p+=f*k+(b-f)*l.lineHeight+(b-1)*t.bodySpacing}u&&(p+=t.footerMarginTop+u*d.lineHeight+(u-1)*t.footerSpacing);let x=0,C=function(k){m=Math.max(m,e.measureText(k).width+x)};return e.save(),e.font=c.string,rt(s.title,C),e.font=l.string,rt(s.beforeBody.concat(s.afterBody),C),x=t.displayColors?r+2+t.boxPadding:0,rt(n,k=>{rt(k.before,C),rt(k.lines,C),rt(k.after,C)}),x=0,e.font=d.string,rt(s.footer,C),e.restore(),m+=g.width,{width:m,height:p}}function Lf(s,t){let{y:e,height:n}=t;return es.height-n/2?"bottom":"center"}function Af(s,t,e,n){let{x:i,width:o}=n,r=e.caretSize+e.caretPadding;if(s==="left"&&i+o+r>t.width||s==="right"&&i-o-r<0)return!0}function Rf(s,t,e,n){let{x:i,width:o}=e,{width:r,chartArea:{left:a,right:l}}=s,c="center";return n==="center"?c=i<=(a+l)/2?"left":"right":i<=o/2?c="left":i>=r-o/2&&(c="right"),Af(c,s,t,e)&&(c="center"),c}function qa(s,t,e){let n=e.yAlign||t.yAlign||Lf(s,e);return{xAlign:e.xAlign||t.xAlign||Rf(s,t,e,n),yAlign:n}}function Pf(s,t){let{x:e,width:n}=s;return t==="right"?e-=n:t==="center"&&(e-=n/2),e}function Of(s,t,e){let{y:n,height:i}=s;return t==="top"?n+=e:t==="bottom"?n-=i+e:n-=i/2,n}function Xa(s,t,e,n){let{caretSize:i,caretPadding:o,cornerRadius:r}=s,{xAlign:a,yAlign:l}=e,c=i+o,{topLeft:d,topRight:h,bottomLeft:u,bottomRight:f}=Ce(r),g=Pf(t,a),p=Of(t,l,c);return l==="center"?a==="left"?g+=c:a==="right"&&(g-=c):a==="left"?g-=Math.max(d,u)+i:a==="right"&&(g+=Math.max(h,f)+i),{x:vt(g,0,n.width-t.width),y:vt(p,0,n.height-t.height)}}function Yn(s,t,e){let n=_t(e.padding);return t==="center"?s.x+s.width/2:t==="right"?s.x+s.width-n.right:s.x+n.left}function Qa(s){return ee([],he(s))}function If(s,t,e){return de(s,{tooltip:t,tooltipItems:e,type:"tooltip"})}function Za(s,t){let e=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return e?s.override(e):s}function Tt(s,t,e,n){let i=s[t].call(e,n);return typeof i=="undefined"?Nl[t].call(e,n):i}function Vf(s,t,e,n){let i=s.indexOf(t);if(i===-1)return Ff(s,t,e,n);let o=s.lastIndexOf(t);return i!==o?e:i}function Ja(s){let t=this.getLabels();return s>=0&&sg&&(S=Ri(w*S/g/f)*f),tt(l)||(y=Math.pow(10,l),S=Math.ceil(S*y)/y),i==="ticks"?(v=Math.floor(p/S)*S,_=Math.ceil(m/S)*S):(v=p,_=m),b&&x&&o&&Br((a-r)/o,S/1e3)?(w=Math.round(Math.min((a-r)/S,d)),S=(a-r)/w,v=r,_=a):C?(v=b?r:v,_=x?a:_,w=c-1,S=(_-v)/w):(w=(_-v)/S,cs(w,Math.round(w),S/1e3)?w=Math.round(w):w=Math.ceil(w));let T=Math.max(Oi(S),Oi(v));y=Math.pow(10,tt(l)?T:l),v=Math.round(v*y)/y,_=Math.round(_*y)/y;let E=0;for(b&&(u&&v!==r?(e.push({value:r}),va)break;e.push({value:M})}return x&&u&&_!==a?e.length&&cs(e[e.length-1].value,a,tl(a,k,s))?e[e.length-1].value=a:e.push({value:a}):(!x||_===a)&&e.push({value:_}),e}function tl(s,t,{horizontal:e,minRotation:n}){let i=Ht(n),o=(e?Math.sin(i):Math.cos(i))||.001,r=.75*t*(""+s).length;return Math.min(t/o,r)}function el(s){return s/Math.pow(10,en(s))===1}function sl(s,t,e){let n=Math.pow(10,e),i=Math.floor(s/n);return Math.ceil(t/n)-i}function zf(s,t){let e=t-s,n=en(e);for(;sl(s,t,n)>10;)n++;for(;sl(s,t,n)<10;)n--;return Math.min(n,en(s))}function Hf(s,{min:t,max:e}){t=Mt(s.min,t);let n=[],i=en(t),o=zf(t,e),r=o<0?Math.pow(10,Math.abs(o)):1,a=Math.pow(10,o),l=i>o?Math.pow(10,i):0,c=Math.round((t-l)*r)/r,d=Math.floor((t-l)/a/10)*a*10,h=Math.floor((c-d)/Math.pow(10,o)),u=Mt(s.min,Math.round((l+d+h*Math.pow(10,o))*r)/r);for(;u=10?h=h<15?15:20:h++,h>=20&&(o++,h=2,r=o>=0?1:r),u=Math.round((l+d+h*Math.pow(10,o))*r)/r;let f=Mt(s.max,u);return n.push({value:f,major:el(f),significand:h}),n}function wo(s){let t=s.ticks;if(t.display&&s.display){let e=_t(t.backdropPadding);return J(t.font&&t.font.size,ut.font.size)+e.height}return 0}function $f(s,t,e){return e=dt(e)?e:[e],{w:Gr(s,t.string,e),h:e.length*t.lineHeight}}function nl(s,t,e,n,i){return s===n||s===i?{start:t-e/2,end:t+e/2}:si?{start:t-e,end:t}:{start:t,end:t+e}}function Wf(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),n=[],i=[],o=s._pointLabels.length,r=s.options.pointLabels,a=r.centerPointLabels?nt/o:0;for(let l=0;lt.r&&(a=(n.end-t.r)/o,s.r=Math.max(s.r,t.r+a)),i.startt.b&&(l=(i.end-t.b)/r,s.b=Math.max(s.b,t.b+l))}function Uf(s,t,e){let n=s.drawingArea,{extra:i,additionalAngle:o,padding:r,size:a}=e,l=s.getPointPosition(t,n+i+r,o),c=Math.round(Pn(xt(l.angle+mt))),d=Xf(l.y,a.h,c),h=Gf(c),u=qf(l.x,a.w,h);return{visible:!0,x:l.x,y:d,textAlign:h,left:u,top:d,right:u+a.w,bottom:d+a.h}}function Kf(s,t){if(!t)return!0;let{left:e,top:n,right:i,bottom:o}=s;return!(Zt({x:e,y:n},t)||Zt({x:e,y:o},t)||Zt({x:i,y:n},t)||Zt({x:i,y:o},t))}function Yf(s,t,e){let n=[],i=s._pointLabels.length,o=s.options,{centerPointLabels:r,display:a}=o.pointLabels,l={extra:wo(o)/2,additionalAngle:r?nt/i:0},c;for(let d=0;d270||e<90)&&(s-=t),s}function Qf(s,t,e){let{left:n,top:i,right:o,bottom:r}=e,{backdropColor:a}=t;if(!tt(a)){let l=Ce(t.borderRadius),c=_t(t.backdropPadding);s.fillStyle=a;let d=n-c.left,h=i-c.top,u=o-n+c.width,f=r-i+c.height;Object.values(l).some(g=>g!==0)?(s.beginPath(),fs(s,{x:d,y:h,w:u,h:f,radius:l}),s.fill()):s.fillRect(d,h,u,f)}}function Zf(s,t){let{ctx:e,options:{pointLabels:n}}=s;for(let i=t-1;i>=0;i--){let o=s._pointLabelItems[i];if(!o.visible)continue;let r=n.setContext(s.getPointLabelContext(i));Qf(e,r,o);let a=bt(r.font),{x:l,y:c,textAlign:d}=o;xe(e,s._pointLabels[i],l,c+a.lineHeight/2,a,{color:r.color,textAlign:d,textBaseline:"middle"})}}function Hl(s,t,e,n){let{ctx:i}=s;if(e)i.arc(s.xCenter,s.yCenter,t,0,ht);else{let o=s.getPointPosition(0,t);i.moveTo(o.x,o.y);for(let r=1;r=At.indexOf(e);o--){let r=At[o];if(oi[r].common&&s._adapter.diff(i,n,r)>=t-1)return r}return At[e?At.indexOf(e):0]}function sg(s){for(let t=At.indexOf(s)+1,e=At.length;t=t?e[n]:e[i];s[o]=!0}}function ng(s,t,e,n){let i=s._adapter,o=+i.startOf(t[0].value,n),r=t[t.length-1].value,a,l;for(a=o;a<=r;a=+i.add(a,1,n))l=e[a],l>=0&&(t[l].major=!0);return t}function ll(s,t,e){let n=[],i={},o=t.length,r,a;for(r=0;r=s[n].pos&&t<=s[i].pos&&({lo:n,hi:i}=Qt(s,"pos",t)),{pos:o,time:a}=s[n],{pos:r,time:l}=s[i]):(t>=s[n].time&&t<=s[i].time&&({lo:n,hi:i}=Qt(s,"time",t)),{time:o,pos:a}=s[n],{time:r,pos:l}=s[i]);let c=r-o;return c?a+(l-a)*(t-o)/c:a}var mo,se,da,ih,Qn,Qs,ro,pa,ph,Lt,Ve,Ne,ie,Be,ke,ms,ze,He,hl,bo,ul,fl,gl,St,Zs,Zn,qn,Nh,Sa,ml,Js,Ea,ti,Rt,eu,ka,wa,Me,bs,vo,Ut,yo,Aa,Cl,Ys,_o,Cu,Su,Eu,Xn,Fa,ne,Se,Hu,Kt,$e,We,wl,Eo,Ba,Tl,Al,si,Pl,Ya,Sf,ni,Il,tn,Fl,Kn,Vl,qs,Nl,Xs,Bl,zl,Ff,Nf,vs,_s,ys,en,Fe,xs,Ee,oi,At,De,Cs,$l,ig,jl=li(()=>{ca();mo=class{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,n,i){let o=e.listeners[i],r=e.duration;o.forEach(a=>a({chart:t,initial:e.initial,numSteps:r,currentStep:Math.min(n-e.start,r)}))}_refresh(){this._request||(this._running=!0,this._request=Ni.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(t=Date.now()){let e=0;this._charts.forEach((n,i)=>{if(!n.running||!n.items.length)return;let o=n.items,r=o.length-1,a=!1,l;for(;r>=0;--r)l=o[r],l._active?(l._total>n.duration&&(n.duration=l._total),l.tick(t),a=!0):(o[r]=o[o.length-1],o.pop());a&&(i.draw(),this._notify(i,n,t,"progress")),o.length||(n.running=!1,this._notify(i,n,t,"complete"),n.initial=!1),e+=o.length}),this._lastDate=t,e===0&&(this._running=!1)}_getAnims(t){let e=this._charts,n=e.get(t);return n||(n={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,n)),n}listen(t,e,n){this._getAnims(t).listeners[e].push(n)}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((n,i)=>Math.max(n,i._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 n=e.items,i=n.length-1;for(;i>=0;--i)n[i].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}},se=new mo,da="transparent",ih={boolean(s,t,e){return e>.5?t:s},color(s,t,e){let n=Wi(s||da),i=n.valid&&Wi(t||da);return i&&i.valid?i.mix(n,e).hexString():t},number(s,t,e){return s+(t-s)*e}},Qn=class{constructor(t,e,n,i){let o=e[n];i=gs([t.to,i,o,t.from]);let r=gs([t.from,o,i]);this._active=!0,this._fn=t.fn||ih[t.type||typeof r],this._easing=is[t.easing]||is.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=n,this._from=r,this._to=i,this._promises=void 0}active(){return this._active}update(t,e,n){if(this._active){this._notify(!1);let i=this._target[this._prop],o=n-this._start,r=this._duration-o;this._start=n,this._duration=Math.floor(Math.max(r,t.duration)),this._total+=o,this._loop=!!t.loop,this._to=gs([t.to,e,i,t.from]),this._from=gs([t.from,i,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){let e=t-this._start,n=this._duration,i=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[i]=this._fn(o,a,l)}wait(){let t=this._promises||(this._promises=[]);return new Promise((e,n)=>{t.push({res:e,rej:n})})}_notify(t){let e=t?"res":"rej",n=this._promises||[];for(let i=0;i{let o=t[i];if(!et(o))return;let r={};for(let a of e)r[a]=o[a];(dt(o.properties)&&o.properties||[i]).forEach(a=>{(a===i||!n.has(a))&&n.set(a,r)})})}_animateOptions(t,e){let n=e.options,i=rh(t,n);if(!i)return[];let o=this._createAnimations(i,n);return n.$shared&&oh(t.options.$animations,n).then(()=>{t.options=n},()=>{}),o}_createAnimations(t,e){let n=this._properties,i=[],o=t.$animations||(t.$animations={}),r=Object.keys(e),a=Date.now(),l;for(l=r.length-1;l>=0;--l){let c=r[l];if(c.charAt(0)==="$")continue;if(c==="options"){i.push(...this._animateOptions(t,e));continue}let d=e[c],h=o[c],u=n.get(c);if(h)if(u&&h.active()){h.update(u,d,a);continue}else h.cancel();if(!u||!u.duration){t[c]=d;continue}o[c]=h=new Qn(u,t,c,d),i.push(h)}return i}update(t,e){if(this._properties.size===0){Object.assign(t,e);return}let n=this._createAnimations(t,e);if(n.length)return se.add(this._chart,n),!0}};ro=s=>s==="reset"||s==="none",pa=(s,t)=>t?s:Object.assign({},s),ph=(s,t,e)=>s&&!t.hidden&&t._stacked&&{keys:cl(e,!0),values:null},Lt=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=io(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&&Ws(this._cachedMeta),this.index=t}linkScales(){let t=this.chart,e=this._cachedMeta,n=this.getDataset(),i=(h,u,f,g)=>h==="x"?u:h==="r"?g:f,o=e.xAxisID=J(n.xAxisID,oo(t,"x")),r=e.yAxisID=J(n.yAxisID,oo(t,"y")),a=e.rAxisID=J(n.rAxisID,oo(t,"r")),l=e.indexAxis,c=e.iAxisID=i(l,o,r,a),d=e.vAxisID=i(l,r,o,a);e.xScale=this.getScaleForId(o),e.yScale=this.getScaleForId(r),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(c),e.vScale=this.getScaleForId(d)}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&&Fi(this._data,this),t._stacked&&Ws(t)}_dataCheck(){let t=this.getDataset(),e=t.data||(t.data=[]),n=this._data;if(et(e)){let i=this._cachedMeta;this._data=ch(e,i)}else if(n!==e){if(n){Fi(n,this);let i=this._cachedMeta;Ws(i),i._parsed=[]}e&&Object.isExtensible(e)&&jr(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,n=this.getDataset(),i=!1;this._dataCheck();let o=e._stacked;e._stacked=io(e.vScale,e),e.stack!==n.stack&&(i=!0,Ws(e),e.stack=n.stack),this._resyncElements(t),(i||o!==e._stacked)&&(ga(this,e._parsed),e._stacked=io(e.vScale,e))}configure(){let t=this.chart.config,e=t.datasetScopeKeys(this._type),n=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(n,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){let{_cachedMeta:n,_data:i}=this,{iScale:o,_stacked:r}=n,a=o.axis,l=t===0&&e===i.length?!0:n._sorted,c=t>0&&n._parsed[t-1],d,h,u;if(this._parsing===!1)n._parsed=i,n._sorted=!0,u=i;else{dt(i[t])?u=this.parseArrayData(n,i,t,e):et(i[t])?u=this.parseObjectData(n,i,t,e):u=this.parsePrimitiveData(n,i,t,e);let f=()=>h[a]===null||c&&h[a]p||h=0;--u)if(!g()){this.updateRangeFromParsed(c,t,f,l);break}}return c}getAllParsedValues(t){let e=this._cachedMeta._parsed,n=[],i,o,r;for(i=0,o=e.length;i=0&&tthis.getContext(n,i,e),p=c.resolveNamedOptions(u,f,g,h);return p.$shared&&(p.$shared=l,o[r]=Object.freeze(pa(p,l))),p}_resolveAnimations(t,e,n){let i=this.chart,o=this._cachedDataOpts,r=`animation-${e}`,a=o[r];if(a)return a;let l;if(i.options.animation!==!1){let d=this.chart.config,h=d.datasetAnimationScopeKeys(this._type,e),u=d.getOptionScopes(this.getDataset(),h);l=d.createResolver(u,this.getContext(t,n,e))}let c=new Qs(i,l&&l.animations);return l&&l._cacheable&&(o[r]=Object.freeze(c)),c}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||ro(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){let n=this.resolveDataElementOptions(t,e),i=this._sharedOptions,o=this.getSharedOptions(n),r=this.includeOptions(e,o)||o!==i;return this.updateSharedOptions(o,e,n),{sharedOptions:o,includeOptions:r}}updateElement(t,e,n,i){ro(i)?Object.assign(t,n):this._resolveAnimations(e,i).update(t,n)}updateSharedOptions(t,e,n){t&&!ro(e)&&this._resolveAnimations(void 0,e).update(t,n)}_setStyle(t,e,n,i){t.active=i;let o=this.getStyle(e,i);this._resolveAnimations(e,n,i).update(t,{options:!i&&this.getSharedOptions(o)||o})}removeHoverStyle(t,e,n){this._setStyle(t,n,"active",!1)}setHoverStyle(t,e,n){this._setStyle(t,n,"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,n=this._cachedMeta.data;for(let[a,l,c]of this._syncList)this[a](l,c);this._syncList=[];let i=n.length,o=e.length,r=Math.min(o,i);r&&this.parse(0,r),o>i?this._insertElements(i,o-i,t):o{for(c.length+=e,a=c.length-1;a>=r;a--)c[a]=c[a-e]};for(l(o),a=t;ad.controller.options.grouped),o=n.options.stacked,r=[],a=this._cachedMeta.controller.getParsed(e),l=a&&a[n.axis],c=d=>{let h=d._parsed.find(f=>f[n.axis]===l),u=h&&h[d.vScale.axis];if(tt(u)||isNaN(u))return!0};for(let d of i)if(!(e!==void 0&&c(d))&&((o===!1||r.indexOf(d.stack)===-1||o===void 0&&d.stack===void 0)&&r.push(d.stack),d.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(n=>t[n].axis===e).shift()}_getAxis(){let t={},e=this.getFirstScaleIdForIndexAxis();for(let n of this.chart.data.datasets)t[J(this.chart.options.indexAxis==="x"?n.xAxisID:n.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,n){let i=this._getStacks(t,n),o=e!==void 0?i.indexOf(e):-1;return o===-1?i.length-1:o}_getRuler(){let t=this.options,e=this._cachedMeta,n=e.iScale,i=[],o,r;for(o=0,r=e.data.length;o=0;--n)e=Math.max(e,t[n].size(this.resolveDataElementOptions(n))/2);return e>0&&e}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart.data.labels||[],{xScale:i,yScale:o}=e,r=this.getParsed(t),a=i.getLabelForValue(r.x),l=o.getLabelForValue(r.y),c=r._custom;return{label:n[t]||"",value:"("+a+", "+l+(c?", "+c:"")+")"}}update(t){let e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,n,i){let o=i==="reset",{iScale:r,vScale:a}=this._cachedMeta,{sharedOptions:l,includeOptions:c}=this._getSharedOptions(e,i),d=r.axis,h=a.axis;for(let u=e;u+n[l];if(et(n[t])){let{key:l="value"}=this._parsing;o=c=>+ce(n[c],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,n=this.chart,i=n.data.labels||[],o=hs(e._parsed[t],n.options.locale);return{label:i[t]||"",value:o}}getMaxBorderWidth(t){let e=0,n=this.chart,i,o,r,a,l;if(!t){for(i=0,o=n.data.datasets.length;it!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),j(ie,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data,{labels:{pointStyle:n,textAlign:i,color:o,useBorderRadius:r,borderRadius:a}}=t.legend.options;return e.labels.length&&e.datasets.length?e.labels.map((l,c)=>{let h=t.getDatasetMeta(0).controller.getStyle(c);return{text:l,fillStyle:h.backgroundColor,fontColor:o,hidden:!t.getDataVisibility(c),lineDash:h.borderDash,lineDashOffset:h.borderDashOffset,lineJoin:h.borderJoinStyle,lineWidth:h.borderWidth,strokeStyle:h.borderColor,textAlign:i,pointStyle:n,borderRadius:r&&(a||h.borderRadius),index:c}}):[]}},onClick(t,e,n){n.chart.toggleDataVisibility(e.index),n.chart.update()}}}});Be=class extends Lt{initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){let e=this._cachedMeta,{dataset:n,data:i=[],_dataset:o}=e,r=this.chart._animationsDisabled,{start:a,count:l}=zi(e,i,r);this._drawStart=a,this._drawCount=l,Hi(e)&&(a=0,l=i.length),n._chart=this.chart,n._datasetIndex=this.index,n._decimated=!!o._decimated,n.points=i;let c=this.resolveDatasetElementOptions(t);this.options.showLine||(c.borderWidth=0),c.segment=this.options.segment,this.updateElement(n,void 0,{animated:!r,options:c},t),this.updateElements(i,a,l,t)}updateElements(t,e,n,i){let o=i==="reset",{iScale:r,vScale:a,_stacked:l,_dataset:c}=this._cachedMeta,{sharedOptions:d,includeOptions:h}=this._getSharedOptions(e,i),u=r.axis,f=a.axis,{spanGaps:g,segment:p}=this.options,m=Pe(g)?g:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||i==="none",x=e+n,C=t.length,k=e>0&&this.getParsed(e-1);for(let S=0;S=x){v.skip=!0;continue}let _=this.getParsed(S),w=tt(_[f]),T=v[u]=r.getPixelForValue(_[u],S),E=v[f]=o||w?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,_,l):_[f],S);v.skip=isNaN(T)||isNaN(E)||w,v.stop=S>0&&Math.abs(_[u]-k[u])>m,p&&(v.parsed=_,v.raw=c.data[S]),h&&(v.options=d||this.resolveDataElementOptions(S,y.active?"active":i)),b||this.updateElement(y,S,v,i),k=_}}getMaxOverflow(){let t=this._cachedMeta,e=t.dataset,n=e.options&&e.options.borderWidth||0,i=t.data||[];if(!i.length)return n;let o=i[0].size(this.resolveDataElementOptions(0)),r=i[i.length-1].size(this.resolveDataElementOptions(i.length-1));return Math.max(n,o,r)/2}draw(){let t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}};j(Be,"id","line"),j(Be,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),j(Be,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});ke=class extends Lt{constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart,i=n.data.labels||[],o=hs(e._parsed[t].r,n.options.locale);return{label:i[t]||"",value:o}}parseObjectData(t,e,n,i){return Xi.bind(this)(t,e,n,i)}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((n,i)=>{let o=this.getParsed(i).r;!isNaN(o)&&this.chart.getDataVisibility(i)&&(oe.max&&(e.max=o))}),e}_updateRadius(){let t=this.chart,e=t.chartArea,n=t.options,i=Math.min(e.right-e.left,e.bottom-e.top),o=Math.max(i/2,0),r=Math.max(n.cutoutPercentage?o/100*n.cutoutPercentage:1,0),a=(o-r)/t.getVisibleDatasetCount();this.outerRadius=o-a*this.index,this.innerRadius=this.outerRadius-a}updateElements(t,e,n,i){let o=i==="reset",r=this.chart,l=r.options.animation,c=this._cachedMeta.rScale,d=c.xCenter,h=c.yCenter,u=c.getIndexAngle(0)-.5*nt,f=u,g,p=360/this.countVisibleElements();for(g=0;g{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++}),e}_computeAngle(t,e,n){return this.chart.getDataVisibility(t)?Ht(this.resolveDataElementOptions(t,e).angle||n):0}};j(ke,"id","polarArea"),j(ke,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),j(ke,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data;if(e.labels.length&&e.datasets.length){let{labels:{pointStyle:n,color:i}}=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:i,lineWidth:l.borderWidth,pointStyle:n,hidden:!t.getDataVisibility(r),index:r}})}return[]}},onClick(t,e,n){n.chart.toggleDataVisibility(e.index),n.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}});ms=class extends ie{};j(ms,"id","pie"),j(ms,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});ze=class extends Lt{getLabelAndValue(t){let e=this._cachedMeta.vScale,n=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(n[e.axis])}}parseObjectData(t,e,n,i){return Xi.bind(this)(t,e,n,i)}update(t){let e=this._cachedMeta,n=e.dataset,i=e.data||[],o=e.iScale.getLabels();if(n.points=i,t!=="resize"){let r=this.resolveDatasetElementOptions(t);this.options.showLine||(r.borderWidth=0);let a={_loop:!0,_fullLoop:o.length===i.length,options:r};this.updateElement(n,void 0,a,t)}this.updateElements(i,0,i.length,t)}updateElements(t,e,n,i){let o=this._cachedMeta.rScale,r=i==="reset";for(let a=e;a0&&this.getParsed(e-1);for(let k=e;k0&&Math.abs(y[f]-C[f])>b,m&&(v.parsed=y,v.raw=c.data[k]),u&&(v.options=h||this.resolveDataElementOptions(k,S.active?"active":i)),x||this.updateElement(S,k,v,i),C=y}this.updateSharedOptions(h,i,d)}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 n=t.dataset,i=n.options&&n.options.borderWidth||0;if(!e.length)return i;let o=e[0].size(this.resolveDataElementOptions(0)),r=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(i,o,r)/2}};j(He,"id","scatter"),j(He,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),j(He,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});hl=Object.freeze({__proto__:null,BarController:Ve,BubbleController:Ne,DoughnutController:ie,LineController:Be,PieController:ms,PolarAreaController:ke,RadarController:ze,ScatterController:He});bo=class s{constructor(t){j(this,"options");this.options=t||{}}static override(t){Object.assign(s.prototype,t)}init(){}formats(){return Ie()}parse(){return Ie()}format(){return Ie()}add(){return Ie()}diff(){return Ie()}startOf(){return Ie()}endOf(){return Ie()}},ul={_date:bo};fl={evaluateInteractionItems:sn,modes:{index(s,t,e,n){let i=_e(t,s),o=e.axis||"x",r=e.includeInvisible||!1,a=e.intersect?lo(s,i,o,n,r):co(s,i,o,!1,n,r),l=[];return a.length?(s.getSortedVisibleDatasetMetas().forEach(c=>{let d=a[0].index,h=c.data[d];h&&!h.skip&&l.push({element:h,datasetIndex:c.index,index:d})}),l):[]},dataset(s,t,e,n){let i=_e(t,s),o=e.axis||"xy",r=e.includeInvisible||!1,a=e.intersect?lo(s,i,o,n,r):co(s,i,o,!1,n,r);if(a.length>0){let l=a[0].datasetIndex,c=s.getDatasetMeta(l).data;a=[];for(let d=0;d{typeof p.beforeLayout=="function"&&p.beforeLayout()});let d=l.reduce((p,m)=>m.box.options&&m.box.options.display===!1?p:p+1,0)||1,h=Object.freeze({outerWidth:t,outerHeight:e,padding:i,availableWidth:o,availableHeight:r,vBoxMaxWidth:o/2/d,hBoxMaxHeight:r/2}),u=Object.assign({},i);pl(u,_t(n));let f=Object.assign({maxPadding:u,w:o,h:r,x:i.left,y:i.top},i),g=Ph(l.concat(c),h);Gs(a.fullSize,f,h,g),Gs(l,f,h,g),Gs(c,f,h,g)&&Gs(l,f,h,g),Fh(f),_a(a.leftAndTop,f,h,g),f.x+=f.w,f.y+=f.h,_a(a.rightAndBottom,f,h,g),s.chartArea={left:f.left,top:f.top,right:f.left+f.w,bottom:f.top+f.h,height:f.h,width:f.w},rt(a.chartArea,p=>{let m=p.box;Object.assign(m,s.chartArea),m.update(f.w,f.h,{left:0,top:0,right:0,bottom:0})})}},Zs=class{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,n){}removeEventListener(t,e,n){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,n,i){return e=Math.max(0,e||t.width),n=n||t.height,{width:e,height:Math.max(0,i?Math.floor(e/i):n)}}isAttached(t){return!0}updateConfig(t){}},Zn=class extends Zs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}},qn="$chartjs",Nh={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},Sa=s=>s===null||s==="";ml=ia?{passive:!0}:!1;Js=new Map,Ea=0;ti=class extends Zs{acquireContext(t,e){let n=t&&t.getContext&&t.getContext("2d");return n&&n.canvas===t?(Bh(t,e),n):null}releaseContext(t){let e=t.canvas;if(!e[qn])return!1;let n=e[qn].initial;["height","width"].forEach(o=>{let r=n[o];tt(r)?e.removeAttribute(o):e.setAttribute(o,r)});let i=n.style||{};return Object.keys(i).forEach(o=>{e.style[o]=i[o]}),e.width=e.width,delete e[qn],!0}addEventListener(t,e,n){this.removeEventListener(t,e);let i=t.$proxies||(t.$proxies={}),r={attach:Wh,detach:jh,resize:Yh}[e]||Gh;i[e]=r(t,e,n)}removeEventListener(t,e){let n=t.$proxies||(t.$proxies={}),i=n[e];if(!i)return;({attach:ho,detach:ho,resize:ho}[e]||Hh)(t,e,i),n[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,n,i){return na(t,e,n,i)}isAttached(t){let e=t&&Hn(t);return!!(e&&e.isConnected)}};Rt=class{constructor(){j(this,"x");j(this,"y");j(this,"active",!1);j(this,"options");j(this,"$animations")}tooltipPosition(t){let{x:e,y:n}=this.getProps(["x","y"],t);return{x:e,y:n}}hasValue(){return Pe(this.x)&&Pe(this.y)}getProps(t,e){let n=this.$animations;if(!e||!n)return this;let i={};return t.forEach(o=>{i[o]=n[o]&&n[o].active()?n[o]._to:this[o]}),i}};j(Rt,"defaults",{}),j(Rt,"defaultRoutes");eu=s=>s==="left"?"right":s==="right"?"left":s,ka=(s,t,e)=>t==="top"||t==="left"?s[t]+e:s[t]-e,wa=(s,t)=>Math.min(t||s,s);Me=class s extends Rt{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:n,_suggestedMax:i}=this;return t=Mt(t,Number.POSITIVE_INFINITY),e=Mt(e,Number.NEGATIVE_INFINITY),n=Mt(n,Number.POSITIVE_INFINITY),i=Mt(i,Number.NEGATIVE_INFINITY),{min:Mt(t,n),max:Mt(e,i),minDefined:gt(t),maxDefined:gt(e)}}getMinMax(t){let{min:e,max:n,minDefined:i,maxDefined:o}=this.getUserBounds(),r;if(i&&o)return{min:e,max:n};let a=this.getMatchingVisibleMetas();for(let l=0,c=a.length;ln?n:e,n=i&&e>n?e:n,{min:Mt(e,Mt(n,e)),max:Mt(n,Mt(e,n))}}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,n){let{beginAtZero:i,grace:o,ticks:r}=this.options,a=r.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=n=Object.assign({left:0,right:0,top:0,bottom:0},n),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+n.left+n.right:this.height+n.top+n.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Qr(this,o,i),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();let l=a=o||n<=1||!this.isHorizontal()){this.labelRotation=i;return}let d=this._getLabelSizes(),h=d.widest.width,u=d.highest.height,f=vt(this.chart.width-h,0,this.maxWidth);a=t.offset?this.maxWidth/n:f/(n-1),h+6>a&&(a=f/(n-(t.offset?.5:1)),l=this.maxHeight-Ks(t.grid)-e.padding-Ma(t.title,this.chart.options.font),c=Math.sqrt(h*h+u*u),r=Pn(Math.min(Math.asin(vt((d.highest.height+6)/a,-1,1)),Math.asin(vt(l/c,-1,1))-Math.asin(vt(u/c,-1,1)))),r=Math.max(i,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:n,title:i,grid:o}}=this,r=this._isVisible(),a=this.isHorizontal();if(r){let l=Ma(i,e.options.font);if(a?(t.width=this.maxWidth,t.height=Ks(o)+l):(t.height=this.maxHeight,t.width=Ks(o)+l),n.display&&this.ticks.length){let{first:c,last:d,widest:h,highest:u}=this._getLabelSizes(),f=n.padding*2,g=Ht(this.labelRotation),p=Math.cos(g),m=Math.sin(g);if(a){let b=n.mirror?0:m*h.width+p*u.height;t.height=Math.min(this.maxHeight,t.height+b+f)}else{let b=n.mirror?0:p*h.width+m*u.height;t.width=Math.min(this.maxWidth,t.width+b+f)}this._calculatePadding(c,d,m,p)}}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,n,i){let{ticks:{align:o,padding:r},position:a}=this.options,l=this.labelRotation!==0,c=a!=="top"&&this.axis==="x";if(this.isHorizontal()){let d=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1),u=0,f=0;l?c?(u=i*t.width,f=n*e.height):(u=n*t.height,f=i*e.width):o==="start"?f=e.width:o==="end"?u=t.width:o!=="inner"&&(u=t.width/2,f=e.width/2),this.paddingLeft=Math.max((u-d+r)*this.width/(this.width-d),0),this.paddingRight=Math.max((f-h+r)*this.width/(this.width-h),0)}else{let d=e.height/2,h=t.height/2;o==="start"?(d=0,h=t.height):o==="end"&&(d=e.height,h=0),this.paddingTop=d+r,this.paddingBottom=h+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,n;for(e=0,n=t.length;e({width:r[w]||0,height:a[w]||0});return{first:_(0),last:_(e-1),widest:_(y),highest:_(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 zr(this._alignToPixels?ye(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*i?a/n:l/i:l*i0}_computeGridLineItems(t){let e=this.axis,n=this.chart,i=this.options,{grid:o,position:r,border:a}=i,l=o.offset,c=this.isHorizontal(),h=this.ticks.length+(l?1:0),u=Ks(o),f=[],g=a.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,b=function(R){return ye(n,R,p)},x,C,k,S,y,v,_,w,T,E,M,L;if(r==="top")x=b(this.bottom),v=this.bottom-u,w=x-m,E=b(t.top)+m,L=t.bottom;else if(r==="bottom")x=b(this.top),E=t.top,L=b(t.bottom)-m,v=x+m,w=this.top+u;else if(r==="left")x=b(this.right),y=this.right-u,_=x-m,T=b(t.left)+m,M=t.right;else if(r==="right")x=b(this.left),T=t.left,M=b(t.right)-m,y=x+m,_=this.left+u;else if(e==="x"){if(r==="center")x=b((t.top+t.bottom)/2+.5);else if(et(r)){let R=Object.keys(r)[0],D=r[R];x=b(this.chart.scales[R].getPixelForValue(D))}E=t.top,L=t.bottom,v=x+m,w=v+u}else if(e==="y"){if(r==="center")x=b((t.left+t.right)/2);else if(et(r)){let R=Object.keys(r)[0],D=r[R];x=b(this.chart.scales[R].getPixelForValue(D))}y=x-m,_=y-u,T=t.left,M=t.right}let I=J(i.ticks.maxTicksLimit,h),F=Math.max(1,Math.ceil(h/I));for(C=0;C0&&(P-=G/2);break}z={left:P,top:B,width:G+A.width,height:$+A.height,color:F.backdropColor}}m.push({label:k,font:w,textOffset:M,options:{rotation:p,color:D,strokeColor:W,strokeWidth:O,textAlign:K,textBaseline:L,translation:[S,y],backdrop:z}})}return m}_getXAxisLabelAlignment(){let{position:t,ticks:e}=this.options;if(-Ht(this.labelRotation))return t==="top"?"left":"right";let i="center";return e.align==="start"?i="left":e.align==="end"?i="right":e.align==="inner"&&(i="inner"),i}_getYAxisLabelAlignment(t){let{position:e,ticks:{crossAlign:n,mirror:i,padding:o}}=this.options,r=this._getLabelSizes(),a=t+o,l=r.widest.width,c,d;return e==="left"?i?(d=this.right+o,n==="near"?c="left":n==="center"?(c="center",d+=l/2):(c="right",d+=l)):(d=this.right-a,n==="near"?c="right":n==="center"?(c="center",d-=l/2):(c="left",d=this.left)):e==="right"?i?(d=this.left+o,n==="near"?c="right":n==="center"?(c="center",d-=l/2):(c="left",d-=l)):(d=this.left+a,n==="near"?c="left":n==="center"?(c="center",d+=l/2):(c="right",d=this.right)):c="right",{textAlign:c,x:d}}_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:n,top:i,width:o,height:r}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(n,i,o,r),t.restore())}getLineWidthForValue(t){let e=this.options.grid;if(!this._isVisible()||!e.display)return 0;let i=this.ticks.findIndex(o=>o.value===t);return i>=0?e.setContext(this.getContext(i)).lineWidth:0}drawGrid(t){let e=this.options.grid,n=this.ctx,i=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t)),o,r,a=(l,c,d)=>{!d.width||!d.color||(n.save(),n.lineWidth=d.width,n.strokeStyle=d.color,n.setLineDash(d.borderDash||[]),n.lineDashOffset=d.borderDashOffset,n.beginPath(),n.moveTo(l.x,l.y),n.lineTo(c.x,c.y),n.stroke(),n.restore())};if(e.display)for(o=0,r=i.length;o{this.draw(o)}}]:[{z:n,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:i,draw:()=>{this.drawBorder()}},{z:e,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(t){let e=this.chart.getSortedVisibleDatasetMetas(),n=this.axis+"AxisID",i=[],o,r;for(o=0,r=e.length;o{let o=n||this._getRegistryForType(i);n||o.isForType(i)||o===this.plugins&&i.id?this._exec(t,o,i):rt(i,r=>{let a=n||this._getRegistryForType(r);this._exec(t,a,r)})})}_exec(t,e,n){let i=Rn(t);ct(n["before"+i],[],n),e[t](n),ct(n["after"+i],[],n)}_getRegistryForType(t){for(let e=0;eo.filter(a=>!r.some(l=>a.plugin.id===l.plugin.id));this._notify(i(e,n),t,"stop"),this._notify(i(n,e),t,"start")}};Aa=new Map,Cl=new Set;Ys=(s,t,e)=>{let n=ce(t,e);n!==void 0&&s.add(n)},_o=class{constructor(t){this._config=xu(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=xl(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(),yl(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return Un(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,e){return Un(`${t}.transition.${e}`,()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,e){return Un(`${t}-${e}`,()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]])}pluginScopeKeys(t){let e=t.id,n=this.type;return Un(`${n}-plugin-${e}`,()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]])}_cachedScopes(t,e){let n=this._scopeCache,i=n.get(t);return(!i||e)&&(i=new Map,n.set(t,i)),i}getOptionScopes(t,e,n){let{options:i,type:o}=this,r=this._cachedScopes(t,n),a=r.get(e);if(a)return a;let l=new Set;e.forEach(d=>{t&&(l.add(t),d.forEach(h=>Ys(l,t,h))),d.forEach(h=>Ys(l,i,h)),d.forEach(h=>Ys(l,ve[o]||{},h)),d.forEach(h=>Ys(l,ut,h)),d.forEach(h=>Ys(l,Fn,h))});let c=Array.from(l);return c.length===0&&c.push(Object.create(null)),Cl.has(e)&&r.set(e,c),c}chartOptionScopes(){let{options:t,type:e}=this;return[t,ve[e]||{},ut.datasets[e]||{},{type:e},ut,Fn]}resolveNamedOptions(t,e,n,i=[""]){let o={$shared:!0},{resolver:r,subPrefixes:a}=Ra(this._resolverCache,t,i),l=r;if(_u(r,e)){o.$shared=!1,n=ae(n)?n():n;let c=this.createResolver(t,n,a);l=Re(r,n,c)}for(let c of e)o[c]=l[c];return o}createResolver(t,e,n=[""],i){let{resolver:o}=Ra(this._resolverCache,t,n);return et(e)?Re(o,e,void 0,i):o}};Cu=s=>et(s)&&Object.getOwnPropertyNames(s).some(t=>ae(s[t]));Su="4.5.1",Eu=["top","bottom","left","right","chartArea"];Xn={},Fa=s=>{let t=_l(s);return Object.values(Xn).filter(e=>e.canvas===t).pop()};ne=class{static register(...t){Ut.add(...t),Va()}static unregister(...t){Ut.remove(...t),Va()}constructor(t,e){let n=this.config=new _o(e),i=_l(t),o=Fa(i);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=n.createResolver(n.chartOptionScopes(),this.getContext());this.platform=new(n.platform||vl(i)),this.platform.updateConfig(n);let a=this.platform.acquireContext(i,r.aspectRatio),l=a&&a.canvas,c=l&&l.height,d=l&&l.width;if(this.id=Or(),this.ctx=a,this.canvas=l,this.width=d,this.height=c,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 yo,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=Ur(h=>this.update(h),r.resizeDelay||0),this._dataChanges=[],Xn[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}se.listen(this,"complete",Ia),se.listen(this,"progress",ku),this._initialize(),this.attached&&this.update()}get aspectRatio(){let{options:{aspectRatio:t,maintainAspectRatio:e},width:n,height:i,_aspectRatio:o}=this;return tt(t)?e&&o?o:i?n/i: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():Qi(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return ji(this.canvas,this.ctx),this}stop(){return se.stop(this),this}resize(t,e){se.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){let n=this.options,i=this.canvas,o=n.maintainAspectRatio&&this.aspectRatio,r=this.platform.getMaximumSize(i,t,e,o),a=n.devicePixelRatio||this.platform.getDevicePixelRatio(),l=this.width?"resize":"attach";this.width=r.width,this.height=r.height,this._aspectRatio=this.aspectRatio,Qi(this,a,!0)&&(this.notifyPlugins("resize",{size:r}),ct(n.onResize,[this,r],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){let e=this.options.scales||{};rt(e,(n,i)=>{n.id=i})}buildOrUpdateScales(){let t=this.options,e=t.scales,n=this.scales,i=Object.keys(n).reduce((r,a)=>(r[a]=!1,r),{}),o=[];e&&(o=o.concat(Object.keys(e).map(r=>{let a=e[r],l=Co(r,a),c=l==="r",d=l==="x";return{options:a,dposition:c?"chartArea":d?"bottom":"left",dtype:c?"radialLinear":d?"category":"linear"}}))),rt(o,r=>{let a=r.options,l=a.id,c=Co(l,a),d=J(a.type,r.dtype);(a.position===void 0||Pa(a.position,c)!==Pa(r.dposition))&&(a.position=r.dposition),i[l]=!0;let h=null;if(l in n&&n[l].type===d)h=n[l];else{let u=Ut.getScale(d);h=new u({id:l,type:d,ctx:this.ctx,chart:this}),n[h.id]=h}h.init(a,t)}),rt(i,(r,a)=>{r||delete n[a]}),rt(n,r=>{St.configure(this,r,r.options),St.addBox(this,r)})}_updateMetasets(){let t=this._metasets,e=this.data.datasets.length,n=t.length;if(t.sort((i,o)=>i.index-o.index),n>e){for(let i=e;ie.length&&delete this._stacks,t.forEach((n,i)=>{e.filter(o=>o===n._dataset).length===0&&this._destroyDatasetMeta(i)})}buildOrUpdateControllers(){let t=[],e=this.data.datasets,n,i;for(this._removeUnreferencedMetasets(),n=0,i=e.length;n{this.getDatasetMeta(e).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){let e=this.config;e.update();let n=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),i=this._animationsDisabled=!n.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 c=0,d=this.data.datasets.length;c{c.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(Oa("z","_idx"));let{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){rt(this.scales,t=>{St.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){let t=this.options,e=new Set(Object.keys(this._listeners)),n=new Set(t.events);(!Ai(e,n)||!!this._responsiveListeners!==t.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){let{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(let{method:n,start:i,count:o}of e){let r=n==="_removeElements"?-o:o;wu(t,i,r)}}_getUniformDataChanges(){let t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];let e=this.data.datasets.length,n=o=>new Set(t.filter(r=>r[0]===o).map((r,a)=>a+","+r.splice(1).join(","))),i=n(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;St.update(this,this.width,this.height,t);let e=this.chartArea,n=e.width<=0||e.height<=0;this._layers=[],rt(this.boxes,i=>{n&&i.position==="chartArea"||(i.configure&&i.configure(),this._layers.push(...i._layers()))},this),this._layers.forEach((i,o)=>{i._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})!==!1){for(let e=0,n=this.data.datasets.length;e=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){let e=this.ctx,n={meta:t,index:t.index,cancelable:!0},i=no(this,t);this.notifyPlugins("beforeDatasetDraw",n)!==!1&&(i&&Hs(e,i),t.controller.draw(),i&&$s(e),n.cancelable=!1,this.notifyPlugins("afterDatasetDraw",n))}isPointInArea(t){return Zt(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,n,i){let o=fl.modes[e];return typeof o=="function"?o(this,t,n,i):[]}getDatasetMeta(t){let e=this.data.datasets[t],n=this._metasets,i=n.filter(o=>o&&o._dataset===e).pop();return i||(i={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},n.push(i)),i}getContext(){return this.$context||(this.$context=de(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){let e=this.data.datasets[t];if(!e)return!1;let n=this.getDatasetMeta(t);return typeof n.hidden=="boolean"?!n.hidden:!e.hidden}setDatasetVisibility(t,e){let n=this.getDatasetMeta(t);n.hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,n){let i=n?"show":"hide",o=this.getDatasetMeta(t),r=o.controller._resolveAnimations(void 0,i);ls(e)?(o.data[e].hidden=!n,this.update()):(this.setDatasetVisibility(t,n),r.update(o,{visible:n}),this.update(a=>a.datasetIndex===t?i: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(),se.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,o,r),t[o]=r},i=(o,r,a)=>{o.offsetX=r,o.offsetY=a,this._eventHandler(o)};rt(this.options.events,o=>n(o,i))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});let t=this._responsiveListeners,e=this.platform,n=(l,c)=>{e.addEventListener(this,l,c),t[l]=c},i=(l,c)=>{t[l]&&(e.removeEventListener(this,l,c),delete t[l])},o=(l,c)=>{this.canvas&&this.resize(l,c)},r,a=()=>{i("attach",a),this.attached=!0,this.resize(),n("resize",o),n("detach",r)};r=()=>{this.attached=!1,i("resize",o),this._stop(),this._resize(0,0),n("attach",a)},e.isAttached(this.canvas)?a():r()}unbindEvents(){rt(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},rt(this._responsiveListeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._responsiveListeners=void 0}updateHoverStyle(t,e,n){let i=n?"set":"remove",o,r,a,l;for(e==="dataset"&&(o=this.getDatasetMeta(t[0].datasetIndex),o.controller["_"+i+"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}});!zs(n,e)&&(this._active=n,this._lastEvent=null,this._updateHoverStyles(n,e))}notifyPlugins(t,e,n){return this._plugins.notify(this,t,e,n)}isPluginEnabled(t){return this._plugins._cache.filter(e=>e.plugin.id===t).length===1}_updateHoverStyles(t,e,n){let i=this.options.hover,o=(l,c)=>l.filter(d=>!c.some(h=>d.datasetIndex===h.datasetIndex&&d.index===h.index)),r=o(e,t),a=n?t:o(t,e);r.length&&this.updateHoverStyle(r,i.mode,!1),a.length&&i.mode&&this.updateHoverStyle(a,i.mode,!0)}_eventHandler(t,e){let n={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},i=r=>(r.options.events||this.options.events).includes(t.native.type);if(this.notifyPlugins("beforeEvent",n,i)===!1)return;let o=this._handleEvent(t,e,n.inChartArea);return n.cancelable=!1,this.notifyPlugins("afterEvent",n,i),(o||n.changed)&&this.render(),this}_handleEvent(t,e,n){let{_active:i=[],options:o}=this,r=e,a=this._getActiveElements(t,i,n,r),l=Vr(t),c=Du(t,this._lastEvent,n,l);n&&(this._lastEvent=null,ct(o.onHover,[t,a,this],this),l&&ct(o.onClick,[t,a,this],this));let d=!zs(a,i);return(d||e)&&(this._active=a,this._updateHoverStyles(a,i,e)),this._lastEvent=c,d}_getActiveElements(t,e,n,i){if(t.type==="mouseout")return[];if(!n)return e;let o=this.options.hover;return this.getElementsAtEventForMode(t,o.mode,o,i)}};j(ne,"defaults",ut),j(ne,"instances",Xn),j(ne,"overrides",ve),j(ne,"registry",Ut),j(ne,"version",Su),j(ne,"getChart",Fa);Se=class extends Rt{constructor(e){super();j(this,"circumference");j(this,"endAngle");j(this,"fullCircles");j(this,"innerRadius");j(this,"outerRadius");j(this,"pixelMargin");j(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,n,i){let o=this.getProps(["x","y"],i),{angle:r,distance:a}=Ii(o,{x:e,y:n}),{startAngle:l,endAngle:c,innerRadius:d,outerRadius:h,circumference:u}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),f=(this.options.spacing+this.options.borderWidth)/2,g=J(u,c-l),p=ds(r,l,c)&&l!==c,m=g>=ht||p,b=te(a,d+f,h+f);return m&&b}getCenterPoint(e){let{x:n,y:i,startAngle:o,endAngle:r,innerRadius:a,outerRadius:l}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],e),{offset:c,spacing:d}=this.options,h=(o+r)/2,u=(a+l+d+c)/2;return{x:n+Math.cos(h)*u,y:i+Math.sin(h)*u}}tooltipPosition(e){return this.getCenterPoint(e)}draw(e){let{options:n,circumference:i}=this,o=(n.offset||0)/4,r=(n.spacing||0)/2,a=n.circular;if(this.pixelMargin=n.borderAlign==="inner"?.33:0,this.fullCircles=i>ht?Math.floor(i/ht):0,i===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 c=1-Math.sin(Math.min(nt,i||0)),d=o*c;e.fillStyle=n.backgroundColor,e.strokeStyle=n.borderColor,Ru(e,this,d,r,a),Pu(e,this,d,r,a),e.restore()}};j(Se,"id","arc"),j(Se,"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}),j(Se,"defaultRoutes",{backgroundColor:"backgroundColor"}),j(Se,"descriptors",{_scriptable:!0,_indexable:e=>e!=="borderDash"});Hu=typeof Path2D=="function";Kt=class extends Rt{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 n=this.options;if((n.tension||n.cubicInterpolationMode==="monotone")&&!n.stepped&&!this._pointsUpdated){let i=n.spanGaps?this._loop:this._fullLoop;sa(this._points,n,t,i,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=la(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,n=t.length;return n&&e[t[n-1].end]}interpolate(t,e){let n=this.options,i=t[e],o=this.points,r=so(this,{property:e,start:i,end:i});if(!r.length)return;let a=[],l=Nu(n),c,d;for(c=0,d=r.length;ct!=="borderDash"&&t!=="fill"});$e=class extends Rt{constructor(e){super();j(this,"parsed");j(this,"skip");j(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,n,i){let o=this.options,{x:r,y:a}=this.getProps(["x","y"],i);return Math.pow(e-r,2)+Math.pow(n-a,2)s.replace("rgb(","rgba(").replace(")",", 0.5)"));Tl={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(s,t,e){if(!e.enabled)return;let{data:{datasets:n},options:i}=s.config,{elements:o}=i,r=za(n)||Zu(i)||o&&za(o)||Ju();if(!e.forceOverride&&r)return;let a=Qu(s);n.forEach(a)}};Al={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(s,t,e)=>{if(!e.enabled){Ha(s);return}let n=s.width;s.data.datasets.forEach((i,o)=>{let{_data:r,indexAxis:a}=i,l=s.getDatasetMeta(o),c=r||i.data;if(gs([a,s.options.indexAxis])==="y"||!l.controller.supportsDecimation)return;let d=s.scales[l.xAxisID];if(d.type!=="linear"&&d.type!=="time"||s.options.parsing)return;let{start:h,count:u}=sf(l,c),f=e.threshold||4*n;if(u<=f){Ll(i);return}tt(r)&&(i._data=c,delete i.data,Object.defineProperty(i,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(p){this._data=p}}));let g;switch(e.algorithm){case"lttb":g=tf(c,h,u,n,e);break;case"min-max":g=ef(c,h,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${e.algorithm}'`)}i._decimated=g})},destroy(s){Ha(s)}};si=class{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,n){let{x:i,y:o,radius:r}=this;return e=e||{start:0,end:ht},t.arc(i,o,r,e.end,e.start,!0),!n.bounds}interpolate(t){let{x:e,y:n,radius:i}=this,o=t.angle;return{x:e+Math.cos(o)*i,y:n+Math.sin(o)*i,angle:o}}};Pl={id:"filler",afterDatasetsUpdate(s,t,e){let n=(s.data.datasets||[]).length,i=[],o,r,a,l;for(r=0;r=0;--r){let a=i[r].$filler;a&&(a.line.updateControlPoints(o,a.axis),n&&a.fill&&go(s.ctx,a,o))}},beforeDatasetsDraw(s,t,e){if(e.drawTime!=="beforeDatasetsDraw")return;let n=s.getSortedVisibleDatasetMetas();for(let i=n.length-1;i>=0;--i){let o=n[i].$filler;Wa(o)&&go(s.ctx,o,s.chartArea)}},beforeDatasetDraw(s,t,e){let n=t.meta.$filler;!Wa(n)||e.drawTime!=="beforeDatasetDraw"||go(s.ctx,n,s.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}},Ya=(s,t)=>{let{boxHeight:e=t,boxWidth:n=t}=s;return s.usePointStyle&&(e=Math.min(e,t),n=s.pointStyleWidth||Math.min(n,t)),{boxWidth:n,boxHeight:e,itemHeight:Math.max(t,e)}},Sf=(s,t)=>s!==null&&t!==null&&s.datasetIndex===t.datasetIndex&&s.index===t.index,ni=class extends Rt{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,n){this.maxWidth=t,this.maxHeight=e,this._margins=n,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(n=>t.filter(n,this.chart.data))),t.sort&&(e=e.sort((n,i)=>t.sort(n,i,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 n=t.labels,i=bt(n.font),o=i.size,r=this._computeTitleHeight(),{boxWidth:a,itemHeight:l}=Ya(n,o),c,d;e.font=i.string,this.isHorizontal()?(c=this.maxWidth,d=this._fitRows(r,o,a,l)+10):(d=this.maxHeight,c=this._fitCols(r,i,a,l)+10),this.width=Math.min(c,t.maxWidth||this.maxWidth),this.height=Math.min(d,t.maxHeight||this.maxHeight)}_fitRows(t,e,n,i){let{ctx:o,maxWidth:r,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],c=this.lineWidths=[0],d=i+a,h=t;o.textAlign="left",o.textBaseline="middle";let u=-1,f=-d;return this.legendItems.forEach((g,p)=>{let m=n+e/2+o.measureText(g.text).width;(p===0||c[c.length-1]+m+2*a>r)&&(h+=d,c[c.length-(p>0?0:1)]=0,f+=d,u++),l[p]={left:0,top:f,row:u,width:m,height:i},c[c.length-1]+=m+a}),h}_fitCols(t,e,n,i){let{ctx:o,maxHeight:r,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],c=this.columnSizes=[],d=r-t,h=a,u=0,f=0,g=0,p=0;return this.legendItems.forEach((m,b)=>{let{itemWidth:x,itemHeight:C}=Ef(n,e,o,m,i);b>0&&f+C+2*a>d&&(h+=u+a,c.push({width:u,height:f}),g+=u+a,p++,u=f=0),l[b]={left:g,top:f,col:p,width:x,height:C},u=Math.max(u,x),f+=C+a}),h+=u,c.push({width:u,height:f}),h}adjustHitBoxes(){if(!this.options.display)return;let t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:n,labels:{padding:i},rtl:o}}=this,r=Oe(o,this.left,this.width);if(this.isHorizontal()){let a=0,l=Ct(n,this.left+i,this.right-this.lineWidths[a]);for(let c of e)a!==c.row&&(a=c.row,l=Ct(n,this.left+i,this.right-this.lineWidths[a])),c.top+=this.top+t+i,c.left=r.leftForLtr(r.x(l),c.width),l+=c.width+i}else{let a=0,l=Ct(n,this.top+t+i,this.bottom-this.columnSizes[a].height);for(let c of e)c.col!==a&&(a=c.col,l=Ct(n,this.top+t+i,this.bottom-this.columnSizes[a].height)),c.top=l,c.left+=this.left+i,c.left=r.leftForLtr(r.x(c.left),c.width),l+=c.height+i}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){let t=this.ctx;Hs(t,this),this._draw(),$s(t)}}_draw(){let{options:t,columnSizes:e,lineWidths:n,ctx:i}=this,{align:o,labels:r}=t,a=ut.color,l=Oe(t.rtl,this.left,this.width),c=bt(r.font),{padding:d}=r,h=c.size,u=h/2,f;this.drawTitle(),i.textAlign=l.textAlign("left"),i.textBaseline="middle",i.lineWidth=.5,i.font=c.string;let{boxWidth:g,boxHeight:p,itemHeight:m}=Ya(r,h),b=function(y,v,_){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;i.save();let w=J(_.lineWidth,1);if(i.fillStyle=J(_.fillStyle,a),i.lineCap=J(_.lineCap,"butt"),i.lineDashOffset=J(_.lineDashOffset,0),i.lineJoin=J(_.lineJoin,"miter"),i.lineWidth=w,i.strokeStyle=J(_.strokeStyle,a),i.setLineDash(J(_.lineDash,[])),r.usePointStyle){let T={radius:p*Math.SQRT2/2,pointStyle:_.pointStyle,rotation:_.rotation,borderWidth:w},E=l.xPlus(y,g/2),M=v+u;Ui(i,T,E,M,r.pointStyleWidth&&g)}else{let T=v+Math.max((h-p)/2,0),E=l.leftForLtr(y,g),M=Ce(_.borderRadius);i.beginPath(),Object.values(M).some(L=>L!==0)?fs(i,{x:E,y:T,w:g,h:p,radius:M}):i.rect(E,T,g,p),i.fill(),w!==0&&i.stroke()}i.restore()},x=function(y,v,_){xe(i,_.text,y,v+m/2,c,{strikethrough:_.hidden,textAlign:l.textAlign(_.textAlign)})},C=this.isHorizontal(),k=this._computeTitleHeight();C?f={x:Ct(o,this.left+d,this.right-n[0]),y:this.top+d+k,line:0}:f={x:this.left+d,y:Ct(o,this.top+k+d,this.bottom-e[0].height),line:0},Ji(this.ctx,t.textDirection);let S=m+d;this.legendItems.forEach((y,v)=>{i.strokeStyle=y.fontColor,i.fillStyle=y.fontColor;let _=i.measureText(y.text).width,w=l.textAlign(y.textAlign||(y.textAlign=r.textAlign)),T=g+u+_,E=f.x,M=f.y;l.setWidth(this.width),C?v>0&&E+T+d>this.right&&(M=f.y+=S,f.line++,E=f.x=Ct(o,this.left+d,this.right-n[f.line])):v>0&&M+S>this.bottom&&(E=f.x=E+e[f.line].width+d,f.line++,M=f.y=Ct(o,this.top+k+d,this.bottom-e[f.line].height));let L=l.x(E);if(b(L,M,y),E=Kr(w,E+g+u,C?E+T:this.right,t.rtl),x(l.x(E),M,y),C)f.x+=T+d;else if(typeof y.text!="string"){let I=c.lineHeight;f.y+=Ol(y,I)+d}else f.y+=S}),to(this.ctx,t.textDirection)}drawTitle(){let t=this.options,e=t.title,n=bt(e.font),i=_t(e.padding);if(!e.display)return;let o=Oe(t.rtl,this.left,this.width),r=this.ctx,a=e.position,l=n.size/2,c=i.top+l,d,h=this.left,u=this.width;if(this.isHorizontal())u=Math.max(...this.lineWidths),d=this.top+c,h=Ct(t.align,h,this.right-u);else{let g=this.columnSizes.reduce((p,m)=>Math.max(p,m.height),0);d=c+Ct(t.align,this.top,this.bottom-g-t.labels.padding-this._computeTitleHeight())}let f=Ct(a,h,h+u);r.textAlign=o.textAlign(In(a)),r.textBaseline="middle",r.strokeStyle=e.color,r.fillStyle=e.color,r.font=n.string,xe(r,e.text,f,d,n)}_computeTitleHeight(){let t=this.options.title,e=bt(t.font),n=_t(t.padding);return t.display?e.lineHeight+n.height:0}_getLegendItemAt(t,e){let n,i,o;if(te(t,this.left,this.right)&&te(e,this.top,this.bottom)){for(o=this.legendHitBoxes,n=0;ns.chart.options.color,boxWidth:40,padding:10,generateLabels(s){let t=s.data.datasets,{labels:{usePointStyle:e,pointStyle:n,textAlign:i,color:o,useBorderRadius:r,borderRadius:a}}=s.legend.options;return s._getSortedDatasetMetas().map(l=>{let c=l.controller.getStyle(e?0:void 0),d=_t(c.borderWidth);return{text:t[l.index].label,fillStyle:c.backgroundColor,fontColor:o,hidden:!l.visible,lineCap:c.borderCapStyle,lineDash:c.borderDash,lineDashOffset:c.borderDashOffset,lineJoin:c.borderJoinStyle,lineWidth:(d.width+d.height)/4,strokeStyle:c.borderColor,pointStyle:n||c.pointStyle,rotation:c.rotation,textAlign:i||c.textAlign,borderRadius:r&&(a||c.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)}}},tn=class extends Rt{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 n=this.options;if(this.left=0,this.top=0,!n.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=t,this.height=this.bottom=e;let i=dt(n.text)?n.text.length:1;this._padding=_t(n.padding);let o=i*bt(n.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:n,bottom:i,right:o,options:r}=this,a=r.align,l=0,c,d,h;return this.isHorizontal()?(d=Ct(a,n,o),h=e+t,c=o-n):(r.position==="left"?(d=n+t,h=Ct(a,i,e),l=nt*-.5):(d=o-t,h=Ct(a,e,i),l=nt*.5),c=i-e),{titleX:d,titleY:h,maxWidth:c,rotation:l}}draw(){let t=this.ctx,e=this.options;if(!e.display)return;let n=bt(e.font),o=n.lineHeight/2+this._padding.top,{titleX:r,titleY:a,maxWidth:l,rotation:c}=this._drawArgs(o);xe(t,e.text,0,0,n,{color:e.color,maxWidth:l,rotation:c,textAlign:In(e.align),textBaseline:"middle",translation:[r,a]})}};Fl={id:"title",_element:tn,start(s,t,e){Mf(s,e)},stop(s){let t=s.titleBlock;St.removeBox(s,t),delete s.titleBlock},beforeUpdate(s,t,e){let n=s.titleBlock;St.configure(s,n,e),n.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}},Kn=new WeakMap,Vl={id:"subtitle",start(s,t,e){let n=new tn({ctx:s.ctx,options:e,chart:s});St.configure(s,n,e),St.addBox(s,n),Kn.set(s,n)},stop(s){St.removeBox(s,Kn.get(s)),Kn.delete(s)},beforeUpdate(s,t,e){let n=Kn.get(s);St.configure(s,n,e),n.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}},qs={average(s){if(!s.length)return!1;let t,e,n=new Set,i=0,o=0;for(t=0,e=s.length;ta+l)/n.size,y:i/o}},nearest(s,t){if(!s.length)return!1;let e=t.x,n=t.y,i=Number.POSITIVE_INFINITY,o,r,a;for(o=0,r=s.length;o0){let t=s[0],e=t.chart.data.labels,n=e?e.length:0;if(this&&this.options&&this.options.mode==="dataset")return t.dataset.label||"";if(t.label)return t.label;if(n>0&&t.dataIndex{let r={before:[],lines:[],after:[]},a=Za(n,o);ee(r.before,he(Tt(a,"beforeLabel",this,o))),ee(r.lines,Tt(a,"label",this,o)),ee(r.after,he(Tt(a,"afterLabel",this,o))),i.push(r)}),i}getAfterBody(t,e){return Qa(Tt(e.callbacks,"afterBody",this,t))}getFooter(t,e){let{callbacks:n}=e,i=Tt(n,"beforeFooter",this,t),o=Tt(n,"footer",this,t),r=Tt(n,"afterFooter",this,t),a=[];return a=ee(a,he(i)),a=ee(a,he(o)),a=ee(a,he(r)),a}_createItems(t){let e=this._active,n=this.chart.data,i=[],o=[],r=[],a=[],l,c;for(l=0,c=e.length;lt.filter(d,h,u,n))),t.itemSort&&(a=a.sort((d,h)=>t.itemSort(d,h,n))),rt(a,d=>{let h=Za(t.callbacks,d);i.push(Tt(h,"labelColor",this,d)),o.push(Tt(h,"labelPointStyle",this,d)),r.push(Tt(h,"labelTextColor",this,d))}),this.labelColors=i,this.labelPointStyles=o,this.labelTextColors=r,this.dataPoints=a,a}update(t,e){let n=this.options.setContext(this.getContext()),i=this._active,o,r=[];if(!i.length)this.opacity!==0&&(o={opacity:0});else{let a=qs[n.position].call(this,i,this._eventPosition);r=this._createItems(n),this.title=this.getTitle(r,n),this.beforeBody=this.getBeforeBody(r,n),this.body=this.getBody(r,n),this.afterBody=this.getAfterBody(r,n),this.footer=this.getFooter(r,n);let l=this._size=Ga(this,n),c=Object.assign({},a,l),d=qa(this.chart,n,c),h=Xa(n,c,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,o={opacity:1,x:h.x,y:h.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&&n.external&&n.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,n,i){let o=this.getCaretPosition(t,n,i);e.lineTo(o.x1,o.y1),e.lineTo(o.x2,o.y2),e.lineTo(o.x3,o.y3)}getCaretPosition(t,e,n){let{xAlign:i,yAlign:o}=this,{caretSize:r,cornerRadius:a}=n,{topLeft:l,topRight:c,bottomLeft:d,bottomRight:h}=Ce(a),{x:u,y:f}=t,{width:g,height:p}=e,m,b,x,C,k,S;return o==="center"?(k=f+p/2,i==="left"?(m=u,b=m-r,C=k+r,S=k-r):(m=u+g,b=m+r,C=k-r,S=k+r),x=m):(i==="left"?b=u+Math.max(l,d)+r:i==="right"?b=u+g-Math.max(c,h)-r:b=this.caretX,o==="top"?(C=f,k=C-r,m=b-r,x=b+r):(C=f+p,k=C+r,m=b+r,x=b-r),S=C),{x1:m,x2:b,x3:x,y1:C,y2:k,y3:S}}drawTitle(t,e,n){let i=this.title,o=i.length,r,a,l;if(o){let c=Oe(n.rtl,this.x,this.width);for(t.x=Yn(this,n.titleAlign,n),e.textAlign=c.textAlign(n.titleAlign),e.textBaseline="middle",r=bt(n.titleFont),a=n.titleSpacing,e.fillStyle=n.titleColor,e.font=r.string,l=0;lx!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,fs(t,{x:p,y:g,w:c,h:l,radius:b}),t.fill(),t.stroke(),t.fillStyle=r.backgroundColor,t.beginPath(),fs(t,{x:m,y:g+1,w:c-2,h:l-2,radius:b}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(p,g,c,l),t.strokeRect(p,g,c,l),t.fillStyle=r.backgroundColor,t.fillRect(m,g+1,c-2,l-2))}t.fillStyle=this.labelTextColors[n]}drawBody(t,e,n){let{body:i}=this,{bodySpacing:o,bodyAlign:r,displayColors:a,boxHeight:l,boxWidth:c,boxPadding:d}=n,h=bt(n.bodyFont),u=h.lineHeight,f=0,g=Oe(n.rtl,this.x,this.width),p=function(_){e.fillText(_,g.x(t.x+f),t.y+u/2),t.y+=u+o},m=g.textAlign(r),b,x,C,k,S,y,v;for(e.textAlign=r,e.textBaseline="middle",e.font=h.string,t.x=Yn(this,m,n),e.fillStyle=n.bodyColor,rt(this.beforeBody,p),f=a&&m!=="right"?r==="center"?c/2+d:c+2+d:0,k=0,y=i.length;k0&&e.stroke()}_updateAnimationTarget(t){let e=this.chart,n=this.$animations,i=n&&n.x,o=n&&n.y;if(i||o){let r=qs[t.position].call(this,this._active,this._eventPosition);if(!r)return;let a=this._size=Ga(this,t),l=Object.assign({},r,this._size),c=qa(e,t,l),d=Xa(t,l,c,e);(i._to!==d.x||o._to!==d.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=a.width,this.height=a.height,this.caretX=r.x,this.caretY=r.y,this._resolveAnimations().update(this,d))}}_willRender(){return!!this.opacity}draw(t){let e=this.options.setContext(this.getContext()),n=this.opacity;if(!n)return;this._updateAnimationTarget(e);let i={width:this.width,height:this.height},o={x:this.x,y:this.y};n=Math.abs(n)<.001?0:n;let r=_t(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=n,this.drawBackground(o,t,i,e),Ji(t,e.textDirection),o.y+=r.top,this.drawTitle(o,t,e),this.drawBody(o,t,e),this.drawFooter(o,t,e),to(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){let n=this._active,i=t.map(({datasetIndex:a,index:l})=>{let c=this.chart.getDatasetMeta(a);if(!c)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:c.data[l],index:l}}),o=!zs(n,i),r=this._positionChanged(i,e);(o||r)&&(this._active=i,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,n=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;let i=this.options,o=this._active||[],r=this._getActiveElements(t,o,e,n),a=this._positionChanged(r,t),l=e||!zs(r,o)||a;return l&&(this._active=r,(i.enabled||i.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),l}_getActiveElements(t,e,n,i){let o=this.options;if(t.type==="mouseout")return[];if(!i)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,n);return o.reverse&&r.reverse(),r}_positionChanged(t,e){let{caretX:n,caretY:i,options:o}=this,r=qs[o.position].call(this,t,e);return r!==!1&&(n!==r.x||i!==r.y)}};j(Xs,"positioners",qs);Bl={id:"tooltip",_element:Xs,positioners:qs,afterInit(s,t,e){e&&(s.tooltip=new Xs({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:Nl},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"]},zl=Object.freeze({__proto__:null,Colors:Tl,Decimation:Al,Filler:Pl,Legend:Il,SubTitle:Vl,Title:Fl,Tooltip:Bl}),Ff=(s,t,e,n)=>(typeof t=="string"?(e=s.push(t)-1,n.unshift({index:e,label:t})):isNaN(t)&&(e=null),e);Nf=(s,t)=>s===null?null:vt(Math.round(s),0,t);vs=class extends Me{constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){let e=this._addedLabels;if(e.length){let n=this.getLabels();for(let{index:i,label:o}of e)n[i]===o&&n.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(tt(t))return null;let n=this.getLabels();return e=isFinite(e)&&n[e]===t?e:Vf(n,t,J(e,t),this._addedLabels),Nf(e,n.length-1)}determineDataLimits(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),{min:n,max:i}=this.getMinMax(!0);this.options.bounds==="ticks"&&(t||(n=0),e||(i=this.getLabels().length-1)),this.min=n,this.max=i}buildTicks(){let t=this.min,e=this.max,n=this.options.offset,i=[],o=this.getLabels();o=t===0&&e===o.length-1?o:o.slice(t,e+1),this._valueRange=Math.max(o.length-(n?0:1),1),this._startValue=this.min-(n?.5:0);for(let r=t;r<=e;r++)i.push({value:r});return i}getLabelForValue(t){return Ja.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}};j(vs,"id","category"),j(vs,"defaults",{ticks:{callback:Ja}});_s=class extends Me{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 tt(t)||(typeof t=="number"||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){let{beginAtZero:t}=this.options,{minDefined:e,maxDefined:n}=this.getUserBounds(),{min:i,max:o}=this,r=l=>i=e?i:l,a=l=>o=n?o:l;if(t){let l=jt(i),c=jt(o);l<0&&c<0?a(0):l>0&&c>0&&r(0)}if(i===o){let l=o===0?1:Math.abs(o*.05);a(o+l),t||r(i-l)}this.min=i,this.max=o}getTickLimit(){let t=this.options.ticks,{maxTicksLimit:e,stepSize:n}=t,i;return n?(i=Math.ceil(this.max/n)-Math.floor(this.min/n)+1,i>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${n} would result generating up to ${i} ticks. Limiting to 1000.`),i=1e3)):(i=this.computeTickLimit(),e=e||11),e&&(i=Math.min(e,i)),i}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){let t=this.options,e=t.ticks,n=this.getTickLimit();n=Math.max(2,n);let i={maxTicks:n,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=Bf(i,o);return t.bounds==="ticks"&&Pi(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,n=this.max;if(super.configure(),this.options.offset&&t.length){let i=(n-e)/Math.max(t.length-1,1)/2;e-=i,n+=i}this._startValue=e,this._endValue=n,this._valueRange=n-e}getLabelForValue(t){return hs(t,this.chart.options.locale,this.options.ticks.format)}},ys=class extends _s{determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=gt(t)?t:0,this.max=gt(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){let t=this.isHorizontal(),e=t?this.width:this.height,n=Ht(this.options.ticks.minRotation),i=(t?Math.sin(n):Math.cos(n))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,o.lineHeight/i))}getPixelForValue(t){return t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}};j(ys,"id","linear"),j(ys,"defaults",{ticks:{callback:us.formatters.numeric}});en=s=>Math.floor(le(s)),Fe=(s,t)=>Math.pow(10,en(s)+t);xs=class extends Me{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){let n=_s.prototype.parse.apply(this,[t,e]);if(n===0){this._zero=!0;return}return gt(n)&&n>0?n:null}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=gt(t)?Math.max(0,t):null,this.max=gt(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!gt(this._userMin)&&(this.min=t===Fe(this.min,0)?Fe(this.min,-1):Fe(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),n=this.min,i=this.max,o=a=>n=t?n:a,r=a=>i=e?i:a;n===i&&(n<=0?(o(1),r(10)):(o(Fe(n,-1)),r(Fe(i,1)))),n<=0&&o(Fe(i,-1)),i<=0&&r(Fe(n,1)),this.min=n,this.max=i}buildTicks(){let t=this.options,e={min:this._userMin,max:this._userMax},n=Hf(e,this);return t.bounds==="ticks"&&Pi(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}getLabelForValue(t){return t===void 0?"0":hs(t,this.chart.options.locale,this.options.ticks.format)}configure(){let t=this.min;super.configure(),this._startValue=le(t),this._valueRange=le(this.max)-le(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(le(t)-this._startValue)/this._valueRange)}getValueForPixel(t){let e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}};j(xs,"id","logarithmic"),j(xs,"defaults",{ticks:{callback:us.formatters.logarithmic,major:{enabled:!0}}});Ee=class extends _s{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=_t(wo(this.options)/2),e=this.width=this.maxWidth-t.width,n=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+n/2+t.top),this.drawingArea=Math.floor(Math.min(e,n)/2)}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!1);this.min=gt(t)&&!isNaN(t)?t:0,this.max=gt(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/wo(this.options))}generateTickLabels(t){_s.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((e,n)=>{let i=ct(this.options.pointLabels.callback,[e,n],this);return i||i===0?i:""}).filter((e,n)=>this.chart.getDataVisibility(n))}fit(){let t=this.options;t.display&&t.pointLabels.display?Wf(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,n,i){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((n-i)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,n,i))}getIndexAngle(t){let e=ht/(this._pointLabels.length||1),n=this.options.startAngle||0;return xt(t*e+Ht(n))}getDistanceFromCenterForValue(t){if(tt(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(tt(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(h!==0||h===0&&this.min<0){l=this.getDistanceFromCenterForValue(d.value);let u=this.getContext(h),f=i.setContext(u),g=o.setContext(u);Jf(this,f,l,r,g)}}),n.display){for(t.save(),a=r-1;a>=0;a--){let d=n.setContext(this.getPointLabelContext(a)),{color:h,lineWidth:u}=d;!u||!h||(t.lineWidth=u,t.strokeStyle=h,t.setLineDash(d.borderDash),t.lineDashOffset=d.borderDashOffset,l=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),c=this.getPointPosition(a,l),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(c.x,c.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){let t=this.ctx,e=this.options,n=e.ticks;if(!n.display)return;let i=this.getIndexAngle(0),o,r;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(i),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach((a,l)=>{if(l===0&&this.min>=0&&!e.reverse)return;let c=n.setContext(this.getContext(l)),d=bt(c.font);if(o=this.getDistanceFromCenterForValue(this.ticks[l].value),c.showLabelBackdrop){t.font=d.string,r=t.measureText(a.label).width,t.fillStyle=c.backdropColor;let h=_t(c.backdropPadding);t.fillRect(-r/2-h.left,-o-d.size/2-h.top,r+h.width,d.size+h.height)}xe(t,a.label,0,-o,d,{color:c.color,strokeColor:c.textStrokeColor,strokeWidth:c.textStrokeWidth})}),t.restore()}drawTitle(){}};j(Ee,"id","radialLinear"),j(Ee,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:us.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),j(Ee,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),j(Ee,"descriptors",{angleLines:{_fallback:"grid"}});oi={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}},At=Object.keys(oi);De=class extends Me{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 n=t.time||(t.time={}),i=this._adapter=new ul._date(t.adapters.date);i.init(e),as(n.displayFormats,i.formats()),this._parseOpts={parser:n.parser,round:n.round,isoWeekday:n.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return t===void 0?null:ol(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){let t=this.options,e=this._adapter,n=t.time.unit||"day",{min:i,max:o,minDefined:r,maxDefined:a}=this.getUserBounds();function l(c){!r&&!isNaN(c.min)&&(i=Math.min(i,c.min)),!a&&!isNaN(c.max)&&(o=Math.max(o,c.max))}(!r||!a)&&(l(this._getLabelBounds()),(t.bounds!=="ticks"||t.ticks.source!=="labels")&&l(this.getMinMax(!1))),i=gt(i)&&!isNaN(i)?i:+e.startOf(Date.now(),n),o=gt(o)&&!isNaN(o)?o:+e.endOf(Date.now(),n)+1,this.min=Math.min(i,o-1),this.max=Math.max(i+1,o)}_getLabelBounds(){let t=this.getLabelTimestamps(),e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],n=t[t.length-1]),{min:e,max:n}}buildTicks(){let t=this.options,e=t.time,n=t.ticks,i=n.source==="labels"?this.getLabelTimestamps():this._generate();t.bounds==="ticks"&&i.length&&(this.min=this._userMin||i[0],this.max=this._userMax||i[i.length-1]);let o=this.min,r=this.max,a=$r(i,o,r);return this._unit=e.unit||(n.autoSkip?rl(e.minUnit,this.min,this.max,this._getLabelCapacity(o)):eg(this,a.length,e.minUnit,this.min,this.max)),this._majorUnit=!n.major.enabled||this._unit==="year"?void 0:sg(this._unit),this.initOffsets(i),t.reverse&&a.reverse(),ll(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(t=>+t.value))}initOffsets(t=[]){let e=0,n=0,i,o;this.options.offset&&t.length&&(i=this.getDecimalForValue(t[0]),t.length===1?e=1-i:e=(this.getDecimalForValue(t[1])-i)/2,o=this.getDecimalForValue(t[t.length-1]),t.length===1?n=o:n=(o-this.getDecimalForValue(t[t.length-2]))/2);let r=t.length<3?.5:.25;e=vt(e,0,r),n=vt(n,0,r),this._offsets={start:e,end:n,factor:1/(e+1+n)}}_generate(){let t=this._adapter,e=this.min,n=this.max,i=this.options,o=i.time,r=o.unit||rl(o.minUnit,e,n,this._getLabelCapacity(e)),a=J(i.ticks.stepSize,1),l=r==="week"?o.isoWeekday:!1,c=Pe(l)||l===!0,d={},h=e,u,f;if(c&&(h=+t.startOf(h,"isoWeek",l)),h=+t.startOf(h,c?"day":r),t.diff(n,e,r)>1e5*a)throw new Error(e+" and "+n+" are too far apart with stepSize of "+a+" "+r);let g=i.ticks.source==="data"&&this.getDataTimestamps();for(u=h,f=0;u+p)}getLabelForValue(t){let e=this._adapter,n=this.options.time;return n.tooltipFormat?e.format(t,n.tooltipFormat):e.format(t,n.displayFormats.datetime)}format(t,e){let i=this.options.time.displayFormats,o=this._unit,r=e||i[o];return this._adapter.format(t,r)}_tickFormatFunction(t,e,n,i){let o=this.options,r=o.ticks.callback;if(r)return ct(r,[t,e,n],this);let a=o.time.displayFormats,l=this._unit,c=this._majorUnit,d=l&&a[l],h=c&&a[c],u=n[e],f=c&&h&&u&&u.major;return this._adapter.format(t,i||(f?h:d))}generateTickLabels(t){let e,n,i;for(e=0,n=t.length;e0?a:1}getDataTimestamps(){let t=this._cache.data||[],e,n;if(t.length)return t;let i=this.getMatchingVisibleMetas();if(this._normalized&&i.length)return this._cache.data=i[0].controller.getAllParsedValues(this);for(e=0,n=i.length;e=e&&c<=n&&i.push(c);if(i.length<2)return[{time:e,pos:0},{time:n,pos:1}];for(r=0,a=i.length;ri-o)}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;let e=this.getDataTimestamps(),n=this.getLabelTimestamps();return e.length&&n.length?t=this.normalize(e.concat(n)):t=e.length?e:n,t=this._cache.all=t,t}getDecimalForValue(t){return(Gn(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){let e=this._offsets,n=this.getDecimalForPixel(t)/e.factor-e.end;return Gn(this._table,n*this._tableRange+this._minPos,!0)}};j(Cs,"id","timeseries"),j(Cs,"defaults",De.defaults);$l=Object.freeze({__proto__:null,CategoryScale:vs,LinearScale:ys,LogarithmicScale:xs,RadialLinearScale:Ee,TimeScale:De,TimeSeriesScale:Cs}),ig=[hl,wl,zl,$l]});var dg={};Ao(dg,{CardView:()=>Ss,default:()=>ri});module.exports=ic(dg);var it=require("obsidian"),Xl=on(ws());var oc=["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"],rc=[{label:"\u{1F1EA}\u{1F1FA} Schengen 90/180 (example)",scope:{countries:oc},window:{type:"rolling",days:180},threshold:90,note:"Example rule \u2014 add your own in Settings \u2192 CSV Card View."}],hi={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:rc,showResidency:!0},rn="xlsx-card-view";var Po=on(ws()),Oo=require("obsidian"),Ue=["Image","image","Cover","cover","Poster","poster","Thumbnail","thumbnail","Thumb","thumb","Photo","photo","Picture","picture","Img","img"],Ke=["Title","title","Name","name"],Ye=["Category","category","Categories","categories","Genre","genre","Genres","genres","Type","type","Types","types","Tag","tag","Tags","tags","Topic","topic","Topics","topics","Subject","subject","Section","section"],Ge=["Status","status","State","state","Progress","progress","Stage","stage","Read","read","Watched","watched","Seen","seen","Done","done","Completed","completed"],qe=["Notes","notes","Note","note","Summary","summary","Review","review","Quote","quote","Quotes","quotes","Comment","comment","Comments","comments","Description","description","Annotation","annotation"];function an(s,t,e){let n=(t!=null?t:"").trim();if(!n)return null;if(/^(https?:|data:)/i.test(n))return n;let i=n.match(/!?\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/);if(i)n=i[1].trim();else{let r=n.match(/!\[[^\]]*\]\(([^)]+)\)/);r&&(n=r[1].trim())}if(/^(https?:|data:)/i.test(n))return n;let o=s.metadataCache.getFirstLinkpathDest(n,e);return o instanceof Oo.TFile?s.vault.getResourcePath(o):null}var ac=15;function qt(s){return s>=1&&s<=ac}var lc=["0","1","true","false","yes","no",""];function Xe(s){return s.length>0&&s.every(t=>lc.includes(t))}function Qe(s){let t=(s!=null?s:"").toLowerCase().trim();return t==="1"||t==="true"||t==="yes"}function Ds(s){return s.replace(/[\\/:*?"<>|#^[\]]/g,"").replace(/\s+/g," ").trim().slice(0,100)}function Io(s){return s.toLowerCase().replace(/[^\p{L}\p{N}/_-]+/gu,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Xt(s){var i,o;if(!s||!s.trim())return{headers:[],rows:[]};let t=Po.default.parse(s,{header:!0,skipEmptyLines:!0}),e=((i=t.meta.fields)!=null?i:[]).map(String),n=((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:n}}function Ze(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 n=t?t.split("/").filter(Boolean):[];for(let i of s.split("/"))if(!(i===""||i===".")){if(i===".."){n.pop();continue}n.push(i)}return n.join("/")}function Fo(s,t,e){let n=e==="asc"?1:-1;return[...s].sort((i,o)=>{var u,f;let r=((u=i[t])!=null?u:"").trim(),a=((f=o[t])!=null?f:"").trim();if(!r&&!a)return 0;if(!r)return 1;if(!a)return-1;let l=parseFloat(r),c=parseFloat(a);return(!isNaN(l)&&!isNaN(c)&&/^-?[\d.]/.test(r)&&/^-?[\d.]/.test(a)?l-c:r.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"}))*n})}function Dt(s){return s.split(/[\s_-]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function Vo(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 i=cc(e,t);return i&&i!==e&&i!=="\u2014"?i:""}function cc(s,t){var o;let e=t.toLowerCase();if(!["rating","score","score /5"].includes(e))return s;let n=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"}[n])!=null?o:s}function No(s,t){if(/^(year|released|decade)$/i.test((s!=null?s:"").trim()))return!0;let e=t.map(i=>(i!=null?i:"").trim()).filter(Boolean);return e.length<3?!1:e.filter(i=>/^(1[89]|20)\d{2}$/.test(i)).length/e.length>=.8}function Bo(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 zo(s,t,e){var r;if(!t.length)return null;let n=Math.max(12,t.length/3),i=null,o=1/0;for(let a of s){if(e.has(a))continue;let l=new Set;for(let d of t)((r=d[a])!=null?r:"").split(",").forEach(h=>{let u=h.trim();u&&l.add(u)});if(l.size<2||l.size>n)continue;let c=Math.abs(Math.log(l.size/8));cE.remove());let r=document.body.createDiv({cls:"csv-select-picker"});r.style.position="fixed",r.style.zIndex="9999";let a=()=>{let E=s.getBoundingClientRect(),M=r.offsetHeight||280,L=E.bottom+4+M>window.innerHeight&&E.top-4-M>0;r.style.left=E.left+"px",r.style.top=L?E.top-4-M+"px":E.bottom+4+"px"};a();let l=E=>{!r.contains(E.target)&&E.target!==s&&d()},c=E=>{r.contains(E.target)||d()},d=()=>{r.remove(),document.removeEventListener("mousedown",l),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",d)},h=r.createEl("input",{cls:"csv-picker-search",type:"text",placeholder:"Search or add\u2026"});h.focus();let u=r.createDiv({cls:"csv-picker-list"}),f=!!(o!=null&&o.multi),g=E=>E.split(",").map(M=>M.trim()).filter(Boolean),p=new Set(f?g(t):[]),m=()=>n([...p].join(", ")),b=f?Array.from(new Set(e.flatMap(g))):Array.from(new Set(e.filter(Boolean))),x=[],C=0,k=()=>{u.querySelectorAll(".csv-picker-item").forEach((E,M)=>{E.toggleClass("csv-picker-item--hover",M===C),M===C&&E.scrollIntoView({block:"nearest"})})},S=E=>{if(!f){n(E.isClear?"":E.value),d();return}E.isClear?p.clear():(p.has(E.value)?p.delete(E.value):p.add(E.value),E.isAdd&&!b.includes(E.value)&&b.push(E.value)),m(),E.isAdd?(h.value="",_("")):_(h.value)},y=E=>f?p.has(E):E===t,v=()=>f?p.size>0:!!t,_=E=>{u.empty(),x=[];let M=E?b.filter(L=>L.toLowerCase().includes(E.toLowerCase())):b;if(v()){x.push({value:"",isClear:!0});let L=u.createDiv({cls:"csv-picker-item csv-picker-clear"});L.setText(f?"\u2715 Clear all":"\u2715 Clear"),L.addEventListener("mousedown",I=>{I.preventDefault(),S({value:"",isClear:!0})})}if(M.forEach(L=>{x.push({value:L});let I=u.createDiv({cls:`csv-picker-item ${y(L)?"active":""}`});I.setText(f?`${p.has(L)?"\u2713 ":""}${L}`:L),I.addEventListener("mousedown",F=>{F.preventDefault(),S({value:L})})}),E&&!b.some(L=>L.toLowerCase()===E.toLowerCase())){x.push({value:E,isAdd:!0});let L=u.createDiv({cls:"csv-picker-item csv-picker-add"});L.setText(`+ Add "${E}"`),L.addEventListener("mousedown",I=>{I.preventDefault(),S({value:E,isAdd:!0})})}!M.length&&!E&&u.createDiv({cls:"csv-picker-empty",text:"No options yet. Type to add."}),C=Math.min(C,Math.max(x.length-1,0)),k()};f&&r.createEl("button",{cls:"csv-picker-done",text:"Done"}).addEventListener("mousedown",E=>{E.preventDefault(),d()}),_(""),a(),h.addEventListener("input",()=>{C=0,_(h.value),a()});let w=typeof window!="undefined"&&((T=window.matchMedia)==null?void 0:T.call(window,"(pointer: coarse)").matches);setTimeout(()=>{document.addEventListener("mousedown",l),w||(window.addEventListener("scroll",c,!0),window.addEventListener("resize",d))},0),h.addEventListener("keydown",E=>{if(E.key==="Escape"){d();return}if(E.key==="ArrowDown"){E.preventDefault(),x.length&&(C=(C+1)%x.length,k());return}if(E.key==="ArrowUp"){E.preventDefault(),x.length&&(C=(C-1+x.length)%x.length,k());return}if(E.key==="Enter")if(E.preventDefault(),x[C])S(x[C]);else{let M=h.value.trim();M&&(n(M),d())}})}function Ho(s,t,e){return!s[t]||t===e||(s[e]||(s[e]=s[t]),delete s[t]),s}var dc={source:["confirmed","inferred","conflict"],resolved:["yes","no"]};function $o(s){var t;return(t=dc[s.trim().toLowerCase()])!=null?t:null}function It(s){return/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(s.trim())}var ln=/^\d{4}-\d{2}-\d{2}$/;var Ft=require("obsidian");function hn(s,t,e,n,i=It){let o=i(t)&&(e===""||ln.test(e.slice(0,10))),r=o?e.slice(0,10):e,a=s.createEl("input",{cls:n,type:o?"date":"text",value:r});o||(a.placeholder=t);let l=$o(t);if(l){let c=`csv-dl-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-${Math.random().toString(36).slice(2,7)}`,d=s.createEl("datalist");d.id=c,l.forEach(h=>d.createEl("option",{value:h})),a.setAttr("list",c)}return a}var Je=class extends Ft.Modal{constructor(t,e,n,i,o,r,a={},l=()=>!1,c,d,h=It){super(t),this.headers=e,this.isNotesCol=n,this.isSelectCol=i,this.getColumnValues=o,this.onSubmit=r,this.optionPresets=a,this.isBooleanCol=l,this.isCategoricalCol=c!=null?c:u=>this.isSelectCol(u)||qt(this.getColumnValues(u).length),this.titleCol=d!=null?d:this.headers.find(u=>["title","name"].includes(u.toLowerCase())),this.isDateCol=h}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"}),n={};this.headers.forEach(d=>n[d]="");let i=this.titleCol,o=new Map;i&&this.getColumnValues(i).forEach(d=>{let h=d.trim().toLowerCase();h&&!o.has(h)&&o.set(h,d.trim())}),this.headers.forEach(d=>{var m;let h=e.createDiv({cls:"csv-modal-row"});h.createEl("label",{text:Dt(d),cls:"csv-modal-label"});let u=(m=this.optionPresets[d])!=null?m:[],f=d===i,g=Et(d),p=!f&&!this.isNotesCol(d)&&!g&&(u.length>0||this.isCategoricalCol(d));if(this.isBooleanCol(d)){n[d]="0";let b=h.createDiv({cls:"csv-toggle"});b.createDiv({cls:"csv-toggle-knob"}),b.addEventListener("click",()=>{let x=!b.hasClass("is-on");b.toggleClass("is-on",x),n[d]=x?"1":"0"})}else if(this.isNotesCol(d)){let b=h.createEl("textarea",{cls:"csv-modal-textarea",placeholder:"Markdown supported\u2026"});b.addEventListener("input",()=>{n[d]=b.value})}else if(p){let b="__custom__",x=[];[...u,...this.getColumnValues(d)].forEach(S=>{let y=(S!=null?S:"").trim();y&&!x.some(v=>v.toLowerCase()===y.toLowerCase())&&x.push(y)});let C=h.createEl("select",{cls:"csv-modal-select"});C.createEl("option",{text:"\u2014",value:""}),x.forEach(S=>C.createEl("option",{text:S,value:S})),C.createEl("option",{text:"+ Custom\u2026",value:b});let k=h.createEl("input",{cls:"csv-modal-input csv-modal-custom",type:"text",placeholder:`Custom ${Dt(d).toLowerCase()}`});k.hide(),k.addEventListener("input",()=>{n[d]=k.value}),k.addEventListener("keydown",S=>{S.key==="Enter"&&c()}),C.addEventListener("change",()=>{C.value===b?(k.show(),k.focus(),n[d]=k.value):(k.hide(),n[d]=C.value)})}else if(!f&&g&&this.isSelectCol(d)){let x=h.createDiv({cls:"csv-modal-select-wrap"}).createDiv({cls:"csv-select-chip empty"});x.setText("\u2014 click to select \u2014"),x.addEventListener("click",C=>{C.stopPropagation(),Ot(x,n[d],this.getColumnValues(d),k=>{n[d]=k,x.setText(k||"\u2014 click to select \u2014"),x.toggleClass("empty",!k)},t,{multi:Et(d)})})}else{let b=hn(h,d,"","csv-modal-input",x=>this.isDateCol(x));if(b.addEventListener("input",()=>{n[d]=b.value}),b.addEventListener("keydown",x=>{x.key==="Enter"&&c()}),d===i&&o.size){let x=h.createDiv({cls:"csv-modal-dup-hint"});x.hide(),b.addEventListener("input",()=>{let C=o.get(b.value.trim().toLowerCase());C?(x.setText(`\u26A0 \u201C${C}\u201D is already in this file`),x.show()):x.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",()=>c());let c=()=>{if(!Object.values(n).some(h=>h.trim())){new Ft.Notice("Fill in at least one field.");return}this.onSubmit(n),this.close()}}onClose(){this.contentEl.empty()}},ts=class extends Ft.Modal{constructor(e,n,i,o,r,a,l,c,d,h,u,f,g=()=>!1,p=It){super(e);this.vvHandler=null;this.row={...n},this.notesCol=i,this.headers=o,this.filePath=r,this.renderComponent=new Ft.Component,this.isNotesCol=a,this.isSelectCol=l,this.getColumnValues=c,this.onSave=d,this.onDelete=h,this.isCategoricalCol=u!=null?u:m=>this.isSelectCol(m)||!It(m)&&qt(this.getColumnValues(m).length),this.titleCol=f!=null?f:this.headers.find(m=>["title","name","Title","Name"].includes(m)),this.isBooleanCol=g,this.isDateCol=p,this.modalEl.addClass("csv-note-expander-modal")}onOpen(){var g,p,m,b,x;this.renderComponent.load();let{contentEl:e}=this;e.empty(),e.addClass("csv-note-expander");let n=window.visualViewport;if(n){let C=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${n.height}px`)};C(),n.addEventListener("resize",C),n.addEventListener("scroll",C),this.vvHandler=C}let i=e.createDiv({cls:"csv-expander-header"});i.createDiv({cls:"csv-expander-title",text:(p=this.row[(g=this.titleCol)!=null?g:this.headers[0]])!=null?p:"\u2014"});let o=i.createDiv({cls:"csv-expander-header-btns"}),r=e.createDiv({cls:"csv-expander-fields"}),a=this.titleCol,l=this.headers.find(C=>["author","Author","director","Director","artist","Artist","creator","Creator"].includes(C));this.headers.forEach(C=>{var v;if(this.isNotesCol(C))return;let k=r.createDiv({cls:"csv-expander-field-row"});if(k.createDiv({cls:"csv-expander-field-label",text:Dt(C)}),this.isBooleanCol(C)){let _=Qe((v=this.row[C])!=null?v:""),w=k.createDiv({cls:`csv-toggle ${_?"is-on":""}`});w.createDiv({cls:"csv-toggle-knob"}),w.addEventListener("click",()=>{let T=!w.hasClass("is-on");w.toggleClass("is-on",T),this.row[C]=T?"1":"0"});return}let S=Et(C);if(C!==a&&(S?this.isSelectCol(C):this.isCategoricalCol(C))){let _=k.createDiv({cls:`csv-select-chip ${this.row[C]?"":"empty"}`});_.setText(this.row[C]||"\u2014"),_.addEventListener("click",w=>{w.stopPropagation(),Ot(_,this.row[C],this.getColumnValues(C),T=>{this.row[C]=T,_.setText(T||"\u2014"),_.toggleClass("empty",!T)},e,{multi:Et(C)})})}else{let _=k.createDiv({cls:"csv-expander-field-value",text:this.row[C]||"\u2014"});_.addEventListener("click",()=>{var E;if(_.querySelector("input"))return;_.empty();let w=hn(_,C,(E=this.row[C])!=null?E:"","csv-inline-input",this.isDateCol);w.focus(),w.type==="text"&&w.select(),w.addEventListener("click",M=>M.stopPropagation());let T=()=>{this.row[C]=w.value,_.empty(),_.setText(w.value||"\u2014")};w.addEventListener("blur",T),w.addEventListener("keydown",M=>{M.key==="Enter"&&w.blur(),M.key==="Escape"&&(_.empty(),_.setText(this.row[C]||"\u2014"))})})}});let c=!1,d=this.notesCol&&(m=this.row[this.notesCol])!=null?m:"",h=null;if(this.notesCol){e.createDiv({cls:"csv-expander-divider"}).createDiv({cls:"csv-expander-notes-label",text:this.notesCol});let k=e.createDiv({cls:"csv-expander-rendered markdown-rendered"});k.title="Click to edit";let S=e.createDiv({cls:"csv-expander-editor"});S.style.display="none";let y=()=>{k.empty(),d.trim()?Ft.MarkdownRenderer.render(this.app,d,k,this.filePath,this.renderComponent):k.createDiv({cls:"csv-notes-empty",text:"+ Add note"})};y(),h=S.createEl("textarea",{cls:"csv-expander-textarea"}),h.value=d,h.addEventListener("input",()=>{d=h.value});let v=()=>{c||(c=!0,k.style.display="none",S.style.display="flex",h.value=d,h.focus())},_=()=>{c&&(c=!1,S.style.display="none",k.style.display="",d=h.value,y())};k.addEventListener("click",w=>{if(w.target.closest("a, button, input, textarea, [contenteditable]"))return;let E=window.getSelection();E&&E.toString().length>0||v()}),h.addEventListener("keydown",w=>{w.key==="Escape"&&(w.preventDefault(),h.blur())}),h.addEventListener("blur",_)}let u=e.createDiv({cls:"csv-expander-footer"});if(this.onDelete){let C=String((x=this.row[(b=this.titleCol)!=null?b:this.headers[0]])!=null?x:"").trim();u.createEl("button",{cls:"csv-expander-delete-btn",text:"Delete"}).addEventListener("click",()=>{let k=C||"this entry";window.confirm(`Delete "${k}"? This can't be undone.`)&&(this.onDelete(),this.close())})}let f=u.createDiv({cls:"csv-expander-footer-right"});f.createEl("button",{cls:"csv-modal-cancel",text:"Cancel"}).addEventListener("click",()=>this.close()),f.createEl("button",{cls:"csv-expander-save-btn",text:"Save & close"}).addEventListener("click",()=>{this.notesCol&&(c&&h&&(d=h.value),this.row[this.notesCol]=d),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()}};var cn=class extends Ft.Modal{constructor(t,e,n,i,o,r,a,l,c,d,h,u,f,g=()=>0){super(t),this.headers=e,this.filePath=n,this.current={...i,habitColumns:i.habitColumns?[...i.habitColumns]:void 0,categoricalColumns:i.categoricalColumns?[...i.categoricalColumns]:void 0},this.autoDetectedHabits=o,this.autoDetectedCategorical=r,this.autoDetectedRoles=a,this.availableModes=l,this.onSave=c,this.getHeaders=d,this.getFileCfg=h,this.onAddColumn=u,this.onRemoveColumn=f,this.onCleanupBooleanColumn=g}onOpen(){var I,F,R;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"}),n=()=>{this.headers=this.getHeaders();let D=this.getFileCfg();this.current={...D,habitColumns:D.habitColumns?[...D.habitColumns]:void 0,categoricalColumns:D.categoricalColumns?[...D.categoricalColumns]:void 0},this.onOpen()},i=e.createDiv({cls:"csv-modal-row"});i.createEl("label",{text:"Columns",cls:"csv-modal-label"}),i.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"}],a=D=>{var z,A,$;let W=(z=this.current.habitColumns)!=null?z:this.autoDetectedHabits,O=(A=this.current.categoricalColumns)!=null?A:this.autoDetectedCategorical,K=($=this.current.dateColumns)!=null?$:this.headers.filter(G=>It(G));return W.includes(D)?{type:"checkbox",auto:!this.current.habitColumns}:O.includes(D)?{type:"categorical",auto:!this.current.categoricalColumns}:K.includes(D)?{type:"date",auto:!this.current.dateColumns}:{type:"text",auto:!1}},l=(D,W)=>{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=>It(O))),this.current.habitColumns=this.current.habitColumns.filter(O=>O!==D),this.current.categoricalColumns=this.current.categoricalColumns.filter(O=>O!==D),this.current.dateColumns=this.current.dateColumns.filter(O=>O!==D),W==="checkbox"?this.current.habitColumns.push(D):W==="categorical"?this.current.categoricalColumns.push(D):W==="date"&&this.current.dateColumns.push(D)},c=(F=(I=this.current.titleColumn)!=null?I:this.autoDetectedRoles.title)!=null?F:this.headers[0],h=i.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),u=h.createEl("thead").createEl("tr");["Column","Type","Visibility"].forEach(D=>u.createEl("th",{text:D}));let f=h.createEl("tbody"),g=()=>{var W;f.empty();let D=new Set((W=this.current.cardFields)!=null?W:this.headers);this.headers.forEach(O=>{let K=f.createEl("tr"),z=K.createEl("td",{cls:"csv-modal-colcfg-name"});z.createSpan({text:O});let A=z.createEl("button",{cls:"csv-modal-column-remove",text:"\u2715",attr:{title:`Remove "${O}" \u2014 deletes this column's data from every row`}});A.addEventListener("click",()=>{if(A.hasClass("confirm")){this.onRemoveColumn(O),n();return}f.querySelectorAll(".csv-modal-column-remove.confirm").forEach(P=>{P.removeClass("confirm"),P.setText("\u2715")}),A.addClass("confirm"),A.setText("Confirm?"),window.setTimeout(()=>{A.isConnected&&(A.removeClass("confirm"),A.setText("\u2715"))},3e3)});let $=K.createEl("td",{cls:"csv-modal-colcfg-type-cell"});if(O===c)$.createSpan({cls:"csv-modal-colcfg-fixed",text:"Text"});else{let P=$.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-type"}),{type:N,auto:H}=a(O);if(o.forEach(V=>{let U=P.createEl("option",{text:V.label,value:V.value});V.value===N&&(U.selected=!0)}),H&&P.addClass("auto-detected"),P.addEventListener("change",()=>{l(O,P.value),g()}),H&&$.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"}),N==="checkbox"){let V=$.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)`}});V.addEventListener("click",()=>{if(V.hasClass("confirm")){let U=this.onCleanupBooleanColumn(O);new Ft.Notice(U>0?`"${O}": normalized ${U} row${U===1?"":"s"} to 1/0.`:`"${O}" is already strict 1/0 \u2014 nothing to change.`);return}f.querySelectorAll(".csv-modal-colcfg-cleanup-btn.confirm").forEach(U=>{U.removeClass("confirm"),U.setText("Clean up")}),V.addClass("confirm"),V.setText("Confirm?"),window.setTimeout(()=>{V.isConnected&&(V.removeClass("confirm"),V.setText("Clean up"))},3e3)})}}let B=K.createEl("td",{cls:"csv-modal-colcfg-card-cell"}).createEl("input",{type:"checkbox"});B.checked=D.has(O),B.addEventListener("change",()=>{this.current.cardFields||(this.current.cardFields=[...this.headers]),B.checked?this.current.cardFields.includes(O)||this.current.cardFields.push(O):this.current.cardFields=this.current.cardFields.filter(P=>P!==O)})})};g();let p=t.createDiv({cls:"csv-modal-section",attr:{style:"margin-top: 24px;"}});p.createEl("h3",{text:"Column Functions",cls:"csv-modal-h3"}),p.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 b=p.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),x=b.createEl("thead").createEl("tr");["Function","Column"].forEach(D=>x.createEl("th",{text:D}));let C=b.createEl("tbody"),k=()=>{C.empty(),r.forEach(D=>{var G,B,P,N,H,V,U,Y,q,X,Z,at;if(D.value==="")return;let W=C.createEl("tr");W.createEl("td",{cls:"csv-modal-colcfg-name"}).setText(D.label);let K=W.createEl("td",{cls:"csv-modal-colcfg-type-cell"}),z=K.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-role"});z.createEl("option",{text:"\u2014 none \u2014",value:""});let A="",$=!1;D.value==="title"?(A=(B=(G=this.current.titleColumn)!=null?G:this.autoDetectedRoles.title)!=null?B:"",$=this.current.titleColumn===void 0&&!!this.autoDetectedRoles.title):D.value==="category"?(A=(N=(P=this.current.categoryColumn)!=null?P:this.autoDetectedRoles.category)!=null?N:"",$=this.current.categoryColumn===void 0&&!!this.autoDetectedRoles.category):D.value==="status"?(A=(V=(H=this.current.statusColumn)!=null?H:this.autoDetectedRoles.status)!=null?V:"",$=this.current.statusColumn===void 0&&!!this.autoDetectedRoles.status):D.value==="notes"?(A=(Y=(U=this.current.notesColumn)!=null?U:this.autoDetectedRoles.notes)!=null?Y:"",$=this.current.notesColumn===void 0&&!!this.autoDetectedRoles.notes):D.value==="image"?(A=(X=(q=this.current.imageColumn)!=null?q:this.autoDetectedRoles.image)!=null?X:"",$=this.current.imageColumn===void 0&&!!this.autoDetectedRoles.image):D.value==="anki"&&(A=(at=(Z=this.current.ankiFrontCol)!=null?Z:this.autoDetectedRoles.anki)!=null?at:"",$=this.current.ankiFrontCol===void 0&&!!this.autoDetectedRoles.anki),this.headers.forEach(Q=>{let st=z.createEl("option",{text:Q,value:Q});Q===A&&(st.selected=!0)}),$&&A!==""&&z.addClass("auto-detected"),z.addEventListener("change",()=>{let Q=z.value;D.value==="title"?this.current.titleColumn=Q:D.value==="category"?this.current.categoryColumn=Q:D.value==="status"?this.current.statusColumn=Q:D.value==="notes"?this.current.notesColumn=Q:D.value==="image"?this.current.imageColumn=Q:D.value==="anki"&&(this.current.ankiFrontCol=Q),k()}),$&&A!==""&&K.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"})})};k();let S=i.createDiv({cls:"csv-modal-add-column"}),y=S.createEl("input",{cls:"csv-modal-input",type:"text",placeholder:"New column name"}),v=S.createEl("button",{cls:"csv-modal-cancel",text:"+ Add column"}),_=()=>{let D=this.onAddColumn(y.value);if(D){new Ft.Notice(D);return}n()};v.addEventListener("click",_),y.addEventListener("keydown",D=>{D.key==="Enter"&&(D.preventDefault(),_())});let w=e.createDiv({cls:"csv-modal-row"});w.createEl("label",{text:"Default view",cls:"csv-modal-label"});let T=w.createEl("select",{cls:"csv-modal-select"}),E=[["\u2014 use global default \u2014",""],...this.availableModes.map(D=>[D.label,D.id])],M=(R=this.current.defaultMode)!=null?R:"";M&&!this.availableModes.some(D=>D.id===M)&&E.push([`${M} (no longer available)`,M]),E.forEach(([D,W])=>{let O=T.createEl("option",{text:D,value:W});M===W&&(O.selected=!0)}),T.addEventListener("change",()=>{this.current.defaultMode=T.value?T.value:void 0});let L=t.createDiv({cls:"csv-modal-btns"});L.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),L.createEl("button",{text:"Save",cls:"csv-modal-submit"}).addEventListener("click",()=>{this.onSave(this.current),this.close()})}onClose(){this.contentEl.empty()}},dn=class extends Ft.Modal{constructor(e,n,i,o,r){super(e);this.title=n;this.initial=i;this.placeholder=o;this.onSubmit=r}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("csv-add-modal"),e.createEl("h2",{text:this.title,cls:"csv-modal-title"});let n=e.createEl("input",{cls:"csv-modal-field",type:"text"});n.value=this.initial,n.placeholder=this.placeholder,window.setTimeout(()=>{n.focus(),n.select()},0);let i=()=>{let r=n.value.trim();r&&(this.onSubmit(r),this.close())};n.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),i())});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:"Create",cls:"csv-modal-submit"}).addEventListener("click",i)}onClose(){this.contentEl.empty()}};var ui=195,hc={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"},uc={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"]},Wo={AF:"Africa",AN:"Antarctica",AS:"Asia",EU:"Europe",NA:"N. America",OC:"Oceania",SA:"S. America"},jo={};for(let[s,t]of Object.entries(uc))for(let e of t)jo[e]=s;function kt(s){return hc[s]||s}function Wt(s){return!s||s.length!==2?"":String.fromCodePoint(...s.toUpperCase().split("").map(t=>t.charCodeAt(0)+127397))}function Nt(s){if(!s||s.indexOf("?")!==-1)return null;let t=new Date(s+"T12:00:00Z");return isNaN(t.getTime())?null:t}function Ms(s){let t=Nt(s.date_entered),e=Nt(s.date_left);return!t||!e?0:Math.max(Math.round((e.getTime()-t.getTime())/864e5),1)}function Uo(s,t=new Date){let e=t.getTime(),n=null,i=-1/0;for(let o of s){let r=Nt(o.date_entered);if(!(!r||r.getTime()>e)){if(o.date_left.trim()!==""){let a=Nt(o.date_left);if(!a||a.getTime()i&&(n=o,i=r.getTime())}}return n}function Ko(s){let t=b=>{var x,C,k,S,y,v,_,w;return{date_entered:(x=b.date_entered)!=null?x:"",date_left:(C=b.date_left)!=null?C:"",country:((k=b.country)!=null?k:"").trim().toUpperCase(),city:(S=b.city)!=null?S:"",visa_status:(y=b.visa_status)!=null?y:"",notes:(v=b.notes)!=null?v:"",source:((_=b.source)!=null?_:"").trim().toLowerCase(),resolved:(w=b.resolved)!=null?w:"",_src:b}},e=s.map(t).filter(b=>b.country),n=e.filter(b=>b.source==="confirmed"),i=e.filter(b=>b.source==="inferred"),o=e.filter(b=>b.source==="conflict"),r=[];for(let b of n){let x=Nt(b.date_entered),C=Nt(b.date_left);x&&C&&r.push([x.getTime(),C.getTime()])}let a=b=>{let x=Nt(b.date_entered),C=Nt(b.date_left);if(!x||!C)return!1;let k=x.getTime(),S=C.getTime();return r.some(([y,v])=>k<=v&&S>=y)},l=i.filter(b=>Nt(b.date_entered)&&Nt(b.date_left)&&!a(b)),c=new Set(n.map(b=>b.country)),d=new Set(i.map(b=>b.country)),h=new Set([...d].filter(b=>!c.has(b))),u=new Set([...c,...d]),f=new Map;for(let b of n)f.set(b.country,(f.get(b.country)||0)+Ms(b));let g=[...f.entries()].map(([b,x])=>({iso:b,days:x})).sort((b,x)=>x.days-b.days||kt(b.iso).localeCompare(kt(x.iso))),p=g.reduce((b,x)=>b+x.days,0),m=new Set;for(let b of c){let x=jo[b];x&&m.add(x)}return{confirmed:n,inferred:i,conflicts:o,inferredVisible:l,confRanges:r,confirmedCountries:c,inferredOnlyCountries:h,allCountries:u,countryDays:g,totalConfirmedDays:p,visitedContinents:m,worldPct:Math.round(c.size/ui*100)}}var fi=864e5;function Yo(s){if(!s||s.indexOf("?")!==-1)return null;let t=Date.parse(s+"T00:00:00Z");return isNaN(t)?null:t}function fc(s,t,e,n){let i=Math.max(s,e),o=Math.min(t,n);return o<=i?0:Math.round((o-i)/fi)}function gc(s,t){var i;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 n=(i=e.days)!=null?i:180;return{start:t-n*fi,end:t+fi,label:`in last ${n} days`}}function Go(s,t,e=Date.now()){var d,h,u;let n=(d=s.scope.countries)!=null?d:s.scope.country?[s.scope.country]:[],i=new Set(n.map(f=>f.toUpperCase())),o=new Set(((u=(h=s.exempt)==null?void 0:h.visa_status)!=null?u:[]).map(f=>f.toLowerCase().trim())),r=gc(s,e),a=0;for(let f of t){if(!i.has((f.country||"").toUpperCase())||o.has((f.visa_status||"").toLowerCase().trim()))continue;let g=Yo(f.date_entered),p=Yo(f.date_left);g===null||p===null||(a+=fc(g,p,r.start,r.end))}let l=s.threshold-a,c=a>=s.threshold?"over":a/s.threshold>=.8?"warn":"ok";return{rule:s,used:a,threshold:s.threshold,remaining:l,windowLabel:r.label,status:c}}var qo=["#c9a96e","#4a6fa5","#5ba06e","#a05b8a","#6ea0a0","#a0855b","#7a6ea0","#a06e6e","#6e8fa0","#a09e5b"],pc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function mc(){let s=new Map,t=0;return e=>(s.has(e)||s.set(e,qo[t++%qo.length]),s.get(e))}function bc(s){let t=document.body.createDiv({cls:"csv-tv-tooltip"}),e=null,n=(r,a)=>{let c=r+14,d=a+16,h=t.offsetWidth,u=t.offsetHeight;c+h+8>window.innerWidth&&(c=r-h-14),d+u+8>window.innerHeight&&(d=a-u-16),t.style.left=`${Math.max(8,c)}px`,t.style.top=`${Math.max(8,d)}px`},i=r=>{var c,d;let a=(d=(c=r.target)==null?void 0:c.closest("[data-tip]"))!=null?d: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")),n(r.clientX,r.clientY)},o=()=>{e=null,t.removeClass("is-on")};return s.addEventListener("pointermove",i),s.addEventListener("pointerleave",o),()=>{s.removeEventListener("pointermove",i),s.removeEventListener("pointerleave",o),t.remove()}}function gi(s){let t=Ms(s);return t?`${t}d`:"\u2014"}function es(s){return s||"\u2014"}function Ls(s){return s.createDiv({cls:"csv-tv-table-wrap"}).createEl("table",{cls:"csv-tv-table"})}function Ts(s,t,e,n){s.addClass("csv-tv-editable"),s.title="Click to edit";let i=()=>{s.empty(),s.setText(t[e]?t[e]:"\u2014")};i(),s.addEventListener("click",()=>{var r;if(s.querySelector("input"))return;s.empty();let o=hn(s,e,(r=t[e])!=null?r:"","csv-inline-input");o.focus(),o.type==="text"&&o.select(),o.addEventListener("blur",()=>{t[e]=o.value,n(),i()}),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 Xo(s,t,e,n=()=>{},i=null,o=()=>{}){let r=Ko(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(bc(a));let l=null,c=()=>{a.querySelectorAll(".country-path").forEach(f=>{let g=(f.getAttribute("data-iso")||"").toUpperCase();f.classList.toggle("cp-selected",!!l&&g===l)}),a.querySelectorAll(".csv-tv-seg").forEach(f=>{f.classList.toggle("is-dim",!!l&&f.getAttribute("data-iso")!==l)}),a.querySelectorAll("tr[data-iso]").forEach(f=>{f.classList.toggle("is-selected",!!l&&f.getAttribute("data-iso")===l)}),u.empty(),l&&(xc(u,r,l,()=>d(null)),u.scrollIntoView({behavior:"smooth",block:"nearest"}))},d=f=>{l=f&&f!==l?f:null,c()};vc(a,r);let h=a.createDiv({cls:"csv-tv-mapwrap"});h.createDiv({cls:"csv-tv-map-loading",text:"Loading map\u2026"});let u=a.createDiv({cls:"csv-tv-detailwrap"});i&&i.length&&Cc(a,r.confirmed,i),_c(a,r,d),Sc(a,r,d),Ec(a,r,n);try{let f=await e();h.empty(),f?yc(h,f,r,d):h.createDiv({cls:"csv-tv-map-loading",text:"World map asset not found (world-map.svg)."})}catch(f){h.empty(),h.createDiv({cls:"csv-tv-map-loading",text:"Couldn't load world map."})}}function vc(s,t){let e=s.createDiv({cls:"csv-tv-stats"}),n=(c,d,h="")=>{let u=e.createDiv({cls:"csv-tv-stat"});u.createDiv({cls:"csv-tv-stat-label",text:c}),u.createDiv({cls:"csv-tv-stat-value",text:d}),h&&u.createDiv({cls:"csv-tv-stat-sub",text:h})},i=Math.round(t.allCountries.size/ui*100);n("Countries",String(t.confirmedCountries.size),`${t.worldPct}% of world`),n("Incl. photos",String(t.allCountries.size),`${i}% of world`),n("Continents",`${t.visitedContinents.size} / 7`,[...t.visitedContinents].map(c=>Wo[c]||c).sort().join(", ")),n("Confirmed trips",String(t.confirmed.length)),n("Confirmed days",String(t.totalConfirmedDays));let o=new Set(t.confirmed.map(c=>c.city.trim().toLowerCase()).filter(Boolean));o.size&&n("Cities",String(o.size));let r=null,a=0;for(let c of t.confirmed){let d=Ms(c);d>a&&(a=d,r=c)}if(r){let c=r.date_entered.slice(0,4);n("Longest trip",`${a}d`,`${Wt(r.country)} ${kt(r.country)}${c?` \xB7 ${c}`:""}`)}let l=Uo(t.confirmed);if(l){let c=Nt(l.date_entered),d=Math.max(1,Math.round((Date.now()-c.getTime())/864e5)+1),h=s.createDiv({cls:"csv-tv-now"});h.createSpan({cls:"csv-tv-now-loc",text:`\u{1F4CD} Currently in ${Wt(l.country)} ${kt(l.country)}`}),h.createSpan({cls:"csv-tv-now-sub",text:` \u2014 since ${l.date_entered} (day ${d})${l.city?` \xB7 ${l.city}`:""}`})}}function yc(s,t,e,n){let i=s.createDiv({cls:"csv-tv-map"});i.innerHTML=t,i.querySelectorAll(".country-path").forEach(r=>{let a=(r.getAttribute("data-iso")||"").toUpperCase();if(r.classList.remove("cp-unvisited","cp-confirmed","cp-inferred"),a&&e.confirmedCountries.has(a)){r.classList.add("cp-confirmed");let l=e.countryDays.find(c=>c.iso===a);r.setAttr("aria-label",`${kt(a)} \u2014 ${l&&l.days?l.days+"d confirmed":"confirmed"}`),r.setAttr("data-tip",`${kt(a)}${l&&l.days?" \xB7 "+l.days+"d":""} \xB7 click for trips`)}else a&&e.inferredOnlyCountries.has(a)?(r.classList.add("cp-inferred"),r.setAttr("aria-label",`${kt(a)} \u2014 photo evidence`),r.setAttr("data-tip",`${kt(a)} \xB7 photo evidence \xB7 click for trips`)):a?(r.classList.add("cp-unvisited"),r.setAttr("data-tip",kt(a))):r.classList.add("cp-unvisited");a&&r.addEventListener("click",()=>{e.allCountries.has(a)?n(a):n(null)})}),i.querySelectorAll(".country-path").forEach(r=>{try{let a=r.getBoundingClientRect();a.width&&a.height&&Math.max(a.width,a.height)<12&&r.classList.add("cp-tiny")}catch(a){}});let o=s.createDiv({cls:"csv-tv-map-legend"});o.createSpan({cls:"csv-tv-leg"}).innerHTML=' Confirmed',o.createSpan({cls:"csv-tv-leg"}).innerHTML=' Photo evidence'}function xc(s,t,e,n){var m,b;let i=s.createDiv({cls:"csv-tv-detail"}),o=i.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:kt(e)});let a=t.confirmed.filter(x=>x.country===e),l=t.inferred.filter(x=>x.country===e),c=(b=(m=t.countryDays.find(x=>x.iso===e))==null?void 0:m.days)!=null?b:0,d=new Set([...a,...l].map(x=>x.city.trim()).filter(Boolean)),h=[];a.length&&h.push(`${a.length} confirmed trip${a.length===1?"":"s"}`),c&&h.push(`${c}d total`),l.length&&h.push(`${l.length} photo-inferred`),d.size&&h.push(`${d.size} cit${d.size===1?"y":"ies"}`),r.createDiv({cls:"csv-tv-detail-sub",text:h.join(" \xB7 ")}),o.createEl("button",{cls:"csv-tv-detail-close",text:"\u2715",title:"Close"}).addEventListener("click",n);let u=un([...a.map(x=>({r:x,inf:!1,date_entered:x.date_entered})),...l.map(x=>({r:x,inf:!0,date_entered:x.date_entered}))]);if(!u.length)return;let f=Ls(i),g=f.createEl("thead").createEl("tr");["","Entered","Left","Days","City","Visa"].forEach(x=>g.createEl("th",{text:x}));let p=f.createEl("tbody");for(let{r:x,inf:C}of u){let k=p.createEl("tr");k.createEl("td",{text:C?"\u{1F4F7}":"",cls:"csv-tv-flag",attr:C?{"data-tip":"Photo-inferred"}:{}}),k.createEl("td",{text:es(x.date_entered)}),k.createEl("td",{text:es(x.date_left)}),k.createEl("td",{text:gi(x)}),k.createEl("td",{text:x.city}),k.createEl("td",{text:x.visa_status})}}function Cc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Residency counters"});let n=s.createDiv({cls:"csv-tv-res-grid"});for(let i of e){let o=Go(i,t),r=n.createDiv({cls:`csv-tv-res-card csv-tv-res-${o.status}`});r.createDiv({cls:"csv-tv-res-label",text:i.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 c=o.status==="over"?i.onExceed?`Over \u2014 ${i.onExceed}`:"Limit reached":`${o.remaining} day${o.remaining===1?"":"s"} left`;r.createDiv({cls:"csv-tv-res-status",text:c}),i.note&&r.createDiv({cls:"csv-tv-res-note",text:i.note})}s.createDiv({cls:"csv-tv-res-disclaimer",text:"Indicators only \u2014 not legal or tax advice. Based on confirmed trips."})}function _c(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Countries visited"});let n=Ls(s),i=n.createEl("thead").createEl("tr");["","Country","Total days"].forEach(r=>i.createEl("th",{text:r}));let o=n.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:kt(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 Sc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Timeline"});let n=mc(),i=[...t.confirmed.map(c=>({...c,_inf:!1})),...t.inferredVisible.map(c=>({...c,_inf:!0}))].filter(c=>c.date_entered&&c.date_left&&c.date_entered.indexOf("?")===-1),o=new Map;for(let c of i){let d=parseInt(c.date_entered.slice(0,4)),h=parseInt(c.date_left.slice(0,4));if(!(isNaN(d)||isNaN(h)))for(let u=d;u<=h;u++)o.has(u)||o.set(u,[]),o.get(u).push(c)}let r=[...o.keys()].sort((c,d)=>d-c),a=s.createDiv({cls:"csv-tv-timeline"});for(let c of r){let d=new Date(`${c}-01-01T12:00:00Z`).getTime(),h=new Date(`${c}-12-31T12:00:00Z`).getTime(),u=h-d,f=a.createDiv({cls:"csv-tv-tl-year"}),g=0,p=new Set;for(let C of o.get(c)){if(p.add(C.country),C._inf)continue;let k=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),d),S=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),h);k<=S&&(g+=Math.max(Math.round((S-k)/864e5)+1,1))}let m=f.createDiv({cls:"csv-tv-tl-label"});m.createSpan({text:String(c)}),m.createSpan({cls:"csv-tv-tl-sub",text:`${g?`${g}d \xB7 `:""}${p.size} ${p.size===1?"country":"countries"}`});let b=f.createDiv({cls:"csv-tv-month-row"});pc.forEach(C=>b.createDiv({cls:"csv-tv-month-tick",text:C}));let x=f.createDiv({cls:"csv-tv-track"});for(let C of o.get(c)){let k=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),d),S=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),h);if(k>S)continue;let y=(k-d)/u*100,v=Math.max((S-k+864e5)/u*100,.5),_=n(C.country),w=x.createDiv({cls:`csv-tv-seg${C._inf?" csv-tv-seg-inf":""}`});w.style.left=`${y}%`,w.style.width=`${v}%`,C._inf?(w.style.borderColor=_,w.style.background=_+"22",w.style.color=_):w.style.background=_,w.setAttr("data-iso",C.country),w.setAttr("data-tip",`${kt(C.country)} ${C.date_entered} \u2192 ${C.date_left} (${Ms(C)}d)${C.visa_status?" ["+C.visa_status+"]":""}${C._inf?" [photo]":""}`),w.addEventListener("click",()=>e(C.country)),v>4?w.createSpan({cls:"csv-tv-seg-lbl",text:`${Wt(C.country)} ${C.country}`}):v>2&&w.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 un(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 Ec(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 n=Ls(s),i=n.createEl("thead").createEl("tr");["","Country","Entered","Left","Duration","City","Visa","Notes"].forEach(r=>i.createEl("th",{text:r}));let o=n.createEl("tbody");for(let r of un(t.confirmed)){let a=o.createEl("tr");a.createEl("td",{text:Wt(r.country),cls:"csv-tv-flag"}),a.createEl("td",{text:kt(r.country)}),Ts(a.createEl("td"),r._src,"date_entered",e),Ts(a.createEl("td"),r._src,"date_left",e),a.createEl("td",{text:gi(r)}),Ts(a.createEl("td"),r._src,"city",e),Ts(a.createEl("td"),r._src,"visa_status",e),Ts(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=Ls(r),l=a.createEl("thead").createEl("tr");["","Country","Entered","Left","Days","City"].forEach(d=>l.createEl("th",{text:d}));let c=a.createEl("tbody");for(let d of un(t.inferred)){let h=c.createEl("tr");h.createEl("td",{text:Wt(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:kt(d.country)}),h.createEl("td",{text:es(d.date_entered)}),h.createEl("td",{text:es(d.date_left)}),h.createEl("td",{text:gi(d)}),h.createEl("td",{text:d.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=Ls(r),l=a.createEl("thead").createEl("tr");["","Country (photos)","Dates","Detail"].forEach(d=>l.createEl("th",{text:d}));let c=a.createEl("tbody");for(let d of un(t.conflicts)){let h=c.createEl("tr");h.createEl("td",{text:Wt(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:d.country}),h.createEl("td",{text:`${es(d.date_entered)} \u2192 ${es(d.date_left)}`}),h.createEl("td",{text:d.notes})}}}var Vt=require("obsidian"),fn=class extends Vt.PluginSettingTab{constructor(t,e){super(t,e),this.plugin=e}display(){let{containerEl:t}=this;t.empty(),t.createEl("h2",{text:"XLSX Card View"}),new Vt.Setting(t).setName("Default view mode").addDropdown(n=>n.addOption("kanban-genre","Kanban").addOption("table","Table").setValue(this.plugin.settings.defaultMode).onChange(async i=>{this.plugin.settings.defaultMode=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Status column name").addText(n=>n.setValue(this.plugin.settings.statusColumn).onChange(async i=>{this.plugin.settings.statusColumn=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Category/Genre column name").addText(n=>n.setValue(this.plugin.settings.categoryColumn).onChange(async i=>{this.plugin.settings.categoryColumn=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Notes column names").setDesc("Comma-separated.").addText(n=>n.setValue(this.plugin.settings.notesColumns.join(", ")).onChange(async i=>{this.plugin.settings.notesColumns=i.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Select/dropdown columns").setDesc("Comma-separated column names that use a dropdown picker.").addText(n=>n.setValue(this.plugin.settings.selectColumns.join(", ")).onChange(async i=>{this.plugin.settings.selectColumns=i.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Notes subfolder").addText(n=>n.setPlaceholder("Notes").setValue(this.plugin.settings.notesSubfolder).onChange(async i=>{this.plugin.settings.notesSubfolder=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Reset column widths").addButton(n=>n.setButtonText("Reset").onClick(async()=>{this.plugin.settings.columnWidths={},await this.plugin.saveSettings(),new Vt.Notice("Column widths reset.")})),new Vt.Setting(t).setName("Residency counters (travel view)").setDesc("Show residency / tax day-gauges in the travel view.").addToggle(n=>n.setValue(this.plugin.settings.showResidency!==!1).onChange(async i=>{this.plugin.settings.showResidency=i,await this.plugin.saveSettings()})),t.createEl("h3",{text:"Residency rules"}),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=[],n=()=>void this.plugin.saveSettings();e.forEach((r,a)=>{var b,x,C,k,S,y;let l=t.createDiv({cls:"csv-rr-card"}),c=l.createDiv({cls:"csv-rr-head"}),d=c.createEl("input",{cls:"csv-rr-label",type:"text",value:r.label});d.placeholder="Label (e.g. \u{1F1EA}\u{1F1FA} Schengen 90/180)",d.addEventListener("input",()=>{r.label=d.value,n()});let h=c.createEl("button",{cls:"csv-rr-del",text:"\u2715"});h.setAttr("aria-label","Remove rule"),h.addEventListener("click",async()=>{e.splice(a,1),await this.plugin.saveSettings(),this.renderResidencyRules(t)});let u=l.createDiv({cls:"csv-rr-grid"}),f=(v,_,w,T="")=>{let E=u.createDiv({cls:"csv-rr-field"});E.createEl("label",{text:v});let M=E.createEl("input",{type:"text",value:_});T&&(M.placeholder=T),M.addEventListener("input",()=>{w(M.value),n()})},g=(b=r.scope.countries)!=null?b:r.scope.country?[r.scope.country]:[];f("Countries (ISO-2, comma)",g.join(", "),v=>{r.scope={countries:v.split(",").map(_=>_.trim().toUpperCase()).filter(Boolean)}},"US, GB");let p=u.createDiv({cls:"csv-rr-field"});p.createEl("label",{text:"Window"});let m=p.createEl("select");[["calendar-year","Calendar year"],["rolling","Rolling N days"],["all-time","All time"]].forEach(([v,_])=>{let w=m.createEl("option",{text:_,value:v});r.window.type===v&&(w.selected=!0)}),m.addEventListener("change",()=>{r.window={type:m.value,days:r.window.days},n(),this.renderResidencyRules(t)}),r.window.type==="rolling"&&f("Rolling days",String((x=r.window.days)!=null?x:180),v=>{let _=parseInt(v,10);r.window.days=isNaN(_)?void 0:_},"180"),f("Threshold (days)",String(r.threshold),v=>{let _=parseInt(v,10);r.threshold=isNaN(_)?0:_},"183"),f("Exempt visas (comma)",((k=(C=r.exempt)==null?void 0:C.visa_status)!=null?k:[]).join(", "),v=>{let _=v.split(",").map(w=>w.trim()).filter(Boolean);r.exempt=_.length?{visa_status:_}:void 0},"F-1, J-1"),f("On-exceed label",(S=r.onExceed)!=null?S:"",v=>{r.onExceed=v||void 0},"tax resident"),f("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 ue=require("obsidian"),Qo=on(ws());async function Zo(s,t,e,n,i={}){var O,K,z;let o=t.split(` -`).map(A=>A.trim()).filter(Boolean),r="";for(let A of o)if(A.startsWith("file:")){r=A.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(n.sourcePath),l=(K=(O=a==null?void 0:a.parent)==null?void 0:O.path)!=null?K:"",c=Ze(r,l),d=s.vault.getAbstractFileByPath(c);if(!d||!(d instanceof ue.TFile)){e.createEl("p",{text:`Error: File not found: ${c}`,cls:"csv-add-error"});return}let h=(z=i[c])!=null?z:{},u=[],f=[];try{let A=await s.vault.read(d),$=Xt(A);u=$.headers,f=$.rows}catch(A){e.createEl("p",{text:`Error reading file: ${A}`,cls:"csv-add-error"});return}if(!u.length){e.createEl("p",{text:"Error: No columns found in file",cls:"csv-add-error"});return}let g=A=>{let $=A.toLowerCase();if(["date","day","datum"].includes($))return!0;let G=f.slice(0,5).map(B=>{var P;return(P=B[A])!=null?P:""});return G.length>0&&G.every(B=>/^\d{4}-\d{2}-\d{2}$/.test(B))},p=A=>{let $=A.toLowerCase();return["notes","note","comments","description","journal"].includes($)},m=h.habitColumns?h.habitColumns.filter(A=>u.includes(A)):u.filter(A=>!g(A)&&Xe(f.map($=>{var G;return((G=$[A])!=null?G:"").toLowerCase().trim()}))),b=u.filter(A=>g(A)),x=u.filter(A=>p(A)),C=u.filter(A=>!m.includes(A)&&!b.includes(A)&&!x.includes(A)),k=h.titleColumn?u.find(A=>A.toLowerCase()===h.titleColumn.toLowerCase()):u.find(A=>["title","name"].includes(A.toLowerCase())),S=e.createDiv({cls:"csv-add-form csv-add-compact"}),y=S.createEl("button",{cls:"csv-add-trigger",text:"+ New entry"});y.style.display="none";let v=S.createDiv({cls:"csv-add-card"}),_=v.createDiv({cls:"csv-add-card-header"});_.createEl("span",{cls:"csv-add-card-title",text:"New entry"});let w=_.createEl("button",{cls:"csv-add-card-close",text:"\xD7"}),T=v.createDiv({cls:"csv-add-rows"}),E={},M={},L=(A,$)=>{let G=T.createDiv({cls:`csv-add-row csv-add-row-${$}`});return G.createEl("span",{cls:"csv-add-row-label",text:Dt(A)}),G};b.forEach(A=>{let G=L(A,"date").createEl("input",{cls:"csv-add-row-control",type:"date"});G.value=new Date().toISOString().split("T")[0],E[A]=G}),m.forEach(A=>{M[A]=!1;let G=L(A,"toggle").createEl("label",{cls:"csv-add-switch"}),B=G.createEl("input",{type:"checkbox",cls:"csv-add-switch-input"});G.createEl("span",{cls:"csv-add-switch-track"}),B.addEventListener("change",()=>{M[A]=B.checked}),E[A]=B}),C.forEach(A=>{let $=L(A,"field"),G=new Set(f.map(P=>{var N;return((N=P[A])!=null?N:"").trim()}).filter(Boolean));if(A!==k&&(h.categoricalColumns?h.categoricalColumns.includes(A):qt(G.size))){let P=$.createEl("select",{cls:"csv-add-row-control"});P.createEl("option",{text:"\u2014",value:""}),Array.from(G).sort().forEach(V=>P.createEl("option",{text:V,value:V})),P.createEl("option",{text:"+ Custom",value:"__custom__"});let N=T.createDiv({cls:"csv-add-row csv-add-row-custom"});N.style.display="none";let H=N.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:`Custom ${Dt(A).toLowerCase()}`});T.insertBefore(N,$.nextSibling),P.addEventListener("change",()=>{N.style.display=P.value==="__custom__"?"flex":"none",P.value==="__custom__"&&H.focus()}),E[A]=P,E[`${A}__custom`]=H}else E[A]=$.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:Dt(A)})}),x.forEach(A=>{let $=T.createDiv({cls:"csv-add-row csv-add-row-notes"});$.createEl("span",{cls:"csv-add-row-label",text:Dt(A)}),E[A]=$.createEl("textarea",{cls:"csv-add-row-textarea",placeholder:"Optional notes\u2026"})});let I=v.createEl("button",{text:"Add",cls:"csv-add-submit"}),F=_.querySelector(".csv-add-card-title"),R=()=>{if(!b.length)return;let A=E[b[0]];if(!A)return;let $=A.value,G=f.find(B=>B[b[0]]===$);F&&F.setText(G?`Updating ${$}`:"New entry"),v.classList.toggle("is-updating",!!G),I.setText(G?"Update":"Add"),m.forEach(B=>{var H;let P=E[B];if(!P)return;let N=Qe((H=G==null?void 0:G[B])!=null?H:"");P.checked=N,M[B]=N}),[...C,...x].forEach(B=>{var H,V;let P=E[B];if(!P)return;let N=(H=G==null?void 0:G[B])!=null?H:"";if(P instanceof HTMLSelectElement)if(Array.from(P.options).find(Y=>Y.value===N)){P.value=N;let Y=(V=E[`${B}__custom`])==null?void 0:V.closest(".csv-add-row-custom");Y&&(Y.style.display="none")}else P.value="";else P instanceof HTMLTextAreaElement,P.value=N})};if(R(),b.length){let A=E[b[0]];A==null||A.addEventListener("change",R)}let D=()=>{v.style.display="block",y.style.display="none";let A=v.querySelector(".csv-add-row-control");A==null||A.focus()},W=()=>{v.style.display="none",y.style.display=""};y.addEventListener("click",D),w.addEventListener("click",W),I.addEventListener("click",async()=>{let A={};u.forEach(V=>{var U,Y,q,X;m.includes(V)?A[V]=M[V]?"1":"0":E[V]instanceof HTMLSelectElement&&E[V].value==="__custom__"?A[V]=(Y=(U=E[`${V}__custom`])==null?void 0:U.value)!=null?Y:"":E[V]instanceof HTMLTextAreaElement?A[V]=E[V].value:A[V]=(X=(q=E[V])==null?void 0:q.value)!=null?X:""});let $=b.length>0&&b.some(V=>{var U;return((U=A[V])!=null?U:"").trim()}),G=[...C,...x].some(V=>{var U;return((U=A[V])!=null?U:"").trim()}),B=m.some(V=>M[V]);if(!$&&!G&&!B){new ue.Notice("Please fill at least one field");return}let P=[];try{let V=await s.vault.read(d);P=Xt(V).rows}catch(V){new ue.Notice(`Error reading file: ${V}`);return}let N=!1,H=-1;if(b.length>0){let V=b[0],U=A[V];if(H=P.findIndex(Y=>Y[V]===U),H>=0){N=!0;let Y=P[H];u.forEach(q=>{var X;(m.includes(q)||((X=A[q])!=null?X:"").trim())&&(Y[q]=A[q])})}else P.push(A)}else P.push(A);try{let V=Qo.default.unparse(P,{columns:u});await s.vault.modify(d,V),new ue.Notice(N?`Updated entry for ${A[b[0]]||""}`:`Added entry to ${d.basename}`),f.length=0,f.push(...P),b.length>0?R():(m.forEach(U=>{M[U]=!1;let Y=E[U];Y&&(Y.checked=!1)}),[...C,...x].forEach(U=>{let Y=E[U];Y instanceof HTMLSelectElement?Y.selectedIndex=0:(Y instanceof HTMLTextAreaElement||Y)&&(Y.value="");let q=E[`${U}__custom`];if(q){q.value="";let X=q.closest(".csv-add-row-custom");X&&(X.style.display="none")}})),setTimeout(async()=>{let U=s.vault.getAbstractFileByPath(n.sourcePath);if(U instanceof ue.TFile){let Y=s.workspace.activeLeaf;Y&&await Y.openFile(U,{state:{mode:"preview"}})}},300)}catch(V){new ue.Notice(`Error saving: ${V}`)}})}function gn(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 i=t.createDiv({cls:"csv-table-wrapper"}).createEl("table",{cls:"csv-table"}),o=i.createEl("thead").createEl("tr");s.headers.forEach(l=>{let c=o.createEl("th");c.setText(l),c.addClass("csv-th-sortable"),s.tableSortCol===l&&c.createSpan({cls:"csv-th-sort-indicator",text:s.tableSortDir==="asc"?" \u25B2":" \u25BC"}),c.title="Click to sort",c.addEventListener("click",g=>{g.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 d=s.settings.columnWidths[l];d&&(c.style.width=d+"px");let h=c.createDiv({cls:"csv-col-resize-handle"}),u=0,f=0;h.addEventListener("pointerdown",g=>{g.preventDefault(),g.stopPropagation(),h.setPointerCapture(g.pointerId),u=g.clientX,f=c.offsetWidth;let p=b=>{c.style.width=Math.max(60,f+b.clientX-u)+"px"},m=b=>{s.settings.columnWidths[l]=Math.max(60,f+b.clientX-u),h.removeEventListener("pointermove",p),h.removeEventListener("pointerup",m),s.persistSettings()};h.addEventListener("pointermove",p),h.addEventListener("pointerup",m)})}),o.createEl("th",{text:""});let r=matchMedia("(pointer: coarse)").matches,a=i.createEl("tbody");e.forEach(l=>{let c=a.createEl("tr");c.addEventListener("contextmenu",u=>s.openRowContextMenu(l,u)),s.headers.forEach(u=>{var g,p;let f=c.createEl("td");if(s.isNotesCol(u)){f.addClass("csv-table-notes-cell");let m=((g=l[u])!=null?g:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").split(` -`).filter(C=>C.trim()).slice(0,3).join(" \xB7 "),b=m?m.slice(0,200)+(m.length>200?"\u2026":""):"+ Add note",x=f.createSpan({text:b});m||x.addClass("csv-table-notes-empty"),f.title="Click to open note",f.addEventListener("click",C=>{C.stopPropagation(),s.openNoteExpander(l,u)})}else if(s.isSelectCol(u))s.renderSelectField(f,l,u);else{let m=(p=l[u])!=null?p:"";f.setText(m),m.length>80&&(f.title=m),As(s,f,l,u)}});let d=c.createEl("td",{cls:"csv-table-action"}),h=s.notesFileExists(l);d.createEl("button",{cls:`csv-table-notes-btn ${h?"exists":""}`,text:h?"\u{1F4C4}":"\u271A",title:h?"Open notes":"Create notes"}).addEventListener("click",()=>s.openOrCreateNotes(l)),d.createEl("button",{cls:"csv-table-del-btn",text:"\u2715",title:"Delete row (Undo available)"}).addEventListener("click",()=>s.deleteWithUndo(l))}),r||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 As(s,t,e,n){t.addEventListener("click",i=>{var d,h;if(t.querySelector("input"))return;t.empty();let o=(d=s.fileCfg.dateColumns)==null?void 0:d.includes(n),r=((h=e[n])!=null?h:"").trim(),a=o||It(n)&&(r===""||ln.test(r)),l=a?r.slice(0,10):r,c=t.createEl("input",{cls:"csv-inline-input",value:l,type:a?"date":"text"});c.focus(),a||c.select(),c.addEventListener("click",u=>u.stopPropagation()),c.addEventListener("blur",()=>{e[n]=c.value,s.scheduleSave(),t.empty(),t.setText(c.value||"\u2014")}),c.addEventListener("keydown",u=>{u.key==="Enter"&&c.blur(),u.key==="Escape"&&(t.empty(),t.setText(e[n]||"\u2014"))})})}function pn(s){return!!(s.getCategoryCol()||s.getStatusCol()||Jo(s)||s.authorKey())}function Jo(s){return s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"])}function Os(s){var i;let t=(s!=null?s:"").trim();if(!t)return null;let e=((i=t.match(/★/g))!=null?i:[]).length;if(e>0)return e;let n=parseFloat(t);return isNaN(n)||n<=0?null:Math.min(5,n)}var tr=["watched","read","finished","completed","done","yes","seen"],er=["watching","reading","in progress","in-progress"],kc=["dropped","abandoned","dnf"];function wc(s){let t=s.toLowerCase();return tr.includes(t)?"is-done":er.includes(t)?"is-progress":kc.includes(t)?"is-dropped":""}function Rs(s,t){let e=new Map;return s.forEach(n=>t(n).forEach(i=>{var o;return e.set(i,((o=e.get(i))!=null?o:0)+1)})),e}function Ps(s,t,e,n){if(!e.length)return;let i=s.createDiv({cls:"csv-stats-section"});i.createDiv({cls:"csv-stats-section-title",text:t});let o=Math.max(...e.map(r=>r.count));e.forEach(r=>{var h;let a=i.createDiv({cls:"csv-stats-bar-row"});a.createDiv({cls:"csv-stats-bar-label",text:r.label,attr:{title:r.label}});let c=a.createDiv({cls:"csv-stats-bar-track"}).createDiv({cls:`csv-stats-bar-fill ${(h=r.cls)!=null?h:""}`});c.style.width=`${Math.max(2,Math.round(r.count/o*100))}%`;let d=n>0?Math.round(r.count/n*100):0;a.createDiv({cls:"csv-stats-bar-count",text:`${r.count} \xB7 ${d}%`}),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 n=t.createDiv({cls:"csv-stats-wrap"}),i=s.getStatusCol(),o=s.getCategoryCol(),r=Jo(s),a=s.authorKey(),l=s.resolveCol(["Year","year"]),c=n.createDiv({cls:"csv-stats-overview"}),d=(u,f)=>{let g=c.createDiv({cls:"csv-stats-chip"});g.createDiv({cls:"csv-stats-chip-value",text:u}),g.createDiv({cls:"csv-stats-chip-label",text:f})};if(d(String(e.length),"entries"),i){let u=e.filter(g=>{var p;return tr.includes(((p=g[i])!=null?p:"").toLowerCase().trim())}).length;u>0&&d(`${u} \xB7 ${Math.round(u/e.length*100)}%`,"done");let f=e.filter(g=>{var p;return er.includes(((p=g[i])!=null?p:"").toLowerCase().trim())}).length;f>0&&d(String(f),"in progress")}if(o){let u=Rs(e,f=>{var g;return((g=f[o])!=null?g:"").split(",").map(p=>p.trim()).filter(Boolean)});u.size>0&&d(String(u.size),o.toLowerCase()==="genre"||o.toLowerCase()==="genres"?"genres":"categories")}if(r){let u=e.map(f=>Os(f[r])).filter(f=>f!==null);if(u.length){let f=u.reduce((g,p)=>g+p,0)/u.length;d(`\u2605 ${f.toFixed(1)}`,`avg of ${u.length} rated`)}}let h=(u,f)=>{s.libraryStatusFilter=u!=null?u:"all",s.libraryGenreFilter=f!=null?f:"all",s.mode="library",s.renderView()};if(i){let u=Rs(e,g=>{var m;let p=((m=g[i])!=null?m:"").trim();return p?[p]:[]}),f=Array.from(u.entries()).sort((g,p)=>p[1]-g[1]).map(([g,p])=>({label:g,count:p,cls:wc(g),onClick:o?()=>h(g,null):void 0}));Ps(n,`By ${i.toLowerCase()}`,f,e.length)}if(o){let u=Rs(e,g=>{var p;return((p=g[o])!=null?p:"").split(",").map(m=>m.trim()).filter(Boolean)}),f=Array.from(u.entries()).sort((g,p)=>p[1]-g[1]||g[0].localeCompare(p[0])).slice(0,12).map(([g,p])=>({label:g,count:p,onClick:()=>h(null,g)}));Ps(n,`By ${o.toLowerCase()}`,f,e.length)}if(r){let u=new Map,f=0;if(e.forEach(g=>{var b;let p=Os(g[r]);if(p===null)return;let m=Math.min(5,Math.max(1,Math.round(p)));u.set(m,((b=u.get(m))!=null?b:0)+1),f++}),f>0){let g=[5,4,3,2,1].filter(p=>{var m;return((m=u.get(p))!=null?m:0)>0}).map(p=>({label:"\u2605".repeat(p),count:u.get(p),cls:"is-rating"}));Ps(n,"Ratings",g,f)}}if(l){let u=Rs(e,f=>{var p;let g=((p=f[l])!=null?p:"").match(/\d{4}/);return g?[g[0]]:[]});if(u.size>1){let f=Array.from(u.entries()).sort((g,p)=>g[0].localeCompare(p[0])).map(([g,p])=>({label:g,count:p}));Ps(n,"By year",f,e.length)}}if(a){let u=Rs(e,g=>{var m;let p=((m=g[a])!=null?m:"").trim();return p?[p]:[]}),f=Array.from(u.entries()).filter(([,g])=>g>1);if(f.length>=2){let g=f.sort((p,m)=>m[1]-p[1]||p[0].localeCompare(m[0])).slice(0,8).map(([p,m])=>({label:p,count:m}));Ps(n,`Top ${a.toLowerCase()}s`,g,e.length)}}}function Bt(s){let t=s.fileCfg.kanbanGroupCol;if(t&&s.headers.includes(t))return t;let e=s.getCategoryCol();if(e)return e;let n=new Set;s.headers.forEach(r=>{s.isNotesCol(r)&&n.add(r)});let i=s.getDateCol();i&&n.add(i);let o=s.titleKey();return o&&n.add(o),zo(s.headers,s.rows,n)}function mn(s,t){let e=Bt(s);if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let n=s.getCategoryCol(),i=s.getStatusCol(),o=i===e?null:i,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 b=l.createEl("option",{text:m===n?`${m} (default)`:m,value:m});m===e&&(b.selected=!0)}),l.addEventListener("change",()=>{let m=s.fileCfg;m.kanbanGroupCol=l.value===n?void 0:l.value,s.saveFileCfg(m),s.renderView(!0)});let c=No(e,r.map(m=>{var b;return(b=m[e])!=null?b:""})),d=m=>{var C;let b=(C=m[e])!=null?C:"",x;if(c){let k=Bo(b);x=k?[k]:[]}else x=b.split(",").map(k=>k.trim()).filter(Boolean);return x.length||(x=["\u2014"]),x},h=new Set;r.forEach(m=>d(m).forEach(b=>h.add(b)));let u=Array.from(h).sort();if(!u.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 f=["In progress","Finished","Not started"],g=o?Array.from(new Set([...f,...r.map(m=>{var b;return(b=m[o])!=null?b:""}).filter(Boolean)])).filter(m=>r.some(b=>{var x;return((x=b[o])!=null?x:"")==m})):[],p=t.createDiv({cls:"csv-kanban-board"});u.forEach(m=>{let b=r.filter(S=>d(S).includes(m));if(!b.length)return;let x=p.createDiv({cls:"csv-kanban-col"}),C=x.createDiv({cls:"csv-kanban-col-header"});C.createDiv({cls:"csv-kanban-col-title",text:m}),C.createDiv({cls:"csv-kanban-col-count",text:String(b.length)});let k=x.createDiv({cls:"csv-kanban-col-body"});if(o&&g.length){g.forEach(v=>{let _=b.filter(T=>{var E;return((E=T[o])!=null?E:"")===v});if(!_.length)return;let w=k.createDiv({cls:"csv-kanban-status-group"});w.createDiv({cls:`csv-kanban-status-label status-${v.toLowerCase().replace(/\s+/g,"-")}`,text:v}),_.forEach(T=>pi(s,w,T,o,e))});let S=new Set(g),y=b.filter(v=>{var _;return!S.has((_=v[o])!=null?_:"")});if(y.length){let v=k.createDiv({cls:"csv-kanban-status-group"});v.createDiv({cls:"csv-kanban-status-label",text:"\u2014"}),y.forEach(_=>pi(s,v,_,o,e))}}else b.forEach(S=>pi(s,k,S,o,e))})}function pi(s,t,e,n,i){var _,w,T,E,M,L,I,F;let o=t.createDiv({cls:"csv-kanban-card"}),r=s.getNotesCol(),a=(w=(_=s.getImageCol)==null?void 0:_.call(s))!=null?w:null;if(a){let R=an(s.app,(T=e[a])!=null?T:"",(M=(E=s.file)==null?void 0:E.path)!=null?M:"");if(R){let D=o.createEl("img",{cls:"csv-kanban-card-img",attr:{src:R,loading:"lazy",alt:""}});D.addEventListener("error",()=>D.remove())}}let l=o.createDiv({cls:"csv-kanban-card-title-row"});l.createDiv({cls:`csv-kanban-card-title ${(L=s.isHighlighted)!=null&&L.call(s,e)?"csv-title-highlight":""}`,text:s.getTitle(e)}).addEventListener("click",R=>{R.stopPropagation(),s.openNoteExpander(e,r!=null?r:"")});let d=s.notesFileExists(e);l.createEl("button",{cls:`csv-kanban-notes-icon ${d?"exists":""}`,text:d?"\u{1F4C4}":"+",title:d?"Open notes file":"Create notes file"}).addEventListener("click",R=>{R.stopPropagation(),s.openOrCreateNotes(e)});let u=s.getSubtitle(e);u&&o.createDiv({cls:"csv-kanban-card-sub",text:u});let f=s.titleKey(),g=s.authorKey(),p=new Set([n,f,g,i].filter(Boolean)),m=o.createDiv({cls:"csv-kanban-card-meta"});((I=s.fileCfg.cardFields)!=null?I:s.headers).forEach(R=>{if(!s.headers.includes(R)||p.has(R)||s.isNotesCol(R))return;let D=m.createDiv({cls:"csv-kanban-chip"});if(D.createSpan({cls:"csv-chip-label",text:R+": "}),s.isSelectCol(R)){let W=D.createSpan({cls:`csv-chip-value csv-chip-select${e[R]?"":" csv-chip-value--empty"}`,text:e[R]||"\u2014"});W.addEventListener("click",O=>{O.stopPropagation(),Ot(W,e[R],s.getColumnValues(R),K=>{e[R]=K,W.setText(K||"\u2014"),W.classList.toggle("csv-chip-value--empty",!K),s.scheduleSave()},s.contentEl,{multi:Et(R)})})}else{let W=e[R]?e[R].length>40?e[R].slice(0,38)+"\u2026":e[R]:"\u2014",O=D.createSpan({cls:`csv-chip-value${e[R]?"":" csv-chip-value--empty"}`,text:W});e[R]&&e[R].length>40&&(O.title=e[R])}});let x=s.getNotesCol(),C=!!(x&&((F=e[x])!=null&&F.trim())),k=o.createDiv({cls:"csv-kanban-notes-preview"});if(C&&x){let R=e[x].replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();k.setText(R.slice(0,120)+(R.length>120?"\u2026":"")),k.title="Click to edit"}else k.addClass("csv-kanban-notes-preview--empty"),x&&k.setText("+ Add note");let S=o.createDiv({cls:"csv-kanban-notes-editor"});S.style.display="none";let y=()=>{var K,z,A;let R=s.contentEl.querySelector(".csv-content-area"),D=(K=R==null?void 0:R.scrollLeft)!=null?K:0,W=(z=R==null?void 0:R.scrollTop)!=null?z:0;k.style.display="none",S.style.display="block",S.empty();let O=S.createEl("textarea",{cls:"csv-notes-textarea"});O.value=(A=x?e[x]:"")!=null?A:"",O.addEventListener("click",$=>$.stopPropagation()),O.addEventListener("mousedown",$=>$.stopPropagation()),O.addEventListener("input",()=>{O.style.height="auto",O.style.height=O.scrollHeight+"px"}),O.addEventListener("keydown",$=>{$.key==="Escape"&&v(O.value,R,D,W)}),O.addEventListener("blur",()=>v(O.value,R,D,W)),O.focus({preventScroll:!0}),O.setSelectionRange(0,0),O.scrollTop=0,requestAnimationFrame(()=>{O.style.height="auto",O.style.height=Math.max(120,O.scrollHeight)+"px"})},v=(R,D,W,O)=>{if(x&&(e[x]=R,s.scheduleSave()),S.style.display="none",k.style.display="",R.trim()){let K=R.replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();k.setText(K.slice(0,120)+(K.length>120?"\u2026":"")),k.removeClass("csv-kanban-notes-preview--empty"),k.title="Click to edit"}else k.addClass("csv-kanban-notes-preview--empty"),k.setText(x?"+ Add note":""),k.removeAttribute("title");D&&(D.scrollLeft=W,D.scrollTop=O,requestAnimationFrame(()=>{D.scrollLeft=W,D.scrollTop=O,requestAnimationFrame(()=>{D.scrollLeft=W,D.scrollTop=O})}),setTimeout(()=>{D.scrollLeft=W,D.scrollTop=O},50))};k.addEventListener("click",R=>{if(R.stopPropagation(),x&&matchMedia("(pointer: coarse)").matches){s.openNoteExpander(e,x);return}y()}),o.addEventListener("contextmenu",R=>s.openRowContextMenu(e,R))}function bn(s,t){var w,T;let e=Bt(s),n=s.getStatusCol(),i=(w=s.titleKey())!=null?w:s.headers[0],o=s.authorKey();if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let r=new Set;s.rows.forEach(E=>{var L;((L=E[e])!=null?L:"").split(",").map(I=>I.trim()).filter(Boolean).forEach(I=>r.add(I))});let a=new Set;n&&s.rows.forEach(E=>{var L;let M=((L=E[n])!=null?L:"").trim();M&&a.add(M)});let l=t.createDiv({cls:"csv-library-filters"}),c=l.createEl("select",{cls:"csv-library-filter-select"});c.createEl("option",{text:"All",value:"all"});let d=["watched","read","finished","completed","done","yes","seen"],h=["watching","reading","in progress","in-progress"],u=Array.from(a).some(E=>d.includes(E.toLowerCase())),f=Array.from(a).some(E=>h.includes(E.toLowerCase()));(u||f)&&(c.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),u&&c.createEl("option",{text:"\u2713 Done",value:"__done__"}),f&&c.createEl("option",{text:"\u25D0 In Progress",value:"__inprogress__"}),c.createEl("option",{text:"\u25CB Not Started",value:"__notstarted__"})),a.size>0&&(c.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),Array.from(a).sort().forEach(E=>{c.createEl("option",{text:E,value:E})})),c.value=s.libraryStatusFilter;let g=l.createEl("select",{cls:"csv-library-filter-select"});g.createEl("option",{text:"All genres",value:"all"}),Array.from(r).sort().forEach(E=>{g.createEl("option",{text:E,value:E})}),g.value=s.libraryGenreFilter;let p=s.resolveCol(["Year","year","Date","date"]),m=s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"]),b=s.resolveCol(["Theme","theme","Tags","tags","Tag","tag","Mood","mood"]),x=(T=s.fileCfg.librarySort)!=null?T:"status",C=l.createEl("select",{cls:"csv-library-filter-select"}),k=[["status","Sort: Status"],["title","Sort: Title"]];m&&k.push(["rating","Sort: Rating"]),p&&k.push(["year","Sort: Year"]),k.forEach(([E,M])=>{let L=C.createEl("option",{text:M,value:E});E===x&&(L.selected=!0)}),C.addEventListener("change",()=>{let E=s.fileCfg;E.librarySort=C.value==="status"?void 0:C.value,s.saveFileCfg(E),s.renderView(!0)});let S=()=>{s.libraryStatusFilter=c.value,s.libraryGenreFilter=g.value,s.renderView(!0)};c.addEventListener("change",S),g.addEventListener("change",S);let y=s.rows.filter(E=>{var M,L;if(s.libraryStatusFilter!=="all"&&n){let I=((M=E[n])!=null?M:"").toLowerCase();if(s.libraryStatusFilter==="__done__"){if(!d.includes(I))return!1}else if(s.libraryStatusFilter==="__inprogress__"){if(!h.includes(I))return!1}else if(s.libraryStatusFilter==="__notstarted__"){if(d.includes(I)||h.includes(I))return!1}else if(I!==s.libraryStatusFilter.toLowerCase())return!1}if(s.libraryGenreFilter!=="all"&&!((L=E[e])!=null?L:"").split(",").map(F=>F.trim().toLowerCase()).includes(s.libraryGenreFilter.toLowerCase()))return!1;if(s.searchQuery.trim()){let I=s.searchQuery.toLowerCase().trim();if(!s.headers.some(F=>{var R;return((R=E[F])!=null?R:"").toLowerCase().includes(I)}))return!1}return!0});(s.libraryStatusFilter!=="all"||s.libraryGenreFilter!=="all"||s.searchQuery.trim())&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${y.length} of ${s.rows.length} entries`});let v={};y.forEach(E=>{var L;let M=s.libraryGenreFilter!=="all"?[s.libraryGenreFilter]:((L=E[e])!=null?L:"Uncategorized").split(",").map(I=>I.trim()).filter(Boolean);M.length===0&&M.push("Uncategorized"),M.forEach(I=>{v[I]||(v[I]=[]),v[I].push(E)})});let _=t.createDiv({cls:"csv-library-sections"});if(Object.keys(v).sort().forEach(E=>{var A,$,G,B,P;let M=v[E],L=_.createEl("details",{cls:"csv-library-section"}),I=E.toLowerCase(),F=((A=s.fileCfg.collapsedGroups)!=null?A:[]).map(N=>N.toLowerCase());L.open=!(($=s.collapsedGroups)!=null&&$.has(I)||F.includes(I)),L.addEventListener("toggle",()=>{var Y;let N=s.fileCfg,H=((Y=N.collapsedGroups)!=null?Y:[]).map(q=>q.toLowerCase()),V=new Set(H);L.open?V.delete(I):V.add(I);let U=Array.from(V);U.length===H.length&&U.every(q=>H.includes(q))||(N.collapsedGroups=U,s.saveFileCfg(N))});let R=L.createEl("summary",{cls:"csv-library-section-header"});R.innerHTML=`\u25B6 ${E} ${M.length}`;let D=L.createDiv({cls:"csv-library-grid"}),W=(N,H)=>{var V,U;return((V=N[i])!=null?V:"").localeCompare((U=H[i])!=null?U:"")},O=(N,H)=>N===null&&H===null?0:N===null?1:H===null?-1:H-N;M.sort((N,H)=>{var V,U,Y,q;if(x==="title")return W(N,H);if(x==="rating"&&m)return O(Os((V=N[m])!=null?V:""),Os((U=H[m])!=null?U:""))||W(N,H);if(x==="year"&&p){let X=Z=>{var Q;let at=((Q=Z[p])!=null?Q:"").match(/\d{4}/);return at?parseInt(at[0],10):null};return O(X(N),X(H))||W(N,H)}if(n){let X=((Y=N[n])!=null?Y:"").toLowerCase(),Z=((q=H[n])!=null?q:"").toLowerCase(),at=d.includes(X),Q=d.includes(Z);if(at!==Q)return at?-1:1;let st=h.includes(X),lt=h.includes(Z);if(st!==lt)return st?-1:1}return W(N,H)});let K=(G=s.fileCfg.cardFields)!=null?G:s.headers,z=(P=(B=s.getImageCol)==null?void 0:B.call(s))!=null?P:null;M.forEach(N=>{var q,X,Z,at,Q,st,lt,$t;let H=D.createDiv({cls:"csv-library-card"});if(z){let ot=an(s.app,(q=N[z])!=null?q:"",(Z=(X=s.file)==null?void 0:X.path)!=null?Z:"");if(ot){let pt=H.createEl("img",{cls:"csv-library-card-img",attr:{src:ot,loading:"lazy",alt:""}});pt.addEventListener("error",()=>pt.remove())}}let V=H.createDiv({cls:`csv-library-card-title ${(at=s.isHighlighted)!=null&&at.call(s,N)?"csv-title-highlight":""}`});if(n){let ot=((Q=N[n])!=null?Q:"").toLowerCase();d.includes(ot)&&V.createSpan({cls:"csv-library-done-dot"})}V.createSpan({text:(st=N[i])!=null?st:"Untitled"});let U=[],Y=[];for(let ot of K){if(!ot)continue;let pt=String((lt=N[ot])!=null?lt:"").trim();if(pt)if(ot===m){let ft=Vo(pt,ot);ft&&H.createDiv({cls:"csv-library-card-rating",text:ft})}else if(ot===b)Y.push(...pt.split(",").map(ft=>ft.trim()).filter(Boolean));else if(ot===p){let ft=pt.match(/\d{4}/);U.push(ft?ft[0]:pt)}else U.push(pt)}if(U.length&&H.createDiv({cls:"csv-library-card-meta",text:U.join(" \xB7 ")}),s.libraryGenreFilter!=="all"){let ot=(($t=N[e])!=null?$t:"").split(",").map(pt=>pt.trim()).filter(pt=>pt&&pt.toLowerCase()!==s.libraryGenreFilter.toLowerCase());Y.push(...ot)}if(Y.length){let ot=H.createDiv({cls:"csv-library-card-tags"});Y.slice(0,3).forEach(pt=>{ot.createSpan({cls:"csv-library-card-tag",text:pt})})}H.addEventListener("click",()=>{var ot;s.openNoteExpander(N,(ot=s.getNotesCol())!=null?ot:"")}),H.addEventListener("contextmenu",ot=>s.openRowContextMenu(N,ot))})}),Object.keys(v).length===0){let E=_.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 Te=require("obsidian");var mi=`--- +`):s}function $f(s,t){let{element:e,datasetIndex:n,index:i}=t,o=s.getDatasetMeta(n).controller,{label:r,value:a}=o.getLabelAndValue(i);return{chart:s,label:r,parsed:o.getParsed(i),raw:s.data.datasets[n].data[i],formattedValue:a,dataset:o.getDataset(),dataIndex:i,datasetIndex:n,element:e}}function Za(s,t){let e=s.chart.ctx,{body:n,footer:i,title:o}=s,{boxWidth:r,boxHeight:a}=t,l=bt(t.bodyFont),c=bt(t.titleFont),d=bt(t.footerFont),h=o.length,u=i.length,f=n.length,p=_t(t.padding),g=p.height,m=0,b=n.reduce((E,S)=>E+S.before.length+S.lines.length+S.after.length,0);if(b+=s.beforeBody.length+s.afterBody.length,h&&(g+=h*c.lineHeight+(h-1)*t.titleSpacing+t.titleMarginBottom),b){let E=t.displayColors?Math.max(a,l.lineHeight):l.lineHeight;g+=f*E+(b-f)*l.lineHeight+(b-1)*t.bodySpacing}u&&(g+=t.footerMarginTop+u*d.lineHeight+(u-1)*t.footerSpacing);let x=0,C=function(E){m=Math.max(m,e.measureText(E).width+x)};return e.save(),e.font=c.string,rt(s.title,C),e.font=l.string,rt(s.beforeBody.concat(s.afterBody),C),x=t.displayColors?r+2+t.boxPadding:0,rt(n,E=>{rt(E.before,C),rt(E.lines,C),rt(E.after,C)}),x=0,e.font=d.string,rt(s.footer,C),e.restore(),m+=p.width,{width:m,height:g}}function Hf(s,t){let{y:e,height:n}=t;return es.height-n/2?"bottom":"center"}function zf(s,t,e,n){let{x:i,width:o}=n,r=e.caretSize+e.caretPadding;if(s==="left"&&i+o+r>t.width||s==="right"&&i-o-r<0)return!0}function Wf(s,t,e,n){let{x:i,width:o}=e,{width:r,chartArea:{left:a,right:l}}=s,c="center";return n==="center"?c=i<=(a+l)/2?"left":"right":i<=o/2?c="left":i>=r-o/2&&(c="right"),zf(c,s,t,e)&&(c="center"),c}function Ja(s,t,e){let n=e.yAlign||t.yAlign||Hf(s,e);return{xAlign:e.xAlign||t.xAlign||Wf(s,t,e,n),yAlign:n}}function jf(s,t){let{x:e,width:n}=s;return t==="right"?e-=n:t==="center"&&(e-=n/2),e}function Uf(s,t,e){let{y:n,height:i}=s;return t==="top"?n+=e:t==="bottom"?n-=i+e:n-=i/2,n}function tl(s,t,e,n){let{caretSize:i,caretPadding:o,cornerRadius:r}=s,{xAlign:a,yAlign:l}=e,c=i+o,{topLeft:d,topRight:h,bottomLeft:u,bottomRight:f}=_e(r),p=jf(t,a),g=Uf(t,l,c);return l==="center"?a==="left"?p+=c:a==="right"&&(p-=c):a==="left"?p-=Math.max(d,u)+i:a==="right"&&(p+=Math.max(h,f)+i),{x:vt(p,0,n.width-t.width),y:vt(g,0,n.height-t.height)}}function Un(s,t,e){let n=_t(e.padding);return t==="center"?s.x+s.width/2:t==="right"?s.x+s.width-n.right:s.x+n.left}function el(s){return ee([],he(s))}function Kf(s,t,e){return de(s,{tooltip:t,tooltipItems:e,type:"tooltip"})}function sl(s,t){let e=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return e?s.override(e):s}function Lt(s,t,e,n){let i=s[t].call(e,n);return typeof i=="undefined"?zl[t].call(e,n):i}function Gf(s,t,e,n){let i=s.indexOf(t);if(i===-1)return Yf(s,t,e,n);let o=s.lastIndexOf(t);return i!==o?e:i}function nl(s){let t=this.getLabels();return s>=0&&sp&&(S=Fi(w*S/p/f)*f),tt(l)||(y=Math.pow(10,l),S=Math.ceil(S*y)/y),i==="ticks"?(v=Math.floor(g/S)*S,_=Math.ceil(m/S)*S):(v=g,_=m),b&&x&&o&&Wr((a-r)/o,S/1e3)?(w=Math.round(Math.min((a-r)/S,d)),S=(a-r)/w,v=r,_=a):C?(v=b?r:v,_=x?a:_,w=c-1,S=(_-v)/w):(w=(_-v)/S,ls(w,Math.round(w),S/1e3)?w=Math.round(w):w=Math.ceil(w));let T=Math.max(Vi(S),Vi(v));y=Math.pow(10,tt(l)?T:l),v=Math.round(v*y)/y,_=Math.round(_*y)/y;let k=0;for(b&&(u&&v!==r?(e.push({value:r}),va)break;e.push({value:M})}return x&&u&&_!==a?e.length&&ls(e[e.length-1].value,a,il(a,E,s))?e[e.length-1].value=a:e.push({value:a}):(!x||_===a)&&e.push({value:_}),e}function il(s,t,{horizontal:e,minRotation:n}){let i=zt(n),o=(e?Math.sin(i):Math.cos(i))||.001,r=.75*t*(""+s).length;return Math.min(t/o,r)}function ol(s){return s/Math.pow(10,sn(s))===1}function rl(s,t,e){let n=Math.pow(10,e),i=Math.floor(s/n);return Math.ceil(t/n)-i}function Qf(s,t){let e=t-s,n=sn(e);for(;rl(s,t,n)>10;)n++;for(;rl(s,t,n)<10;)n--;return Math.min(n,sn(s))}function Zf(s,{min:t,max:e}){t=Tt(s.min,t);let n=[],i=sn(t),o=Qf(t,e),r=o<0?Math.pow(10,Math.abs(o)):1,a=Math.pow(10,o),l=i>o?Math.pow(10,i):0,c=Math.round((t-l)*r)/r,d=Math.floor((t-l)/a/10)*a*10,h=Math.floor((c-d)/Math.pow(10,o)),u=Tt(s.min,Math.round((l+d+h*Math.pow(10,o))*r)/r);for(;u=10?h=h<15?15:20:h++,h>=20&&(o++,h=2,r=o>=0?1:r),u=Math.round((l+d+h*Math.pow(10,o))*r)/r;let f=Tt(s.max,u);return n.push({value:f,major:ol(f),significand:h}),n}function To(s){let t=s.ticks;if(t.display&&s.display){let e=_t(t.backdropPadding);return J(t.font&&t.font.size,ut.font.size)+e.height}return 0}function Jf(s,t,e){return e=dt(e)?e:[e],{w:Zr(s,t.string,e),h:e.length*t.lineHeight}}function al(s,t,e,n,i){return s===n||s===i?{start:t-e/2,end:t+e/2}:si?{start:t-e,end:t}:{start:t,end:t+e}}function tp(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),n=[],i=[],o=s._pointLabels.length,r=s.options.pointLabels,a=r.centerPointLabels?nt/o:0;for(let l=0;lt.r&&(a=(n.end-t.r)/o,s.r=Math.max(s.r,t.r+a)),i.startt.b&&(l=(i.end-t.b)/r,s.b=Math.max(s.b,t.b+l))}function sp(s,t,e){let n=s.drawingArea,{extra:i,additionalAngle:o,padding:r,size:a}=e,l=s.getPointPosition(t,n+i+r,o),c=Math.round(An(xt(l.angle+mt))),d=ap(l.y,a.h,c),h=op(c),u=rp(l.x,a.w,h);return{visible:!0,x:l.x,y:d,textAlign:h,left:u,top:d,right:u+a.w,bottom:d+a.h}}function np(s,t){if(!t)return!0;let{left:e,top:n,right:i,bottom:o}=s;return!(Zt({x:e,y:n},t)||Zt({x:e,y:o},t)||Zt({x:i,y:n},t)||Zt({x:i,y:o},t))}function ip(s,t,e){let n=[],i=s._pointLabels.length,o=s.options,{centerPointLabels:r,display:a}=o.pointLabels,l={extra:To(o)/2,additionalAngle:r?nt/i:0},c;for(let d=0;d270||e<90)&&(s-=t),s}function lp(s,t,e){let{left:n,top:i,right:o,bottom:r}=e,{backdropColor:a}=t;if(!tt(a)){let l=_e(t.borderRadius),c=_t(t.backdropPadding);s.fillStyle=a;let d=n-c.left,h=i-c.top,u=o-n+c.width,f=r-i+c.height;Object.values(l).some(p=>p!==0)?(s.beginPath(),us(s,{x:d,y:h,w:u,h:f,radius:l}),s.fill()):s.fillRect(d,h,u,f)}}function cp(s,t){let{ctx:e,options:{pointLabels:n}}=s;for(let i=t-1;i>=0;i--){let o=s._pointLabelItems[i];if(!o.visible)continue;let r=n.setContext(s.getPointLabelContext(i));lp(e,r,o);let a=bt(r.font),{x:l,y:c,textAlign:d}=o;Ce(e,s._pointLabels[i],l,c+a.lineHeight/2,a,{color:r.color,textAlign:d,textBaseline:"middle"})}}function Ul(s,t,e,n){let{ctx:i}=s;if(e)i.arc(s.xCenter,s.yCenter,t,0,ht);else{let o=s.getPointPosition(0,t);i.moveTo(o.x,o.y);for(let r=1;r=Pt.indexOf(e);o--){let r=Pt[o];if(ni[r].common&&s._adapter.diff(i,n,r)>=t-1)return r}return Pt[e?Pt.indexOf(e):0]}function fp(s){for(let t=Pt.indexOf(s)+1,e=Pt.length;t=t?e[n]:e[i];s[o]=!0}}function pp(s,t,e,n){let i=s._adapter,o=+i.startOf(t[0].value,n),r=t[t.length-1].value,a,l;for(a=o;a<=r;a=+i.add(a,1,n))l=e[a],l>=0&&(t[l].major=!0);return t}function ul(s,t,e){let n=[],i={},o=t.length,r,a;for(r=0;r=s[n].pos&&t<=s[i].pos&&({lo:n,hi:i}=Qt(s,"pos",t)),{pos:o,time:a}=s[n],{pos:r,time:l}=s[i]):(t>=s[n].time&&t<=s[i].time&&({lo:n,hi:i}=Qt(s,"time",t)),{time:o,pos:a}=s[n],{time:r,pos:l}=s[i]);let c=r-o;return c?a+(l-a)*(t-o)/c:a}var yo,se,pa,gh,qn,Zs,co,ya,wh,At,Ne,Be,ie,$e,we,gs,He,ze,gl,xo,ml,bl,vl,St,Js,Xn,Yn,qh,Da,xl,tn,Ma,Zn,Rt,uu,Ta,La,Te,ms,Co,Kt,_o,Fa,kl,Gs,ko,Pu,Ou,Fu,Gn,$a,ne,Ee,Zu,Yt,We,je,Ll,Do,Wa,Rl,Fl,ti,Vl,Qa,Of,ei,Bl,en,$l,jn,Hl,Xs,zl,Qs,Wl,jl,Yf,qf,bs,Cs,vs,sn,Ve,ys,ke,ni,Pt,Me,xs,Kl,gp,Gl=fi(()=>{fa();yo=class{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,n,i){let o=e.listeners[i],r=e.duration;o.forEach(a=>a({chart:t,initial:e.initial,numSteps:r,currentStep:Math.min(n-e.start,r)}))}_refresh(){this._request||(this._running=!0,this._request=Hi.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(t=Date.now()){let e=0;this._charts.forEach((n,i)=>{if(!n.running||!n.items.length)return;let o=n.items,r=o.length-1,a=!1,l;for(;r>=0;--r)l=o[r],l._active?(l._total>n.duration&&(n.duration=l._total),l.tick(t),a=!0):(o[r]=o[o.length-1],o.pop());a&&(i.draw(),this._notify(i,n,t,"progress")),o.length||(n.running=!1,this._notify(i,n,t,"complete"),n.initial=!1),e+=o.length}),this._lastDate=t,e===0&&(this._running=!1)}_getAnims(t){let e=this._charts,n=e.get(t);return n||(n={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,n)),n}listen(t,e,n){this._getAnims(t).listeners[e].push(n)}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((n,i)=>Math.max(n,i._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 n=e.items,i=n.length-1;for(;i>=0;--i)n[i].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}},se=new yo,pa="transparent",gh={boolean(s,t,e){return e>.5?t:s},color(s,t,e){let n=Ki(s||pa),i=n.valid&&Ki(t||pa);return i&&i.valid?i.mix(n,e).hexString():t},number(s,t,e){return s+(t-s)*e}},qn=class{constructor(t,e,n,i){let o=e[n];i=fs([t.to,i,o,t.from]);let r=fs([t.from,o,i]);this._active=!0,this._fn=t.fn||gh[t.type||typeof r],this._easing=ns[t.easing]||ns.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=n,this._from=r,this._to=i,this._promises=void 0}active(){return this._active}update(t,e,n){if(this._active){this._notify(!1);let i=this._target[this._prop],o=n-this._start,r=this._duration-o;this._start=n,this._duration=Math.floor(Math.max(r,t.duration)),this._total+=o,this._loop=!!t.loop,this._to=fs([t.to,e,i,t.from]),this._from=fs([t.from,i,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){let e=t-this._start,n=this._duration,i=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[i]=this._fn(o,a,l)}wait(){let t=this._promises||(this._promises=[]);return new Promise((e,n)=>{t.push({res:e,rej:n})})}_notify(t){let e=t?"res":"rej",n=this._promises||[];for(let i=0;i{let o=t[i];if(!et(o))return;let r={};for(let a of e)r[a]=o[a];(dt(o.properties)&&o.properties||[i]).forEach(a=>{(a===i||!n.has(a))&&n.set(a,r)})})}_animateOptions(t,e){let n=e.options,i=bh(t,n);if(!i)return[];let o=this._createAnimations(i,n);return n.$shared&&mh(t.options.$animations,n).then(()=>{t.options=n},()=>{}),o}_createAnimations(t,e){let n=this._properties,i=[],o=t.$animations||(t.$animations={}),r=Object.keys(e),a=Date.now(),l;for(l=r.length-1;l>=0;--l){let c=r[l];if(c.charAt(0)==="$")continue;if(c==="options"){i.push(...this._animateOptions(t,e));continue}let d=e[c],h=o[c],u=n.get(c);if(h)if(u&&h.active()){h.update(u,d,a);continue}else h.cancel();if(!u||!u.duration){t[c]=d;continue}o[c]=h=new qn(u,t,c,d),i.push(h)}return i}update(t,e){if(this._properties.size===0){Object.assign(t,e);return}let n=this._createAnimations(t,e);if(n.length)return se.add(this._chart,n),!0}};co=s=>s==="reset"||s==="none",ya=(s,t)=>t?s:Object.assign({},s),wh=(s,t,e)=>s&&!t.hidden&&t._stacked&&{keys:fl(e,!0),values:null},At=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=ao(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,n=this.getDataset(),i=(h,u,f,p)=>h==="x"?u:h==="r"?p:f,o=e.xAxisID=J(n.xAxisID,lo(t,"x")),r=e.yAxisID=J(n.yAxisID,lo(t,"y")),a=e.rAxisID=J(n.rAxisID,lo(t,"r")),l=e.indexAxis,c=e.iAxisID=i(l,o,r,a),d=e.vAxisID=i(l,r,o,a);e.xScale=this.getScaleForId(o),e.yScale=this.getScaleForId(r),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(c),e.vScale=this.getScaleForId(d)}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&&Bi(this._data,this),t._stacked&&js(t)}_dataCheck(){let t=this.getDataset(),e=t.data||(t.data=[]),n=this._data;if(et(e)){let i=this._cachedMeta;this._data=xh(e,i)}else if(n!==e){if(n){Bi(n,this);let i=this._cachedMeta;js(i),i._parsed=[]}e&&Object.isExtensible(e)&&Gr(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,n=this.getDataset(),i=!1;this._dataCheck();let o=e._stacked;e._stacked=ao(e.vScale,e),e.stack!==n.stack&&(i=!0,js(e),e.stack=n.stack),this._resyncElements(t),(i||o!==e._stacked)&&(va(this,e._parsed),e._stacked=ao(e.vScale,e))}configure(){let t=this.chart.config,e=t.datasetScopeKeys(this._type),n=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(n,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){let{_cachedMeta:n,_data:i}=this,{iScale:o,_stacked:r}=n,a=o.axis,l=t===0&&e===i.length?!0:n._sorted,c=t>0&&n._parsed[t-1],d,h,u;if(this._parsing===!1)n._parsed=i,n._sorted=!0,u=i;else{dt(i[t])?u=this.parseArrayData(n,i,t,e):et(i[t])?u=this.parseObjectData(n,i,t,e):u=this.parsePrimitiveData(n,i,t,e);let f=()=>h[a]===null||c&&h[a]g||h=0;--u)if(!p()){this.updateRangeFromParsed(c,t,f,l);break}}return c}getAllParsedValues(t){let e=this._cachedMeta._parsed,n=[],i,o,r;for(i=0,o=e.length;i=0&&tthis.getContext(n,i,e),g=c.resolveNamedOptions(u,f,p,h);return g.$shared&&(g.$shared=l,o[r]=Object.freeze(ya(g,l))),g}_resolveAnimations(t,e,n){let i=this.chart,o=this._cachedDataOpts,r=`animation-${e}`,a=o[r];if(a)return a;let l;if(i.options.animation!==!1){let d=this.chart.config,h=d.datasetAnimationScopeKeys(this._type,e),u=d.getOptionScopes(this.getDataset(),h);l=d.createResolver(u,this.getContext(t,n,e))}let c=new Zs(i,l&&l.animations);return l&&l._cacheable&&(o[r]=Object.freeze(c)),c}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 n=this.resolveDataElementOptions(t,e),i=this._sharedOptions,o=this.getSharedOptions(n),r=this.includeOptions(e,o)||o!==i;return this.updateSharedOptions(o,e,n),{sharedOptions:o,includeOptions:r}}updateElement(t,e,n,i){co(i)?Object.assign(t,n):this._resolveAnimations(e,i).update(t,n)}updateSharedOptions(t,e,n){t&&!co(e)&&this._resolveAnimations(void 0,e).update(t,n)}_setStyle(t,e,n,i){t.active=i;let o=this.getStyle(e,i);this._resolveAnimations(e,n,i).update(t,{options:!i&&this.getSharedOptions(o)||o})}removeHoverStyle(t,e,n){this._setStyle(t,n,"active",!1)}setHoverStyle(t,e,n){this._setStyle(t,n,"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,n=this._cachedMeta.data;for(let[a,l,c]of this._syncList)this[a](l,c);this._syncList=[];let i=n.length,o=e.length,r=Math.min(o,i);r&&this.parse(0,r),o>i?this._insertElements(i,o-i,t):o{for(c.length+=e,a=c.length-1;a>=r;a--)c[a]=c[a-e]};for(l(o),a=t;ad.controller.options.grouped),o=n.options.stacked,r=[],a=this._cachedMeta.controller.getParsed(e),l=a&&a[n.axis],c=d=>{let h=d._parsed.find(f=>f[n.axis]===l),u=h&&h[d.vScale.axis];if(tt(u)||isNaN(u))return!0};for(let d of i)if(!(e!==void 0&&c(d))&&((o===!1||r.indexOf(d.stack)===-1||o===void 0&&d.stack===void 0)&&r.push(d.stack),d.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(n=>t[n].axis===e).shift()}_getAxis(){let t={},e=this.getFirstScaleIdForIndexAxis();for(let n of this.chart.data.datasets)t[J(this.chart.options.indexAxis==="x"?n.xAxisID:n.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,n){let i=this._getStacks(t,n),o=e!==void 0?i.indexOf(e):-1;return o===-1?i.length-1:o}_getRuler(){let t=this.options,e=this._cachedMeta,n=e.iScale,i=[],o,r;for(o=0,r=e.data.length;o=0;--n)e=Math.max(e,t[n].size(this.resolveDataElementOptions(n))/2);return e>0&&e}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart.data.labels||[],{xScale:i,yScale:o}=e,r=this.getParsed(t),a=i.getLabelForValue(r.x),l=o.getLabelForValue(r.y),c=r._custom;return{label:n[t]||"",value:"("+a+", "+l+(c?", "+c:"")+")"}}update(t){let e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,n,i){let o=i==="reset",{iScale:r,vScale:a}=this._cachedMeta,{sharedOptions:l,includeOptions:c}=this._getSharedOptions(e,i),d=r.axis,h=a.axis;for(let u=e;u+n[l];if(et(n[t])){let{key:l="value"}=this._parsing;o=c=>+ce(n[c],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,n=this.chart,i=n.data.labels||[],o=ds(e._parsed[t],n.options.locale);return{label:i[t]||"",value:o}}getMaxBorderWidth(t){let e=0,n=this.chart,i,o,r,a,l;if(!t){for(i=0,o=n.data.datasets.length;it!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),U(ie,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data,{labels:{pointStyle:n,textAlign:i,color:o,useBorderRadius:r,borderRadius:a}}=t.legend.options;return e.labels.length&&e.datasets.length?e.labels.map((l,c)=>{let h=t.getDatasetMeta(0).controller.getStyle(c);return{text:l,fillStyle:h.backgroundColor,fontColor:o,hidden:!t.getDataVisibility(c),lineDash:h.borderDash,lineDashOffset:h.borderDashOffset,lineJoin:h.borderJoinStyle,lineWidth:h.borderWidth,strokeStyle:h.borderColor,textAlign:i,pointStyle:n,borderRadius:r&&(a||h.borderRadius),index:c}}):[]}},onClick(t,e,n){n.chart.toggleDataVisibility(e.index),n.chart.update()}}}});$e=class extends At{initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){let e=this._cachedMeta,{dataset:n,data:i=[],_dataset:o}=e,r=this.chart._animationsDisabled,{start:a,count:l}=Wi(e,i,r);this._drawStart=a,this._drawCount=l,ji(e)&&(a=0,l=i.length),n._chart=this.chart,n._datasetIndex=this.index,n._decimated=!!o._decimated,n.points=i;let c=this.resolveDatasetElementOptions(t);this.options.showLine||(c.borderWidth=0),c.segment=this.options.segment,this.updateElement(n,void 0,{animated:!r,options:c},t),this.updateElements(i,a,l,t)}updateElements(t,e,n,i){let o=i==="reset",{iScale:r,vScale:a,_stacked:l,_dataset:c}=this._cachedMeta,{sharedOptions:d,includeOptions:h}=this._getSharedOptions(e,i),u=r.axis,f=a.axis,{spanGaps:p,segment:g}=this.options,m=Oe(p)?p:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||i==="none",x=e+n,C=t.length,E=e>0&&this.getParsed(e-1);for(let S=0;S=x){v.skip=!0;continue}let _=this.getParsed(S),w=tt(_[f]),T=v[u]=r.getPixelForValue(_[u],S),k=v[f]=o||w?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,_,l):_[f],S);v.skip=isNaN(T)||isNaN(k)||w,v.stop=S>0&&Math.abs(_[u]-E[u])>m,g&&(v.parsed=_,v.raw=c.data[S]),h&&(v.options=d||this.resolveDataElementOptions(S,y.active?"active":i)),b||this.updateElement(y,S,v,i),E=_}}getMaxOverflow(){let t=this._cachedMeta,e=t.dataset,n=e.options&&e.options.borderWidth||0,i=t.data||[];if(!i.length)return n;let o=i[0].size(this.resolveDataElementOptions(0)),r=i[i.length-1].size(this.resolveDataElementOptions(i.length-1));return Math.max(n,o,r)/2}draw(){let t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}};U($e,"id","line"),U($e,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),U($e,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});we=class extends At{constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart,i=n.data.labels||[],o=ds(e._parsed[t].r,n.options.locale);return{label:i[t]||"",value:o}}parseObjectData(t,e,n,i){return Ji.bind(this)(t,e,n,i)}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((n,i)=>{let o=this.getParsed(i).r;!isNaN(o)&&this.chart.getDataVisibility(i)&&(oe.max&&(e.max=o))}),e}_updateRadius(){let t=this.chart,e=t.chartArea,n=t.options,i=Math.min(e.right-e.left,e.bottom-e.top),o=Math.max(i/2,0),r=Math.max(n.cutoutPercentage?o/100*n.cutoutPercentage:1,0),a=(o-r)/t.getVisibleDatasetCount();this.outerRadius=o-a*this.index,this.innerRadius=this.outerRadius-a}updateElements(t,e,n,i){let o=i==="reset",r=this.chart,l=r.options.animation,c=this._cachedMeta.rScale,d=c.xCenter,h=c.yCenter,u=c.getIndexAngle(0)-.5*nt,f=u,p,g=360/this.countVisibleElements();for(p=0;p{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++}),e}_computeAngle(t,e,n){return this.chart.getDataVisibility(t)?zt(this.resolveDataElementOptions(t,e).angle||n):0}};U(we,"id","polarArea"),U(we,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),U(we,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data;if(e.labels.length&&e.datasets.length){let{labels:{pointStyle:n,color:i}}=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:i,lineWidth:l.borderWidth,pointStyle:n,hidden:!t.getDataVisibility(r),index:r}})}return[]}},onClick(t,e,n){n.chart.toggleDataVisibility(e.index),n.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}});gs=class extends ie{};U(gs,"id","pie"),U(gs,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});He=class extends At{getLabelAndValue(t){let e=this._cachedMeta.vScale,n=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(n[e.axis])}}parseObjectData(t,e,n,i){return Ji.bind(this)(t,e,n,i)}update(t){let e=this._cachedMeta,n=e.dataset,i=e.data||[],o=e.iScale.getLabels();if(n.points=i,t!=="resize"){let r=this.resolveDatasetElementOptions(t);this.options.showLine||(r.borderWidth=0);let a={_loop:!0,_fullLoop:o.length===i.length,options:r};this.updateElement(n,void 0,a,t)}this.updateElements(i,0,i.length,t)}updateElements(t,e,n,i){let o=this._cachedMeta.rScale,r=i==="reset";for(let a=e;a0&&this.getParsed(e-1);for(let E=e;E0&&Math.abs(y[f]-C[f])>b,m&&(v.parsed=y,v.raw=c.data[E]),u&&(v.options=h||this.resolveDataElementOptions(E,S.active?"active":i)),x||this.updateElement(S,E,v,i),C=y}this.updateSharedOptions(h,i,d)}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 n=t.dataset,i=n.options&&n.options.borderWidth||0;if(!e.length)return i;let o=e[0].size(this.resolveDataElementOptions(0)),r=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(i,o,r)/2}};U(ze,"id","scatter"),U(ze,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),U(ze,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});gl=Object.freeze({__proto__:null,BarController:Ne,BubbleController:Be,DoughnutController:ie,LineController:$e,PieController:gs,PolarAreaController:we,RadarController:He,ScatterController:ze});xo=class s{constructor(t){U(this,"options");this.options=t||{}}static override(t){Object.assign(s.prototype,t)}init(){}formats(){return Ie()}parse(){return Ie()}format(){return Ie()}add(){return Ie()}diff(){return Ie()}startOf(){return Ie()}endOf(){return Ie()}},ml={_date:xo};bl={evaluateInteractionItems:nn,modes:{index(s,t,e,n){let i=Se(t,s),o=e.axis||"x",r=e.includeInvisible||!1,a=e.intersect?uo(s,i,o,n,r):fo(s,i,o,!1,n,r),l=[];return a.length?(s.getSortedVisibleDatasetMetas().forEach(c=>{let d=a[0].index,h=c.data[d];h&&!h.skip&&l.push({element:h,datasetIndex:c.index,index:d})}),l):[]},dataset(s,t,e,n){let i=Se(t,s),o=e.axis||"xy",r=e.includeInvisible||!1,a=e.intersect?uo(s,i,o,n,r):fo(s,i,o,!1,n,r);if(a.length>0){let l=a[0].datasetIndex,c=s.getDatasetMeta(l).data;a=[];for(let d=0;d{typeof g.beforeLayout=="function"&&g.beforeLayout()});let d=l.reduce((g,m)=>m.box.options&&m.box.options.display===!1?g:g+1,0)||1,h=Object.freeze({outerWidth:t,outerHeight:e,padding:i,availableWidth:o,availableHeight:r,vBoxMaxWidth:o/2/d,hBoxMaxHeight:r/2}),u=Object.assign({},i);yl(u,_t(n));let f=Object.assign({maxPadding:u,w:o,h:r,x:i.left,y:i.top},i),p=jh(l.concat(c),h);qs(a.fullSize,f,h,p),qs(l,f,h,p),qs(c,f,h,p)&&qs(l,f,h,p),Yh(f),wa(a.leftAndTop,f,h,p),f.x+=f.w,f.y+=f.h,wa(a.rightAndBottom,f,h,p),s.chartArea={left:f.left,top:f.top,right:f.left+f.w,bottom:f.top+f.h,height:f.h,width:f.w},rt(a.chartArea,g=>{let m=g.box;Object.assign(m,s.chartArea),m.update(f.w,f.h,{left:0,top:0,right:0,bottom:0})})}},Js=class{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,n){}removeEventListener(t,e,n){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,n,i){return e=Math.max(0,e||t.width),n=n||t.height,{width:e,height:Math.max(0,i?Math.floor(e/i):n)}}isAttached(t){return!0}updateConfig(t){}},Xn=class extends Js{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}},Yn="$chartjs",qh={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},Da=s=>s===null||s==="";xl=la?{passive:!0}:!1;tn=new Map,Ma=0;Zn=class extends Js{acquireContext(t,e){let n=t&&t.getContext&&t.getContext("2d");return n&&n.canvas===t?(Xh(t,e),n):null}releaseContext(t){let e=t.canvas;if(!e[Yn])return!1;let n=e[Yn].initial;["height","width"].forEach(o=>{let r=n[o];tt(r)?e.removeAttribute(o):e.setAttribute(o,r)});let i=n.style||{};return Object.keys(i).forEach(o=>{e.style[o]=i[o]}),e.width=e.width,delete e[Yn],!0}addEventListener(t,e,n){this.removeEventListener(t,e);let i=t.$proxies||(t.$proxies={}),r={attach:tu,detach:eu,resize:iu}[e]||ou;i[e]=r(t,e,n)}removeEventListener(t,e){let n=t.$proxies||(t.$proxies={}),i=n[e];if(!i)return;({attach:po,detach:po,resize:po}[e]||Zh)(t,e,i),n[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,n,i){return aa(t,e,n,i)}isAttached(t){let e=t&&Bn(t);return!!(e&&e.isConnected)}};Rt=class{constructor(){U(this,"x");U(this,"y");U(this,"active",!1);U(this,"options");U(this,"$animations")}tooltipPosition(t){let{x:e,y:n}=this.getProps(["x","y"],t);return{x:e,y:n}}hasValue(){return Oe(this.x)&&Oe(this.y)}getProps(t,e){let n=this.$animations;if(!e||!n)return this;let i={};return t.forEach(o=>{i[o]=n[o]&&n[o].active()?n[o]._to:this[o]}),i}};U(Rt,"defaults",{}),U(Rt,"defaultRoutes");uu=s=>s==="left"?"right":s==="right"?"left":s,Ta=(s,t,e)=>t==="top"||t==="left"?s[t]+e:s[t]-e,La=(s,t)=>Math.min(t||s,s);Te=class s extends Rt{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:n,_suggestedMax:i}=this;return t=Tt(t,Number.POSITIVE_INFINITY),e=Tt(e,Number.NEGATIVE_INFINITY),n=Tt(n,Number.POSITIVE_INFINITY),i=Tt(i,Number.NEGATIVE_INFINITY),{min:Tt(t,n),max:Tt(e,i),minDefined:pt(t),maxDefined:pt(e)}}getMinMax(t){let{min:e,max:n,minDefined:i,maxDefined:o}=this.getUserBounds(),r;if(i&&o)return{min:e,max:n};let a=this.getMatchingVisibleMetas();for(let l=0,c=a.length;ln?n:e,n=i&&e>n?e:n,{min:Tt(e,Tt(n,e)),max:Tt(n,Tt(e,n))}}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,n){let{beginAtZero:i,grace:o,ticks:r}=this.options,a=r.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=n=Object.assign({left:0,right:0,top:0,bottom:0},n),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+n.left+n.right:this.height+n.top+n.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=ea(this,o,i),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();let l=a=o||n<=1||!this.isHorizontal()){this.labelRotation=i;return}let d=this._getLabelSizes(),h=d.widest.width,u=d.highest.height,f=vt(this.chart.width-h,0,this.maxWidth);a=t.offset?this.maxWidth/n:f/(n-1),h+6>a&&(a=f/(n-(t.offset?.5:1)),l=this.maxHeight-Ys(t.grid)-e.padding-Pa(t.title,this.chart.options.font),c=Math.sqrt(h*h+u*u),r=An(Math.min(Math.asin(vt((d.highest.height+6)/a,-1,1)),Math.asin(vt(l/c,-1,1))-Math.asin(vt(u/c,-1,1)))),r=Math.max(i,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:n,title:i,grid:o}}=this,r=this._isVisible(),a=this.isHorizontal();if(r){let l=Pa(i,e.options.font);if(a?(t.width=this.maxWidth,t.height=Ys(o)+l):(t.height=this.maxHeight,t.width=Ys(o)+l),n.display&&this.ticks.length){let{first:c,last:d,widest:h,highest:u}=this._getLabelSizes(),f=n.padding*2,p=zt(this.labelRotation),g=Math.cos(p),m=Math.sin(p);if(a){let b=n.mirror?0:m*h.width+g*u.height;t.height=Math.min(this.maxHeight,t.height+b+f)}else{let b=n.mirror?0:g*h.width+m*u.height;t.width=Math.min(this.maxWidth,t.width+b+f)}this._calculatePadding(c,d,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,n,i){let{ticks:{align:o,padding:r},position:a}=this.options,l=this.labelRotation!==0,c=a!=="top"&&this.axis==="x";if(this.isHorizontal()){let d=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1),u=0,f=0;l?c?(u=i*t.width,f=n*e.height):(u=n*t.height,f=i*e.width):o==="start"?f=e.width:o==="end"?u=t.width:o!=="inner"&&(u=t.width/2,f=e.width/2),this.paddingLeft=Math.max((u-d+r)*this.width/(this.width-d),0),this.paddingRight=Math.max((f-h+r)*this.width/(this.width-h),0)}else{let d=e.height/2,h=t.height/2;o==="start"?(d=0,h=t.height):o==="end"&&(d=e.height,h=0),this.paddingTop=d+r,this.paddingBottom=h+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,n;for(e=0,n=t.length;e({width:r[w]||0,height:a[w]||0});return{first:_(0),last:_(e-1),widest:_(y),highest:_(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?xe(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*i?a/n:l/i:l*i0}_computeGridLineItems(t){let e=this.axis,n=this.chart,i=this.options,{grid:o,position:r,border:a}=i,l=o.offset,c=this.isHorizontal(),h=this.ticks.length+(l?1:0),u=Ys(o),f=[],p=a.setContext(this.getContext()),g=p.display?p.width:0,m=g/2,b=function(R){return xe(n,R,g)},x,C,E,S,y,v,_,w,T,k,M,L;if(r==="top")x=b(this.bottom),v=this.bottom-u,w=x-m,k=b(t.top)+m,L=t.bottom;else if(r==="bottom")x=b(this.top),k=t.top,L=b(t.bottom)-m,v=x+m,w=this.top+u;else if(r==="left")x=b(this.right),y=this.right-u,_=x-m,T=b(t.left)+m,M=t.right;else if(r==="right")x=b(this.left),T=t.left,M=b(t.right)-m,y=x+m,_=this.left+u;else if(e==="x"){if(r==="center")x=b((t.top+t.bottom)/2+.5);else if(et(r)){let R=Object.keys(r)[0],D=r[R];x=b(this.chart.scales[R].getPixelForValue(D))}k=t.top,L=t.bottom,v=x+m,w=v+u}else if(e==="y"){if(r==="center")x=b((t.left+t.right)/2);else if(et(r)){let R=Object.keys(r)[0],D=r[R];x=b(this.chart.scales[R].getPixelForValue(D))}y=x-m,_=y-u,T=t.left,M=t.right}let I=J(i.ticks.maxTicksLimit,h),P=Math.max(1,Math.ceil(h/I));for(C=0;C0&&(F-=G/2);break}$={left:F,top:B,width:G+A.width,height:z+A.height,color:P.backdropColor}}m.push({label:E,font:w,textOffset:M,options:{rotation:g,color:D,strokeColor:W,strokeWidth:O,textAlign:j,textBaseline:L,translation:[S,y],backdrop:$}})}return m}_getXAxisLabelAlignment(){let{position:t,ticks:e}=this.options;if(-zt(this.labelRotation))return t==="top"?"left":"right";let i="center";return e.align==="start"?i="left":e.align==="end"?i="right":e.align==="inner"&&(i="inner"),i}_getYAxisLabelAlignment(t){let{position:e,ticks:{crossAlign:n,mirror:i,padding:o}}=this.options,r=this._getLabelSizes(),a=t+o,l=r.widest.width,c,d;return e==="left"?i?(d=this.right+o,n==="near"?c="left":n==="center"?(c="center",d+=l/2):(c="right",d+=l)):(d=this.right-a,n==="near"?c="right":n==="center"?(c="center",d-=l/2):(c="left",d=this.left)):e==="right"?i?(d=this.left+o,n==="near"?c="right":n==="center"?(c="center",d-=l/2):(c="left",d-=l)):(d=this.left+a,n==="near"?c="left":n==="center"?(c="center",d+=l/2):(c="right",d=this.right)):c="right",{textAlign:c,x:d}}_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:n,top:i,width:o,height:r}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(n,i,o,r),t.restore())}getLineWidthForValue(t){let e=this.options.grid;if(!this._isVisible()||!e.display)return 0;let i=this.ticks.findIndex(o=>o.value===t);return i>=0?e.setContext(this.getContext(i)).lineWidth:0}drawGrid(t){let e=this.options.grid,n=this.ctx,i=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t)),o,r,a=(l,c,d)=>{!d.width||!d.color||(n.save(),n.lineWidth=d.width,n.strokeStyle=d.color,n.setLineDash(d.borderDash||[]),n.lineDashOffset=d.borderDashOffset,n.beginPath(),n.moveTo(l.x,l.y),n.lineTo(c.x,c.y),n.stroke(),n.restore())};if(e.display)for(o=0,r=i.length;o{this.draw(o)}}]:[{z:n,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:i,draw:()=>{this.drawBorder()}},{z:e,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(t){let e=this.chart.getSortedVisibleDatasetMetas(),n=this.axis+"AxisID",i=[],o,r;for(o=0,r=e.length;o{let o=n||this._getRegistryForType(i);n||o.isForType(i)||o===this.plugins&&i.id?this._exec(t,o,i):rt(i,r=>{let a=n||this._getRegistryForType(r);this._exec(t,a,r)})})}_exec(t,e,n){let i=Ln(t);ct(n["before"+i],[],n),e[t](n),ct(n["after"+i],[],n)}_getRegistryForType(t){for(let e=0;eo.filter(a=>!r.some(l=>a.plugin.id===l.plugin.id));this._notify(i(e,n),t,"stop"),this._notify(i(n,e),t,"start")}};Fa=new Map,kl=new Set;Gs=(s,t,e)=>{let n=ce(t,e);n!==void 0&&s.add(n)},ko=class{constructor(t){this._config=Au(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=El(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(),Sl(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return Wn(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,e){return Wn(`${t}.transition.${e}`,()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,e){return Wn(`${t}-${e}`,()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]])}pluginScopeKeys(t){let e=t.id,n=this.type;return Wn(`${n}-plugin-${e}`,()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]])}_cachedScopes(t,e){let n=this._scopeCache,i=n.get(t);return(!i||e)&&(i=new Map,n.set(t,i)),i}getOptionScopes(t,e,n){let{options:i,type:o}=this,r=this._cachedScopes(t,n),a=r.get(e);if(a)return a;let l=new Set;e.forEach(d=>{t&&(l.add(t),d.forEach(h=>Gs(l,t,h))),d.forEach(h=>Gs(l,i,h)),d.forEach(h=>Gs(l,ye[o]||{},h)),d.forEach(h=>Gs(l,ut,h)),d.forEach(h=>Gs(l,On,h))});let c=Array.from(l);return c.length===0&&c.push(Object.create(null)),kl.has(e)&&r.set(e,c),c}chartOptionScopes(){let{options:t,type:e}=this;return[t,ye[e]||{},ut.datasets[e]||{},{type:e},ut,On]}resolveNamedOptions(t,e,n,i=[""]){let o={$shared:!0},{resolver:r,subPrefixes:a}=Ia(this._resolverCache,t,i),l=r;if(Ru(r,e)){o.$shared=!1,n=ae(n)?n():n;let c=this.createResolver(t,n,a);l=Re(r,n,c)}for(let c of e)o[c]=l[c];return o}createResolver(t,e,n=[""],i){let{resolver:o}=Ia(this._resolverCache,t,n);return et(e)?Re(o,e,void 0,i):o}};Pu=s=>et(s)&&Object.getOwnPropertyNames(s).some(t=>ae(s[t]));Ou="4.5.1",Fu=["top","bottom","left","right","chartArea"];Gn={},$a=s=>{let t=wl(s);return Object.values(Gn).filter(e=>e.canvas===t).pop()};ne=class{static register(...t){Kt.add(...t),Ha()}static unregister(...t){Kt.remove(...t),Ha()}constructor(t,e){let n=this.config=new ko(e),i=wl(t),o=$a(i);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=n.createResolver(n.chartOptionScopes(),this.getContext());this.platform=new(n.platform||_l(i)),this.platform.updateConfig(n);let a=this.platform.acquireContext(i,r.aspectRatio),l=a&&a.canvas,c=l&&l.height,d=l&&l.width;if(this.id=Nr(),this.ctx=a,this.canvas=l,this.width=d,this.height=c,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 _o,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=qr(h=>this.update(h),r.resizeDelay||0),this._dataChanges=[],Gn[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}se.listen(this,"complete",Ba),se.listen(this,"progress",Iu),this._initialize(),this.attached&&this.update()}get aspectRatio(){let{options:{aspectRatio:t,maintainAspectRatio:e},width:n,height:i,_aspectRatio:o}=this;return tt(t)?e&&o?o:i?n/i: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 Kt}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():to(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Yi(this.canvas,this.ctx),this}stop(){return se.stop(this),this}resize(t,e){se.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){let n=this.options,i=this.canvas,o=n.maintainAspectRatio&&this.aspectRatio,r=this.platform.getMaximumSize(i,t,e,o),a=n.devicePixelRatio||this.platform.getDevicePixelRatio(),l=this.width?"resize":"attach";this.width=r.width,this.height=r.height,this._aspectRatio=this.aspectRatio,to(this,a,!0)&&(this.notifyPlugins("resize",{size:r}),ct(n.onResize,[this,r],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){let e=this.options.scales||{};rt(e,(n,i)=>{n.id=i})}buildOrUpdateScales(){let t=this.options,e=t.scales,n=this.scales,i=Object.keys(n).reduce((r,a)=>(r[a]=!1,r),{}),o=[];e&&(o=o.concat(Object.keys(e).map(r=>{let a=e[r],l=Eo(r,a),c=l==="r",d=l==="x";return{options:a,dposition:c?"chartArea":d?"bottom":"left",dtype:c?"radialLinear":d?"category":"linear"}}))),rt(o,r=>{let a=r.options,l=a.id,c=Eo(l,a),d=J(a.type,r.dtype);(a.position===void 0||Va(a.position,c)!==Va(r.dposition))&&(a.position=r.dposition),i[l]=!0;let h=null;if(l in n&&n[l].type===d)h=n[l];else{let u=Kt.getScale(d);h=new u({id:l,type:d,ctx:this.ctx,chart:this}),n[h.id]=h}h.init(a,t)}),rt(i,(r,a)=>{r||delete n[a]}),rt(n,r=>{St.configure(this,r,r.options),St.addBox(this,r)})}_updateMetasets(){let t=this._metasets,e=this.data.datasets.length,n=t.length;if(t.sort((i,o)=>i.index-o.index),n>e){for(let i=e;ie.length&&delete this._stacks,t.forEach((n,i)=>{e.filter(o=>o===n._dataset).length===0&&this._destroyDatasetMeta(i)})}buildOrUpdateControllers(){let t=[],e=this.data.datasets,n,i;for(this._removeUnreferencedMetasets(),n=0,i=e.length;n{this.getDatasetMeta(e).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){let e=this.config;e.update();let n=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),i=this._animationsDisabled=!n.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 c=0,d=this.data.datasets.length;c{c.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(Na("z","_idx"));let{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){rt(this.scales,t=>{St.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){let t=this.options,e=new Set(Object.keys(this._listeners)),n=new Set(t.events);(!Oi(e,n)||!!this._responsiveListeners!==t.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){let{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(let{method:n,start:i,count:o}of e){let r=n==="_removeElements"?-o:o;Vu(t,i,r)}}_getUniformDataChanges(){let t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];let e=this.data.datasets.length,n=o=>new Set(t.filter(r=>r[0]===o).map((r,a)=>a+","+r.splice(1).join(","))),i=n(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;St.update(this,this.width,this.height,t);let e=this.chartArea,n=e.width<=0||e.height<=0;this._layers=[],rt(this.boxes,i=>{n&&i.position==="chartArea"||(i.configure&&i.configure(),this._layers.push(...i._layers()))},this),this._layers.forEach((i,o)=>{i._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})!==!1){for(let e=0,n=this.data.datasets.length;e=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){let e=this.ctx,n={meta:t,index:t.index,cancelable:!0},i=ro(this,t);this.notifyPlugins("beforeDatasetDraw",n)!==!1&&(i&&zs(e,i),t.controller.draw(),i&&Ws(e),n.cancelable=!1,this.notifyPlugins("afterDatasetDraw",n))}isPointInArea(t){return Zt(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,n,i){let o=bl.modes[e];return typeof o=="function"?o(this,t,n,i):[]}getDatasetMeta(t){let e=this.data.datasets[t],n=this._metasets,i=n.filter(o=>o&&o._dataset===e).pop();return i||(i={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},n.push(i)),i}getContext(){return this.$context||(this.$context=de(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){let e=this.data.datasets[t];if(!e)return!1;let n=this.getDatasetMeta(t);return typeof n.hidden=="boolean"?!n.hidden:!e.hidden}setDatasetVisibility(t,e){let n=this.getDatasetMeta(t);n.hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,n){let i=n?"show":"hide",o=this.getDatasetMeta(t),r=o.controller._resolveAnimations(void 0,i);as(e)?(o.data[e].hidden=!n,this.update()):(this.setDatasetVisibility(t,n),r.update(o,{visible:n}),this.update(a=>a.datasetIndex===t?i: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(),se.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,o,r),t[o]=r},i=(o,r,a)=>{o.offsetX=r,o.offsetY=a,this._eventHandler(o)};rt(this.options.events,o=>n(o,i))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});let t=this._responsiveListeners,e=this.platform,n=(l,c)=>{e.addEventListener(this,l,c),t[l]=c},i=(l,c)=>{t[l]&&(e.removeEventListener(this,l,c),delete t[l])},o=(l,c)=>{this.canvas&&this.resize(l,c)},r,a=()=>{i("attach",a),this.attached=!0,this.resize(),n("resize",o),n("detach",r)};r=()=>{this.attached=!1,i("resize",o),this._stop(),this._resize(0,0),n("attach",a)},e.isAttached(this.canvas)?a():r()}unbindEvents(){rt(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},rt(this._responsiveListeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._responsiveListeners=void 0}updateHoverStyle(t,e,n){let i=n?"set":"remove",o,r,a,l;for(e==="dataset"&&(o=this.getDatasetMeta(t[0].datasetIndex),o.controller["_"+i+"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}});!Hs(n,e)&&(this._active=n,this._lastEvent=null,this._updateHoverStyles(n,e))}notifyPlugins(t,e,n){return this._plugins.notify(this,t,e,n)}isPluginEnabled(t){return this._plugins._cache.filter(e=>e.plugin.id===t).length===1}_updateHoverStyles(t,e,n){let i=this.options.hover,o=(l,c)=>l.filter(d=>!c.some(h=>d.datasetIndex===h.datasetIndex&&d.index===h.index)),r=o(e,t),a=n?t:o(t,e);r.length&&this.updateHoverStyle(r,i.mode,!1),a.length&&i.mode&&this.updateHoverStyle(a,i.mode,!0)}_eventHandler(t,e){let n={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},i=r=>(r.options.events||this.options.events).includes(t.native.type);if(this.notifyPlugins("beforeEvent",n,i)===!1)return;let o=this._handleEvent(t,e,n.inChartArea);return n.cancelable=!1,this.notifyPlugins("afterEvent",n,i),(o||n.changed)&&this.render(),this}_handleEvent(t,e,n){let{_active:i=[],options:o}=this,r=e,a=this._getActiveElements(t,i,n,r),l=Hr(t),c=Nu(t,this._lastEvent,n,l);n&&(this._lastEvent=null,ct(o.onHover,[t,a,this],this),l&&ct(o.onClick,[t,a,this],this));let d=!Hs(a,i);return(d||e)&&(this._active=a,this._updateHoverStyles(a,i,e)),this._lastEvent=c,d}_getActiveElements(t,e,n,i){if(t.type==="mouseout")return[];if(!n)return e;let o=this.options.hover;return this.getElementsAtEventForMode(t,o.mode,o,i)}};U(ne,"defaults",ut),U(ne,"instances",Gn),U(ne,"overrides",ye),U(ne,"registry",Kt),U(ne,"version",Ou),U(ne,"getChart",$a);Ee=class extends Rt{constructor(e){super();U(this,"circumference");U(this,"endAngle");U(this,"fullCircles");U(this,"innerRadius");U(this,"outerRadius");U(this,"pixelMargin");U(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,n,i){let o=this.getProps(["x","y"],i),{angle:r,distance:a}=Ni(o,{x:e,y:n}),{startAngle:l,endAngle:c,innerRadius:d,outerRadius:h,circumference:u}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),f=(this.options.spacing+this.options.borderWidth)/2,p=J(u,c-l),g=cs(r,l,c)&&l!==c,m=p>=ht||g,b=te(a,d+f,h+f);return m&&b}getCenterPoint(e){let{x:n,y:i,startAngle:o,endAngle:r,innerRadius:a,outerRadius:l}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],e),{offset:c,spacing:d}=this.options,h=(o+r)/2,u=(a+l+d+c)/2;return{x:n+Math.cos(h)*u,y:i+Math.sin(h)*u}}tooltipPosition(e){return this.getCenterPoint(e)}draw(e){let{options:n,circumference:i}=this,o=(n.offset||0)/4,r=(n.spacing||0)/2,a=n.circular;if(this.pixelMargin=n.borderAlign==="inner"?.33:0,this.fullCircles=i>ht?Math.floor(i/ht):0,i===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 c=1-Math.sin(Math.min(nt,i||0)),d=o*c;e.fillStyle=n.backgroundColor,e.strokeStyle=n.borderColor,Wu(e,this,d,r,a),ju(e,this,d,r,a),e.restore()}};U(Ee,"id","arc"),U(Ee,"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}),U(Ee,"defaultRoutes",{backgroundColor:"backgroundColor"}),U(Ee,"descriptors",{_scriptable:!0,_indexable:e=>e!=="borderDash"});Zu=typeof Path2D=="function";Yt=class extends Rt{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 n=this.options;if((n.tension||n.cubicInterpolationMode==="monotone")&&!n.stepped&&!this._pointsUpdated){let i=n.spanGaps?this._loop:this._fullLoop;ra(this._points,n,t,i,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=ua(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,n=t.length;return n&&e[t[n-1].end]}interpolate(t,e){let n=this.options,i=t[e],o=this.points,r=oo(this,{property:e,start:i,end:i});if(!r.length)return;let a=[],l=qu(n),c,d;for(c=0,d=r.length;ct!=="borderDash"&&t!=="fill"});We=class extends Rt{constructor(e){super();U(this,"parsed");U(this,"skip");U(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,n,i){let o=this.options,{x:r,y:a}=this.getProps(["x","y"],i);return Math.pow(e-r,2)+Math.pow(n-a,2)s.replace("rgb(","rgba(").replace(")",", 0.5)"));Rl={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(s,t,e){if(!e.enabled)return;let{data:{datasets:n},options:i}=s.config,{elements:o}=i,r=ja(n)||df(i)||o&&ja(o)||hf();if(!e.forceOverride&&r)return;let a=cf(s);n.forEach(a)}};Fl={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(s,t,e)=>{if(!e.enabled){Ua(s);return}let n=s.width;s.data.datasets.forEach((i,o)=>{let{_data:r,indexAxis:a}=i,l=s.getDatasetMeta(o),c=r||i.data;if(fs([a,s.options.indexAxis])==="y"||!l.controller.supportsDecimation)return;let d=s.scales[l.xAxisID];if(d.type!=="linear"&&d.type!=="time"||s.options.parsing)return;let{start:h,count:u}=pf(l,c),f=e.threshold||4*n;if(u<=f){Ol(i);return}tt(r)&&(i._data=c,delete i.data,Object.defineProperty(i,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(g){this._data=g}}));let p;switch(e.algorithm){case"lttb":p=uf(c,h,u,n,e);break;case"min-max":p=ff(c,h,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${e.algorithm}'`)}i._decimated=p})},destroy(s){Ua(s)}};ti=class{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,n){let{x:i,y:o,radius:r}=this;return e=e||{start:0,end:ht},t.arc(i,o,r,e.end,e.start,!0),!n.bounds}interpolate(t){let{x:e,y:n,radius:i}=this,o=t.angle;return{x:e+Math.cos(o)*i,y:n+Math.sin(o)*i,angle:o}}};Vl={id:"filler",afterDatasetsUpdate(s,t,e){let n=(s.data.datasets||[]).length,i=[],o,r,a,l;for(r=0;r=0;--r){let a=i[r].$filler;a&&(a.line.updateControlPoints(o,a.axis),n&&a.fill&&bo(s.ctx,a,o))}},beforeDatasetsDraw(s,t,e){if(e.drawTime!=="beforeDatasetsDraw")return;let n=s.getSortedVisibleDatasetMetas();for(let i=n.length-1;i>=0;--i){let o=n[i].$filler;Ya(o)&&bo(s.ctx,o,s.chartArea)}},beforeDatasetDraw(s,t,e){let n=t.meta.$filler;!Ya(n)||e.drawTime!=="beforeDatasetDraw"||bo(s.ctx,n,s.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}},Qa=(s,t)=>{let{boxHeight:e=t,boxWidth:n=t}=s;return s.usePointStyle&&(e=Math.min(e,t),n=s.pointStyleWidth||Math.min(n,t)),{boxWidth:n,boxHeight:e,itemHeight:Math.max(t,e)}},Of=(s,t)=>s!==null&&t!==null&&s.datasetIndex===t.datasetIndex&&s.index===t.index,ei=class extends Rt{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,n){this.maxWidth=t,this.maxHeight=e,this._margins=n,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(n=>t.filter(n,this.chart.data))),t.sort&&(e=e.sort((n,i)=>t.sort(n,i,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 n=t.labels,i=bt(n.font),o=i.size,r=this._computeTitleHeight(),{boxWidth:a,itemHeight:l}=Qa(n,o),c,d;e.font=i.string,this.isHorizontal()?(c=this.maxWidth,d=this._fitRows(r,o,a,l)+10):(d=this.maxHeight,c=this._fitCols(r,i,a,l)+10),this.width=Math.min(c,t.maxWidth||this.maxWidth),this.height=Math.min(d,t.maxHeight||this.maxHeight)}_fitRows(t,e,n,i){let{ctx:o,maxWidth:r,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],c=this.lineWidths=[0],d=i+a,h=t;o.textAlign="left",o.textBaseline="middle";let u=-1,f=-d;return this.legendItems.forEach((p,g)=>{let m=n+e/2+o.measureText(p.text).width;(g===0||c[c.length-1]+m+2*a>r)&&(h+=d,c[c.length-(g>0?0:1)]=0,f+=d,u++),l[g]={left:0,top:f,row:u,width:m,height:i},c[c.length-1]+=m+a}),h}_fitCols(t,e,n,i){let{ctx:o,maxHeight:r,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],c=this.columnSizes=[],d=r-t,h=a,u=0,f=0,p=0,g=0;return this.legendItems.forEach((m,b)=>{let{itemWidth:x,itemHeight:C}=Ff(n,e,o,m,i);b>0&&f+C+2*a>d&&(h+=u+a,c.push({width:u,height:f}),p+=u+a,g++,u=f=0),l[b]={left:p,top:f,col:g,width:x,height:C},u=Math.max(u,x),f+=C+a}),h+=u,c.push({width:u,height:f}),h}adjustHitBoxes(){if(!this.options.display)return;let t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:n,labels:{padding:i},rtl:o}}=this,r=Fe(o,this.left,this.width);if(this.isHorizontal()){let a=0,l=Ct(n,this.left+i,this.right-this.lineWidths[a]);for(let c of e)a!==c.row&&(a=c.row,l=Ct(n,this.left+i,this.right-this.lineWidths[a])),c.top+=this.top+t+i,c.left=r.leftForLtr(r.x(l),c.width),l+=c.width+i}else{let a=0,l=Ct(n,this.top+t+i,this.bottom-this.columnSizes[a].height);for(let c of e)c.col!==a&&(a=c.col,l=Ct(n,this.top+t+i,this.bottom-this.columnSizes[a].height)),c.top=l,c.left+=this.left+i,c.left=r.leftForLtr(r.x(c.left),c.width),l+=c.height+i}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){let t=this.ctx;zs(t,this),this._draw(),Ws(t)}}_draw(){let{options:t,columnSizes:e,lineWidths:n,ctx:i}=this,{align:o,labels:r}=t,a=ut.color,l=Fe(t.rtl,this.left,this.width),c=bt(r.font),{padding:d}=r,h=c.size,u=h/2,f;this.drawTitle(),i.textAlign=l.textAlign("left"),i.textBaseline="middle",i.lineWidth=.5,i.font=c.string;let{boxWidth:p,boxHeight:g,itemHeight:m}=Qa(r,h),b=function(y,v,_){if(isNaN(p)||p<=0||isNaN(g)||g<0)return;i.save();let w=J(_.lineWidth,1);if(i.fillStyle=J(_.fillStyle,a),i.lineCap=J(_.lineCap,"butt"),i.lineDashOffset=J(_.lineDashOffset,0),i.lineJoin=J(_.lineJoin,"miter"),i.lineWidth=w,i.strokeStyle=J(_.strokeStyle,a),i.setLineDash(J(_.lineDash,[])),r.usePointStyle){let T={radius:g*Math.SQRT2/2,pointStyle:_.pointStyle,rotation:_.rotation,borderWidth:w},k=l.xPlus(y,p/2),M=v+u;Gi(i,T,k,M,r.pointStyleWidth&&p)}else{let T=v+Math.max((h-g)/2,0),k=l.leftForLtr(y,p),M=_e(_.borderRadius);i.beginPath(),Object.values(M).some(L=>L!==0)?us(i,{x:k,y:T,w:p,h:g,radius:M}):i.rect(k,T,p,g),i.fill(),w!==0&&i.stroke()}i.restore()},x=function(y,v,_){Ce(i,_.text,y,v+m/2,c,{strikethrough:_.hidden,textAlign:l.textAlign(_.textAlign)})},C=this.isHorizontal(),E=this._computeTitleHeight();C?f={x:Ct(o,this.left+d,this.right-n[0]),y:this.top+d+E,line:0}:f={x:this.left+d,y:Ct(o,this.top+E+d,this.bottom-e[0].height),line:0},so(this.ctx,t.textDirection);let S=m+d;this.legendItems.forEach((y,v)=>{i.strokeStyle=y.fontColor,i.fillStyle=y.fontColor;let _=i.measureText(y.text).width,w=l.textAlign(y.textAlign||(y.textAlign=r.textAlign)),T=p+u+_,k=f.x,M=f.y;l.setWidth(this.width),C?v>0&&k+T+d>this.right&&(M=f.y+=S,f.line++,k=f.x=Ct(o,this.left+d,this.right-n[f.line])):v>0&&M+S>this.bottom&&(k=f.x=k+e[f.line].width+d,f.line++,M=f.y=Ct(o,this.top+E+d,this.bottom-e[f.line].height));let L=l.x(k);if(b(L,M,y),k=Xr(w,k+p+u,C?k+T:this.right,t.rtl),x(l.x(k),M,y),C)f.x+=T+d;else if(typeof y.text!="string"){let I=c.lineHeight;f.y+=Nl(y,I)+d}else f.y+=S}),no(this.ctx,t.textDirection)}drawTitle(){let t=this.options,e=t.title,n=bt(e.font),i=_t(e.padding);if(!e.display)return;let o=Fe(t.rtl,this.left,this.width),r=this.ctx,a=e.position,l=n.size/2,c=i.top+l,d,h=this.left,u=this.width;if(this.isHorizontal())u=Math.max(...this.lineWidths),d=this.top+c,h=Ct(t.align,h,this.right-u);else{let p=this.columnSizes.reduce((g,m)=>Math.max(g,m.height),0);d=c+Ct(t.align,this.top,this.bottom-p-t.labels.padding-this._computeTitleHeight())}let f=Ct(a,h,h+u);r.textAlign=o.textAlign(Rn(a)),r.textBaseline="middle",r.strokeStyle=e.color,r.fillStyle=e.color,r.font=n.string,Ce(r,e.text,f,d,n)}_computeTitleHeight(){let t=this.options.title,e=bt(t.font),n=_t(t.padding);return t.display?e.lineHeight+n.height:0}_getLegendItemAt(t,e){let n,i,o;if(te(t,this.left,this.right)&&te(e,this.top,this.bottom)){for(o=this.legendHitBoxes,n=0;ns.chart.options.color,boxWidth:40,padding:10,generateLabels(s){let t=s.data.datasets,{labels:{usePointStyle:e,pointStyle:n,textAlign:i,color:o,useBorderRadius:r,borderRadius:a}}=s.legend.options;return s._getSortedDatasetMetas().map(l=>{let c=l.controller.getStyle(e?0:void 0),d=_t(c.borderWidth);return{text:t[l.index].label,fillStyle:c.backgroundColor,fontColor:o,hidden:!l.visible,lineCap:c.borderCapStyle,lineDash:c.borderDash,lineDashOffset:c.borderDashOffset,lineJoin:c.borderJoinStyle,lineWidth:(d.width+d.height)/4,strokeStyle:c.borderColor,pointStyle:n||c.pointStyle,rotation:c.rotation,textAlign:i||c.textAlign,borderRadius:r&&(a||c.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)}}},en=class extends Rt{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 n=this.options;if(this.left=0,this.top=0,!n.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=t,this.height=this.bottom=e;let i=dt(n.text)?n.text.length:1;this._padding=_t(n.padding);let o=i*bt(n.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:n,bottom:i,right:o,options:r}=this,a=r.align,l=0,c,d,h;return this.isHorizontal()?(d=Ct(a,n,o),h=e+t,c=o-n):(r.position==="left"?(d=n+t,h=Ct(a,i,e),l=nt*-.5):(d=o-t,h=Ct(a,e,i),l=nt*.5),c=i-e),{titleX:d,titleY:h,maxWidth:c,rotation:l}}draw(){let t=this.ctx,e=this.options;if(!e.display)return;let n=bt(e.font),o=n.lineHeight/2+this._padding.top,{titleX:r,titleY:a,maxWidth:l,rotation:c}=this._drawArgs(o);Ce(t,e.text,0,0,n,{color:e.color,maxWidth:l,rotation:c,textAlign:Rn(e.align),textBaseline:"middle",translation:[r,a]})}};$l={id:"title",_element:en,start(s,t,e){Bf(s,e)},stop(s){let t=s.titleBlock;St.removeBox(s,t),delete s.titleBlock},beforeUpdate(s,t,e){let n=s.titleBlock;St.configure(s,n,e),n.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}},jn=new WeakMap,Hl={id:"subtitle",start(s,t,e){let n=new en({ctx:s.ctx,options:e,chart:s});St.configure(s,n,e),St.addBox(s,n),jn.set(s,n)},stop(s){St.removeBox(s,jn.get(s)),jn.delete(s)},beforeUpdate(s,t,e){let n=jn.get(s);St.configure(s,n,e),n.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}},Xs={average(s){if(!s.length)return!1;let t,e,n=new Set,i=0,o=0;for(t=0,e=s.length;ta+l)/n.size,y:i/o}},nearest(s,t){if(!s.length)return!1;let e=t.x,n=t.y,i=Number.POSITIVE_INFINITY,o,r,a;for(o=0,r=s.length;o0){let t=s[0],e=t.chart.data.labels,n=e?e.length:0;if(this&&this.options&&this.options.mode==="dataset")return t.dataset.label||"";if(t.label)return t.label;if(n>0&&t.dataIndex{let r={before:[],lines:[],after:[]},a=sl(n,o);ee(r.before,he(Lt(a,"beforeLabel",this,o))),ee(r.lines,Lt(a,"label",this,o)),ee(r.after,he(Lt(a,"afterLabel",this,o))),i.push(r)}),i}getAfterBody(t,e){return el(Lt(e.callbacks,"afterBody",this,t))}getFooter(t,e){let{callbacks:n}=e,i=Lt(n,"beforeFooter",this,t),o=Lt(n,"footer",this,t),r=Lt(n,"afterFooter",this,t),a=[];return a=ee(a,he(i)),a=ee(a,he(o)),a=ee(a,he(r)),a}_createItems(t){let e=this._active,n=this.chart.data,i=[],o=[],r=[],a=[],l,c;for(l=0,c=e.length;lt.filter(d,h,u,n))),t.itemSort&&(a=a.sort((d,h)=>t.itemSort(d,h,n))),rt(a,d=>{let h=sl(t.callbacks,d);i.push(Lt(h,"labelColor",this,d)),o.push(Lt(h,"labelPointStyle",this,d)),r.push(Lt(h,"labelTextColor",this,d))}),this.labelColors=i,this.labelPointStyles=o,this.labelTextColors=r,this.dataPoints=a,a}update(t,e){let n=this.options.setContext(this.getContext()),i=this._active,o,r=[];if(!i.length)this.opacity!==0&&(o={opacity:0});else{let a=Xs[n.position].call(this,i,this._eventPosition);r=this._createItems(n),this.title=this.getTitle(r,n),this.beforeBody=this.getBeforeBody(r,n),this.body=this.getBody(r,n),this.afterBody=this.getAfterBody(r,n),this.footer=this.getFooter(r,n);let l=this._size=Za(this,n),c=Object.assign({},a,l),d=Ja(this.chart,n,c),h=tl(n,c,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,o={opacity:1,x:h.x,y:h.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&&n.external&&n.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,n,i){let o=this.getCaretPosition(t,n,i);e.lineTo(o.x1,o.y1),e.lineTo(o.x2,o.y2),e.lineTo(o.x3,o.y3)}getCaretPosition(t,e,n){let{xAlign:i,yAlign:o}=this,{caretSize:r,cornerRadius:a}=n,{topLeft:l,topRight:c,bottomLeft:d,bottomRight:h}=_e(a),{x:u,y:f}=t,{width:p,height:g}=e,m,b,x,C,E,S;return o==="center"?(E=f+g/2,i==="left"?(m=u,b=m-r,C=E+r,S=E-r):(m=u+p,b=m+r,C=E-r,S=E+r),x=m):(i==="left"?b=u+Math.max(l,d)+r:i==="right"?b=u+p-Math.max(c,h)-r:b=this.caretX,o==="top"?(C=f,E=C-r,m=b-r,x=b+r):(C=f+g,E=C+r,m=b+r,x=b-r),S=C),{x1:m,x2:b,x3:x,y1:C,y2:E,y3:S}}drawTitle(t,e,n){let i=this.title,o=i.length,r,a,l;if(o){let c=Fe(n.rtl,this.x,this.width);for(t.x=Un(this,n.titleAlign,n),e.textAlign=c.textAlign(n.titleAlign),e.textBaseline="middle",r=bt(n.titleFont),a=n.titleSpacing,e.fillStyle=n.titleColor,e.font=r.string,l=0;lx!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,us(t,{x:g,y:p,w:c,h:l,radius:b}),t.fill(),t.stroke(),t.fillStyle=r.backgroundColor,t.beginPath(),us(t,{x:m,y:p+1,w:c-2,h:l-2,radius:b}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(g,p,c,l),t.strokeRect(g,p,c,l),t.fillStyle=r.backgroundColor,t.fillRect(m,p+1,c-2,l-2))}t.fillStyle=this.labelTextColors[n]}drawBody(t,e,n){let{body:i}=this,{bodySpacing:o,bodyAlign:r,displayColors:a,boxHeight:l,boxWidth:c,boxPadding:d}=n,h=bt(n.bodyFont),u=h.lineHeight,f=0,p=Fe(n.rtl,this.x,this.width),g=function(_){e.fillText(_,p.x(t.x+f),t.y+u/2),t.y+=u+o},m=p.textAlign(r),b,x,C,E,S,y,v;for(e.textAlign=r,e.textBaseline="middle",e.font=h.string,t.x=Un(this,m,n),e.fillStyle=n.bodyColor,rt(this.beforeBody,g),f=a&&m!=="right"?r==="center"?c/2+d:c+2+d:0,E=0,y=i.length;E0&&e.stroke()}_updateAnimationTarget(t){let e=this.chart,n=this.$animations,i=n&&n.x,o=n&&n.y;if(i||o){let r=Xs[t.position].call(this,this._active,this._eventPosition);if(!r)return;let a=this._size=Za(this,t),l=Object.assign({},r,this._size),c=Ja(e,t,l),d=tl(t,l,c,e);(i._to!==d.x||o._to!==d.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=a.width,this.height=a.height,this.caretX=r.x,this.caretY=r.y,this._resolveAnimations().update(this,d))}}_willRender(){return!!this.opacity}draw(t){let e=this.options.setContext(this.getContext()),n=this.opacity;if(!n)return;this._updateAnimationTarget(e);let i={width:this.width,height:this.height},o={x:this.x,y:this.y};n=Math.abs(n)<.001?0:n;let r=_t(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=n,this.drawBackground(o,t,i,e),so(t,e.textDirection),o.y+=r.top,this.drawTitle(o,t,e),this.drawBody(o,t,e),this.drawFooter(o,t,e),no(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){let n=this._active,i=t.map(({datasetIndex:a,index:l})=>{let c=this.chart.getDatasetMeta(a);if(!c)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:c.data[l],index:l}}),o=!Hs(n,i),r=this._positionChanged(i,e);(o||r)&&(this._active=i,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,n=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;let i=this.options,o=this._active||[],r=this._getActiveElements(t,o,e,n),a=this._positionChanged(r,t),l=e||!Hs(r,o)||a;return l&&(this._active=r,(i.enabled||i.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),l}_getActiveElements(t,e,n,i){let o=this.options;if(t.type==="mouseout")return[];if(!i)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,n);return o.reverse&&r.reverse(),r}_positionChanged(t,e){let{caretX:n,caretY:i,options:o}=this,r=Xs[o.position].call(this,t,e);return r!==!1&&(n!==r.x||i!==r.y)}};U(Qs,"positioners",Xs);Wl={id:"tooltip",_element:Qs,positioners:Xs,afterInit(s,t,e){e&&(s.tooltip=new Qs({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:zl},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:Rl,Decimation:Fl,Filler:Vl,Legend:Bl,SubTitle:Hl,Title:$l,Tooltip:Wl}),Yf=(s,t,e,n)=>(typeof t=="string"?(e=s.push(t)-1,n.unshift({index:e,label:t})):isNaN(t)&&(e=null),e);qf=(s,t)=>s===null?null:vt(Math.round(s),0,t);bs=class extends Te{constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){let e=this._addedLabels;if(e.length){let n=this.getLabels();for(let{index:i,label:o}of e)n[i]===o&&n.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(tt(t))return null;let n=this.getLabels();return e=isFinite(e)&&n[e]===t?e:Gf(n,t,J(e,t),this._addedLabels),qf(e,n.length-1)}determineDataLimits(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),{min:n,max:i}=this.getMinMax(!0);this.options.bounds==="ticks"&&(t||(n=0),e||(i=this.getLabels().length-1)),this.min=n,this.max=i}buildTicks(){let t=this.min,e=this.max,n=this.options.offset,i=[],o=this.getLabels();o=t===0&&e===o.length-1?o:o.slice(t,e+1),this._valueRange=Math.max(o.length-(n?0:1),1),this._startValue=this.min-(n?.5:0);for(let r=t;r<=e;r++)i.push({value:r});return i}getLabelForValue(t){return nl.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}};U(bs,"id","category"),U(bs,"defaults",{ticks:{callback:nl}});Cs=class extends Te{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 tt(t)||(typeof t=="number"||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){let{beginAtZero:t}=this.options,{minDefined:e,maxDefined:n}=this.getUserBounds(),{min:i,max:o}=this,r=l=>i=e?i:l,a=l=>o=n?o:l;if(t){let l=Ut(i),c=Ut(o);l<0&&c<0?a(0):l>0&&c>0&&r(0)}if(i===o){let l=o===0?1:Math.abs(o*.05);a(o+l),t||r(i-l)}this.min=i,this.max=o}getTickLimit(){let t=this.options.ticks,{maxTicksLimit:e,stepSize:n}=t,i;return n?(i=Math.ceil(this.max/n)-Math.floor(this.min/n)+1,i>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${n} would result generating up to ${i} ticks. Limiting to 1000.`),i=1e3)):(i=this.computeTickLimit(),e=e||11),e&&(i=Math.min(e,i)),i}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){let t=this.options,e=t.ticks,n=this.getTickLimit();n=Math.max(2,n);let i={maxTicks:n,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=Xf(i,o);return t.bounds==="ticks"&&Ii(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,n=this.max;if(super.configure(),this.options.offset&&t.length){let i=(n-e)/Math.max(t.length-1,1)/2;e-=i,n+=i}this._startValue=e,this._endValue=n,this._valueRange=n-e}getLabelForValue(t){return ds(t,this.chart.options.locale,this.options.ticks.format)}},vs=class extends Cs{determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=pt(t)?t:0,this.max=pt(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){let t=this.isHorizontal(),e=t?this.width:this.height,n=zt(this.options.ticks.minRotation),i=(t?Math.sin(n):Math.cos(n))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,o.lineHeight/i))}getPixelForValue(t){return t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}};U(vs,"id","linear"),U(vs,"defaults",{ticks:{callback:hs.formatters.numeric}});sn=s=>Math.floor(le(s)),Ve=(s,t)=>Math.pow(10,sn(s)+t);ys=class extends Te{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){let n=Cs.prototype.parse.apply(this,[t,e]);if(n===0){this._zero=!0;return}return pt(n)&&n>0?n:null}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=pt(t)?Math.max(0,t):null,this.max=pt(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!pt(this._userMin)&&(this.min=t===Ve(this.min,0)?Ve(this.min,-1):Ve(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),n=this.min,i=this.max,o=a=>n=t?n:a,r=a=>i=e?i:a;n===i&&(n<=0?(o(1),r(10)):(o(Ve(n,-1)),r(Ve(i,1)))),n<=0&&o(Ve(i,-1)),i<=0&&r(Ve(n,1)),this.min=n,this.max=i}buildTicks(){let t=this.options,e={min:this._userMin,max:this._userMax},n=Zf(e,this);return t.bounds==="ticks"&&Ii(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}getLabelForValue(t){return t===void 0?"0":ds(t,this.chart.options.locale,this.options.ticks.format)}configure(){let t=this.min;super.configure(),this._startValue=le(t),this._valueRange=le(this.max)-le(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(le(t)-this._startValue)/this._valueRange)}getValueForPixel(t){let e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}};U(ys,"id","logarithmic"),U(ys,"defaults",{ticks:{callback:hs.formatters.logarithmic,major:{enabled:!0}}});ke=class extends Cs{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=_t(To(this.options)/2),e=this.width=this.maxWidth-t.width,n=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+n/2+t.top),this.drawingArea=Math.floor(Math.min(e,n)/2)}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!1);this.min=pt(t)&&!isNaN(t)?t:0,this.max=pt(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/To(this.options))}generateTickLabels(t){Cs.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((e,n)=>{let i=ct(this.options.pointLabels.callback,[e,n],this);return i||i===0?i:""}).filter((e,n)=>this.chart.getDataVisibility(n))}fit(){let t=this.options;t.display&&t.pointLabels.display?tp(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,n,i){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((n-i)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,n,i))}getIndexAngle(t){let e=ht/(this._pointLabels.length||1),n=this.options.startAngle||0;return xt(t*e+zt(n))}getDistanceFromCenterForValue(t){if(tt(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(tt(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(h!==0||h===0&&this.min<0){l=this.getDistanceFromCenterForValue(d.value);let u=this.getContext(h),f=i.setContext(u),p=o.setContext(u);dp(this,f,l,r,p)}}),n.display){for(t.save(),a=r-1;a>=0;a--){let d=n.setContext(this.getPointLabelContext(a)),{color:h,lineWidth:u}=d;!u||!h||(t.lineWidth=u,t.strokeStyle=h,t.setLineDash(d.borderDash),t.lineDashOffset=d.borderDashOffset,l=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),c=this.getPointPosition(a,l),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(c.x,c.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){let t=this.ctx,e=this.options,n=e.ticks;if(!n.display)return;let i=this.getIndexAngle(0),o,r;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(i),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach((a,l)=>{if(l===0&&this.min>=0&&!e.reverse)return;let c=n.setContext(this.getContext(l)),d=bt(c.font);if(o=this.getDistanceFromCenterForValue(this.ticks[l].value),c.showLabelBackdrop){t.font=d.string,r=t.measureText(a.label).width,t.fillStyle=c.backdropColor;let h=_t(c.backdropPadding);t.fillRect(-r/2-h.left,-o-d.size/2-h.top,r+h.width,d.size+h.height)}Ce(t,a.label,0,-o,d,{color:c.color,strokeColor:c.textStrokeColor,strokeWidth:c.textStrokeWidth})}),t.restore()}drawTitle(){}};U(ke,"id","radialLinear"),U(ke,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:hs.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),U(ke,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),U(ke,"descriptors",{angleLines:{_fallback:"grid"}});ni={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}},Pt=Object.keys(ni);Me=class extends Te{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 n=t.time||(t.time={}),i=this._adapter=new ml._date(t.adapters.date);i.init(e),rs(n.displayFormats,i.formats()),this._parseOpts={parser:n.parser,round:n.round,isoWeekday:n.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return t===void 0?null:cl(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){let t=this.options,e=this._adapter,n=t.time.unit||"day",{min:i,max:o,minDefined:r,maxDefined:a}=this.getUserBounds();function l(c){!r&&!isNaN(c.min)&&(i=Math.min(i,c.min)),!a&&!isNaN(c.max)&&(o=Math.max(o,c.max))}(!r||!a)&&(l(this._getLabelBounds()),(t.bounds!=="ticks"||t.ticks.source!=="labels")&&l(this.getMinMax(!1))),i=pt(i)&&!isNaN(i)?i:+e.startOf(Date.now(),n),o=pt(o)&&!isNaN(o)?o:+e.endOf(Date.now(),n)+1,this.min=Math.min(i,o-1),this.max=Math.max(i+1,o)}_getLabelBounds(){let t=this.getLabelTimestamps(),e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],n=t[t.length-1]),{min:e,max:n}}buildTicks(){let t=this.options,e=t.time,n=t.ticks,i=n.source==="labels"?this.getLabelTimestamps():this._generate();t.bounds==="ticks"&&i.length&&(this.min=this._userMin||i[0],this.max=this._userMax||i[i.length-1]);let o=this.min,r=this.max,a=Kr(i,o,r);return this._unit=e.unit||(n.autoSkip?dl(e.minUnit,this.min,this.max,this._getLabelCapacity(o)):up(this,a.length,e.minUnit,this.min,this.max)),this._majorUnit=!n.major.enabled||this._unit==="year"?void 0:fp(this._unit),this.initOffsets(i),t.reverse&&a.reverse(),ul(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(t=>+t.value))}initOffsets(t=[]){let e=0,n=0,i,o;this.options.offset&&t.length&&(i=this.getDecimalForValue(t[0]),t.length===1?e=1-i:e=(this.getDecimalForValue(t[1])-i)/2,o=this.getDecimalForValue(t[t.length-1]),t.length===1?n=o:n=(o-this.getDecimalForValue(t[t.length-2]))/2);let r=t.length<3?.5:.25;e=vt(e,0,r),n=vt(n,0,r),this._offsets={start:e,end:n,factor:1/(e+1+n)}}_generate(){let t=this._adapter,e=this.min,n=this.max,i=this.options,o=i.time,r=o.unit||dl(o.minUnit,e,n,this._getLabelCapacity(e)),a=J(i.ticks.stepSize,1),l=r==="week"?o.isoWeekday:!1,c=Oe(l)||l===!0,d={},h=e,u,f;if(c&&(h=+t.startOf(h,"isoWeek",l)),h=+t.startOf(h,c?"day":r),t.diff(n,e,r)>1e5*a)throw new Error(e+" and "+n+" are too far apart with stepSize of "+a+" "+r);let p=i.ticks.source==="data"&&this.getDataTimestamps();for(u=h,f=0;u+g)}getLabelForValue(t){let e=this._adapter,n=this.options.time;return n.tooltipFormat?e.format(t,n.tooltipFormat):e.format(t,n.displayFormats.datetime)}format(t,e){let i=this.options.time.displayFormats,o=this._unit,r=e||i[o];return this._adapter.format(t,r)}_tickFormatFunction(t,e,n,i){let o=this.options,r=o.ticks.callback;if(r)return ct(r,[t,e,n],this);let a=o.time.displayFormats,l=this._unit,c=this._majorUnit,d=l&&a[l],h=c&&a[c],u=n[e],f=c&&h&&u&&u.major;return this._adapter.format(t,i||(f?h:d))}generateTickLabels(t){let e,n,i;for(e=0,n=t.length;e0?a:1}getDataTimestamps(){let t=this._cache.data||[],e,n;if(t.length)return t;let i=this.getMatchingVisibleMetas();if(this._normalized&&i.length)return this._cache.data=i[0].controller.getAllParsedValues(this);for(e=0,n=i.length;e=e&&c<=n&&i.push(c);if(i.length<2)return[{time:e,pos:0},{time:n,pos:1}];for(r=0,a=i.length;ri-o)}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;let e=this.getDataTimestamps(),n=this.getLabelTimestamps();return e.length&&n.length?t=this.normalize(e.concat(n)):t=e.length?e:n,t=this._cache.all=t,t}getDecimalForValue(t){return(Kn(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){let e=this._offsets,n=this.getDecimalForPixel(t)/e.factor-e.end;return Kn(this._table,n*this._tableRange+this._minPos,!0)}};U(xs,"id","timeseries"),U(xs,"defaults",Me.defaults);Kl=Object.freeze({__proto__:null,CategoryScale:bs,LinearScale:vs,LogarithmicScale:ys,RadialLinearScale:ke,TimeScale:Me,TimeSeriesScale:xs}),gp=[gl,Ll,jl,Kl]});var Pp={};zo(Pp,{CardView:()=>Es,default:()=>hi});module.exports=Sc(Pp);var it=require("obsidian"),gc=an(Ds());var Ec=["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"],kc=[{label:"\u{1F1EA}\u{1F1FA} Schengen 90/180 (example)",scope:{countries:Ec},window:{type:"rolling",days:180},threshold:90,note:"Example rule \u2014 add your own in Settings \u2192 CSV Card View."}],mi={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:kc,showResidency:!0},ln="xlsx-card-view";var jo=an(Ds()),Uo=require("obsidian"),Ke=["Image","image","Cover","cover","Poster","poster","Thumbnail","thumbnail","Thumb","thumb","Photo","photo","Picture","picture","Img","img"],Ye=["Title","title","Name","name"],Ge=["Category","category","Categories","categories","Genre","genre","Genres","genres","Type","type","Types","types","Tag","tag","Tags","tags","Topic","topic","Topics","topics","Subject","subject","Section","section"],qe=["Status","status","State","state","Progress","progress","Stage","stage","Read","read","Watched","watched","Seen","seen","Done","done","Completed","completed"],Xe=["Notes","notes","Note","note","Summary","summary","Review","review","Quote","quote","Quotes","quotes","Comment","comment","Comments","comments","Description","description","Annotation","annotation"];function cn(s,t,e){let n=(t!=null?t:"").trim();if(!n)return null;if(/^(https?:|data:)/i.test(n))return n;let i=n.match(/!?\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/);if(i)n=i[1].trim();else{let r=n.match(/!\[[^\]]*\]\(([^)]+)\)/);r&&(n=r[1].trim())}if(/^(https?:|data:)/i.test(n))return n;let o=s.metadataCache.getFirstLinkpathDest(n,e);return o instanceof Uo.TFile?s.vault.getResourcePath(o):null}var wc=15;function Xt(s){return s>=1&&s<=wc}var Dc=["0","1","true","false","yes","no",""];function Qe(s){return s.length>0&&s.every(t=>Dc.includes(t))}function Ze(s){let t=(s!=null?s:"").toLowerCase().trim();return t==="1"||t==="true"||t==="yes"}function Ms(s){return s.replace(/[\\/:*?"<>|#^[\]]/g,"").replace(/\s+/g," ").trim().slice(0,100)}function Ko(s){return s.toLowerCase().replace(/[^\p{L}\p{N}/_-]+/gu,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Nt(s){var i,o;if(!s||!s.trim())return{headers:[],rows:[]};let t=jo.default.parse(s,{header:!0,skipEmptyLines:!0}),e=((i=t.meta.fields)!=null?i:[]).map(String),n=((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:n}}function ue(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 n=t?t.split("/").filter(Boolean):[];for(let i of s.split("/"))if(!(i===""||i===".")){if(i===".."){n.pop();continue}n.push(i)}return n.join("/")}function Yo(s,t,e){let n=e==="asc"?1:-1;return[...s].sort((i,o)=>{var u,f;let r=((u=i[t])!=null?u:"").trim(),a=((f=o[t])!=null?f:"").trim();if(!r&&!a)return 0;if(!r)return 1;if(!a)return-1;let l=parseFloat(r),c=parseFloat(a);return(!isNaN(l)&&!isNaN(c)&&/^-?[\d.]/.test(r)&&/^-?[\d.]/.test(a)?l-c:r.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"}))*n})}function Mt(s){return s.split(/[\s_-]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function Go(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 i=Mc(e,t);return i&&i!==e&&i!=="\u2014"?i:""}function Mc(s,t){var o;let e=t.toLowerCase();if(!["rating","score","score /5"].includes(e))return s;let n=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"}[n])!=null?o:s}function qo(s,t){if(/^(year|released|decade)$/i.test((s!=null?s:"").trim()))return!0;let e=t.map(i=>(i!=null?i:"").trim()).filter(Boolean);return e.length<3?!1:e.filter(i=>/^(1[89]|20)\d{2}$/.test(i)).length/e.length>=.8}function Xo(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 Qo(s,t,e){var r;if(!t.length)return null;let n=Math.max(12,t.length/3),i=null,o=1/0;for(let a of s){if(e.has(a))continue;let l=new Set;for(let d of t)((r=d[a])!=null?r:"").split(",").forEach(h=>{let u=h.trim();u&&l.add(u)});if(l.size<2||l.size>n)continue;let c=Math.abs(Math.log(l.size/8));ck.remove());let r=document.body.createDiv({cls:"csv-select-picker"});r.style.position="fixed",r.style.zIndex="9999";let a=()=>{let k=s.getBoundingClientRect(),M=r.offsetHeight||280,L=k.bottom+4+M>window.innerHeight&&k.top-4-M>0;r.style.left=k.left+"px",r.style.top=L?k.top-4-M+"px":k.bottom+4+"px"};a();let l=k=>{!r.contains(k.target)&&k.target!==s&&d()},c=k=>{r.contains(k.target)||d()},d=()=>{r.remove(),document.removeEventListener("mousedown",l),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",d)},h=r.createEl("input",{cls:"csv-picker-search",type:"text",placeholder:"Search or add\u2026"});h.focus();let u=r.createDiv({cls:"csv-picker-list"}),f=!!(o!=null&&o.multi),p=k=>k.split(",").map(M=>M.trim()).filter(Boolean),g=new Set(f?p(t):[]),m=()=>n([...g].join(", ")),b=f?Array.from(new Set(e.flatMap(p))):Array.from(new Set(e.filter(Boolean))),x=[],C=0,E=()=>{u.querySelectorAll(".csv-picker-item").forEach((k,M)=>{k.toggleClass("csv-picker-item--hover",M===C),M===C&&k.scrollIntoView({block:"nearest"})})},S=k=>{if(!f){n(k.isClear?"":k.value),d();return}k.isClear?g.clear():(g.has(k.value)?g.delete(k.value):g.add(k.value),k.isAdd&&!b.includes(k.value)&&b.push(k.value)),m(),k.isAdd?(h.value="",_("")):_(h.value)},y=k=>f?g.has(k):k===t,v=()=>f?g.size>0:!!t,_=k=>{u.empty(),x=[];let M=k?b.filter(L=>L.toLowerCase().includes(k.toLowerCase())):b;if(v()){x.push({value:"",isClear:!0});let L=u.createDiv({cls:"csv-picker-item csv-picker-clear"});L.setText(f?"\u2715 Clear all":"\u2715 Clear"),L.addEventListener("mousedown",I=>{I.preventDefault(),S({value:"",isClear:!0})})}if(M.forEach(L=>{x.push({value:L});let I=u.createDiv({cls:`csv-picker-item ${y(L)?"active":""}`});I.setText(f?`${g.has(L)?"\u2713 ":""}${L}`:L),I.addEventListener("mousedown",P=>{P.preventDefault(),S({value:L})})}),k&&!b.some(L=>L.toLowerCase()===k.toLowerCase())){x.push({value:k,isAdd:!0});let L=u.createDiv({cls:"csv-picker-item csv-picker-add"});L.setText(`+ Add "${k}"`),L.addEventListener("mousedown",I=>{I.preventDefault(),S({value:k,isAdd:!0})})}!M.length&&!k&&u.createDiv({cls:"csv-picker-empty",text:"No options yet. Type to add."}),C=Math.min(C,Math.max(x.length-1,0)),E()};f&&r.createEl("button",{cls:"csv-picker-done",text:"Done"}).addEventListener("mousedown",k=>{k.preventDefault(),d()}),_(""),a(),h.addEventListener("input",()=>{C=0,_(h.value),a()});let w=typeof window!="undefined"&&((T=window.matchMedia)==null?void 0:T.call(window,"(pointer: coarse)").matches);setTimeout(()=>{document.addEventListener("mousedown",l),w||(window.addEventListener("scroll",c,!0),window.addEventListener("resize",d))},0),h.addEventListener("keydown",k=>{if(k.key==="Escape"){d();return}if(k.key==="ArrowDown"){k.preventDefault(),x.length&&(C=(C+1)%x.length,E());return}if(k.key==="ArrowUp"){k.preventDefault(),x.length&&(C=(C-1+x.length)%x.length,E());return}if(k.key==="Enter")if(k.preventDefault(),x[C])S(x[C]);else{let M=h.value.trim();M&&(n(M),d())}})}function Zo(s,t,e){return!s[t]||t===e||(s[e]||(s[e]=s[t]),delete s[t]),s}var Tc={source:["confirmed","inferred","conflict"],resolved:["yes","no"]};function Jo(s){var t;return(t=Tc[s.trim().toLowerCase()])!=null?t:null}function Et(s){return/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(s.trim())}var dn=/^\d{4}-\d{2}-\d{2}$/;var It=require("obsidian");function fn(s,t,e,n,i=Et){let o=i(t)&&(e===""||dn.test(e.slice(0,10))),r=o?e.slice(0,10):e,a=s.createEl("input",{cls:n,type:o?"date":"text",value:r});o||(a.placeholder=t);let l=Jo(t);if(l){let c=`csv-dl-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-${Math.random().toString(36).slice(2,7)}`,d=s.createEl("datalist");d.id=c,l.forEach(h=>d.createEl("option",{value:h})),a.setAttr("list",c)}return a}var Je=class extends It.Modal{constructor(t,e,n,i,o,r,a={},l=()=>!1,c,d,h=Et){super(t),this.headers=e,this.isNotesCol=n,this.isSelectCol=i,this.getColumnValues=o,this.onSubmit=r,this.optionPresets=a,this.isBooleanCol=l,this.isCategoricalCol=c!=null?c:u=>this.isSelectCol(u)||Xt(this.getColumnValues(u).length),this.titleCol=d!=null?d:this.headers.find(u=>["title","name"].includes(u.toLowerCase())),this.isDateCol=h}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"}),n={};this.headers.forEach(d=>n[d]="");let i=this.titleCol,o=new Map;i&&this.getColumnValues(i).forEach(d=>{let h=d.trim().toLowerCase();h&&!o.has(h)&&o.set(h,d.trim())}),this.headers.forEach(d=>{var m;let h=e.createDiv({cls:"csv-modal-row"});h.createEl("label",{text:Mt(d),cls:"csv-modal-label"});let u=(m=this.optionPresets[d])!=null?m:[],f=d===i,p=kt(d),g=!f&&!this.isNotesCol(d)&&!p&&(u.length>0||this.isCategoricalCol(d));if(this.isBooleanCol(d)){n[d]="0";let b=h.createDiv({cls:"csv-toggle"});b.createDiv({cls:"csv-toggle-knob"}),b.addEventListener("click",()=>{let x=!b.hasClass("is-on");b.toggleClass("is-on",x),n[d]=x?"1":"0"})}else if(this.isNotesCol(d)){let b=h.createEl("textarea",{cls:"csv-modal-textarea",placeholder:"Markdown supported\u2026"});b.addEventListener("input",()=>{n[d]=b.value})}else if(g){let b="__custom__",x=[];[...u,...this.getColumnValues(d)].forEach(S=>{let y=(S!=null?S:"").trim();y&&!x.some(v=>v.toLowerCase()===y.toLowerCase())&&x.push(y)});let C=h.createEl("select",{cls:"csv-modal-select"});C.createEl("option",{text:"\u2014",value:""}),x.forEach(S=>C.createEl("option",{text:S,value:S})),C.createEl("option",{text:"+ Custom\u2026",value:b});let E=h.createEl("input",{cls:"csv-modal-input csv-modal-custom",type:"text",placeholder:`Custom ${Mt(d).toLowerCase()}`});E.hide(),E.addEventListener("input",()=>{n[d]=E.value}),E.addEventListener("keydown",S=>{S.key==="Enter"&&c()}),C.addEventListener("change",()=>{C.value===b?(E.show(),E.focus(),n[d]=E.value):(E.hide(),n[d]=C.value)})}else if(!f&&p&&this.isSelectCol(d)){let x=h.createDiv({cls:"csv-modal-select-wrap"}).createDiv({cls:"csv-select-chip empty"});x.setText("\u2014 click to select \u2014"),x.addEventListener("click",C=>{C.stopPropagation(),Ft(x,n[d],this.getColumnValues(d),E=>{n[d]=E,x.setText(E||"\u2014 click to select \u2014"),x.toggleClass("empty",!E)},t,{multi:kt(d)})})}else{let b=fn(h,d,"","csv-modal-input",x=>this.isDateCol(x));if(b.addEventListener("input",()=>{n[d]=b.value}),b.addEventListener("keydown",x=>{x.key==="Enter"&&c()}),d===i&&o.size){let x=h.createDiv({cls:"csv-modal-dup-hint"});x.hide(),b.addEventListener("input",()=>{let C=o.get(b.value.trim().toLowerCase());C?(x.setText(`\u26A0 \u201C${C}\u201D is already in this file`),x.show()):x.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",()=>c());let c=()=>{if(!Object.values(n).some(h=>h.trim())){new It.Notice("Fill in at least one field.");return}this.onSubmit(n),this.close()}}onClose(){this.contentEl.empty()}},ts=class extends It.Modal{constructor(e,n,i,o,r,a,l,c,d,h,u,f,p=()=>!1,g=Et){super(e);this.vvHandler=null;this.row={...n},this.notesCol=i,this.headers=o,this.filePath=r,this.renderComponent=new It.Component,this.isNotesCol=a,this.isSelectCol=l,this.getColumnValues=c,this.onSave=d,this.onDelete=h,this.isCategoricalCol=u!=null?u:m=>this.isSelectCol(m)||!Et(m)&&Xt(this.getColumnValues(m).length),this.titleCol=f!=null?f:this.headers.find(m=>["title","name","Title","Name"].includes(m)),this.isBooleanCol=p,this.isDateCol=g,this.modalEl.addClass("csv-note-expander-modal")}onOpen(){var p,g,m,b,x;this.renderComponent.load();let{contentEl:e}=this;e.empty(),e.addClass("csv-note-expander");let n=window.visualViewport;if(n){let C=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${n.height}px`)};C(),n.addEventListener("resize",C),n.addEventListener("scroll",C),this.vvHandler=C}let i=e.createDiv({cls:"csv-expander-header"});i.createDiv({cls:"csv-expander-title",text:(g=this.row[(p=this.titleCol)!=null?p:this.headers[0]])!=null?g:"\u2014"});let o=i.createDiv({cls:"csv-expander-header-btns"}),r=e.createDiv({cls:"csv-expander-fields"}),a=this.titleCol,l=this.headers.find(C=>["author","Author","director","Director","artist","Artist","creator","Creator"].includes(C));this.headers.forEach(C=>{var v;if(this.isNotesCol(C))return;let E=r.createDiv({cls:"csv-expander-field-row"});if(E.createDiv({cls:"csv-expander-field-label",text:Mt(C)}),this.isBooleanCol(C)){let _=Ze((v=this.row[C])!=null?v:""),w=E.createDiv({cls:`csv-toggle ${_?"is-on":""}`});w.createDiv({cls:"csv-toggle-knob"}),w.addEventListener("click",()=>{let T=!w.hasClass("is-on");w.toggleClass("is-on",T),this.row[C]=T?"1":"0"});return}let S=kt(C);if(C!==a&&(S?this.isSelectCol(C):this.isCategoricalCol(C))){let _=E.createDiv({cls:`csv-select-chip ${this.row[C]?"":"empty"}`});_.setText(this.row[C]||"\u2014"),_.addEventListener("click",w=>{w.stopPropagation(),Ft(_,this.row[C],this.getColumnValues(C),T=>{this.row[C]=T,_.setText(T||"\u2014"),_.toggleClass("empty",!T)},e,{multi:kt(C)})})}else{let _=E.createDiv({cls:"csv-expander-field-value",text:this.row[C]||"\u2014"});_.addEventListener("click",()=>{var k;if(_.querySelector("input"))return;_.empty();let w=fn(_,C,(k=this.row[C])!=null?k:"","csv-inline-input",this.isDateCol);w.focus(),w.type==="text"&&w.select(),w.addEventListener("click",M=>M.stopPropagation());let T=()=>{this.row[C]=w.value,_.empty(),_.setText(w.value||"\u2014")};w.addEventListener("blur",T),w.addEventListener("keydown",M=>{M.key==="Enter"&&w.blur(),M.key==="Escape"&&(_.empty(),_.setText(this.row[C]||"\u2014"))})})}});let c=!1,d=this.notesCol&&(m=this.row[this.notesCol])!=null?m:"",h=null;if(this.notesCol){e.createDiv({cls:"csv-expander-divider"}).createDiv({cls:"csv-expander-notes-label",text:this.notesCol});let E=e.createDiv({cls:"csv-expander-rendered markdown-rendered"});E.title="Click to edit";let S=e.createDiv({cls:"csv-expander-editor"});S.style.display="none";let y=()=>{E.empty(),d.trim()?It.MarkdownRenderer.render(this.app,d,E,this.filePath,this.renderComponent):E.createDiv({cls:"csv-notes-empty",text:"+ Add note"})};y(),h=S.createEl("textarea",{cls:"csv-expander-textarea"}),h.value=d,h.addEventListener("input",()=>{d=h.value});let v=()=>{c||(c=!0,E.style.display="none",S.style.display="flex",h.value=d,h.focus())},_=()=>{c&&(c=!1,S.style.display="none",E.style.display="",d=h.value,y())};E.addEventListener("click",w=>{if(w.target.closest("a, button, input, textarea, [contenteditable]"))return;let k=window.getSelection();k&&k.toString().length>0||v()}),h.addEventListener("keydown",w=>{w.key==="Escape"&&(w.preventDefault(),h.blur())}),h.addEventListener("blur",_)}let u=e.createDiv({cls:"csv-expander-footer"});if(this.onDelete){let C=String((x=this.row[(b=this.titleCol)!=null?b:this.headers[0]])!=null?x:"").trim();u.createEl("button",{cls:"csv-expander-delete-btn",text:"Delete"}).addEventListener("click",()=>{let E=C||"this entry";window.confirm(`Delete "${E}"? This can't be undone.`)&&(this.onDelete(),this.close())})}let f=u.createDiv({cls:"csv-expander-footer-right"});f.createEl("button",{cls:"csv-modal-cancel",text:"Cancel"}).addEventListener("click",()=>this.close()),f.createEl("button",{cls:"csv-expander-save-btn",text:"Save & close"}).addEventListener("click",()=>{this.notesCol&&(c&&h&&(d=h.value),this.row[this.notesCol]=d),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()}};var hn=class extends It.Modal{constructor(t,e,n,i,o,r,a,l,c,d,h,u,f,p=()=>0){super(t),this.headers=e,this.filePath=n,this.current={...i,habitColumns:i.habitColumns?[...i.habitColumns]:void 0,categoricalColumns:i.categoricalColumns?[...i.categoricalColumns]:void 0},this.autoDetectedHabits=o,this.autoDetectedCategorical=r,this.autoDetectedRoles=a,this.availableModes=l,this.onSave=c,this.getHeaders=d,this.getFileCfg=h,this.onAddColumn=u,this.onRemoveColumn=f,this.onCleanupBooleanColumn=p}onOpen(){var I,P,R;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"}),n=()=>{this.headers=this.getHeaders();let D=this.getFileCfg();this.current={...D,habitColumns:D.habitColumns?[...D.habitColumns]:void 0,categoricalColumns:D.categoricalColumns?[...D.categoricalColumns]:void 0},this.onOpen()},i=e.createDiv({cls:"csv-modal-row"});i.createEl("label",{text:"Columns",cls:"csv-modal-label"}),i.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"}],a=D=>{var $,A,z;let W=($=this.current.habitColumns)!=null?$:this.autoDetectedHabits,O=(A=this.current.categoricalColumns)!=null?A:this.autoDetectedCategorical,j=(z=this.current.dateColumns)!=null?z:this.headers.filter(G=>Et(G));return W.includes(D)?{type:"checkbox",auto:!this.current.habitColumns}:O.includes(D)?{type:"categorical",auto:!this.current.categoricalColumns}:j.includes(D)?{type:"date",auto:!this.current.dateColumns}:{type:"text",auto:!1}},l=(D,W)=>{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!==D),this.current.categoricalColumns=this.current.categoricalColumns.filter(O=>O!==D),this.current.dateColumns=this.current.dateColumns.filter(O=>O!==D),W==="checkbox"?this.current.habitColumns.push(D):W==="categorical"?this.current.categoricalColumns.push(D):W==="date"&&this.current.dateColumns.push(D)},c=(P=(I=this.current.titleColumn)!=null?I:this.autoDetectedRoles.title)!=null?P:this.headers[0],h=i.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),u=h.createEl("thead").createEl("tr");["Column","Type","Visibility"].forEach(D=>u.createEl("th",{text:D}));let f=h.createEl("tbody"),p=()=>{var W;f.empty();let D=new Set((W=this.current.cardFields)!=null?W:this.headers);this.headers.forEach(O=>{let j=f.createEl("tr"),$=j.createEl("td",{cls:"csv-modal-colcfg-name"});$.createSpan({text:O});let A=$.createEl("button",{cls:"csv-modal-column-remove",text:"\u2715",attr:{title:`Remove "${O}" \u2014 deletes this column's data from every row`}});A.addEventListener("click",()=>{if(A.hasClass("confirm")){this.onRemoveColumn(O),n();return}f.querySelectorAll(".csv-modal-column-remove.confirm").forEach(F=>{F.removeClass("confirm"),F.setText("\u2715")}),A.addClass("confirm"),A.setText("Confirm?"),window.setTimeout(()=>{A.isConnected&&(A.removeClass("confirm"),A.setText("\u2715"))},3e3)});let z=j.createEl("td",{cls:"csv-modal-colcfg-type-cell"});if(O===c)z.createSpan({cls:"csv-modal-colcfg-fixed",text:"Text"});else{let F=z.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-type"}),{type:N,auto:H}=a(O);if(o.forEach(V=>{let K=F.createEl("option",{text:V.label,value:V.value});V.value===N&&(K.selected=!0)}),H&&F.addClass("auto-detected"),F.addEventListener("change",()=>{l(O,F.value),p()}),H&&z.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"}),N==="checkbox"){let V=z.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)`}});V.addEventListener("click",()=>{if(V.hasClass("confirm")){let K=this.onCleanupBooleanColumn(O);new It.Notice(K>0?`"${O}": normalized ${K} row${K===1?"":"s"} to 1/0.`:`"${O}" is already strict 1/0 \u2014 nothing to change.`);return}f.querySelectorAll(".csv-modal-colcfg-cleanup-btn.confirm").forEach(K=>{K.removeClass("confirm"),K.setText("Clean up")}),V.addClass("confirm"),V.setText("Confirm?"),window.setTimeout(()=>{V.isConnected&&(V.removeClass("confirm"),V.setText("Clean up"))},3e3)})}}let B=j.createEl("td",{cls:"csv-modal-colcfg-card-cell"}).createEl("input",{type:"checkbox"});B.checked=D.has(O),B.addEventListener("change",()=>{this.current.cardFields||(this.current.cardFields=[...this.headers]),B.checked?this.current.cardFields.includes(O)||this.current.cardFields.push(O):this.current.cardFields=this.current.cardFields.filter(F=>F!==O)})})};p();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 b=g.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),x=b.createEl("thead").createEl("tr");["Function","Column"].forEach(D=>x.createEl("th",{text:D}));let C=b.createEl("tbody"),E=()=>{C.empty(),r.forEach(D=>{var G,B,F,N,H,V,K,Y,q,X,Z,at;if(D.value==="")return;let W=C.createEl("tr");W.createEl("td",{cls:"csv-modal-colcfg-name"}).setText(D.label);let j=W.createEl("td",{cls:"csv-modal-colcfg-type-cell"}),$=j.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-role"});$.createEl("option",{text:"\u2014 none \u2014",value:""});let A="",z=!1;D.value==="title"?(A=(B=(G=this.current.titleColumn)!=null?G:this.autoDetectedRoles.title)!=null?B:"",z=this.current.titleColumn===void 0&&!!this.autoDetectedRoles.title):D.value==="category"?(A=(N=(F=this.current.categoryColumn)!=null?F:this.autoDetectedRoles.category)!=null?N:"",z=this.current.categoryColumn===void 0&&!!this.autoDetectedRoles.category):D.value==="status"?(A=(V=(H=this.current.statusColumn)!=null?H:this.autoDetectedRoles.status)!=null?V:"",z=this.current.statusColumn===void 0&&!!this.autoDetectedRoles.status):D.value==="notes"?(A=(Y=(K=this.current.notesColumn)!=null?K:this.autoDetectedRoles.notes)!=null?Y:"",z=this.current.notesColumn===void 0&&!!this.autoDetectedRoles.notes):D.value==="image"?(A=(X=(q=this.current.imageColumn)!=null?q:this.autoDetectedRoles.image)!=null?X:"",z=this.current.imageColumn===void 0&&!!this.autoDetectedRoles.image):D.value==="anki"&&(A=(at=(Z=this.current.ankiFrontCol)!=null?Z:this.autoDetectedRoles.anki)!=null?at:"",z=this.current.ankiFrontCol===void 0&&!!this.autoDetectedRoles.anki),this.headers.forEach(Q=>{let st=$.createEl("option",{text:Q,value:Q});Q===A&&(st.selected=!0)}),z&&A!==""&&$.addClass("auto-detected"),$.addEventListener("change",()=>{let Q=$.value;D.value==="title"?this.current.titleColumn=Q:D.value==="category"?this.current.categoryColumn=Q:D.value==="status"?this.current.statusColumn=Q:D.value==="notes"?this.current.notesColumn=Q:D.value==="image"?this.current.imageColumn=Q:D.value==="anki"&&(this.current.ankiFrontCol=Q),E()}),z&&A!==""&&j.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"})})};E();let S=i.createDiv({cls:"csv-modal-add-column"}),y=S.createEl("input",{cls:"csv-modal-input",type:"text",placeholder:"New column name"}),v=S.createEl("button",{cls:"csv-modal-cancel",text:"+ Add column"}),_=()=>{let D=this.onAddColumn(y.value);if(D){new It.Notice(D);return}n()};v.addEventListener("click",_),y.addEventListener("keydown",D=>{D.key==="Enter"&&(D.preventDefault(),_())});let w=e.createDiv({cls:"csv-modal-row"});w.createEl("label",{text:"Default view",cls:"csv-modal-label"});let T=w.createEl("select",{cls:"csv-modal-select"}),k=[["\u2014 use global default \u2014",""],...this.availableModes.map(D=>[D.label,D.id])],M=(R=this.current.defaultMode)!=null?R:"";M&&!this.availableModes.some(D=>D.id===M)&&k.push([`${M} (no longer available)`,M]),k.forEach(([D,W])=>{let O=T.createEl("option",{text:D,value:W});M===W&&(O.selected=!0)}),T.addEventListener("change",()=>{this.current.defaultMode=T.value?T.value:void 0});let L=t.createDiv({cls:"csv-modal-btns"});L.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),L.createEl("button",{text:"Save",cls:"csv-modal-submit"}).addEventListener("click",()=>{this.onSave(this.current),this.close()})}onClose(){this.contentEl.empty()}},un=class extends It.Modal{constructor(e,n,i,o,r){super(e);this.title=n;this.initial=i;this.placeholder=o;this.onSubmit=r}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("csv-add-modal"),e.createEl("h2",{text:this.title,cls:"csv-modal-title"});let n=e.createEl("input",{cls:"csv-modal-field",type:"text"});n.value=this.initial,n.placeholder=this.placeholder,window.setTimeout(()=>{n.focus(),n.select()},0);let i=()=>{let r=n.value.trim();r&&(this.onSubmit(r),this.close())};n.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),i())});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:"Create",cls:"csv-modal-submit"}).addEventListener("click",i)}onClose(){this.contentEl.empty()}};var bi=195,Lc={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"},Ac={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"]},tr={AF:"Africa",AN:"Antarctica",AS:"Asia",EU:"Europe",NA:"N. America",OC:"Oceania",SA:"S. America"},er={};for(let[s,t]of Object.entries(Ac))for(let e of t)er[e]=s;function wt(s){return Lc[s]||s}function jt(s){return!s||s.length!==2?"":String.fromCodePoint(...s.toUpperCase().split("").map(t=>t.charCodeAt(0)+127397))}function Bt(s){if(!s||s.indexOf("?")!==-1)return null;let t=new Date(s+"T12:00:00Z");return isNaN(t.getTime())?null:t}function Ts(s){let t=Bt(s.date_entered),e=Bt(s.date_left);return!t||!e?0:Math.max(Math.round((e.getTime()-t.getTime())/864e5),1)}function sr(s,t=new Date){let e=t.getTime(),n=null,i=-1/0;for(let o of s){let r=Bt(o.date_entered);if(!(!r||r.getTime()>e)){if(o.date_left.trim()!==""){let a=Bt(o.date_left);if(!a||a.getTime()i&&(n=o,i=r.getTime())}}return n}function nr(s){let t=b=>{var x,C,E,S,y,v,_,w;return{date_entered:(x=b.date_entered)!=null?x:"",date_left:(C=b.date_left)!=null?C:"",country:((E=b.country)!=null?E:"").trim().toUpperCase(),city:(S=b.city)!=null?S:"",visa_status:(y=b.visa_status)!=null?y:"",notes:(v=b.notes)!=null?v:"",source:((_=b.source)!=null?_:"").trim().toLowerCase(),resolved:(w=b.resolved)!=null?w:"",_src:b}},e=s.map(t).filter(b=>b.country),n=e.filter(b=>b.source==="confirmed"),i=e.filter(b=>b.source==="inferred"),o=e.filter(b=>b.source==="conflict"),r=[];for(let b of n){let x=Bt(b.date_entered),C=Bt(b.date_left);x&&C&&r.push([x.getTime(),C.getTime()])}let a=b=>{let x=Bt(b.date_entered),C=Bt(b.date_left);if(!x||!C)return!1;let E=x.getTime(),S=C.getTime();return r.some(([y,v])=>E<=v&&S>=y)},l=i.filter(b=>Bt(b.date_entered)&&Bt(b.date_left)&&!a(b)),c=new Set(n.map(b=>b.country)),d=new Set(i.map(b=>b.country)),h=new Set([...d].filter(b=>!c.has(b))),u=new Set([...c,...d]),f=new Map;for(let b of n)f.set(b.country,(f.get(b.country)||0)+Ts(b));let p=[...f.entries()].map(([b,x])=>({iso:b,days:x})).sort((b,x)=>x.days-b.days||wt(b.iso).localeCompare(wt(x.iso))),g=p.reduce((b,x)=>b+x.days,0),m=new Set;for(let b of c){let x=er[b];x&&m.add(x)}return{confirmed:n,inferred:i,conflicts:o,inferredVisible:l,confRanges:r,confirmedCountries:c,inferredOnlyCountries:h,allCountries:u,countryDays:p,totalConfirmedDays:g,visitedContinents:m,worldPct:Math.round(c.size/bi*100)}}var vi=864e5;function ir(s){if(!s||s.indexOf("?")!==-1)return null;let t=Date.parse(s+"T00:00:00Z");return isNaN(t)?null:t}function Pc(s,t,e,n){let i=Math.max(s,e),o=Math.min(t,n);return o<=i?0:Math.round((o-i)/vi)}function Rc(s,t){var i;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 n=(i=e.days)!=null?i:180;return{start:t-n*vi,end:t+vi,label:`in last ${n} days`}}function or(s,t,e=Date.now()){var d,h,u;let n=(d=s.scope.countries)!=null?d:s.scope.country?[s.scope.country]:[],i=new Set(n.map(f=>f.toUpperCase())),o=new Set(((u=(h=s.exempt)==null?void 0:h.visa_status)!=null?u:[]).map(f=>f.toLowerCase().trim())),r=Rc(s,e),a=0;for(let f of t){if(!i.has((f.country||"").toUpperCase())||o.has((f.visa_status||"").toLowerCase().trim()))continue;let p=ir(f.date_entered),g=ir(f.date_left);p===null||g===null||(a+=Pc(p,g,r.start,r.end))}let l=s.threshold-a,c=a>=s.threshold?"over":a/s.threshold>=.8?"warn":"ok";return{rule:s,used:a,threshold:s.threshold,remaining:l,windowLabel:r.label,status:c}}var rr=["#c9a96e","#4a6fa5","#5ba06e","#a05b8a","#6ea0a0","#a0855b","#7a6ea0","#a06e6e","#6e8fa0","#a09e5b"],Oc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Fc(){let s=new Map,t=0;return e=>(s.has(e)||s.set(e,rr[t++%rr.length]),s.get(e))}function Ic(s){let t=document.body.createDiv({cls:"csv-tv-tooltip"}),e=null,n=(r,a)=>{let c=r+14,d=a+16,h=t.offsetWidth,u=t.offsetHeight;c+h+8>window.innerWidth&&(c=r-h-14),d+u+8>window.innerHeight&&(d=a-u-16),t.style.left=`${Math.max(8,c)}px`,t.style.top=`${Math.max(8,d)}px`},i=r=>{var c,d;let a=(d=(c=r.target)==null?void 0:c.closest("[data-tip]"))!=null?d: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")),n(r.clientX,r.clientY)},o=()=>{e=null,t.removeClass("is-on")};return s.addEventListener("pointermove",i),s.addEventListener("pointerleave",o),()=>{s.removeEventListener("pointermove",i),s.removeEventListener("pointerleave",o),t.remove()}}function yi(s){let t=Ts(s);return t?`${t}d`:"\u2014"}function es(s){return s||"\u2014"}function As(s){return s.createDiv({cls:"csv-tv-table-wrap"}).createEl("table",{cls:"csv-tv-table"})}function Ls(s,t,e,n){s.addClass("csv-tv-editable"),s.title="Click to edit";let i=()=>{s.empty(),s.setText(t[e]?t[e]:"\u2014")};i(),s.addEventListener("click",()=>{var r;if(s.querySelector("input"))return;s.empty();let o=fn(s,e,(r=t[e])!=null?r:"","csv-inline-input");o.focus(),o.type==="text"&&o.select(),o.addEventListener("blur",()=>{t[e]=o.value,n(),i()}),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 ar(s,t,e,n=()=>{},i=null,o=()=>{}){let r=nr(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(Ic(a));let l=null,c=()=>{a.querySelectorAll(".country-path").forEach(f=>{let p=(f.getAttribute("data-iso")||"").toUpperCase();f.classList.toggle("cp-selected",!!l&&p===l)}),a.querySelectorAll(".csv-tv-seg").forEach(f=>{f.classList.toggle("is-dim",!!l&&f.getAttribute("data-iso")!==l)}),a.querySelectorAll("tr[data-iso]").forEach(f=>{f.classList.toggle("is-selected",!!l&&f.getAttribute("data-iso")===l)}),u.empty(),l&&(Bc(u,r,l,()=>d(null)),u.scrollIntoView({behavior:"smooth",block:"nearest"}))},d=f=>{l=f&&f!==l?f:null,c()};Vc(a,r);let h=a.createDiv({cls:"csv-tv-mapwrap"});h.createDiv({cls:"csv-tv-map-loading",text:"Loading map\u2026"});let u=a.createDiv({cls:"csv-tv-detailwrap"});i&&i.length&&$c(a,r.confirmed,i),Hc(a,r,d),zc(a,r,d),Wc(a,r,n);try{let f=await e();h.empty(),f?Nc(h,f,r,d):h.createDiv({cls:"csv-tv-map-loading",text:"World map asset not found (world-map.svg)."})}catch(f){h.empty(),h.createDiv({cls:"csv-tv-map-loading",text:"Couldn't load world map."})}}function Vc(s,t){let e=s.createDiv({cls:"csv-tv-stats"}),n=(c,d,h="")=>{let u=e.createDiv({cls:"csv-tv-stat"});u.createDiv({cls:"csv-tv-stat-label",text:c}),u.createDiv({cls:"csv-tv-stat-value",text:d}),h&&u.createDiv({cls:"csv-tv-stat-sub",text:h})},i=Math.round(t.allCountries.size/bi*100);n("Countries",String(t.confirmedCountries.size),`${t.worldPct}% of world`),n("Incl. photos",String(t.allCountries.size),`${i}% of world`),n("Continents",`${t.visitedContinents.size} / 7`,[...t.visitedContinents].map(c=>tr[c]||c).sort().join(", ")),n("Confirmed trips",String(t.confirmed.length)),n("Confirmed days",String(t.totalConfirmedDays));let o=new Set(t.confirmed.map(c=>c.city.trim().toLowerCase()).filter(Boolean));o.size&&n("Cities",String(o.size));let r=null,a=0;for(let c of t.confirmed){let d=Ts(c);d>a&&(a=d,r=c)}if(r){let c=r.date_entered.slice(0,4);n("Longest trip",`${a}d`,`${jt(r.country)} ${wt(r.country)}${c?` \xB7 ${c}`:""}`)}let l=sr(t.confirmed);if(l){let c=Bt(l.date_entered),d=Math.max(1,Math.round((Date.now()-c.getTime())/864e5)+1),h=s.createDiv({cls:"csv-tv-now"});h.createSpan({cls:"csv-tv-now-loc",text:`\u{1F4CD} Currently in ${jt(l.country)} ${wt(l.country)}`}),h.createSpan({cls:"csv-tv-now-sub",text:` \u2014 since ${l.date_entered} (day ${d})${l.city?` \xB7 ${l.city}`:""}`})}}function Nc(s,t,e,n){let i=s.createDiv({cls:"csv-tv-map"});i.innerHTML=t,i.querySelectorAll(".country-path").forEach(r=>{let a=(r.getAttribute("data-iso")||"").toUpperCase();if(r.classList.remove("cp-unvisited","cp-confirmed","cp-inferred"),a&&e.confirmedCountries.has(a)){r.classList.add("cp-confirmed");let l=e.countryDays.find(c=>c.iso===a);r.setAttr("aria-label",`${wt(a)} \u2014 ${l&&l.days?l.days+"d confirmed":"confirmed"}`),r.setAttr("data-tip",`${wt(a)}${l&&l.days?" \xB7 "+l.days+"d":""} \xB7 click for trips`)}else a&&e.inferredOnlyCountries.has(a)?(r.classList.add("cp-inferred"),r.setAttr("aria-label",`${wt(a)} \u2014 photo evidence`),r.setAttr("data-tip",`${wt(a)} \xB7 photo evidence \xB7 click for trips`)):a?(r.classList.add("cp-unvisited"),r.setAttr("data-tip",wt(a))):r.classList.add("cp-unvisited");a&&r.addEventListener("click",()=>{e.allCountries.has(a)?n(a):n(null)})}),i.querySelectorAll(".country-path").forEach(r=>{try{let a=r.getBoundingClientRect();a.width&&a.height&&Math.max(a.width,a.height)<12&&r.classList.add("cp-tiny")}catch(a){}});let o=s.createDiv({cls:"csv-tv-map-legend"});o.createSpan({cls:"csv-tv-leg"}).innerHTML=' Confirmed',o.createSpan({cls:"csv-tv-leg"}).innerHTML=' Photo evidence'}function Bc(s,t,e,n){var m,b;let i=s.createDiv({cls:"csv-tv-detail"}),o=i.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(x=>x.country===e),l=t.inferred.filter(x=>x.country===e),c=(b=(m=t.countryDays.find(x=>x.iso===e))==null?void 0:m.days)!=null?b:0,d=new Set([...a,...l].map(x=>x.city.trim()).filter(Boolean)),h=[];a.length&&h.push(`${a.length} confirmed trip${a.length===1?"":"s"}`),c&&h.push(`${c}d total`),l.length&&h.push(`${l.length} photo-inferred`),d.size&&h.push(`${d.size} cit${d.size===1?"y":"ies"}`),r.createDiv({cls:"csv-tv-detail-sub",text:h.join(" \xB7 ")}),o.createEl("button",{cls:"csv-tv-detail-close",text:"\u2715",title:"Close"}).addEventListener("click",n);let u=pn([...a.map(x=>({r:x,inf:!1,date_entered:x.date_entered})),...l.map(x=>({r:x,inf:!0,date_entered:x.date_entered}))]);if(!u.length)return;let f=As(i),p=f.createEl("thead").createEl("tr");["","Entered","Left","Days","City","Visa"].forEach(x=>p.createEl("th",{text:x}));let g=f.createEl("tbody");for(let{r:x,inf:C}of u){let E=g.createEl("tr");E.createEl("td",{text:C?"\u{1F4F7}":"",cls:"csv-tv-flag",attr:C?{"data-tip":"Photo-inferred"}:{}}),E.createEl("td",{text:es(x.date_entered)}),E.createEl("td",{text:es(x.date_left)}),E.createEl("td",{text:yi(x)}),E.createEl("td",{text:x.city}),E.createEl("td",{text:x.visa_status})}}function $c(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Residency counters"});let n=s.createDiv({cls:"csv-tv-res-grid"});for(let i of e){let o=or(i,t),r=n.createDiv({cls:`csv-tv-res-card csv-tv-res-${o.status}`});r.createDiv({cls:"csv-tv-res-label",text:i.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 c=o.status==="over"?i.onExceed?`Over \u2014 ${i.onExceed}`:"Limit reached":`${o.remaining} day${o.remaining===1?"":"s"} left`;r.createDiv({cls:"csv-tv-res-status",text:c}),i.note&&r.createDiv({cls:"csv-tv-res-note",text:i.note})}s.createDiv({cls:"csv-tv-res-disclaimer",text:"Indicators only \u2014 not legal or tax advice. Based on confirmed trips."})}function Hc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Countries visited"});let n=As(s),i=n.createEl("thead").createEl("tr");["","Country","Total days"].forEach(r=>i.createEl("th",{text:r}));let o=n.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 zc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Timeline"});let n=Fc(),i=[...t.confirmed.map(c=>({...c,_inf:!1})),...t.inferredVisible.map(c=>({...c,_inf:!0}))].filter(c=>c.date_entered&&c.date_left&&c.date_entered.indexOf("?")===-1),o=new Map;for(let c of i){let d=parseInt(c.date_entered.slice(0,4)),h=parseInt(c.date_left.slice(0,4));if(!(isNaN(d)||isNaN(h)))for(let u=d;u<=h;u++)o.has(u)||o.set(u,[]),o.get(u).push(c)}let r=[...o.keys()].sort((c,d)=>d-c),a=s.createDiv({cls:"csv-tv-timeline"});for(let c of r){let d=new Date(`${c}-01-01T12:00:00Z`).getTime(),h=new Date(`${c}-12-31T12:00:00Z`).getTime(),u=h-d,f=a.createDiv({cls:"csv-tv-tl-year"}),p=0,g=new Set;for(let C of o.get(c)){if(g.add(C.country),C._inf)continue;let E=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),d),S=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),h);E<=S&&(p+=Math.max(Math.round((S-E)/864e5)+1,1))}let m=f.createDiv({cls:"csv-tv-tl-label"});m.createSpan({text:String(c)}),m.createSpan({cls:"csv-tv-tl-sub",text:`${p?`${p}d \xB7 `:""}${g.size} ${g.size===1?"country":"countries"}`});let b=f.createDiv({cls:"csv-tv-month-row"});Oc.forEach(C=>b.createDiv({cls:"csv-tv-month-tick",text:C}));let x=f.createDiv({cls:"csv-tv-track"});for(let C of o.get(c)){let E=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),d),S=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),h);if(E>S)continue;let y=(E-d)/u*100,v=Math.max((S-E+864e5)/u*100,.5),_=n(C.country),w=x.createDiv({cls:`csv-tv-seg${C._inf?" csv-tv-seg-inf":""}`});w.style.left=`${y}%`,w.style.width=`${v}%`,C._inf?(w.style.borderColor=_,w.style.background=_+"22",w.style.color=_):w.style.background=_,w.setAttr("data-iso",C.country),w.setAttr("data-tip",`${wt(C.country)} ${C.date_entered} \u2192 ${C.date_left} (${Ts(C)}d)${C.visa_status?" ["+C.visa_status+"]":""}${C._inf?" [photo]":""}`),w.addEventListener("click",()=>e(C.country)),v>4?w.createSpan({cls:"csv-tv-seg-lbl",text:`${jt(C.country)} ${C.country}`}):v>2&&w.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 pn(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 Wc(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 n=As(s),i=n.createEl("thead").createEl("tr");["","Country","Entered","Left","Duration","City","Visa","Notes"].forEach(r=>i.createEl("th",{text:r}));let o=n.createEl("tbody");for(let r of pn(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)}),Ls(a.createEl("td"),r._src,"date_entered",e),Ls(a.createEl("td"),r._src,"date_left",e),a.createEl("td",{text:yi(r)}),Ls(a.createEl("td"),r._src,"city",e),Ls(a.createEl("td"),r._src,"visa_status",e),Ls(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=As(r),l=a.createEl("thead").createEl("tr");["","Country","Entered","Left","Days","City"].forEach(d=>l.createEl("th",{text:d}));let c=a.createEl("tbody");for(let d of pn(t.inferred)){let h=c.createEl("tr");h.createEl("td",{text:jt(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:wt(d.country)}),h.createEl("td",{text:es(d.date_entered)}),h.createEl("td",{text:es(d.date_left)}),h.createEl("td",{text:yi(d)}),h.createEl("td",{text:d.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=As(r),l=a.createEl("thead").createEl("tr");["","Country (photos)","Dates","Detail"].forEach(d=>l.createEl("th",{text:d}));let c=a.createEl("tbody");for(let d of pn(t.conflicts)){let h=c.createEl("tr");h.createEl("td",{text:jt(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:d.country}),h.createEl("td",{text:`${es(d.date_entered)} \u2192 ${es(d.date_left)}`}),h.createEl("td",{text:d.notes})}}}var Vt=require("obsidian"),gn=class extends Vt.PluginSettingTab{constructor(t,e){super(t,e),this.plugin=e}display(){let{containerEl:t}=this;t.empty(),t.createEl("h2",{text:"XLSX Card View"}),new Vt.Setting(t).setName("Default view mode").addDropdown(n=>n.addOption("kanban-genre","Kanban").addOption("table","Table").setValue(this.plugin.settings.defaultMode).onChange(async i=>{this.plugin.settings.defaultMode=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Status column name").addText(n=>n.setValue(this.plugin.settings.statusColumn).onChange(async i=>{this.plugin.settings.statusColumn=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Category/Genre column name").addText(n=>n.setValue(this.plugin.settings.categoryColumn).onChange(async i=>{this.plugin.settings.categoryColumn=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Notes column names").setDesc("Comma-separated.").addText(n=>n.setValue(this.plugin.settings.notesColumns.join(", ")).onChange(async i=>{this.plugin.settings.notesColumns=i.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Select/dropdown columns").setDesc("Comma-separated column names that use a dropdown picker.").addText(n=>n.setValue(this.plugin.settings.selectColumns.join(", ")).onChange(async i=>{this.plugin.settings.selectColumns=i.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Notes subfolder").addText(n=>n.setPlaceholder("Notes").setValue(this.plugin.settings.notesSubfolder).onChange(async i=>{this.plugin.settings.notesSubfolder=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Reset column widths").addButton(n=>n.setButtonText("Reset").onClick(async()=>{this.plugin.settings.columnWidths={},await this.plugin.saveSettings(),new Vt.Notice("Column widths reset.")})),new Vt.Setting(t).setName("Residency counters (travel view)").setDesc("Show residency / tax day-gauges in the travel view.").addToggle(n=>n.setValue(this.plugin.settings.showResidency!==!1).onChange(async i=>{this.plugin.settings.showResidency=i,await this.plugin.saveSettings()})),t.createEl("h3",{text:"Residency rules"}),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=[],n=()=>void this.plugin.saveSettings();e.forEach((r,a)=>{var b,x,C,E,S,y;let l=t.createDiv({cls:"csv-rr-card"}),c=l.createDiv({cls:"csv-rr-head"}),d=c.createEl("input",{cls:"csv-rr-label",type:"text",value:r.label});d.placeholder="Label (e.g. \u{1F1EA}\u{1F1FA} Schengen 90/180)",d.addEventListener("input",()=>{r.label=d.value,n()});let h=c.createEl("button",{cls:"csv-rr-del",text:"\u2715"});h.setAttr("aria-label","Remove rule"),h.addEventListener("click",async()=>{e.splice(a,1),await this.plugin.saveSettings(),this.renderResidencyRules(t)});let u=l.createDiv({cls:"csv-rr-grid"}),f=(v,_,w,T="")=>{let k=u.createDiv({cls:"csv-rr-field"});k.createEl("label",{text:v});let M=k.createEl("input",{type:"text",value:_});T&&(M.placeholder=T),M.addEventListener("input",()=>{w(M.value),n()})},p=(b=r.scope.countries)!=null?b:r.scope.country?[r.scope.country]:[];f("Countries (ISO-2, comma)",p.join(", "),v=>{r.scope={countries:v.split(",").map(_=>_.trim().toUpperCase()).filter(Boolean)}},"US, GB");let g=u.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,_])=>{let w=m.createEl("option",{text:_,value:v});r.window.type===v&&(w.selected=!0)}),m.addEventListener("change",()=>{r.window={type:m.value,days:r.window.days},n(),this.renderResidencyRules(t)}),r.window.type==="rolling"&&f("Rolling days",String((x=r.window.days)!=null?x:180),v=>{let _=parseInt(v,10);r.window.days=isNaN(_)?void 0:_},"180"),f("Threshold (days)",String(r.threshold),v=>{let _=parseInt(v,10);r.threshold=isNaN(_)?0:_},"183"),f("Exempt visas (comma)",((E=(C=r.exempt)==null?void 0:C.visa_status)!=null?E:[]).join(", "),v=>{let _=v.split(",").map(w=>w.trim()).filter(Boolean);r.exempt=_.length?{visa_status:_}:void 0},"F-1, J-1"),f("On-exceed label",(S=r.onExceed)!=null?S:"",v=>{r.onExceed=v||void 0},"tax resident"),f("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 fe=require("obsidian"),lr=an(Ds());async function cr(s,t,e,n,i={}){var O,j,$;let o=t.split(` +`).map(A=>A.trim()).filter(Boolean),r="";for(let A of o)if(A.startsWith("file:")){r=A.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(n.sourcePath),l=(j=(O=a==null?void 0:a.parent)==null?void 0:O.path)!=null?j:"",c=ue(r,l),d=s.vault.getAbstractFileByPath(c);if(!d||!(d instanceof fe.TFile)){e.createEl("p",{text:`Error: File not found: ${c}`,cls:"csv-add-error"});return}let h=($=i[c])!=null?$:{},u=[],f=[];try{let A=await s.vault.read(d),z=Nt(A);u=z.headers,f=z.rows}catch(A){e.createEl("p",{text:`Error reading file: ${A}`,cls:"csv-add-error"});return}if(!u.length){e.createEl("p",{text:"Error: No columns found in file",cls:"csv-add-error"});return}let p=A=>{let z=A.toLowerCase();if(["date","day","datum"].includes(z))return!0;let G=f.slice(0,5).map(B=>{var F;return(F=B[A])!=null?F:""});return G.length>0&&G.every(B=>/^\d{4}-\d{2}-\d{2}$/.test(B))},g=A=>{let z=A.toLowerCase();return["notes","note","comments","description","journal"].includes(z)},m=h.habitColumns?h.habitColumns.filter(A=>u.includes(A)):u.filter(A=>!p(A)&&Qe(f.map(z=>{var G;return((G=z[A])!=null?G:"").toLowerCase().trim()}))),b=u.filter(A=>p(A)),x=u.filter(A=>g(A)),C=u.filter(A=>!m.includes(A)&&!b.includes(A)&&!x.includes(A)),E=h.titleColumn?u.find(A=>A.toLowerCase()===h.titleColumn.toLowerCase()):u.find(A=>["title","name"].includes(A.toLowerCase())),S=e.createDiv({cls:"csv-add-form csv-add-compact"}),y=S.createEl("button",{cls:"csv-add-trigger",text:"+ New entry"});y.style.display="none";let v=S.createDiv({cls:"csv-add-card"}),_=v.createDiv({cls:"csv-add-card-header"});_.createEl("span",{cls:"csv-add-card-title",text:"New entry"});let w=_.createEl("button",{cls:"csv-add-card-close",text:"\xD7"}),T=v.createDiv({cls:"csv-add-rows"}),k={},M={},L=(A,z)=>{let G=T.createDiv({cls:`csv-add-row csv-add-row-${z}`});return G.createEl("span",{cls:"csv-add-row-label",text:Mt(A)}),G};b.forEach(A=>{let G=L(A,"date").createEl("input",{cls:"csv-add-row-control",type:"date"});G.value=new Date().toISOString().split("T")[0],k[A]=G}),m.forEach(A=>{M[A]=!1;let G=L(A,"toggle").createEl("label",{cls:"csv-add-switch"}),B=G.createEl("input",{type:"checkbox",cls:"csv-add-switch-input"});G.createEl("span",{cls:"csv-add-switch-track"}),B.addEventListener("change",()=>{M[A]=B.checked}),k[A]=B}),C.forEach(A=>{let z=L(A,"field"),G=new Set(f.map(F=>{var N;return((N=F[A])!=null?N:"").trim()}).filter(Boolean));if(A!==E&&(h.categoricalColumns?h.categoricalColumns.includes(A):Xt(G.size))){let F=z.createEl("select",{cls:"csv-add-row-control"});F.createEl("option",{text:"\u2014",value:""}),Array.from(G).sort().forEach(V=>F.createEl("option",{text:V,value:V})),F.createEl("option",{text:"+ Custom",value:"__custom__"});let N=T.createDiv({cls:"csv-add-row csv-add-row-custom"});N.style.display="none";let H=N.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:`Custom ${Mt(A).toLowerCase()}`});T.insertBefore(N,z.nextSibling),F.addEventListener("change",()=>{N.style.display=F.value==="__custom__"?"flex":"none",F.value==="__custom__"&&H.focus()}),k[A]=F,k[`${A}__custom`]=H}else k[A]=z.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:Mt(A)})}),x.forEach(A=>{let z=T.createDiv({cls:"csv-add-row csv-add-row-notes"});z.createEl("span",{cls:"csv-add-row-label",text:Mt(A)}),k[A]=z.createEl("textarea",{cls:"csv-add-row-textarea",placeholder:"Optional notes\u2026"})});let I=v.createEl("button",{text:"Add",cls:"csv-add-submit"}),P=_.querySelector(".csv-add-card-title"),R=()=>{if(!b.length)return;let A=k[b[0]];if(!A)return;let z=A.value,G=f.find(B=>B[b[0]]===z);P&&P.setText(G?`Updating ${z}`:"New entry"),v.classList.toggle("is-updating",!!G),I.setText(G?"Update":"Add"),m.forEach(B=>{var H;let F=k[B];if(!F)return;let N=Ze((H=G==null?void 0:G[B])!=null?H:"");F.checked=N,M[B]=N}),[...C,...x].forEach(B=>{var H,V;let F=k[B];if(!F)return;let N=(H=G==null?void 0:G[B])!=null?H:"";if(F instanceof HTMLSelectElement)if(Array.from(F.options).find(Y=>Y.value===N)){F.value=N;let Y=(V=k[`${B}__custom`])==null?void 0:V.closest(".csv-add-row-custom");Y&&(Y.style.display="none")}else F.value="";else F instanceof HTMLTextAreaElement,F.value=N})};if(R(),b.length){let A=k[b[0]];A==null||A.addEventListener("change",R)}let D=()=>{v.style.display="block",y.style.display="none";let A=v.querySelector(".csv-add-row-control");A==null||A.focus()},W=()=>{v.style.display="none",y.style.display=""};y.addEventListener("click",D),w.addEventListener("click",W),I.addEventListener("click",async()=>{let A={};u.forEach(V=>{var K,Y,q,X;m.includes(V)?A[V]=M[V]?"1":"0":k[V]instanceof HTMLSelectElement&&k[V].value==="__custom__"?A[V]=(Y=(K=k[`${V}__custom`])==null?void 0:K.value)!=null?Y:"":k[V]instanceof HTMLTextAreaElement?A[V]=k[V].value:A[V]=(X=(q=k[V])==null?void 0:q.value)!=null?X:""});let z=b.length>0&&b.some(V=>{var K;return((K=A[V])!=null?K:"").trim()}),G=[...C,...x].some(V=>{var K;return((K=A[V])!=null?K:"").trim()}),B=m.some(V=>M[V]);if(!z&&!G&&!B){new fe.Notice("Please fill at least one field");return}let F=[];try{let V=await s.vault.read(d);F=Nt(V).rows}catch(V){new fe.Notice(`Error reading file: ${V}`);return}let N=!1,H=-1;if(b.length>0){let V=b[0],K=A[V];if(H=F.findIndex(Y=>Y[V]===K),H>=0){N=!0;let Y=F[H];u.forEach(q=>{var X;(m.includes(q)||((X=A[q])!=null?X:"").trim())&&(Y[q]=A[q])})}else F.push(A)}else F.push(A);try{let V=lr.default.unparse(F,{columns:u});await s.vault.modify(d,V),new fe.Notice(N?`Updated entry for ${A[b[0]]||""}`:`Added entry to ${d.basename}`),f.length=0,f.push(...F),b.length>0?R():(m.forEach(K=>{M[K]=!1;let Y=k[K];Y&&(Y.checked=!1)}),[...C,...x].forEach(K=>{let Y=k[K];Y instanceof HTMLSelectElement?Y.selectedIndex=0:(Y instanceof HTMLTextAreaElement||Y)&&(Y.value="");let q=k[`${K}__custom`];if(q){q.value="";let X=q.closest(".csv-add-row-custom");X&&(X.style.display="none")}})),setTimeout(async()=>{let K=s.vault.getAbstractFileByPath(n.sourcePath);if(K instanceof fe.TFile){let Y=s.workspace.activeLeaf;Y&&await Y.openFile(K,{state:{mode:"preview"}})}},300)}catch(V){new fe.Notice(`Error saving: ${V}`)}})}function mn(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 i=t.createDiv({cls:"csv-table-wrapper"}).createEl("table",{cls:"csv-table"}),o=i.createEl("thead").createEl("tr");s.headers.forEach(l=>{let c=o.createEl("th");c.setText(l),c.addClass("csv-th-sortable"),s.tableSortCol===l&&c.createSpan({cls:"csv-th-sort-indicator",text:s.tableSortDir==="asc"?" \u25B2":" \u25BC"}),c.title="Click to sort",c.addEventListener("click",p=>{p.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 d=s.settings.columnWidths[l];d&&(c.style.width=d+"px");let h=c.createDiv({cls:"csv-col-resize-handle"}),u=0,f=0;h.addEventListener("pointerdown",p=>{p.preventDefault(),p.stopPropagation(),h.setPointerCapture(p.pointerId),u=p.clientX,f=c.offsetWidth;let g=b=>{c.style.width=Math.max(60,f+b.clientX-u)+"px"},m=b=>{s.settings.columnWidths[l]=Math.max(60,f+b.clientX-u),h.removeEventListener("pointermove",g),h.removeEventListener("pointerup",m),s.persistSettings()};h.addEventListener("pointermove",g),h.addEventListener("pointerup",m)})}),o.createEl("th",{text:""});let r=matchMedia("(pointer: coarse)").matches,a=i.createEl("tbody");e.forEach(l=>{let c=a.createEl("tr");c.addEventListener("contextmenu",u=>s.openRowContextMenu(l,u)),s.headers.forEach(u=>{var p,g;let f=c.createEl("td");if(s.isNotesCol(u)){f.addClass("csv-table-notes-cell");let m=((p=l[u])!=null?p:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").split(` +`).filter(C=>C.trim()).slice(0,3).join(" \xB7 "),b=m?m.slice(0,200)+(m.length>200?"\u2026":""):"+ Add note",x=f.createSpan({text:b});m||x.addClass("csv-table-notes-empty"),f.title="Click to open note",f.addEventListener("click",C=>{C.stopPropagation(),s.openNoteExpander(l,u)})}else if(s.isSelectCol(u))s.renderSelectField(f,l,u);else{let m=(g=l[u])!=null?g:"";f.setText(m),m.length>80&&(f.title=m),Ps(s,f,l,u)}});let d=c.createEl("td",{cls:"csv-table-action"}),h=s.notesFileExists(l);d.createEl("button",{cls:`csv-table-notes-btn ${h?"exists":""}`,text:h?"\u{1F4C4}":"\u271A",title:h?"Open notes":"Create notes"}).addEventListener("click",()=>s.openOrCreateNotes(l)),d.createEl("button",{cls:"csv-table-del-btn",text:"\u2715",title:"Delete row (Undo available)"}).addEventListener("click",()=>s.deleteWithUndo(l))}),r||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 Ps(s,t,e,n){t.addEventListener("click",i=>{var d,h;if(t.querySelector("input"))return;t.empty();let o=(d=s.fileCfg.dateColumns)==null?void 0:d.includes(n),r=((h=e[n])!=null?h:"").trim(),a=o||Et(n)&&(r===""||dn.test(r)),l=a?r.slice(0,10):r,c=t.createEl("input",{cls:"csv-inline-input",value:l,type:a?"date":"text"});c.focus(),a||c.select(),c.addEventListener("click",u=>u.stopPropagation()),c.addEventListener("blur",()=>{e[n]=c.value,s.scheduleSave(),t.empty(),t.setText(c.value||"\u2014")}),c.addEventListener("keydown",u=>{u.key==="Enter"&&c.blur(),u.key==="Escape"&&(t.empty(),t.setText(e[n]||"\u2014"))})})}function bn(s){return!!(s.getCategoryCol()||s.getStatusCol()||dr(s)||s.authorKey())}function dr(s){return s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"])}function Fs(s){var i;let t=(s!=null?s:"").trim();if(!t)return null;let e=((i=t.match(/★/g))!=null?i:[]).length;if(e>0)return e;let n=parseFloat(t);return isNaN(n)||n<=0?null:Math.min(5,n)}var hr=["watched","read","finished","completed","done","yes","seen"],ur=["watching","reading","in progress","in-progress"],jc=["dropped","abandoned","dnf"];function Uc(s){let t=s.toLowerCase();return hr.includes(t)?"is-done":ur.includes(t)?"is-progress":jc.includes(t)?"is-dropped":""}function Rs(s,t){let e=new Map;return s.forEach(n=>t(n).forEach(i=>{var o;return e.set(i,((o=e.get(i))!=null?o:0)+1)})),e}function Os(s,t,e,n){if(!e.length)return;let i=s.createDiv({cls:"csv-stats-section"});i.createDiv({cls:"csv-stats-section-title",text:t});let o=Math.max(...e.map(r=>r.count));e.forEach(r=>{var h;let a=i.createDiv({cls:"csv-stats-bar-row"});a.createDiv({cls:"csv-stats-bar-label",text:r.label,attr:{title:r.label}});let c=a.createDiv({cls:"csv-stats-bar-track"}).createDiv({cls:`csv-stats-bar-fill ${(h=r.cls)!=null?h:""}`});c.style.width=`${Math.max(2,Math.round(r.count/o*100))}%`;let d=n>0?Math.round(r.count/n*100):0;a.createDiv({cls:"csv-stats-bar-count",text:`${r.count} \xB7 ${d}%`}),r.onClick&&(a.addClass("is-clickable"),a.title=`Show "${r.label}" in the library`,a.addEventListener("click",r.onClick))})}function fr(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 n=t.createDiv({cls:"csv-stats-wrap"}),i=s.getStatusCol(),o=s.getCategoryCol(),r=dr(s),a=s.authorKey(),l=s.resolveCol(["Year","year"]),c=n.createDiv({cls:"csv-stats-overview"}),d=(u,f)=>{let p=c.createDiv({cls:"csv-stats-chip"});p.createDiv({cls:"csv-stats-chip-value",text:u}),p.createDiv({cls:"csv-stats-chip-label",text:f})};if(d(String(e.length),"entries"),i){let u=e.filter(p=>{var g;return hr.includes(((g=p[i])!=null?g:"").toLowerCase().trim())}).length;u>0&&d(`${u} \xB7 ${Math.round(u/e.length*100)}%`,"done");let f=e.filter(p=>{var g;return ur.includes(((g=p[i])!=null?g:"").toLowerCase().trim())}).length;f>0&&d(String(f),"in progress")}if(o){let u=Rs(e,f=>{var p;return((p=f[o])!=null?p:"").split(",").map(g=>g.trim()).filter(Boolean)});u.size>0&&d(String(u.size),o.toLowerCase()==="genre"||o.toLowerCase()==="genres"?"genres":"categories")}if(r){let u=e.map(f=>Fs(f[r])).filter(f=>f!==null);if(u.length){let f=u.reduce((p,g)=>p+g,0)/u.length;d(`\u2605 ${f.toFixed(1)}`,`avg of ${u.length} rated`)}}let h=(u,f)=>{s.libraryStatusFilter=u!=null?u:"all",s.libraryGenreFilter=f!=null?f:"all",s.mode="library",s.renderView()};if(i){let u=Rs(e,p=>{var m;let g=((m=p[i])!=null?m:"").trim();return g?[g]:[]}),f=Array.from(u.entries()).sort((p,g)=>g[1]-p[1]).map(([p,g])=>({label:p,count:g,cls:Uc(p),onClick:o?()=>h(p,null):void 0}));Os(n,`By ${i.toLowerCase()}`,f,e.length)}if(o){let u=Rs(e,p=>{var g;return((g=p[o])!=null?g:"").split(",").map(m=>m.trim()).filter(Boolean)}),f=Array.from(u.entries()).sort((p,g)=>g[1]-p[1]||p[0].localeCompare(g[0])).slice(0,12).map(([p,g])=>({label:p,count:g,onClick:()=>h(null,p)}));Os(n,`By ${o.toLowerCase()}`,f,e.length)}if(r){let u=new Map,f=0;if(e.forEach(p=>{var b;let g=Fs(p[r]);if(g===null)return;let m=Math.min(5,Math.max(1,Math.round(g)));u.set(m,((b=u.get(m))!=null?b:0)+1),f++}),f>0){let p=[5,4,3,2,1].filter(g=>{var m;return((m=u.get(g))!=null?m:0)>0}).map(g=>({label:"\u2605".repeat(g),count:u.get(g),cls:"is-rating"}));Os(n,"Ratings",p,f)}}if(l){let u=Rs(e,f=>{var g;let p=((g=f[l])!=null?g:"").match(/\d{4}/);return p?[p[0]]:[]});if(u.size>1){let f=Array.from(u.entries()).sort((p,g)=>p[0].localeCompare(g[0])).map(([p,g])=>({label:p,count:g}));Os(n,"By year",f,e.length)}}if(a){let u=Rs(e,p=>{var m;let g=((m=p[a])!=null?m:"").trim();return g?[g]:[]}),f=Array.from(u.entries()).filter(([,p])=>p>1);if(f.length>=2){let p=f.sort((g,m)=>m[1]-g[1]||g[0].localeCompare(m[0])).slice(0,8).map(([g,m])=>({label:g,count:m}));Os(n,`Top ${a.toLowerCase()}s`,p,e.length)}}}function $t(s){let t=s.fileCfg.kanbanGroupCol;if(t&&s.headers.includes(t))return t;let e=s.getCategoryCol();if(e)return e;let n=new Set;s.headers.forEach(r=>{s.isNotesCol(r)&&n.add(r)});let i=s.getDateCol();i&&n.add(i);let o=s.titleKey();return o&&n.add(o),Qo(s.headers,s.rows,n)}function vn(s,t){let e=$t(s);if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let n=s.getCategoryCol(),i=s.getStatusCol(),o=i===e?null:i,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 b=l.createEl("option",{text:m===n?`${m} (default)`:m,value:m});m===e&&(b.selected=!0)}),l.addEventListener("change",()=>{let m=s.fileCfg;m.kanbanGroupCol=l.value===n?void 0:l.value,s.saveFileCfg(m),s.renderView(!0)});let c=qo(e,r.map(m=>{var b;return(b=m[e])!=null?b:""})),d=m=>{var C;let b=(C=m[e])!=null?C:"",x;if(c){let E=Xo(b);x=E?[E]:[]}else x=b.split(",").map(E=>E.trim()).filter(Boolean);return x.length||(x=["\u2014"]),x},h=new Set;r.forEach(m=>d(m).forEach(b=>h.add(b)));let u=Array.from(h).sort();if(!u.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 f=["In progress","Finished","Not started"],p=o?Array.from(new Set([...f,...r.map(m=>{var b;return(b=m[o])!=null?b:""}).filter(Boolean)])).filter(m=>r.some(b=>{var x;return((x=b[o])!=null?x:"")==m})):[],g=t.createDiv({cls:"csv-kanban-board"});u.forEach(m=>{let b=r.filter(S=>d(S).includes(m));if(!b.length)return;let x=g.createDiv({cls:"csv-kanban-col"}),C=x.createDiv({cls:"csv-kanban-col-header"});C.createDiv({cls:"csv-kanban-col-title",text:m}),C.createDiv({cls:"csv-kanban-col-count",text:String(b.length)});let E=x.createDiv({cls:"csv-kanban-col-body"});if(o&&p.length){p.forEach(v=>{let _=b.filter(T=>{var k;return((k=T[o])!=null?k:"")===v});if(!_.length)return;let w=E.createDiv({cls:"csv-kanban-status-group"});w.createDiv({cls:`csv-kanban-status-label status-${v.toLowerCase().replace(/\s+/g,"-")}`,text:v}),_.forEach(T=>xi(s,w,T,o,e))});let S=new Set(p),y=b.filter(v=>{var _;return!S.has((_=v[o])!=null?_:"")});if(y.length){let v=E.createDiv({cls:"csv-kanban-status-group"});v.createDiv({cls:"csv-kanban-status-label",text:"\u2014"}),y.forEach(_=>xi(s,v,_,o,e))}}else b.forEach(S=>xi(s,E,S,o,e))})}function xi(s,t,e,n,i){var _,w,T,k,M,L,I,P;let o=t.createDiv({cls:"csv-kanban-card"}),r=s.getNotesCol(),a=(w=(_=s.getImageCol)==null?void 0:_.call(s))!=null?w:null;if(a){let R=cn(s.app,(T=e[a])!=null?T:"",(M=(k=s.file)==null?void 0:k.path)!=null?M:"");if(R){let D=o.createEl("img",{cls:"csv-kanban-card-img",attr:{src:R,loading:"lazy",alt:""}});D.addEventListener("error",()=>D.remove())}}let l=o.createDiv({cls:"csv-kanban-card-title-row"});l.createDiv({cls:`csv-kanban-card-title ${(L=s.isHighlighted)!=null&&L.call(s,e)?"csv-title-highlight":""}`,text:s.getTitle(e)}).addEventListener("click",R=>{R.stopPropagation(),s.openNoteExpander(e,r!=null?r:"")});let d=s.notesFileExists(e);l.createEl("button",{cls:`csv-kanban-notes-icon ${d?"exists":""}`,text:d?"\u{1F4C4}":"+",title:d?"Open notes file":"Create notes file"}).addEventListener("click",R=>{R.stopPropagation(),s.openOrCreateNotes(e)});let u=s.getSubtitle(e);u&&o.createDiv({cls:"csv-kanban-card-sub",text:u});let f=s.titleKey(),p=s.authorKey(),g=new Set([n,f,p,i].filter(Boolean)),m=o.createDiv({cls:"csv-kanban-card-meta"});((I=s.fileCfg.cardFields)!=null?I:s.headers).forEach(R=>{if(!s.headers.includes(R)||g.has(R)||s.isNotesCol(R))return;let D=m.createDiv({cls:"csv-kanban-chip"});if(D.createSpan({cls:"csv-chip-label",text:R+": "}),s.isSelectCol(R)){let W=D.createSpan({cls:`csv-chip-value csv-chip-select${e[R]?"":" csv-chip-value--empty"}`,text:e[R]||"\u2014"});W.addEventListener("click",O=>{O.stopPropagation(),Ft(W,e[R],s.getColumnValues(R),j=>{e[R]=j,W.setText(j||"\u2014"),W.classList.toggle("csv-chip-value--empty",!j),s.scheduleSave()},s.contentEl,{multi:kt(R)})})}else{let W=e[R]?e[R].length>40?e[R].slice(0,38)+"\u2026":e[R]:"\u2014",O=D.createSpan({cls:`csv-chip-value${e[R]?"":" csv-chip-value--empty"}`,text:W});e[R]&&e[R].length>40&&(O.title=e[R])}});let x=s.getNotesCol(),C=!!(x&&((P=e[x])!=null&&P.trim())),E=o.createDiv({cls:"csv-kanban-notes-preview"});if(C&&x){let R=e[x].replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();E.setText(R.slice(0,120)+(R.length>120?"\u2026":"")),E.title="Click to edit"}else E.addClass("csv-kanban-notes-preview--empty"),x&&E.setText("+ Add note");let S=o.createDiv({cls:"csv-kanban-notes-editor"});S.style.display="none";let y=()=>{var j,$,A;let R=s.contentEl.querySelector(".csv-content-area"),D=(j=R==null?void 0:R.scrollLeft)!=null?j:0,W=($=R==null?void 0:R.scrollTop)!=null?$:0;E.style.display="none",S.style.display="block",S.empty();let O=S.createEl("textarea",{cls:"csv-notes-textarea"});O.value=(A=x?e[x]:"")!=null?A:"",O.addEventListener("click",z=>z.stopPropagation()),O.addEventListener("mousedown",z=>z.stopPropagation()),O.addEventListener("input",()=>{O.style.height="auto",O.style.height=O.scrollHeight+"px"}),O.addEventListener("keydown",z=>{z.key==="Escape"&&v(O.value,R,D,W)}),O.addEventListener("blur",()=>v(O.value,R,D,W)),O.focus({preventScroll:!0}),O.setSelectionRange(0,0),O.scrollTop=0,requestAnimationFrame(()=>{O.style.height="auto",O.style.height=Math.max(120,O.scrollHeight)+"px"})},v=(R,D,W,O)=>{if(x&&(e[x]=R,s.scheduleSave()),S.style.display="none",E.style.display="",R.trim()){let j=R.replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();E.setText(j.slice(0,120)+(j.length>120?"\u2026":"")),E.removeClass("csv-kanban-notes-preview--empty"),E.title="Click to edit"}else E.addClass("csv-kanban-notes-preview--empty"),E.setText(x?"+ Add note":""),E.removeAttribute("title");D&&(D.scrollLeft=W,D.scrollTop=O,requestAnimationFrame(()=>{D.scrollLeft=W,D.scrollTop=O,requestAnimationFrame(()=>{D.scrollLeft=W,D.scrollTop=O})}),setTimeout(()=>{D.scrollLeft=W,D.scrollTop=O},50))};E.addEventListener("click",R=>{if(R.stopPropagation(),x&&matchMedia("(pointer: coarse)").matches){s.openNoteExpander(e,x);return}y()}),o.addEventListener("contextmenu",R=>s.openRowContextMenu(e,R))}function yn(s,t){var w,T;let e=$t(s),n=s.getStatusCol(),i=(w=s.titleKey())!=null?w:s.headers[0],o=s.authorKey();if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let r=new Set;s.rows.forEach(k=>{var L;((L=k[e])!=null?L:"").split(",").map(I=>I.trim()).filter(Boolean).forEach(I=>r.add(I))});let a=new Set;n&&s.rows.forEach(k=>{var L;let M=((L=k[n])!=null?L:"").trim();M&&a.add(M)});let l=t.createDiv({cls:"csv-library-filters"}),c=l.createEl("select",{cls:"csv-library-filter-select"});c.createEl("option",{text:"All",value:"all"});let d=["watched","read","finished","completed","done","yes","seen"],h=["watching","reading","in progress","in-progress"],u=Array.from(a).some(k=>d.includes(k.toLowerCase())),f=Array.from(a).some(k=>h.includes(k.toLowerCase()));(u||f)&&(c.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),u&&c.createEl("option",{text:"\u2713 Done",value:"__done__"}),f&&c.createEl("option",{text:"\u25D0 In Progress",value:"__inprogress__"}),c.createEl("option",{text:"\u25CB Not Started",value:"__notstarted__"})),a.size>0&&(c.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),Array.from(a).sort().forEach(k=>{c.createEl("option",{text:k,value:k})})),c.value=s.libraryStatusFilter;let p=l.createEl("select",{cls:"csv-library-filter-select"});p.createEl("option",{text:"All genres",value:"all"}),Array.from(r).sort().forEach(k=>{p.createEl("option",{text:k,value:k})}),p.value=s.libraryGenreFilter;let g=s.resolveCol(["Year","year","Date","date"]),m=s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"]),b=s.resolveCol(["Theme","theme","Tags","tags","Tag","tag","Mood","mood"]),x=(T=s.fileCfg.librarySort)!=null?T:"status",C=l.createEl("select",{cls:"csv-library-filter-select"}),E=[["status","Sort: Status"],["title","Sort: Title"]];m&&E.push(["rating","Sort: Rating"]),g&&E.push(["year","Sort: Year"]),E.forEach(([k,M])=>{let L=C.createEl("option",{text:M,value:k});k===x&&(L.selected=!0)}),C.addEventListener("change",()=>{let k=s.fileCfg;k.librarySort=C.value==="status"?void 0:C.value,s.saveFileCfg(k),s.renderView(!0)});let S=()=>{s.libraryStatusFilter=c.value,s.libraryGenreFilter=p.value,s.renderView(!0)};c.addEventListener("change",S),p.addEventListener("change",S);let y=s.rows.filter(k=>{var M,L;if(s.libraryStatusFilter!=="all"&&n){let I=((M=k[n])!=null?M:"").toLowerCase();if(s.libraryStatusFilter==="__done__"){if(!d.includes(I))return!1}else if(s.libraryStatusFilter==="__inprogress__"){if(!h.includes(I))return!1}else if(s.libraryStatusFilter==="__notstarted__"){if(d.includes(I)||h.includes(I))return!1}else if(I!==s.libraryStatusFilter.toLowerCase())return!1}if(s.libraryGenreFilter!=="all"&&!((L=k[e])!=null?L:"").split(",").map(P=>P.trim().toLowerCase()).includes(s.libraryGenreFilter.toLowerCase()))return!1;if(s.searchQuery.trim()){let I=s.searchQuery.toLowerCase().trim();if(!s.headers.some(P=>{var R;return((R=k[P])!=null?R:"").toLowerCase().includes(I)}))return!1}return!0});(s.libraryStatusFilter!=="all"||s.libraryGenreFilter!=="all"||s.searchQuery.trim())&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${y.length} of ${s.rows.length} entries`});let v={};y.forEach(k=>{var L;let M=s.libraryGenreFilter!=="all"?[s.libraryGenreFilter]:((L=k[e])!=null?L:"Uncategorized").split(",").map(I=>I.trim()).filter(Boolean);M.length===0&&M.push("Uncategorized"),M.forEach(I=>{v[I]||(v[I]=[]),v[I].push(k)})});let _=t.createDiv({cls:"csv-library-sections"});if(Object.keys(v).sort().forEach(k=>{var A,z,G,B,F;let M=v[k],L=_.createEl("details",{cls:"csv-library-section"}),I=k.toLowerCase(),P=((A=s.fileCfg.collapsedGroups)!=null?A:[]).map(N=>N.toLowerCase());L.open=!((z=s.collapsedGroups)!=null&&z.has(I)||P.includes(I)),L.addEventListener("toggle",()=>{var Y;let N=s.fileCfg,H=((Y=N.collapsedGroups)!=null?Y:[]).map(q=>q.toLowerCase()),V=new Set(H);L.open?V.delete(I):V.add(I);let K=Array.from(V);K.length===H.length&&K.every(q=>H.includes(q))||(N.collapsedGroups=K,s.saveFileCfg(N))});let R=L.createEl("summary",{cls:"csv-library-section-header"});R.innerHTML=`\u25B6 ${k} ${M.length}`;let D=L.createDiv({cls:"csv-library-grid"}),W=(N,H)=>{var V,K;return((V=N[i])!=null?V:"").localeCompare((K=H[i])!=null?K:"")},O=(N,H)=>N===null&&H===null?0:N===null?1:H===null?-1:H-N;M.sort((N,H)=>{var V,K,Y,q;if(x==="title")return W(N,H);if(x==="rating"&&m)return O(Fs((V=N[m])!=null?V:""),Fs((K=H[m])!=null?K:""))||W(N,H);if(x==="year"&&g){let X=Z=>{var Q;let at=((Q=Z[g])!=null?Q:"").match(/\d{4}/);return at?parseInt(at[0],10):null};return O(X(N),X(H))||W(N,H)}if(n){let X=((Y=N[n])!=null?Y:"").toLowerCase(),Z=((q=H[n])!=null?q:"").toLowerCase(),at=d.includes(X),Q=d.includes(Z);if(at!==Q)return at?-1:1;let st=h.includes(X),lt=h.includes(Z);if(st!==lt)return st?-1:1}return W(N,H)});let j=(G=s.fileCfg.cardFields)!=null?G:s.headers,$=(F=(B=s.getImageCol)==null?void 0:B.call(s))!=null?F:null;M.forEach(N=>{var q,X,Z,at,Q,st,lt,Wt;let H=D.createDiv({cls:"csv-library-card"});if($){let ot=cn(s.app,(q=N[$])!=null?q:"",(Z=(X=s.file)==null?void 0:X.path)!=null?Z:"");if(ot){let gt=H.createEl("img",{cls:"csv-library-card-img",attr:{src:ot,loading:"lazy",alt:""}});gt.addEventListener("error",()=>gt.remove())}}let V=H.createDiv({cls:`csv-library-card-title ${(at=s.isHighlighted)!=null&&at.call(s,N)?"csv-title-highlight":""}`});if(n){let ot=((Q=N[n])!=null?Q:"").toLowerCase();d.includes(ot)&&V.createSpan({cls:"csv-library-done-dot"})}V.createSpan({text:(st=N[i])!=null?st:"Untitled"});let K=[],Y=[];for(let ot of j){if(!ot)continue;let gt=String((lt=N[ot])!=null?lt:"").trim();if(gt)if(ot===m){let ft=Go(gt,ot);ft&&H.createDiv({cls:"csv-library-card-rating",text:ft})}else if(ot===b)Y.push(...gt.split(",").map(ft=>ft.trim()).filter(Boolean));else if(ot===g){let ft=gt.match(/\d{4}/);K.push(ft?ft[0]:gt)}else K.push(gt)}if(K.length&&H.createDiv({cls:"csv-library-card-meta",text:K.join(" \xB7 ")}),s.libraryGenreFilter!=="all"){let ot=((Wt=N[e])!=null?Wt:"").split(",").map(gt=>gt.trim()).filter(gt=>gt&>.toLowerCase()!==s.libraryGenreFilter.toLowerCase());Y.push(...ot)}if(Y.length){let ot=H.createDiv({cls:"csv-library-card-tags"});Y.slice(0,3).forEach(gt=>{ot.createSpan({cls:"csv-library-card-tag",text:gt})})}H.addEventListener("click",()=>{var ot;s.openNoteExpander(N,(ot=s.getNotesCol())!=null?ot:"")}),H.addEventListener("contextmenu",ot=>s.openRowContextMenu(N,ot))})}),Object.keys(v).length===0){let k=_.createDiv({cls:"csv-empty-state"});k.createEl("p",{text:"No entries match your filters."}),k.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.libraryStatusFilter="all",s.libraryGenreFilter="all",s.searchQuery="",s.renderView()})}}var di=require("obsidian");var Le=require("obsidian");var Ci=`--- obsidianUIMode: preview obsidianEditingMode: source --- -`,bi=` +`,_i=` --- Requires Dataview plugin with DataviewJS enabled -`;function nr(s){let{filePath:t,csvPath:e,habitCols:n,labels:i,dateCol:o}=s;return`${mi}## Quick Add +`;function pr(s){let{filePath:t,csvPath:e,habitCols:n,labels:i,dateCol:o}=s;return`${Ci}## Quick Add \`\`\`csv-add file: ${t} @@ -117,7 +117,7 @@ if (!csvData || !csvData.length) { } } \`\`\` -${bi}`}function ir(s){let{filePath:t,csvPath:e,titleKey:n,categoryCol:i,statusCol:o,authorKey:r,yearCol:a,ratingCol:l,themeCol:c,compactGrid:d}=s;return`${mi}## Add Entry +${_i}`}function gr(s){let{filePath:t,csvPath:e,titleKey:n,categoryCol:i,statusCol:o,authorKey:r,yearCol:a,ratingCol:l,themeCol:c,compactGrid:d}=s;return`${Ci}## Add Entry \`\`\`csv-add file: ${t} @@ -295,7 +295,7 @@ if (!csvData || !csvData.length) { } } \`\`\` -${bi}`}function or(s){let{filePath:t,csvPath:e,headers:n}=s;return`${mi}## Add Entry +${_i}`}function mr(s){let{filePath:t,csvPath:e,headers:n}=s;return`${Ci}## Add Entry \`\`\`csv-add file: ${t} @@ -365,12 +365,13 @@ if (!csvData || !csvData.length) { } } \`\`\` -${bi}`}async function rr(s){var c,d,h,u,f,g,p,m,b,x;if(!s.file)return;let t=(d=(c=s.file.parent)==null?void 0:c.path)!=null?d:"",e=t?`${t}/Mobile`:"Mobile";await s.app.vault.adapter.exists(e)||await s.app.vault.adapter.mkdir(e);let n=`${e}/${s.file.basename}.md`,i=s.file.path,o=s.getDateCol(),r=s.getCategoryCol(),a="../"+s.file.name,l;if(o){let C=s.getBooleanColumns();l=nr({filePath:a,csvPath:i,habitCols:C,labels:C.map(Dt),dateCol:o})}else if(r){let C=(f=(u=(h=s.titleKey())!=null?h:s.resolveCol(["Quote","quote","Headline","headline","Phrase","phrase"]))!=null?u:s.headers[0])!=null?f:"Title";l=ir({filePath:a,csvPath:i,titleKey:C,categoryCol:r,statusCol:(g=s.getStatusCol())!=null?g:"Status",authorKey:(p=s.authorKey())!=null?p:"",yearCol:(m=s.resolveCol(["Year","year","Released","released"]))!=null?m:"",ratingCol:(b=s.resolveCol(["Rating","rating","Score","score","Stars","stars"]))!=null?b:"",themeCol:(x=s.resolveCol(["Theme","theme","Subgenre","subgenre","Mood","mood"]))!=null?x:"",compactGrid:s.titleKey()!==null})}else l=or({filePath:a,csvPath:i,headers:s.headers});try{let C=s.app.vault.getAbstractFileByPath(n);C&&C instanceof Te.TFile?(await s.app.vault.modify(C,l),new Te.Notice(`Updated: ${n}`)):(await s.app.vault.create(n,l),new Te.Notice(`Created: ${n}`))}catch(C){let k=s.app.vault.getAbstractFileByPath(n);k instanceof Te.TFile&&(await s.app.vault.modify(k,l),new Te.Notice(`Updated: ${n}`))}}var fe=require("obsidian"),Dc="http://127.0.0.1:8765",Mc=6;async function ar(s,t){let e;try{e=await(0,fe.requestUrl)({url:Dc,method:"POST",contentType:"application/json",body:JSON.stringify({action:s,version:Mc,params:t}),throw:!1})}catch(i){throw new Error("Couldn't reach Anki. Is the desktop app open with the AnkiConnect add-on installed?")}let n=e.json;if(n.error)throw new Error(n.error);return n.result}function yi(s){var t,e,n;return(n=(e=(t=s.titleKey())!=null?t:s.resolveCol(["Quote","Headline","Phrase","Term","Word","Question","Front","Name","Title"]))!=null?e:s.headers[0])!=null?n:null}function Tc(s){let t=s.fileCfg.ankiFrontCol;return t&&s.headers.includes(t)?t:yi(s)}function vi(s){return s.replace(/&/g,"&").replace(//g,">")}function Lc(s,t,e){return s.headers.filter(n=>{var i;return n!==e&&((i=t[n])!=null?i:"").trim()}).map(n=>`${vi(n)}: ${vi(t[n].trim())}`).join("
")}async function lr(s){if(!s.file)return;let t=Tc(s);if(!t){new fe.Notice("No column to use as the Anki card front.",6e3);return}let e=s.file.basename,n=s.rows.filter(o=>{var r;return((r=o[t])!=null?r:"").trim()});if(!n.length){new fe.Notice(`Nothing to sync \u2014 no rows with a "${t}" value.`,6e3);return}let i=new fe.Notice(`Syncing ${n.length} cards to Anki deck \u201C${e}\u201D\u2026`,0);try{await ar("createDeck",{deck:e});let o=n.map(c=>({deckName:e,modelName:"Basic",fields:{Front:vi(c[t].trim()),Back:Lc(s,c,t)},options:{allowDuplicate:!1,duplicateScope:"deck"},tags:["datadeck"]})),r=await ar("addNotes",{notes:o}),a=r.filter(c=>c!=null).length,l=r.length-a;i.hide(),new fe.Notice(`Anki sync: ${a} added${l?`, ${l} already present`:""} (deck \u201C${e}\u201D).`,6e3)}catch(o){i.hide(),new fe.Notice(`Anki sync failed: ${o instanceof Error?o.message:String(o)}`,8e3)}}function vn(s){return s.resolveCol(["Type","type","Kind","kind","Item","item"])}function Ci(s){var t;return(t=s.resolveCol(["Project","project","Projects","projects","Area","area"]))!=null?t:Bt(s)}function hr(s){return s.resolveCol(["Due","due","Deadline","deadline","Due Date","Due date","due date"])}function yn(s){return s.resolveCol(["Priority","priority","Prio","prio","Importance","importance"])}var Ac=["task","todo","to-do","action","note","idea","reference","ref"],ur=["done","complete","completed","finished","closed","resolved","yes","x","\u2713","true"],Rc={high:0,med:1,medium:1,normal:1,low:2};function ss(s){if(hr(s)||yn(s))return!0;let t=vn(s);return t?s.rows.some(e=>{var n;return Ac.includes(((n=e[t])!=null?n:"").trim().toLowerCase())}):!1}function xi(s,t,e){var n;return e?ur.includes(((n=t[e])!=null?n:"").trim().toLowerCase()):!1}function cr(s){let t=Rc[(s!=null?s:"").trim().toLowerCase()];return t===void 0?3:t}function dr(s){return(s!=null?s:"").trim()?0:1}function Pc(){return new Date().toISOString().slice(0,10)}function Oc(s,t){let e=new Map;s.rows.forEach(o=>{var a,l;let r=((a=o[t])!=null?a:"").trim();r&&ur.includes(r.toLowerCase())&&e.set(r,((l=e.get(r))!=null?l:0)+1)});let n="done",i=0;return e.forEach((o,r)=>{o>i&&(n=r,i=o)}),n}function fr(s,t){var T,E;let e=Ci(s),n=vn(s),i=s.getStatusCol(),o=hr(s),r=yn(s),a=(T=s.titleKey())!=null?T:s.headers[0],l=t.createDiv({cls:"csv-library-filters"}),c=new Set;e&&s.rows.forEach(M=>{var L;((L=M[e])!=null?L:"").split(",").map(I=>I.trim()).filter(Boolean).forEach(I=>c.add(I))});let d=l.createEl("select",{cls:"csv-library-filter-select"});d.createEl("option",{text:e?"All projects":"All",value:"all"}),Array.from(c).sort().forEach(M=>d.createEl("option",{text:M,value:M})),d.value=s.taskProjectFilter;let h=new Set;n&&s.rows.forEach(M=>{var I;let L=((I=M[n])!=null?I:"").trim();L&&h.add(L)});let u=null;h.size>0&&(u=l.createEl("select",{cls:"csv-library-filter-select"}),u.createEl("option",{text:"All types",value:"all"}),Array.from(h).sort().forEach(M=>u.createEl("option",{text:M,value:M})),u.value=s.taskTypeFilter);let f=()=>{s.taskProjectFilter=d.value,u&&(s.taskTypeFilter=u.value),s.renderView(!0)};d.addEventListener("change",f),u==null||u.addEventListener("change",f);let g=s.searchQuery.toLowerCase().trim(),p=s.rows.filter(M=>{var L,I;return!(s.taskProjectFilter!=="all"&&e&&!((L=M[e])!=null?L:"").split(",").map(R=>R.trim().toLowerCase()).includes(s.taskProjectFilter.toLowerCase())||s.taskTypeFilter!=="all"&&n&&((I=M[n])!=null?I:"").trim().toLowerCase()!==s.taskTypeFilter.toLowerCase()||g&&!s.headers.some(F=>{var R;return((R=M[F])!=null?R:"").toLowerCase().includes(g)}))});(s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"||g)&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${p.length} of ${s.rows.length} entries`});let m={},b=M=>{var I;return e&&((I=M[e])!=null?I:"").split(",").map(F=>F.trim()).filter(Boolean)[0]||"\u2014"};p.forEach(M=>{var R,D,W;let L=n?((R=M[n])!=null?R:"").trim():"",I=n?L||"\u2014":"Tasks",F=b(M);m[I]||(m[I]={}),((W=(D=m[I])[F])!=null?W:D[F]=[]).push(M)});let x=t.createDiv({cls:"csv-tasks"}),C=Pc(),k=i?Oc(s,i):"done",y=((E=s.fileCfg.cardFields)!=null?E:s.headers).filter(M=>M!==e&&M!==n&&M!==i),v=[];i&&v.push({name:"",cls:"csv-tasks-check-cell"}),y.forEach(M=>{let L="";M===a?L="csv-tasks-name-cell":M===o?L="csv-tasks-due":M===r?L="csv-tasks-priority":s.isNotesCol(M)?L="csv-tasks-generic-cell csv-tasks-notes-cell":L="csv-tasks-generic-cell",v.push({name:M,cls:L})});let _=(M,L)=>{L.sort((I,F)=>{var W,O,K,z,A,$;let R=xi(s,I,i),D=xi(s,F,i);if(R!==D)return R?1:-1;if(r){let G=cr((W=I[r])!=null?W:"")-cr((O=F[r])!=null?O:"");if(G)return G}if(o){let G=dr((K=I[o])!=null?K:"")-dr((z=F[o])!=null?z:"");if(G)return G;let B=((A=I[o])!=null?A:"").localeCompare(($=F[o])!=null?$:"");if(B)return B}return s.getTitle(I).localeCompare(s.getTitle(F))}),L.forEach(I=>{let F=xi(s,I,i),R=M.createEl("tr");if(i){let W=R.createEl("td",{cls:"csv-tasks-check-cell"}).createEl("span",{cls:`csv-tasks-check ${F?"is-done":""}`,text:F?"\u2713":""});W.setAttr("title",F?"Mark not done":"Mark done"),W.addEventListener("click",O=>{O.stopPropagation(),I[i]=F?"":k,s.scheduleSave(),s.renderView(!0)})}y.forEach(D=>{var W,O,K;if(D===a)Fc(s,R,I,a,F);else if(D===o){let z=R.createEl("td",{cls:"csv-tasks-due csv-tasks-editable"}),A=o?((W=I[o])!=null?W:"").slice(0,10):"";z.setText(A||"\u2014"),A&&!F&&A{var G;A.stopPropagation();let $=Array.from(new Set([...s.getColumnValues(r),"high","medium","low"]));Ot(z,(G=I[r])!=null?G:"",$,B=>{I[r]=B,s.scheduleSave(),s.renderView(!0)},s.contentEl)})}else if(s.isNotesCol(D)){let z=((O=I[D])!=null?O:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim(),A=z?z.length>50?z.slice(0,48)+"\u2026":z:"\u2014",$=R.createEl("td",{text:A,cls:"csv-tasks-generic-cell csv-tasks-notes-cell csv-tasks-editable"});As(s,$,I,D)}else{let z=(K=I[D])!=null?K:"",A=z.length>40?z.slice(0,38)+"\u2026":z,$=R.createEl("td",{text:A||"\u2014",cls:"csv-tasks-generic-cell csv-tasks-editable"});As(s,$,I,D)}}),R.addEventListener("contextmenu",D=>s.openRowContextMenu(I,D))})},w=Object.keys(m).sort((M,L)=>M==="Tasks"||M==="\u2014"?-1:L==="Tasks"||L==="\u2014"?1:M.localeCompare(L));if(w.forEach(M=>{Ic(s,x,M,m[M],_,v)}),w.length===0){let M=x.createDiv({cls:"csv-empty-state"});M.createEl("p",{text:g||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"?"No entries match your filters.":"No tasks yet."}),(g||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all")&&M.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.taskProjectFilter="all",s.taskTypeFilter="all",s.searchQuery="",s.renderView()})}}function Ic(s,t,e,n,i,o){if(Object.keys(n).length===0)return;t.createDiv({cls:"csv-tasks-section-header",text:e});let r=t.createDiv({cls:"csv-tasks-section"});Object.keys(n).sort().forEach(a=>{let l=n[a],c=r.createEl("details",{cls:"csv-tasks-group"});c.open=!0;let d=c.createEl("summary",{cls:"csv-tasks-group-header"});d.innerHTML=`\u25B6 ${a} ${l.length}`;let u=c.createDiv({cls:"csv-tasks-table-wrapper"}).createEl("table",{cls:"csv-tasks-table"}),f=120;o.forEach(b=>{b.cls.includes("check-cell")?f+=30:b.cls.includes("priority")?f+=90:b.cls.includes("due")?f+=150:b.cls.includes("notes-cell")?f+=140:b.cls.includes("generic-cell")&&(f+=150)}),u.style.minWidth=`${f}px`;let p=u.createEl("thead").createEl("tr");o.forEach(b=>p.createEl("th",{text:b.name,cls:b.cls}));let m=u.createEl("tbody");i(m,l)})}function Fc(s,t,e,n,i){var h;let o=t.createEl("td",{cls:"csv-tasks-name-cell"}),r=(h=s.isHighlighted)!=null&&h.call(s,e)?"csv-title-highlight":"",a=o.createSpan({cls:`csv-tasks-link ${i?"csv-tasks-done":""} ${r}`,text:e[n]||"Untitled"}),l=s.getNotesCol();a.addEventListener("click",()=>{l?s.openNoteExpander(e,l):s.openOrCreateNotes(e)});let c=s.notesFileExists(e),d=o.createEl("button",{cls:`csv-tasks-page-icon ${c?"exists":""}`,text:c?"\u{1F4C4}":"+"});d.setAttr("title",c?"Open page":"Create page"),d.addEventListener("click",u=>{u.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"}),ss(s)&&t.push({id:"tasks",label:"Tasks"}),Bt(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"}),pn(s)&&t.push({id:"stats",label:"Stats"}),t}function gr(s,t){var f,g,p;let e=t.createDiv({cls:"csv-toolbar"});e.createDiv({cls:"csv-toolbar-title",text:(g=(f=s.file)==null?void 0:f.basename)!=null?g:""});let n=e.createDiv({cls:"csv-toolbar-controls"});n.createDiv({cls:"csv-row-count",text:`${s.rows.length} entries`});let i=n.createDiv({cls:"csv-mode-group"}),o=xn(s),r=i.createEl("select",{cls:"csv-mode-select",attr:{"aria-label":"View mode"}});if(o.forEach(({id:m,label:b})=>{let x=r.createEl("option",{text:b,value:m});s.mode===m&&(x.selected=!0)}),r.addEventListener("change",()=>{s.mode=r.value,s.renderView()}),s.mode!=="dashboard"){let m=n.createEl("button",{cls:"csv-cfg-btn csv-search-toggle",text:"\u{1F50D}",title:"Search"}),b=n.createDiv({cls:"csv-search-wrap"}),x=b.createDiv({cls:"csv-search-input-wrap"}),C=x.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search...",value:s.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),k=x.createEl("button",{cls:"csv-search-clear",text:"\xD7",title:"Clear search"});k.toggleClass("is-hidden",!s.searchQuery),b.createEl("button",{cls:"csv-search-done",text:"Done",title:"Dismiss keyboard"}).addEventListener("click",v=>{if(v.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",v=>{s.searchQuery=v.target.value,k.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",v=>{v.key==="Enter"&&(v.preventDefault(),C.blur())}),k.addEventListener("click",()=>{s.searchQuery="",C.value="",k.addClass("is-hidden"),m.removeClass("has-query"),C.focus({preventScroll:!0}),s.renderView(!0)}),s.searchQuery&&m.addClass("has-query"),m.addEventListener("click",()=>{e.addClass("csv-toolbar--search-expanded"),C.focus({preventScroll:!0})})}if(s.mode==="table"&&s.hasDateColumn()){let m=(p=s.fileCfg.sortNewestFirst)!=null?p:!0;n.createEl("button",{cls:`csv-cfg-btn ${m?"active":""}`,text:m?"\u2193 Newest":"\u2191 Oldest",title:"Toggle sort order"}).addEventListener("click",()=>{var C;let x=s.fileCfg;x.sortNewestFirst=!((C=x.sortNewestFirst)==null||C),s.saveFileCfg(x),s.tableSortCol=null,s.renderViewPreservingScroll()})}let a=()=>{var b,x;let m={title:s.resolveCol(Ke),category:s.resolveCol(Ye),status:s.resolveCol(Ge),notes:s.resolveCol(qe),image:s.resolveCol(Ue),anki:yi(s)};new cn(s.app,s.headers,(x=(b=s.file)==null?void 0:b.path)!=null?x:"",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=()=>rr(s),c=()=>s.backupToArchive(),d=()=>lr(s);n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u2699 Config",title:"Configure this file's columns and views"}).addEventListener("click",a),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F4F1} Mobile",title:"Generate mobile dashboard with add form"}).addEventListener("click",l),n.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",c),n.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",d),n.createEl("button",{cls:"csv-add-btn",text:"+ Add"}).addEventListener("click",()=>s.openAddModal()),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-overflow",text:"\u22EF",title:"More actions"}).addEventListener("click",m=>{let b=new Cn.Menu;b.addItem(x=>x.setTitle("Config").setIcon("settings").onClick(a)),b.addItem(x=>x.setTitle("Mobile dashboard").setIcon("smartphone").onClick(l)),b.addItem(x=>x.setTitle("Backup").setIcon("save").onClick(c)),b.addItem(x=>x.setTitle("Sync to Anki").setIcon("layers").onClick(d)),b.addSeparator(),b.addItem(x=>x.setTitle("Built 2026-07-09 11:37").setIcon("info").setDisabled(!0)),b.showAtMouseEvent(m)}),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary csv-info-btn",text:"\u24D8",title:"Built 2026-07-09 11:37 \u2014 click to confirm"}).addEventListener("click",()=>new Cn.Notice("datadeck \u2014 built 2026-07-09 11:37",4e3))}function Vc(s){return s&&typeof s=="object"&&"basename"in s?s:null}var Nc=["Author","author","By","by","Source","source","Speaker","speaker","Artist","artist","Director","director"];async function pr(s,t,e,n){var x,C,k;let i=t.split(` -`).map(S=>S.trim()).filter(Boolean),o=S=>{var y,v;return(v=(y=i.find(_=>_.startsWith(S+":")))==null?void 0:y.slice(S.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(n.sourcePath),l=(C=(x=a==null?void 0:a.parent)==null?void 0:x.path)!=null?C:"",c=Ze(r,l),d=Vc(s.vault.getAbstractFileByPath(c));if(!d){e.createEl("p",{text:`Error: File not found: ${c}`,cls:"csv-add-error"});return}let h=[],u=[];try{let S=Xt(await s.vault.read(d));h=S.headers,u=S.rows}catch(S){e.createEl("p",{text:`Error reading file: ${S}`,cls:"csv-add-error"});return}if(!u.length){e.createEl("p",{text:"No entries in file.",cls:"csv-add-error"});return}let f=o("field"),g=(k=h.find(S=>S.toLowerCase()===f.toLowerCase()))!=null?k:h[0],p=Nc.map(S=>h.find(y=>y===S)).find(Boolean),m=e.createDiv({cls:"csv-random-card"}),b=()=>{var E;m.empty();let S=u.filter(M=>{var L;return((L=M[g])!=null?L:"").trim()}),y=S.length?S:u,v=y[Math.floor(Math.random()*y.length)];m.createDiv({cls:"csv-random-text",text:v[g]||"\u2014"});let _=p?((E=v[p])!=null?E:"").trim():"";_&&m.createDiv({cls:"csv-random-sub",text:`\u2014 ${_}`});let w=m.createDiv({cls:"csv-random-foot"});w.createSpan({cls:"csv-random-src",text:d.basename}),w.createEl("button",{cls:"csv-random-btn",text:"\u21BB",title:"Another one"}).addEventListener("click",b)};b()}var Do=null;async function og(){if(Do)return Do;let s=await Promise.resolve().then(()=>(jl(),Wl));return s.Chart.register(s.LineController,s.LineElement,s.PointElement,s.LinearScale,s.CategoryScale,s.Filler,s.Tooltip),Do=s,s}async function Ul(s,t){var A,$,G;let e=s.getDateCol();if(!e){t.createEl("p",{text:"No date column detected.",cls:"csv-empty-state"});return}let n=s.getBooleanColumns(),i=s.getNotesCol(),o=s.formatDate(new Date),r=[...s.rows].sort((B,P)=>{var N,H;return((N=B[e])!=null?N:"").localeCompare((H=P[e])!=null?H:"")});s.selectedDate||(s.selectedDate=o);let a=r.find(B=>B[e]===s.selectedDate),l=s.selectedDate===o;t.addClass("csv-dashboard");let c=[...new Set([...r.map(B=>B[e]),o])].filter(Boolean).sort(),d=t.createDiv({cls:"csv-dash-nav"});d.createEl("button",{cls:"csv-dash-nav-btn csv-dash-back-btn",text:"\u25C0"}).addEventListener("click",()=>{let B=c.indexOf(s.selectedDate);if(B>0)s.selectedDate=c[B-1],s.renderView();else if(B===-1&&c.length>0){let P=c.filter(N=>N0&&(s.selectedDate=P[P.length-1],s.renderView())}});let u=d.createDiv({cls:"csv-dash-date"});l&&u.createSpan({cls:"csv-dash-today-dot"});let f=u.createEl("select",{cls:"csv-dash-date-select"});if(c.forEach(B=>{let P=f.createEl("option",{text:B,value:B});B===s.selectedDate&&(P.selected=!0)}),f.addEventListener("change",()=>{s.selectedDate=f.value,s.renderView()}),d.createEl("button",{cls:"csv-dash-nav-btn",text:"\u25B6"}).addEventListener("click",()=>{let B=c.indexOf(s.selectedDate);if(B>=0&&BN>s.selectedDate);P.length>0&&(s.selectedDate=P[0],s.renderView())}}),l||d.createEl("button",{cls:"csv-dash-today-btn",text:"Today"}).addEventListener("click",()=>{s.selectedDate=o,s.renderView()}),!a){let B=t.createDiv({cls:"csv-dash-add-section"});B.createEl("p",{text:`No entry for ${s.selectedDate}`}),B.createEl("button",{cls:"csv-dash-add-btn",text:`+ Add entry for ${s.selectedDate}`}).addEventListener("click",()=>{let N={};s.headers.forEach(H=>N[H]=""),N[e]=s.selectedDate,s.rows.push(N),s.scheduleSave(),s.renderView()})}if(a){let B=t.createDiv({cls:"csv-dash-habits"});B.createEl("h3",{text:s.selectedDate===o?"Today":s.selectedDate,cls:"csv-dash-section-title"});let P=B.createDiv({cls:"csv-dash-habits-grid"});n.forEach(H=>{let V=s.isTruthy(a[H]),U=P.createDiv({cls:`csv-dash-habit ${V?"checked":""}`}),Y=U.createEl("button",{cls:"csv-dash-habit-check",text:V?"\u25CF":"\u25CB"});U.createSpan({cls:"csv-dash-habit-label",text:H}),Y.addEventListener("click",()=>{a[H]=V?"0":"1",s.scheduleSave(),s.renderViewPreservingScroll()})});let N=n.filter(H=>s.isTruthy(a[H])).length;if(B.createDiv({cls:"csv-dash-habits-count",text:`${N} of ${n.length} complete`}),i&&((A=a[i])!=null&&A.trim())){let H=B.createDiv({cls:"csv-dash-notes-preview"});H.createEl("strong",{text:"Notes: "}),H.createSpan({text:a[i].slice(0,200)+(a[i].length>200?"\u2026":"")})}}let p=t.createDiv({cls:"csv-dash-chart-section"});p.createEl("h3",{text:"Progress",cls:"csv-dash-section-title"});let b=p.createDiv({cls:"csv-dash-chart-wrap"}).createEl("canvas",{cls:"csv-dash-chart"}),x=r.map(B=>{var N;return((N=B[e])!=null?N:"").slice(5)}),C=r.map(B=>n.filter(P=>s.isTruthy(B[P])).length);s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:k}=await og();if(!b.isConnected)return;s.chartInstance=new k(b,{type:"line",data:{labels:x,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:n.length||8,ticks:{stepSize:1}}},plugins:{tooltip:{enabled:!0}}}});let S=t.createDiv({cls:"csv-dash-stats-section"});S.createEl("h3",{text:"Stats",cls:"csv-dash-section-title"});let y=r.length,v=r.reduce((B,P)=>B+n.filter(N=>s.isTruthy(P[N])).length,0),_=y>0?(v/y).toFixed(1):"0",w=r.filter(B=>n.every(P=>s.isTruthy(B[P]))).length,T=0,E=0,M=null;for(let B of r){let P=n.filter(V=>s.isTruthy(B[V])).length,N=s.parseDate(($=B[e])!=null?$:""),H=!0;M&&N&&Math.round((N.getTime()-M.getTime())/864e5)!==1&&(H=!1),P>=1&&(H||M===null)?(E++,E>T&&(T=E)):P>=1?(E=1,E>T&&(T=E)):E=0,M=N}let L=0,I=new Date;I.setHours(0,0,0,0);let F=I;for(let B=r.length-1;B>=0;B--){let P=s.parseDate((G=r[B][e])!=null?G:"");if(!P)break;let N=Math.round((F.getTime()-P.getTime())/(1e3*60*60*24));if(L===0&&N>1||L>0&&N!==1)break;if(n.filter(V=>s.isTruthy(r[B][V])).length>=1)L++,F=P;else break}let R=S.createDiv({cls:"csv-dash-stats-bar"});R.innerHTML=`${y} days logged \xB7 ${_} avg/day \xB7 ${w} perfect days \xB7 current streak ${L}d \xB7 best streak ${T}d`;let W=t.createDiv({cls:"csv-dash-cards-section"}).createDiv({cls:"csv-dash-cards-grid"}),O=new Date().getFullYear(),K={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}"};n.map(B=>{let P=r.filter(Y=>s.isTruthy(Y[B])),N=P.length>0?P[P.length-1][e]:null,H=new Set;P.forEach(Y=>{var X;let q=s.parseDate((X=Y[e])!=null?X:"");q&&H.add(q.getFullYear())});let V=r.filter(Y=>{var X;let q=s.parseDate((X=Y[e])!=null?X:"");return q&&q.getFullYear()===O}),U=V.filter(Y=>s.isTruthy(Y[B])).length;return{habit:B,doneCount:P.length,doneThisYear:U,totalThisYear:V.length,lastDone:N,years:Array.from(H).sort()}}).sort((B,P)=>!B.lastDone&&!P.lastDone?0:B.lastDone?P.lastDone?P.lastDone.localeCompare(B.lastDone):-1:1).forEach(({habit:B,doneCount:P,doneThisYear:N,totalThisYear:H,lastDone:V,years:U})=>{var st;let Y=W.createDiv({cls:"csv-dash-habit-card"}),q=(st=K[B.toLowerCase()])!=null?st:"\u25CB",X=Y.createDiv({cls:"csv-dash-habit-card-header"});if(X.createSpan({cls:"csv-dash-habit-icon",text:q}),X.createSpan({cls:"csv-dash-habit-card-name",text:Dt(B)}),U.length>0&&Y.createDiv({cls:"csv-dash-habit-years"}).setText(U.join(" \xB7 ")),Y.createDiv({cls:"csv-dash-habit-card-thisyear",text:`${N} of ${H} complete this year`}),Y.createDiv({cls:"csv-dash-habit-card-alltime",text:`${P} of ${y} all time`}),V){let lt=s.parseDate(V),$t=lt?lt.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):V;Y.createDiv({cls:"csv-dash-habit-card-last",text:`Last logged: ${$t}`})}else Y.createDiv({cls:"csv-dash-habit-card-last",text:"Never logged"});let Z=y>0?P/y*100:0,Q=Y.createDiv({cls:"csv-dash-habit-progress"}).createDiv({cls:"csv-dash-habit-progress-bar"});Q.style.width=`${Z}%`,Y.addEventListener("click",()=>{s.selectedHabit=s.selectedHabit===B?null:B,s.renderViewPreservingScroll()}),s.selectedHabit===B&&Y.addClass("selected")}),s.selectedHabit&&n.includes(s.selectedHabit)&&rg(s,t,r,e,s.selectedHabit)}function rg(s,t,e,n,i){var T,E,M;let o=t.createDiv({cls:"csv-dash-timeline-section"}),r=o.createDiv({cls:"csv-dash-timeline-header"});r.createEl("h3",{text:`${Dt(i)} Timeline`,cls:"csv-dash-section-title"});let a=r.createEl("select",{cls:"csv-dash-year-select"}),l=new Set;e.forEach(L=>{var F;let I=s.parseDate((F=L[n])!=null?F:"");I&&l.add(I.getFullYear())}),l.add(new Date().getFullYear()),Array.from(l).sort().reverse().forEach(L=>{let I=a.createEl("option",{text:String(L),value:String(L)});L===s.timelineYear&&(I.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 d=new Map;e.forEach(L=>{var I;d.set((I=L[n])!=null?I:"",s.isTruthy(L[i]))});let h=o.createDiv({cls:"csv-dash-timeline-grid-wrap"}),u=h.createDiv({cls:"csv-dash-timeline-months"});["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].forEach(L=>u.createSpan({cls:"csv-dash-timeline-month-label",text:L}));let g=h.createDiv({cls:"csv-dash-timeline-calendar"}),p=g.createDiv({cls:"csv-dash-timeline-day-labels"});for(let L=1;L<=31;L++)p.createDiv({cls:"csv-dash-timeline-day-label",text:L%5===0||L===1?String(L):""});for(let L=0;L<12;L++){let I=g.createDiv({cls:"csv-dash-timeline-month-col"}),F=new Date(s.timelineYear,L+1,0).getDate();for(let R=1;R<=31;R++){if(R>F){I.createDiv({cls:"csv-dash-timeline-cell empty"});continue}let D=`${s.timelineYear}-${String(L+1).padStart(2,"0")}-${String(R).padStart(2,"0")}`,W=(T=d.get(D))!=null?T:!1,O=d.has(D),K=new Date(s.timelineYear,L,R)>new Date,z=I.createDiv({cls:`csv-dash-timeline-cell ${K?"future":""} ${W?"done":""} ${O&&!W?"missed":""} ${!O&&!K?"no-entry":""}`});z.title=`${D}: ${K?"Future":W?"\u2713 Done":O?"\u2717 Missed":"No entry"}`}}let m=e.filter(L=>{var F;let I=s.parseDate((F=L[n])!=null?F:"");return I&&I.getFullYear()===s.timelineYear}),b=m.filter(L=>s.isTruthy(L[i])).length,x=m.length,C=0,k=0,S=0,y=null;for(let L of e){let I=s.isTruthy(L[i]),F=s.parseDate((E=L[n])!=null?E:""),R=!0;y&&F&&Math.round((F.getTime()-y.getTime())/864e5)!==1&&(R=!1),I&&(R||y===null)?(S++,S>k&&(k=S)):I?S=1:S=0,y=F}let v=new Date;v.setHours(0,0,0,0);let _=v;for(let L=e.length-1;L>=0;L--){let I=s.parseDate((M=e[L][n])!=null?M:"");if(!I)break;let F=Math.round((_.getTime()-I.getTime())/(1e3*60*60*24));if(C===0&&F>1||C>0&&F!==1)break;if(s.isTruthy(e[L][i]))C++,_=I;else break}let w=o.createDiv({cls:"csv-dash-timeline-stats"});w.innerHTML=`${b} of ${x} in ${s.timelineYear} \xB7 current streak ${C}d \xB7 best streak ${k}d`}function Kl(s,t){var x,C,k;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 S=t.createDiv({cls:"csv-empty-state"});S.createEl("p",{text:s.searchQuery?"No matching entries found.":"No entries yet."}),s.searchQuery&&S.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 n=e[s.focusIndex],i=(x=s.titleKey())!=null?x:s.headers[0],o=s.getNotesCol(),r=s.authorKey(),a=t.createDiv({cls:"csv-focus-wrap",attr:{tabindex:"0"}}),l=S=>{s.focusIndex=(S%e.length+e.length)%e.length,s.focusNavPending=!0,s.renderView(!0)},c=a.createDiv({cls:"csv-focus-card"});c.createDiv({cls:"csv-focus-position",text:`${s.focusIndex+1} / ${e.length}`});let d=c.createDiv({cls:`csv-focus-title ${(C=s.isHighlighted)!=null&&C.call(s,n)?"csv-title-highlight":""}`,text:s.getTitle(n)});o&&(d.addClass("is-clickable"),d.title="Open entry",d.addEventListener("click",()=>s.openNoteExpander(n,o)));let h=s.getSubtitle(n);if(h&&c.createDiv({cls:"csv-focus-sub",text:h}),o&&o!==i&&((k=n[o])!=null&&k.trim())){let S=c.createDiv({cls:"csv-focus-notes"});s.renderMarkdownInto(S,n[o])}let u=new Set([i,o,r].filter(Boolean)),f=s.headers.filter(S=>{var y;return!u.has(S)&&((y=n[S])!=null?y:"").trim()});if(f.length){let S=c.createDiv({cls:"csv-focus-meta"});f.forEach(y=>{let v=S.createDiv({cls:"csv-kanban-chip"});if(v.createSpan({cls:"csv-chip-label",text:y+": "}),s.isSelectCol(y)){let _=v.createSpan({cls:"csv-chip-value csv-chip-select",text:n[y]});_.addEventListener("click",w=>{w.stopPropagation(),Ot(_,n[y],s.getColumnValues(y),T=>{n[y]=T,_.setText(T||"\u2014"),s.scheduleSave()},s.contentEl,{multi:Et(y)})})}else v.createSpan({cls:"csv-chip-value",text:n[y]})})}c.addEventListener("contextmenu",S=>s.openRowContextMenu(n,S));let g=a.createDiv({cls:"csv-focus-nav"}),p=g.createEl("button",{cls:"csv-focus-nav-btn",text:"\u2039",title:"Previous (\u2190)"}),m=g.createEl("button",{cls:"csv-focus-nav-btn csv-focus-nav-rand",text:"\u{1F500}",title:"Random entry"}),b=g.createEl("button",{cls:"csv-focus-nav-btn",text:"\u203A",title:"Next (\u2192)"});p.addEventListener("click",()=>l(s.focusIndex-1)),b.addEventListener("click",()=>l(s.focusIndex+1)),m.addEventListener("click",()=>{if(e.length<2)return;let S=s.focusIndex;for(;S===s.focusIndex;)S=Math.floor(Math.random()*e.length);l(S)}),a.addEventListener("keydown",S=>{S.key==="ArrowLeft"?(S.preventDefault(),l(s.focusIndex-1)):S.key==="ArrowRight"&&(S.preventDefault(),l(s.focusIndex+1))}),(s.focusNavPending||document.activeElement===document.body)&&(s.focusNavPending=!1,a.focus({preventScroll:!0}))}var Pt=require("obsidian"),Gl=on(ws());var ag=[{id:"table",label:"Table"},{id:"library",label:"Cards"},{id:"kanban-genre",label:"Kanban"}];function Yl(s){return s&&typeof s=="object"&&"basename"in s?s:null}function lg(s){let t=s.split(` -`).map(r=>r.trim()).filter(Boolean),e=r=>{var a,l;return(l=(a=t.find(c=>c.toLowerCase().startsWith(r+":")))==null?void 0:a.slice(r.length+1).trim())!=null?l:""},n=e("mode").toLowerCase(),i=n==="kanban"||n==="kanban-genre"?"kanban-genre":n==="cards"||n==="card"||n==="library"?"library":"table",o=parseInt(e("height"),10);return{file:e("file"),mode:i,height:Number.isFinite(o)&&o>0?o:null,collapse:e("collapse").split(",").map(r=>r.trim()).filter(Boolean)}}var Mo=class extends Pt.MarkdownRenderChild{constructor(e,n,i,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=n,this.settings=i,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}async onload(){if(this.containerEl.addClass("csv-inline-view"),!this.opts.file){this.renderError("No file specified. Use: file: yourfile.csv");return}await this.reload()&&(this.renderView(),this.registerEvent(this.app.vault.on("modify",async e=>{if(!this.file||e.path!==this.file.path)return;let n=await this.app.vault.read(this.file);if(n===this.lastWritten)return;let i=Xt(n);this.headers=i.headers,this.rows=i.rows,this.renderView()})),this.registerEvent(this.app.vault.on("rename",(e,n)=>{this.file&&n===this.file.path&&(this.file=Yl(e))})))}onunload(){this.saveTimer&&window.clearTimeout(this.saveTimer)}async reload(){let e=Yl(this.app.vault.getAbstractFileByPath(this.opts.file));if(!e)return this.renderError(`File not found: ${this.opts.file}`),!1;this.file=e;try{let n=Xt(await this.app.vault.read(e));this.headers=n.headers,this.rows=n.rows}catch(n){return this.renderError(`Error reading file: ${n instanceof Error?n.message:String(n)}`),!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=Gl.default.unparse(this.rows,{columns:this.headers});this.lastWritten=e,await this.app.vault.modify(this.file,e)}catch(e){new Pt.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 n;return((n=this.fileCfg.highlightedTitles)!=null?n:[]).includes(this.getTitle(e))}toggleHighlight(e){let n=this.getTitle(e),i=this.fileCfg,o=i.highlightedTitles?[...i.highlightedTitles]:[],r=o.indexOf(n);r>=0?o.splice(r,1):o.push(n),i.highlightedTitles=o,this.saveFileCfg(i)}resolveCol(e){for(let n of e){let i=this.headers.find(o=>o.toLowerCase()===n.toLowerCase());if(i)return i}return null}getNotesCol(){return this.fileCfg.notesColumn?this.fileCfg.notesColumn:this.resolveCol(qe)}isNotesCol(e){let n=this.getNotesCol();return n?e===n:this.settings.notesColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var i;let n=(i=this.titleKey())!=null?i:this.headers[0];return e===n||this.getDateCol()===e||Et(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(n=>n.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ge)}getCategoryCol(){var e;return this.fileCfg.categoryColumn!==void 0?this.fileCfg.categoryColumn===""?null:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ye)}titleKey(){var e,n;return this.fileCfg.titleColumn!==void 0?this.fileCfg.titleColumn===""?void 0:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(n=this.resolveCol(Ke))!=null?n: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 i;let n=this.titleKey();return(i=n?e[n]:e[this.headers[0]])!=null?i:"\u2014"}getSubtitle(e){var i;let n=this.authorKey();return n&&(i=e[n])!=null?i:""}getColumnValues(e){return Array.from(new Set(this.rows.map(n=>{var i;return(i=n[e])!=null?i:""}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn!==void 0?this.fileCfg.imageColumn===""?null:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ue)}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 n=this.rows.map(i=>{var o;return((o=i[e])!=null?o:"").toLowerCase().trim()});return Xe(n)})}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 n=/^\d{4}-\d{2}-\d{2}$/,i=this.rows.slice(0,5);return i.length>0&&i.every(a=>{var l;return n.test((l=a[e])!=null?l:"")})?e:(r=this.headers.find(a=>this.isDateCol(a)))!=null?r:null}isDateCol(e){var n;return(n=this.fileCfg.dateColumns)!=null&&n.includes(e)?!0:It(e)}getFilteredRows(){var i;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 d,h;let c=((d=a[o])!=null?d:"").localeCompare((h=l[o])!=null?h:"",void 0,{numeric:!0});return r==="asc"?c:-c})}let n=this.getDateCol();if(this.mode==="table"&&n){let o=(i=this.fileCfg.sortNewestFirst)!=null?i:!0;e=[...e].sort((r,a)=>{var c,d;let l=((c=r[n])!=null?c:"").localeCompare((d=a[n])!=null?d:"");return o?-l:l})}return e}notesFilePath(e){var a,l,c;let n=Ds(this.getTitle(e)),i=(c=(l=(a=this.file)==null?void 0:a.parent)==null?void 0:l.path)!=null?c:"",o=this.settings.notesSubfolder.trim(),r=o?i?`${i}/${o}`:o:i;return(0,Pt.normalizePath)(`${r}/${n}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}async openOrCreateNotes(e){var o;let n=this.notesFilePath(e),i=this.app.vault.getAbstractFileByPath(n);if(!i){let a=["---",...this.headers.filter(h=>!this.isNotesCol(h)&&e[h]).map(h=>`${h}: "${e[h].replace(/"/g,'\\"')}"`),"---","",`# ${this.getTitle(e)}`,"",""].join(` -`),l=this.headers.find(h=>this.isNotesCol(h)),c=a+(l&&((o=e[l])!=null&&o.trim())?e[l]:""),d=n.substring(0,n.lastIndexOf("/"));d&&!this.app.vault.getAbstractFileByPath(d)&&await this.app.vault.createFolder(d),i=await this.app.vault.create(n,c),new Pt.Notice(`Created: ${i.name}`)}await this.app.workspace.getLeaf("tab").openFile(i)}deleteWithUndo(e){let n=this.rows.indexOf(e);if(n<0)return;this.rows.splice(n,1),this.scheduleSave(),this.renderView();let i=this.getTitle(e)||"entry",o=document.createDocumentFragment();o.createSpan({text:`Deleted \u201C${i}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new Pt.Notice(o,6e3);r.addEventListener("click",()=>{r.hasAttribute("disabled")||(r.setAttribute("disabled","true"),this.rows.splice(Math.min(n,this.rows.length),0,e),this.scheduleSave(),this.renderView(),a.hide(),new Pt.Notice(`Restored \u201C${i}\u201D`,2500))})}openRowContextMenu(e,n){let i=new Pt.Menu;i.addItem(a=>a.setTitle("Open / Create Notes file").setIcon("file-text").onClick(()=>void this.openOrCreateNotes(e))),i.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&&(i.addSeparator(),a.forEach(l=>{l!==e[o]&&i.addItem(c=>c.setTitle(`Mark as: ${l}`).onClick(()=>{e[o]=l,this.scheduleSave(),this.renderView()}))}))}i.addSeparator();let r=this.isHighlighted(e);i.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderView()})),i.addSeparator(),i.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),i.showAtMouseEvent(n)}openNoteExpander(e,n){var i,o;new ts(this.app,e,n,this.headers,(o=(i=this.file)==null?void 0:i.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 Je(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 Pt.Notice(`Added: ${this.getTitle(e)}`)},{},e=>this.getBooleanColumns().includes(e),e=>this.isCategoricalCol(e),this.titleKey(),e=>this.isDateCol(e)).open()}renderSelectField(e,n,i){var a;let o=(a=n[i])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),i.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",l=>{var c;l.stopPropagation(),Ot(r,(c=n[i])!=null?c:"",this.getColumnValues(i),d=>{n[i]=d,r.setText(d||"\u2014"),this.scheduleSave()},this.contentEl)}),r}renderMarkdownInto(e,n){var i,o;Pt.MarkdownRenderer.render(this.app,n,e,(o=(i=this.file)==null?void 0:i.path)!=null?o:"",this.renderComponent)}renderViewPreservingScroll(){this.renderView()}renderView(e=!1){let n=this.containerEl;e?this.contentArea&&this.contentArea.empty():(n.empty(),this.renderToolbar(n),this.contentArea=n.createDiv({cls:"csv-content-area"}),this.opts.height&&(this.contentArea.style.maxHeight=this.opts.height+"px"));let i=this.contentArea;if(i){if(i.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){i.createDiv({cls:"csv-empty-state"}).createEl("p",{text:"This file is empty."});return}if(this.rows.length===0){let o=i.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")&&!Bt(this.asView)&&(this.mode="table"),this.mode==="library"?bn(this.asView,i):this.mode==="kanban-genre"?mn(this.asView,i):gn(this.asView,i)}}renderToolbar(e){var c,d;let n=e.createDiv({cls:"csv-toolbar csv-inline-toolbar"});n.createDiv({cls:"csv-toolbar-title",text:(d=(c=this.file)==null?void 0:c.basename)!=null?d:""}).addEventListener("click",()=>{this.file&&this.app.workspace.getLeaf("tab").openFile(this.file)});let i=n.createDiv({cls:"csv-toolbar-controls"});i.createDiv({cls:"csv-row-count",text:`${this.rows.length} entries`});let o=!!Bt(this.asView),r=i.createDiv({cls:"csv-mode-group"});ag.forEach(({id:h,label:u})=>{if((h==="library"||h==="kanban-genre")&&!o)return;r.createEl("button",{cls:`csv-mode-btn ${this.mode===h?"active":""}`,text:u}).addEventListener("click",()=>{this.mode=h,this.renderView()})});let a=i.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",h=>{this.searchQuery=h.target.value,l!==null&&window.clearTimeout(l),l=window.setTimeout(()=>{l=null,this.renderView(!0)},120)}),i.createEl("button",{cls:"csv-add-btn",text:"+ Add"}).addEventListener("click",()=>this.openAddModal())}};function ql(s,t,e,n){n("csv-view",(i,o,r)=>{var h,u,f;let a=lg(i),l=(f=(u=(h=s.vault.getAbstractFileByPath(r.sourcePath))==null?void 0:h.parent)==null?void 0:u.path)!=null?f:"",c=a.file?Ze(a.file,l):a.file,d=new Mo(o,s,t,e,{...a,file:c});r.addChild(d)})}var nn,Ss=class extends it.FileView{constructor(e,n,i){super(e);this.headers=[];this.rows=[];this.saveTimer=null;this.searchQuery="";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=n,this.persistSettings=i,this.mode=n.defaultMode,this.renderComponent=new it.Component,this.renderComponent.load()}getViewType(){return rn}getDisplayText(){var e,n;return(n=(e=this.file)==null?void 0:e.basename)!=null?n:"Card View"}getIcon(){return"table"}async onLoadFile(e){var o;try{let r=await this.app.vault.read(e),a=Xt(r);this.headers=a.headers,this.rows=a.rows}catch(r){console.error("CardView load error",r),this.headers=[],this.rows=[],new it.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 n=this.mode==="kanban-genre"||this.mode==="library",i=this.mode==="dashboard";(n&&!Bt(this)||i&&!this.hasDateColumn()||this.mode==="travel"&&!this.isTravelFile()||this.mode==="stats"&&!pn(this)||this.mode==="tasks"&&!ss(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=Xl.default.unparse(this.rows,{columns:this.headers});await this.app.vault.modify(this.file,e)}catch(e){console.error("CardView save error",e),new it.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 n;return((n=this.fileCfg.highlightedTitles)!=null?n:[]).includes(this.getTitle(e))}toggleHighlight(e){let n=this.getTitle(e),i=this.fileCfg,o=i.highlightedTitles?[...i.highlightedTitles]:[],r=o.indexOf(n);r>=0?o.splice(r,1):o.push(n),i.highlightedTitles=o,this.saveFileCfg(i)}addColumn(e){let n=e.trim();return n?this.headers.some(i=>i.toLowerCase()===n.toLowerCase())?`"${n}" already exists.`:(this.headers.push(n),this.rows.forEach(i=>{i[n]=""}),this.scheduleSave(),this.renderViewPreservingScroll(),null):"Column name can't be empty."}removeColumn(e){this.headers=this.headers.filter(i=>i!==e),this.rows.forEach(i=>{delete i[e]});let n=this.fileCfg;n.categoryColumn===e&&(n.categoryColumn=void 0),n.statusColumn===e&&(n.statusColumn=void 0),n.notesColumn===e&&(n.notesColumn=void 0),n.ankiFrontCol===e&&(n.ankiFrontCol=void 0),n.kanbanGroupCol===e&&(n.kanbanGroupCol=void 0),n.habitColumns&&(n.habitColumns=n.habitColumns.filter(i=>i!==e)),n.cardFields&&(n.cardFields=n.cardFields.filter(i=>i!==e)),n.categoricalColumns&&(n.categoricalColumns=n.categoricalColumns.filter(i=>i!==e)),this.saveFileCfg(n),this.scheduleSave(),this.renderViewPreservingScroll()}resolveCol(e){for(let n of e){let i=this.headers.find(o=>o.toLowerCase()===n.toLowerCase());if(i)return i}return null}getNotesCol(){return this.fileCfg.notesColumn?this.fileCfg.notesColumn:this.resolveCol(qe)}isNotesCol(e){let n=this.getNotesCol();return n?e===n:this.settings.notesColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var i;let n=(i=this.titleKey())!=null?i:this.headers[0];return e===n||this.isDateCol(e)||Et(e)?!1:this.fileCfg.categoricalColumns?this.fileCfg.categoricalColumns.includes(e):this.isSelectCol(e)||qt(this.getColumnValues(e).length)}autoDetectCategoricalColumns(){var n;let e=(n=this.titleKey())!=null?n:this.headers[0];return this.headers.filter(i=>i===e||this.isDateCol(i)||Et(i)||this.isNotesCol(i)?!1:this.isSelectCol(i)||qt(this.getColumnValues(i).length))}isDateCol(e){var n;return(n=this.fileCfg.dateColumns)!=null&&n.includes(e)?!0:It(e)}getStatusCol(){var e;return this.fileCfg.statusColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ge)}getCategoryCol(){var e;return this.fileCfg.categoryColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ye)}titleKey(){var e,n;return this.fileCfg.titleColumn?(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(n=this.resolveCol(Ke))!=null?n: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 i;let n=this.titleKey();return(i=n?e[n]:e[this.headers[0]])!=null?i:"\u2014"}getSubtitle(e){var i;let n=this.authorKey();return n&&(i=e[n])!=null?i:""}getColumnValues(e){return Array.from(new Set(this.rows.map(n=>{var i;return(i=n[e])!=null?i:""}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ue)}notesFilePath(e){var a,l,c;let n=Ds(this.getTitle(e)),i=(c=(l=(a=this.file)==null?void 0:a.parent)==null?void 0:l.path)!=null?c:"",o=this.settings.notesSubfolder.trim(),r=o?i?`${i}/${o}`:o:i;return(0,it.normalizePath)(`${r}/${n}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}deleteWithUndo(e){let n=this.rows.indexOf(e);if(n<0)return;this.rows.splice(n,1),this.scheduleSave(),this.renderViewPreservingScroll();let i=this.getTitle(e)||"entry",o=document.createDocumentFragment();o.createSpan({text:`Deleted \u201C${i}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new it.Notice(o,6e3);r.addEventListener("click",()=>{if(r.hasAttribute("disabled"))return;r.setAttribute("disabled","true");let l=Math.min(n,this.rows.length);this.rows.splice(l,0,e),this.scheduleSave(),this.renderViewPreservingScroll(),a.hide(),new it.Notice(`Restored \u201C${i}\u201D`,2500)})}openRowContextMenu(e,n){let i=new it.Menu;i.addItem(a=>a.setTitle("Open / Create Notes file").setIcon("file-text").onClick(()=>this.openOrCreateNotes(e))),i.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&&(i.addSeparator(),a.forEach(l=>{l!==e[o]&&i.addItem(c=>c.setTitle(`Mark as: ${l}`).onClick(()=>{e[o]=l,this.scheduleSave(),this.renderViewPreservingScroll()}))}))}i.addSeparator();let r=this.isHighlighted(e);i.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderViewPreservingScroll()})),i.addSeparator(),i.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),i.showAtMouseEvent(n)}async openOrCreateNotes(e){var o,r;let n=this.notesFilePath(e),i=this.app.vault.getAbstractFileByPath(n);if(!i){let a={},l=ss(this)?Ci(this):null,c=l?((o=e[l])!=null?o:"").split(",").map(g=>Io(g.trim())).filter(Boolean).map(g=>`project-${g}`):[];c.length&&(a.tags=c);for(let g of this.headers)!this.isNotesCol(g)&&e[g]&&(a[g]=e[g]);this.file&&!Object.keys(a).some(g=>g.toLowerCase()==="source")&&(a.source=`[[${this.file.path}]]`);let d=["---",(0,it.stringifyYaml)(a).trimEnd(),"---","",`# ${this.getTitle(e)}`,"",""].join(` -`),h=this.headers.find(g=>this.isNotesCol(g)),u=d+(h&&((r=e[h])!=null&&r.trim())?e[h]:""),f=n.substring(0,n.lastIndexOf("/"));f&&!this.app.vault.getAbstractFileByPath(f)&&await this.app.vault.createFolder(f),i=await this.app.vault.create(n,u),new it.Notice(`Created: ${i.name}`)}await this.app.workspace.getLeaf("tab").openFile(i)}openNoteExpander(e,n){var i,o;new ts(this.app,e,n,this.headers,(o=(i=this.file)==null?void 0:i.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,c,d,h,u;let e=this.contentEl,n=e.querySelector(".csv-content-area"),i=e.querySelector(".csv-table-wrapper"),o=e.querySelector(".csv-kanban-board"),r={contentTop:(l=n==null?void 0:n.scrollTop)!=null?l:0,contentLeft:(c=n==null?void 0:n.scrollLeft)!=null?c:0,tableLeft:(d=i==null?void 0:i.scrollLeft)!=null?d:0,tableTop:(h=i==null?void 0:i.scrollTop)!=null?h:0,boardLeft:(u=o==null?void 0:o.scrollLeft)!=null?u:0,cols:new Map};e.querySelectorAll(".csv-kanban-col").forEach(f=>{var m,b;let g=(b=(m=f.querySelector(".csv-kanban-col-title"))==null?void 0:m.textContent)!=null?b:"",p=f.querySelector(".csv-kanban-col-body");g&&p&&r.cols.set(g,p.scrollTop)}),this.renderView();let a=()=>{let f=this.contentEl.querySelector(".csv-content-area"),g=this.contentEl.querySelector(".csv-table-wrapper"),p=this.contentEl.querySelector(".csv-kanban-board");f&&(f.scrollTop=r.contentTop,f.scrollLeft=r.contentLeft),g&&(g.scrollLeft=r.tableLeft,g.scrollTop=r.tableTop),p&&(p.scrollLeft=r.boardLeft),this.contentEl.querySelectorAll(".csv-kanban-col").forEach(m=>{var k,S;let b=(S=(k=m.querySelector(".csv-kanban-col-title"))==null?void 0:k.textContent)!=null?S:"",x=m.querySelector(".csv-kanban-col-body"),C=r.cols.get(b);x&&C!=null&&(x.scrollTop=C)})};a(),requestAnimationFrame(()=>{a(),requestAnimationFrame(a)}),setTimeout(a,50)}openAddModal(){let e={};if(ss(this)){let n=vn(this);n&&(e[n]=["Task","Note","Idea"]);let i=yn(this);i&&(e[i]=["Low","Medium","High"])}new Je(this.app,this.headers,this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),n=>{this.rows.push(n),this.scheduleSave(),this.renderViewPreservingScroll(),new it.Notice(`Added: ${this.getTitle(n)}`)},e,n=>this.getBooleanColumns().includes(n),n=>this.isCategoricalCol(n),this.titleKey(),n=>this.isDateCol(n)).open()}renderSelectField(e,n,i){var a;let o=(a=n[i])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),i.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",l=>{var c;l.stopPropagation(),Ot(r,(c=n[i])!=null?c:"",this.getColumnValues(i),d=>{n[i]=d,r.setText(d||"\u2014"),r.className=`csv-select-chip ${d?"":"empty"}`,i.toLowerCase()==="status"&&d&&r.addClass(`status-chip-${d.toLowerCase().replace(/\s+/g,"-")}`),this.scheduleSave()},this.contentEl,{multi:Et(i)})}),r}renderView(e=!1){var o;let n=this.contentEl;e?this.contentArea&&this.contentArea.empty():(n.empty(),n.addClass("datadeck-root"),this.renderComponent.unload(),this.renderComponent=new it.Component,this.renderComponent.load(),gr(this,n),this.contentArea=n.createDiv({cls:"csv-content-area"}),this.installTouchScrollGuard(this.contentArea));let i=this.contentArea;if(i){if(i.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){let r=i.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=i.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"?Xo(i,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"?Ul(this,i):this.mode==="library"?bn(this,i):this.mode==="kanban-genre"?mn(this,i):this.mode==="stats"?sr(this,i):this.mode==="focus"?Kl(this,i):this.mode==="tasks"?fr(this,i):gn(this,i)}}installTouchScrollGuard(e){if(!matchMedia("(pointer: coarse)").matches)return;let n=0,i=0,o=!1;e.addEventListener("touchstart",r=>{r.touches.length===1&&(n=r.touches[0].clientX,i=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-n),l=Math.abs(r.touches[0].clientY-i);(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:"",n=e?`${e}/Archive`:"Archive";await this.app.vault.adapter.exists(n)||await this.app.vault.adapter.mkdir(n);let i=new Date().toISOString().slice(0,10),o=`${n}/${this.file.basename}_${i}.${this.file.extension}`;if(await this.app.vault.adapter.exists(o)){new it.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 it.Notice(`Backed up to ${o}`)}hasDateColumn(){return this.getDateCol()!==null}isTravelFile(){let e=new Set(this.headers.map(n=>n.toLowerCase()));return e.has("country")&&e.has("date_entered")&&e.has("date_left")&&e.has("source")}async loadMapSvg(){if(nn!==void 0)return nn;let e=(0,it.normalizePath)(`${this.app.vault.configDir}/plugins/datadeck/world-map.svg`);try{nn=await this.app.vault.adapter.read(e)}catch(n){nn=null}return nn}getFilteredRows(){var i;let e=this.rows;if(this.searchQuery.trim()){let o=this.searchQuery.toLowerCase().trim();e=e.filter(r=>this.headers.some(a=>{var c;return((c=r[a])!=null?c:"").toLowerCase().includes(o)}))}if(this.mode==="table"&&this.tableSortCol&&this.headers.includes(this.tableSortCol))return Fo(e,this.tableSortCol,this.tableSortDir);let n=this.getDateCol();if(this.mode==="table"&&n){let o=(i=this.fileCfg.sortNewestFirst)!=null?i:!0;e=[...e].sort((r,a)=>{var h,u;let l=(h=r[n])!=null?h:"",c=(u=a[n])!=null?u:"",d=l.localeCompare(c);return o?-d:d})}return e}getDateCol(){if(this.headers.length===0)return null;let e=this.headers[0],n=e.toLowerCase();if(["date","day","datum"].includes(n))return e;let i=this.rows.slice(0,5),o=/^\d{4}-\d{2}-\d{2}$/;return i.length>0&&i.every(a=>{var l;return o.test((l=a[e])!=null?l:"")})?e:null}getBooleanColumns(){return this.fileCfg.habitColumns?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.autoDetectBooleanColumns()}cleanupBooleanColumn(e){let n=0;return this.rows.forEach(i=>{var r;let o=this.isTruthy((r=i[e])!=null?r:"")?"1":"0";i[e]!==o&&n++,i[e]=o}),n>0&&(this.scheduleSave(),this.renderViewPreservingScroll()),n}autoDetectBooleanColumns(){return this.headers.filter(e=>{if(e===this.getDateCol()||this.isNotesCol(e))return!1;let n=this.rows.map(i=>{var o;return((o=i[e])!=null?o:"").toLowerCase().trim()});return Xe(n)})}parseDate(e){let n=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);return n?new Date(parseInt(n[1]),parseInt(n[2])-1,parseInt(n[3])):null}formatDate(e){let n=e.getFullYear(),i=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${n}-${i}-${o}`}isTruthy(e){return Qe(e)}renderMarkdownInto(e,n){var i,o;it.MarkdownRenderer.render(this.app,n,e,(o=(i=this.file)==null?void 0:i.path)!=null?o:"",this.renderComponent)}cycleMode(){let e=xn(this);if(e.length<2)return;let n=e.findIndex(i=>i.id===this.mode);this.mode=e[(n+1)%e.length].id,this.renderView()}onunload(){this.renderComponent.unload(),this.saveTimer&&window.clearTimeout(this.saveTimer)}},cg=[{id:"tasks",command:"Create tasks file",defaultName:"Tasks",headers:["Title","Priority","Notes","Due","Status"],mode:"tasks",configOverrides:{categoricalColumns:["Priority"],dateColumns:["Due"],habitColumns:["Status"],statusColumn:"Status",notesColumn:"Notes"}},{id:"travel",command:"Create travel file",defaultName:"Travel",headers:["Country","date_entered","date_left","source","Notes"],mode:"travel"},{id:"habits",command:"Create habit tracker file",defaultName:"Habits",headers:["Date","Exercise","Meditate","Read","Notes"],mode:"dashboard"}],ri=class extends it.Plugin{constructor(){super(...arguments);this.settings=hi}async onload(){await this.loadSettings(),this.registerView(rn,e=>new Ss(e,this.settings,()=>this.saveSettings())),this.registerExtensions(["csv"],rn),this.addSettingTab(new fn(this.app,this)),this.registerMarkdownCodeBlockProcessor("csv-add",async(e,n,i)=>{await Zo(this.app,e.trim(),n,i,this.settings.fileConfigs)}),this.registerMarkdownCodeBlockProcessor("csv-random",async(e,n,i)=>{await pr(this.app,e.trim(),n,i)}),ql(this.app,this.settings,()=>this.saveSettings(),(e,n)=>this.registerMarkdownCodeBlockProcessor(e,n)),this.addCommand({id:"add-entry",name:"Add entry to current CSV",checkCallback:e=>{let n=this.app.workspace.getActiveViewOfType(Ss);return n?(e||n.openAddModal(),!0):!1}}),this.addCommand({id:"cycle-view-mode",name:"Cycle view mode",checkCallback:e=>{let n=this.app.workspace.getActiveViewOfType(Ss);return n?(e||n.cycleMode(),!0):!1}});for(let e of cg)this.addCommand({id:`create-${e.id}`,name:e.command,callback:()=>this.createTemplateFile(e)});this.registerEvent(this.app.vault.on("rename",async(e,n)=>{e instanceof it.TFile&&e.extension==="csv"&&this.settings.fileConfigs[n]&&(Ho(this.settings.fileConfigs,n,e.path),await this.saveSettings())})),this.registerEvent(this.app.vault.on("delete",async e=>{e instanceof it.TFile&&this.settings.fileConfigs[e.path]&&(delete this.settings.fileConfigs[e.path],await this.saveSettings())})),this.registerMarkdownCodeBlockProcessor("csv-refresh",(e,n,i)=>{let o=n.createEl("button",{cls:"csv-refresh-btn"});o.innerHTML="\u21BB refresh",o.addEventListener("click",async()=>{let r=i.sourcePath,a=this.app.vault.getAbstractFileByPath(r);if(a instanceof it.TFile){let l=this.app.workspace.activeLeaf;l&&await l.openFile(a,{state:{mode:"preview"}})}})})}async createTemplateFile(e){new dn(this.app,e.command,e.defaultName,"File name (without .csv)",async n=>{let i=this.app.workspace.getActiveFile(),o=i!=null&&i.parent&&i.parent.path!=="/"?`${i.parent.path}/`:"",r=Ds(n),a=(0,it.normalizePath)(`${o}${r}.csv`);for(let d=2;this.app.vault.getAbstractFileByPath(a);d++)a=(0,it.normalizePath)(`${o}${r} ${d}.csv`);let l=await this.app.vault.create(a,e.headers.join(",")+` -`),c=this.settings.fileConfigs[l.path]||{};this.settings.fileConfigs[l.path]={...c,defaultMode:e.mode,...e.configOverrides||{}},await this.saveSettings(),await this.app.workspace.getLeaf("tab").openFile(l),new it.Notice(`Created: ${l.name}`)}).open()}async loadSettings(){var e;this.settings=Object.assign({},hi,await this.loadData()),this.settings.residencyRules=JSON.parse(JSON.stringify((e=this.settings.residencyRules)!=null?e:[]))}async saveSettings(){await this.saveData(this.settings)}}; +${_i}`}async function br(s){var c,d,h,u,f,p,g,m,b,x;if(!s.file)return;let t=(d=(c=s.file.parent)==null?void 0:c.path)!=null?d:"",e=t?`${t}/Mobile`:"Mobile";await s.app.vault.adapter.exists(e)||await s.app.vault.adapter.mkdir(e);let n=`${e}/${s.file.basename}.md`,i=s.file.path,o=s.getDateCol(),r=s.getCategoryCol(),a="../"+s.file.name,l;if(o){let C=s.getBooleanColumns();l=pr({filePath:a,csvPath:i,habitCols:C,labels:C.map(Mt),dateCol:o})}else if(r){let C=(f=(u=(h=s.titleKey())!=null?h:s.resolveCol(["Quote","quote","Headline","headline","Phrase","phrase"]))!=null?u:s.headers[0])!=null?f:"Title";l=gr({filePath:a,csvPath:i,titleKey:C,categoryCol:r,statusCol:(p=s.getStatusCol())!=null?p:"Status",authorKey:(g=s.authorKey())!=null?g:"",yearCol:(m=s.resolveCol(["Year","year","Released","released"]))!=null?m:"",ratingCol:(b=s.resolveCol(["Rating","rating","Score","score","Stars","stars"]))!=null?b:"",themeCol:(x=s.resolveCol(["Theme","theme","Subgenre","subgenre","Mood","mood"]))!=null?x:"",compactGrid:s.titleKey()!==null})}else l=mr({filePath:a,csvPath:i,headers:s.headers});try{let C=s.app.vault.getAbstractFileByPath(n);C&&C instanceof Le.TFile?(await s.app.vault.modify(C,l),new Le.Notice(`Updated: ${n}`)):(await s.app.vault.create(n,l),new Le.Notice(`Created: ${n}`))}catch(C){let E=s.app.vault.getAbstractFileByPath(n);E instanceof Le.TFile&&(await s.app.vault.modify(E,l),new Le.Notice(`Updated: ${n}`))}}var pe=require("obsidian"),Kc="http://127.0.0.1:8765",Yc=6;async function vr(s,t){let e;try{e=await(0,pe.requestUrl)({url:Kc,method:"POST",contentType:"application/json",body:JSON.stringify({action:s,version:Yc,params:t}),throw:!1})}catch(i){throw new Error("Couldn't reach Anki. Is the desktop app open with the AnkiConnect add-on installed?")}let n=e.json;if(n.error)throw new Error(n.error);return n.result}function Ei(s){var t,e,n;return(n=(e=(t=s.titleKey())!=null?t:s.resolveCol(["Quote","Headline","Phrase","Term","Word","Question","Front","Name","Title"]))!=null?e:s.headers[0])!=null?n:null}function Gc(s){let t=s.fileCfg.ankiFrontCol;return t&&s.headers.includes(t)?t:Ei(s)}function Si(s){return s.replace(/&/g,"&").replace(//g,">")}function qc(s,t,e){return s.headers.filter(n=>{var i;return n!==e&&((i=t[n])!=null?i:"").trim()}).map(n=>`${Si(n)}: ${Si(t[n].trim())}`).join("
")}async function yr(s){if(!s.file)return;let t=Gc(s);if(!t){new pe.Notice("No column to use as the Anki card front.",6e3);return}let e=s.file.basename,n=s.rows.filter(o=>{var r;return((r=o[t])!=null?r:"").trim()});if(!n.length){new pe.Notice(`Nothing to sync \u2014 no rows with a "${t}" value.`,6e3);return}let i=new pe.Notice(`Syncing ${n.length} cards to Anki deck \u201C${e}\u201D\u2026`,0);try{await vr("createDeck",{deck:e});let o=n.map(c=>({deckName:e,modelName:"Basic",fields:{Front:Si(c[t].trim()),Back:qc(s,c,t)},options:{allowDuplicate:!1,duplicateScope:"deck"},tags:["datadeck"]})),r=await vr("addNotes",{notes:o}),a=r.filter(c=>c!=null).length,l=r.length-a;i.hide(),new pe.Notice(`Anki sync: ${a} added${l?`, ${l} already present`:""} (deck \u201C${e}\u201D).`,6e3)}catch(o){i.hide(),new pe.Notice(`Anki sync failed: ${o instanceof Error?o.message:String(o)}`,8e3)}}var Lo=null;async function _s(){if(Lo)return Lo;let s=await Promise.resolve().then(()=>(Gl(),Yl));return s.Chart.register(s.LineController,s.ScatterController,s.LineElement,s.PointElement,s.LinearScale,s.CategoryScale,s.Filler,s.Tooltip,s.Legend),Lo=s,s}var ql={pi:Math.PI,e:Math.E},Xl={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},Ao={min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2};function mp(s){let t=[],e=0;for(;e{var u;return(u=e[n])!=null?u:null},o=()=>{var u;return(u=e[n++])!=null?u:null};function r(){let u=a();for(;;){let f=i();if((f==null?void 0:f.kind)==="op"&&(f.op==="+"||f.op==="-")){n++;let p=a(),g=u;u=f.op==="+"?b=>g(b)+p(b):b=>g(b)-p(b)}else return u}}function a(){let u=l();for(;;){let f=i();if((f==null?void 0:f.kind)==="op"&&(f.op==="*"||f.op==="/"||f.op==="%")){n++;let p=l(),g=u,m=f.op;u=m==="*"?b=>g(b)*p(b):m==="/"?b=>g(b)/p(b):b=>g(b)%p(b)}else if(f&&(f.kind==="num"||f.kind==="ident"||f.kind==="lparen")){let p=l(),g=u;u=m=>g(m)*p(m)}else return u}}function l(){let u=i();if((u==null?void 0:u.kind)==="op"&&u.op==="-"){n++;let f=l();return p=>-f(p)}return(u==null?void 0:u.kind)==="op"&&u.op==="+"?(n++,l()):c()}function c(){let u=d(),f=i();if((f==null?void 0:f.kind)==="op"&&f.op==="^"){n++;let p=l();return g=>Math.pow(u(g),p(g))}return u}function d(){var f,p,g,m,b;let u=o();if(!u)throw new Error("Unexpected end of formula");if(u.kind==="num"){let x=u.value;return()=>x}if(u.kind==="lparen"){let x=r();if(((f=o())==null?void 0:f.kind)!=="rparen")throw new Error("Missing closing )");return x}if(u.kind==="ident"){if(u.name==="x")return C=>C;if(u.name in ql){let C=ql[u.name];return()=>C}let x=((p=i())==null?void 0:p.kind)==="lparen";if(u.name in Xl||u.name in Ao){if(!x)throw new Error(`${u.name} needs parentheses, e.g. ${u.name}(x)`);n++;let C=r();if(u.name in Ao){if(((g=o())==null?void 0:g.kind)!=="comma")throw new Error(`${u.name}(a, b) needs two arguments`);let S=r();if(((m=o())==null?void 0:m.kind)!=="rparen")throw new Error("Missing closing )");let y=Ao[u.name];return v=>y(C(v),S(v))}if(((b=o())==null?void 0:b.kind)!=="rparen")throw new Error("Missing closing )");let E=Xl[u.name];return S=>E(C(S))}throw new Error(`Unknown name "${u.name}" \u2014 use x, pi, e, or a function like sin()`)}throw new Error(`Unexpected "${u.kind==="op"?u.op:u.kind}"`)}let h=r();if(n{var o;let n=0,i=0;for(let r of t){let a=((o=r[e])!=null?o:"").trim();a&&(n++,Po(a)!==null&&i++)}return i>=2&&i/n>=.7})}function bp(s){let t=s.length;if(t<2)return null;let e=0,n=0,i=0,o=0,r=0;for(let f of s)e+=f.x,n+=f.y,i+=f.x*f.x,o+=f.x*f.y,r+=f.y*f.y;let a=t*i-e*e;if(a===0)return null;let l=(t*o-e*n)/a,c=(n-l*e)/t,d=n/t,h=0,u=0;for(let f of s){let p=f.y-(l*f.x+c);h+=p*p,u+=(f.y-d)*(f.y-d)}return{slope:l,intercept:c,r2:u===0?1:1-h/u}}function Ro(s){var n;let t=(n=s.ownerDocument.defaultView)==null?void 0:n.getComputedStyle(s),e=(i,o)=>(t==null?void 0:t.getPropertyValue(i).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")}}var on=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)},Zl=s=>{let t=new Date(s);return isNaN(t.getTime())?String(s):t.toISOString().slice(0,10)};function Oo(s,t){var d,h;let e=[],n=s.connect?[...s.points].sort((u,f)=>u.x-f.x):s.points;n.length&&e.push({type:s.connect?"line":"scatter",label:s.yLabel,data:n,backgroundColor:t.accent,borderColor:t.accent,borderWidth:1.5,pointRadius:s.connect?3:4,pointHoverRadius:6,tension:.3});let i=n.map(u=>u.x),o=n.length?Math.min(...i):(d=s.xMin)!=null?d:0,r=n.length?Math.max(...i):(h=s.xMax)!=null?h:10,a=null;if(s.fit==="linear"){let u=bp(n);if(u&&r>o){e.push({type:"line",label:"Best fit",data:[{x:o,y:u.slope*o+u.intercept},{x:r,y:u.slope*r+u.intercept}],borderColor:t.fitLine,borderDash:[6,4],borderWidth:1.5,pointRadius:0,pointHitRadius:0});let f=` \xB7 R\xB2 = ${(Math.round(u.r2*1e3)/1e3).toFixed(3)}`;if(s.xIsDate){let p=u.slope*864e5;a=`Trend: ${p>=0?"+":""}${on(p)} ${s.yLabel}/day${f}`}else{let p=u.intercept>=0?"+":"\u2212";a=`y = ${on(u.slope)}x ${p} ${on(Math.abs(u.intercept))}${f}`}}}let l=null;if(s.formula.trim())try{let u=Ql(s.formula),f=[],p=160;for(let g=0;g<=p;g++){let m=o+(r-o)*g/p,b=u(m);Number.isFinite(b)&&f.push({x:m,y:b})}f.length&&e.push({type:"line",label:s.formula.trim(),data:f,borderColor:t.formula,borderWidth:1.5,pointRadius:0,pointHitRadius:0,tension:0})}catch(u){l=u instanceof Error?u.message:String(u)}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:u=>Zl(Number(u)),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.length>1,labels:{color:t.muted,boxWidth:12}},tooltip:{callbacks:{label:u=>{let f=u.raw,p=s.xIsDate?Zl(f.x):on(f.x);return`${f.label?`${f.label}: `:""}(${p}, ${on(f.y)})`}}}}}},fitText:a,formulaError:l}}var ii="(row number)";function Fo(s,t,e,n,i,o){let r=[],a=0;return s.forEach((l,c)=>{var u,f,p;let d=Po((u=l[e])!=null?u:""),h;if(t===ii)h=c+1;else if(n){let g=i((f=l[t])!=null?f:"");h=g?g.getTime():null}else h=Po((p=l[t])!=null?p:"");if(h===null||d===null){a++;return}r.push({x:h,y:d,label:o(l)})}),{points:r,skipped:a}}function ri(s){return s.rows.length>=2&&oi(s.headers,s.rows).length>=1}async function Jl(s,t){var L,I;let e=s.getFilteredRows(),n=oi(s.headers,s.rows);if(!n.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 i=s.fileCfg,o=s.getDateCol(),r=[...o?[o]:[],...n.filter(P=>P!==o),ii],a=i.chartXCol&&r.includes(i.chartXCol)?i.chartXCol:r[0],l=n,c=i.chartYCol&&l.includes(i.chartYCol)?i.chartYCol:(L=l.find(P=>P!==a))!=null?L:l[0],d=i.chartFit==="linear"?"linear":"none",h=(I=i.chartFormula)!=null?I:"",u=t.createDiv({cls:"csv-chart-view"}),f=u.createDiv({cls:"csv-chart-controls"}),p=P=>{s.saveFileCfg({...s.fileCfg,...P}),s.renderViewPreservingScroll()},g=(P,R,D,W)=>{let O=f.createDiv({cls:"csv-chart-control"});O.createSpan({cls:"csv-chart-control-label",text:P});let j=O.createEl("select",{cls:"csv-chart-select",attr:{"aria-label":P}});return R.forEach($=>{let A=j.createEl("option",{text:$,value:$});$===D&&(A.selected=!0)}),j.addEventListener("change",()=>W(j.value)),j};g("X",r,a,P=>p({chartXCol:P})),g("Y",l,c,P=>p({chartYCol:P})),f.createEl("button",{cls:`csv-cfg-btn csv-chart-fit-btn ${d==="linear"?"active":""}`,text:"Best fit",title:"Toggle a least-squares fit line"}).addEventListener("click",()=>p({chartFit:d==="linear"?"none":"linear"}));let b=f.createDiv({cls:"csv-chart-control csv-chart-formula-wrap"});b.createSpan({cls:"csv-chart-control-label",text:"y ="});let x=b.createEl("input",{cls:"csv-chart-formula-input",type:"text",value:h,placeholder:"overlay, e.g. 2x + 1",attr:{spellcheck:"false",autocomplete:"off",enterkeyhint:"done"}}),C=()=>{x.value.trim()!==h.trim()&&p({chartFormula:x.value})};x.addEventListener("change",C),x.addEventListener("keydown",P=>{P.key==="Enter"&&(P.preventDefault(),x.blur())});let E=a!==ii&&(a===o||s.isDateCol(a)),{points:S,skipped:y}=Fo(e,a,c,E,P=>s.parseDate(P),P=>s.getTitle(P)),v=u.createDiv({cls:"csv-chart-wrap"}),_=v.createEl("canvas",{cls:"csv-chart-canvas"}),w=u.createDiv({cls:"csv-chart-footer"});if(!S.length){v.remove(),w.remove(),u.createEl("p",{text:`No rows with both "${a}" and "${c}" values to plot.`,cls:"csv-empty-state"});return}let k=Oo({points:S,xIsDate:E,xLabel:a===ii?"row":a,yLabel:c,connect:E,fit:d,formula:h},Ro(t));k.fitText&&w.createSpan({cls:"csv-chart-fit-text",text:k.fitText}),k.formulaError&&w.createSpan({cls:"csv-chart-formula-error",text:`formula: ${k.formulaError}`}),y>0&&w.createSpan({cls:"csv-chart-skipped",text:`${y} row${y===1?"":"s"} skipped (no numeric value)`}),s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:M}=await _s();_.isConnected&&(s.chartInstance=new M(_,k.config))}function ai(s){return s.resolveCol(["Type","type","Kind","kind","Item","item"])}function Vo(s){var t;return(t=s.resolveCol(["Project","project","Projects","projects","Area","area"]))!=null?t:$t(s)}function sc(s){return s.resolveCol(["Due","due","Deadline","deadline","Due Date","Due date","due date"])}function li(s){return s.resolveCol(["Priority","priority","Prio","prio","Importance","importance"])}var vp=["task","todo","to-do","action","note","idea","reference","ref"],nc=["done","complete","completed","finished","closed","resolved","yes","x","\u2713","true"],yp={high:0,med:1,medium:1,normal:1,low:2};function Ss(s){if(sc(s)||li(s))return!0;let t=ai(s);return t?s.rows.some(e=>{var n;return vp.includes(((n=e[t])!=null?n:"").trim().toLowerCase())}):!1}function Io(s,t,e){var n;return e?nc.includes(((n=t[e])!=null?n:"").trim().toLowerCase()):!1}function tc(s){let t=yp[(s!=null?s:"").trim().toLowerCase()];return t===void 0?3:t}function ec(s){return(s!=null?s:"").trim()?0:1}function xp(){return new Date().toISOString().slice(0,10)}function Cp(s,t){let e=new Map;s.rows.forEach(o=>{var a,l;let r=((a=o[t])!=null?a:"").trim();r&&nc.includes(r.toLowerCase())&&e.set(r,((l=e.get(r))!=null?l:0)+1)});let n="done",i=0;return e.forEach((o,r)=>{o>i&&(n=r,i=o)}),n}function ic(s,t){var T,k;let e=Vo(s),n=ai(s),i=s.getStatusCol(),o=sc(s),r=li(s),a=(T=s.titleKey())!=null?T:s.headers[0],l=t.createDiv({cls:"csv-library-filters"}),c=new Set;e&&s.rows.forEach(M=>{var L;((L=M[e])!=null?L:"").split(",").map(I=>I.trim()).filter(Boolean).forEach(I=>c.add(I))});let d=l.createEl("select",{cls:"csv-library-filter-select"});d.createEl("option",{text:e?"All projects":"All",value:"all"}),Array.from(c).sort().forEach(M=>d.createEl("option",{text:M,value:M})),d.value=s.taskProjectFilter;let h=new Set;n&&s.rows.forEach(M=>{var I;let L=((I=M[n])!=null?I:"").trim();L&&h.add(L)});let u=null;h.size>0&&(u=l.createEl("select",{cls:"csv-library-filter-select"}),u.createEl("option",{text:"All types",value:"all"}),Array.from(h).sort().forEach(M=>u.createEl("option",{text:M,value:M})),u.value=s.taskTypeFilter);let f=()=>{s.taskProjectFilter=d.value,u&&(s.taskTypeFilter=u.value),s.renderView(!0)};d.addEventListener("change",f),u==null||u.addEventListener("change",f);let p=s.searchQuery.toLowerCase().trim(),g=s.rows.filter(M=>{var L,I;return!(s.taskProjectFilter!=="all"&&e&&!((L=M[e])!=null?L:"").split(",").map(R=>R.trim().toLowerCase()).includes(s.taskProjectFilter.toLowerCase())||s.taskTypeFilter!=="all"&&n&&((I=M[n])!=null?I:"").trim().toLowerCase()!==s.taskTypeFilter.toLowerCase()||p&&!s.headers.some(P=>{var R;return((R=M[P])!=null?R:"").toLowerCase().includes(p)}))});(s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"||p)&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${g.length} of ${s.rows.length} entries`});let m={},b=M=>{var I;return e&&((I=M[e])!=null?I:"").split(",").map(P=>P.trim()).filter(Boolean)[0]||"\u2014"};g.forEach(M=>{var R,D,W;let L=n?((R=M[n])!=null?R:"").trim():"",I=n?L||"\u2014":"Tasks",P=b(M);m[I]||(m[I]={}),((W=(D=m[I])[P])!=null?W:D[P]=[]).push(M)});let x=t.createDiv({cls:"csv-tasks"}),C=xp(),E=i?Cp(s,i):"done",y=((k=s.fileCfg.cardFields)!=null?k:s.headers).filter(M=>M!==e&&M!==n&&M!==i),v=[];i&&v.push({name:"",cls:"csv-tasks-check-cell"}),y.forEach(M=>{let L="";M===a?L="csv-tasks-name-cell":M===o?L="csv-tasks-due":M===r?L="csv-tasks-priority":s.isNotesCol(M)?L="csv-tasks-generic-cell csv-tasks-notes-cell":L="csv-tasks-generic-cell",v.push({name:M,cls:L})});let _=(M,L)=>{L.sort((I,P)=>{var W,O,j,$,A,z;let R=Io(s,I,i),D=Io(s,P,i);if(R!==D)return R?1:-1;if(r){let G=tc((W=I[r])!=null?W:"")-tc((O=P[r])!=null?O:"");if(G)return G}if(o){let G=ec((j=I[o])!=null?j:"")-ec(($=P[o])!=null?$:"");if(G)return G;let B=((A=I[o])!=null?A:"").localeCompare((z=P[o])!=null?z:"");if(B)return B}return s.getTitle(I).localeCompare(s.getTitle(P))}),L.forEach(I=>{let P=Io(s,I,i),R=M.createEl("tr");if(i){let W=R.createEl("td",{cls:"csv-tasks-check-cell"}).createEl("span",{cls:`csv-tasks-check ${P?"is-done":""}`,text:P?"\u2713":""});W.setAttr("title",P?"Mark not done":"Mark done"),W.addEventListener("click",O=>{O.stopPropagation(),I[i]=P?"":E,s.scheduleSave(),s.renderView(!0)})}y.forEach(D=>{var W,O,j;if(D===a)Sp(s,R,I,a,P);else if(D===o){let $=R.createEl("td",{cls:"csv-tasks-due csv-tasks-editable"}),A=o?((W=I[o])!=null?W:"").slice(0,10):"";$.setText(A||"\u2014"),A&&!P&&A{var G;A.stopPropagation();let z=Array.from(new Set([...s.getColumnValues(r),"high","medium","low"]));Ft($,(G=I[r])!=null?G:"",z,B=>{I[r]=B,s.scheduleSave(),s.renderView(!0)},s.contentEl)})}else if(s.isNotesCol(D)){let $=((O=I[D])!=null?O:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim(),A=$?$.length>50?$.slice(0,48)+"\u2026":$:"\u2014",z=R.createEl("td",{text:A,cls:"csv-tasks-generic-cell csv-tasks-notes-cell csv-tasks-editable"});Ps(s,z,I,D)}else{let $=(j=I[D])!=null?j:"",A=$.length>40?$.slice(0,38)+"\u2026":$,z=R.createEl("td",{text:A||"\u2014",cls:"csv-tasks-generic-cell csv-tasks-editable"});Ps(s,z,I,D)}}),R.addEventListener("contextmenu",D=>s.openRowContextMenu(I,D))})},w=Object.keys(m).sort((M,L)=>M==="Tasks"||M==="\u2014"?-1:L==="Tasks"||L==="\u2014"?1:M.localeCompare(L));if(w.forEach(M=>{_p(s,x,M,m[M],_,v)}),w.length===0){let M=x.createDiv({cls:"csv-empty-state"});M.createEl("p",{text:p||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"?"No entries match your filters.":"No tasks yet."}),(p||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all")&&M.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.taskProjectFilter="all",s.taskTypeFilter="all",s.searchQuery="",s.renderView()})}}function _p(s,t,e,n,i,o){if(Object.keys(n).length===0)return;t.createDiv({cls:"csv-tasks-section-header",text:e});let r=t.createDiv({cls:"csv-tasks-section"});Object.keys(n).sort().forEach(a=>{let l=n[a],c=r.createEl("details",{cls:"csv-tasks-group"});c.open=!0;let d=c.createEl("summary",{cls:"csv-tasks-group-header"});d.innerHTML=`\u25B6 ${a} ${l.length}`;let u=c.createDiv({cls:"csv-tasks-table-wrapper"}).createEl("table",{cls:"csv-tasks-table"}),f=120;o.forEach(b=>{b.cls.includes("check-cell")?f+=30:b.cls.includes("priority")?f+=90:b.cls.includes("due")?f+=150:b.cls.includes("notes-cell")?f+=140:b.cls.includes("generic-cell")&&(f+=150)}),u.style.minWidth=`${f}px`;let g=u.createEl("thead").createEl("tr");o.forEach(b=>g.createEl("th",{text:b.name,cls:b.cls}));let m=u.createEl("tbody");i(m,l)})}function Sp(s,t,e,n,i){var h;let o=t.createEl("td",{cls:"csv-tasks-name-cell"}),r=(h=s.isHighlighted)!=null&&h.call(s,e)?"csv-title-highlight":"",a=o.createSpan({cls:`csv-tasks-link ${i?"csv-tasks-done":""} ${r}`,text:e[n]||"Untitled"}),l=s.getNotesCol();a.addEventListener("click",()=>{l?s.openNoteExpander(e,l):s.openOrCreateNotes(e)});let c=s.notesFileExists(e),d=o.createEl("button",{cls:`csv-tasks-page-icon ${c?"exists":""}`,text:c?"\u{1F4C4}":"+"});d.setAttr("title",c?"Open page":"Create page"),d.addEventListener("click",u=>{u.stopPropagation(),s.openOrCreateNotes(e)})}function ci(s){let t=[];return s.isTravelFile()&&t.push({id:"travel",label:"Travel"}),s.hasDateColumn()&&t.push({id:"dashboard",label:"Dashboard"}),Ss(s)&&t.push({id:"tasks",label:"Tasks"}),$t(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"}),bn(s)&&t.push({id:"stats",label:"Stats"}),ri(s)&&t.push({id:"chart",label:"Chart"}),t}function oc(s,t){var f,p,g;let e=t.createDiv({cls:"csv-toolbar"});e.createDiv({cls:"csv-toolbar-title",text:(p=(f=s.file)==null?void 0:f.basename)!=null?p:""});let n=e.createDiv({cls:"csv-toolbar-controls"});n.createDiv({cls:"csv-row-count",text:`${s.rows.length} entries`});let i=n.createDiv({cls:"csv-mode-group"}),o=ci(s),r=i.createEl("select",{cls:"csv-mode-select",attr:{"aria-label":"View mode"}});if(o.forEach(({id:m,label:b})=>{let x=r.createEl("option",{text:b,value:m});s.mode===m&&(x.selected=!0)}),r.addEventListener("change",()=>{s.mode=r.value,s.renderView()}),s.mode!=="dashboard"){let m=n.createEl("button",{cls:"csv-cfg-btn csv-search-toggle",text:"\u{1F50D}",title:"Search"}),b=n.createDiv({cls:"csv-search-wrap"}),x=b.createDiv({cls:"csv-search-input-wrap"}),C=x.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search...",value:s.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),E=x.createEl("button",{cls:"csv-search-clear",text:"\xD7",title:"Clear search"});E.toggleClass("is-hidden",!s.searchQuery),b.createEl("button",{cls:"csv-search-done",text:"Done",title:"Dismiss keyboard"}).addEventListener("click",v=>{if(v.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",v=>{s.searchQuery=v.target.value,E.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",v=>{v.key==="Enter"&&(v.preventDefault(),C.blur())}),E.addEventListener("click",()=>{s.searchQuery="",C.value="",E.addClass("is-hidden"),m.removeClass("has-query"),C.focus({preventScroll:!0}),s.renderView(!0)}),s.searchQuery&&m.addClass("has-query"),m.addEventListener("click",()=>{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;n.createEl("button",{cls:`csv-cfg-btn ${m?"active":""}`,text:m?"\u2193 Newest":"\u2191 Oldest",title:"Toggle sort order"}).addEventListener("click",()=>{var C;let x=s.fileCfg;x.sortNewestFirst=!((C=x.sortNewestFirst)==null||C),s.saveFileCfg(x),s.tableSortCol=null,s.renderViewPreservingScroll()})}let a=()=>{var b,x;let m={title:s.resolveCol(Ye),category:s.resolveCol(Ge),status:s.resolveCol(qe),notes:s.resolveCol(Xe),image:s.resolveCol(Ke),anki:Ei(s)};new hn(s.app,s.headers,(x=(b=s.file)==null?void 0:b.path)!=null?x:"",s.fileCfg,s.autoDetectBooleanColumns(),s.autoDetectCategoricalColumns(),m,ci(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=()=>br(s),c=()=>s.backupToArchive(),d=()=>yr(s);n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u2699 Config",title:"Configure this file's columns and views"}).addEventListener("click",a),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F4F1} Mobile",title:"Generate mobile dashboard with add form"}).addEventListener("click",l),n.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",c),n.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",d),n.createEl("button",{cls:"csv-add-btn",text:"+ Add"}).addEventListener("click",()=>s.openAddModal()),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-overflow",text:"\u22EF",title:"More actions"}).addEventListener("click",m=>{let b=new di.Menu;b.addItem(x=>x.setTitle("Config").setIcon("settings").onClick(a)),b.addItem(x=>x.setTitle("Mobile dashboard").setIcon("smartphone").onClick(l)),b.addItem(x=>x.setTitle("Backup").setIcon("save").onClick(c)),b.addItem(x=>x.setTitle("Sync to Anki").setIcon("layers").onClick(d)),b.addSeparator(),b.addItem(x=>x.setTitle("Built 2026-07-11 23:32").setIcon("info").setDisabled(!0)),b.showAtMouseEvent(m)}),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary csv-info-btn",text:"\u24D8",title:"Built 2026-07-11 23:32 \u2014 click to confirm"}).addEventListener("click",()=>new di.Notice("datadeck \u2014 built 2026-07-11 23:32",4e3))}function Ep(s){return s&&typeof s=="object"&&"basename"in s?s:null}var kp=["Author","author","By","by","Source","source","Speaker","speaker","Artist","artist","Director","director"];async function rc(s,t,e,n){var x,C,E;let i=t.split(` +`).map(S=>S.trim()).filter(Boolean),o=S=>{var y,v;return(v=(y=i.find(_=>_.startsWith(S+":")))==null?void 0:y.slice(S.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(n.sourcePath),l=(C=(x=a==null?void 0:a.parent)==null?void 0:x.path)!=null?C:"",c=ue(r,l),d=Ep(s.vault.getAbstractFileByPath(c));if(!d){e.createEl("p",{text:`Error: File not found: ${c}`,cls:"csv-add-error"});return}let h=[],u=[];try{let S=Nt(await s.vault.read(d));h=S.headers,u=S.rows}catch(S){e.createEl("p",{text:`Error reading file: ${S}`,cls:"csv-add-error"});return}if(!u.length){e.createEl("p",{text:"No entries in file.",cls:"csv-add-error"});return}let f=o("field"),p=(E=h.find(S=>S.toLowerCase()===f.toLowerCase()))!=null?E:h[0],g=kp.map(S=>h.find(y=>y===S)).find(Boolean),m=e.createDiv({cls:"csv-random-card"}),b=()=>{var k;m.empty();let S=u.filter(M=>{var L;return((L=M[p])!=null?L:"").trim()}),y=S.length?S:u,v=y[Math.floor(Math.random()*y.length)];m.createDiv({cls:"csv-random-text",text:v[p]||"\u2014"});let _=g?((k=v[g])!=null?k:"").trim():"";_&&m.createDiv({cls:"csv-random-sub",text:`\u2014 ${_}`});let w=m.createDiv({cls:"csv-random-foot"});w.createSpan({cls:"csv-random-src",text:d.basename}),w.createEl("button",{cls:"csv-random-btn",text:"\u21BB",title:"Another one"}).addEventListener("click",b)};b()}async function ac(s,t){var A,z,G;let e=s.getDateCol();if(!e){t.createEl("p",{text:"No date column detected.",cls:"csv-empty-state"});return}let n=s.getBooleanColumns(),i=s.getNotesCol(),o=s.formatDate(new Date),r=[...s.rows].sort((B,F)=>{var N,H;return((N=B[e])!=null?N:"").localeCompare((H=F[e])!=null?H:"")});s.selectedDate||(s.selectedDate=o);let a=r.find(B=>B[e]===s.selectedDate),l=s.selectedDate===o;t.addClass("csv-dashboard");let c=[...new Set([...r.map(B=>B[e]),o])].filter(Boolean).sort(),d=t.createDiv({cls:"csv-dash-nav"});d.createEl("button",{cls:"csv-dash-nav-btn csv-dash-back-btn",text:"\u25C0"}).addEventListener("click",()=>{let B=c.indexOf(s.selectedDate);if(B>0)s.selectedDate=c[B-1],s.renderView();else if(B===-1&&c.length>0){let F=c.filter(N=>N0&&(s.selectedDate=F[F.length-1],s.renderView())}});let u=d.createDiv({cls:"csv-dash-date"});l&&u.createSpan({cls:"csv-dash-today-dot"});let f=u.createEl("select",{cls:"csv-dash-date-select"});if(c.forEach(B=>{let F=f.createEl("option",{text:B,value:B});B===s.selectedDate&&(F.selected=!0)}),f.addEventListener("change",()=>{s.selectedDate=f.value,s.renderView()}),d.createEl("button",{cls:"csv-dash-nav-btn",text:"\u25B6"}).addEventListener("click",()=>{let B=c.indexOf(s.selectedDate);if(B>=0&&BN>s.selectedDate);F.length>0&&(s.selectedDate=F[0],s.renderView())}}),l||d.createEl("button",{cls:"csv-dash-today-btn",text:"Today"}).addEventListener("click",()=>{s.selectedDate=o,s.renderView()}),!a){let B=t.createDiv({cls:"csv-dash-add-section"});B.createEl("p",{text:`No entry for ${s.selectedDate}`}),B.createEl("button",{cls:"csv-dash-add-btn",text:`+ Add entry for ${s.selectedDate}`}).addEventListener("click",()=>{let N={};s.headers.forEach(H=>N[H]=""),N[e]=s.selectedDate,s.rows.push(N),s.scheduleSave(),s.renderView()})}if(a){let B=t.createDiv({cls:"csv-dash-habits"});B.createEl("h3",{text:s.selectedDate===o?"Today":s.selectedDate,cls:"csv-dash-section-title"});let F=B.createDiv({cls:"csv-dash-habits-grid"});n.forEach(H=>{let V=s.isTruthy(a[H]),K=F.createDiv({cls:`csv-dash-habit ${V?"checked":""}`}),Y=K.createEl("button",{cls:"csv-dash-habit-check",text:V?"\u25CF":"\u25CB"});K.createSpan({cls:"csv-dash-habit-label",text:H}),Y.addEventListener("click",()=>{a[H]=V?"0":"1",s.scheduleSave(),s.renderViewPreservingScroll()})});let N=n.filter(H=>s.isTruthy(a[H])).length;if(B.createDiv({cls:"csv-dash-habits-count",text:`${N} of ${n.length} complete`}),i&&((A=a[i])!=null&&A.trim())){let H=B.createDiv({cls:"csv-dash-notes-preview"});H.createEl("strong",{text:"Notes: "}),H.createSpan({text:a[i].slice(0,200)+(a[i].length>200?"\u2026":"")})}}let g=t.createDiv({cls:"csv-dash-chart-section"});g.createEl("h3",{text:"Progress",cls:"csv-dash-section-title"});let b=g.createDiv({cls:"csv-dash-chart-wrap"}).createEl("canvas",{cls:"csv-dash-chart"}),x=r.map(B=>{var N;return((N=B[e])!=null?N:"").slice(5)}),C=r.map(B=>n.filter(F=>s.isTruthy(B[F])).length);s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:E}=await _s();if(!b.isConnected)return;s.chartInstance=new E(b,{type:"line",data:{labels:x,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:n.length||8,ticks:{stepSize:1}}},plugins:{tooltip:{enabled:!0}}}});let S=t.createDiv({cls:"csv-dash-stats-section"});S.createEl("h3",{text:"Stats",cls:"csv-dash-section-title"});let y=r.length,v=r.reduce((B,F)=>B+n.filter(N=>s.isTruthy(F[N])).length,0),_=y>0?(v/y).toFixed(1):"0",w=r.filter(B=>n.every(F=>s.isTruthy(B[F]))).length,T=0,k=0,M=null;for(let B of r){let F=n.filter(V=>s.isTruthy(B[V])).length,N=s.parseDate((z=B[e])!=null?z:""),H=!0;M&&N&&Math.round((N.getTime()-M.getTime())/864e5)!==1&&(H=!1),F>=1&&(H||M===null)?(k++,k>T&&(T=k)):F>=1?(k=1,k>T&&(T=k)):k=0,M=N}let L=0,I=new Date;I.setHours(0,0,0,0);let P=I;for(let B=r.length-1;B>=0;B--){let F=s.parseDate((G=r[B][e])!=null?G:"");if(!F)break;let N=Math.round((P.getTime()-F.getTime())/(1e3*60*60*24));if(L===0&&N>1||L>0&&N!==1)break;if(n.filter(V=>s.isTruthy(r[B][V])).length>=1)L++,P=F;else break}let R=S.createDiv({cls:"csv-dash-stats-bar"});R.innerHTML=`${y} days logged \xB7 ${_} avg/day \xB7 ${w} perfect days \xB7 current streak ${L}d \xB7 best streak ${T}d`;let W=t.createDiv({cls:"csv-dash-cards-section"}).createDiv({cls:"csv-dash-cards-grid"}),O=new Date().getFullYear(),j={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}"};n.map(B=>{let F=r.filter(Y=>s.isTruthy(Y[B])),N=F.length>0?F[F.length-1][e]:null,H=new Set;F.forEach(Y=>{var X;let q=s.parseDate((X=Y[e])!=null?X:"");q&&H.add(q.getFullYear())});let V=r.filter(Y=>{var X;let q=s.parseDate((X=Y[e])!=null?X:"");return q&&q.getFullYear()===O}),K=V.filter(Y=>s.isTruthy(Y[B])).length;return{habit:B,doneCount:F.length,doneThisYear:K,totalThisYear:V.length,lastDone:N,years:Array.from(H).sort()}}).sort((B,F)=>!B.lastDone&&!F.lastDone?0:B.lastDone?F.lastDone?F.lastDone.localeCompare(B.lastDone):-1:1).forEach(({habit:B,doneCount:F,doneThisYear:N,totalThisYear:H,lastDone:V,years:K})=>{var st;let Y=W.createDiv({cls:"csv-dash-habit-card"}),q=(st=j[B.toLowerCase()])!=null?st:"\u25CB",X=Y.createDiv({cls:"csv-dash-habit-card-header"});if(X.createSpan({cls:"csv-dash-habit-icon",text:q}),X.createSpan({cls:"csv-dash-habit-card-name",text:Mt(B)}),K.length>0&&Y.createDiv({cls:"csv-dash-habit-years"}).setText(K.join(" \xB7 ")),Y.createDiv({cls:"csv-dash-habit-card-thisyear",text:`${N} of ${H} complete this year`}),Y.createDiv({cls:"csv-dash-habit-card-alltime",text:`${F} of ${y} all time`}),V){let lt=s.parseDate(V),Wt=lt?lt.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):V;Y.createDiv({cls:"csv-dash-habit-card-last",text:`Last logged: ${Wt}`})}else Y.createDiv({cls:"csv-dash-habit-card-last",text:"Never logged"});let Z=y>0?F/y*100:0,Q=Y.createDiv({cls:"csv-dash-habit-progress"}).createDiv({cls:"csv-dash-habit-progress-bar"});Q.style.width=`${Z}%`,Y.addEventListener("click",()=>{s.selectedHabit=s.selectedHabit===B?null:B,s.renderViewPreservingScroll()}),s.selectedHabit===B&&Y.addClass("selected")}),s.selectedHabit&&n.includes(s.selectedHabit)&&wp(s,t,r,e,s.selectedHabit)}function wp(s,t,e,n,i){var T,k,M;let o=t.createDiv({cls:"csv-dash-timeline-section"}),r=o.createDiv({cls:"csv-dash-timeline-header"});r.createEl("h3",{text:`${Mt(i)} Timeline`,cls:"csv-dash-section-title"});let a=r.createEl("select",{cls:"csv-dash-year-select"}),l=new Set;e.forEach(L=>{var P;let I=s.parseDate((P=L[n])!=null?P:"");I&&l.add(I.getFullYear())}),l.add(new Date().getFullYear()),Array.from(l).sort().reverse().forEach(L=>{let I=a.createEl("option",{text:String(L),value:String(L)});L===s.timelineYear&&(I.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 d=new Map;e.forEach(L=>{var I;d.set((I=L[n])!=null?I:"",s.isTruthy(L[i]))});let h=o.createDiv({cls:"csv-dash-timeline-grid-wrap"}),u=h.createDiv({cls:"csv-dash-timeline-months"});["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].forEach(L=>u.createSpan({cls:"csv-dash-timeline-month-label",text:L}));let p=h.createDiv({cls:"csv-dash-timeline-calendar"}),g=p.createDiv({cls:"csv-dash-timeline-day-labels"});for(let L=1;L<=31;L++)g.createDiv({cls:"csv-dash-timeline-day-label",text:L%5===0||L===1?String(L):""});for(let L=0;L<12;L++){let I=p.createDiv({cls:"csv-dash-timeline-month-col"}),P=new Date(s.timelineYear,L+1,0).getDate();for(let R=1;R<=31;R++){if(R>P){I.createDiv({cls:"csv-dash-timeline-cell empty"});continue}let D=`${s.timelineYear}-${String(L+1).padStart(2,"0")}-${String(R).padStart(2,"0")}`,W=(T=d.get(D))!=null?T:!1,O=d.has(D),j=new Date(s.timelineYear,L,R)>new Date,$=I.createDiv({cls:`csv-dash-timeline-cell ${j?"future":""} ${W?"done":""} ${O&&!W?"missed":""} ${!O&&!j?"no-entry":""}`});$.title=`${D}: ${j?"Future":W?"\u2713 Done":O?"\u2717 Missed":"No entry"}`}}let m=e.filter(L=>{var P;let I=s.parseDate((P=L[n])!=null?P:"");return I&&I.getFullYear()===s.timelineYear}),b=m.filter(L=>s.isTruthy(L[i])).length,x=m.length,C=0,E=0,S=0,y=null;for(let L of e){let I=s.isTruthy(L[i]),P=s.parseDate((k=L[n])!=null?k:""),R=!0;y&&P&&Math.round((P.getTime()-y.getTime())/864e5)!==1&&(R=!1),I&&(R||y===null)?(S++,S>E&&(E=S)):I?S=1:S=0,y=P}let v=new Date;v.setHours(0,0,0,0);let _=v;for(let L=e.length-1;L>=0;L--){let I=s.parseDate((M=e[L][n])!=null?M:"");if(!I)break;let P=Math.round((_.getTime()-I.getTime())/(1e3*60*60*24));if(C===0&&P>1||C>0&&P!==1)break;if(s.isTruthy(e[L][i]))C++,_=I;else break}let w=o.createDiv({cls:"csv-dash-timeline-stats"});w.innerHTML=`${b} of ${x} in ${s.timelineYear} \xB7 current streak ${C}d \xB7 best streak ${E}d`}function lc(s,t){var x,C,E;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 S=t.createDiv({cls:"csv-empty-state"});S.createEl("p",{text:s.searchQuery?"No matching entries found.":"No entries yet."}),s.searchQuery&&S.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 n=e[s.focusIndex],i=(x=s.titleKey())!=null?x:s.headers[0],o=s.getNotesCol(),r=s.authorKey(),a=t.createDiv({cls:"csv-focus-wrap",attr:{tabindex:"0"}}),l=S=>{s.focusIndex=(S%e.length+e.length)%e.length,s.focusNavPending=!0,s.renderView(!0)},c=a.createDiv({cls:"csv-focus-card"});c.createDiv({cls:"csv-focus-position",text:`${s.focusIndex+1} / ${e.length}`});let d=c.createDiv({cls:`csv-focus-title ${(C=s.isHighlighted)!=null&&C.call(s,n)?"csv-title-highlight":""}`,text:s.getTitle(n)});o&&(d.addClass("is-clickable"),d.title="Open entry",d.addEventListener("click",()=>s.openNoteExpander(n,o)));let h=s.getSubtitle(n);if(h&&c.createDiv({cls:"csv-focus-sub",text:h}),o&&o!==i&&((E=n[o])!=null&&E.trim())){let S=c.createDiv({cls:"csv-focus-notes"});s.renderMarkdownInto(S,n[o])}let u=new Set([i,o,r].filter(Boolean)),f=s.headers.filter(S=>{var y;return!u.has(S)&&((y=n[S])!=null?y:"").trim()});if(f.length){let S=c.createDiv({cls:"csv-focus-meta"});f.forEach(y=>{let v=S.createDiv({cls:"csv-kanban-chip"});if(v.createSpan({cls:"csv-chip-label",text:y+": "}),s.isSelectCol(y)){let _=v.createSpan({cls:"csv-chip-value csv-chip-select",text:n[y]});_.addEventListener("click",w=>{w.stopPropagation(),Ft(_,n[y],s.getColumnValues(y),T=>{n[y]=T,_.setText(T||"\u2014"),s.scheduleSave()},s.contentEl,{multi:kt(y)})})}else v.createSpan({cls:"csv-chip-value",text:n[y]})})}c.addEventListener("contextmenu",S=>s.openRowContextMenu(n,S));let p=a.createDiv({cls:"csv-focus-nav"}),g=p.createEl("button",{cls:"csv-focus-nav-btn",text:"\u2039",title:"Previous (\u2190)"}),m=p.createEl("button",{cls:"csv-focus-nav-btn csv-focus-nav-rand",text:"\u{1F500}",title:"Random entry"}),b=p.createEl("button",{cls:"csv-focus-nav-btn",text:"\u203A",title:"Next (\u2192)"});g.addEventListener("click",()=>l(s.focusIndex-1)),b.addEventListener("click",()=>l(s.focusIndex+1)),m.addEventListener("click",()=>{if(e.length<2)return;let S=s.focusIndex;for(;S===s.focusIndex;)S=Math.floor(Math.random()*e.length);l(S)}),a.addEventListener("keydown",S=>{S.key==="ArrowLeft"?(S.preventDefault(),l(s.focusIndex-1)):S.key==="ArrowRight"&&(S.preventDefault(),l(s.focusIndex+1))}),(s.focusNavPending||document.activeElement===document.body)&&(s.focusNavPending=!1,a.focus({preventScroll:!0}))}var Ot=require("obsidian"),dc=an(Ds());var Dp=[{id:"table",label:"Table"},{id:"library",label:"Cards"},{id:"kanban-genre",label:"Kanban"}];function cc(s){return s&&typeof s=="object"&&"basename"in s?s:null}function Mp(s){let t=s.split(` +`).map(r=>r.trim()).filter(Boolean),e=r=>{var a,l;return(l=(a=t.find(c=>c.toLowerCase().startsWith(r+":")))==null?void 0:a.slice(r.length+1).trim())!=null?l:""},n=e("mode").toLowerCase(),i=n==="kanban"||n==="kanban-genre"?"kanban-genre":n==="cards"||n==="card"||n==="library"?"library":"table",o=parseInt(e("height"),10);return{file:e("file"),mode:i,height:Number.isFinite(o)&&o>0?o:null,collapse:e("collapse").split(",").map(r=>r.trim()).filter(Boolean)}}var No=class extends Ot.MarkdownRenderChild{constructor(e,n,i,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=n,this.settings=i,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}async onload(){if(this.containerEl.addClass("csv-inline-view"),!this.opts.file){this.renderError("No file specified. Use: file: yourfile.csv");return}await this.reload()&&(this.renderView(),this.registerEvent(this.app.vault.on("modify",async e=>{if(!this.file||e.path!==this.file.path)return;let n=await this.app.vault.read(this.file);if(n===this.lastWritten)return;let i=Nt(n);this.headers=i.headers,this.rows=i.rows,this.renderView()})),this.registerEvent(this.app.vault.on("rename",(e,n)=>{this.file&&n===this.file.path&&(this.file=cc(e))})))}onunload(){this.saveTimer&&window.clearTimeout(this.saveTimer)}async reload(){let e=cc(this.app.vault.getAbstractFileByPath(this.opts.file));if(!e)return this.renderError(`File not found: ${this.opts.file}`),!1;this.file=e;try{let n=Nt(await this.app.vault.read(e));this.headers=n.headers,this.rows=n.rows}catch(n){return this.renderError(`Error reading file: ${n instanceof Error?n.message:String(n)}`),!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=dc.default.unparse(this.rows,{columns:this.headers});this.lastWritten=e,await this.app.vault.modify(this.file,e)}catch(e){new Ot.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 n;return((n=this.fileCfg.highlightedTitles)!=null?n:[]).includes(this.getTitle(e))}toggleHighlight(e){let n=this.getTitle(e),i=this.fileCfg,o=i.highlightedTitles?[...i.highlightedTitles]:[],r=o.indexOf(n);r>=0?o.splice(r,1):o.push(n),i.highlightedTitles=o,this.saveFileCfg(i)}resolveCol(e){for(let n of e){let i=this.headers.find(o=>o.toLowerCase()===n.toLowerCase());if(i)return i}return null}getNotesCol(){return this.fileCfg.notesColumn?this.fileCfg.notesColumn:this.resolveCol(Xe)}isNotesCol(e){let n=this.getNotesCol();return n?e===n:this.settings.notesColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var i;let n=(i=this.titleKey())!=null?i:this.headers[0];return e===n||this.getDateCol()===e||kt(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(n=>n.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(qe)}getCategoryCol(){var e;return this.fileCfg.categoryColumn!==void 0?this.fileCfg.categoryColumn===""?null:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ge)}titleKey(){var e,n;return this.fileCfg.titleColumn!==void 0?this.fileCfg.titleColumn===""?void 0:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(n=this.resolveCol(Ye))!=null?n: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 i;let n=this.titleKey();return(i=n?e[n]:e[this.headers[0]])!=null?i:"\u2014"}getSubtitle(e){var i;let n=this.authorKey();return n&&(i=e[n])!=null?i:""}getColumnValues(e){return Array.from(new Set(this.rows.map(n=>{var i;return(i=n[e])!=null?i:""}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn!==void 0?this.fileCfg.imageColumn===""?null:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ke)}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 n=this.rows.map(i=>{var o;return((o=i[e])!=null?o:"").toLowerCase().trim()});return Qe(n)})}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 n=/^\d{4}-\d{2}-\d{2}$/,i=this.rows.slice(0,5);return i.length>0&&i.every(a=>{var l;return n.test((l=a[e])!=null?l:"")})?e:(r=this.headers.find(a=>this.isDateCol(a)))!=null?r:null}isDateCol(e){var n;return(n=this.fileCfg.dateColumns)!=null&&n.includes(e)?!0:Et(e)}getFilteredRows(){var i;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 d,h;let c=((d=a[o])!=null?d:"").localeCompare((h=l[o])!=null?h:"",void 0,{numeric:!0});return r==="asc"?c:-c})}let n=this.getDateCol();if(this.mode==="table"&&n){let o=(i=this.fileCfg.sortNewestFirst)!=null?i:!0;e=[...e].sort((r,a)=>{var c,d;let l=((c=r[n])!=null?c:"").localeCompare((d=a[n])!=null?d:"");return o?-l:l})}return e}notesFilePath(e){var a,l,c;let n=Ms(this.getTitle(e)),i=(c=(l=(a=this.file)==null?void 0:a.parent)==null?void 0:l.path)!=null?c:"",o=this.settings.notesSubfolder.trim(),r=o?i?`${i}/${o}`:o:i;return(0,Ot.normalizePath)(`${r}/${n}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}async openOrCreateNotes(e){var o;let n=this.notesFilePath(e),i=this.app.vault.getAbstractFileByPath(n);if(!i){let a=["---",...this.headers.filter(h=>!this.isNotesCol(h)&&e[h]).map(h=>`${h}: "${e[h].replace(/"/g,'\\"')}"`),"---","",`# ${this.getTitle(e)}`,"",""].join(` +`),l=this.headers.find(h=>this.isNotesCol(h)),c=a+(l&&((o=e[l])!=null&&o.trim())?e[l]:""),d=n.substring(0,n.lastIndexOf("/"));d&&!this.app.vault.getAbstractFileByPath(d)&&await this.app.vault.createFolder(d),i=await this.app.vault.create(n,c),new Ot.Notice(`Created: ${i.name}`)}await this.app.workspace.getLeaf("tab").openFile(i)}deleteWithUndo(e){let n=this.rows.indexOf(e);if(n<0)return;this.rows.splice(n,1),this.scheduleSave(),this.renderView();let i=this.getTitle(e)||"entry",o=document.createDocumentFragment();o.createSpan({text:`Deleted \u201C${i}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new Ot.Notice(o,6e3);r.addEventListener("click",()=>{r.hasAttribute("disabled")||(r.setAttribute("disabled","true"),this.rows.splice(Math.min(n,this.rows.length),0,e),this.scheduleSave(),this.renderView(),a.hide(),new Ot.Notice(`Restored \u201C${i}\u201D`,2500))})}openRowContextMenu(e,n){let i=new Ot.Menu;i.addItem(a=>a.setTitle("Open / Create Notes file").setIcon("file-text").onClick(()=>void this.openOrCreateNotes(e))),i.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&&(i.addSeparator(),a.forEach(l=>{l!==e[o]&&i.addItem(c=>c.setTitle(`Mark as: ${l}`).onClick(()=>{e[o]=l,this.scheduleSave(),this.renderView()}))}))}i.addSeparator();let r=this.isHighlighted(e);i.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderView()})),i.addSeparator(),i.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),i.showAtMouseEvent(n)}openNoteExpander(e,n){var i,o;new ts(this.app,e,n,this.headers,(o=(i=this.file)==null?void 0:i.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 Je(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 Ot.Notice(`Added: ${this.getTitle(e)}`)},{},e=>this.getBooleanColumns().includes(e),e=>this.isCategoricalCol(e),this.titleKey(),e=>this.isDateCol(e)).open()}renderSelectField(e,n,i){var a;let o=(a=n[i])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),i.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",l=>{var c;l.stopPropagation(),Ft(r,(c=n[i])!=null?c:"",this.getColumnValues(i),d=>{n[i]=d,r.setText(d||"\u2014"),this.scheduleSave()},this.contentEl)}),r}renderMarkdownInto(e,n){var i,o;Ot.MarkdownRenderer.render(this.app,n,e,(o=(i=this.file)==null?void 0:i.path)!=null?o:"",this.renderComponent)}renderViewPreservingScroll(){this.renderView()}renderView(e=!1){let n=this.containerEl;e?this.contentArea&&this.contentArea.empty():(n.empty(),this.renderToolbar(n),this.contentArea=n.createDiv({cls:"csv-content-area"}),this.opts.height&&(this.contentArea.style.maxHeight=this.opts.height+"px"));let i=this.contentArea;if(i){if(i.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){i.createDiv({cls:"csv-empty-state"}).createEl("p",{text:"This file is empty."});return}if(this.rows.length===0){let o=i.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")&&!$t(this.asView)&&(this.mode="table"),this.mode==="library"?yn(this.asView,i):this.mode==="kanban-genre"?vn(this.asView,i):mn(this.asView,i)}}renderToolbar(e){var c,d;let n=e.createDiv({cls:"csv-toolbar csv-inline-toolbar"});n.createDiv({cls:"csv-toolbar-title",text:(d=(c=this.file)==null?void 0:c.basename)!=null?d:""}).addEventListener("click",()=>{this.file&&this.app.workspace.getLeaf("tab").openFile(this.file)});let i=n.createDiv({cls:"csv-toolbar-controls"});i.createDiv({cls:"csv-row-count",text:`${this.rows.length} entries`});let o=!!$t(this.asView),r=i.createDiv({cls:"csv-mode-group"});Dp.forEach(({id:h,label:u})=>{if((h==="library"||h==="kanban-genre")&&!o)return;r.createEl("button",{cls:`csv-mode-btn ${this.mode===h?"active":""}`,text:u}).addEventListener("click",()=>{this.mode=h,this.renderView()})});let a=i.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",h=>{this.searchQuery=h.target.value,l!==null&&window.clearTimeout(l),l=window.setTimeout(()=>{l=null,this.renderView(!0)},120)}),i.createEl("button",{cls:"csv-add-btn",text:"+ Add"}).addEventListener("click",()=>this.openAddModal())}};function hc(s,t,e,n){n("csv-view",(i,o,r)=>{var h,u,f;let a=Mp(i),l=(f=(u=(h=s.vault.getAbstractFileByPath(r.sourcePath))==null?void 0:h.parent)==null?void 0:u.path)!=null?f:"",c=a.file?ue(a.file,l):a.file,d=new No(o,s,t,e,{...a,file:c});r.addChild(d)})}var fc=require("obsidian");function Tp(s){let t=s.split(` +`).map(i=>i.trim()).filter(Boolean),e=i=>{var o,r;return(r=(o=t.find(a=>a.toLowerCase().startsWith(i+":")))==null?void 0:o.slice(i.length+1).trim())!=null?r:""},n=i=>{let o=parseFloat(e(i));return Number.isFinite(o)?o:null};return{file:e("file"),x:e("x"),y:e("y"),fit:e("fit").toLowerCase()==="linear"?"linear":"none",formula:e("formula"),xmin:n("xmin"),xmax:n("xmax"),height:n("height")}}function Lp(s){return s&&typeof s=="object"&&"basename"in s?s:null}function uc(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 Bo=class extends fc.MarkdownRenderChild{constructor(e,n,i){super(e);this.app=n;this.opts=i;this.chart=null}async onload(){this.containerEl.addClass("csv-chart-block"),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,n)=>{n===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 c,d,h,u,f;let e=this.containerEl;this.chart&&(this.chart.destroy(),this.chart=null),e.empty();let n,i=0;if(this.opts.file){let p=Lp(this.app.vault.getAbstractFileByPath(this.opts.file));if(!p)return this.renderError(`File not found: ${this.opts.file}`);let g,m;try{({headers:g,rows:m}=Nt(await this.app.vault.read(p)))}catch(_){return this.renderError(`Error reading file: ${_ instanceof Error?_.message:String(_)}`)}let b=_=>{var w;return(w=g.find(T=>T.toLowerCase()===_.toLowerCase()))!=null?w:null},x=oi(g,m),C=(c=g.find(_=>Et(_)))!=null?c:m.slice(0,5).length&&m.slice(0,5).every(_=>{var w;return uc((w=_[g[0]])!=null?w:"")})?g[0]:null,E=this.opts.x?b(this.opts.x):(d=C!=null?C:x[0])!=null?d:null;if(this.opts.x&&!E)return this.renderError(`No column "${this.opts.x}" in ${p.basename}`);let S=this.opts.y?b(this.opts.y):(h=x.find(_=>_!==E))!=null?h:null;if(this.opts.y&&!S)return this.renderError(`No column "${this.opts.y}" in ${p.basename}`);if(!E||!S)return this.renderError(`Couldn't auto-pick x/y columns \u2014 add "x:" and "y:" lines`);let y=E===C||Et(E),v=Fo(m,E,S,y,uc,_=>{var w;return(w=_[g[0]])!=null?w:""});if(i=v.skipped,!v.points.length)return this.renderError(`No rows with numeric "${E}" and "${S}" values`);n={points:v.points,xIsDate:y,xLabel:E,yLabel:S,connect:y,fit:this.opts.fit,formula:this.opts.formula}}else{if(!this.opts.formula.trim())return this.renderError('Give a "file:" line, a "formula:" line, or both');n={points:[],xIsDate:!1,xLabel:"x",yLabel:"y",connect:!1,fit:"none",formula:this.opts.formula,xMin:(u=this.opts.xmin)!=null?u:-10,xMax:(f=this.opts.xmax)!=null?f:10}}let o=Oo(n,Ro(e));if(o.formulaError)return this.renderError(`formula: ${o.formulaError}`);let r=e.createDiv({cls:"csv-chart-wrap"});this.opts.height&&(r.style.height=this.opts.height+"px");let a=r.createEl("canvas",{cls:"csv-chart-canvas"});if(o.fitText||i>0){let p=e.createDiv({cls:"csv-chart-footer"});o.fitText&&p.createSpan({cls:"csv-chart-fit-text",text:o.fitText}),i>0&&p.createSpan({cls:"csv-chart-skipped",text:`${i} row${i===1?"":"s"} skipped (no numeric value)`})}let{Chart:l}=await _s();a.isConnected&&(this.chart=new l(a,o.config))}};function pc(s,t){t("csv-chart",(e,n,i)=>{var l,c,d;let o=Tp(e),r=(d=(c=(l=s.vault.getAbstractFileByPath(i.sourcePath))==null?void 0:l.parent)==null?void 0:c.path)!=null?d:"",a=o.file?ue(o.file,r):o.file;i.addChild(new Bo(n,s,{...o,file:a}))})}var rn,Es=class extends it.FileView{constructor(e,n,i){super(e);this.headers=[];this.rows=[];this.saveTimer=null;this.searchQuery="";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=n,this.persistSettings=i,this.mode=n.defaultMode,this.renderComponent=new it.Component,this.renderComponent.load()}getViewType(){return ln}getDisplayText(){var e,n;return(n=(e=this.file)==null?void 0:e.basename)!=null?n:"Card View"}getIcon(){return"table"}async onLoadFile(e){var o;try{let r=await this.app.vault.read(e),a=Nt(r);this.headers=a.headers,this.rows=a.rows}catch(r){console.error("CardView load error",r),this.headers=[],this.rows=[],new it.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 n=this.mode==="kanban-genre"||this.mode==="library",i=this.mode==="dashboard";(n&&!$t(this)||i&&!this.hasDateColumn()||this.mode==="travel"&&!this.isTravelFile()||this.mode==="stats"&&!bn(this)||this.mode==="chart"&&!ri(this)||this.mode==="tasks"&&!Ss(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=gc.default.unparse(this.rows,{columns:this.headers});await this.app.vault.modify(this.file,e)}catch(e){console.error("CardView save error",e),new it.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 n;return((n=this.fileCfg.highlightedTitles)!=null?n:[]).includes(this.getTitle(e))}toggleHighlight(e){let n=this.getTitle(e),i=this.fileCfg,o=i.highlightedTitles?[...i.highlightedTitles]:[],r=o.indexOf(n);r>=0?o.splice(r,1):o.push(n),i.highlightedTitles=o,this.saveFileCfg(i)}addColumn(e){let n=e.trim();return n?this.headers.some(i=>i.toLowerCase()===n.toLowerCase())?`"${n}" already exists.`:(this.headers.push(n),this.rows.forEach(i=>{i[n]=""}),this.scheduleSave(),this.renderViewPreservingScroll(),null):"Column name can't be empty."}removeColumn(e){this.headers=this.headers.filter(i=>i!==e),this.rows.forEach(i=>{delete i[e]});let n=this.fileCfg;n.categoryColumn===e&&(n.categoryColumn=void 0),n.statusColumn===e&&(n.statusColumn=void 0),n.notesColumn===e&&(n.notesColumn=void 0),n.ankiFrontCol===e&&(n.ankiFrontCol=void 0),n.kanbanGroupCol===e&&(n.kanbanGroupCol=void 0),n.habitColumns&&(n.habitColumns=n.habitColumns.filter(i=>i!==e)),n.cardFields&&(n.cardFields=n.cardFields.filter(i=>i!==e)),n.categoricalColumns&&(n.categoricalColumns=n.categoricalColumns.filter(i=>i!==e)),this.saveFileCfg(n),this.scheduleSave(),this.renderViewPreservingScroll()}resolveCol(e){for(let n of e){let i=this.headers.find(o=>o.toLowerCase()===n.toLowerCase());if(i)return i}return null}getNotesCol(){return this.fileCfg.notesColumn?this.fileCfg.notesColumn:this.resolveCol(Xe)}isNotesCol(e){let n=this.getNotesCol();return n?e===n:this.settings.notesColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var i;let n=(i=this.titleKey())!=null?i:this.headers[0];return e===n||this.isDateCol(e)||kt(e)?!1:this.fileCfg.categoricalColumns?this.fileCfg.categoricalColumns.includes(e):this.isSelectCol(e)||Xt(this.getColumnValues(e).length)}autoDetectCategoricalColumns(){var n;let e=(n=this.titleKey())!=null?n:this.headers[0];return this.headers.filter(i=>i===e||this.isDateCol(i)||kt(i)||this.isNotesCol(i)?!1:this.isSelectCol(i)||Xt(this.getColumnValues(i).length))}isDateCol(e){var n;return(n=this.fileCfg.dateColumns)!=null&&n.includes(e)?!0:Et(e)}getStatusCol(){var e;return this.fileCfg.statusColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(qe)}getCategoryCol(){var e;return this.fileCfg.categoryColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ge)}titleKey(){var e,n;return this.fileCfg.titleColumn?(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(n=this.resolveCol(Ye))!=null?n: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 i;let n=this.titleKey();return(i=n?e[n]:e[this.headers[0]])!=null?i:"\u2014"}getSubtitle(e){var i;let n=this.authorKey();return n&&(i=e[n])!=null?i:""}getColumnValues(e){return Array.from(new Set(this.rows.map(n=>{var i;return(i=n[e])!=null?i:""}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ke)}notesFilePath(e){var a,l,c;let n=Ms(this.getTitle(e)),i=(c=(l=(a=this.file)==null?void 0:a.parent)==null?void 0:l.path)!=null?c:"",o=this.settings.notesSubfolder.trim(),r=o?i?`${i}/${o}`:o:i;return(0,it.normalizePath)(`${r}/${n}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}deleteWithUndo(e){let n=this.rows.indexOf(e);if(n<0)return;this.rows.splice(n,1),this.scheduleSave(),this.renderViewPreservingScroll();let i=this.getTitle(e)||"entry",o=document.createDocumentFragment();o.createSpan({text:`Deleted \u201C${i}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new it.Notice(o,6e3);r.addEventListener("click",()=>{if(r.hasAttribute("disabled"))return;r.setAttribute("disabled","true");let l=Math.min(n,this.rows.length);this.rows.splice(l,0,e),this.scheduleSave(),this.renderViewPreservingScroll(),a.hide(),new it.Notice(`Restored \u201C${i}\u201D`,2500)})}openRowContextMenu(e,n){let i=new it.Menu;i.addItem(a=>a.setTitle("Open / Create Notes file").setIcon("file-text").onClick(()=>this.openOrCreateNotes(e))),i.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&&(i.addSeparator(),a.forEach(l=>{l!==e[o]&&i.addItem(c=>c.setTitle(`Mark as: ${l}`).onClick(()=>{e[o]=l,this.scheduleSave(),this.renderViewPreservingScroll()}))}))}i.addSeparator();let r=this.isHighlighted(e);i.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderViewPreservingScroll()})),i.addSeparator(),i.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),i.showAtMouseEvent(n)}async openOrCreateNotes(e){var o,r;let n=this.notesFilePath(e),i=this.app.vault.getAbstractFileByPath(n);if(!i){let a={},l=Ss(this)?Vo(this):null,c=l?((o=e[l])!=null?o:"").split(",").map(p=>Ko(p.trim())).filter(Boolean).map(p=>`project-${p}`):[];c.length&&(a.tags=c);for(let p of this.headers)!this.isNotesCol(p)&&e[p]&&(a[p]=e[p]);this.file&&!Object.keys(a).some(p=>p.toLowerCase()==="source")&&(a.source=`[[${this.file.path}]]`);let d=["---",(0,it.stringifyYaml)(a).trimEnd(),"---","",`# ${this.getTitle(e)}`,"",""].join(` +`),h=this.headers.find(p=>this.isNotesCol(p)),u=d+(h&&((r=e[h])!=null&&r.trim())?e[h]:""),f=n.substring(0,n.lastIndexOf("/"));f&&!this.app.vault.getAbstractFileByPath(f)&&await this.app.vault.createFolder(f),i=await this.app.vault.create(n,u),new it.Notice(`Created: ${i.name}`)}await this.app.workspace.getLeaf("tab").openFile(i)}openNoteExpander(e,n){var i,o;new ts(this.app,e,n,this.headers,(o=(i=this.file)==null?void 0:i.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,c,d,h,u;let e=this.contentEl,n=e.querySelector(".csv-content-area"),i=e.querySelector(".csv-table-wrapper"),o=e.querySelector(".csv-kanban-board"),r={contentTop:(l=n==null?void 0:n.scrollTop)!=null?l:0,contentLeft:(c=n==null?void 0:n.scrollLeft)!=null?c:0,tableLeft:(d=i==null?void 0:i.scrollLeft)!=null?d:0,tableTop:(h=i==null?void 0:i.scrollTop)!=null?h:0,boardLeft:(u=o==null?void 0:o.scrollLeft)!=null?u:0,cols:new Map};e.querySelectorAll(".csv-kanban-col").forEach(f=>{var m,b;let p=(b=(m=f.querySelector(".csv-kanban-col-title"))==null?void 0:m.textContent)!=null?b:"",g=f.querySelector(".csv-kanban-col-body");p&&g&&r.cols.set(p,g.scrollTop)}),this.renderView();let a=()=>{let f=this.contentEl.querySelector(".csv-content-area"),p=this.contentEl.querySelector(".csv-table-wrapper"),g=this.contentEl.querySelector(".csv-kanban-board");f&&(f.scrollTop=r.contentTop,f.scrollLeft=r.contentLeft),p&&(p.scrollLeft=r.tableLeft,p.scrollTop=r.tableTop),g&&(g.scrollLeft=r.boardLeft),this.contentEl.querySelectorAll(".csv-kanban-col").forEach(m=>{var E,S;let b=(S=(E=m.querySelector(".csv-kanban-col-title"))==null?void 0:E.textContent)!=null?S:"",x=m.querySelector(".csv-kanban-col-body"),C=r.cols.get(b);x&&C!=null&&(x.scrollTop=C)})};a(),requestAnimationFrame(()=>{a(),requestAnimationFrame(a)}),setTimeout(a,50)}openAddModal(){let e={};if(Ss(this)){let n=ai(this);n&&(e[n]=["Task","Note","Idea"]);let i=li(this);i&&(e[i]=["Low","Medium","High"])}new Je(this.app,this.headers,this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),n=>{this.rows.push(n),this.scheduleSave(),this.renderViewPreservingScroll(),new it.Notice(`Added: ${this.getTitle(n)}`)},e,n=>this.getBooleanColumns().includes(n),n=>this.isCategoricalCol(n),this.titleKey(),n=>this.isDateCol(n)).open()}renderSelectField(e,n,i){var a;let o=(a=n[i])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),i.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",l=>{var c;l.stopPropagation(),Ft(r,(c=n[i])!=null?c:"",this.getColumnValues(i),d=>{n[i]=d,r.setText(d||"\u2014"),r.className=`csv-select-chip ${d?"":"empty"}`,i.toLowerCase()==="status"&&d&&r.addClass(`status-chip-${d.toLowerCase().replace(/\s+/g,"-")}`),this.scheduleSave()},this.contentEl,{multi:kt(i)})}),r}renderView(e=!1){var o;let n=this.contentEl;e?this.contentArea&&this.contentArea.empty():(n.empty(),n.addClass("datadeck-root"),this.renderComponent.unload(),this.renderComponent=new it.Component,this.renderComponent.load(),oc(this,n),this.contentArea=n.createDiv({cls:"csv-content-area"}),this.installTouchScrollGuard(this.contentArea));let i=this.contentArea;if(i){if(i.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){let r=i.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=i.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"?ar(i,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"?ac(this,i):this.mode==="library"?yn(this,i):this.mode==="kanban-genre"?vn(this,i):this.mode==="stats"?fr(this,i):this.mode==="chart"?Jl(this,i):this.mode==="focus"?lc(this,i):this.mode==="tasks"?ic(this,i):mn(this,i)}}installTouchScrollGuard(e){if(!matchMedia("(pointer: coarse)").matches)return;let n=0,i=0,o=!1;e.addEventListener("touchstart",r=>{r.touches.length===1&&(n=r.touches[0].clientX,i=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-n),l=Math.abs(r.touches[0].clientY-i);(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:"",n=e?`${e}/Archive`:"Archive";await this.app.vault.adapter.exists(n)||await this.app.vault.adapter.mkdir(n);let i=new Date().toISOString().slice(0,10),o=`${n}/${this.file.basename}_${i}.${this.file.extension}`;if(await this.app.vault.adapter.exists(o)){new it.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 it.Notice(`Backed up to ${o}`)}hasDateColumn(){return this.getDateCol()!==null}isTravelFile(){let e=new Set(this.headers.map(n=>n.toLowerCase()));return e.has("country")&&e.has("date_entered")&&e.has("date_left")&&e.has("source")}async loadMapSvg(){if(rn!==void 0)return rn;let e=(0,it.normalizePath)(`${this.app.vault.configDir}/plugins/datadeck/world-map.svg`);try{rn=await this.app.vault.adapter.read(e)}catch(n){rn=null}return rn}getFilteredRows(){var i;let e=this.rows;if(this.searchQuery.trim()){let o=this.searchQuery.toLowerCase().trim();e=e.filter(r=>this.headers.some(a=>{var c;return((c=r[a])!=null?c:"").toLowerCase().includes(o)}))}if(this.mode==="table"&&this.tableSortCol&&this.headers.includes(this.tableSortCol))return Yo(e,this.tableSortCol,this.tableSortDir);let n=this.getDateCol();if(this.mode==="table"&&n){let o=(i=this.fileCfg.sortNewestFirst)!=null?i:!0;e=[...e].sort((r,a)=>{var h,u;let l=(h=r[n])!=null?h:"",c=(u=a[n])!=null?u:"",d=l.localeCompare(c);return o?-d:d})}return e}getDateCol(){if(this.headers.length===0)return null;let e=this.headers[0],n=e.toLowerCase();if(["date","day","datum"].includes(n))return e;let i=this.rows.slice(0,5),o=/^\d{4}-\d{2}-\d{2}$/;return i.length>0&&i.every(a=>{var l;return o.test((l=a[e])!=null?l:"")})?e:null}getBooleanColumns(){return this.fileCfg.habitColumns?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.autoDetectBooleanColumns()}cleanupBooleanColumn(e){let n=0;return this.rows.forEach(i=>{var r;let o=this.isTruthy((r=i[e])!=null?r:"")?"1":"0";i[e]!==o&&n++,i[e]=o}),n>0&&(this.scheduleSave(),this.renderViewPreservingScroll()),n}autoDetectBooleanColumns(){return this.headers.filter(e=>{if(e===this.getDateCol()||this.isNotesCol(e))return!1;let n=this.rows.map(i=>{var o;return((o=i[e])!=null?o:"").toLowerCase().trim()});return Qe(n)})}parseDate(e){let n=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);return n?new Date(parseInt(n[1]),parseInt(n[2])-1,parseInt(n[3])):null}formatDate(e){let n=e.getFullYear(),i=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${n}-${i}-${o}`}isTruthy(e){return Ze(e)}renderMarkdownInto(e,n){var i,o;it.MarkdownRenderer.render(this.app,n,e,(o=(i=this.file)==null?void 0:i.path)!=null?o:"",this.renderComponent)}cycleMode(){let e=ci(this);if(e.length<2)return;let n=e.findIndex(i=>i.id===this.mode);this.mode=e[(n+1)%e.length].id,this.renderView()}onunload(){this.renderComponent.unload(),this.saveTimer&&window.clearTimeout(this.saveTimer)}},Ap=[{id:"tasks",command:"Create tasks file",defaultName:"Tasks",headers:["Title","Priority","Notes","Due","Status"],mode:"tasks",configOverrides:{categoricalColumns:["Priority"],dateColumns:["Due"],habitColumns:["Status"],statusColumn:"Status",notesColumn:"Notes"}},{id:"travel",command:"Create travel file",defaultName:"Travel",headers:["Country","date_entered","date_left","source","Notes"],mode:"travel"},{id:"habits",command:"Create habit tracker file",defaultName:"Habits",headers:["Date","Exercise","Meditate","Read","Notes"],mode:"dashboard"}],hi=class extends it.Plugin{constructor(){super(...arguments);this.settings=mi}async onload(){await this.loadSettings(),this.registerView(ln,e=>new Es(e,this.settings,()=>this.saveSettings())),this.registerExtensions(["csv"],ln),this.addSettingTab(new gn(this.app,this)),this.registerMarkdownCodeBlockProcessor("csv-add",async(e,n,i)=>{await cr(this.app,e.trim(),n,i,this.settings.fileConfigs)}),this.registerMarkdownCodeBlockProcessor("csv-random",async(e,n,i)=>{await rc(this.app,e.trim(),n,i)}),hc(this.app,this.settings,()=>this.saveSettings(),(e,n)=>this.registerMarkdownCodeBlockProcessor(e,n)),pc(this.app,(e,n)=>this.registerMarkdownCodeBlockProcessor(e,n)),this.addCommand({id:"add-entry",name:"Add entry to current CSV",checkCallback:e=>{let n=this.app.workspace.getActiveViewOfType(Es);return n?(e||n.openAddModal(),!0):!1}}),this.addCommand({id:"cycle-view-mode",name:"Cycle view mode",checkCallback:e=>{let n=this.app.workspace.getActiveViewOfType(Es);return n?(e||n.cycleMode(),!0):!1}});for(let e of Ap)this.addCommand({id:`create-${e.id}`,name:e.command,callback:()=>this.createTemplateFile(e)});this.registerEvent(this.app.vault.on("rename",async(e,n)=>{e instanceof it.TFile&&e.extension==="csv"&&this.settings.fileConfigs[n]&&(Zo(this.settings.fileConfigs,n,e.path),await this.saveSettings())})),this.registerEvent(this.app.vault.on("delete",async e=>{e instanceof it.TFile&&this.settings.fileConfigs[e.path]&&(delete this.settings.fileConfigs[e.path],await this.saveSettings())})),this.registerMarkdownCodeBlockProcessor("csv-refresh",(e,n,i)=>{let o=n.createEl("button",{cls:"csv-refresh-btn"});o.innerHTML="\u21BB refresh",o.addEventListener("click",async()=>{let r=i.sourcePath,a=this.app.vault.getAbstractFileByPath(r);if(a instanceof it.TFile){let l=this.app.workspace.activeLeaf;l&&await l.openFile(a,{state:{mode:"preview"}})}})})}async createTemplateFile(e){new un(this.app,e.command,e.defaultName,"File name (without .csv)",async n=>{let i=this.app.workspace.getActiveFile(),o=i!=null&&i.parent&&i.parent.path!=="/"?`${i.parent.path}/`:"",r=Ms(n),a=(0,it.normalizePath)(`${o}${r}.csv`);for(let d=2;this.app.vault.getAbstractFileByPath(a);d++)a=(0,it.normalizePath)(`${o}${r} ${d}.csv`);let l=await this.app.vault.create(a,e.headers.join(",")+` +`),c=this.settings.fileConfigs[l.path]||{};this.settings.fileConfigs[l.path]={...c,defaultMode:e.mode,...e.configOverrides||{}},await this.saveSettings(),await this.app.workspace.getLeaf("tab").openFile(l),new it.Notice(`Created: ${l.name}`)}).open()}async loadSettings(){var e;this.settings=Object.assign({},mi,await this.loadData()),this.settings.residencyRules=JSON.parse(JSON.stringify((e=this.settings.residencyRules)!=null?e:[]))}async saveSettings(){await this.saveData(this.settings)}}; /*! Bundled license information: papaparse/papaparse.min.js: diff --git a/main.ts b/main.ts index d73dbc9..236eaef 100644 --- a/main.ts +++ b/main.ts @@ -32,9 +32,11 @@ import { renderToolbar, availableModes } from "./src/view/toolbar"; import { renderRandomCard } from "./src/random-block"; import { renderDashboard } from "./src/view/dashboard"; import { renderStats, hasStatsColumns } from "./src/view/stats"; +import { renderChart, hasChartColumns } from "./src/view/chart"; import { renderFocus } from "./src/view/focus"; import { renderTasks, hasTaskColumns, taskProjectCol, taskTypeCol, taskPriorityCol } from "./src/view/tasks"; import { registerCsvViewBlock } from "./src/inline-view"; +import { registerCsvChartBlock } from "./src/chart-block"; // World-map SVG asset, loaded lazily from the plugin dir and cached for the // session (undefined = not yet read, null = read failed/missing). @@ -111,6 +113,7 @@ export class CardView extends FileView { if ((needsCategory && !effectiveGroupCol(this)) || (needsDate && !this.hasDateColumn()) || (this.mode === "travel" && !this.isTravelFile()) || (this.mode === "stats" && !hasStatsColumns(this)) + || (this.mode === "chart" && !hasChartColumns(this)) || (this.mode === "tasks" && !hasTaskColumns(this))) { this.mode = "table"; } @@ -628,6 +631,7 @@ export class CardView extends FileView { else if (this.mode === "library") renderLibrary(this, content); else if (this.mode === "kanban-genre") renderKanbanGenre(this, content); else if (this.mode === "stats") renderStats(this, content); + else if (this.mode === "chart") void renderChart(this, content); else if (this.mode === "focus") renderFocus(this, content); else if (this.mode === "tasks") renderTasks(this, content); else renderTable(this, content); @@ -982,6 +986,14 @@ export default class CardViewPlugin extends Plugin { (lang, handler) => this.registerMarkdownCodeBlockProcessor(lang, handler), ); + // csv-chart: an inline read-only chart of a CSV (or a pure y = f(x) + // formula plot) — scatter/line, best-fit, formula overlay. See + // src/chart-block.ts. + registerCsvChartBlock( + this.app, + (lang, handler) => this.registerMarkdownCodeBlockProcessor(lang, handler), + ); + // Palette commands — operate on the active CSV view, so they're // hotkey-able (Settings → Hotkeys → filter "CSV Card View"). this.addCommand({ diff --git a/src/chart-block.ts b/src/chart-block.ts new file mode 100644 index 0000000..97524ac --- /dev/null +++ b/src/chart-block.ts @@ -0,0 +1,201 @@ +// ─── csv-chart code block: an inline chart in any note ─────────────────────── +// +// Embeds a Chart.js scatter/line plot of a CSV's columns — or a pure formula +// curve with no data at all — inside a note, the way csv-view embeds a table. +// +// ```csv-chart +// file: ../health.csv (sibling / ../ walked / vault-relative, like csv-view; +// omit entirely for a formula-only plot) +// x: date (optional — default: date column → first numeric) +// y: weight (optional — default: first numeric column ≠ x) +// fit: linear (optional best-fit line with equation + R²) +// formula: 0.5x + 2 (optional y = f(x) overlay; the whole plot when +// there's no file. See src/formula.ts for syntax.) +// xmin: -10 (formula-only plots: domain, default -10 … 10) +// xmax: 10 +// height: 280 (optional px height) +// ``` +// +// Read-only: it re-renders off the vault `modify` event when the source CSV +// changes (edited in a DataDeck tab, a csv-view block, or external sync), but +// never writes. Reuses the extraction / fit / config core from src/view/chart.ts +// and the shared lazy Chart.js loader. Covered by test-view-smoke.mjs. + +import { App, MarkdownPostProcessorContext, MarkdownRenderChild, TFile } from "obsidian"; +import { CSVRow } from "./types"; +import { parseCSV, resolvePath } from "./utils"; +import { isDateCol } from "./field-types"; +import { loadChart } from "./chartjs-loader"; +import { + buildChartConfig, extractPoints, numericColumns, resolveChartColors, + ChartSpec, +} from "./view/chart"; + +interface ChartBlockOptions { + file: string; + x: string; + y: string; + fit: "none" | "linear"; + formula: string; + xmin: number | null; + xmax: number | null; + height: number | null; +} + +/** Parse the `key: value` lines of a csv-chart block. Forgiving, like csv-view. */ +function parseBlockSource(source: string): ChartBlockOptions { + const lines = source.split("\n").map(l => l.trim()).filter(Boolean); + const opt = (key: string) => + lines.find(l => l.toLowerCase().startsWith(key + ":"))?.slice(key.length + 1).trim() ?? ""; + const num = (key: string): number | null => { + const n = parseFloat(opt(key)); + return Number.isFinite(n) ? n : null; + }; + return { + file: opt("file"), + x: opt("x"), + y: opt("y"), + fit: opt("fit").toLowerCase() === "linear" ? "linear" : "none", + formula: opt("formula"), + xmin: num("xmin"), + xmax: num("xmax"), + height: num("height"), + }; +} + +/** Duck-typed TFile check — mirrors inline-view.ts (cross-bundle instanceof is unreliable). */ +function asFile(f: unknown): TFile | null { + return f && typeof f === "object" && "basename" in (f as object) ? (f as TFile) : null; +} + +function parseIsoDate(s: string): Date | null { + const m = (s ?? "").trim().match(/^(\d{4})-(\d{2})-(\d{2})/); + if (!m) return null; + return new Date(parseInt(m[1]), parseInt(m[2]) - 1, parseInt(m[3])); +} + +class ChartBlock extends MarkdownRenderChild { + private chart: { destroy(): void } | null = null; + + constructor( + containerEl: HTMLElement, + private app: App, + private opts: ChartBlockOptions, + ) { + super(containerEl); + } + + async onload(): Promise { + this.containerEl.addClass("csv-chart-block"); + await this.render(); + if (this.opts.file) { + this.registerEvent(this.app.vault.on("modify", (f) => { + if (f.path === this.opts.file) void this.render(); + })); + this.registerEvent(this.app.vault.on("rename", (f, oldPath) => { + if (oldPath === this.opts.file) this.opts.file = f.path; + })); + } + } + + onunload(): void { + if (this.chart) { this.chart.destroy(); this.chart = null; } + } + + private renderError(msg: string): void { + this.containerEl.empty(); + this.containerEl.createEl("p", { text: `csv-chart: ${msg}`, cls: "csv-add-error" }); + } + + private async render(): Promise { + const root = this.containerEl; + if (this.chart) { this.chart.destroy(); this.chart = null; } + root.empty(); + + let spec: ChartSpec; + let skipped = 0; + + if (this.opts.file) { + const file = asFile(this.app.vault.getAbstractFileByPath(this.opts.file)); + if (!file) return this.renderError(`File not found: ${this.opts.file}`); + let headers: string[], rows: CSVRow[]; + try { + ({ headers, rows } = parseCSV(await this.app.vault.read(file))); + } catch (e) { + return this.renderError(`Error reading file: ${e instanceof Error ? e.message : String(e)}`); + } + + const findCol = (name: string) => headers.find(h => h.toLowerCase() === name.toLowerCase()) ?? null; + const numCols = numericColumns(headers, rows); + // Same date heuristic as the views: a date-named column, or a first + // column whose sample values are yyyy-mm-dd. + const dateCol = headers.find(h => isDateCol(h)) + ?? (rows.slice(0, 5).length && rows.slice(0, 5).every(r => parseIsoDate(r[headers[0]] ?? "")) ? headers[0] : null); + + const xCol = this.opts.x ? findCol(this.opts.x) : (dateCol ?? numCols[0] ?? null); + if (this.opts.x && !xCol) return this.renderError(`No column "${this.opts.x}" in ${file.basename}`); + const yCol = this.opts.y ? findCol(this.opts.y) : numCols.find(c => c !== xCol) ?? null; + if (this.opts.y && !yCol) return this.renderError(`No column "${this.opts.y}" in ${file.basename}`); + if (!xCol || !yCol) return this.renderError(`Couldn't auto-pick x/y columns — add "x:" and "y:" lines`); + + const isDateX = xCol === dateCol || isDateCol(xCol); + const extracted = extractPoints(rows, xCol, yCol, isDateX, parseIsoDate, r => r[headers[0]] ?? ""); + skipped = extracted.skipped; + if (!extracted.points.length) return this.renderError(`No rows with numeric "${xCol}" and "${yCol}" values`); + + spec = { + points: extracted.points, + xIsDate: isDateX, + xLabel: xCol, + yLabel: yCol, + connect: isDateX, + fit: this.opts.fit, + formula: this.opts.formula, + }; + } else { + // Formula-only plot: no data, just the curve over an explicit domain. + if (!this.opts.formula.trim()) return this.renderError(`Give a "file:" line, a "formula:" line, or both`); + spec = { + points: [], + xIsDate: false, + xLabel: "x", + yLabel: "y", + connect: false, + fit: "none", + formula: this.opts.formula, + xMin: this.opts.xmin ?? -10, + xMax: this.opts.xmax ?? 10, + }; + } + + const built = buildChartConfig(spec, resolveChartColors(root)); + if (built.formulaError) return this.renderError(`formula: ${built.formulaError}`); + + const wrap = root.createDiv({ cls: "csv-chart-wrap" }); + if (this.opts.height) wrap.style.height = this.opts.height + "px"; + const canvas = wrap.createEl("canvas", { cls: "csv-chart-canvas" }); + + if (built.fitText || skipped > 0) { + const footer = root.createDiv({ cls: "csv-chart-footer" }); + if (built.fitText) footer.createSpan({ cls: "csv-chart-fit-text", text: built.fitText }); + if (skipped > 0) footer.createSpan({ cls: "csv-chart-skipped", text: `${skipped} row${skipped === 1 ? "" : "s"} skipped (no numeric value)` }); + } + + const { Chart } = await loadChart(); + if (!canvas.isConnected) return; + this.chart = new Chart(canvas, built.config); + } +} + +/** csv-chart block processor. Each block gets its own child tied to the block's lifecycle. */ +export function registerCsvChartBlock( + app: App, + register: (lang: string, handler: (source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) => void) => void, +): void { + register("csv-chart", (source, el, ctx) => { + const opts = parseBlockSource(source); + const noteFolder = app.vault.getAbstractFileByPath(ctx.sourcePath)?.parent?.path ?? ""; + const resolved = opts.file ? resolvePath(opts.file, noteFolder) : opts.file; + ctx.addChild(new ChartBlock(el, app, { ...opts, file: resolved })); + }); +} diff --git a/src/chartjs-loader.ts b/src/chartjs-loader.ts new file mode 100644 index 0000000..a818a94 --- /dev/null +++ b/src/chartjs-loader.ts @@ -0,0 +1,23 @@ +// Shared lazy Chart.js loader. Chart.js is ~200KB of init cost, so it's only +// paid the first time a chart actually renders (dashboard progress chart, +// Chart view, or a csv-chart block) — sessions that never chart never load it. +// Registers the superset of components those three consumers use; registering +// is idempotent so the union is cheaper than per-consumer bookkeeping. +// Covered by test-view-smoke.mjs (with a chart.js stub). + +type ChartModule = typeof import("chart.js"); + +let chartModule: ChartModule | null = null; + +export async function loadChart(): Promise { + if (chartModule) return chartModule; + const mod = await import("chart.js"); + mod.Chart.register( + mod.LineController, mod.ScatterController, + mod.LineElement, mod.PointElement, + mod.LinearScale, mod.CategoryScale, + mod.Filler, mod.Tooltip, mod.Legend, + ); + chartModule = mod; + return mod; +} diff --git a/src/formula.ts b/src/formula.ts new file mode 100644 index 0000000..a211279 --- /dev/null +++ b/src/formula.ts @@ -0,0 +1,176 @@ +// Safe y = f(x) expression compiler for the Chart view and csv-chart blocks. +// A tiny tokenizer + recursive-descent parser — no eval/Function, so it's +// community-plugin-store safe and can't touch anything outside pure math. +// +// Supported: numbers, x, pi/e, + - * / % ^ (right-assoc), unary minus, +// parentheses, one/two-arg functions (sin cos tan asin acos atan sqrt log ln +// exp abs floor ceil round sign min max pow atan2), and implicit +// multiplication ("2x", "3(x+1)", "x sin(x)") so formulas read naturally. +// Compiles once into a closure tree; evaluation per sample is just calls. +// Covered by test-view-smoke.mjs. + +export type CompiledFormula = (x: number) => number; + +const CONSTANTS: Record = { pi: Math.PI, e: Math.E }; + +const FUNCS_1: Record number> = { + 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, +}; + +const FUNCS_2: Record number> = { + min: Math.min, max: Math.max, pow: Math.pow, atan2: Math.atan2, +}; + +type Token = + | { kind: "num"; value: number } + | { kind: "ident"; name: string } + | { kind: "op"; op: string } // + - * / % ^ + | { kind: "lparen" } | { kind: "rparen" } | { kind: "comma" }; + +function tokenize(src: string): Token[] { + const tokens: Token[] = []; + let i = 0; + while (i < src.length) { + const ch = src[i]; + if (/\s/.test(ch)) { i++; continue; } + if (/[0-9.]/.test(ch)) { + const m = src.slice(i).match(/^\d*\.?\d+(?:[eE][+-]?\d+)?/); + if (!m || m[0] === "") throw new Error(`Bad number at "${src.slice(i, i + 8)}"`); + tokens.push({ kind: "num", value: parseFloat(m[0]) }); + i += m[0].length; + continue; + } + if (/[a-zA-Z_]/.test(ch)) { + const m = src.slice(i).match(/^[a-zA-Z_][a-zA-Z_0-9]*/)!; + tokens.push({ kind: "ident", name: m[0].toLowerCase() }); + i += m[0].length; + continue; + } + if ("+-*/%^".includes(ch)) { tokens.push({ kind: "op", op: ch }); i++; continue; } + if (ch === "(") { tokens.push({ kind: "lparen" }); i++; continue; } + if (ch === ")") { tokens.push({ kind: "rparen" }); i++; continue; } + if (ch === ",") { tokens.push({ kind: "comma" }); i++; continue; } + throw new Error(`Unexpected character "${ch}"`); + } + return tokens; +} + +/** + * Compile an expression like "2x^2 - 3x + 1" or "10 sin(x/2)" into a plain + * (x) => number. Throws Error with a human-readable message on bad input — + * callers show it inline next to the formula field. + */ +export function compileFormula(source: string): CompiledFormula { + // Allow a leading "y =" / "f(x) =" so users can paste equations verbatim. + const cleaned = source.trim().replace(/^(y|f\s*\(\s*x\s*\))\s*=\s*/i, ""); + if (!cleaned) throw new Error("Empty formula"); + const tokens = tokenize(cleaned); + let pos = 0; + + const peek = (): Token | null => tokens[pos] ?? null; + const next = (): Token | null => tokens[pos++] ?? null; + + // expr := term (('+'|'-') term)* + function parseExpr(): CompiledFormula { + let left = parseTerm(); + for (;;) { + const t = peek(); + if (t?.kind === "op" && (t.op === "+" || t.op === "-")) { + pos++; + const right = parseTerm(); + const l = left, op = t.op; + left = op === "+" ? (x) => l(x) + right(x) : (x) => l(x) - right(x); + } else return left; + } + } + + // term := unary (('*'|'/'|'%'| implicit-mult) unary)* + function parseTerm(): CompiledFormula { + let left = parseUnary(); + for (;;) { + const t = peek(); + if (t?.kind === "op" && (t.op === "*" || t.op === "/" || t.op === "%")) { + pos++; + const right = parseUnary(); + const l = left, op = t.op; + left = op === "*" ? (x) => l(x) * right(x) + : op === "/" ? (x) => l(x) / right(x) + : (x) => l(x) % right(x); + } else if (t && (t.kind === "num" || t.kind === "ident" || t.kind === "lparen")) { + // implicit multiplication: 2x, 3(x+1), x sin(x) + const right = parseUnary(); + const l = left; + left = (x) => l(x) * right(x); + } else return left; + } + } + + // unary := '-' unary | power + function parseUnary(): CompiledFormula { + const t = peek(); + if (t?.kind === "op" && t.op === "-") { + pos++; + const operand = parseUnary(); + return (x) => -operand(x); + } + if (t?.kind === "op" && t.op === "+") { pos++; return parseUnary(); } + return parsePower(); + } + + // power := atom ('^' unary)? — right-associative, and -x^2 = -(x^2) + function parsePower(): CompiledFormula { + const base = parseAtom(); + const t = peek(); + if (t?.kind === "op" && t.op === "^") { + pos++; + const exp = parseUnary(); + return (x) => Math.pow(base(x), exp(x)); + } + return base; + } + + // atom := number | x | constant | func '(' expr (',' expr)? ')' | '(' expr ')' + function parseAtom(): CompiledFormula { + const t = next(); + if (!t) throw new Error("Unexpected end of formula"); + if (t.kind === "num") { const v = t.value; return () => v; } + if (t.kind === "lparen") { + const inner = parseExpr(); + if (next()?.kind !== "rparen") throw new Error("Missing closing )"); + return inner; + } + if (t.kind === "ident") { + if (t.name === "x") return (x) => x; + if (t.name in CONSTANTS) { const v = CONSTANTS[t.name]; return () => v; } + const isCall = peek()?.kind === "lparen"; + if (t.name in FUNCS_1 || t.name in FUNCS_2) { + if (!isCall) throw new Error(`${t.name} needs parentheses, e.g. ${t.name}(x)`); + pos++; // consume ( + const a = parseExpr(); + if (t.name in FUNCS_2) { + if (next()?.kind !== "comma") throw new Error(`${t.name}(a, b) needs two arguments`); + const b = parseExpr(); + if (next()?.kind !== "rparen") throw new Error("Missing closing )"); + const fn = FUNCS_2[t.name]; + return (x) => fn(a(x), b(x)); + } + if (next()?.kind !== "rparen") throw new Error("Missing closing )"); + const fn = FUNCS_1[t.name]; + return (x) => fn(a(x)); + } + throw new Error(`Unknown name "${t.name}" — use x, pi, e, or a function like sin()`); + } + throw new Error(`Unexpected "${t.kind === "op" ? t.op : t.kind}"`); + } + + const compiled = parseExpr(); + if (pos < tokens.length) { + const t = tokens[pos]; + throw new Error(`Unexpected "${t.kind === "op" ? t.op : t.kind === "ident" ? t.name : t.kind}" after end of expression`); + } + return compiled; +} diff --git a/src/types.ts b/src/types.ts index 99c6249..0e02db8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,7 @@ // ─── Types ──────────────────────────────────────────────────────────────────── export interface CSVRow { [key: string]: string; } -export type ViewMode = "kanban-genre" | "table" | "dashboard" | "library" | "travel" | "stats" | "focus" | "tasks"; +export type ViewMode = "kanban-genre" | "table" | "dashboard" | "library" | "travel" | "stats" | "focus" | "tasks" | "chart"; // ─── Residency / threshold rules (travel view) ────────────────────────────── // A declarative rule: count days a person was in `scope` within `window`, @@ -63,6 +63,11 @@ export interface FileConfig { // the row context menu. Keyed by value (like // collapsedGroups) rather than a row id — the // CSV has no stable identity column. + chartXCol?: string; // Chart view X column. Unset = date col → first + // numeric → row number (see src/view/chart.ts). + chartYCol?: string; // Chart view Y column. Unset = first numeric ≠ X. + chartFit?: "none" | "linear"; // Chart view best-fit line toggle. + chartFormula?: string; // Chart view y = f(x) overlay (src/formula.ts). } export type LibrarySort = "status" | "title" | "rating" | "year"; diff --git a/src/view/chart.ts b/src/view/chart.ts new file mode 100644 index 0000000..23bb283 --- /dev/null +++ b/src/view/chart.ts @@ -0,0 +1,402 @@ +// Chart view renderer — scatter/line plots of one column against another, +// with an optional least-squares fit line (equation + R² shown below) and an +// optional y = f(x) formula overlay (safe evaluator, see src/formula.ts). +// Chart.js is lazy-loaded via src/chartjs-loader.ts, same deal as the +// dashboard: the controls render synchronously, the canvas paints when the +// module arrives. X/Y/fit/formula picks persist per file in fileCfg. +// The csv-chart code block (src/chart-block.ts) reuses the extraction + +// config-building core below. Covered by test-view-smoke.mjs (chart.js stub). + +import type { ChartConfiguration, TooltipItem } from "chart.js"; +import type { CardView } from "../../main"; +import { CSVRow } from "../types"; +import { loadChart } from "../chartjs-loader"; +import { compileFormula } from "../formula"; + +// ── Numeric parsing / column detection ────────────────────────────────────── + +/** + * Parse a cell into a finite number, or null. Tolerates thousands separators + * ("1,234" / "1 234") and a European decimal comma ("3,5") — data typed on a + * Swedish keyboard should chart without a cleanup pass. + */ +export function parseNumeric(raw: string): number | null { + let s = (raw ?? "").trim(); + if (!s) return null; + if (/^-?\d{1,3}(?:[,\s]\d{3})+(?:\.\d+)?$/.test(s)) s = s.replace(/[,\s]/g, ""); + else if (/^-?\d+,\d+$/.test(s)) s = s.replace(",", "."); + if (!/^-?\d*\.?\d+(?:[eE][+-]?\d+)?$/.test(s)) return null; + const n = parseFloat(s); + return Number.isFinite(n) ? n : null; +} + +/** + * Headers that are chartable as numbers: at least two non-empty values and a + * 70%+ numeric hit rate (so an odd "n/a" doesn't disqualify a column). + */ +export function numericColumns(headers: string[], rows: CSVRow[]): string[] { + return headers.filter(h => { + let nonEmpty = 0, numeric = 0; + for (const r of rows) { + const v = (r[h] ?? "").trim(); + if (!v) continue; + nonEmpty++; + if (parseNumeric(v) !== null) numeric++; + } + return numeric >= 2 && numeric / nonEmpty >= 0.7; + }); +} + +// ── Fit + config building (shared with the csv-chart block) ───────────────── + +export interface LinearFit { slope: number; intercept: number; r2: number; } + +/** Least-squares linear regression. Null when <2 points or X has no spread. */ +export function linearFit(pts: { x: number; y: number }[]): LinearFit | null { + const n = pts.length; + if (n < 2) return null; + let sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0; + for (const p of pts) { sx += p.x; sy += p.y; sxx += p.x * p.x; sxy += p.x * p.y; syy += p.y * p.y; } + const denom = n * sxx - sx * sx; + if (denom === 0) return null; + const slope = (n * sxy - sx * sy) / denom; + const intercept = (sy - slope * sx) / n; + // R² = 1 - SSres/SStot (1 when Y is constant — the flat line fits exactly) + const meanY = sy / n; + let ssRes = 0, ssTot = 0; + for (const p of pts) { + const e = p.y - (slope * p.x + intercept); + ssRes += e * e; + ssTot += (p.y - meanY) * (p.y - meanY); + } + return { slope, intercept, r2: ssTot === 0 ? 1 : 1 - ssRes / ssTot }; +} + +export interface ChartPoint { x: number; y: number; label?: string; } + +export interface ChartSpec { + points: ChartPoint[]; + xIsDate: boolean; // X values are ms timestamps → date-formatted ticks + xLabel: string; + yLabel: string; + connect: boolean; // draw the series as a line (sorted by x) vs dots + fit: "none" | "linear"; + formula: string; // raw y=f(x) text, "" = none + // Domain for a pure-formula plot with no data points. + xMin?: number; + xMax?: number; +} + +/** Theme colors resolved from CSS variables at render time (canvas needs concrete values). */ +export interface ChartColors { accent: string; muted: string; grid: string; fitLine: string; formula: string; } + +export function resolveChartColors(el: HTMLElement): ChartColors { + // Via the element's own window — a bare getComputedStyle global doesn't + // exist in the jsdom smoke tests (and popout windows have their own). + const css = el.ownerDocument.defaultView?.getComputedStyle(el); + const v = (name: string, fallback: string) => css?.getPropertyValue(name).trim() || fallback; + return { + accent: v("--interactive-accent", "#378ADD"), + muted: v("--text-muted", "#888888"), + grid: v("--background-modifier-border", "rgba(128,128,128,0.25)"), + fitLine: v("--text-faint", "#999999"), + formula: v("--color-orange", "#e0883a"), + }; +} + +const fmtNum = (n: number): string => { + if (!Number.isFinite(n)) return String(n); + const abs = Math.abs(n); + return abs !== 0 && (abs >= 1e6 || abs < 1e-3) ? n.toExponential(2) : String(Math.round(n * 1000) / 1000); +}; + +const fmtDate = (ms: number): string => { + const d = new Date(ms); + return isNaN(d.getTime()) ? String(ms) : d.toISOString().slice(0, 10); +}; + +export interface BuiltChart { + config: ChartConfiguration; + /** "y = 2.35x + 1.2 · R² = 0.91" (or the per-day phrasing for date X), null when no fit drawn. */ + fitText: string | null; + /** Compile error for the formula overlay, null when it parsed (or was empty). */ + formulaError: string | null; +} + +/** + * Build a Chart.js scatter config from a spec: data points, optional fit-line + * dataset, optional formula-overlay dataset. Pure — no DOM, no Chart.js + * import — so the smoke tests can assert on it without a canvas. + */ +export function buildChartConfig(spec: ChartSpec, colors: ChartColors): BuiltChart { + const datasets: ChartConfiguration<"scatter" | "line">["data"]["datasets"] = []; + const pts = spec.connect ? [...spec.points].sort((a, b) => a.x - b.x) : spec.points; + + if (pts.length) { + datasets.push({ + type: spec.connect ? "line" : "scatter", + label: spec.yLabel, + data: pts, + backgroundColor: colors.accent, + borderColor: colors.accent, + borderWidth: 1.5, + pointRadius: spec.connect ? 3 : 4, + pointHoverRadius: 6, + tension: 0.3, + }); + } + + const xs = pts.map(p => p.x); + const xMin = pts.length ? Math.min(...xs) : (spec.xMin ?? 0); + const xMax = pts.length ? Math.max(...xs) : (spec.xMax ?? 10); + + let fitText: string | null = null; + if (spec.fit === "linear") { + const fit = linearFit(pts); + if (fit && xMax > xMin) { + datasets.push({ + type: "line", + label: "Best fit", + data: [ + { x: xMin, y: fit.slope * xMin + fit.intercept }, + { x: xMax, y: fit.slope * xMax + fit.intercept }, + ], + borderColor: colors.fitLine, + borderDash: [6, 4], + borderWidth: 1.5, + pointRadius: 0, + pointHitRadius: 0, + }); + const r2 = ` · R² = ${(Math.round(fit.r2 * 1000) / 1000).toFixed(3)}`; + if (spec.xIsDate) { + // Slope is per millisecond — meaningless to read. Phrase it per day. + const perDay = fit.slope * 86_400_000; + fitText = `Trend: ${perDay >= 0 ? "+" : ""}${fmtNum(perDay)} ${spec.yLabel}/day${r2}`; + } else { + const sign = fit.intercept >= 0 ? "+" : "−"; + fitText = `y = ${fmtNum(fit.slope)}x ${sign} ${fmtNum(Math.abs(fit.intercept))}${r2}`; + } + } + } + + let formulaError: string | null = null; + if (spec.formula.trim()) { + try { + const f = compileFormula(spec.formula); + const samples: ChartPoint[] = []; + const steps = 160; + for (let i = 0; i <= steps; i++) { + const x = xMin + ((xMax - xMin) * i) / steps; + const y = f(x); + if (Number.isFinite(y)) samples.push({ x, y }); + } + if (samples.length) { + datasets.push({ + type: "line", + label: spec.formula.trim(), + data: samples, + borderColor: colors.formula, + borderWidth: 1.5, + pointRadius: 0, + pointHitRadius: 0, + tension: 0, + }); + } + } catch (e) { + formulaError = e instanceof Error ? e.message : String(e); + } + } + + const config: ChartConfiguration = { + type: "scatter", + data: { datasets }, + options: { + responsive: true, + maintainAspectRatio: false, + scales: { + x: { + type: "linear", + title: { display: !spec.xIsDate && !!spec.xLabel, text: spec.xLabel, color: colors.muted }, + ticks: { + color: colors.muted, + ...(spec.xIsDate ? { callback: (v: unknown) => fmtDate(Number(v)), maxTicksLimit: 8 } : {}), + }, + grid: { color: colors.grid }, + }, + y: { + title: { display: !!spec.yLabel, text: spec.yLabel, color: colors.muted }, + ticks: { color: colors.muted }, + grid: { color: colors.grid }, + }, + }, + plugins: { + legend: { + display: datasets.length > 1, + labels: { color: colors.muted, boxWidth: 12 }, + }, + tooltip: { + callbacks: { + label: (item: TooltipItem<"scatter">) => { + const p = item.raw as ChartPoint; + const x = spec.xIsDate ? fmtDate(p.x) : fmtNum(p.x); + const head = p.label ? `${p.label}: ` : ""; + return `${head}(${x}, ${fmtNum(p.y)})`; + }, + }, + }, + }, + } as ChartConfiguration["options"], + }; + return { config, fitText, formulaError }; +} + +// ── Data extraction ────────────────────────────────────────────────────────── + +const ROW_INDEX = "(row number)"; + +/** + * Rows → points for an x/y column pair. `xCol` may be a date column (values + * parsed via `parseDate`), a numeric column, or ROW_INDEX. Rows where either + * side doesn't parse are skipped and counted. + */ +export function extractPoints( + rows: CSVRow[], + xCol: string, + yCol: string, + isDateX: boolean, + parseDate: (s: string) => Date | null, + labelOf: (row: CSVRow) => string, +): { points: ChartPoint[]; skipped: number } { + const points: ChartPoint[] = []; + let skipped = 0; + rows.forEach((r, i) => { + const y = parseNumeric(r[yCol] ?? ""); + let x: number | null; + if (xCol === ROW_INDEX) x = i + 1; + else if (isDateX) { + const d = parseDate(r[xCol] ?? ""); + x = d ? d.getTime() : null; + } else x = parseNumeric(r[xCol] ?? ""); + if (x === null || y === null) { skipped++; return; } + points.push({ x, y, label: labelOf(r) }); + }); + return { points, skipped }; +} + +// ── The Chart view ─────────────────────────────────────────────────────────── + +/** True when the file has a column pair worth plotting (≥1 numeric column). */ +export function hasChartColumns(view: CardView): boolean { + return view.rows.length >= 2 && numericColumns(view.headers, view.rows).length >= 1; +} + +export async function renderChart(view: CardView, container: HTMLElement): Promise { + const rows = view.getFilteredRows(); + const numCols = numericColumns(view.headers, view.rows); + if (!numCols.length) { + container.createEl("p", { text: "No numeric column to chart.", cls: "csv-empty-state" }); + return; + } + + if (view.searchQuery.trim()) { + container.createDiv({ cls: "csv-search-results", text: `Chart over ${rows.length} of ${view.rows.length} entries` }); + } + + const cfg = view.fileCfg; + const dateCol = view.getDateCol(); + + // X candidates: the date column first (time series is the common case), + // then every numeric column, then plain row order as a fallback. + const xOptions = [...(dateCol ? [dateCol] : []), ...numCols.filter(c => c !== dateCol), ROW_INDEX]; + let xCol = cfg.chartXCol && xOptions.includes(cfg.chartXCol) ? cfg.chartXCol : xOptions[0]; + const yOptions = numCols; + let yCol = cfg.chartYCol && yOptions.includes(cfg.chartYCol) + ? cfg.chartYCol + : yOptions.find(c => c !== xCol) ?? yOptions[0]; + const fit: "none" | "linear" = cfg.chartFit === "linear" ? "linear" : "none"; + const formula = cfg.chartFormula ?? ""; + + const wrap = container.createDiv({ cls: "csv-chart-view" }); + + // ── Controls ────────────────────────────────────────────────────────────── + const controls = wrap.createDiv({ cls: "csv-chart-controls" }); + const save = (patch: Partial) => { + view.saveFileCfg({ ...view.fileCfg, ...patch }); + view.renderViewPreservingScroll(); + }; + const labeledSelect = (label: string, options: string[], value: string, onChange: (v: string) => void) => { + const group = controls.createDiv({ cls: "csv-chart-control" }); + group.createSpan({ cls: "csv-chart-control-label", text: label }); + const sel = group.createEl("select", { cls: "csv-chart-select", attr: { "aria-label": label } }); + options.forEach(o => { + const opt = sel.createEl("option", { text: o, value: o }); + if (o === value) opt.selected = true; + }); + sel.addEventListener("change", () => onChange(sel.value)); + return sel; + }; + + labeledSelect("X", xOptions, xCol, v => save({ chartXCol: v })); + labeledSelect("Y", yOptions, yCol, v => save({ chartYCol: v })); + + const fitBtn = controls.createEl("button", { + cls: `csv-cfg-btn csv-chart-fit-btn ${fit === "linear" ? "active" : ""}`, + text: "Best fit", + title: "Toggle a least-squares fit line", + }); + fitBtn.addEventListener("click", () => save({ chartFit: fit === "linear" ? "none" : "linear" })); + + // Formula applies on Enter/blur, not per keystroke — the whole view + // re-renders on apply, which would eat the input focus mid-typing. + const formulaWrap = controls.createDiv({ cls: "csv-chart-control csv-chart-formula-wrap" }); + formulaWrap.createSpan({ cls: "csv-chart-control-label", text: "y =" }); + const formulaInput = formulaWrap.createEl("input", { + cls: "csv-chart-formula-input", + type: "text", + value: formula, + placeholder: "overlay, e.g. 2x + 1", + attr: { spellcheck: "false", autocomplete: "off", enterkeyhint: "done" }, + }); + const applyFormula = () => { + if (formulaInput.value.trim() === formula.trim()) return; + save({ chartFormula: formulaInput.value }); + }; + formulaInput.addEventListener("change", applyFormula); + formulaInput.addEventListener("keydown", e => { if (e.key === "Enter") { e.preventDefault(); formulaInput.blur(); } }); + + // ── Chart ───────────────────────────────────────────────────────────────── + const isDateX = xCol !== ROW_INDEX && (xCol === dateCol || view.isDateCol(xCol)); + const { points, skipped } = extractPoints(rows, xCol, yCol, isDateX, s => view.parseDate(s), r => view.getTitle(r)); + + const canvasWrap = wrap.createDiv({ cls: "csv-chart-wrap" }); + const canvas = canvasWrap.createEl("canvas", { cls: "csv-chart-canvas" }); + const footer = wrap.createDiv({ cls: "csv-chart-footer" }); + + if (!points.length) { + canvasWrap.remove(); + footer.remove(); + wrap.createEl("p", { text: `No rows with both "${xCol}" and "${yCol}" values to plot.`, cls: "csv-empty-state" }); + return; + } + + const spec: ChartSpec = { + points, + xIsDate: isDateX, + xLabel: xCol === ROW_INDEX ? "row" : xCol, + yLabel: yCol, + connect: isDateX, // time series read better connected; numeric pairs as dots + fit, + formula, + }; + const built = buildChartConfig(spec, resolveChartColors(container)); + + if (built.fitText) footer.createSpan({ cls: "csv-chart-fit-text", text: built.fitText }); + if (built.formulaError) footer.createSpan({ cls: "csv-chart-formula-error", text: `formula: ${built.formulaError}` }); + if (skipped > 0) footer.createSpan({ cls: "csv-chart-skipped", text: `${skipped} row${skipped === 1 ? "" : "s"} skipped (no numeric value)` }); + + // Same lazy-load + stale-canvas guard as the dashboard chart. + if (view.chartInstance) { view.chartInstance.destroy(); view.chartInstance = null; } + const { Chart } = await loadChart(); + if (!canvas.isConnected) return; + view.chartInstance = new Chart(canvas, built.config); +} diff --git a/src/view/dashboard.ts b/src/view/dashboard.ts index 8578067..a62256e 100644 --- a/src/view/dashboard.ts +++ b/src/view/dashboard.ts @@ -6,19 +6,9 @@ import type { CardView } from "../../main"; import { CSVRow } from "../types"; import { titleCase } from "../utils"; - -// Lazy-load Chart.js + register the bits we use. Only paid when the dashboard -// view first renders. Sessions that only touch books/movies/quotes/dictionary -// never load Chart.js at all. -type ChartModule = typeof import("chart.js"); -let chartModule: ChartModule | null = null; -async function loadChart(): Promise { - if (chartModule) return chartModule; - const mod = await import("chart.js"); - mod.Chart.register(mod.LineController, mod.LineElement, mod.PointElement, mod.LinearScale, mod.CategoryScale, mod.Filler, mod.Tooltip); - chartModule = mod; - return mod; -} +// Chart.js stays a lazy load (shared with the Chart view / csv-chart blocks) — +// only paid when a chart actually renders. See src/chartjs-loader.ts. +import { loadChart } from "../chartjs-loader"; export async function renderDashboard(view: CardView, container: HTMLElement): Promise { const dateCol = view.getDateCol(); diff --git a/src/view/toolbar.ts b/src/view/toolbar.ts index d05b734..565bc36 100644 --- a/src/view/toolbar.ts +++ b/src/view/toolbar.ts @@ -10,6 +10,7 @@ import { FileConfigModal, AutoDetectedRoles } from "../modals"; import { generateMobileFiles } from "./mobile"; import { syncToAnki, autoAnkiFrontCol } from "./anki"; import { hasStatsColumns } from "./stats"; +import { hasChartColumns } from "./chart"; import { hasTaskColumns } from "./tasks"; import { effectiveGroupCol } from "./kanban"; import { TITLE_COL_ALIASES, CATEGORY_COL_ALIASES, STATUS_COL_ALIASES, NOTES_COL_ALIASES, IMAGE_COL_ALIASES } from "../utils"; @@ -43,6 +44,9 @@ export function availableModes(view: CardView): {id: ViewMode, label: string}[] // render fine just made the dropdown feel arbitrarily short.) if (view.rows.length > 0) modes.push({id: "focus", label: "Focus"}); if (hasStatsColumns(view)) modes.push({id: "stats", label: "Stats"}); + // Chart: scatter/line plots of numeric column pairs, with best-fit and + // formula overlays. Needs at least one numeric column (see hasChartColumns). + if (hasChartColumns(view)) modes.push({id: "chart", label: "Chart"}); return modes; } diff --git a/styles.css b/styles.css index 7bb34c4..ab1509b 100644 --- a/styles.css +++ b/styles.css @@ -4135,3 +4135,82 @@ select.csv-add-row-control { transition: left 0.15s ease; } .csv-toggle.is-on .csv-toggle-knob { left: 18px; } + +/* ─── Chart view + csv-chart block ─────────────────────────────────────── */ + +.csv-chart-view { + max-width: 900px; + margin: 0 auto; + padding: 8px 4px; +} + +.csv-chart-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 14px; + margin-bottom: 12px; +} + +.csv-chart-control { + display: flex; + align-items: center; + gap: 6px; +} + +.csv-chart-control-label { + font-size: 12px; + font-weight: 600; + color: var(--csv-text-muted); +} + +.csv-chart-select { + font-size: 13px; + max-width: 180px; +} + +.csv-chart-fit-btn.active { + background: var(--csv-accent); + color: var(--text-on-accent, #fff); + border-color: var(--csv-accent); +} + +.csv-chart-formula-wrap { flex: 1 1 180px; min-width: 160px; } + +.csv-chart-formula-input { + flex: 1; + min-width: 0; + font-size: 13px; + font-family: var(--font-monospace); + padding: 4px 8px; +} + +.csv-chart-wrap { + height: 340px; + position: relative; +} + +.csv-chart-block .csv-chart-wrap { height: 280px; } + +.csv-chart-canvas { + width: 100%; + height: 100%; +} + +.csv-chart-footer { + display: flex; + flex-wrap: wrap; + gap: 4px 16px; + margin-top: 8px; + font-size: 12px; + color: var(--csv-text-muted); +} + +.csv-chart-fit-text { font-family: var(--font-monospace); } + +.csv-chart-formula-error { color: var(--text-error, #e05252); } + +@media (max-width: 600px) { + .csv-chart-wrap { height: 260px; } + .csv-chart-select { max-width: 130px; } +} diff --git a/test-support/chartjs-stub.mjs b/test-support/chartjs-stub.mjs index 1c0d22b..ad82878 100644 --- a/test-support/chartjs-stub.mjs +++ b/test-support/chartjs-stub.mjs @@ -1,11 +1,19 @@ -// Minimal "chart.js" stub for the dashboard smoke test — jsdom has no canvas -// 2D context, so the real Chart would throw. loadChart() calls Chart.register -// and `new Chart(canvas, cfg)`; both are no-ops here. -export class Chart { constructor() {} destroy() {} static register() {} } +// Minimal "chart.js" stub for the dashboard/chart smoke tests — jsdom has no +// canvas 2D context, so the real Chart would throw. loadChart() calls +// Chart.register and `new Chart(canvas, cfg)`; both are no-ops here, but the +// last-constructed config is kept so tests can assert on datasets/scales. +export class Chart { + static lastConfig = null; + constructor(_canvas, config) { Chart.lastConfig = config ?? null; } + destroy() {} + static register() {} +} export class LineController {} +export class ScatterController {} export class LineElement {} export class PointElement {} export class LinearScale {} export class CategoryScale {} export class Filler {} export class Tooltip {} +export class Legend {} diff --git a/test-view-smoke.mjs b/test-view-smoke.mjs index cbd9fd1..f07d83e 100644 --- a/test-view-smoke.mjs +++ b/test-view-smoke.mjs @@ -1489,6 +1489,140 @@ await test("anki: surfaces a transport failure instead of throwing", async () => delete globalThis.__ankiRequestUrl; }); +// ── Formula evaluator ──────────────────────────────────────────────────────── +const { compileFormula } = await load("./src/formula.ts"); + +await test("formula: polynomial, implicit multiplication, constants, functions", async () => { + assert(compileFormula("2x^2 - 3x + 1")(2) === 3, "2x^2-3x+1 at x=2"); + assert(compileFormula("3(x+1)")(2) === 9, "implicit mult over parens"); + assert(Math.abs(compileFormula("sin(pi/2)")(0) - 1) < 1e-12, "sin(pi/2) = 1"); + assert(compileFormula("2^3^2")(0) === 512, "^ is right-associative"); + assert(compileFormula("y = -x^2")(3) === -9, "leading y= allowed; -x^2 = -(x^2)"); + assert(compileFormula("max(x, 5)")(2) === 5, "two-arg function"); + assert(compileFormula("10 sin(x)")(0) === 0, "implicit mult before function call"); +}); + +await test("formula: bad input throws readable errors", async () => { + for (const bad of ["", "2 +", "(x", "foo(x)", "x $ 2", "sin x"]) { + let threw = false; + try { compileFormula(bad); } catch { threw = true; } + assert(threw, `"${bad}" should throw`); + } +}); + +// ── Chart view ─────────────────────────────────────────────────────────────── +const { renderChart, hasChartColumns, parseNumeric, numericColumns, linearFit, buildChartConfig } = + await load("./src/view/chart.ts"); + +await test("chart: parseNumeric handles separators and rejects text", async () => { + assert(parseNumeric("1,234") === 1234, "thousands comma"); + assert(parseNumeric("1 234") === 1234, "thousands space"); + assert(parseNumeric("3,5") === 3.5, "decimal comma"); + assert(parseNumeric("-2.5e3") === -2500, "scientific"); + assert(parseNumeric("abc") === null, "text rejected"); + assert(parseNumeric("") === null, "empty rejected"); +}); + +await test("chart: numericColumns needs 2+ values at a 70%+ hit rate", async () => { + const rows = [ + { title: "A", score: "1", year: "n/a" }, + { title: "B", score: "2", year: "1999" }, + { title: "C", score: "3", year: "" }, + ]; + const cols = numericColumns(["title", "score", "year"], rows); + assert(cols.join(",") === "score", `only score qualifies (got ${cols})`); +}); + +await test("chart: linearFit recovers an exact line with R² = 1", async () => { + const fit = linearFit([{ x: 0, y: 1 }, { x: 1, y: 3 }, { x: 2, y: 5 }]); + assert(Math.abs(fit.slope - 2) < 1e-12 && Math.abs(fit.intercept - 1) < 1e-12, "y = 2x + 1"); + assert(fit.r2 === 1, "perfect fit"); + assert(linearFit([{ x: 1, y: 1 }, { x: 1, y: 2 }]) === null, "no X spread → null"); +}); + +const chartColors = { accent: "#38d", muted: "#888", grid: "#ccc", fitLine: "#999", formula: "#e83" }; + +await test("chart: buildChartConfig adds fit + formula datasets and fit text", async () => { + const built = buildChartConfig({ + points: [{ x: 0, y: 1 }, { x: 1, y: 3 }, { x: 2, y: 5 }], + xIsDate: false, xLabel: "x", yLabel: "score", connect: false, + fit: "linear", formula: "2x + 1", + }, chartColors); + assert(built.config.data.datasets.length === 3, "points + fit + formula datasets"); + assert(built.fitText.startsWith("y = 2x + 1"), `fit equation (got "${built.fitText}")`); + assert(built.fitText.includes("R² = 1.000"), "R² shown"); + assert(built.formulaError === null, "formula compiled"); +}); + +await test("chart: date X gets per-day trend text; bad formula surfaces error", async () => { + const day = 86_400_000; + const built = buildChartConfig({ + points: [{ x: 0, y: 0 }, { x: day, y: 2 }, { x: 2 * day, y: 4 }], + xIsDate: true, xLabel: "date", yLabel: "km", connect: true, + fit: "linear", formula: "foo(x)", + }, chartColors); + assert(built.fitText.startsWith("Trend: +2 km/day"), `per-day phrasing (got "${built.fitText}")`); + assert(built.formulaError !== null, "bad formula reported, not thrown"); +}); + +function chartView(rows, cfg = {}) { + let savedCfg = null; + const view = { + rows, headers: Object.keys(rows[0] ?? {}), searchQuery: "", + getFilteredRows: () => rows, + fileCfg: cfg, saveFileCfg: (c) => { savedCfg = c; view.fileCfg = c; }, + getDateCol: () => (Object.keys(rows[0] ?? {}).includes("date") ? "date" : null), + isDateCol: (h) => h === "date", + parseDate: (s) => (/^\d{4}-\d{2}-\d{2}$/.test(s) ? new Date(s + "T00:00:00") : null), + getTitle: (r) => r[Object.keys(r)[0]] ?? "—", + chartInstance: null, + renderView: () => {}, renderViewPreservingScroll: () => {}, + getSavedCfg: () => savedCfg, + }; + return view; +} + +await test("chart: renders controls, canvas, and fit text over a numeric file", async () => { + const rows = [ + { title: "A", year: "2000", rating: "2" }, + { title: "B", year: "2010", rating: "3" }, + { title: "C", year: "2020", rating: "4" }, + ]; + const view = chartView(rows, { chartXCol: "year", chartYCol: "rating", chartFit: "linear" }); + assert(hasChartColumns(view), "file is chartable"); + const c = document.body.createDiv(); + await renderChart(view, c); + assert(c.querySelectorAll(".csv-chart-select").length === 2, "X and Y selects present"); + assert(c.querySelector(".csv-chart-fit-btn.active"), "fit toggle reflects saved state"); + assert(c.querySelector(".csv-chart-formula-input"), "formula input present"); + assert(c.querySelector("canvas.csv-chart-canvas"), "canvas present"); + assert(c.querySelector(".csv-chart-fit-text"), "fit equation shown"); + assert(view.chartInstance, "Chart instance created"); +}); + +await test("chart: changing the Y select persists to fileCfg and re-renders", async () => { + const rows = [ + { title: "A", pages: "100", rating: "2" }, + { title: "B", pages: "200", rating: "5" }, + ]; + const view = chartView(rows); + const c = document.body.createDiv(); + await renderChart(view, c); + const ySel = c.querySelectorAll(".csv-chart-select")[1]; + ySel.value = "rating"; + ySel.dispatchEvent(new window.Event("change", { bubbles: true })); + assert(view.getSavedCfg()?.chartYCol === "rating", "Y pick saved to fileCfg"); +}); + +await test("chart: non-numeric file is not chartable; empty pair shows empty state", async () => { + assert(!hasChartColumns(chartView([{ title: "A" }, { title: "B" }])), "no numeric column"); + const view = chartView([{ title: "A", score: "1" }, { title: "B", score: "2" }], { chartFormula: "" }); + view.getFilteredRows = () => []; // search filtered everything out + const c = document.body.createDiv(); + await renderChart(view, c); + assert(c.querySelector(".csv-empty-state"), "empty state when nothing plots"); +}); + console.log(`\n${"=".repeat(50)}`); console.log(`View smoke tests: ${passed} passed, ${failed} failed`); console.log(`${"=".repeat(50)}`);