From 8518dd7a2ffb11bc50982afae93ec55fe07d91c5 Mon Sep 17 00:00:00 2001 From: SVM0N <61781578+SVM0N@users.noreply.github.com> Date: Sun, 28 Jun 2026 17:53:11 +0000 Subject: [PATCH] feat: inline csv-view block, image columns, kanban grouping fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inline view (src/inline-view.ts): a csv-view code block renders an editable table/cards/kanban view of a CSV inside any note. InlineCardHost satisfies the renderers' duck-typed surface so renderTable/renderLibrary/renderKanbanGenre are reused unchanged; edits write back via vault.modify and re-sync off the modify event. Block directives: file/mode/height/collapse. - Cards/Kanban thumbnails: getImageCol() auto-detects Image/Cover/Poster/… columns; resolveImageSrc() handles vault paths, wikilinks, md-images, URLs. - Card title + context-menu "Open entry" now open the expander even without a notes column (NoteExpanderModal hides its notes section when absent), so notes-less files (e.g. applications trackers) are editable from cards. - collapse: directive + fileCfg.collapsedGroups: Cards groups collapse by default and remember manual toggles (full-page too). - Habit add-form toggles for 0/1 columns; pseudo-categorical columns (few distinct values) get option dropdowns in the add + edit forms via shared looksCategorical() helper. - Kanban: empty group value → "—" column (was dropped in default grouping); rows with blank/unknown status render ungrouped instead of vanishing while the column header still counted them. - Dark-mode table row hover: explicit text-tint overlay (was near-invisible). - Docs: csv-view syntax in README; architecture + open follow-ups in handoff. Co-Authored-By: Claude Opus 4.8 --- main.js | 44 ++-- main.ts | 34 ++- src/add-entry-form.ts | 4 +- src/inline-view.ts | 552 ++++++++++++++++++++++++++++++++++++++++++ src/modals.ts | 160 +++++++----- src/types.ts | 4 + src/utils.ts | 40 +++ src/view/kanban.ts | 35 ++- src/view/library.ts | 42 +++- styles.css | 128 +++++++++- 10 files changed, 937 insertions(+), 106 deletions(-) create mode 100644 src/inline-view.ts diff --git a/main.js b/main.js index 3a30a99..6de6568 100644 --- a/main.js +++ b/main.js @@ -1,24 +1,24 @@ -"use strict";var Fl=Object.create;var us=Object.defineProperty;var Vl=Object.getOwnPropertyDescriptor;var Nl=Object.getOwnPropertyNames;var Bl=Object.getPrototypeOf,zl=Object.prototype.hasOwnProperty;var Hl=(s,t,e)=>t in s?us(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var jn=(s,t)=>()=>(s&&(t=s(s=0)),t);var $l=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),fo=(s,t)=>{for(var e in t)us(s,e,{get:t[e],enumerable:!0})},po=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Nl(t))!zl.call(s,i)&&i!==e&&us(s,i,{get:()=>t[i],enumerable:!(n=Vl(t,i))||n.enumerable});return s};var Un=(s,t,e)=>(e=s!=null?Fl(Bl(s)):{},po(t||!s||!s.__esModule?us(e,"default",{value:s,enumerable:!0}):e,s)),Wl=s=>po(us({},"__esModule",{value:!0}),s);var z=(s,t,e)=>(Hl(s,typeof t!="symbol"?t+"":t,e),e);var $s=$l((Yn,Kn)=>{((s,t)=>{typeof define=="function"&&define.amd?define([],t):typeof Kn=="object"&&typeof Yn!="undefined"?Kn.exports=t():s.Papa=t()})(Yn,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(v){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(m){var C=S(m);C.chunkSize=parseInt(C.chunkSize),m.step||m.chunk||(C.chunkSize=null),this._handle=new f(C),(this._handle.streamer=this)._config=C}.call(this,v),this.parseChunk=function(m,C){var k=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview),i)t.postMessage({results:w,workerId:a.WORKER_ID,finished:k});else if(E(this._config.chunk)&&!C){if(this._config.chunk(w,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=w=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(w.data),this._completeResults.errors=this._completeResults.errors.concat(w.errors),this._completeResults.meta=w.meta),this._completed||!k||!E(this._config.complete)||w&&w.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),k||w&&w.meta.paused||this._nextChunk(),w}this._halted=!0},this._sendError=function(m){E(this._config.error)?this._config.error(m):i&&this._config.error&&t.postMessage({workerId:a.WORKER_ID,error:m,finished:!1})}}function c(v){var m;(v=v||{}).chunkSize||(v.chunkSize=a.RemoteChunkSize),l.call(this,v),this._nextChunk=n?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(C){this._input=C,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(m=new XMLHttpRequest,this._config.withCredentials&&(m.withCredentials=this._config.withCredentials),n||(m.onload=M(this._chunkLoaded,this),m.onerror=M(this._chunkError,this)),m.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var C,k=this._config.downloadRequestHeaders;for(C in k)m.setRequestHeader(C,k[C])}var w;this._config.chunkSize&&(w=this._start+this._config.chunkSize-1,m.setRequestHeader("Range","bytes="+this._start+"-"+w));try{m.send(this._config.downloadRequestBody)}catch(_){this._chunkError(_.message)}n&&m.status===0&&this._chunkError()}},this._chunkLoaded=function(){m.readyState===4&&(m.status<200||400<=m.status?this._chunkError():(this._start+=this._config.chunkSize||m.responseText.length,this._finished=!this._config.chunkSize||this._start>=(C=>(C=C.getResponseHeader("Content-Range"))!==null?parseInt(C.substring(C.lastIndexOf("/")+1)):-1)(m),this.parseChunk(m.responseText)))},this._chunkError=function(C){C=m.statusText||C,this._sendError(new Error(C))}}function d(v){(v=v||{}).chunkSize||(v.chunkSize=a.LocalChunkSize),l.call(this,v);var m,C,k=typeof FileReader!="undefined";this.stream=function(w){this._input=w,C=w.slice||w.webkitSlice||w.mozSlice,k?((m=new FileReader).onload=M(this._chunkLoaded,this),m.onerror=M(this._chunkError,this)):m=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(w.target.result)},this._chunkError=function(){this._sendError(m.error)}}function h(v){var m;l.call(this,v=v||{}),this.stream=function(C){return m=C,this._nextChunk()},this._nextChunk=function(){var C,k;if(!this._finished)return C=this._config.chunkSize,m=C?(k=m.substring(0,C),m.substring(C)):(k=m,""),this._finished=!m,this.parseChunk(k)}}function u(v){l.call(this,v=v||{});var m=[],C=!0,k=!1;this.pause=function(){l.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){l.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(w){this._input=w,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){k&&m.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),m.length?this.parseChunk(m.shift()):C=!0},this._streamData=M(function(w){try{m.push(typeof w=="string"?w:w.toString(this._config.encoding)),C&&(C=!1,this._checkIsFinished(),this.parseChunk(m.shift()))}catch(_){this._streamError(_)}},this),this._streamError=M(function(w){this._streamCleanUp(),this._sendError(w)},this),this._streamEnd=M(function(){this._streamCleanUp(),k=!0,this._streamData("")},this),this._streamCleanUp=M(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function f(v){var m,C,k,w,_=Math.pow(2,53),D=-_,T=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,P=/^((\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)))$/,R=this,H=0,B=0,G=!1,W=!1,L=[],A={data:[],errors:[],meta:{}};function V(I){return v.skipEmptyLines==="greedy"?I.join("").trim()==="":I.length===1&&I[0].length===0}function $(){if(A&&k&&(F("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),k=!1),v.skipEmptyLines&&(A.data=A.data.filter(function(Y){return!V(Y)})),U()){let Y=function(K,X){E(v.transformHeader)&&(K=v.transformHeader(K,X)),L.push(K)};var N=Y;if(A)if(Array.isArray(A.data[0])){for(var I=0;U()&&I(dt=>(v.dynamicTypingFunction&&v.dynamicTyping[dt]===void 0&&(v.dynamicTyping[dt]=v.dynamicTypingFunction(dt)),(v.dynamicTyping[dt]||v.dynamicTyping)===!0))(st)?ot==="true"||ot==="TRUE"||ot!=="false"&&ot!=="FALSE"&&((dt=>{if(T.test(dt)&&(dt=parseFloat(dt),D=L.length?"__parsed_extra":L[J]:Q,mt=v.transform?v.transform(mt,Q):mt);Q==="__parsed_extra"?(X[Q]=X[Q]||[],X[Q].push(mt)):X[Q]=mt}return v.header&&(J>L.length?F("FieldMismatch","TooManyFields","Too many fields: expected "+L.length+" fields but parsed "+J,B+K):Jv.preview?C.abort():(A.data=A.data[0],w(A,R))))}),this.parse=function(I,O,j){var N=v.quoteChar||'"',N=(v.newline||(v.newline=this.guessLineEndings(I,N)),k=!1,v.delimiter?E(v.delimiter)&&(v.delimiter=v.delimiter(I),A.meta.delimiter=v.delimiter):((N=((Y,K,X,J,Q)=>{var mt,st,ot,dt;Q=Q||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var re=0;re=j.length/2?`\r -`:"\r"}}function p(v){return v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function g(v){var m=(v=v||{}).delimiter,C=v.newline,k=v.comments,w=v.step,_=v.preview,D=v.fastMode,T=null,P=!1,R=v.quoteChar==null?'"':v.quoteChar,H=R;if(v.escapeChar!==void 0&&(H=v.escapeChar),(typeof m!="string"||-1=_)return _t(!0);break}j.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:O.length,index:B}),st++}}else if(k&&N.length===0&&W.substring(B,B+F)===k){if(Q===-1)return _t();B=Q+U,Q=W.indexOf(C,B),J=W.indexOf(m,B)}else if(J!==-1&&(J=_)return _t(!0)}return zt();function dt(gt){O.push(gt),Y=B}function re(gt){var St=0;return St=gt!==-1&&(gt=W.substring(st+1,gt))&>.trim()===""?gt.length:St}function zt(gt){return A||(gt===void 0&&(gt=W.substring(B)),N.push(gt),B=V,dt(N),I&&Ht()),_t()}function ds(gt){B=gt,dt(N),N=[],Q=W.indexOf(C,B)}function _t(gt){if(v.header&&!L&&O.length&&!P){var St=O[0],Zt=Object.create(null),Wn=new Set(St);let ho=!1;for(let ze=0;zek.charCodeAt(0)!==65279?k:k.slice(1))(v),C=new(m.download?c:h)(m)):v.readable===!0&&E(v.read)&&E(v.on)?C=new u(m):(t.File&&v instanceof File||v instanceof Object)&&(C=new d(m)),C.stream(v);(C=(()=>{var k;return!!a.WORKERS_SUPPORTED&&(k=(()=>{var w=t.URL||t.webkitURL||null,_=s.toString();return a.BLOB_URL||(a.BLOB_URL=w.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; ","(",_,")();"],{type:"text/javascript"})))})(),(k=new t.Worker(k)).onmessage=b,k.id=r++,o[k.id]=k)})()).userStep=m.step,C.userChunk=m.chunk,C.userComplete=m.complete,C.userError=m.error,m.step=E(m.step),m.chunk=E(m.chunk),m.complete=E(m.complete),m.error=E(m.error),delete m.worker,C.postMessage({input:v,config:m,workerId:C.id})},a.unparse=function(v,m){var C=!1,k=!0,w=",",_=`\r -`,D='"',T=D+D,P=!1,R=null,H=!1,B=((()=>{if(typeof m=="object"){if(typeof m.delimiter!="string"||a.BAD_DELIMITERS.filter(function(L){return m.delimiter.indexOf(L)!==-1}).length||(w=m.delimiter),typeof m.quotes!="boolean"&&typeof m.quotes!="function"&&!Array.isArray(m.quotes)||(C=m.quotes),typeof m.skipEmptyLines!="boolean"&&typeof m.skipEmptyLines!="string"||(P=m.skipEmptyLines),typeof m.newline=="string"&&(_=m.newline),typeof m.quoteChar=="string"&&(D=m.quoteChar),typeof m.header=="boolean"&&(k=m.header),Array.isArray(m.columns)){if(m.columns.length===0)throw new Error("Option columns is empty");R=m.columns}m.escapeChar!==void 0&&(T=m.escapeChar+D),m.escapeFormulae instanceof RegExp?H=m.escapeFormulae:typeof m.escapeFormulae=="boolean"&&m.escapeFormulae&&(H=/^[=+\-@\t\r].*$/)}})(),new RegExp(p(D),"g"));if(typeof v=="string"&&(v=JSON.parse(v)),Array.isArray(v)){if(!v.length||Array.isArray(v[0]))return G(null,v,P);if(typeof v[0]=="object")return G(R||Object.keys(v[0]),v,P)}else if(typeof v=="object")return typeof v.data=="string"&&(v.data=JSON.parse(v.data)),Array.isArray(v.data)&&(v.fields||(v.fields=v.meta&&v.meta.fields||R),v.fields||(v.fields=Array.isArray(v.data[0])?v.fields:typeof v.data[0]=="object"?Object.keys(v.data[0]):[]),Array.isArray(v.data[0])||typeof v.data[0]=="object"||(v.data=[v.data])),G(v.fields||[],v.data||[],P);throw new Error("Unable to serialize unrecognized input");function G(L,A,V){var $="",U=(typeof L=="string"&&(L=JSON.parse(L)),typeof A=="string"&&(A=JSON.parse(A)),Array.isArray(L)&&0{for(var I=0;Ie-n*Math.max(Math.min(r-3,9-r,1),-1);return[i(0),i(8),i(4)]}function Ac(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 Pc(s,t,e){let n=lr(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 Rc(s,t,e,n,i){return s===i?(t-e)/n+(t.5?d/(2-o-r):d/(o+r),l=Rc(e,n,i,d,o),l=l*60+.5),[l|0,c||0,a]}function li(s,t,e,n){return(Array.isArray(t)?s(t[0],t[1],t[2]):s(t,e,n)).map(de)}function ci(s,t,e){return li(lr,s,t,e)}function Oc(s,t,e){return li(Pc,s,t,e)}function Ic(s,t,e){return li(Ac,s,t,e)}function cr(s){return(s%360+360)%360}function Fc(s){let t=Lc.exec(s),e=255,n;if(!t)return;t[5]!==n&&(e=t[6]?vs(+t[5]):de(+t[5]));let i=cr(+t[2]),o=+t[3]/100,r=+t[4]/100;return t[1]==="hwb"?n=Oc(i,o,r):t[1]==="hsv"?n=Ic(i,o,r):n=ci(i,o,r),{r:n[0],g:n[1],b:n[2],a:e}}function Vc(s,t){var e=ai(s);e[0]=cr(e[0]+t),e=ci(e),s.r=e[0],s.g=e[1],s.b=e[2]}function Nc(s){if(!s)return;let t=ai(s),e=t[0],n=ir(t[1]),i=ir(t[2]);return s.a<255?`hsla(${e}, ${n}%, ${i}%, ${te(s.a)})`:`hsl(${e}, ${n}%, ${i}%)`}function Bc(){let s={},t=Object.keys(rr),e=Object.keys(or),n,i,o,r,a;for(n=0;n>16&255,o>>8&255,o&255]}return s}function zc(s){on||(on=Bc(),on.transparent=[0,0,0,0]);let t=on[s.toLowerCase()];return t&&{r:t[0],g:t[1],b:t[2],a:t.length===4?t[3]:255}}function $c(s){let t=Hc.exec(s),e=255,n,i,o;if(t){if(t[7]!==n){let r=+t[7];e=t[8]?vs(r):ce(r*255,0,255)}return n=+t[1],i=+t[3],o=+t[5],n=255&(t[2]?vs(n):ce(n,0,255)),i=255&(t[4]?vs(i):ce(i,0,255)),o=255&(t[6]?vs(o):ce(o,0,255)),{r:n,g:i,b:o,a:e}}}function Wc(s){return s&&(s.a<255?`rgba(${s.r}, ${s.g}, ${s.b}, ${te(s.a)})`:`rgb(${s.r}, ${s.g}, ${s.b})`)}function jc(s,t,e){let n=We(te(s.r)),i=We(te(s.g)),o=We(te(s.b));return{r:de(oi(n+e*(We(te(t.r))-n))),g:de(oi(i+e*(We(te(t.g))-i))),b:de(oi(o+e*(We(te(t.b))-o))),a:s.a+e*(t.a-s.a)}}function rn(s,t,e){if(s){let n=ai(s);n[t]=Math.max(0,Math.min(n[t]+n[t]*e,t===0?360:1)),n=ci(n),s.r=n[0],s.g=n[1],s.b=n[2]}}function dr(s,t){return s&&Object.assign(t||{},s)}function ar(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=de(s[3]))):(t=dr(s,{r:0,g:0,b:0,a:1}),t.a=de(t.a)),t}function Uc(s){return s.charAt(0)==="r"?$c(s):Fc(s)}var ce,Pt,ri,Ec,kc,nn,wc,Dc,Lc,or,rr,on,Hc,oi,We,xs,hr=jn(()=>{ce=(s,t,e)=>Math.max(Math.min(s,e),t);Pt={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},ri=[..."0123456789ABCDEF"],Ec=s=>ri[s&15],kc=s=>ri[(s&240)>>4]+ri[s&15],nn=s=>(s&240)>>4===(s&15),wc=s=>nn(s.r)&&nn(s.g)&&nn(s.b)&&nn(s.a);Dc=(s,t)=>s<255?t(s):"";Lc=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;or={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"},rr={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"};Hc=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;oi=s=>s<=.0031308?s*12.92:Math.pow(s,1/2.4)*1.055-.055,We=s=>s<=.04045?s/12.92:Math.pow((s+.055)/1.055,2.4);xs=class s{constructor(t){if(t instanceof s)return t;let e=typeof t,n;e==="object"?n=ar(t):e==="string"&&(n=Mc(t)||zc(t)||Uc(t)),this._rgb=n,this._valid=!!n}get valid(){return this._valid}get rgb(){var t=dr(this._rgb);return t&&(t.a=te(t.a)),t}set rgb(t){this._rgb=ar(t)}rgbString(){return this._valid?Wc(this._rgb):void 0}hexString(){return this._valid?Tc(this._rgb):void 0}hslString(){return this._valid?Nc(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=jc(this._rgb,t._rgb,e)),this}clone(){return new s(this.rgb)}alpha(t){return this._rgb.a=de(t),this}clearer(t){let e=this._rgb;return e.a*=1-t,this}greyscale(){let t=this._rgb,e=_s(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 rn(this._rgb,2,t),this}darken(t){return rn(this._rgb,2,-t),this}saturate(t){return rn(this._rgb,1,t),this}desaturate(t){return rn(this._rgb,1,-t),this}rotate(t){return Vc(this._rgb,t),this}}});function Yt(){}function Z(s){return s==null}function at(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 tt(s){return s!==null&&Object.prototype.toString.call(s)==="[object Object]"}function ht(s){return(typeof s=="number"||s instanceof Number)&&isFinite(+s)}function kt(s,t){return ht(s)?s:t}function q(s,t){return typeof s=="undefined"?t:s}function rt(s,t,e){if(s&&typeof s.call=="function")return s.apply(e,t)}function nt(s,t,e,n){let i,o,r;if(at(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 ne(s,t){return(ur[t]||(ur[t]=qc(t)))(s)}function pn(s){return s.charAt(0).toUpperCase()+s.slice(1)}function kr(s){return s.type==="mouseup"||s.type==="click"||s.type==="contextmenu"}function qe(s,t,e){return Math.abs(s-t)i-o).pop(),t}function Zc(s){return typeof s=="symbol"||typeof s=="object"&&s!==null&&!(Symbol.toPrimitive in s||"toString"in s||"valueOf"in s)}function Te(s){return!Zc(s)&&!isNaN(parseFloat(s))&&isFinite(s)}function Mr(s,t){let e=Math.round(s);return e-t<=s&&e+t>=s}function mi(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 mn(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 Lr(s,t,e){let n=0,i=s.length;for(;nn&&s[i-1]>e;)i--;return n>0||i{let n="_onData"+pn(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 vi(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)&&(Ar.forEach(o=>{delete s[o]}),delete s._chartjs)}function xi(s){let t=new Set(s);return t.size===s.length?s:Array.from(t)}function Ci(s,t){let e=[],n=!1;return function(...i){e=i,n||(n=!0,_i.call(window,()=>{n=!1,s.apply(t,e)}))}}function Rr(s,t){let e;return function(...n){return t?(clearTimeout(e),e=setTimeout(s,t,n)):s.apply(this,n),t}}function Si(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(jt(l,d,h).lo,e?n:jt(t,d,r.getPixelForValue(h)).lo),c){let g=l.slice(0,i+1).reverse().findIndex(b=>!Z(b[a.axis]));i-=Math.max(0,g)}i=pt(i,0,n-1)}if(p){let g=Math.max(jt(l,r.axis,u,!0).hi+1,e?0:jt(t,d,r.getPixelForValue(u),!0).hi+1);if(c){let b=l.slice(g-1).findIndex(y=>!Z(y[a.axis]));g+=Math.max(0,b)}o=pt(g,i,n)-i}else o=n-i}return{start:i,count:o}}function Ei(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 ki(s){if(s&&typeof s=="object"){let t=s.toString();return t==="[object CanvasPattern]"||t==="[object CanvasGradient]"}return!1}function wi(s){return ki(s)?s:new xs(s)}function di(s){return ki(s)?s:new xs(s).saturate(.5).darken(.1).hexString()}function sd(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:ed},numbers:{type:"number",properties:td}}),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 nd(s){s.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}function id(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 Qe(s,t,e){return id(t,e).format(s)}function od(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 rd(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:Ze.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 Cs(s,t){if(!t)return s;let e=t.split(".");for(let n=0,i=e.length;nn&&(n=o),n}function Fr(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 Ut(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,ld(s,o),l=0;lq(s[r],s[t[r]]):r=>s[r]:()=>s;for(let r of i)e[r]=pd(o(r));return e}function Ti(s){return xn(s,{top:"y",right:"x",bottom:"y",left:"x"})}function me(s){return xn(s,["topLeft","topRight","bottomLeft","bottomRight"])}function vt(s){let t=Ti(s);return t.width=t.left+t.right,t.height=t.top+t.bottom,t}function ft(s,t){s=s||{},t=t||ct.font;let e=q(s.size,t.size);typeof e=="string"&&(e=parseInt(e,10));let n=q(s.style,t.style);n&&!(""+n).match(ud)&&(console.warn('Invalid font style specified: "'+n+'"'),n=void 0);let i={family:q(s.family,t.family),lineHeight:fd(q(s.lineHeight,t.lineHeight),e),size:e,style:n,weight:q(s.weight,t.weight),string:""};return i.string=ad(i),i}function ts(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 ie(s,t){return Object.assign(Object.create(s),t)}function _n(s,t=[""],e,n,i=()=>s[0]){let o=e||s;typeof n=="undefined"&&(n=$r("_fallback",s));let r={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:s,_rootScopes:o,_fallback:n,_getTarget:i,override:a=>_n([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,()=>Cd(l,t,s,a))},getOwnPropertyDescriptor(a,l){return Reflect.getOwnPropertyDescriptor(a._scopes[0],l)},getPrototypeOf(){return Reflect.getPrototypeOf(s[0])},has(a,l){return yr(a).includes(l)},ownKeys(a){return yr(a)},set(a,l,c){let d=a._storage||(a._storage=i());return a[l]=d[l]=c,delete a._keys,!0}})}function De(s,t,e,n){let i={_cacheable:!1,_proxy:s,_context:t,_subProxy:e,_stack:new Set,_descriptors:Li(s,n),setContext:o=>De(s,o,e,n),override:o=>De(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,()=>md(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 Li(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:ee(e)?e:()=>e,isIndexable:ee(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 md(s,t,e){let{_proxy:n,_context:i,_subProxy:o,_descriptors:r}=s,a=n[t];return ee(a)&&r.isScriptable(t)&&(a=bd(t,a,s,e)),at(a)&&a.length&&(a=yd(t,a,s,r.isIndexable)),Ai(t,a)&&(a=De(a,i,o&&o[t],r)),a}function bd(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),Ai(s,l)&&(l=Pi(i._scopes,i,s,l)),l}function yd(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(tt(t[0])){let l=t,c=i._scopes.filter(d=>d!==l);t=[];for(let d of l){let h=Pi(c,i,s,d);t.push(De(h,o,r&&r[s],a))}}return t}function Hr(s,t,e){return ee(s)?s(t,e):s}function xd(s,t,e,n,i){for(let o of t){let r=vd(e,o);if(r){s.add(r);let a=Hr(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 Pi(s,t,e,n){let i=t._rootScopes,o=Hr(t._fallback,e,n),r=[...s,...i],a=new Set;a.add(n);let l=br(a,r,e,o||e,n);return l===null||typeof o!="undefined"&&o!==e&&(l=br(a,r,o,l,n),l===null)?!1:_n(Array.from(a),[""],i,o,()=>_d(t,e,n))}function br(s,t,e,n,i){for(;e;)e=xd(s,t,e,n,i);return e}function _d(s,t,e){let n=s._getTarget();t in n||(n[t]={});let i=n[t];return at(i)&&tt(e)?e:i||{}}function Cd(s,t,e,n){let i;for(let o of t)if(i=$r(gd(o,s),e),typeof i!="undefined")return Ai(s,i)?Pi(e,n,s,i):i}function $r(s,t){for(let e of t){if(!e)continue;let n=e[s];if(typeof n!="undefined")return n}}function yr(s){let t=s._keys;return t||(t=s._keys=Sd(s._scopes)),t}function Sd(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 Ri(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")Dd(s,i);else{let c=n?s[s.length-1]:s[0];for(o=0,r=s.length;ol.height&&(d=l.height,c=ue(Math.floor(d*n))),{width:c,height:d}}function Oi(s,t,e){let n=t||1,i=ue(s.height*n),o=ue(s.width*n);s.height=ue(s.height),s.width=ue(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 Ii(s,t){let e=Ld(s,t),n=e&&e.match(/^(\d+)(\.\d+)?px$/);return n?+n[1]:void 0}function he(s,t,e,n){return{x:s.x+e*(t.x-s.x),y:s.y+e*(t.y-s.y)}}function Kr(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 Gr(s,t,e,n){let i={x:s.cp2x,y:s.cp2y},o={x:t.cp1x,y:t.cp1y},r=he(s,i,e),a=he(i,o,e),l=he(o,t,e),c=he(r,a,e),d=he(a,l,e);return he(c,d,e)}function Le(s,t,e){return s?Id(t,e):Fd()}function Fi(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 Vi(s,t){t!==void 0&&(delete s.prevTextDirection,s.canvas.style.setProperty("direction",t[0],t[1]))}function qr(s){return s==="angle"?{between:Xe,compare:Jc,normalize:bt}:{between:Kt,compare:(t,e)=>t-e,normalize:t=>t}}function vr({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 Vd(s,t,e){let{property:n,start:i,end:o}=e,{between:r,normalize:a}=qr(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,S,y)&&a(i,S)!==0,E=()=>a(o,y)===0||l(o,S,y),v=()=>g||M(),m=()=>!g||E();for(let C=d,k=d;C<=h;++C)x=t[C%r],!x.skip&&(y=c(x[n]),y!==S&&(g=l(y,i,o),b===null&&v()&&(b=a(y,i)===0?C:k),b!==null&&m()&&(p.push(vr({start:b,end:C,loop:u,count:r,style:f})),b=null),k=C,S=y));return b!==null&&p.push(vr({start:b,end:h,loop:u,count:r,style:f})),p}function Bi(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 Bd(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 Xr(s,t){let e=s.points,n=s.options.spanGaps,i=e.length;if(!i)return[];let o=!!s._loop,{start:r,end:a}=Nd(e,i,o,n);if(n===!0)return xr(s,[{start:r,end:a,loop:o}],e,t);let l=a{hr();Cr=(()=>{let s=0;return()=>s++})();Sr=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100:+s/t,fi=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100*t:+s;ur={"":s=>s,x:s=>s.x,y:s=>s.y};Ge=s=>typeof s!="undefined",ee=s=>typeof s=="function",pi=(s,t)=>{if(s.size!==t.size)return!1;for(let e of s)if(!t.has(e))return!1;return!0};et=Math.PI,lt=2*et,Xc=lt+et,hn=Number.POSITIVE_INFINITY,Qc=et/180,ut=et/2,we=et/4,fr=et*2/3,se=Math.log10,Vt=Math.sign;jt=(s,t,e,n)=>mn(s,e,n?i=>{let o=s[i][t];return os[i][t]mn(s,e,n=>s[n][t]>=e);Ar=["push","pop","shift","splice","unshift"];_i=function(){return typeof window=="undefined"?function(s){return s()}:window.requestAnimationFrame}();bn=s=>s==="start"?"left":s==="end"?"right":"center",yt=(s,t,e)=>s==="start"?t:s==="end"?e:(t+e)/2,Or=(s,t,e,n)=>s===(n?"left":"right")?e:s==="center"?(t+e)/2:t;an=s=>s===0||s===1,pr=(s,t,e)=>-(Math.pow(2,10*(s-=1))*Math.sin((s-t)*lt/e)),gr=(s,t,e)=>Math.pow(2,-10*s)*Math.sin((s-t)*lt/e)+1,je={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*ut)+1,easeOutSine:s=>Math.sin(s*ut),easeInOutSine:s=>-.5*(Math.cos(et*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=>an(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=>an(s)?s:pr(s,.075,.3),easeOutElastic:s=>an(s)?s:gr(s,.075,.3),easeInOutElastic(s){return an(s)?s:s<.5?.5*pr(s*2,.1125,.45):.5+.5*gr(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-je.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?je.easeInBounce(s*2)*.5:je.easeOutBounce(s*2-1)*.5+.5};td=["x","y","borderWidth","radius","tension"],ed=["color","borderColor","backgroundColor"];mr=new Map;Ir={values(s){return at(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=od(s,e)}let r=se(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),Qe(s,n,l)},logarithmic(s,t,e){if(s===0)return"0";let n=e[t].significand||s/Math.pow(10,Math.floor(se(s)));return[1,2,3,5,10,15].includes(n)||t>.8*e.length?Ir.numeric.call(this,s,t,e):""}};Ze={formatters:Ir};fe=Object.create(null),yn=Object.create(null);ui=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 hi(this,t,e)}get(t){return Cs(this,t)}describe(t,e){return hi(yn,t,e)}override(t,e){return hi(fe,t,e)}route(t,e,n,i){let o=Cs(this,t),r=Cs(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 tt(l)?Object.assign({},c,l):q(l,c)},set(l){this[a]=l}}})}apply(t){t.forEach(e=>e(this))}},ct=new ui({_scriptable:s=>!s.startsWith("on"),_indexable:s=>s!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[sd,nd,rd]);hd=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,ud=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;pd=s=>+s||0;gd=(s,t)=>s?s+pn(t):t,Ai=(s,t)=>tt(t)&&s!=="adapters"&&(Object.getPrototypeOf(t)===null||t.constructor===Object);vd=(s,t)=>s===!0?t:typeof s=="string"?ne(t,s):void 0;Ed=Number.EPSILON||1e-14,Ye=(s,t)=>ts==="x"?"y":"x";En=s=>s.ownerDocument.defaultView.getComputedStyle(s,null);Ad=["top","right","bottom","left"];Pd=(s,t,e)=>(s>0||t>0)&&(!e||!e.shadowRoot);ue=s=>Math.round(s*10)/10;Yr=function(){let s=!1;try{let t={get passive(){return s=!0,!1}};Cn()&&(window.addEventListener("test",null,t),window.removeEventListener("test",null,t))}catch(t){}return s}();Id=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}}},Fd=function(){return{x(s){return s},setWidth(s){},textAlign(s){return s},xPlus(s,t){return s+t},leftForLtr(s,t){return s}}}});var Al={};fo(Al,{Animation:()=>Rn,Animations:()=>Is,ArcElement:()=>ye,BarController:()=>Re,BarElement:()=>Be,BasePlatform:()=>Fs,BasicPlatform:()=>On,BubbleController:()=>Oe,CategoryScale:()=>is,Chart:()=>Xt,Colors:()=>bl,DatasetController:()=>Mt,Decimation:()=>vl,DomPlatform:()=>Fn,DoughnutController:()=>Qt,Element:()=>Tt,Filler:()=>_l,Interaction:()=>el,Legend:()=>Sl,LineController:()=>Ie,LineElement:()=>Bt,LinearScale:()=>os,LogarithmicScale:()=>rs,PieController:()=>ss,PointElement:()=>Ne,PolarAreaController:()=>xe,RadarController:()=>Fe,RadialLinearScale:()=>ve,Scale:()=>Se,ScatterController:()=>Ve,SubTitle:()=>kl,Ticks:()=>Ze,TimeScale:()=>Ce,TimeSeriesScale:()=>as,Title:()=>El,Tooltip:()=>Ml,_adapters:()=>tl,_detectPlatform:()=>rl,animator:()=>qt,controllers:()=>Ja,defaults:()=>ct,elements:()=>pl,layouts:()=>xt,plugins:()=>Dl,registerables:()=>Wf,registry:()=>Nt,scales:()=>Ll});function jd(s,t){let e=[],n=Object.keys(t);for(let i=0;i0||!e&&o<0)return i.index}return null}function sa(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=qd(o,r,n),h=t.length,u;for(let f=0;fe[n].axis===t).shift()}function Zd(s,t){return ie(s,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function Jd(s,t,e){return ie(s,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:e,index:t,mode:"default",type:"data"})}function Ms(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 eh(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 sh(s){let t=s.iScale,e=eh(t,s.type),n=t._length,i,o,r,a,l=()=>{r===32767||r===-32768||(Ge(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 Za(s,t,e,n){return at(s)?oh(s,t,e,n):t[e.axis]=e.parse(s,n),t}function ia(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 ah(s){let t,e,n,i,o;return s.horizontal?(t=s.base>s.x,e="left",n="right"):(t=s.baseXe(S,a,l,!0)?1:Math.max(M,M*e,E,E*e),p=(S,M,E)=>Xe(S,a,l,!0)?-1:Math.min(M,M*e,E,E*e),g=f(0,c,h),b=f(ut,d,u),y=p(et,c,h),x=p(et+ut,d,u);n=(g-y)/2,i=(b-x)/2,o=-(g+y)/2,r=-(b+x)/2}return{ratioX:n,ratioY:i,offsetX:o,offsetY:r}}function Ae(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}function uh(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?Tr:jt;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=>!Z(g[h.axis]));d.lo-=Math.max(0,f);let p=u.slice(d.hi).findIndex(g=>!Z(g[h.axis]));d.hi+=Math.max(0,p)}return d}}return{lo:0,hi:o.length-1}}function zs(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 Ds(s,t){return s.filter(e=>e.pos===t)}function la(s,t){return s.filter(e=>sl.indexOf(e.pos)===-1&&e.box.axis===t)}function Ts(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 mh(s){let t=[],e,n,i,o,r,a;for(e=0,n=(s||[]).length;ec.box.fullSize),!0),n=Ts(Ds(t,"left"),!0),i=Ts(Ds(t,"right")),o=Ts(Ds(t,"top"),!0),r=Ts(Ds(t,"bottom")),a=la(t,"x"),l=la(t,"y");return{fullSize:e,leftAndTop:n.concat(o),rightAndBottom:i.concat(l).concat(r).concat(a),chartArea:Ds(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 nl(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 xh(s,t,e,n){let{pos:i,box:o}=e,r=s.maxPadding;if(!tt(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&&nl(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 _h(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 Ch(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 Ps(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||In(a.addedNodes,n),r=r&&!In(a.removedNodes,n);r&&e()});return i.observe(document,{childList:!0,subtree:!0}),i}function Th(s,t,e){let n=s.canvas,i=new MutationObserver(o=>{let r=!1;for(let a of o)r=r||In(a.removedNodes,n),r=r&&!In(a.addedNodes,n);r&&e()});return i.observe(document,{childList:!0,subtree:!0}),i}function ol(){let s=window.devicePixelRatio;s!==ua&&(ua=s,Vs.forEach((t,e)=>{e.currentDevicePixelRatio!==s&&t()}))}function Lh(s,t){Vs.size||window.addEventListener("resize",ol),Vs.set(s,t)}function Ah(s){Vs.delete(s),Vs.size||window.removeEventListener("resize",ol)}function Ph(s,t,e){let n=s.canvas,i=n&&Sn(n);if(!i)return;let o=Ci((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),Lh(s,o),r}function Ki(s,t,e){e&&e.disconnect(),t==="resize"&&Ah(s)}function Rh(s,t,e){let n=s.canvas,i=Ci(o=>{s.ctx!==null&&e(Mh(o,s))},s);return kh(n,t,i),i}function rl(s){return!Cn()||typeof OffscreenCanvas!="undefined"&&s instanceof OffscreenCanvas?On:Fn}function Oh(s,t){let e=s.options.ticks,n=Ih(s),i=Math.min(e.maxTicksLimit||n,n),o=e.major.enabled?Vh(t):[],r=o.length,a=o[0],l=o[r-1],c=[];if(r>i)return Nh(t,c,o,r/i),c;let d=Fh(o,t,i);if(r>0){let h,u,f=r>1?Math.round((l-a)/(r-1)):null;for(wn(t,c,d,Z(f)?0:a-f,a),h=0,u=r-1;hi)return l}return Math.max(i,1)}function Vh(s){let t=[],e,n;for(e=0,n=s.length;er+a)))return l}function $h(s,t){nt(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(".");ct.route(o,i,l,a)})}function qh(s){return"id"in s&&"defaults"in s}function Xh(s){let t={},e=[],n=Object.keys(Nt.plugins.items);for(let o=0;o1&&ba(s[0].toLowerCase());if(n)return n}throw new Error(`Cannot determine type of '${s}' axis. Please provide 'axis' or 'position' option.`)}function ya(s,t,e){if(e[t+"AxisID"]===s)return{axis:t}}function nu(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 ya(s,"x",e[0])||ya(s,"y",e[0])}return{}}function iu(s,t){let e=fe[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(!tt(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=no(r,a,nu(r,s),ct.scales[a.type]),c=eu(l,i),d=e.scales||{};o[r]=Ke(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=(fe[a]||{}).scales||{};Object.keys(d).forEach(h=>{let u=tu(h,l),f=r[u+"AxisID"]||u;o[f]=o[f]||Object.create(null),Ke(o[f],[{axis:u},n[f],d[h]])})}),Object.keys(o).forEach(r=>{let a=o[r];Ke(a,[ct.scales[a.type],ct.scale])}),o}function al(s){let t=s.options||(s.options={});t.plugins=q(t.plugins,{}),t.scales=iu(s,t)}function ll(s){return s=s||{},s.datasets=s.datasets||[],s.labels=s.labels||[],s}function ou(s){return s=s||{},s.data=ll(s.data),al(s),s}function Mn(s,t){let e=va.get(s);return e||(e=t(),va.set(s,e),cl.add(e)),e}function xa(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:_n(t,e),subPrefixes:e.filter(a=>!a.toLowerCase().includes("hover"))},n.set(i,o)),o}function au(s,t){let{isScriptable:e,isIndexable:n}=Li(s);for(let i of t){let o=e(i),r=n(i),a=(r||o)&&s[i];if(o&&(ee(a)||ru(a))||r&&at(a))return!0}return!1}function _a(s,t){return s==="top"||s==="bottom"||cu.indexOf(s)===-1&&t==="x"}function Ca(s,t){return function(e,n){return e[s]===n[s]?e[t]-n[t]:e[s]-n[s]}}function Sa(s){let t=s.chart,e=t.options.animation;t.notifyPlugins("afterRender"),rt(e&&e.onComplete,[s],t)}function du(s){let t=s.chart,e=t.options.animation;rt(e&&e.onProgress,[s],t)}function dl(s){return Cn()&&typeof s=="string"?s=document.getElementById(s):s&&s.length&&(s=s[0]),s&&s.canvas&&(s=s.canvas),s}function hu(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 uu(s,t,e,n){return!e||s.type==="mouseout"?null:n?t:s}function ka(){return nt(Xt.instances,s=>s._plugins.invalidate())}function fu(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,bt(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,bt(n-e));s.arc(i,o,a+c/2,e-u/2,n+u/2,!0)}else{let u=Math.min(c/2,r*bt(n-e));if(d==="round")s.arc(i,o,u,e-et/2,n+et/2,!0);else if(d==="bevel"){let f=2*u*u,p=-f*Math.cos(e+et/2)+i,g=-f*Math.sin(e+et/2)+o,b=f*Math.cos(n+et/2)+i,y=f*Math.sin(n+et/2)+o;s.lineTo(p,g),s.lineTo(b,y)}}s.closePath(),s.moveTo(0,0),s.rect(0,0,s.canvas.width,s.canvas.height),s.clip("evenodd")}function pu(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+ut,n-ut),s.closePath(),s.clip()}function gu(s){return xn(s,["outerStart","outerEnd","innerStart","innerEnd"])}function mu(s,t,e,n){let i=gu(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 pt(l,0,Math.min(o,c))};return{outerStart:a(i.outerStart),outerEnd:a(i.outerEnd),innerStart:pt(i.innerStart,0,r),innerEnd:pt(i.innerEnd,0,r)}}function es(s,t,e,n){return{x:e+s*Math.cos(t),y:n+s*Math.sin(t)}}function Vn(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 R=d>0?d-n:0,H=h>0?h-n:0,B=(R+H)/2,G=B!==0?p*B/(B+n):p;f=(p-G)/2}let g=Math.max(.001,p*h-e/et)/h,b=(p-g)/2,y=l+b+f,x=i-b-f,{outerStart:S,outerEnd:M,innerStart:E,innerEnd:v}=mu(t,u,h,x-y),m=h-S,C=h-M,k=y+S/m,w=x-M/C,_=u+E,D=u+v,T=y+E/_,P=x-v/D;if(s.beginPath(),o){let R=(k+w)/2;if(s.arc(r,a,h,k,R),s.arc(r,a,h,R,w),M>0){let W=es(C,w,r,a);s.arc(W.x,W.y,M,w,x+ut)}let H=es(D,x,r,a);if(s.lineTo(H.x,H.y),v>0){let W=es(D,P,r,a);s.arc(W.x,W.y,v,x+ut,P+Math.PI)}let B=(x-v/u+(y+E/u))/2;if(s.arc(r,a,u,x-v/u,B,!0),s.arc(r,a,u,B,y+E/u,!0),E>0){let W=es(_,T,r,a);s.arc(W.x,W.y,E,T+Math.PI,y-ut)}let G=es(m,y,r,a);if(s.lineTo(G.x,G.y),S>0){let W=es(m,k,r,a);s.arc(W.x,W.y,S,y-ut,k)}}else{s.moveTo(r,a);let R=Math.cos(k)*h+r,H=Math.sin(k)*h+a;s.lineTo(R,H);let B=Math.cos(w)*h+r,G=Math.sin(w)*h+a;s.lineTo(B,G)}s.closePath()}function bu(s,t,e,n,i){let{fullCircles:o,startAngle:r,circumference:a}=t,l=t.endAngle;if(o){Vn(s,t,e,n,l,i);for(let c=0;c=et&&f===0&&d!=="miter"&&fu(s,t,g),o||(Vn(s,t,e,n,g,i),s.stroke())}function hl(s,t,e=t){s.lineCap=q(e.borderCapStyle,t.borderCapStyle),s.setLineDash(q(e.borderDash,t.borderDash)),s.lineDashOffset=q(e.borderDashOffset,t.borderDashOffset),s.lineJoin=q(e.borderJoinStyle,t.borderJoinStyle),s.lineWidth=q(e.borderWidth,t.borderWidth),s.strokeStyle=q(e.borderColor,t.borderColor)}function vu(s,t,e){s.lineTo(e.x,e.y)}function xu(s){return s.stepped?Vr:s.tension||s.cubicInterpolationMode==="monotone"?Nr:vu}function ul(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-M:M))%o,S=()=>{g!==b&&(s.lineTo(d,b),s.lineTo(d,g),s.lineTo(d,y))};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 M=f.x,E=f.y,v=M|0;v===p?(Eb&&(b=E),d=(h*d+M)/++h):(S(),s.lineTo(M,E),p=v,h=0,g=b=E),y=E}S()}function oo(s){let t=s.options,e=t.borderDash&&t.borderDash.length;return!s._decimated&&!s._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!e?Cu:_u}function Su(s){return s.stepped?Kr:s.tension||s.cubicInterpolationMode==="monotone"?Gr:he}function Eu(s,t,e,n){let i=t._path;i||(i=t._path=new Path2D,t.path(i,e,n)&&i.closePath()),hl(s,t.options),s.stroke(i)}function ku(s,t,e,n){let{segments:i,options:o}=t,r=oo(t);for(let a of i)hl(s,o,a.style),s.beginPath(),r(s,t,a,{start:e,end:e+n-1})&&s.closePath(),s.stroke()}function Mu(s,t,e,n){wu&&!t.options.segment?Eu(s,t,e,n):ku(s,t,e,n)}function wa(s,t,e,n){let i=s.options,{[e]:o}=s.getProps([e],n);return Math.abs(t-o)gl(t++)),t}function Iu(s,t){return s.backgroundColor=s.data.map(()=>ml(t++)),t}function Fu(s){let t=0;return(e,n)=>{let i=s.getDatasetMeta(n).controller;i instanceof Qt?t=Ou(e,t):i instanceof xe?t=Iu(e,t):i&&(t=Ru(e,t))}}function Da(s){let t;for(t in s)if(s[t].borderColor||s[t].backgroundColor)return!0;return!1}function Vu(s){return s&&(s.borderColor||s.backgroundColor)}function Nu(){return ct.borderColor!=="rgba(0,0,0,0.1)"||ct.backgroundColor!=="rgba(0,0,0,0.1)"}function Bu(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 zu(s,t,e,n){let i=0,o=0,r,a,l,c,d,h,u,f,p,g,b=[],y=t+e-1,x=s[t].x,M=s[y].x-x;for(r=t;rg&&(g=c,u=r),i=(o*i+a.x)/++o;else{let v=r-1;if(!Z(h)&&!Z(u)){let m=Math.min(h,u),C=Math.max(h,u);m!==f&&m!==v&&b.push({...s[m],x:i}),C!==f&&C!==v&&b.push({...s[C],x:i})}r>0&&v!==f&&b.push(s[v]),b.push(a),d=E,o=0,p=g=c,h=u=f=r}}return b}function yl(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 Ta(s){s.data.datasets.forEach(t=>{yl(t)})}function Hu(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=pt(jt(t,o.axis,r).lo,0,e-1)),c?i=pt(jt(t,o.axis,a).hi+1,n,e)-n:i=e-n,{start:n,count:i}}function $u(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=zn(l,c,i);let d=ao(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=Bi(t,d);for(let u of h){let f=ao(e,o[u.start],o[u.end],u.loop),p=Ni(a,i,f);for(let g of p)r.push({source:g,target:u,start:{[e]:La(d,f,"start",Math.max)},end:{[e]:La(d,f,"end",Math.min)}})}}return r}function ao(s,t,e,n){if(n)return;let i=t[s],o=e[s];return s==="angle"&&(i=bt(i),o=bt(o)),{property:s,start:i,end:o}}function Wu(s,t){let{x:e=null,y:n=null}=s||{},i=t.points,o=[];return t.segments.forEach(({start:r,end:a})=>{a=zn(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 zn(s,t,e){for(;t>s;t--){let n=e[t];if(!isNaN(n.x)&&!isNaN(n.y))break}return t}function La(s,t,e,n){return s&&t?n(s[e],t[e]):s?s[e]:t?t[e]:0}function xl(s,t){let e=[],n=!1;return at(s)?(n=!0,e=s):e=Wu(s,t),e.length?new Bt({points:e,options:{tension:0},_loop:n,_fullLoop:n}):null}function Aa(s){return s&&s.fill!==!1}function ju(s,t,e){let i=s[t].fill,o=[t],r;if(!e)return i;for(;i!==!1&&o.indexOf(i)===-1;){if(!ht(i))return i;if(r=s[i],!r)return!1;if(r.visible)return i;o.push(i),i=r.fill}return!1}function Uu(s,t,e){let n=qu(s);if(tt(n))return isNaN(n.value)?!1:n;let i=parseFloat(n);return ht(i)&&Math.floor(i)===i?Yu(n[0],t,i,e):["origin","start","end","stack","shape"].indexOf(n)>=0&&n}function Yu(s,t,e,n){return(s==="-"||s==="+")&&(e=t+e),e===t||e<0||e>=n?!1:e}function Ku(s,t){let e=null;return s==="start"?e=t.bottom:s==="end"?e=t.top:tt(s)?e=t.getPixelForValue(s.value):t.getBasePixel&&(e=t.getBasePixel()),e}function Gu(s,t,e){let n;return s==="start"?n=e:s==="end"?n=t.options.reverse?t.min:t.max:tt(s)?n=s.value:n=t.getBaseValue(),n}function qu(s){let t=s.options,e=t.fill,n=q(e&&e.target,e);return n===void 0&&(n=!!t.backgroundColor),n===!1||n===null?!1:n===!0?"origin":n}function Xu(s){let{scale:t,index:e,line:n}=s,i=[],o=n.segments,r=n.points,a=Qu(t,e);a.push(xl({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 hf(s,t,e){let n=s;return typeof t.text!="string"&&(n=Cl(t,e)),n}function Cl(s,t){let e=s.text?s.text.length:0;return t*e}function uf(s,t){return!!((s==="mousemove"||s==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(s==="click"||s==="mouseup"))}function ff(s,t){let e=new Ns({ctx:s.ctx,options:t,chart:s});xt.configure(s,e,t),xt.addBox(s,e),s.titleBlock=e}function Gt(s,t){return t&&(at(t)?Array.prototype.push.apply(s,t):s.push(t)),s}function oe(s){return(typeof s=="string"||s instanceof String)&&s.indexOf(` +"use strict";var Ul=Object.create;var ms=Object.defineProperty;var Kl=Object.getOwnPropertyDescriptor;var Yl=Object.getOwnPropertyNames;var Gl=Object.getPrototypeOf,ql=Object.prototype.hasOwnProperty;var Xl=(s,t,e)=>t in s?ms(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var ti=(s,t)=>()=>(s&&(t=s(s=0)),t);var Ql=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),So=(s,t)=>{for(var e in t)ms(s,e,{get:t[e],enumerable:!0})},wo=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Yl(t))!ql.call(s,i)&&i!==e&&ms(s,i,{get:()=>t[i],enumerable:!(n=Kl(t,i))||n.enumerable});return s};var qs=(s,t,e)=>(e=s!=null?Ul(Gl(s)):{},wo(t||!s||!s.__esModule?ms(e,"default",{value:s,enumerable:!0}):e,s)),Zl=s=>wo(ms({},"__esModule",{value:!0}),s);var H=(s,t,e)=>(Xl(s,typeof t!="symbol"?t+"":t,e),e);var bs=Ql((ei,si)=>{((s,t)=>{typeof define=="function"&&define.amd?define([],t):typeof si=="object"&&typeof ei!="undefined"?si.exports=t():s.Papa=t()})(ei,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(v){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(y){var S=_(y);S.chunkSize=parseInt(S.chunkSize),y.step||y.chunk||(S.chunkSize=null),this._handle=new f(S),(this._handle.streamer=this)._config=S}.call(this,v),this.parseChunk=function(y,S){var D=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview),i)t.postMessage({results:M,workerId:a.WORKER_ID,finished:D});else if(w(this._config.chunk)&&!S){if(this._config.chunk(M,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=M=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(M.data),this._completeResults.errors=this._completeResults.errors.concat(M.errors),this._completeResults.meta=M.meta),this._completed||!D||!w(this._config.complete)||M&&M.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),D||M&&M.meta.paused||this._nextChunk(),M}this._halted=!0},this._sendError=function(y){w(this._config.error)?this._config.error(y):i&&this._config.error&&t.postMessage({workerId:a.WORKER_ID,error:y,finished:!1})}}function c(v){var y;(v=v||{}).chunkSize||(v.chunkSize=a.RemoteChunkSize),l.call(this,v),this._nextChunk=n?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(S){this._input=S,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(y=new XMLHttpRequest,this._config.withCredentials&&(y.withCredentials=this._config.withCredentials),n||(y.onload=E(this._chunkLoaded,this),y.onerror=E(this._chunkError,this)),y.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var S,D=this._config.downloadRequestHeaders;for(S in D)y.setRequestHeader(S,D[S])}var M;this._config.chunkSize&&(M=this._start+this._config.chunkSize-1,y.setRequestHeader("Range","bytes="+this._start+"-"+M));try{y.send(this._config.downloadRequestBody)}catch(C){this._chunkError(C.message)}n&&y.status===0&&this._chunkError()}},this._chunkLoaded=function(){y.readyState===4&&(y.status<200||400<=y.status?this._chunkError():(this._start+=this._config.chunkSize||y.responseText.length,this._finished=!this._config.chunkSize||this._start>=(S=>(S=S.getResponseHeader("Content-Range"))!==null?parseInt(S.substring(S.lastIndexOf("/")+1)):-1)(y),this.parseChunk(y.responseText)))},this._chunkError=function(S){S=y.statusText||S,this._sendError(new Error(S))}}function d(v){(v=v||{}).chunkSize||(v.chunkSize=a.LocalChunkSize),l.call(this,v);var y,S,D=typeof FileReader!="undefined";this.stream=function(M){this._input=M,S=M.slice||M.webkitSlice||M.mozSlice,D?((y=new FileReader).onload=E(this._chunkLoaded,this),y.onerror=E(this._chunkError,this)):y=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(M.target.result)},this._chunkError=function(){this._sendError(y.error)}}function h(v){var y;l.call(this,v=v||{}),this.stream=function(S){return y=S,this._nextChunk()},this._nextChunk=function(){var S,D;if(!this._finished)return S=this._config.chunkSize,y=S?(D=y.substring(0,S),y.substring(S)):(D=y,""),this._finished=!y,this.parseChunk(D)}}function u(v){l.call(this,v=v||{});var y=[],S=!0,D=!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(M){this._input=M,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){D&&y.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),y.length?this.parseChunk(y.shift()):S=!0},this._streamData=E(function(M){try{y.push(typeof M=="string"?M:M.toString(this._config.encoding)),S&&(S=!1,this._checkIsFinished(),this.parseChunk(y.shift()))}catch(C){this._streamError(C)}},this),this._streamError=E(function(M){this._streamCleanUp(),this._sendError(M)},this),this._streamEnd=E(function(){this._streamCleanUp(),D=!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(v){var y,S,D,M,C=Math.pow(2,53),T=-C,k=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,A=/^((\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,O=0,z=0,G=!1,$=!1,L=[],V={data:[],errors:[],meta:{}};function W(F){return v.skipEmptyLines==="greedy"?F.join("").trim()==="":F.length===1&&F[0].length===0}function j(){if(V&&D&&(B("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+a.DefaultDelimiter+"'"),D=!1),v.skipEmptyLines&&(V.data=V.data.filter(function(Y){return!W(Y)})),U()){let Y=function(K,Z){w(v.transformHeader)&&(K=v.transformHeader(K,Z)),L.push(K)};var R=Y;if(V)if(Array.isArray(V.data[0])){for(var F=0;U()&&F(at=>(v.dynamicTypingFunction&&v.dynamicTyping[at]===void 0&&(v.dynamicTyping[at]=v.dynamicTypingFunction(at)),(v.dynamicTyping[at]||v.dynamicTyping)===!0))(J)?st==="true"||st==="TRUE"||st!=="false"&&st!=="FALSE"&&((at=>{if(k.test(at)&&(at=parseFloat(at),T=L.length?"__parsed_extra":L[X]:q,ut=v.transform?v.transform(ut,q):ut);q==="__parsed_extra"?(Z[q]=Z[q]||[],Z[q].push(ut)):Z[q]=ut}return v.header&&(X>L.length?B("FieldMismatch","TooManyFields","Too many fields: expected "+L.length+" fields but parsed "+X,z+K):Xv.preview?S.abort():(V.data=V.data[0],M(V,P))))}),this.parse=function(F,I,N){var R=v.quoteChar||'"',R=(v.newline||(v.newline=this.guessLineEndings(F,R)),D=!1,v.delimiter?w(v.delimiter)&&(v.delimiter=v.delimiter(F),V.meta.delimiter=v.delimiter):((R=((Y,K,Z,X,q)=>{var ut,J,st,at;q=q||[","," ","|",";",a.RECORD_SEP,a.UNIT_SEP];for(var Rt=0;Rt=N.length/2?`\r +`:"\r"}}function p(v){return v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function m(v){var y=(v=v||{}).delimiter,S=v.newline,D=v.comments,M=v.step,C=v.preview,T=v.fastMode,k=null,A=!1,P=v.quoteChar==null?'"':v.quoteChar,O=P;if(v.escapeChar!==void 0&&(O=v.escapeChar),(typeof y!="string"||-1=C)return ft(!0);break}N.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:I.length,index:z}),J++}}else if(D&&R.length===0&&$.substring(z,z+B)===D){if(q===-1)return ft();z=q+U,q=$.indexOf(S,z),X=$.indexOf(y,z)}else if(X!==-1&&(X=C)return ft(!0)}return it();function at(yt){I.push(yt),Y=z}function Rt(yt){var Et=0;return Et=yt!==-1&&(yt=$.substring(J+1,yt))&&yt.trim()===""?yt.length:Et}function it(yt){return V||(yt===void 0&&(yt=$.substring(z)),R.push(yt),z=W,at(R),F&&Kt()),ft()}function gt(yt){z=yt,at(R),R=[],q=$.indexOf(S,z)}function ft(yt){if(v.header&&!L&&I.length&&!A){var Et=I[0],ne=Object.create(null),Jn=new Set(Et);let _o=!1;for(let $e=0;$eD.charCodeAt(0)!==65279?D:D.slice(1))(v),S=new(y.download?c:h)(y)):v.readable===!0&&w(v.read)&&w(v.on)?S=new u(y):(t.File&&v instanceof File||v instanceof Object)&&(S=new d(y)),S.stream(v);(S=(()=>{var D;return!!a.WORKERS_SUPPORTED&&(D=(()=>{var M=t.URL||t.webkitURL||null,C=s.toString();return a.BLOB_URL||(a.BLOB_URL=M.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; ","(",C,")();"],{type:"text/javascript"})))})(),(D=new t.Worker(D)).onmessage=g,D.id=r++,o[D.id]=D)})()).userStep=y.step,S.userChunk=y.chunk,S.userComplete=y.complete,S.userError=y.error,y.step=w(y.step),y.chunk=w(y.chunk),y.complete=w(y.complete),y.error=w(y.error),delete y.worker,S.postMessage({input:v,config:y,workerId:S.id})},a.unparse=function(v,y){var S=!1,D=!0,M=",",C=`\r +`,T='"',k=T+T,A=!1,P=null,O=!1,z=((()=>{if(typeof y=="object"){if(typeof y.delimiter!="string"||a.BAD_DELIMITERS.filter(function(L){return y.delimiter.indexOf(L)!==-1}).length||(M=y.delimiter),typeof y.quotes!="boolean"&&typeof y.quotes!="function"&&!Array.isArray(y.quotes)||(S=y.quotes),typeof y.skipEmptyLines!="boolean"&&typeof y.skipEmptyLines!="string"||(A=y.skipEmptyLines),typeof y.newline=="string"&&(C=y.newline),typeof y.quoteChar=="string"&&(T=y.quoteChar),typeof y.header=="boolean"&&(D=y.header),Array.isArray(y.columns)){if(y.columns.length===0)throw new Error("Option columns is empty");P=y.columns}y.escapeChar!==void 0&&(k=y.escapeChar+T),y.escapeFormulae instanceof RegExp?O=y.escapeFormulae:typeof y.escapeFormulae=="boolean"&&y.escapeFormulae&&(O=/^[=+\-@\t\r].*$/)}})(),new RegExp(p(T),"g"));if(typeof v=="string"&&(v=JSON.parse(v)),Array.isArray(v)){if(!v.length||Array.isArray(v[0]))return G(null,v,A);if(typeof v[0]=="object")return G(P||Object.keys(v[0]),v,A)}else if(typeof v=="object")return typeof v.data=="string"&&(v.data=JSON.parse(v.data)),Array.isArray(v.data)&&(v.fields||(v.fields=v.meta&&v.meta.fields||P),v.fields||(v.fields=Array.isArray(v.data[0])?v.fields:typeof v.data[0]=="object"?Object.keys(v.data[0]):[]),Array.isArray(v.data[0])||typeof v.data[0]=="object"||(v.data=[v.data])),G(v.fields||[],v.data||[],A);throw new Error("Unable to serialize unrecognized input");function G(L,V,W){var j="",U=(typeof L=="string"&&(L=JSON.parse(L)),typeof V=="string"&&(V=JSON.parse(V)),Array.isArray(L)&&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 Hc(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 $c(s,t,e){let n=pr(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 Wc(s,t,e,n,i){return s===i?(t-e)/n+(t.5?d/(2-o-r):d/(o+r),l=Wc(e,n,i,d,o),l=l*60+.5),[l|0,c||0,a]}function bi(s,t,e,n){return(Array.isArray(t)?s(t[0],t[1],t[2]):s(t,e,n)).map(fe)}function vi(s,t,e){return bi(pr,s,t,e)}function jc(s,t,e){return bi($c,s,t,e)}function Uc(s,t,e){return bi(Hc,s,t,e)}function gr(s){return(s%360+360)%360}function Kc(s){let t=zc.exec(s),e=255,n;if(!t)return;t[5]!==n&&(e=t[6]?ks(+t[5]):fe(+t[5]));let i=gr(+t[2]),o=+t[3]/100,r=+t[4]/100;return t[1]==="hwb"?n=jc(i,o,r):t[1]==="hsv"?n=Uc(i,o,r):n=vi(i,o,r),{r:n[0],g:n[1],b:n[2],a:e}}function Yc(s,t){var e=mi(s);e[0]=gr(e[0]+t),e=vi(e),s.r=e[0],s.g=e[1],s.b=e[2]}function Gc(s){if(!s)return;let t=mi(s),e=t[0],n=dr(t[1]),i=dr(t[2]);return s.a<255?`hsla(${e}, ${n}%, ${i}%, ${ie(s.a)})`:`hsl(${e}, ${n}%, ${i}%)`}function qc(){let s={},t=Object.keys(ur),e=Object.keys(hr),n,i,o,r,a;for(n=0;n>16&255,o>>8&255,o&255]}return s}function Xc(s){gn||(gn=qc(),gn.transparent=[0,0,0,0]);let t=gn[s.toLowerCase()];return t&&{r:t[0],g:t[1],b:t[2],a:t.length===4?t[3]:255}}function Zc(s){let t=Qc.exec(s),e=255,n,i,o;if(t){if(t[7]!==n){let r=+t[7];e=t[8]?ks(r):ue(r*255,0,255)}return n=+t[1],i=+t[3],o=+t[5],n=255&(t[2]?ks(n):ue(n,0,255)),i=255&(t[4]?ks(i):ue(i,0,255)),o=255&(t[6]?ks(o):ue(o,0,255)),{r:n,g:i,b:o,a:e}}}function Jc(s){return s&&(s.a<255?`rgba(${s.r}, ${s.g}, ${s.b}, ${ie(s.a)})`:`rgb(${s.r}, ${s.g}, ${s.b})`)}function td(s,t,e){let n=Ge(ie(s.r)),i=Ge(ie(s.g)),o=Ge(ie(s.b));return{r:fe(pi(n+e*(Ge(ie(t.r))-n))),g:fe(pi(i+e*(Ge(ie(t.g))-i))),b:fe(pi(o+e*(Ge(ie(t.b))-o))),a:s.a+e*(t.a-s.a)}}function mn(s,t,e){if(s){let n=mi(s);n[t]=Math.max(0,Math.min(n[t]+n[t]*e,t===0?360:1)),n=vi(n),s.r=n[0],s.g=n[1],s.b=n[2]}}function mr(s,t){return s&&Object.assign(t||{},s)}function fr(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=fe(s[3]))):(t=mr(s,{r:0,g:0,b:0,a:1}),t.a=fe(t.a)),t}function ed(s){return s.charAt(0)==="r"?Zc(s):Kc(s)}var ue,Bt,gi,Oc,Fc,pn,Ic,Nc,zc,hr,ur,gn,Qc,pi,Ge,Ms,br=ti(()=>{ue=(s,t,e)=>Math.max(Math.min(s,e),t);Bt={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},gi=[..."0123456789ABCDEF"],Oc=s=>gi[s&15],Fc=s=>gi[(s&240)>>4]+gi[s&15],pn=s=>(s&240)>>4===(s&15),Ic=s=>pn(s.r)&&pn(s.g)&&pn(s.b)&&pn(s.a);Nc=(s,t)=>s<255?t(s):"";zc=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;hr={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"},ur={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"};Qc=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;pi=s=>s<=.0031308?s*12.92:Math.pow(s,1/2.4)*1.055-.055,Ge=s=>s<=.04045?s/12.92:Math.pow((s+.055)/1.055,2.4);Ms=class s{constructor(t){if(t instanceof s)return t;let e=typeof t,n;e==="object"?n=fr(t):e==="string"&&(n=Vc(t)||Xc(t)||ed(t)),this._rgb=n,this._valid=!!n}get valid(){return this._valid}get rgb(){var t=mr(this._rgb);return t&&(t.a=ie(t.a)),t}set rgb(t){this._rgb=fr(t)}rgbString(){return this._valid?Jc(this._rgb):void 0}hexString(){return this._valid?Bc(this._rgb):void 0}hslString(){return this._valid?Gc(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=td(this._rgb,t._rgb,e)),this}clone(){return new s(this.rgb)}alpha(t){return this._rgb.a=fe(t),this}clearer(t){let e=this._rgb;return e.a*=1-t,this}greyscale(){let t=this._rgb,e=Ds(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 mn(this._rgb,2,t),this}darken(t){return mn(this._rgb,2,-t),this}saturate(t){return mn(this._rgb,1,t),this}desaturate(t){return mn(this._rgb,1,-t),this}rotate(t){return Yc(this._rgb,t),this}}});function Qt(){}function tt(s){return s==null}function ct(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 Mt(s,t){return pt(s)?s:t}function Q(s,t){return typeof s=="undefined"?t:s}function lt(s,t,e){if(s&&typeof s.call=="function")return s.apply(e,t)}function ot(s,t,e,n){let i,o,r;if(ct(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 ae(s,t){return(vr[t]||(vr[t]=od(t)))(s)}function wn(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Ar(s){return s.type==="mouseup"||s.type==="click"||s.type==="contextmenu"}function ts(s,t,e){return Math.abs(s-t)i-o).pop(),t}function ld(s){return typeof s=="symbol"||typeof s=="object"&&s!==null&&!(Symbol.toPrimitive in s||"toString"in s||"valueOf"in s)}function Ae(s){return!ld(s)&&!isNaN(parseFloat(s))&&isFinite(s)}function Rr(s,t){let e=Math.round(s);return e-t<=s&&e+t>=s}function Ei(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 kn(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 Ir(s,t,e){let n=0,i=s.length;for(;nn&&s[i-1]>e;)i--;return n>0||i{let n="_onData"+wn(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 Di(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)&&(Vr.forEach(o=>{delete s[o]}),delete s._chartjs)}function Ti(s){let t=new Set(s);return t.size===s.length?s:Array.from(t)}function Ai(s,t){let e=[],n=!1;return function(...i){e=i,n||(n=!0,Li.call(window,()=>{n=!1,s.apply(t,e)}))}}function Br(s,t){let e;return function(...n){return t?(clearTimeout(e),e=setTimeout(s,t,n)):s.apply(this,n),t}}function Pi(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 m=l.slice(0,i+1).reverse().findIndex(g=>!tt(g[a.axis]));i-=Math.max(0,m)}i=vt(i,0,n-1)}if(p){let m=Math.max(qt(l,r.axis,u,!0).hi+1,e?0:qt(t,d,r.getPixelForValue(u),!0).hi+1);if(c){let g=l.slice(m-1).findIndex(b=>!tt(b[a.axis]));m+=Math.max(0,g)}o=vt(m,i,n)-i}else o=n-i}return{start:i,count:o}}function Ri(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 Oi(s){if(s&&typeof s=="object"){let t=s.toString();return t==="[object CanvasPattern]"||t==="[object CanvasGradient]"}return!1}function Fi(s){return Oi(s)?s:new Ms(s)}function yi(s){return Oi(s)?s:new Ms(s).saturate(.5).darken(.1).hexString()}function ud(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:hd},numbers:{type:"number",properties:dd}}),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 fd(s){s.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}function pd(s,t){t=t||{};let e=s+JSON.stringify(t),n=Cr.get(e);return n||(n=new Intl.NumberFormat(s,t),Cr.set(e,n)),n}function ss(s,t,e){return pd(t,e).format(s)}function gd(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 md(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:ns.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 Ts(s,t){if(!t)return s;let e=t.split(".");for(let n=0,i=e.length;nn&&(n=o),n}function $r(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 Xt(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,vd(s,o),l=0;lQ(s[r],s[t[r]]):r=>s[r]:()=>s;for(let r of i)e[r]=wd(o(r));return e}function Ni(s){return Ln(s,{top:"y",right:"x",bottom:"y",left:"x"})}function ye(s){return Ln(s,["topLeft","topRight","bottomLeft","bottomRight"])}function Ct(s){let t=Ni(s);return t.width=t.left+t.right,t.height=t.top+t.bottom,t}function bt(s,t){s=s||{},t=t||ht.font;let e=Q(s.size,t.size);typeof e=="string"&&(e=parseInt(e,10));let n=Q(s.style,t.style);n&&!(""+n).match(Cd)&&(console.warn('Invalid font style specified: "'+n+'"'),n=void 0);let i={family:Q(s.family,t.family),lineHeight:Sd(Q(s.lineHeight,t.lineHeight),e),size:e,style:n,weight:Q(s.weight,t.weight),string:""};return i.string=bd(i),i}function os(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 le(s,t){return Object.assign(Object.create(s),t)}function An(s,t=[""],e,n,i=()=>s[0]){let o=e||s;typeof n=="undefined"&&(n=Gr("_fallback",s));let r={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:s,_rootScopes:o,_fallback:n,_getTarget:i,override:a=>An([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 Kr(a,l,()=>Pd(l,t,s,a))},getOwnPropertyDescriptor(a,l){return Reflect.getOwnPropertyDescriptor(a._scopes[0],l)},getPrototypeOf(){return Reflect.getPrototypeOf(s[0])},has(a,l){return wr(a).includes(l)},ownKeys(a){return wr(a)},set(a,l,c){let d=a._storage||(a._storage=i());return a[l]=d[l]=c,delete a._keys,!0}})}function Le(s,t,e,n){let i={_cacheable:!1,_proxy:s,_context:t,_subProxy:e,_stack:new Set,_descriptors:Bi(s,n),setContext:o=>Le(s,o,e,n),override:o=>Le(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 Kr(o,r,()=>kd(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 Bi(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:oe(e)?e:()=>e,isIndexable:oe(n)?n:()=>n}}function Kr(s,t,e){if(Object.prototype.hasOwnProperty.call(s,t)||t==="constructor")return s[t];let n=e();return s[t]=n,n}function kd(s,t,e){let{_proxy:n,_context:i,_subProxy:o,_descriptors:r}=s,a=n[t];return oe(a)&&r.isScriptable(t)&&(a=Md(t,a,s,e)),ct(a)&&a.length&&(a=Dd(t,a,s,r.isIndexable)),zi(t,a)&&(a=Le(a,i,o&&o[t],r)),a}function Md(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),zi(s,l)&&(l=Hi(i._scopes,i,s,l)),l}function Dd(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=Hi(c,i,s,d);t.push(Le(h,o,r&&r[s],a))}}return t}function Yr(s,t,e){return oe(s)?s(t,e):s}function Ld(s,t,e,n,i){for(let o of t){let r=Td(e,o);if(r){s.add(r);let a=Yr(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 Hi(s,t,e,n){let i=t._rootScopes,o=Yr(t._fallback,e,n),r=[...s,...i],a=new Set;a.add(n);let l=Sr(a,r,e,o||e,n);return l===null||typeof o!="undefined"&&o!==e&&(l=Sr(a,r,o,l,n),l===null)?!1:An(Array.from(a),[""],i,o,()=>Ad(t,e,n))}function Sr(s,t,e,n,i){for(;e;)e=Ld(s,t,e,n,i);return e}function Ad(s,t,e){let n=s._getTarget();t in n||(n[t]={});let i=n[t];return ct(i)&&et(e)?e:i||{}}function Pd(s,t,e,n){let i;for(let o of t)if(i=Gr(Ed(o,s),e),typeof i!="undefined")return zi(s,i)?Hi(e,n,s,i):i}function Gr(s,t){for(let e of t){if(!e)continue;let n=e[s];if(typeof n!="undefined")return n}}function wr(s){let t=s._keys;return t||(t=s._keys=Rd(s._scopes)),t}function Rd(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 $i(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")Nd(s,i);else{let c=n?s[s.length-1]:s[0];for(o=0,r=s.length;ol.height&&(d=l.height,c=ge(Math.floor(d*n))),{width:c,height:d}}function Wi(s,t,e){let n=t||1,i=ge(s.height*n),o=ge(s.width*n);s.height=ge(s.height),s.width=ge(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 ji(s,t){let e=zd(s,t),n=e&&e.match(/^(\d+)(\.\d+)?px$/);return n?+n[1]:void 0}function pe(s,t,e,n){return{x:s.x+e*(t.x-s.x),y:s.y+e*(t.y-s.y)}}function Jr(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 ta(s,t,e,n){let i={x:s.cp2x,y:s.cp2y},o={x:t.cp1x,y:t.cp1y},r=pe(s,i,e),a=pe(i,o,e),l=pe(o,t,e),c=pe(r,a,e),d=pe(a,l,e);return pe(c,d,e)}function Pe(s,t,e){return s?Ud(t,e):Kd()}function Ui(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 Ki(s,t){t!==void 0&&(delete s.prevTextDirection,s.canvas.style.setProperty("direction",t[0],t[1]))}function ea(s){return s==="angle"?{between:es,compare:cd,normalize:xt}:{between:Zt,compare:(t,e)=>t-e,normalize:t=>t}}function Er({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 Yd(s,t,e){let{property:n,start:i,end:o}=e,{between:r,normalize:a}=ea(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,_,b)&&a(i,_)!==0,w=()=>a(o,b)===0||l(o,_,b),v=()=>m||E(),y=()=>!m||w();for(let S=d,D=d;S<=h;++S)x=t[S%r],!x.skip&&(b=c(x[n]),b!==_&&(m=l(b,i,o),g===null&&v()&&(g=a(b,i)===0?S:D),g!==null&&y()&&(p.push(Er({start:g,end:S,loop:u,count:r,style:f})),g=null),D=S,_=b));return g!==null&&p.push(Er({start:g,end:h,loop:u,count:r,style:f})),p}function Gi(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 qd(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 sa(s,t){let e=s.points,n=s.options.spanGaps,i=e.length;if(!i)return[];let o=!!s._loop,{start:r,end:a}=Gd(e,i,o,n);if(n===!0)return kr(s,[{start:r,end:a,loop:o}],e,t);let l=a{br();Dr=(()=>{let s=0;return()=>s++})();Tr=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100:+s/t,Ci=(s,t)=>typeof s=="string"&&s.endsWith("%")?parseFloat(s)/100*t:+s;vr={"":s=>s,x:s=>s.x,y:s=>s.y};Je=s=>typeof s!="undefined",oe=s=>typeof s=="function",Si=(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,dt=2*nt,rd=dt+nt,_n=Number.POSITIVE_INFINITY,ad=nt/180,mt=nt/2,De=nt/4,yr=nt*2/3,re=Math.log10,Wt=Math.sign;qt=(s,t,e,n)=>kn(s,e,n?i=>{let o=s[i][t];return os[i][t]kn(s,e,n=>s[n][t]>=e);Vr=["push","pop","shift","splice","unshift"];Li=function(){return typeof window=="undefined"?function(s){return s()}:window.requestAnimationFrame}();Mn=s=>s==="start"?"left":s==="end"?"right":"center",_t=(s,t,e)=>s==="start"?t:s==="end"?e:(t+e)/2,zr=(s,t,e,n)=>s===(n?"left":"right")?e:s==="center"?(t+e)/2:t;bn=s=>s===0||s===1,xr=(s,t,e)=>-(Math.pow(2,10*(s-=1))*Math.sin((s-t)*dt/e)),_r=(s,t,e)=>Math.pow(2,-10*s)*Math.sin((s-t)*dt/e)+1,qe={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=>bn(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=>bn(s)?s:xr(s,.075,.3),easeOutElastic:s=>bn(s)?s:_r(s,.075,.3),easeInOutElastic(s){return bn(s)?s:s<.5?.5*xr(s*2,.1125,.45):.5+.5*_r(s*2-1,.1125,.45)},easeInBack(s){return s*s*((1.70158+1)*s-1.70158)},easeOutBack(s){return(s-=1)*s*((1.70158+1)*s+1.70158)+1},easeInOutBack(s){let t=1.70158;return(s/=.5)<1?.5*(s*s*(((t*=1.525)+1)*s-t)):.5*((s-=2)*s*(((t*=1.525)+1)*s+t)+2)},easeInBounce:s=>1-qe.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?qe.easeInBounce(s*2)*.5:qe.easeOutBounce(s*2-1)*.5+.5};dd=["x","y","borderWidth","radius","tension"],hd=["color","borderColor","backgroundColor"];Cr=new Map;Hr={values(s){return ct(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=gd(s,e)}let r=re(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),ss(s,n,l)},logarithmic(s,t,e){if(s===0)return"0";let n=e[t].significand||s/Math.pow(10,Math.floor(re(s)));return[1,2,3,5,10,15].includes(n)||t>.8*e.length?Hr.numeric.call(this,s,t,e):""}};ns={formatters:Hr};me=Object.create(null),Dn=Object.create(null);_i=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)=>yi(i.backgroundColor),this.hoverBorderColor=(n,i)=>yi(i.borderColor),this.hoverColor=(n,i)=>yi(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 xi(this,t,e)}get(t){return Ts(this,t)}describe(t,e){return xi(Dn,t,e)}override(t,e){return xi(me,t,e)}route(t,e,n,i){let o=Ts(this,t),r=Ts(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):Q(l,c)},set(l){this[a]=l}}})}apply(t){t.forEach(e=>e(this))}},ht=new _i({_scriptable:s=>!s.startsWith("on"),_indexable:s=>s!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[ud,fd,md]);_d=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,Cd=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;wd=s=>+s||0;Ed=(s,t)=>s?s+wn(t):t,zi=(s,t)=>et(t)&&s!=="adapters"&&(Object.getPrototypeOf(t)===null||t.constructor===Object);Td=(s,t)=>s===!0?t:typeof s=="string"?ae(t,s):void 0;Od=Number.EPSILON||1e-14,Qe=(s,t)=>ts==="x"?"y":"x";On=s=>s.ownerDocument.defaultView.getComputedStyle(s,null);Hd=["top","right","bottom","left"];$d=(s,t,e)=>(s>0||t>0)&&(!e||!e.shadowRoot);ge=s=>Math.round(s*10)/10;Zr=function(){let s=!1;try{let t={get passive(){return s=!0,!1}};Pn()&&(window.addEventListener("test",null,t),window.removeEventListener("test",null,t))}catch(t){}return s}();Ud=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}}},Kd=function(){return{x(s){return s},setWidth(s){},textAlign(s){return s},xPlus(s,t){return s+t},leftForLtr(s,t){return s}}}});var Vl={};So(Vl,{Animation:()=>Wn,Animations:()=>$s,ArcElement:()=>_e,BarController:()=>Fe,BarElement:()=>He,BasePlatform:()=>Ws,BasicPlatform:()=>jn,BubbleController:()=>Ie,CategoryScale:()=>cs,Chart:()=>ee,Colors:()=>Sl,DatasetController:()=>Tt,Decimation:()=>El,DomPlatform:()=>Kn,DoughnutController:()=>se,Element:()=>At,Filler:()=>Ml,Interaction:()=>al,Legend:()=>Tl,LineController:()=>Ve,LineElement:()=>Ut,LinearScale:()=>ds,LogarithmicScale:()=>hs,PieController:()=>as,PointElement:()=>ze,PolarAreaController:()=>Se,RadarController:()=>Ne,RadialLinearScale:()=>Ce,Scale:()=>ke,ScatterController:()=>Be,SubTitle:()=>Al,Ticks:()=>ns,TimeScale:()=>Ee,TimeSeriesScale:()=>us,Title:()=>Ll,Tooltip:()=>Rl,_adapters:()=>rl,_detectPlatform:()=>ul,animator:()=>te,controllers:()=>ol,defaults:()=>ht,elements:()=>xl,layouts:()=>St,plugins:()=>Ol,registerables:()=>Jf,registry:()=>jt,scales:()=>Il});function th(s,t){let e=[],n=Object.keys(t);for(let i=0;i0||!e&&o<0)return i.index}return null}function la(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=oh(o,r,n),h=t.length,u;for(let f=0;fe[n].axis===t).shift()}function lh(s,t){return le(s,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function ch(s,t,e){return le(s,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:e,index:t,mode:"default",type:"data"})}function Os(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 hh(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 uh(s){let t=s.iScale,e=hh(t,s.type),n=t._length,i,o,r,a,l=()=>{r===32767||r===-32768||(Je(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 il(s,t,e,n){return ct(s)?gh(s,t,e,n):t[e.axis]=e.parse(s,n),t}function da(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 bh(s){let t,e,n,i,o;return s.horizontal?(t=s.base>s.x,e="left",n="right"):(t=s.basees(_,a,l,!0)?1:Math.max(E,E*e,w,w*e),p=(_,E,w)=>es(_,a,l,!0)?-1:Math.min(E,E*e,w,w*e),m=f(0,c,h),g=f(mt,d,u),b=p(nt,c,h),x=p(nt+mt,d,u);n=(m-b)/2,i=(g-x)/2,o=-(m+b)/2,r=-(g+x)/2}return{ratioX:n,ratioY:i,offsetX:o,offsetY:r}}function Re(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}function Ch(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?Fr: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(m=>!tt(m[h.axis]));d.lo-=Math.max(0,f);let p=u.slice(d.hi).findIndex(m=>!tt(m[h.axis]));d.hi+=Math.max(0,p)}return d}}return{lo:0,hi:o.length-1}}function Ys(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 Fs(s,t){return s.filter(e=>e.pos===t)}function pa(s,t){return s.filter(e=>ll.indexOf(e.pos)===-1&&e.box.axis===t)}function Is(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 kh(s){let t=[],e,n,i,o,r,a;for(e=0,n=(s||[]).length;ec.box.fullSize),!0),n=Is(Fs(t,"left"),!0),i=Is(Fs(t,"right")),o=Is(Fs(t,"top"),!0),r=Is(Fs(t,"bottom")),a=pa(t,"x"),l=pa(t,"y");return{fullSize:e,leftAndTop:n.concat(o),rightAndBottom:i.concat(l).concat(r).concat(a),chartArea:Fs(t,"chartArea"),vertical:n.concat(i).concat(l),horizontal:o.concat(r).concat(a)}}function ga(s,t,e,n){return Math.max(s[e],t[e])+Math.max(s[n],t[n])}function cl(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 Lh(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&&cl(r,o.getPadding());let a=Math.max(0,t.outerWidth-ga(r,s,"left","right")),l=Math.max(0,t.outerHeight-ga(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 Ah(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 Ph(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 Bs(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||Un(a.addedNodes,n),r=r&&!Un(a.removedNodes,n);r&&e()});return i.observe(document,{childList:!0,subtree:!0}),i}function Bh(s,t,e){let n=s.canvas,i=new MutationObserver(o=>{let r=!1;for(let a of o)r=r||Un(a.removedNodes,n),r=r&&!Un(a.addedNodes,n);r&&e()});return i.observe(document,{childList:!0,subtree:!0}),i}function hl(){let s=window.devicePixelRatio;s!==va&&(va=s,js.forEach((t,e)=>{e.currentDevicePixelRatio!==s&&t()}))}function zh(s,t){js.size||window.addEventListener("resize",hl),js.set(s,t)}function Hh(s){js.delete(s),js.size||window.removeEventListener("resize",hl)}function $h(s,t,e){let n=s.canvas,i=n&&Rn(n);if(!i)return;let o=Ai((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),zh(s,o),r}function so(s,t,e){e&&e.disconnect(),t==="resize"&&Hh(s)}function Wh(s,t,e){let n=s.canvas,i=Ai(o=>{s.ctx!==null&&e(Vh(o,s))},s);return Fh(n,t,i),i}function ul(s){return!Pn()||typeof OffscreenCanvas!="undefined"&&s instanceof OffscreenCanvas?jn:Kn}function jh(s,t){let e=s.options.ticks,n=Uh(s),i=Math.min(e.maxTicksLimit||n,n),o=e.major.enabled?Yh(t):[],r=o.length,a=o[0],l=o[r-1],c=[];if(r>i)return Gh(t,c,o,r/i),c;let d=Kh(o,t,i);if(r>0){let h,u,f=r>1?Math.round((l-a)/(r-1)):null;for(In(t,c,d,tt(f)?0:a-f,a),h=0,u=r-1;hi)return l}return Math.max(i,1)}function Yh(s){let t=[],e,n;for(e=0,n=s.length;er+a)))return l}function Zh(s,t){ot(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(".");ht.route(o,i,l,a)})}function ou(s){return"id"in s&&"defaults"in s}function ru(s){let t={},e=[],n=Object.keys(jt.plugins.items);for(let o=0;o1&&Sa(s[0].toLowerCase());if(n)return n}throw new Error(`Cannot determine type of '${s}' axis. Please provide 'axis' or 'position' option.`)}function wa(s,t,e){if(e[t+"AxisID"]===s)return{axis:t}}function fu(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 wa(s,"x",e[0])||wa(s,"y",e[0])}return{}}function pu(s,t){let e=me[s.type]||{scales:{}},n=t.scales||{},i=uo(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=fo(r,a,fu(r,s),ht.scales[a.type]),c=hu(l,i),d=e.scales||{};o[r]=Ze(Object.create(null),[{axis:l},a,d[l],d[c]])}),s.data.datasets.forEach(r=>{let a=r.type||s.type,l=r.indexAxis||uo(a,t),d=(me[a]||{}).scales||{};Object.keys(d).forEach(h=>{let u=du(h,l),f=r[u+"AxisID"]||u;o[f]=o[f]||Object.create(null),Ze(o[f],[{axis:u},n[f],d[h]])})}),Object.keys(o).forEach(r=>{let a=o[r];Ze(a,[ht.scales[a.type],ht.scale])}),o}function fl(s){let t=s.options||(s.options={});t.plugins=Q(t.plugins,{}),t.scales=pu(s,t)}function pl(s){return s=s||{},s.datasets=s.datasets||[],s.labels=s.labels||[],s}function gu(s){return s=s||{},s.data=pl(s.data),fl(s),s}function Vn(s,t){let e=Ea.get(s);return e||(e=t(),Ea.set(s,e),gl.add(e)),e}function ka(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:An(t,e),subPrefixes:e.filter(a=>!a.toLowerCase().includes("hover"))},n.set(i,o)),o}function bu(s,t){let{isScriptable:e,isIndexable:n}=Bi(s);for(let i of t){let o=e(i),r=n(i),a=(r||o)&&s[i];if(o&&(oe(a)||mu(a))||r&&ct(a))return!0}return!1}function Ma(s,t){return s==="top"||s==="bottom"||yu.indexOf(s)===-1&&t==="x"}function Da(s,t){return function(e,n){return e[s]===n[s]?e[t]-n[t]:e[s]-n[s]}}function Ta(s){let t=s.chart,e=t.options.animation;t.notifyPlugins("afterRender"),lt(e&&e.onComplete,[s],t)}function xu(s){let t=s.chart,e=t.options.animation;lt(e&&e.onProgress,[s],t)}function ml(s){return Pn()&&typeof s=="string"?s=document.getElementById(s):s&&s.length&&(s=s[0]),s&&s.canvas&&(s=s.canvas),s}function _u(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 Cu(s,t,e,n){return!e||s.type==="mouseout"?null:n?t:s}function Aa(){return ot(ee.instances,s=>s._plugins.invalidate())}function Su(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,m=-f*Math.sin(e+nt/2)+o,g=f*Math.cos(n+nt/2)+i,b=f*Math.sin(n+nt/2)+o;s.lineTo(p,m),s.lineTo(g,b)}}s.closePath(),s.moveTo(0,0),s.rect(0,0,s.canvas.width,s.canvas.height),s.clip("evenodd")}function wu(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 Eu(s){return Ln(s,["outerStart","outerEnd","innerStart","innerEnd"])}function ku(s,t,e,n){let i=Eu(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 rs(s,t,e,n){return{x:e+s*Math.cos(t),y:n+s*Math.sin(t)}}function Yn(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,O=h>0?h-n:0,z=(P+O)/2,G=z!==0?p*z/(z+n):p;f=(p-G)/2}let m=Math.max(.001,p*h-e/nt)/h,g=(p-m)/2,b=l+g+f,x=i-g-f,{outerStart:_,outerEnd:E,innerStart:w,innerEnd:v}=ku(t,u,h,x-b),y=h-_,S=h-E,D=b+_/y,M=x-E/S,C=u+w,T=u+v,k=b+w/C,A=x-v/T;if(s.beginPath(),o){let P=(D+M)/2;if(s.arc(r,a,h,D,P),s.arc(r,a,h,P,M),E>0){let $=rs(S,M,r,a);s.arc($.x,$.y,E,M,x+mt)}let O=rs(T,x,r,a);if(s.lineTo(O.x,O.y),v>0){let $=rs(T,A,r,a);s.arc($.x,$.y,v,x+mt,A+Math.PI)}let z=(x-v/u+(b+w/u))/2;if(s.arc(r,a,u,x-v/u,z,!0),s.arc(r,a,u,z,b+w/u,!0),w>0){let $=rs(C,k,r,a);s.arc($.x,$.y,w,k+Math.PI,b-mt)}let G=rs(y,b,r,a);if(s.lineTo(G.x,G.y),_>0){let $=rs(y,D,r,a);s.arc($.x,$.y,_,b-mt,D)}}else{s.moveTo(r,a);let P=Math.cos(D)*h+r,O=Math.sin(D)*h+a;s.lineTo(P,O);let z=Math.cos(M)*h+r,G=Math.sin(M)*h+a;s.lineTo(z,G)}s.closePath()}function Mu(s,t,e,n,i){let{fullCircles:o,startAngle:r,circumference:a}=t,l=t.endAngle;if(o){Yn(s,t,e,n,l,i);for(let c=0;c=nt&&f===0&&d!=="miter"&&Su(s,t,m),o||(Yn(s,t,e,n,m,i),s.stroke())}function bl(s,t,e=t){s.lineCap=Q(e.borderCapStyle,t.borderCapStyle),s.setLineDash(Q(e.borderDash,t.borderDash)),s.lineDashOffset=Q(e.borderDashOffset,t.borderDashOffset),s.lineJoin=Q(e.borderJoinStyle,t.borderJoinStyle),s.lineWidth=Q(e.borderWidth,t.borderWidth),s.strokeStyle=Q(e.borderColor,t.borderColor)}function Tu(s,t,e){s.lineTo(e.x,e.y)}function Lu(s){return s.stepped?Wr:s.tension||s.cubicInterpolationMode==="monotone"?jr:Tu}function vl(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,_=()=>{m!==g&&(s.lineTo(d,g),s.lineTo(d,m),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,w=f.y,v=E|0;v===p?(wg&&(g=w),d=(h*d+E)/++h):(_(),s.lineTo(E,w),p=v,h=0,m=g=w),b=w}_()}function go(s){let t=s.options,e=t.borderDash&&t.borderDash.length;return!s._decimated&&!s._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!e?Pu:Au}function Ru(s){return s.stepped?Jr:s.tension||s.cubicInterpolationMode==="monotone"?ta:pe}function Ou(s,t,e,n){let i=t._path;i||(i=t._path=new Path2D,t.path(i,e,n)&&i.closePath()),bl(s,t.options),s.stroke(i)}function Fu(s,t,e,n){let{segments:i,options:o}=t,r=go(t);for(let a of i)bl(s,o,a.style),s.beginPath(),r(s,t,a,{start:e,end:e+n-1})&&s.closePath(),s.stroke()}function Vu(s,t,e,n){Iu&&!t.options.segment?Ou(s,t,e,n):Fu(s,t,e,n)}function Pa(s,t,e,n){let i=s.options,{[e]:o}=s.getProps([e],n);return Math.abs(t-o)_l(t++)),t}function Uu(s,t){return s.backgroundColor=s.data.map(()=>Cl(t++)),t}function Ku(s){let t=0;return(e,n)=>{let i=s.getDatasetMeta(n).controller;i instanceof se?t=ju(e,t):i instanceof Se?t=Uu(e,t):i&&(t=Wu(e,t))}}function Oa(s){let t;for(t in s)if(s[t].borderColor||s[t].backgroundColor)return!0;return!1}function Yu(s){return s&&(s.borderColor||s.backgroundColor)}function Gu(){return ht.borderColor!=="rgba(0,0,0,0.1)"||ht.backgroundColor!=="rgba(0,0,0,0.1)"}function qu(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,m;for(r[l++]=s[d],h=0;hf&&(f=p,u=s[x],m=x);r[l++]=u,d=m}return r[l++]=s[c],r}function Xu(s,t,e,n){let i=0,o=0,r,a,l,c,d,h,u,f,p,m,g=[],b=t+e-1,x=s[t].x,E=s[b].x-x;for(r=t;rm&&(m=c,u=r),i=(o*i+a.x)/++o;else{let v=r-1;if(!tt(h)&&!tt(u)){let y=Math.min(h,u),S=Math.max(h,u);y!==f&&y!==v&&g.push({...s[y],x:i}),S!==f&&S!==v&&g.push({...s[S],x:i})}r>0&&v!==f&&g.push(s[v]),g.push(a),d=w,o=0,p=m=c,h=u=f=r}}return g}function wl(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 Fa(s){s.data.datasets.forEach(t=>{wl(t)})}function Qu(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 Zu(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=Xn(l,c,i);let d=bo(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=Gi(t,d);for(let u of h){let f=bo(e,o[u.start],o[u.end],u.loop),p=Yi(a,i,f);for(let m of p)r.push({source:m,target:u,start:{[e]:Ia(d,f,"start",Math.max)},end:{[e]:Ia(d,f,"end",Math.min)}})}}return r}function bo(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 Ju(s,t){let{x:e=null,y:n=null}=s||{},i=t.points,o=[];return t.segments.forEach(({start:r,end:a})=>{a=Xn(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 Xn(s,t,e){for(;t>s;t--){let n=e[t];if(!isNaN(n.x)&&!isNaN(n.y))break}return t}function Ia(s,t,e,n){return s&&t?n(s[e],t[e]):s?s[e]:t?t[e]:0}function kl(s,t){let e=[],n=!1;return ct(s)?(n=!0,e=s):e=Ju(s,t),e.length?new Ut({points:e,options:{tension:0},_loop:n,_fullLoop:n}):null}function Va(s){return s&&s.fill!==!1}function tf(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 ef(s,t,e){let n=rf(s);if(et(n))return isNaN(n.value)?!1:n;let i=parseFloat(n);return pt(i)&&Math.floor(i)===i?sf(n[0],t,i,e):["origin","start","end","stack","shape"].indexOf(n)>=0&&n}function sf(s,t,e,n){return(s==="-"||s==="+")&&(e=t+e),e===t||e<0||e>=n?!1:e}function nf(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 of(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 rf(s){let t=s.options,e=t.fill,n=Q(e&&e.target,e);return n===void 0&&(n=!!t.backgroundColor),n===!1||n===null?!1:n===!0?"origin":n}function af(s){let{scale:t,index:e,line:n}=s,i=[],o=n.segments,r=n.points,a=lf(t,e);a.push(kl({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 _f(s,t,e){let n=s;return typeof t.text!="string"&&(n=Dl(t,e)),n}function Dl(s,t){let e=s.text?s.text.length:0;return t*e}function Cf(s,t){return!!((s==="mousemove"||s==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(s==="click"||s==="mouseup"))}function Sf(s,t){let e=new Us({ctx:s.ctx,options:t,chart:s});St.configure(s,e,t),St.addBox(s,e),s.titleBlock=e}function Jt(s,t){return t&&(ct(t)?Array.prototype.push.apply(s,t):s.push(t)),s}function ce(s){return(typeof s=="string"||s instanceof String)&&s.indexOf(` `)>-1?s.split(` -`):s}function pf(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 Fa(s,t){let e=s.chart.ctx,{body:n,footer:i,title:o}=s,{boxWidth:r,boxHeight:a}=t,l=ft(t.bodyFont),c=ft(t.titleFont),d=ft(t.footerFont),h=o.length,u=i.length,f=n.length,p=vt(t.padding),g=p.height,b=0,y=n.reduce((M,E)=>M+E.before.length+E.lines.length+E.after.length,0);if(y+=s.beforeBody.length+s.afterBody.length,h&&(g+=h*c.lineHeight+(h-1)*t.titleSpacing+t.titleMarginBottom),y){let M=t.displayColors?Math.max(a,l.lineHeight):l.lineHeight;g+=f*M+(y-f)*l.lineHeight+(y-1)*t.bodySpacing}u&&(g+=t.footerMarginTop+u*d.lineHeight+(u-1)*t.footerSpacing);let x=0,S=function(M){b=Math.max(b,e.measureText(M).width+x)};return e.save(),e.font=c.string,nt(s.title,S),e.font=l.string,nt(s.beforeBody.concat(s.afterBody),S),x=t.displayColors?r+2+t.boxPadding:0,nt(n,M=>{nt(M.before,S),nt(M.lines,S),nt(M.after,S)}),x=0,e.font=d.string,nt(s.footer,S),e.restore(),b+=p.width,{width:b,height:g}}function gf(s,t){let{y:e,height:n}=t;return es.height-n/2?"bottom":"center"}function mf(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 bf(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"),mf(c,s,t,e)&&(c="center"),c}function Va(s,t,e){let n=e.yAlign||t.yAlign||gf(s,e);return{xAlign:e.xAlign||t.xAlign||bf(s,t,e,n),yAlign:n}}function yf(s,t){let{x:e,width:n}=s;return t==="right"?e-=n:t==="center"&&(e-=n/2),e}function vf(s,t,e){let{y:n,height:i}=s;return t==="top"?n+=e:t==="bottom"?n-=i+e:n-=i/2,n}function Na(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}=me(r),p=yf(t,a),g=vf(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:pt(p,0,n.width-t.width),y:pt(g,0,n.height-t.height)}}function Tn(s,t,e){let n=vt(e.padding);return t==="center"?s.x+s.width/2:t==="right"?s.x+s.width-n.right:s.x+n.left}function Ba(s){return Gt([],oe(s))}function xf(s,t,e){return ie(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 wt(s,t,e,n){let i=s[t].call(e,n);return typeof i=="undefined"?wl[t].call(e,n):i}function Cf(s,t,e,n){let i=s.indexOf(t);if(i===-1)return _f(s,t,e,n);let o=s.lastIndexOf(t);return i!==o?e:i}function Ha(s){let t=this.getLabels();return s>=0&&sp&&(E=gi(k*E/p/f)*f),Z(l)||(v=Math.pow(10,l),E=Math.ceil(E*v)/v),i==="ticks"?(m=Math.floor(g/E)*E,C=Math.ceil(b/E)*E):(m=g,C=b),y&&x&&o&&Mr((a-r)/o,E/1e3)?(k=Math.round(Math.min((a-r)/E,d)),E=(a-r)/k,m=r,C=a):S?(m=y?r:m,C=x?a:C,k=c-1,E=(C-m)/k):(k=(C-m)/E,qe(k,Math.round(k),E/1e3)?k=Math.round(k):k=Math.ceil(k));let w=Math.max(bi(E),bi(m));v=Math.pow(10,Z(l)?w:l),m=Math.round(m*v)/v,C=Math.round(C*v)/v;let _=0;for(y&&(u&&m!==r?(e.push({value:r}),ma)break;e.push({value:D})}return x&&u&&C!==a?e.length&&qe(e[e.length-1].value,a,$a(a,M,s))?e[e.length-1].value=a:e.push({value:a}):(!x||C===a)&&e.push({value:C}),e}function $a(s,t,{horizontal:e,minRotation:n}){let i=Rt(n),o=(e?Math.sin(i):Math.cos(i))||.001,r=.75*t*(""+s).length;return Math.min(t/o,r)}function Wa(s){return s/Math.pow(10,Bs(s))===1}function ja(s,t,e){let n=Math.pow(10,e),i=Math.floor(s/n);return Math.ceil(t/n)-i}function kf(s,t){let e=t-s,n=Bs(e);for(;ja(s,t,n)>10;)n++;for(;ja(s,t,n)<10;)n--;return Math.min(n,Bs(s))}function wf(s,{min:t,max:e}){t=kt(s.min,t);let n=[],i=Bs(t),o=kf(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=kt(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=kt(s.max,u);return n.push({value:f,major:Wa(f),significand:h}),n}function lo(s){let t=s.ticks;if(t.display&&s.display){let e=vt(t.backdropPadding);return q(t.font&&t.font.size,ct.font.size)+e.height}return 0}function Mf(s,t,e){return e=at(e)?e:[e],{w:Fr(s,t.string,e),h:e.length*t.lineHeight}}function Ua(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 Df(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?et/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 Lf(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(gn(bt(l.angle+ut))),d=If(l.y,a.h,c),h=Rf(c),u=Of(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 Af(s,t){if(!t)return!0;let{left:e,top:n,right:i,bottom:o}=s;return!(Ut({x:e,y:n},t)||Ut({x:e,y:o},t)||Ut({x:i,y:n},t)||Ut({x:i,y:o},t))}function Pf(s,t,e){let n=[],i=s._pointLabels.length,o=s.options,{centerPointLabels:r,display:a}=o.pointLabels,l={extra:lo(o)/2,additionalAngle:r?et/i:0},c;for(let d=0;d270||e<90)&&(s-=t),s}function Ff(s,t,e){let{left:n,top:i,right:o,bottom:r}=e,{backdropColor:a}=t;if(!Z(a)){let l=me(t.borderRadius),c=vt(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(),Je(s,{x:d,y:h,w:u,h:f,radius:l}),s.fill()):s.fillRect(d,h,u,f)}}function Vf(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));Ff(e,r,o);let a=ft(r.font),{x:l,y:c,textAlign:d}=o;ge(e,s._pointLabels[i],l,c+a.lineHeight/2,a,{color:r.color,textAlign:d,textBaseline:"middle"})}}function Tl(s,t,e,n){let{ctx:i}=s;if(e)i.arc(s.xCenter,s.yCenter,t,0,lt);else{let o=s.getPointPosition(0,t);i.moveTo(o.x,o.y);for(let r=1;r=Dt.indexOf(e);o--){let r=Dt[o];if(Hn[r].common&&s._adapter.diff(i,n,r)>=t-1)return r}return Dt[e?Dt.indexOf(e):0]}function Hf(s){for(let t=Dt.indexOf(s)+1,e=Dt.length;t=t?e[n]:e[i];s[o]=!0}}function $f(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 Xa(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}=jt(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}=jt(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 Zi,qt,Zr,Wd,Rn,Is,Wi,na,th,Mt,Re,Oe,Qt,Ie,xe,ss,Fe,Ve,Ja,Ji,tl,el,sl,xt,Fs,On,An,Sh,ha,il,Vs,ua,Fn,Tt,zh,fa,pa,Se,ns,to,Nt,eo,va,cl,As,io,ru,lu,cu,Pn,Ea,Xt,ye,wu,Bt,Ne,Be,pl,ro,Ma,bl,vl,Nn,_l,Ia,lf,Bn,Sl,Ns,El,Dn,kl,Rs,wl,Os,Ml,Dl,_f,Sf,is,ls,os,Bs,Pe,rs,ve,Hn,Dt,Ce,as,Ll,Wf,Pl=jn(()=>{Qr();Zi=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=_i.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)}},qt=new Zi,Zr="transparent",Wd={boolean(s,t,e){return e>.5?t:s},color(s,t,e){let n=wi(s||Zr),i=n.valid&&wi(t||Zr);return i&&i.valid?i.mix(n,e).hexString():t},number(s,t,e){return s+(t-s)*e}},Rn=class{constructor(t,e,n,i){let o=e[n];i=ts([t.to,i,o,t.from]);let r=ts([t.from,o,i]);this._active=!0,this._fn=t.fn||Wd[t.type||typeof r],this._easing=je[t.easing]||je.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=ts([t.to,e,i,t.from]),this._from=ts([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(!tt(o))return;let r={};for(let a of e)r[a]=o[a];(at(o.properties)&&o.properties||[i]).forEach(a=>{(a===i||!n.has(a))&&n.set(a,r)})})}_animateOptions(t,e){let n=e.options,i=Ud(t,n);if(!i)return[];let o=this._createAnimations(i,n);return n.$shared&&jd(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 Rn(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 qt.add(this._chart,n),!0}};Wi=s=>s==="reset"||s==="none",na=(s,t)=>t?s:Object.assign({},s),th=(s,t,e)=>s&&!t.hidden&&t._stacked&&{keys:Qa(e,!0),values:null},Mt=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=Hi(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&&Ms(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=q(n.xAxisID,$i(t,"x")),r=e.yAxisID=q(n.yAxisID,$i(t,"y")),a=e.rAxisID=q(n.rAxisID,$i(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&&vi(this._data,this),t._stacked&&Ms(t)}_dataCheck(){let t=this.getDataset(),e=t.data||(t.data=[]),n=this._data;if(tt(e)){let i=this._cachedMeta;this._data=Gd(e,i)}else if(n!==e){if(n){vi(n,this);let i=this._cachedMeta;Ms(i),i._parsed=[]}e&&Object.isExtensible(e)&&Pr(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=Hi(e.vScale,e),e.stack!==n.stack&&(i=!0,Ms(e),e.stack=n.stack),this._resyncElements(t),(i||o!==e._stacked)&&(sa(this,e._parsed),e._stacked=Hi(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{at(i[t])?u=this.parseArrayData(n,i,t,e):tt(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(na(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 Is(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||Wi(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){Wi(i)?Object.assign(t,n):this._resolveAnimations(e,i).update(t,n)}updateSharedOptions(t,e,n){t&&!Wi(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(Z(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[q(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(tt(n[t])){let{key:l="value"}=this._parsing;o=c=>+ne(n[c],l)}let r,a;for(r=t,a=t+e;r0&&!isNaN(t)?lt*(Math.abs(t)/e):0}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart,i=n.data.labels||[],o=Qe(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")}),z(Qt,"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()}}}});Ie=class extends Mt{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}=Si(e,i,r);this._drawStart=a,this._drawCount=l,Ei(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,b=Te(p)?p:Number.POSITIVE_INFINITY,y=this.chart._animationsDisabled||o||i==="none",x=e+n,S=t.length,M=e>0&&this.getParsed(e-1);for(let E=0;E=x){m.skip=!0;continue}let C=this.getParsed(E),k=Z(C[f]),w=m[u]=r.getPixelForValue(C[u],E),_=m[f]=o||k?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,C,l):C[f],E);m.skip=isNaN(w)||isNaN(_)||k,m.stop=E>0&&Math.abs(C[u]-M[u])>b,g&&(m.parsed=C,m.raw=c.data[E]),h&&(m.options=d||this.resolveDataElementOptions(E,v.active?"active":i)),y||this.updateElement(v,E,m,i),M=C}}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()}};z(Ie,"id","line"),z(Ie,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),z(Ie,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});xe=class extends Mt{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=Qe(e._parsed[t].r,n.options.locale);return{label:i[t]||"",value:o}}parseObjectData(t,e,n,i){return Ri.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*et,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)?Rt(this.resolveDataElementOptions(t,e).angle||n):0}};z(xe,"id","polarArea"),z(xe,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),z(xe,"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}}});ss=class extends Qt{};z(ss,"id","pie"),z(ss,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});Fe=class extends Mt{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 Ri.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 M=e;M0&&Math.abs(v[f]-S[f])>y,b&&(m.parsed=v,m.raw=c.data[M]),u&&(m.options=h||this.resolveDataElementOptions(M,E.active?"active":i)),x||this.updateElement(E,M,m,i),S=v}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}};z(Ve,"id","scatter"),z(Ve,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),z(Ve,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});Ja=Object.freeze({__proto__:null,BarController:Re,BubbleController:Oe,DoughnutController:Qt,LineController:Ie,PieController:ss,PolarAreaController:xe,RadarController:Fe,ScatterController:Ve});Ji=class s{constructor(t){z(this,"options");this.options=t||{}}static override(t){Object.assign(s.prototype,t)}init(){}formats(){return Ae()}parse(){return Ae()}format(){return Ae()}add(){return Ae()}diff(){return Ae()}startOf(){return Ae()}endOf(){return Ae()}},tl={_date:Ji};el={evaluateInteractionItems:zs,modes:{index(s,t,e,n){let i=be(t,s),o=e.axis||"x",r=e.includeInvisible||!1,a=e.intersect?Ui(s,i,o,n,r):Yi(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=be(t,s),o=e.axis||"xy",r=e.includeInvisible||!1,a=e.intersect?Ui(s,i,o,n,r):Yi(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,b)=>b.box.options&&b.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);nl(u,vt(n));let f=Object.assign({maxPadding:u,w:o,h:r,x:i.left,y:i.top},i),p=yh(l.concat(c),h);Ps(a.fullSize,f,h,p),Ps(l,f,h,p),Ps(c,f,h,p)&&Ps(l,f,h,p),_h(f),da(a.leftAndTop,f,h,p),f.x+=f.w,f.y+=f.h,da(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},nt(a.chartArea,g=>{let b=g.box;Object.assign(b,s.chartArea),b.update(f.w,f.h,{left:0,top:0,right:0,bottom:0})})}},Fs=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){}},On=class extends Fs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}},An="$chartjs",Sh={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},ha=s=>s===null||s==="";il=Yr?{passive:!0}:!1;Vs=new Map,ua=0;Fn=class extends Fs{acquireContext(t,e){let n=t&&t.getContext&&t.getContext("2d");return n&&n.canvas===t?(Eh(t,e),n):null}releaseContext(t){let e=t.canvas;if(!e[An])return!1;let n=e[An].initial;["height","width"].forEach(o=>{let r=n[o];Z(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[An],!0}addEventListener(t,e,n){this.removeEventListener(t,e);let i=t.$proxies||(t.$proxies={}),r={attach:Dh,detach:Th,resize:Ph}[e]||Rh;i[e]=r(t,e,n)}removeEventListener(t,e){let n=t.$proxies||(t.$proxies={}),i=n[e];if(!i)return;({attach:Ki,detach:Ki,resize:Ki}[e]||wh)(t,e,i),n[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,n,i){return Ur(t,e,n,i)}isAttached(t){let e=t&&Sn(t);return!!(e&&e.isConnected)}};Tt=class{constructor(){z(this,"x");z(this,"y");z(this,"active",!1);z(this,"options");z(this,"$animations")}tooltipPosition(t){let{x:e,y:n}=this.getProps(["x","y"],t);return{x:e,y:n}}hasValue(){return Te(this.x)&&Te(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}};z(Tt,"defaults",{}),z(Tt,"defaultRoutes");zh=s=>s==="left"?"right":s==="right"?"left":s,fa=(s,t,e)=>t==="top"||t==="left"?s[t]+e:s[t]-e,pa=(s,t)=>Math.min(t||s,s);Se=class s extends Tt{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=kt(t,Number.POSITIVE_INFINITY),e=kt(e,Number.NEGATIVE_INFINITY),n=kt(n,Number.POSITIVE_INFINITY),i=kt(i,Number.NEGATIVE_INFINITY),{min:kt(t,n),max:kt(e,i),minDefined:ht(t),maxDefined:ht(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:kt(e,kt(n,e)),max:kt(n,kt(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(){rt(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=Br(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=pt(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-Ls(t.grid)-e.padding-ma(t.title,this.chart.options.font),c=Math.sqrt(h*h+u*u),r=gn(Math.min(Math.asin(pt((d.highest.height+6)/a,-1,1)),Math.asin(pt(l/c,-1,1))-Math.asin(pt(u/c,-1,1)))),r=Math.max(i,Math.min(o,r))),this.labelRotation=r}afterCalculateLabelRotation(){rt(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){rt(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=Ls(o)+l):(t.height=this.maxHeight,t.width=Ls(o)+l),n.display&&this.ticks.length){let{first:c,last:d,widest:h,highest:u}=this._getLabelSizes(),f=n.padding*2,p=Rt(this.labelRotation),g=Math.cos(p),b=Math.sin(p);if(a){let y=n.mirror?0:b*h.width+g*u.height;t.height=Math.min(this.maxHeight,t.height+y+f)}else{let y=n.mirror?0:g*h.width+b*u.height;t.width=Math.min(this.maxWidth,t.width+y+f)}this._calculatePadding(c,d,b,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(){rt(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[k]||0,height:a[k]||0});return{first:C(0),last:C(e-1),widest:C(v),highest:C(m),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 Dr(this._alignToPixels?pe(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=Ls(o),f=[],p=a.setContext(this.getContext()),g=p.display?p.width:0,b=g/2,y=function(H){return pe(n,H,g)},x,S,M,E,v,m,C,k,w,_,D,T;if(r==="top")x=y(this.bottom),m=this.bottom-u,k=x-b,_=y(t.top)+b,T=t.bottom;else if(r==="bottom")x=y(this.top),_=t.top,T=y(t.bottom)-b,m=x+b,k=this.top+u;else if(r==="left")x=y(this.right),v=this.right-u,C=x-b,w=y(t.left)+b,D=t.right;else if(r==="right")x=y(this.left),w=t.left,D=y(t.right)-b,v=x+b,C=this.left+u;else if(e==="x"){if(r==="center")x=y((t.top+t.bottom)/2+.5);else if(tt(r)){let H=Object.keys(r)[0],B=r[H];x=y(this.chart.scales[H].getPixelForValue(B))}_=t.top,T=t.bottom,m=x+b,k=m+u}else if(e==="y"){if(r==="center")x=y((t.left+t.right)/2);else if(tt(r)){let H=Object.keys(r)[0],B=r[H];x=y(this.chart.scales[H].getPixelForValue(B))}v=x-b,C=v-u,w=t.left,D=t.right}let P=q(i.ticks.maxTicksLimit,h),R=Math.max(1,Math.ceil(h/P));for(S=0;S0&&(I-=U/2);break}A={left:I,top:F,width:U+V.width,height:$+V.height,color:R.backdropColor}}b.push({label:M,font:k,textOffset:D,options:{rotation:g,color:B,strokeColor:G,strokeWidth:W,textAlign:L,textBaseline:T,translation:[E,v],backdrop:A}})}return b}_getXAxisLabelAlignment(){let{position:t,ticks:e}=this.options;if(-Rt(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):nt(i,r=>{let a=n||this._getRegistryForType(r);this._exec(t,a,r)})})}_exec(t,e,n){let i=pn(t);rt(n["before"+i],[],n),e[t](n),rt(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")}};va=new Map,cl=new Set;As=(s,t,e)=>{let n=ne(t,e);n!==void 0&&s.add(n)},io=class{constructor(t){this._config=ou(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=ll(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(),al(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return Mn(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,e){return Mn(`${t}.transition.${e}`,()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,e){return Mn(`${t}-${e}`,()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]])}pluginScopeKeys(t){let e=t.id,n=this.type;return Mn(`${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=>As(l,t,h))),d.forEach(h=>As(l,i,h)),d.forEach(h=>As(l,fe[o]||{},h)),d.forEach(h=>As(l,ct,h)),d.forEach(h=>As(l,yn,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,fe[e]||{},ct.datasets[e]||{},{type:e},ct,yn]}resolveNamedOptions(t,e,n,i=[""]){let o={$shared:!0},{resolver:r,subPrefixes:a}=xa(this._resolverCache,t,i),l=r;if(au(r,e)){o.$shared=!1,n=ee(n)?n():n;let c=this.createResolver(t,n,a);l=De(r,n,c)}for(let c of e)o[c]=l[c];return o}createResolver(t,e,n=[""],i){let{resolver:o}=xa(this._resolverCache,t,n);return tt(e)?De(o,e,void 0,i):o}};ru=s=>tt(s)&&Object.getOwnPropertyNames(s).some(t=>ee(s[t]));lu="4.5.1",cu=["top","bottom","left","right","chartArea"];Pn={},Ea=s=>{let t=dl(s);return Object.values(Pn).filter(e=>e.canvas===t).pop()};Xt=class{static register(...t){Nt.add(...t),ka()}static unregister(...t){Nt.remove(...t),ka()}constructor(t,e){let n=this.config=new io(e),i=dl(t),o=Ea(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||rl(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=Cr(),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 eo,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=Rr(h=>this.update(h),r.resizeDelay||0),this._dataChanges=[],Pn[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}qt.listen(this,"complete",Sa),qt.listen(this,"progress",du),this._initialize(),this.attached&&this.update()}get aspectRatio(){let{options:{aspectRatio:t,maintainAspectRatio:e},width:n,height:i,_aspectRatio:o}=this;return Z(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 Nt}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():Oi(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Mi(this.canvas,this.ctx),this}stop(){return qt.stop(this),this}resize(t,e){qt.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,Oi(this,a,!0)&&(this.notifyPlugins("resize",{size:r}),rt(n.onResize,[this,r],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){let e=this.options.scales||{};nt(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=no(r,a),c=l==="r",d=l==="x";return{options:a,dposition:c?"chartArea":d?"bottom":"left",dtype:c?"radialLinear":d?"category":"linear"}}))),nt(o,r=>{let a=r.options,l=a.id,c=no(l,a),d=q(a.type,r.dtype);(a.position===void 0||_a(a.position,c)!==_a(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=Nt.getScale(d);h=new u({id:l,type:d,ctx:this.ctx,chart:this}),n[h.id]=h}h.init(a,t)}),nt(i,(r,a)=>{r||delete n[a]}),nt(n,r=>{xt.configure(this,r,r.options),xt.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(Ca("z","_idx"));let{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){nt(this.scales,t=>{xt.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){let t=this.options,e=new Set(Object.keys(this._listeners)),n=new Set(t.events);(!pi(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;hu(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;xt.update(this,this.width,this.height,t);let e=this.chartArea,n=e.width<=0||e.height<=0;this._layers=[],nt(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=zi(this,t);this.notifyPlugins("beforeDatasetDraw",n)!==!1&&(i&&ks(e,i),t.controller.draw(),i&&ws(e),n.cancelable=!1,this.notifyPlugins("afterDatasetDraw",n))}isPointInArea(t){return Ut(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,n,i){let o=el.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=ie(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);Ge(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(),qt.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)};nt(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(){nt(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},nt(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}});!Es(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=kr(t),c=uu(t,this._lastEvent,n,l);n&&(this._lastEvent=null,rt(o.onHover,[t,a,this],this),l&&rt(o.onClick,[t,a,this],this));let d=!Es(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)}};z(Xt,"defaults",ct),z(Xt,"instances",Pn),z(Xt,"overrides",fe),z(Xt,"registry",Nt),z(Xt,"version",lu),z(Xt,"getChart",Ea);ye=class extends Tt{constructor(e){super();z(this,"circumference");z(this,"endAngle");z(this,"fullCircles");z(this,"innerRadius");z(this,"outerRadius");z(this,"pixelMargin");z(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}=yi(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=q(u,c-l),g=Xe(r,l,c)&&l!==c,b=p>=lt||g,y=Kt(a,d+f,h+f);return b&&y}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>lt?Math.floor(i/lt):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(et,i||0)),d=o*c;e.fillStyle=n.backgroundColor,e.strokeStyle=n.borderColor,bu(e,this,d,r,a),yu(e,this,d,r,a),e.restore()}};z(ye,"id","arc"),z(ye,"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}),z(ye,"defaultRoutes",{backgroundColor:"backgroundColor"}),z(ye,"descriptors",{_scriptable:!0,_indexable:e=>e!=="borderDash"});wu=typeof Path2D=="function";Bt=class extends Tt{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;jr(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=Xr(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=Bi(this,{property:e,start:i,end:i});if(!r.length)return;let a=[],l=Su(n),c,d;for(c=0,d=r.length;ct!=="borderDash"&&t!=="fill"});Ne=class extends Tt{constructor(e){super();z(this,"parsed");z(this,"skip");z(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)"));bl={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=Da(n)||Vu(i)||o&&Da(o)||Nu();if(!e.forceOverride&&r)return;let a=Fu(s);n.forEach(a)}};vl={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(s,t,e)=>{if(!e.enabled){Ta(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(ts([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}=Hu(l,c),f=e.threshold||4*n;if(u<=f){yl(i);return}Z(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=Bu(c,h,u,n,e);break;case"min-max":p=zu(c,h,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${e.algorithm}'`)}i._decimated=p})},destroy(s){Ta(s)}};Nn=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:lt},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}}};_l={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&&Xi(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;Aa(o)&&Xi(s.ctx,o,s.chartArea)}},beforeDatasetDraw(s,t,e){let n=t.meta.$filler;!Aa(n)||e.drawTime!=="beforeDatasetDraw"||Xi(s.ctx,n,s.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}},Ia=(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)}},lf=(s,t)=>s!==null&&t!==null&&s.datasetIndex===t.datasetIndex&&s.index===t.index,Bn=class extends Tt{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=rt(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=ft(n.font),o=i.size,r=this._computeTitleHeight(),{boxWidth:a,itemHeight:l}=Ia(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 b=n+e/2+o.measureText(p.text).width;(g===0||c[c.length-1]+b+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:b,height:i},c[c.length-1]+=b+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((b,y)=>{let{itemWidth:x,itemHeight:S}=cf(n,e,o,b,i);y>0&&f+S+2*a>d&&(h+=u+a,c.push({width:u,height:f}),p+=u+a,g++,u=f=0),l[y]={left:p,top:f,col:g,width:x,height:S},u=Math.max(u,x),f+=S+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=Le(o,this.left,this.width);if(this.isHorizontal()){let a=0,l=yt(n,this.left+i,this.right-this.lineWidths[a]);for(let c of e)a!==c.row&&(a=c.row,l=yt(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=yt(n,this.top+t+i,this.bottom-this.columnSizes[a].height);for(let c of e)c.col!==a&&(a=c.col,l=yt(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;ks(t,this),this._draw(),ws(t)}}_draw(){let{options:t,columnSizes:e,lineWidths:n,ctx:i}=this,{align:o,labels:r}=t,a=ct.color,l=Le(t.rtl,this.left,this.width),c=ft(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:b}=Ia(r,h),y=function(v,m,C){if(isNaN(p)||p<=0||isNaN(g)||g<0)return;i.save();let k=q(C.lineWidth,1);if(i.fillStyle=q(C.fillStyle,a),i.lineCap=q(C.lineCap,"butt"),i.lineDashOffset=q(C.lineDashOffset,0),i.lineJoin=q(C.lineJoin,"miter"),i.lineWidth=k,i.strokeStyle=q(C.strokeStyle,a),i.setLineDash(q(C.lineDash,[])),r.usePointStyle){let w={radius:g*Math.SQRT2/2,pointStyle:C.pointStyle,rotation:C.rotation,borderWidth:k},_=l.xPlus(v,p/2),D=m+u;Di(i,w,_,D,r.pointStyleWidth&&p)}else{let w=m+Math.max((h-g)/2,0),_=l.leftForLtr(v,p),D=me(C.borderRadius);i.beginPath(),Object.values(D).some(T=>T!==0)?Je(i,{x:_,y:w,w:p,h:g,radius:D}):i.rect(_,w,p,g),i.fill(),k!==0&&i.stroke()}i.restore()},x=function(v,m,C){ge(i,C.text,v,m+b/2,c,{strikethrough:C.hidden,textAlign:l.textAlign(C.textAlign)})},S=this.isHorizontal(),M=this._computeTitleHeight();S?f={x:yt(o,this.left+d,this.right-n[0]),y:this.top+d+M,line:0}:f={x:this.left+d,y:yt(o,this.top+M+d,this.bottom-e[0].height),line:0},Fi(this.ctx,t.textDirection);let E=b+d;this.legendItems.forEach((v,m)=>{i.strokeStyle=v.fontColor,i.fillStyle=v.fontColor;let C=i.measureText(v.text).width,k=l.textAlign(v.textAlign||(v.textAlign=r.textAlign)),w=p+u+C,_=f.x,D=f.y;l.setWidth(this.width),S?m>0&&_+w+d>this.right&&(D=f.y+=E,f.line++,_=f.x=yt(o,this.left+d,this.right-n[f.line])):m>0&&D+E>this.bottom&&(_=f.x=_+e[f.line].width+d,f.line++,D=f.y=yt(o,this.top+M+d,this.bottom-e[f.line].height));let T=l.x(_);if(y(T,D,v),_=Or(k,_+p+u,S?_+w:this.right,t.rtl),x(l.x(_),D,v),S)f.x+=w+d;else if(typeof v.text!="string"){let P=c.lineHeight;f.y+=Cl(v,P)+d}else f.y+=E}),Vi(this.ctx,t.textDirection)}drawTitle(){let t=this.options,e=t.title,n=ft(e.font),i=vt(e.padding);if(!e.display)return;let o=Le(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=yt(t.align,h,this.right-u);else{let p=this.columnSizes.reduce((g,b)=>Math.max(g,b.height),0);d=c+yt(t.align,this.top,this.bottom-p-t.labels.padding-this._computeTitleHeight())}let f=yt(a,h,h+u);r.textAlign=o.textAlign(bn(a)),r.textBaseline="middle",r.strokeStyle=e.color,r.fillStyle=e.color,r.font=n.string,ge(r,e.text,f,d,n)}_computeTitleHeight(){let t=this.options.title,e=ft(t.font),n=vt(t.padding);return t.display?e.lineHeight+n.height:0}_getLegendItemAt(t,e){let n,i,o;if(Kt(t,this.left,this.right)&&Kt(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=vt(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)}}},Ns=class extends Tt{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=at(n.text)?n.text.length:1;this._padding=vt(n.padding);let o=i*ft(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=yt(a,n,o),h=e+t,c=o-n):(r.position==="left"?(d=n+t,h=yt(a,i,e),l=et*-.5):(d=o-t,h=yt(a,e,i),l=et*.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=ft(e.font),o=n.lineHeight/2+this._padding.top,{titleX:r,titleY:a,maxWidth:l,rotation:c}=this._drawArgs(o);ge(t,e.text,0,0,n,{color:e.color,maxWidth:l,rotation:c,textAlign:bn(e.align),textBaseline:"middle",translation:[r,a]})}};El={id:"title",_element:Ns,start(s,t,e){ff(s,e)},stop(s){let t=s.titleBlock;xt.removeBox(s,t),delete s.titleBlock},beforeUpdate(s,t,e){let n=s.titleBlock;xt.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}},Dn=new WeakMap,kl={id:"subtitle",start(s,t,e){let n=new Ns({ctx:s.ctx,options:e,chart:s});xt.configure(s,n,e),xt.addBox(s,n),Dn.set(s,n)},stop(s){xt.removeBox(s,Dn.get(s)),Dn.delete(s)},beforeUpdate(s,t,e){let n=Dn.get(s);xt.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}},Rs={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);Gt(r.before,oe(wt(a,"beforeLabel",this,o))),Gt(r.lines,wt(a,"label",this,o)),Gt(r.after,oe(wt(a,"afterLabel",this,o))),i.push(r)}),i}getAfterBody(t,e){return Ba(wt(e.callbacks,"afterBody",this,t))}getFooter(t,e){let{callbacks:n}=e,i=wt(n,"beforeFooter",this,t),o=wt(n,"footer",this,t),r=wt(n,"afterFooter",this,t),a=[];return a=Gt(a,oe(i)),a=Gt(a,oe(o)),a=Gt(a,oe(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))),nt(a,d=>{let h=za(t.callbacks,d);i.push(wt(h,"labelColor",this,d)),o.push(wt(h,"labelPointStyle",this,d)),r.push(wt(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=Rs[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=Fa(this,n),c=Object.assign({},a,l),d=Va(this.chart,n,c),h=Na(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}=me(a),{x:u,y:f}=t,{width:p,height:g}=e,b,y,x,S,M,E;return o==="center"?(M=f+g/2,i==="left"?(b=u,y=b-r,S=M+r,E=M-r):(b=u+p,y=b+r,S=M-r,E=M+r),x=b):(i==="left"?y=u+Math.max(l,d)+r:i==="right"?y=u+p-Math.max(c,h)-r:y=this.caretX,o==="top"?(S=f,M=S-r,b=y-r,x=y+r):(S=f+g,M=S+r,b=y+r,x=y-r),E=S),{x1:b,x2:y,x3:x,y1:S,y2:M,y3:E}}drawTitle(t,e,n){let i=this.title,o=i.length,r,a,l;if(o){let c=Le(n.rtl,this.x,this.width);for(t.x=Tn(this,n.titleAlign,n),e.textAlign=c.textAlign(n.titleAlign),e.textBaseline="middle",r=ft(n.titleFont),a=n.titleSpacing,e.fillStyle=n.titleColor,e.font=r.string,l=0;lx!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,Je(t,{x:g,y:p,w:c,h:l,radius:y}),t.fill(),t.stroke(),t.fillStyle=r.backgroundColor,t.beginPath(),Je(t,{x:b,y:p+1,w:c-2,h:l-2,radius:y}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(g,p,c,l),t.strokeRect(g,p,c,l),t.fillStyle=r.backgroundColor,t.fillRect(b,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=ft(n.bodyFont),u=h.lineHeight,f=0,p=Le(n.rtl,this.x,this.width),g=function(C){e.fillText(C,p.x(t.x+f),t.y+u/2),t.y+=u+o},b=p.textAlign(r),y,x,S,M,E,v,m;for(e.textAlign=r,e.textBaseline="middle",e.font=h.string,t.x=Tn(this,b,n),e.fillStyle=n.bodyColor,nt(this.beforeBody,g),f=a&&b!=="right"?r==="center"?c/2+d:c+2+d:0,M=0,v=i.length;M0&&e.stroke()}_updateAnimationTarget(t){let e=this.chart,n=this.$animations,i=n&&n.x,o=n&&n.y;if(i||o){let r=Rs[t.position].call(this,this._active,this._eventPosition);if(!r)return;let a=this._size=Fa(this,t),l=Object.assign({},r,this._size),c=Va(e,t,l),d=Na(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=vt(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),Fi(t,e.textDirection),o.y+=r.top,this.drawTitle(o,t,e),this.drawBody(o,t,e),this.drawFooter(o,t,e),Vi(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=!Es(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||!Es(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=Rs[o.position].call(this,t,e);return r!==!1&&(n!==r.x||i!==r.y)}};z(Os,"positioners",Rs);Ml={id:"tooltip",_element:Os,positioners:Rs,afterInit(s,t,e){e&&(s.tooltip=new Os({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:wl},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"]},Dl=Object.freeze({__proto__:null,Colors:bl,Decimation:vl,Filler:_l,Legend:Sl,SubTitle:kl,Title:El,Tooltip:Ml}),_f=(s,t,e,n)=>(typeof t=="string"?(e=s.push(t)-1,n.unshift({index:e,label:t})):isNaN(t)&&(e=null),e);Sf=(s,t)=>s===null?null:pt(Math.round(s),0,t);is=class extends Se{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(Z(t))return null;let n=this.getLabels();return e=isFinite(e)&&n[e]===t?e:Cf(n,t,q(e,t),this._addedLabels),Sf(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 Ha.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}};z(is,"id","category"),z(is,"defaults",{ticks:{callback:Ha}});ls=class extends Se{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 Z(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=Vt(i),c=Vt(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=Ef(i,o);return t.bounds==="ticks"&&mi(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 Qe(t,this.chart.options.locale,this.options.ticks.format)}},os=class extends ls{determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=ht(t)?t:0,this.max=ht(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){let t=this.isHorizontal(),e=t?this.width:this.height,n=Rt(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}};z(os,"id","linear"),z(os,"defaults",{ticks:{callback:Ze.formatters.numeric}});Bs=s=>Math.floor(se(s)),Pe=(s,t)=>Math.pow(10,Bs(s)+t);rs=class extends Se{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){let n=ls.prototype.parse.apply(this,[t,e]);if(n===0){this._zero=!0;return}return ht(n)&&n>0?n:null}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=ht(t)?Math.max(0,t):null,this.max=ht(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!ht(this._userMin)&&(this.min=t===Pe(this.min,0)?Pe(this.min,-1):Pe(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(Pe(n,-1)),r(Pe(i,1)))),n<=0&&o(Pe(i,-1)),i<=0&&r(Pe(n,1)),this.min=n,this.max=i}buildTicks(){let t=this.options,e={min:this._userMin,max:this._userMax},n=wf(e,this);return t.bounds==="ticks"&&mi(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":Qe(t,this.chart.options.locale,this.options.ticks.format)}configure(){let t=this.min;super.configure(),this._startValue=se(t),this._valueRange=se(this.max)-se(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(se(t)-this._startValue)/this._valueRange)}getValueForPixel(t){let e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}};z(rs,"id","logarithmic"),z(rs,"defaults",{ticks:{callback:Ze.formatters.logarithmic,major:{enabled:!0}}});ve=class extends ls{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=vt(lo(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=ht(t)&&!isNaN(t)?t:0,this.max=ht(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/lo(this.options))}generateTickLabels(t){ls.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((e,n)=>{let i=rt(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?Df(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=lt/(this._pointLabels.length||1),n=this.options.startAngle||0;return bt(t*e+Rt(n))}getDistanceFromCenterForValue(t){if(Z(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(Z(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);Nf(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=ft(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=vt(c.backdropPadding);t.fillRect(-r/2-h.left,-o-d.size/2-h.top,r+h.width,d.size+h.height)}ge(t,a.label,0,-o,d,{color:c.color,strokeColor:c.textStrokeColor,strokeWidth:c.textStrokeWidth})}),t.restore()}drawTitle(){}};z(ve,"id","radialLinear"),z(ve,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:Ze.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),z(ve,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),z(ve,"descriptors",{angleLines:{_fallback:"grid"}});Hn={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}},Dt=Object.keys(Hn);Ce=class extends Se{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 tl._date(t.adapters.date);i.init(e),Ke(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:Ka(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=ht(i)&&!isNaN(i)?i:+e.startOf(Date.now(),n),o=ht(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=Lr(i,o,r);return this._unit=e.unit||(n.autoSkip?Ga(e.minUnit,this.min,this.max,this._getLabelCapacity(o)):zf(this,a.length,e.minUnit,this.min,this.max)),this._majorUnit=!n.major.enabled||this._unit==="year"?void 0:Hf(this._unit),this.initOffsets(i),t.reverse&&a.reverse(),Xa(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=pt(e,0,r),n=pt(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||Ga(o.minUnit,e,n,this._getLabelCapacity(e)),a=q(i.ticks.stepSize,1),l=r==="week"?o.isoWeekday:!1,c=Te(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 rt(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(Ln(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){let e=this._offsets,n=this.getDecimalForPixel(t)/e.factor-e.end;return Ln(this._table,n*this._tableRange+this._minPos,!0)}};z(as,"id","timeseries"),z(as,"defaults",Ce.defaults);Ll=Object.freeze({__proto__:null,CategoryScale:is,LinearScale:os,LogarithmicScale:rs,RadialLinearScale:ve,TimeScale:Ce,TimeSeriesScale:as}),Wf=[Ja,pl,Dl,Ll]});var Kf={};fo(Kf,{CardView:()=>cs,default:()=>$n});module.exports=Wl(Kf);var it=require("obsidian"),Il=Un($s());var jl=["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"],Ul=[{label:"\u{1F1EA}\u{1F1FA} Schengen 90/180 (example)",scope:{countries:jl},window:{type:"rolling",days:180},threshold:90,note:"Example rule \u2014 add your own in Settings \u2192 CSV Card View."}],Gn={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:Ul,showResidency:!0},Ws="xlsx-card-view";var go=Un($s());function qn(s){return s.replace(/[\\/:*?"<>|#^[\]]/g,"").replace(/\s+/g," ").trim().slice(0,100)}function mo(s){return s.toLowerCase().replace(/[^\p{L}\p{N}/_-]+/gu,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Ee(s){var i,o;if(!s||!s.trim())return{headers:[],rows:[]};let t=go.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 js(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 bo(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 Et(s){return s.split(/[\s_-]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function yo(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=Yl(e,t);return i&&i!==e&&i!=="\u2014"?i:""}function Yl(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 vo(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 _o(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));c_.remove());let r=document.body.createDiv({cls:"csv-select-picker"});r.style.position="fixed",r.style.zIndex="9999";let a=()=>{let _=s.getBoundingClientRect(),D=r.offsetHeight||280,T=_.bottom+4+D>window.innerHeight&&_.top-4-D>0;r.style.left=_.left+"px",r.style.top=T?_.top-4-D+"px":_.bottom+4+"px"};a();let l=_=>{!r.contains(_.target)&&_.target!==s&&d()},c=()=>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=_=>_.split(",").map(D=>D.trim()).filter(Boolean),g=new Set(f?p(t):[]),b=()=>n([...g].join(", ")),y=f?Array.from(new Set(e.flatMap(p))):Array.from(new Set(e.filter(Boolean))),x=[],S=0,M=()=>{u.querySelectorAll(".csv-picker-item").forEach((_,D)=>{_.toggleClass("csv-picker-item--hover",D===S),D===S&&_.scrollIntoView({block:"nearest"})})},E=_=>{if(!f){n(_.isClear?"":_.value),d();return}_.isClear?g.clear():(g.has(_.value)?g.delete(_.value):g.add(_.value),_.isAdd&&!y.includes(_.value)&&y.push(_.value)),b(),_.isAdd?(h.value="",C("")):C(h.value)},v=_=>f?g.has(_):_===t,m=()=>f?g.size>0:!!t,C=_=>{u.empty(),x=[];let D=_?y.filter(T=>T.toLowerCase().includes(_.toLowerCase())):y;if(m()){x.push({value:"",isClear:!0});let T=u.createDiv({cls:"csv-picker-item csv-picker-clear"});T.setText(f?"\u2715 Clear all":"\u2715 Clear"),T.addEventListener("mousedown",P=>{P.preventDefault(),E({value:"",isClear:!0})})}if(D.forEach(T=>{x.push({value:T});let P=u.createDiv({cls:`csv-picker-item ${v(T)?"active":""}`});P.setText(f?`${g.has(T)?"\u2713 ":""}${T}`:T),P.addEventListener("mousedown",R=>{R.preventDefault(),E({value:T})})}),_&&!y.some(T=>T.toLowerCase()===_.toLowerCase())){x.push({value:_,isAdd:!0});let T=u.createDiv({cls:"csv-picker-item csv-picker-add"});T.setText(`+ Add "${_}"`),T.addEventListener("mousedown",P=>{P.preventDefault(),E({value:_,isAdd:!0})})}!D.length&&!_&&u.createDiv({cls:"csv-picker-empty",text:"No options yet. Type to add."}),S=Math.min(S,Math.max(x.length-1,0)),M()};f&&r.createEl("button",{cls:"csv-picker-done",text:"Done"}).addEventListener("mousedown",_=>{_.preventDefault(),d()}),C(""),a(),h.addEventListener("input",()=>{S=0,C(h.value),a()});let k=typeof window!="undefined"&&((w=window.matchMedia)==null?void 0:w.call(window,"(pointer: coarse)").matches);setTimeout(()=>{document.addEventListener("mousedown",l),k||(window.addEventListener("scroll",c,!0),window.addEventListener("resize",d))},0),h.addEventListener("keydown",_=>{if(_.key==="Escape"){d();return}if(_.key==="ArrowDown"){_.preventDefault(),x.length&&(S=(S+1)%x.length,M());return}if(_.key==="ArrowUp"){_.preventDefault(),x.length&&(S=(S-1+x.length)%x.length,M());return}if(_.key==="Enter")if(_.preventDefault(),x[S])E(x[S]);else{let D=h.value.trim();D&&(n(D),d())}})}function Co(s,t,e){return!s[t]||t===e||(s[e]||(s[e]=s[t]),delete s[t]),s}var It=require("obsidian");var Kl={source:["confirmed","inferred","conflict"],resolved:["yes","no"]};function So(s){var t;return(t=Kl[s.trim().toLowerCase()])!=null?t:null}function Eo(s){return/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(s.trim())}var ko=/^\d{4}-\d{2}-\d{2}$/;function qs(s,t,e,n){let i=Eo(t)&&(e===""||ko.test(e)),o=s.createEl("input",{cls:n,type:i?"date":"text",value:e});i||(o.placeholder=t);let r=So(t);if(r){let a=`csv-dl-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-${Math.random().toString(36).slice(2,7)}`,l=s.createEl("datalist");l.id=a,r.forEach(c=>l.createEl("option",{value:c})),o.setAttr("list",a)}return o}var Us=class extends It.Modal{constructor(t,e,n,i,o,r,a={}){super(t),this.headers=e,this.isNotesCol=n,this.isSelectCol=i,this.getColumnValues=o,this.onSubmit=r,this.optionPresets=a}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.headers.find(d=>["title","name"].includes(d.toLowerCase())),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 p;let h=e.createDiv({cls:"csv-modal-row"});h.createEl("label",{text:Et(d),cls:"csv-modal-label"});let u=(p=this.optionPresets[d])!=null?p:[],f=!this.isNotesCol(d)&&(u.length>0||this.isSelectCol(d)&&!Wt(d));if(this.isNotesCol(d)){let g=h.createEl("textarea",{cls:"csv-modal-textarea",placeholder:"Markdown supported\u2026"});g.addEventListener("input",()=>{n[d]=g.value})}else if(f){let g="__custom__",b=[];[...u,...this.getColumnValues(d)].forEach(S=>{let M=(S!=null?S:"").trim();M&&!b.some(E=>E.toLowerCase()===M.toLowerCase())&&b.push(M)});let y=h.createEl("select",{cls:"csv-modal-select"});y.createEl("option",{text:"\u2014",value:""}),b.forEach(S=>y.createEl("option",{text:S,value:S})),y.createEl("option",{text:"+ Custom\u2026",value:g});let x=h.createEl("input",{cls:"csv-modal-input csv-modal-custom",type:"text",placeholder:`Custom ${Et(d).toLowerCase()}`});x.hide(),x.addEventListener("input",()=>{n[d]=x.value}),x.addEventListener("keydown",S=>{S.key==="Enter"&&c()}),y.addEventListener("change",()=>{y.value===g?(x.show(),x.focus(),n[d]=x.value):(x.hide(),n[d]=y.value)})}else if(this.isSelectCol(d)){let b=h.createDiv({cls:"csv-modal-select-wrap"}).createDiv({cls:"csv-select-chip empty"});b.setText("\u2014 click to select \u2014"),b.addEventListener("click",y=>{y.stopPropagation(),Ot(b,n[d],this.getColumnValues(d),x=>{n[d]=x,b.setText(x||"\u2014 click to select \u2014"),b.toggleClass("empty",!x)},t,{multi:Wt(d)})})}else{let g=qs(h,d,"","csv-modal-input");if(g.addEventListener("input",()=>{n[d]=g.value}),g.addEventListener("keydown",b=>{b.key==="Enter"&&c()}),d===i&&o.size){let b=h.createDiv({cls:"csv-modal-dup-hint"});b.hide(),g.addEventListener("input",()=>{let y=o.get(g.value.trim().toLowerCase());y?(b.setText(`\u26A0 \u201C${y}\u201D is already in this file`),b.show()):b.hide()})}}});let r=t.createDiv({cls:"csv-modal-btns"});r.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),r.createEl("button",{text:"Add entry",cls:"csv-modal-submit"}).addEventListener("click",()=>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()}},Ys=class extends It.Modal{constructor(e,n,i,o,r,a,l,c,d,h){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.modalEl.addClass("csv-note-expander-modal")}onOpen(){var M,E,v,m,C;this.renderComponent.load();let{contentEl:e}=this;e.empty(),e.addClass("csv-note-expander");let n=window.visualViewport;if(n){let k=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${n.height}px`)};k(),n.addEventListener("resize",k),n.addEventListener("scroll",k),this.vvHandler=k}let i=e.createDiv({cls:"csv-expander-header"});i.createDiv({cls:"csv-expander-title",text:(E=this.row[(M=this.headers.find(k=>["title","name","Title","Name"].includes(k)))!=null?M:this.headers[0]])!=null?E:"\u2014"});let o=i.createDiv({cls:"csv-expander-header-btns"}),r=e.createDiv({cls:"csv-expander-fields"}),a=this.headers.find(k=>["title","name","Title","Name"].includes(k)),l=this.headers.find(k=>["author","Author","director","Director","artist","Artist","creator","Creator"].includes(k));this.headers.forEach(k=>{if(this.isNotesCol(k))return;let w=r.createDiv({cls:"csv-expander-field-row"});if(w.createDiv({cls:"csv-expander-field-label",text:Et(k)}),this.isSelectCol(k)){let _=w.createDiv({cls:`csv-select-chip ${this.row[k]?"":"empty"}`});_.setText(this.row[k]||"\u2014"),_.addEventListener("click",D=>{D.stopPropagation(),Ot(_,this.row[k],this.getColumnValues(k),T=>{this.row[k]=T,_.setText(T||"\u2014"),_.toggleClass("empty",!T)},e,{multi:Wt(k)})})}else{let _=w.createDiv({cls:"csv-expander-field-value",text:this.row[k]||"\u2014"});_.addEventListener("click",()=>{var P;_.empty();let D=qs(_,k,(P=this.row[k])!=null?P:"","csv-inline-input");D.focus(),D.type==="text"&&D.select();let T=()=>{this.row[k]=D.value,_.empty(),_.setText(D.value||"\u2014")};D.addEventListener("blur",T),D.addEventListener("keydown",R=>{R.key==="Enter"&&D.blur(),R.key==="Escape"&&(_.empty(),_.setText(this.row[k]||"\u2014"))})})}}),e.createDiv({cls:"csv-expander-divider"}).createDiv({cls:"csv-expander-notes-label",text:this.notesCol});let d=!1,h=(v=this.row[this.notesCol])!=null?v:"",u=e.createDiv({cls:"csv-expander-rendered markdown-rendered"});u.title="Click to edit";let f=e.createDiv({cls:"csv-expander-editor"});f.style.display="none";let p=()=>{u.empty(),h.trim()?It.MarkdownRenderer.render(this.app,h,u,this.filePath,this.renderComponent):u.createDiv({cls:"csv-notes-empty",text:"+ Add note"})};p();let g=f.createEl("textarea",{cls:"csv-expander-textarea"});g.value=h,g.addEventListener("input",()=>{h=g.value});let b=()=>{d||(d=!0,u.style.display="none",f.style.display="flex",g.value=h,g.focus())},y=()=>{d&&(d=!1,f.style.display="none",u.style.display="",h=g.value,p())};u.addEventListener("click",k=>{if(k.target.closest("a, button, input, textarea, [contenteditable]"))return;let _=window.getSelection();_&&_.toString().length>0||b()}),g.addEventListener("keydown",k=>{k.key==="Escape"&&(k.preventDefault(),g.blur())}),g.addEventListener("blur",y);let x=e.createDiv({cls:"csv-expander-footer"});if(this.onDelete){let k=String((C=this.row[(m=this.headers.find(w=>["title","name","Title","Name"].includes(w)))!=null?m:this.headers[0]])!=null?C:"").trim();x.createEl("button",{cls:"csv-expander-delete-btn",text:"Delete"}).addEventListener("click",()=>{let w=k||"this entry";window.confirm(`Delete "${w}"? This can't be undone.`)&&(this.onDelete(),this.close())})}let S=x.createDiv({cls:"csv-expander-footer-right"});S.createEl("button",{cls:"csv-modal-cancel",text:"Cancel"}).addEventListener("click",()=>this.close()),S.createEl("button",{cls:"csv-expander-save-btn",text:"Save & close"}).addEventListener("click",()=>{d&&(h=g.value),this.row[this.notesCol]=h,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 Ks=class extends It.Modal{constructor(t,e,n,i,o,r,a){super(t),this.headers=e,this.filePath=n,this.current={...i,habitColumns:i.habitColumns?[...i.habitColumns]:void 0},this.autoDetectedHabits=o,this.availableModes=r,this.onSave=a}onOpen(){var C,k,w;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="\u2014 use global default \u2014",i=[n,...this.headers],o=(_,D,T)=>{let P=e.createDiv({cls:"csv-modal-row"});P.createEl("label",{text:_,cls:"csv-modal-label"});let R=P.createEl("select",{cls:"csv-modal-select"});i.forEach(H=>{let B=R.createEl("option",{text:H,value:H});(D!=null?D:n)===H&&(B.selected=!0)}),R.addEventListener("change",()=>T(R.value===n?void 0:R.value))};o("Category column (kanban grouping)",this.current.categoryColumn,_=>{this.current.categoryColumn=_}),o("Status column (row subgroups)",this.current.statusColumn,_=>{this.current.statusColumn=_}),o("Notes column",this.current.notesColumn,_=>{this.current.notesColumn=_});let r=e.createDiv({cls:"csv-modal-row"});r.createEl("label",{text:"Habit columns (dashboard)",cls:"csv-modal-label"});let a=r.createEl("p",{cls:"csv-modal-hint",text:"Select columns to track as habits. Auto-detected columns with binary values (0/1) are pre-selected."}),l=r.createDiv({cls:"csv-modal-checkbox-grid"}),c=new Set((C=this.current.habitColumns)!=null?C:this.autoDetectedHabits);this.headers.forEach(_=>{let D=l.createEl("label",{cls:"csv-modal-checkbox-label"}),T=D.createEl("input",{type:"checkbox"});T.checked=c.has(_),this.autoDetectedHabits.includes(_)&&!this.current.habitColumns&&D.addClass("auto-detected"),D.createSpan({text:_}),T.addEventListener("change",()=>{this.current.habitColumns||(this.current.habitColumns=[...this.autoDetectedHabits]),T.checked?this.current.habitColumns.includes(_)||this.current.habitColumns.push(_):this.current.habitColumns=this.current.habitColumns.filter(P=>P!==_)})});let d=e.createDiv({cls:"csv-modal-row"});d.createEl("label",{text:"Card fields (Library / Kanban)",cls:"csv-modal-label"}),d.createEl("p",{cls:"csv-modal-hint",text:"Columns shown under each card title. Rating renders as stars, theme/tag columns as pills. Leave all unchecked for title-only cards."});let h=d.createDiv({cls:"csv-modal-checkbox-grid"}),u=_=>this.headers.find(D=>_.some(T=>T.toLowerCase()===D.toLowerCase())),f=[u(["Author","Authors","Director","Artist","Creator","By"]),u(["Year","Date","Released"]),u(["Rating","Score","Score /5","Stars"]),u(["Theme","Tags","Tag","Mood"])].filter(_=>!!_),p=new Set((k=this.current.cardFields)!=null?k:f),g=!!this.current.cardFields;this.headers.forEach(_=>{let D=h.createEl("label",{cls:"csv-modal-checkbox-label"}),T=D.createEl("input",{type:"checkbox"});T.checked=p.has(_),f.includes(_)&&!g&&D.addClass("auto-detected"),D.createSpan({text:_}),T.addEventListener("change",()=>{this.current.cardFields||(this.current.cardFields=[...f]),T.checked?this.current.cardFields.includes(_)||this.current.cardFields.push(_):this.current.cardFields=this.current.cardFields.filter(P=>P!==_)})});let b="\u2014 title / primary field \u2014",y=e.createDiv({cls:"csv-modal-row"});y.createEl("label",{text:"Anki card front",cls:"csv-modal-label"}),y.createEl("p",{cls:"csv-modal-hint",text:"Column used as the front of each card when syncing to Anki. Other columns become the back."});let x=y.createEl("select",{cls:"csv-modal-select"});[b,...this.headers].forEach(_=>{var T;let D=x.createEl("option",{text:_,value:_});((T=this.current.ankiFrontCol)!=null?T:b)===_&&(D.selected=!0)}),x.addEventListener("change",()=>{this.current.ankiFrontCol=x.value===b?void 0:x.value});let S=e.createDiv({cls:"csv-modal-row"});S.createEl("label",{text:"Default view",cls:"csv-modal-label"});let M=S.createEl("select",{cls:"csv-modal-select"}),E=[["\u2014 use global default \u2014",""],...this.availableModes.map(_=>[_.label,_.id])],v=(w=this.current.defaultMode)!=null?w:"";v&&!this.availableModes.some(_=>_.id===v)&&E.push([`${v} (no longer available)`,v]),E.forEach(([_,D])=>{let T=M.createEl("option",{text:_,value:D});v===D&&(T.selected=!0)}),M.addEventListener("change",()=>{this.current.defaultMode=M.value?M.value:void 0});let m=t.createDiv({cls:"csv-modal-btns"});m.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),m.createEl("button",{text:"Save",cls:"csv-modal-submit"}).addEventListener("click",()=>{this.onSave(this.current),this.close()})}onClose(){this.contentEl.empty()}},Gs=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 Xn=195,Gl={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"},ql={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"},Mo={};for(let[s,t]of Object.entries(ql))for(let e of t)Mo[e]=s;function Ct(s){return Gl[s]||s}function Ft(s){return!s||s.length!==2?"":String.fromCodePoint(...s.toUpperCase().split("").map(t=>t.charCodeAt(0)+127397))}function At(s){if(!s||s.indexOf("?")!==-1)return null;let t=new Date(s+"T12:00:00Z");return isNaN(t.getTime())?null:t}function fs(s){let t=At(s.date_entered),e=At(s.date_left);return!t||!e?0:Math.max(Math.round((e.getTime()-t.getTime())/864e5),1)}function Do(s,t=new Date){let e=t.getTime(),n=null,i=-1/0;for(let o of s){let r=At(o.date_entered);if(!(!r||r.getTime()>e)){if(o.date_left.trim()!==""){let a=At(o.date_left);if(!a||a.getTime()i&&(n=o,i=r.getTime())}}return n}function To(s){let t=y=>{var x,S,M,E,v,m,C,k;return{date_entered:(x=y.date_entered)!=null?x:"",date_left:(S=y.date_left)!=null?S:"",country:((M=y.country)!=null?M:"").trim().toUpperCase(),city:(E=y.city)!=null?E:"",visa_status:(v=y.visa_status)!=null?v:"",notes:(m=y.notes)!=null?m:"",source:((C=y.source)!=null?C:"").trim().toLowerCase(),resolved:(k=y.resolved)!=null?k:"",_src:y}},e=s.map(t).filter(y=>y.country),n=e.filter(y=>y.source==="confirmed"),i=e.filter(y=>y.source==="inferred"),o=e.filter(y=>y.source==="conflict"),r=[];for(let y of n){let x=At(y.date_entered),S=At(y.date_left);x&&S&&r.push([x.getTime(),S.getTime()])}let a=y=>{let x=At(y.date_entered),S=At(y.date_left);if(!x||!S)return!1;let M=x.getTime(),E=S.getTime();return r.some(([v,m])=>M<=m&&E>=v)},l=i.filter(y=>At(y.date_entered)&&At(y.date_left)&&!a(y)),c=new Set(n.map(y=>y.country)),d=new Set(i.map(y=>y.country)),h=new Set([...d].filter(y=>!c.has(y))),u=new Set([...c,...d]),f=new Map;for(let y of n)f.set(y.country,(f.get(y.country)||0)+fs(y));let p=[...f.entries()].map(([y,x])=>({iso:y,days:x})).sort((y,x)=>x.days-y.days||Ct(y.iso).localeCompare(Ct(x.iso))),g=p.reduce((y,x)=>y+x.days,0),b=new Set;for(let y of c){let x=Mo[y];x&&b.add(x)}return{confirmed:n,inferred:i,conflicts:o,inferredVisible:l,confRanges:r,confirmedCountries:c,inferredOnlyCountries:h,allCountries:u,countryDays:p,totalConfirmedDays:g,visitedContinents:b,worldPct:Math.round(c.size/Xn*100)}}var Qn=864e5;function Lo(s){if(!s||s.indexOf("?")!==-1)return null;let t=Date.parse(s+"T00:00:00Z");return isNaN(t)?null:t}function Xl(s,t,e,n){let i=Math.max(s,e),o=Math.min(t,n);return o<=i?0:Math.round((o-i)/Qn)}function Ql(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*Qn,end:t+Qn,label:`in last ${n} days`}}function Ao(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=Ql(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=Lo(f.date_entered),g=Lo(f.date_left);p===null||g===null||(a+=Xl(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 Po=["#c9a96e","#4a6fa5","#5ba06e","#a05b8a","#6ea0a0","#a0855b","#7a6ea0","#a06e6e","#6e8fa0","#a09e5b"],Zl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Jl(){let s=new Map,t=0;return e=>(s.has(e)||s.set(e,Po[t++%Po.length]),s.get(e))}function tc(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 Zn(s){let t=fs(s);return t?`${t}d`:"\u2014"}function He(s){return s||"\u2014"}function gs(s){return s.createDiv({cls:"csv-tv-table-wrap"}).createEl("table",{cls:"csv-tv-table"})}function ps(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=qs(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 Ro(s,t,e,n=()=>{},i=null,o=()=>{}){let r=To(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(tc(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&&(nc(u,r,l,()=>d(null)),u.scrollIntoView({behavior:"smooth",block:"nearest"}))},d=f=>{l=f&&f!==l?f:null,c()};ec(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&&ic(a,r.confirmed,i),oc(a,r,d),rc(a,r,d),ac(a,r,n);try{let f=await e();h.empty(),f?sc(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 ec(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/Xn*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=fs(c);d>a&&(a=d,r=c)}if(r){let c=r.date_entered.slice(0,4);n("Longest trip",`${a}d`,`${Ft(r.country)} ${Ct(r.country)}${c?` \xB7 ${c}`:""}`)}let l=Do(t.confirmed);if(l){let c=At(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 ${Ft(l.country)} ${Ct(l.country)}`}),h.createSpan({cls:"csv-tv-now-sub",text:` \u2014 since ${l.date_entered} (day ${d})${l.city?` \xB7 ${l.city}`:""}`})}}function sc(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",`${Ct(a)} \u2014 ${l&&l.days?l.days+"d confirmed":"confirmed"}`),r.setAttr("data-tip",`${Ct(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",`${Ct(a)} \u2014 photo evidence`),r.setAttr("data-tip",`${Ct(a)} \xB7 photo evidence \xB7 click for trips`)):a?(r.classList.add("cp-unvisited"),r.setAttr("data-tip",Ct(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 nc(s,t,e,n){var b,y;let i=s.createDiv({cls:"csv-tv-detail"}),o=i.createDiv({cls:"csv-tv-detail-head"});o.createSpan({cls:"csv-tv-detail-flag",text:Ft(e)});let r=o.createDiv({cls:"csv-tv-detail-titles"});r.createDiv({cls:"csv-tv-detail-name",text:Ct(e)});let a=t.confirmed.filter(x=>x.country===e),l=t.inferred.filter(x=>x.country===e),c=(y=(b=t.countryDays.find(x=>x.iso===e))==null?void 0:b.days)!=null?y: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=Xs([...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=gs(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:S}of u){let M=g.createEl("tr");M.createEl("td",{text:S?"\u{1F4F7}":"",cls:"csv-tv-flag",attr:S?{"data-tip":"Photo-inferred"}:{}}),M.createEl("td",{text:He(x.date_entered)}),M.createEl("td",{text:He(x.date_left)}),M.createEl("td",{text:Zn(x)}),M.createEl("td",{text:x.city}),M.createEl("td",{text:x.visa_status})}}function ic(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=Ao(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 oc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Countries visited"});let n=gs(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:Ft(r),cls:"csv-tv-flag"}),l.createEl("td",{text:Ct(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(Ft).join(" ")})}}function rc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Timeline"});let n=Jl(),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 S of o.get(c)){if(g.add(S.country),S._inf)continue;let M=Math.max(new Date(S.date_entered+"T12:00:00Z").getTime(),d),E=Math.min(new Date(S.date_left+"T12:00:00Z").getTime(),h);M<=E&&(p+=Math.max(Math.round((E-M)/864e5)+1,1))}let b=f.createDiv({cls:"csv-tv-tl-label"});b.createSpan({text:String(c)}),b.createSpan({cls:"csv-tv-tl-sub",text:`${p?`${p}d \xB7 `:""}${g.size} ${g.size===1?"country":"countries"}`});let y=f.createDiv({cls:"csv-tv-month-row"});Zl.forEach(S=>y.createDiv({cls:"csv-tv-month-tick",text:S}));let x=f.createDiv({cls:"csv-tv-track"});for(let S of o.get(c)){let M=Math.max(new Date(S.date_entered+"T12:00:00Z").getTime(),d),E=Math.min(new Date(S.date_left+"T12:00:00Z").getTime(),h);if(M>E)continue;let v=(M-d)/u*100,m=Math.max((E-M+864e5)/u*100,.5),C=n(S.country),k=x.createDiv({cls:`csv-tv-seg${S._inf?" csv-tv-seg-inf":""}`});k.style.left=`${v}%`,k.style.width=`${m}%`,S._inf?(k.style.borderColor=C,k.style.background=C+"22",k.style.color=C):k.style.background=C,k.setAttr("data-iso",S.country),k.setAttr("data-tip",`${Ct(S.country)} ${S.date_entered} \u2192 ${S.date_left} (${fs(S)}d)${S.visa_status?" ["+S.visa_status+"]":""}${S._inf?" [photo]":""}`),k.addEventListener("click",()=>e(S.country)),m>4?k.createSpan({cls:"csv-tv-seg-lbl",text:`${Ft(S.country)} ${S.country}`}):m>2&&k.createSpan({cls:"csv-tv-seg-lbl",text:Ft(S.country)})}}a.createDiv({cls:"csv-tv-tl-legend"}).setText("Confirmed (solid) \xB7 Photo inferred (outlined)")}function Xs(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 ac(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=gs(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 Xs(t.confirmed)){let a=o.createEl("tr");a.createEl("td",{text:Ft(r.country),cls:"csv-tv-flag"}),a.createEl("td",{text:Ct(r.country)}),ps(a.createEl("td"),r._src,"date_entered",e),ps(a.createEl("td"),r._src,"date_left",e),a.createEl("td",{text:Zn(r)}),ps(a.createEl("td"),r._src,"city",e),ps(a.createEl("td"),r._src,"visa_status",e),ps(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=gs(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 Xs(t.inferred)){let h=c.createEl("tr");h.createEl("td",{text:Ft(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:Ct(d.country)}),h.createEl("td",{text:He(d.date_entered)}),h.createEl("td",{text:He(d.date_left)}),h.createEl("td",{text:Zn(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=gs(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 Xs(t.conflicts)){let h=c.createEl("tr");h.createEl("td",{text:Ft(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:d.country}),h.createEl("td",{text:`${He(d.date_entered)} \u2192 ${He(d.date_left)}`}),h.createEl("td",{text:d.notes})}}}var Lt=require("obsidian"),Qs=class extends Lt.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 Lt.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 Lt.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 Lt.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 Lt.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 Lt.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 Lt.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 Lt.Setting(t).setName("Reset column widths").addButton(n=>n.setButtonText("Reset").onClick(async()=>{this.plugin.settings.columnWidths={},await this.plugin.saveSettings(),new Lt.Notice("Column widths reset.")})),new Lt.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 y,x,S,M,E,v;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=(m,C,k,w="")=>{let _=u.createDiv({cls:"csv-rr-field"});_.createEl("label",{text:m});let D=_.createEl("input",{type:"text",value:C});w&&(D.placeholder=w),D.addEventListener("input",()=>{k(D.value),n()})},p=(y=r.scope.countries)!=null?y:r.scope.country?[r.scope.country]:[];f("Countries (ISO-2, comma)",p.join(", "),m=>{r.scope={countries:m.split(",").map(C=>C.trim().toUpperCase()).filter(Boolean)}},"US, GB");let g=u.createDiv({cls:"csv-rr-field"});g.createEl("label",{text:"Window"});let b=g.createEl("select");[["calendar-year","Calendar year"],["rolling","Rolling N days"],["all-time","All time"]].forEach(([m,C])=>{let k=b.createEl("option",{text:C,value:m});r.window.type===m&&(k.selected=!0)}),b.addEventListener("change",()=>{r.window={type:b.value,days:r.window.days},n(),this.renderResidencyRules(t)}),r.window.type==="rolling"&&f("Rolling days",String((x=r.window.days)!=null?x:180),m=>{let C=parseInt(m,10);r.window.days=isNaN(C)?void 0:C},"180"),f("Threshold (days)",String(r.threshold),m=>{let C=parseInt(m,10);r.threshold=isNaN(C)?0:C},"183"),f("Exempt visas (comma)",((M=(S=r.exempt)==null?void 0:S.visa_status)!=null?M:[]).join(", "),m=>{let C=m.split(",").map(k=>k.trim()).filter(Boolean);r.exempt=C.length?{visa_status:C}:void 0},"F-1, J-1"),f("On-exceed label",(E=r.onExceed)!=null?E:"",m=>{r.onExceed=m||void 0},"tax resident"),f("Note",(v=r.note)!=null?v:"",m=>{r.note=m||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 ae=require("obsidian"),Oo=Un($s());async function Io(s,t,e,n){var G,W;let i=t.split(` -`).map(L=>L.trim()).filter(Boolean),o="";for(let L of i)if(L.startsWith("file:")){o=L.replace("file:","").trim();break}if(!o){e.createEl("p",{text:"Error: No file specified. Use: file: yourfile.csv",cls:"csv-add-error"});return}let r=s.vault.getAbstractFileByPath(n.sourcePath),a=(W=(G=r==null?void 0:r.parent)==null?void 0:G.path)!=null?W:"",l=js(o,a),c=s.vault.getAbstractFileByPath(l);if(!c||!(c instanceof ae.TFile)){e.createEl("p",{text:`Error: File not found: ${l}`,cls:"csv-add-error"});return}let d=[],h=[];try{let L=await s.vault.read(c),A=Ee(L);d=A.headers,h=A.rows}catch(L){e.createEl("p",{text:`Error reading file: ${L}`,cls:"csv-add-error"});return}if(!d.length){e.createEl("p",{text:"Error: No columns found in file",cls:"csv-add-error"});return}let u=["0","1","true","false","yes","no",""],f=L=>{let A=h.map(V=>{var $;return(($=V[L])!=null?$:"").toLowerCase().trim()});return A.length>0&&A.every(V=>u.includes(V))},p=L=>{let A=L.toLowerCase();if(["date","day","datum"].includes(A))return!0;let V=h.slice(0,5).map($=>{var U;return(U=$[L])!=null?U:""});return V.length>0&&V.every($=>/^\d{4}-\d{2}-\d{2}$/.test($))},g=L=>{let A=L.toLowerCase();return["notes","note","comments","description","journal"].includes(A)},b=d.filter(L=>f(L)&&!p(L)),y=d.filter(L=>p(L)),x=d.filter(L=>g(L)),S=d.filter(L=>!b.includes(L)&&!y.includes(L)&&!x.includes(L)),M=e.createDiv({cls:"csv-add-form csv-add-compact"}),E=M.createEl("button",{cls:"csv-add-trigger",text:"+ New entry"});E.style.display="none";let v=M.createDiv({cls:"csv-add-card"}),m=v.createDiv({cls:"csv-add-card-header"});m.createEl("span",{cls:"csv-add-card-title",text:"New entry"});let C=m.createEl("button",{cls:"csv-add-card-close",text:"\xD7"}),k=v.createDiv({cls:"csv-add-rows"}),w={},_={},D=(L,A)=>{let V=k.createDiv({cls:`csv-add-row csv-add-row-${A}`});return V.createEl("span",{cls:"csv-add-row-label",text:Et(L)}),V};y.forEach(L=>{let V=D(L,"date").createEl("input",{cls:"csv-add-row-control",type:"date"});V.value=new Date().toISOString().split("T")[0],w[L]=V}),b.forEach(L=>{_[L]=!1;let V=D(L,"toggle").createEl("label",{cls:"csv-add-switch"}),$=V.createEl("input",{type:"checkbox",cls:"csv-add-switch-input"});V.createEl("span",{cls:"csv-add-switch-track"}),$.addEventListener("change",()=>{_[L]=$.checked}),w[L]=$}),S.forEach(L=>{let A=D(L,"field"),V=new Set(h.map($=>{var U;return((U=$[L])!=null?U:"").trim()}).filter(Boolean));if(V.size>0&&V.size<=15){let $=A.createEl("select",{cls:"csv-add-row-control"});$.createEl("option",{text:"\u2014",value:""}),Array.from(V).sort().forEach(I=>$.createEl("option",{text:I,value:I})),$.createEl("option",{text:"+ Custom",value:"__custom__"});let U=k.createDiv({cls:"csv-add-row csv-add-row-custom"});U.style.display="none";let F=U.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:`Custom ${Et(L).toLowerCase()}`});k.insertBefore(U,A.nextSibling),$.addEventListener("change",()=>{U.style.display=$.value==="__custom__"?"flex":"none",$.value==="__custom__"&&F.focus()}),w[L]=$,w[`${L}__custom`]=F}else w[L]=A.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:Et(L)})}),x.forEach(L=>{let A=k.createDiv({cls:"csv-add-row csv-add-row-notes"});A.createEl("span",{cls:"csv-add-row-label",text:Et(L)}),w[L]=A.createEl("textarea",{cls:"csv-add-row-textarea",placeholder:"Optional notes\u2026"})});let T=v.createEl("button",{text:"Add",cls:"csv-add-submit"}),P=m.querySelector(".csv-add-card-title"),R=()=>{if(!y.length)return;let L=w[y[0]];if(!L)return;let A=L.value,V=h.find($=>$[y[0]]===A);P&&P.setText(V?`Updating ${A}`:"New entry"),v.classList.toggle("is-updating",!!V),T.setText(V?"Update":"Add"),b.forEach($=>{var O;let U=w[$];if(!U)return;let F=((O=V==null?void 0:V[$])!=null?O:"").toLowerCase().trim(),I=F==="1"||F==="true"||F==="yes";U.checked=I,_[$]=I}),[...S,...x].forEach($=>{var I,O;let U=w[$];if(!U)return;let F=(I=V==null?void 0:V[$])!=null?I:"";if(U instanceof HTMLSelectElement)if(Array.from(U.options).find(N=>N.value===F)){U.value=F;let N=(O=w[`${$}__custom`])==null?void 0:O.closest(".csv-add-row-custom");N&&(N.style.display="none")}else U.value="";else U instanceof HTMLTextAreaElement,U.value=F})};if(R(),y.length){let L=w[y[0]];L==null||L.addEventListener("change",R)}let H=()=>{v.style.display="block",E.style.display="none";let L=v.querySelector(".csv-add-row-control");L==null||L.focus()},B=()=>{v.style.display="none",E.style.display=""};E.addEventListener("click",H),C.addEventListener("click",B),T.addEventListener("click",async()=>{let L={};d.forEach(O=>{var j,N,Y,K;b.includes(O)?L[O]=_[O]?"1":"0":w[O]instanceof HTMLSelectElement&&w[O].value==="__custom__"?L[O]=(N=(j=w[`${O}__custom`])==null?void 0:j.value)!=null?N:"":w[O]instanceof HTMLTextAreaElement?L[O]=w[O].value:L[O]=(K=(Y=w[O])==null?void 0:Y.value)!=null?K:""});let A=y.length>0&&y.some(O=>{var j;return((j=L[O])!=null?j:"").trim()}),V=[...S,...x].some(O=>{var j;return((j=L[O])!=null?j:"").trim()}),$=b.some(O=>_[O]);if(!A&&!V&&!$){new ae.Notice("Please fill at least one field");return}let U=[];try{let O=await s.vault.read(c);U=Ee(O).rows}catch(O){new ae.Notice(`Error reading file: ${O}`);return}let F=!1,I=-1;if(y.length>0){let O=y[0],j=L[O];if(I=U.findIndex(N=>N[O]===j),I>=0){F=!0;let N=U[I];d.forEach(Y=>{var K;(b.includes(Y)||((K=L[Y])!=null?K:"").trim())&&(N[Y]=L[Y])})}else U.push(L)}else U.push(L);try{let O=Oo.default.unparse(U,{columns:d});await s.vault.modify(c,O),new ae.Notice(F?`Updated entry for ${L[y[0]]||""}`:`Added entry to ${c.basename}`),h.length=0,h.push(...U),y.length>0?R():(b.forEach(j=>{_[j]=!1;let N=w[j];N&&(N.checked=!1)}),[...S,...x].forEach(j=>{let N=w[j];N instanceof HTMLSelectElement?N.selectedIndex=0:(N instanceof HTMLTextAreaElement||N)&&(N.value="");let Y=w[`${j}__custom`];if(Y){Y.value="";let K=Y.closest(".csv-add-row-custom");K&&(K.style.display="none")}})),setTimeout(async()=>{let j=s.vault.getAbstractFileByPath(n.sourcePath);if(j instanceof ae.TFile){let N=s.workspace.activeLeaf;N&&await N.openFile(j,{state:{mode:"preview"}})}},300)}catch(O){new ae.Notice(`Error saving: ${O}`)}})}function Fo(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=y=>{c.style.width=Math.max(60,f+y.clientX-u)+"px"},b=y=>{s.settings.columnWidths[l]=Math.max(60,f+y.clientX-u),h.removeEventListener("pointermove",g),h.removeEventListener("pointerup",b),s.persistSettings()};h.addEventListener("pointermove",g),h.addEventListener("pointerup",b)})}),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 b=((p=l[u])!=null?p:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").split(` -`).filter(S=>S.trim()).slice(0,3).join(" \xB7 "),y=b?b.slice(0,200)+(b.length>200?"\u2026":""):"+ Add note",x=f.createSpan({text:y});b||x.addClass("csv-table-notes-empty"),f.title="Click to open note",f.addEventListener("click",S=>{S.stopPropagation(),s.openNoteExpander(l,u)})}else if(s.isSelectCol(u))s.renderSelectField(f,l,u);else{let b=(g=l[u])!=null?g:"";f.setText(b),b.length>80&&(f.title=b),lc(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 lc(s,t,e,n){t.addEventListener("click",()=>{var o;t.empty();let i=t.createEl("input",{cls:"csv-inline-input",value:(o=e[n])!=null?o:"",type:"text"});i.focus(),i.select(),i.addEventListener("blur",()=>{e[n]=i.value,s.scheduleSave(),t.empty(),t.setText(i.value||"\u2014")}),i.addEventListener("keydown",r=>{r.key==="Enter"&&i.blur(),r.key==="Escape"&&(t.empty(),t.setText(e[n]||"\u2014"))})})}function Zs(s){return!!(s.getCategoryCol()||s.getStatusCol()||Vo(s)||s.authorKey())}function Vo(s){return s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"])}function ys(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 No=["watched","read","finished","completed","done","yes","seen"],Bo=["watching","reading","in progress","in-progress"],cc=["dropped","abandoned","dnf"];function dc(s){let t=s.toLowerCase();return No.includes(t)?"is-done":Bo.includes(t)?"is-progress":cc.includes(t)?"is-dropped":""}function ms(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 bs(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 zo(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=Vo(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 No.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 Bo.includes(((g=p[i])!=null?g:"").toLowerCase().trim())}).length;f>0&&d(String(f),"in progress")}if(o){let u=ms(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=>ys(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=ms(e,p=>{var b;let g=((b=p[i])!=null?b:"").trim();return g?[g]:[]}),f=Array.from(u.entries()).sort((p,g)=>g[1]-p[1]).map(([p,g])=>({label:p,count:g,cls:dc(p),onClick:o?()=>h(p,null):void 0}));bs(n,`By ${i.toLowerCase()}`,f,e.length)}if(o){let u=ms(e,p=>{var g;return((g=p[o])!=null?g:"").split(",").map(b=>b.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)}));bs(n,`By ${o.toLowerCase()}`,f,e.length)}if(r){let u=new Map,f=0;if(e.forEach(p=>{var y;let g=ys(p[r]);if(g===null)return;let b=Math.min(5,Math.max(1,Math.round(g)));u.set(b,((y=u.get(b))!=null?y:0)+1),f++}),f>0){let p=[5,4,3,2,1].filter(g=>{var b;return((b=u.get(g))!=null?b:0)>0}).map(g=>({label:"\u2605".repeat(g),count:u.get(g),cls:"is-rating"}));bs(n,"Ratings",p,f)}}if(l){let u=ms(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}));bs(n,"By year",f,e.length)}}if(a){let u=ms(e,p=>{var b;let g=((b=p[a])!=null?b:"").trim();return g?[g]:[]}),f=Array.from(u.entries()).filter(([,p])=>p>1);if(f.length>=2){let p=f.sort((g,b)=>b[1]-g[1]||g[0].localeCompare(b[0])).slice(0,8).map(([g,b])=>({label:g,count:b}));bs(n,`Top ${a.toLowerCase()}s`,p,e.length)}}}function Jt(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),_o(s.headers,s.rows,n)}function $o(s,t){let e=Jt(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(y=>!s.isNotesCol(y)).forEach(y=>{let x=l.createEl("option",{text:y===n?`${y} (default)`:y,value:y});y===e&&(x.selected=!0)}),l.addEventListener("change",()=>{let y=s.fileCfg;y.kanbanGroupCol=l.value===n?void 0:l.value,s.saveFileCfg(y),s.renderView(!0)});let c=vo(e,r.map(y=>{var x;return(x=y[e])!=null?x:""})),d=e!==n,h=y=>{var M;let x=(M=y[e])!=null?M:"",S;if(c){let E=xo(x);S=E?[E]:[]}else S=x.split(",").map(E=>E.trim()).filter(Boolean);return!S.length&&d&&(S=["\u2014"]),S},u=new Set;r.forEach(y=>h(y).forEach(x=>u.add(x)));let f=Array.from(u).sort();if(!f.length){let y=t.createDiv({cls:"csv-empty-state"});y.createEl("p",{text:s.searchQuery?"No matching entries found.":`No "${e}" values found.`}),s.searchQuery&&y.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear search"}).addEventListener("click",()=>{s.searchQuery="",s.renderView()});return}let p=["In progress","Finished","Not started"],g=o?Array.from(new Set([...p,...r.map(y=>{var x;return(x=y[o])!=null?x:""}).filter(Boolean)])).filter(y=>r.some(x=>{var S;return((S=x[o])!=null?S:"")==y})):[],b=t.createDiv({cls:"csv-kanban-board"});f.forEach(y=>{let x=r.filter(v=>h(v).includes(y));if(!x.length)return;let S=b.createDiv({cls:"csv-kanban-col"}),M=S.createDiv({cls:"csv-kanban-col-header"});M.createDiv({cls:"csv-kanban-col-title",text:y}),M.createDiv({cls:"csv-kanban-col-count",text:String(x.length)});let E=S.createDiv({cls:"csv-kanban-col-body"});o&&g.length?g.forEach(v=>{let m=x.filter(k=>{var w;return((w=k[o])!=null?w:"")===v});if(!m.length)return;let C=E.createDiv({cls:"csv-kanban-status-group"});C.createDiv({cls:`csv-kanban-status-label status-${v.toLowerCase().replace(/\s+/g,"-")}`,text:v}),m.forEach(k=>Ho(s,C,k,o,e))}):x.forEach(v=>Ho(s,E,v,o,e))})}function Ho(s,t,e,n,i){var v;let o=t.createDiv({cls:"csv-kanban-card"}),r=s.getNotesCol(),a=o.createDiv({cls:"csv-kanban-card-title-row"}),l=a.createDiv({cls:"csv-kanban-card-title",text:s.getTitle(e)});r&&l.addEventListener("click",m=>{m.stopPropagation(),s.openNoteExpander(e,r)});let c=s.notesFileExists(e);a.createEl("button",{cls:`csv-kanban-notes-icon ${c?"exists":""}`,text:c?"\u{1F4C4}":"+",title:c?"Open notes file":"Create notes file"}).addEventListener("click",m=>{m.stopPropagation(),s.openOrCreateNotes(e)});let h=s.getSubtitle(e);h&&o.createDiv({cls:"csv-kanban-card-sub",text:h});let u=s.titleKey(),f=s.authorKey(),p=new Set([n,u,f,i].filter(Boolean)),g=o.createDiv({cls:"csv-kanban-card-meta"});s.headers.forEach(m=>{if(p.has(m)||s.isNotesCol(m)||!e[m])return;let C=g.createDiv({cls:"csv-kanban-chip"});if(C.createSpan({cls:"csv-chip-label",text:m+": "}),s.isSelectCol(m)){let k=C.createSpan({cls:"csv-chip-value csv-chip-select",text:e[m]});k.addEventListener("click",w=>{w.stopPropagation(),Ot(k,e[m],s.getColumnValues(m),_=>{e[m]=_,k.setText(_||"\u2014"),s.scheduleSave()},s.contentEl,{multi:Wt(m)})})}else{let k=e[m].length>40?e[m].slice(0,38)+"\u2026":e[m],w=C.createSpan({cls:"csv-chip-value",text:k});e[m].length>40&&(w.title=e[m])}});let b=s.getNotesCol(),y=!!(b&&((v=e[b])!=null&&v.trim())),x=o.createDiv({cls:"csv-kanban-notes-preview"});if(y&&b){let m=e[b].replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();x.setText(m.slice(0,120)+(m.length>120?"\u2026":"")),x.title="Click to edit"}else x.addClass("csv-kanban-notes-preview--empty"),b&&x.setText("+ Add note");let S=o.createDiv({cls:"csv-kanban-notes-editor"});S.style.display="none";let M=()=>{var _,D,T;let m=s.contentEl.querySelector(".csv-content-area"),C=(_=m==null?void 0:m.scrollLeft)!=null?_:0,k=(D=m==null?void 0:m.scrollTop)!=null?D:0;x.style.display="none",S.style.display="block",S.empty();let w=S.createEl("textarea",{cls:"csv-notes-textarea"});w.value=(T=b?e[b]:"")!=null?T:"",w.addEventListener("click",P=>P.stopPropagation()),w.addEventListener("mousedown",P=>P.stopPropagation()),w.addEventListener("input",()=>{w.style.height="auto",w.style.height=w.scrollHeight+"px"}),w.addEventListener("keydown",P=>{P.key==="Escape"&&E(w.value,m,C,k)}),w.addEventListener("blur",()=>E(w.value,m,C,k)),w.focus({preventScroll:!0}),w.setSelectionRange(0,0),w.scrollTop=0,requestAnimationFrame(()=>{w.style.height="auto",w.style.height=Math.max(120,w.scrollHeight)+"px"})},E=(m,C,k,w)=>{if(b&&(e[b]=m,s.scheduleSave()),S.style.display="none",x.style.display="",m.trim()){let _=m.replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();x.setText(_.slice(0,120)+(_.length>120?"\u2026":"")),x.removeClass("csv-kanban-notes-preview--empty"),x.title="Click to edit"}else x.addClass("csv-kanban-notes-preview--empty"),x.setText(b?"+ Add note":""),x.removeAttribute("title");C&&(C.scrollLeft=k,C.scrollTop=w,requestAnimationFrame(()=>{C.scrollLeft=k,C.scrollTop=w,requestAnimationFrame(()=>{C.scrollLeft=k,C.scrollTop=w})}),setTimeout(()=>{C.scrollLeft=k,C.scrollTop=w},50))};x.addEventListener("click",m=>{if(m.stopPropagation(),b&&matchMedia("(pointer: coarse)").matches){s.openNoteExpander(e,b);return}M()}),o.addEventListener("contextmenu",m=>s.openRowContextMenu(e,m))}function Wo(s,t){var k,w;let e=Jt(s),n=s.getStatusCol(),i=(k=s.titleKey())!=null?k: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(_=>{var T;((T=_[e])!=null?T:"").split(",").map(P=>P.trim()).filter(Boolean).forEach(P=>r.add(P))});let a=new Set;n&&s.rows.forEach(_=>{var T;let D=((T=_[n])!=null?T:"").trim();D&&a.add(D)});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(_=>d.includes(_.toLowerCase())),f=Array.from(a).some(_=>h.includes(_.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(_=>{c.createEl("option",{text:_,value:_})})),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(_=>{p.createEl("option",{text:_,value:_})}),p.value=s.libraryGenreFilter;let g=s.resolveCol(["Year","year","Date","date"]),b=s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"]),y=s.resolveCol(["Theme","theme","Tags","tags","Tag","tag","Mood","mood"]),x=(w=s.fileCfg.librarySort)!=null?w:"status",S=l.createEl("select",{cls:"csv-library-filter-select"}),M=[["status","Sort: Status"],["title","Sort: Title"]];b&&M.push(["rating","Sort: Rating"]),g&&M.push(["year","Sort: Year"]),M.forEach(([_,D])=>{let T=S.createEl("option",{text:D,value:_});_===x&&(T.selected=!0)}),S.addEventListener("change",()=>{let _=s.fileCfg;_.librarySort=S.value==="status"?void 0:S.value,s.saveFileCfg(_),s.renderView(!0)});let E=()=>{s.libraryStatusFilter=c.value,s.libraryGenreFilter=p.value,s.renderView(!0)};c.addEventListener("change",E),p.addEventListener("change",E);let v=s.rows.filter(_=>{var D,T;if(s.libraryStatusFilter!=="all"&&n){let P=((D=_[n])!=null?D:"").toLowerCase();if(s.libraryStatusFilter==="__done__"){if(!d.includes(P))return!1}else if(s.libraryStatusFilter==="__inprogress__"){if(!h.includes(P))return!1}else if(s.libraryStatusFilter==="__notstarted__"){if(d.includes(P)||h.includes(P))return!1}else if(P!==s.libraryStatusFilter.toLowerCase())return!1}if(s.libraryGenreFilter!=="all"&&!((T=_[e])!=null?T:"").split(",").map(R=>R.trim().toLowerCase()).includes(s.libraryGenreFilter.toLowerCase()))return!1;if(s.searchQuery.trim()){let P=s.searchQuery.toLowerCase().trim();if(!s.headers.some(R=>{var H;return((H=_[R])!=null?H:"").toLowerCase().includes(P)}))return!1}return!0});(s.libraryStatusFilter!=="all"||s.libraryGenreFilter!=="all"||s.searchQuery.trim())&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${v.length} of ${s.rows.length} entries`});let m={};v.forEach(_=>{var T;let D=s.libraryGenreFilter!=="all"?[s.libraryGenreFilter]:((T=_[e])!=null?T:"Uncategorized").split(",").map(P=>P.trim()).filter(Boolean);D.length===0&&D.push("Uncategorized"),D.forEach(P=>{m[P]||(m[P]=[]),m[P].push(_)})});let C=t.createDiv({cls:"csv-library-sections"});if(Object.keys(m).sort().forEach(_=>{var L;let D=m[_],T=C.createEl("details",{cls:"csv-library-section"});T.open=!0;let P=T.createEl("summary",{cls:"csv-library-section-header"});P.innerHTML=`\u25B6 ${_} ${D.length}`;let R=T.createDiv({cls:"csv-library-grid"}),H=(A,V)=>{var $,U;return(($=A[i])!=null?$:"").localeCompare((U=V[i])!=null?U:"")},B=(A,V)=>A===null&&V===null?0:A===null?1:V===null?-1:V-A;D.sort((A,V)=>{var $,U,F,I;if(x==="title")return H(A,V);if(x==="rating"&&b)return B(ys(($=A[b])!=null?$:""),ys((U=V[b])!=null?U:""))||H(A,V);if(x==="year"&&g){let O=j=>{var Y;let N=((Y=j[g])!=null?Y:"").match(/\d{4}/);return N?parseInt(N[0],10):null};return B(O(A),O(V))||H(A,V)}if(n){let O=((F=A[n])!=null?F:"").toLowerCase(),j=((I=V[n])!=null?I:"").toLowerCase(),N=d.includes(O),Y=d.includes(j);if(N!==Y)return N?-1:1;let K=h.includes(O),X=h.includes(j);if(K!==X)return K?-1:1}return H(A,V)});let G=[o,g,b,y].filter(A=>!!A),W=(L=s.fileCfg.cardFields)!=null?L:G;D.forEach(A=>{var I,O,j,N;let V=R.createDiv({cls:"csv-library-card"}),$=V.createDiv({cls:"csv-library-card-title"});if(n){let Y=((I=A[n])!=null?I:"").toLowerCase();d.includes(Y)&&$.createSpan({cls:"csv-library-done-dot"})}$.createSpan({text:(O=A[i])!=null?O:"Untitled"});let U=[],F=[];for(let Y of W){if(!Y)continue;let K=String((j=A[Y])!=null?j:"").trim();if(K)if(Y===b){let X=yo(K,Y);X&&V.createDiv({cls:"csv-library-card-rating",text:X})}else if(Y===y)F.push(...K.split(",").map(X=>X.trim()).filter(Boolean));else if(Y===g){let X=K.match(/\d{4}/);U.push(X?X[0]:K)}else U.push(K)}if(U.length&&V.createDiv({cls:"csv-library-card-meta",text:U.join(" \xB7 ")}),s.libraryGenreFilter!=="all"){let Y=((N=A[e])!=null?N:"").split(",").map(K=>K.trim()).filter(K=>K&&K.toLowerCase()!==s.libraryGenreFilter.toLowerCase());F.push(...Y)}if(F.length){let Y=V.createDiv({cls:"csv-library-card-tags"});F.slice(0,3).forEach(K=>{Y.createSpan({cls:"csv-library-card-tag",text:K})})}V.addEventListener("click",()=>{let Y=s.getNotesCol();Y&&s.openNoteExpander(A,Y)}),V.addEventListener("contextmenu",Y=>s.openRowContextMenu(A,Y))})}),Object.keys(m).length===0){let _=C.createDiv({cls:"csv-empty-state"});_.createEl("p",{text:"No entries match your filters."}),_.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.libraryStatusFilter="all",s.libraryGenreFilter="all",s.searchQuery="",s.renderView()})}}var sn=require("obsidian");var ke=require("obsidian");var Jn=`--- +`):s}function wf(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 $a(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=Ct(t.padding),m=p.height,g=0,b=n.reduce((E,w)=>E+w.before.length+w.lines.length+w.after.length,0);if(b+=s.beforeBody.length+s.afterBody.length,h&&(m+=h*c.lineHeight+(h-1)*t.titleSpacing+t.titleMarginBottom),b){let E=t.displayColors?Math.max(a,l.lineHeight):l.lineHeight;m+=f*E+(b-f)*l.lineHeight+(b-1)*t.bodySpacing}u&&(m+=t.footerMarginTop+u*d.lineHeight+(u-1)*t.footerSpacing);let x=0,_=function(E){g=Math.max(g,e.measureText(E).width+x)};return e.save(),e.font=c.string,ot(s.title,_),e.font=l.string,ot(s.beforeBody.concat(s.afterBody),_),x=t.displayColors?r+2+t.boxPadding:0,ot(n,E=>{ot(E.before,_),ot(E.lines,_),ot(E.after,_)}),x=0,e.font=d.string,ot(s.footer,_),e.restore(),g+=p.width,{width:g,height:m}}function Ef(s,t){let{y:e,height:n}=t;return es.height-n/2?"bottom":"center"}function kf(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 Mf(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"),kf(c,s,t,e)&&(c="center"),c}function Wa(s,t,e){let n=e.yAlign||t.yAlign||Ef(s,e);return{xAlign:e.xAlign||t.xAlign||Mf(s,t,e,n),yAlign:n}}function Df(s,t){let{x:e,width:n}=s;return t==="right"?e-=n:t==="center"&&(e-=n/2),e}function Tf(s,t,e){let{y:n,height:i}=s;return t==="top"?n+=e:t==="bottom"?n-=i+e:n-=i/2,n}function ja(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}=ye(r),p=Df(t,a),m=Tf(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(m,0,n.height-t.height)}}function Bn(s,t,e){let n=Ct(e.padding);return t==="center"?s.x+s.width/2:t==="right"?s.x+s.width-n.right:s.x+n.left}function Ua(s){return Jt([],ce(s))}function Lf(s,t,e){return le(s,{tooltip:t,tooltipItems:e,type:"tooltip"})}function Ka(s,t){let e=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return e?s.override(e):s}function Dt(s,t,e,n){let i=s[t].call(e,n);return typeof i=="undefined"?Pl[t].call(e,n):i}function Pf(s,t,e,n){let i=s.indexOf(t);if(i===-1)return Af(s,t,e,n);let o=s.lastIndexOf(t);return i!==o?e:i}function Ya(s){let t=this.getLabels();return s>=0&&sp&&(w=wi(D*w/p/f)*f),tt(l)||(v=Math.pow(10,l),w=Math.ceil(w*v)/v),i==="ticks"?(y=Math.floor(m/w)*w,S=Math.ceil(g/w)*w):(y=m,S=g),b&&x&&o&&Rr((a-r)/o,w/1e3)?(D=Math.round(Math.min((a-r)/w,d)),w=(a-r)/D,y=r,S=a):_?(y=b?r:y,S=x?a:S,D=c-1,w=(S-y)/D):(D=(S-y)/w,ts(D,Math.round(D),w/1e3)?D=Math.round(D):D=Math.ceil(D));let M=Math.max(ki(w),ki(y));v=Math.pow(10,tt(l)?M:l),y=Math.round(y*v)/v,S=Math.round(S*v)/v;let C=0;for(b&&(u&&y!==r?(e.push({value:r}),ya)break;e.push({value:T})}return x&&u&&S!==a?e.length&&ts(e[e.length-1].value,a,Ga(a,E,s))?e[e.length-1].value=a:e.push({value:a}):(!x||S===a)&&e.push({value:S}),e}function Ga(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 qa(s){return s/Math.pow(10,Ks(s))===1}function Xa(s,t,e){let n=Math.pow(10,e),i=Math.floor(s/n);return Math.ceil(t/n)-i}function Ff(s,t){let e=t-s,n=Ks(e);for(;Xa(s,t,n)>10;)n++;for(;Xa(s,t,n)<10;)n--;return Math.min(n,Ks(s))}function If(s,{min:t,max:e}){t=Mt(s.min,t);let n=[],i=Ks(t),o=Ff(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:qa(f),significand:h}),n}function vo(s){let t=s.ticks;if(t.display&&s.display){let e=Ct(t.backdropPadding);return Q(t.font&&t.font.size,ht.font.size)+e.height}return 0}function Vf(s,t,e){return e=ct(e)?e:[e],{w:$r(s,t.string,e),h:e.length*t.lineHeight}}function Qa(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 Nf(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 zf(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(En(xt(l.angle+mt))),d=Uf(l.y,a.h,c),h=Wf(c),u=jf(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 Hf(s,t){if(!t)return!0;let{left:e,top:n,right:i,bottom:o}=s;return!(Xt({x:e,y:n},t)||Xt({x:e,y:o},t)||Xt({x:i,y:n},t)||Xt({x:i,y:o},t))}function $f(s,t,e){let n=[],i=s._pointLabels.length,o=s.options,{centerPointLabels:r,display:a}=o.pointLabels,l={extra:vo(o)/2,additionalAngle:r?nt/i:0},c;for(let d=0;d270||e<90)&&(s-=t),s}function Kf(s,t,e){let{left:n,top:i,right:o,bottom:r}=e,{backdropColor:a}=t;if(!tt(a)){let l=ye(t.borderRadius),c=Ct(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(),is(s,{x:d,y:h,w:u,h:f,radius:l}),s.fill()):s.fillRect(d,h,u,f)}}function Yf(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));Kf(e,r,o);let a=bt(r.font),{x:l,y:c,textAlign:d}=o;ve(e,s._pointLabels[i],l,c+a.lineHeight/2,a,{color:r.color,textAlign:d,textBaseline:"middle"})}}function Fl(s,t,e,n){let{ctx:i}=s;if(e)i.arc(s.xCenter,s.yCenter,t,0,dt);else{let o=s.getPointPosition(0,t);i.moveTo(o.x,o.y);for(let r=1;r=Lt.indexOf(e);o--){let r=Lt[o];if(Qn[r].common&&s._adapter.diff(i,n,r)>=t-1)return r}return Lt[e?Lt.indexOf(e):0]}function Qf(s){for(let t=Lt.indexOf(s)+1,e=Lt.length;t=t?e[n]:e[i];s[o]=!0}}function Zf(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 sl(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 ao,te,ia,Jd,Wn,$s,Zi,ca,dh,Tt,Fe,Ie,se,Ve,Se,as,Ne,Be,ol,lo,rl,al,ll,St,Ws,jn,Hn,Rh,ba,dl,js,va,Kn,At,Xh,ya,xa,ke,ls,co,jt,ho,Ea,gl,Ns,po,mu,vu,yu,$n,La,ee,_e,Iu,Ut,ze,He,xl,mo,Ra,Sl,El,Gn,Ml,Ha,vf,qn,Tl,Us,Ll,Nn,Al,zs,Pl,Hs,Rl,Ol,Af,Rf,cs,fs,ds,Ks,Oe,hs,Ce,Qn,Lt,Ee,us,Il,Jf,Nl=ti(()=>{na();ao=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=Li.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)}},te=new ao,ia="transparent",Jd={boolean(s,t,e){return e>.5?t:s},color(s,t,e){let n=Fi(s||ia),i=n.valid&&Fi(t||ia);return i&&i.valid?i.mix(n,e).hexString():t},number(s,t,e){return s+(t-s)*e}},Wn=class{constructor(t,e,n,i){let o=e[n];i=os([t.to,i,o,t.from]);let r=os([t.from,o,i]);this._active=!0,this._fn=t.fn||Jd[t.type||typeof r],this._easing=qe[t.easing]||qe.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=os([t.to,e,i,t.from]),this._from=os([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];(ct(o.properties)&&o.properties||[i]).forEach(a=>{(a===i||!n.has(a))&&n.set(a,r)})})}_animateOptions(t,e){let n=e.options,i=eh(t,n);if(!i)return[];let o=this._createAnimations(i,n);return n.$shared&&th(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 Wn(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 te.add(this._chart,n),!0}};Zi=s=>s==="reset"||s==="none",ca=(s,t)=>t?s:Object.assign({},s),dh=(s,t,e)=>s&&!t.hidden&&t._stacked&&{keys:nl(e,!0),values:null},Tt=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=Xi(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&&Os(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=Q(n.xAxisID,Qi(t,"x")),r=e.yAxisID=Q(n.yAxisID,Qi(t,"y")),a=e.rAxisID=Q(n.rAxisID,Qi(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&&Di(this._data,this),t._stacked&&Os(t)}_dataCheck(){let t=this.getDataset(),e=t.data||(t.data=[]),n=this._data;if(et(e)){let i=this._cachedMeta;this._data=ih(e,i)}else if(n!==e){if(n){Di(n,this);let i=this._cachedMeta;Os(i),i._parsed=[]}e&&Object.isExtensible(e)&&Nr(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=Xi(e.vScale,e),e.stack!==n.stack&&(i=!0,Os(e),e.stack=n.stack),this._resyncElements(t),(i||o!==e._stacked)&&(la(this,e._parsed),e._stacked=Xi(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{ct(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]m||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),m=c.resolveNamedOptions(u,f,p,h);return m.$shared&&(m.$shared=l,o[r]=Object.freeze(ca(m,l))),m}_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 $s(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||Zi(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){Zi(i)?Object.assign(t,n):this._resolveAnimations(e,i).update(t,n)}updateSharedOptions(t,e,n){t&&!Zi(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[Q(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=>+ae(n[c],l)}let r,a;for(r=t,a=t+e;r0&&!isNaN(t)?dt*(Math.abs(t)/e):0}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart,i=n.data.labels||[],o=ss(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")}),H(se,"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()}}}});Ve=class extends Tt{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}=Pi(e,i,r);this._drawStart=a,this._drawCount=l,Ri(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:m}=this.options,g=Ae(p)?p:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||i==="none",x=e+n,_=t.length,E=e>0&&this.getParsed(e-1);for(let w=0;w<_;++w){let v=t[w],y=b?v:{};if(w=x){y.skip=!0;continue}let S=this.getParsed(w),D=tt(S[f]),M=y[u]=r.getPixelForValue(S[u],w),C=y[f]=o||D?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,S,l):S[f],w);y.skip=isNaN(M)||isNaN(C)||D,y.stop=w>0&&Math.abs(S[u]-E[u])>g,m&&(y.parsed=S,y.raw=c.data[w]),h&&(y.options=d||this.resolveDataElementOptions(w,v.active?"active":i)),b||this.updateElement(v,w,y,i),E=S}}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()}};H(Ve,"id","line"),H(Ve,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),H(Ve,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});Se=class extends Tt{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=ss(e._parsed[t].r,n.options.locale);return{label:i[t]||"",value:o}}parseObjectData(t,e,n,i){return $i.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,m=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}};H(Se,"id","polarArea"),H(Se,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),H(Se,"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}}});as=class extends se{};H(as,"id","pie"),H(as,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});Ne=class extends Tt{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 $i.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(v[f]-_[f])>b,g&&(y.parsed=v,y.raw=c.data[E]),u&&(y.options=h||this.resolveDataElementOptions(E,w.active?"active":i)),x||this.updateElement(w,E,y,i),_=v}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}};H(Be,"id","scatter"),H(Be,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),H(Be,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});ol=Object.freeze({__proto__:null,BarController:Fe,BubbleController:Ie,DoughnutController:se,LineController:Ve,PieController:as,PolarAreaController:Se,RadarController:Ne,ScatterController:Be});lo=class s{constructor(t){H(this,"options");this.options=t||{}}static override(t){Object.assign(s.prototype,t)}init(){}formats(){return Re()}parse(){return Re()}format(){return Re()}add(){return Re()}diff(){return Re()}startOf(){return Re()}endOf(){return Re()}},rl={_date:lo};al={evaluateInteractionItems:Ys,modes:{index(s,t,e,n){let i=xe(t,s),o=e.axis||"x",r=e.includeInvisible||!1,a=e.intersect?to(s,i,o,n,r):eo(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=xe(t,s),o=e.axis||"xy",r=e.includeInvisible||!1,a=e.intersect?to(s,i,o,n,r):eo(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 m.beforeLayout=="function"&&m.beforeLayout()});let d=l.reduce((m,g)=>g.box.options&&g.box.options.display===!1?m:m+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);cl(u,Ct(n));let f=Object.assign({maxPadding:u,w:o,h:r,x:i.left,y:i.top},i),p=Dh(l.concat(c),h);Bs(a.fullSize,f,h,p),Bs(l,f,h,p),Bs(c,f,h,p)&&Bs(l,f,h,p),Ah(f),ma(a.leftAndTop,f,h,p),f.x+=f.w,f.y+=f.h,ma(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},ot(a.chartArea,m=>{let g=m.box;Object.assign(g,s.chartArea),g.update(f.w,f.h,{left:0,top:0,right:0,bottom:0})})}},Ws=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){}},jn=class extends Ws{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}},Hn="$chartjs",Rh={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},ba=s=>s===null||s==="";dl=Zr?{passive:!0}:!1;js=new Map,va=0;Kn=class extends Ws{acquireContext(t,e){let n=t&&t.getContext&&t.getContext("2d");return n&&n.canvas===t?(Oh(t,e),n):null}releaseContext(t){let e=t.canvas;if(!e[Hn])return!1;let n=e[Hn].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[Hn],!0}addEventListener(t,e,n){this.removeEventListener(t,e);let i=t.$proxies||(t.$proxies={}),r={attach:Nh,detach:Bh,resize:$h}[e]||Wh;i[e]=r(t,e,n)}removeEventListener(t,e){let n=t.$proxies||(t.$proxies={}),i=n[e];if(!i)return;({attach:so,detach:so,resize:so}[e]||Ih)(t,e,i),n[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,n,i){return Qr(t,e,n,i)}isAttached(t){let e=t&&Rn(t);return!!(e&&e.isConnected)}};At=class{constructor(){H(this,"x");H(this,"y");H(this,"active",!1);H(this,"options");H(this,"$animations")}tooltipPosition(t){let{x:e,y:n}=this.getProps(["x","y"],t);return{x:e,y:n}}hasValue(){return Ae(this.x)&&Ae(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}};H(At,"defaults",{}),H(At,"defaultRoutes");Xh=s=>s==="left"?"right":s==="right"?"left":s,ya=(s,t,e)=>t==="top"||t==="left"?s[t]+e:s[t]-e,xa=(s,t)=>Math.min(t||s,s);ke=class s extends At{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: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: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(){lt(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=Ur(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-Vs(t.grid)-e.padding-Ca(t.title,this.chart.options.font),c=Math.sqrt(h*h+u*u),r=En(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(){lt(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){lt(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=Ca(i,e.options.font);if(a?(t.width=this.maxWidth,t.height=Vs(o)+l):(t.height=this.maxHeight,t.width=Vs(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),m=Math.cos(p),g=Math.sin(p);if(a){let b=n.mirror?0:g*h.width+m*u.height;t.height=Math.min(this.maxHeight,t.height+b+f)}else{let b=n.mirror?0:m*h.width+g*u.height;t.width=Math.min(this.maxWidth,t.width+b+f)}this._calculatePadding(c,d,g,m)}}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(){lt(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[D]||0,height:a[D]||0});return{first:S(0),last:S(e-1),widest:S(v),highest:S(y),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 Or(this._alignToPixels?be(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=Vs(o),f=[],p=a.setContext(this.getContext()),m=p.display?p.width:0,g=m/2,b=function(O){return be(n,O,m)},x,_,E,w,v,y,S,D,M,C,T,k;if(r==="top")x=b(this.bottom),y=this.bottom-u,D=x-g,C=b(t.top)+g,k=t.bottom;else if(r==="bottom")x=b(this.top),C=t.top,k=b(t.bottom)-g,y=x+g,D=this.top+u;else if(r==="left")x=b(this.right),v=this.right-u,S=x-g,M=b(t.left)+g,T=t.right;else if(r==="right")x=b(this.left),M=t.left,T=b(t.right)-g,v=x+g,S=this.left+u;else if(e==="x"){if(r==="center")x=b((t.top+t.bottom)/2+.5);else if(et(r)){let O=Object.keys(r)[0],z=r[O];x=b(this.chart.scales[O].getPixelForValue(z))}C=t.top,k=t.bottom,y=x+g,D=y+u}else if(e==="y"){if(r==="center")x=b((t.left+t.right)/2);else if(et(r)){let O=Object.keys(r)[0],z=r[O];x=b(this.chart.scales[O].getPixelForValue(z))}v=x-g,S=v-u,M=t.left,T=t.right}let A=Q(i.ticks.maxTicksLimit,h),P=Math.max(1,Math.ceil(h/A));for(_=0;_0&&(F-=U/2);break}V={left:F,top:B,width:U+W.width,height:j+W.height,color:P.backdropColor}}g.push({label:E,font:D,textOffset:T,options:{rotation:m,color:z,strokeColor:G,strokeWidth:$,textAlign:L,textBaseline:k,translation:[w,v],backdrop:V}})}return g}_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):ot(i,r=>{let a=n||this._getRegistryForType(r);this._exec(t,a,r)})})}_exec(t,e,n){let i=wn(t);lt(n["before"+i],[],n),e[t](n),lt(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")}};Ea=new Map,gl=new Set;Ns=(s,t,e)=>{let n=ae(t,e);n!==void 0&&s.add(n)},po=class{constructor(t){this._config=gu(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=pl(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){let t=this._config;this.clearCache(),fl(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return Vn(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,e){return Vn(`${t}.transition.${e}`,()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,e){return Vn(`${t}-${e}`,()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]])}pluginScopeKeys(t){let e=t.id,n=this.type;return Vn(`${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=>Ns(l,t,h))),d.forEach(h=>Ns(l,i,h)),d.forEach(h=>Ns(l,me[o]||{},h)),d.forEach(h=>Ns(l,ht,h)),d.forEach(h=>Ns(l,Dn,h))});let c=Array.from(l);return c.length===0&&c.push(Object.create(null)),gl.has(e)&&r.set(e,c),c}chartOptionScopes(){let{options:t,type:e}=this;return[t,me[e]||{},ht.datasets[e]||{},{type:e},ht,Dn]}resolveNamedOptions(t,e,n,i=[""]){let o={$shared:!0},{resolver:r,subPrefixes:a}=ka(this._resolverCache,t,i),l=r;if(bu(r,e)){o.$shared=!1,n=oe(n)?n():n;let c=this.createResolver(t,n,a);l=Le(r,n,c)}for(let c of e)o[c]=l[c];return o}createResolver(t,e,n=[""],i){let{resolver:o}=ka(this._resolverCache,t,n);return et(e)?Le(o,e,void 0,i):o}};mu=s=>et(s)&&Object.getOwnPropertyNames(s).some(t=>oe(s[t]));vu="4.5.1",yu=["top","bottom","left","right","chartArea"];$n={},La=s=>{let t=ml(s);return Object.values($n).filter(e=>e.canvas===t).pop()};ee=class{static register(...t){jt.add(...t),Aa()}static unregister(...t){jt.remove(...t),Aa()}constructor(t,e){let n=this.config=new po(e),i=ml(t),o=La(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||ul(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=Dr(),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 ho,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=Br(h=>this.update(h),r.resizeDelay||0),this._dataChanges=[],$n[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}te.listen(this,"complete",Ta),te.listen(this,"progress",xu),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 jt}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():Wi(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Ii(this.canvas,this.ctx),this}stop(){return te.stop(this),this}resize(t,e){te.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,Wi(this,a,!0)&&(this.notifyPlugins("resize",{size:r}),lt(n.onResize,[this,r],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){let e=this.options.scales||{};ot(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=fo(r,a),c=l==="r",d=l==="x";return{options:a,dposition:c?"chartArea":d?"bottom":"left",dtype:c?"radialLinear":d?"category":"linear"}}))),ot(o,r=>{let a=r.options,l=a.id,c=fo(l,a),d=Q(a.type,r.dtype);(a.position===void 0||Ma(a.position,c)!==Ma(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=jt.getScale(d);h=new u({id:l,type:d,ctx:this.ctx,chart:this}),n[h.id]=h}h.init(a,t)}),ot(i,(r,a)=>{r||delete n[a]}),ot(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(Da("z","_idx"));let{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){ot(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);(!Si(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;_u(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=[],ot(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=qi(this,t);this.notifyPlugins("beforeDatasetDraw",n)!==!1&&(i&&Ps(e,i),t.controller.draw(),i&&Rs(e),n.cancelable=!1,this.notifyPlugins("afterDatasetDraw",n))}isPointInArea(t){return Xt(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,n,i){let o=al.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=le(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);Je(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(),te.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)};ot(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(){ot(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},ot(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}});!As(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=Ar(t),c=Cu(t,this._lastEvent,n,l);n&&(this._lastEvent=null,lt(o.onHover,[t,a,this],this),l&<(o.onClick,[t,a,this],this));let d=!As(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)}};H(ee,"defaults",ht),H(ee,"instances",$n),H(ee,"overrides",me),H(ee,"registry",jt),H(ee,"version",vu),H(ee,"getChart",La);_e=class extends At{constructor(e){super();H(this,"circumference");H(this,"endAngle");H(this,"fullCircles");H(this,"innerRadius");H(this,"outerRadius");H(this,"pixelMargin");H(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}=Mi(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=Q(u,c-l),m=es(r,l,c)&&l!==c,g=p>=dt||m,b=Zt(a,d+f,h+f);return g&&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>dt?Math.floor(i/dt):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,Mu(e,this,d,r,a),Du(e,this,d,r,a),e.restore()}};H(_e,"id","arc"),H(_e,"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}),H(_e,"defaultRoutes",{backgroundColor:"backgroundColor"}),H(_e,"descriptors",{_scriptable:!0,_indexable:e=>e!=="borderDash"});Iu=typeof Path2D=="function";Ut=class extends At{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;Xr(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=sa(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=Gi(this,{property:e,start:i,end:i});if(!r.length)return;let a=[],l=Ru(n),c,d;for(c=0,d=r.length;ct!=="borderDash"&&t!=="fill"});ze=class extends At{constructor(e){super();H(this,"parsed");H(this,"skip");H(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)"));Sl={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=Oa(n)||Yu(i)||o&&Oa(o)||Gu();if(!e.forceOverride&&r)return;let a=Ku(s);n.forEach(a)}};El={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(s,t,e)=>{if(!e.enabled){Fa(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(os([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}=Qu(l,c),f=e.threshold||4*n;if(u<=f){wl(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(m){this._data=m}}));let p;switch(e.algorithm){case"lttb":p=qu(c,h,u,n,e);break;case"min-max":p=Xu(c,h,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${e.algorithm}'`)}i._decimated=p})},destroy(s){Fa(s)}};Gn=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:dt},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}}};Ml={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&&oo(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;Va(o)&&oo(s.ctx,o,s.chartArea)}},beforeDatasetDraw(s,t,e){let n=t.meta.$filler;!Va(n)||e.drawTime!=="beforeDatasetDraw"||oo(s.ctx,n,s.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}},Ha=(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)}},vf=(s,t)=>s!==null&&t!==null&&s.datasetIndex===t.datasetIndex&&s.index===t.index,qn=class extends At{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=lt(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}=Ha(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,m)=>{let g=n+e/2+o.measureText(p.text).width;(m===0||c[c.length-1]+g+2*a>r)&&(h+=d,c[c.length-(m>0?0:1)]=0,f+=d,u++),l[m]={left:0,top:f,row:u,width:g,height:i},c[c.length-1]+=g+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,m=0;return this.legendItems.forEach((g,b)=>{let{itemWidth:x,itemHeight:_}=yf(n,e,o,g,i);b>0&&f+_+2*a>d&&(h+=u+a,c.push({width:u,height:f}),p+=u+a,m++,u=f=0),l[b]={left:p,top:f,col:m,width:x,height:_},u=Math.max(u,x),f+=_+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=Pe(o,this.left,this.width);if(this.isHorizontal()){let a=0,l=_t(n,this.left+i,this.right-this.lineWidths[a]);for(let c of e)a!==c.row&&(a=c.row,l=_t(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=_t(n,this.top+t+i,this.bottom-this.columnSizes[a].height);for(let c of e)c.col!==a&&(a=c.col,l=_t(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;Ps(t,this),this._draw(),Rs(t)}}_draw(){let{options:t,columnSizes:e,lineWidths:n,ctx:i}=this,{align:o,labels:r}=t,a=ht.color,l=Pe(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:m,itemHeight:g}=Ha(r,h),b=function(v,y,S){if(isNaN(p)||p<=0||isNaN(m)||m<0)return;i.save();let D=Q(S.lineWidth,1);if(i.fillStyle=Q(S.fillStyle,a),i.lineCap=Q(S.lineCap,"butt"),i.lineDashOffset=Q(S.lineDashOffset,0),i.lineJoin=Q(S.lineJoin,"miter"),i.lineWidth=D,i.strokeStyle=Q(S.strokeStyle,a),i.setLineDash(Q(S.lineDash,[])),r.usePointStyle){let M={radius:m*Math.SQRT2/2,pointStyle:S.pointStyle,rotation:S.rotation,borderWidth:D},C=l.xPlus(v,p/2),T=y+u;Vi(i,M,C,T,r.pointStyleWidth&&p)}else{let M=y+Math.max((h-m)/2,0),C=l.leftForLtr(v,p),T=ye(S.borderRadius);i.beginPath(),Object.values(T).some(k=>k!==0)?is(i,{x:C,y:M,w:p,h:m,radius:T}):i.rect(C,M,p,m),i.fill(),D!==0&&i.stroke()}i.restore()},x=function(v,y,S){ve(i,S.text,v,y+g/2,c,{strikethrough:S.hidden,textAlign:l.textAlign(S.textAlign)})},_=this.isHorizontal(),E=this._computeTitleHeight();_?f={x:_t(o,this.left+d,this.right-n[0]),y:this.top+d+E,line:0}:f={x:this.left+d,y:_t(o,this.top+E+d,this.bottom-e[0].height),line:0},Ui(this.ctx,t.textDirection);let w=g+d;this.legendItems.forEach((v,y)=>{i.strokeStyle=v.fontColor,i.fillStyle=v.fontColor;let S=i.measureText(v.text).width,D=l.textAlign(v.textAlign||(v.textAlign=r.textAlign)),M=p+u+S,C=f.x,T=f.y;l.setWidth(this.width),_?y>0&&C+M+d>this.right&&(T=f.y+=w,f.line++,C=f.x=_t(o,this.left+d,this.right-n[f.line])):y>0&&T+w>this.bottom&&(C=f.x=C+e[f.line].width+d,f.line++,T=f.y=_t(o,this.top+E+d,this.bottom-e[f.line].height));let k=l.x(C);if(b(k,T,v),C=zr(D,C+p+u,_?C+M:this.right,t.rtl),x(l.x(C),T,v),_)f.x+=M+d;else if(typeof v.text!="string"){let A=c.lineHeight;f.y+=Dl(v,A)+d}else f.y+=w}),Ki(this.ctx,t.textDirection)}drawTitle(){let t=this.options,e=t.title,n=bt(e.font),i=Ct(e.padding);if(!e.display)return;let o=Pe(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=_t(t.align,h,this.right-u);else{let p=this.columnSizes.reduce((m,g)=>Math.max(m,g.height),0);d=c+_t(t.align,this.top,this.bottom-p-t.labels.padding-this._computeTitleHeight())}let f=_t(a,h,h+u);r.textAlign=o.textAlign(Mn(a)),r.textBaseline="middle",r.strokeStyle=e.color,r.fillStyle=e.color,r.font=n.string,ve(r,e.text,f,d,n)}_computeTitleHeight(){let t=this.options.title,e=bt(t.font),n=Ct(t.padding);return t.display?e.lineHeight+n.height:0}_getLegendItemAt(t,e){let n,i,o;if(Zt(t,this.left,this.right)&&Zt(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=Ct(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)}}},Us=class extends At{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=ct(n.text)?n.text.length:1;this._padding=Ct(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=_t(a,n,o),h=e+t,c=o-n):(r.position==="left"?(d=n+t,h=_t(a,i,e),l=nt*-.5):(d=o-t,h=_t(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);ve(t,e.text,0,0,n,{color:e.color,maxWidth:l,rotation:c,textAlign:Mn(e.align),textBaseline:"middle",translation:[r,a]})}};Ll={id:"title",_element:Us,start(s,t,e){Sf(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}},Nn=new WeakMap,Al={id:"subtitle",start(s,t,e){let n=new Us({ctx:s.ctx,options:e,chart:s});St.configure(s,n,e),St.addBox(s,n),Nn.set(s,n)},stop(s){St.removeBox(s,Nn.get(s)),Nn.delete(s)},beforeUpdate(s,t,e){let n=Nn.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}},zs={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=Ka(n,o);Jt(r.before,ce(Dt(a,"beforeLabel",this,o))),Jt(r.lines,Dt(a,"label",this,o)),Jt(r.after,ce(Dt(a,"afterLabel",this,o))),i.push(r)}),i}getAfterBody(t,e){return Ua(Dt(e.callbacks,"afterBody",this,t))}getFooter(t,e){let{callbacks:n}=e,i=Dt(n,"beforeFooter",this,t),o=Dt(n,"footer",this,t),r=Dt(n,"afterFooter",this,t),a=[];return a=Jt(a,ce(i)),a=Jt(a,ce(o)),a=Jt(a,ce(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))),ot(a,d=>{let h=Ka(t.callbacks,d);i.push(Dt(h,"labelColor",this,d)),o.push(Dt(h,"labelPointStyle",this,d)),r.push(Dt(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=zs[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=$a(this,n),c=Object.assign({},a,l),d=Wa(this.chart,n,c),h=ja(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}=ye(a),{x:u,y:f}=t,{width:p,height:m}=e,g,b,x,_,E,w;return o==="center"?(E=f+m/2,i==="left"?(g=u,b=g-r,_=E+r,w=E-r):(g=u+p,b=g+r,_=E-r,w=E+r),x=g):(i==="left"?b=u+Math.max(l,d)+r:i==="right"?b=u+p-Math.max(c,h)-r:b=this.caretX,o==="top"?(_=f,E=_-r,g=b-r,x=b+r):(_=f+m,E=_+r,g=b+r,x=b-r),w=_),{x1:g,x2:b,x3:x,y1:_,y2:E,y3:w}}drawTitle(t,e,n){let i=this.title,o=i.length,r,a,l;if(o){let c=Pe(n.rtl,this.x,this.width);for(t.x=Bn(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,is(t,{x:m,y:p,w:c,h:l,radius:b}),t.fill(),t.stroke(),t.fillStyle=r.backgroundColor,t.beginPath(),is(t,{x:g,y:p+1,w:c-2,h:l-2,radius:b}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(m,p,c,l),t.strokeRect(m,p,c,l),t.fillStyle=r.backgroundColor,t.fillRect(g,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=Pe(n.rtl,this.x,this.width),m=function(S){e.fillText(S,p.x(t.x+f),t.y+u/2),t.y+=u+o},g=p.textAlign(r),b,x,_,E,w,v,y;for(e.textAlign=r,e.textBaseline="middle",e.font=h.string,t.x=Bn(this,g,n),e.fillStyle=n.bodyColor,ot(this.beforeBody,m),f=a&&g!=="right"?r==="center"?c/2+d:c+2+d:0,E=0,v=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=zs[t.position].call(this,this._active,this._eventPosition);if(!r)return;let a=this._size=$a(this,t),l=Object.assign({},r,this._size),c=Wa(e,t,l),d=ja(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=Ct(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=n,this.drawBackground(o,t,i,e),Ui(t,e.textDirection),o.y+=r.top,this.drawTitle(o,t,e),this.drawBody(o,t,e),this.drawFooter(o,t,e),Ki(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=!As(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||!As(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=zs[o.position].call(this,t,e);return r!==!1&&(n!==r.x||i!==r.y)}};H(Hs,"positioners",zs);Rl={id:"tooltip",_element:Hs,positioners:zs,afterInit(s,t,e){e&&(s.tooltip=new Hs({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:Pl},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"]},Ol=Object.freeze({__proto__:null,Colors:Sl,Decimation:El,Filler:Ml,Legend:Tl,SubTitle:Al,Title:Ll,Tooltip:Rl}),Af=(s,t,e,n)=>(typeof t=="string"?(e=s.push(t)-1,n.unshift({index:e,label:t})):isNaN(t)&&(e=null),e);Rf=(s,t)=>s===null?null:vt(Math.round(s),0,t);cs=class extends ke{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:Pf(n,t,Q(e,t),this._addedLabels),Rf(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 Ya.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}};H(cs,"id","category"),H(cs,"defaults",{ticks:{callback:Ya}});fs=class extends ke{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=Wt(i),c=Wt(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=Of(i,o);return t.bounds==="ticks"&&Ei(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 ss(t,this.chart.options.locale,this.options.ticks.format)}},ds=class extends fs{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}};H(ds,"id","linear"),H(ds,"defaults",{ticks:{callback:ns.formatters.numeric}});Ks=s=>Math.floor(re(s)),Oe=(s,t)=>Math.pow(10,Ks(s)+t);hs=class extends ke{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){let n=fs.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===Oe(this.min,0)?Oe(this.min,-1):Oe(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(Oe(n,-1)),r(Oe(i,1)))),n<=0&&o(Oe(i,-1)),i<=0&&r(Oe(n,1)),this.min=n,this.max=i}buildTicks(){let t=this.options,e={min:this._userMin,max:this._userMax},n=If(e,this);return t.bounds==="ticks"&&Ei(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":ss(t,this.chart.options.locale,this.options.ticks.format)}configure(){let t=this.min;super.configure(),this._startValue=re(t),this._valueRange=re(this.max)-re(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(re(t)-this._startValue)/this._valueRange)}getValueForPixel(t){let e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}};H(hs,"id","logarithmic"),H(hs,"defaults",{ticks:{callback:ns.formatters.logarithmic,major:{enabled:!0}}});Ce=class extends fs{constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){let t=this._padding=Ct(vo(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/vo(this.options))}generateTickLabels(t){fs.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((e,n)=>{let i=lt(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?Nf(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=dt/(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);Gf(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=Ct(c.backdropPadding);t.fillRect(-r/2-h.left,-o-d.size/2-h.top,r+h.width,d.size+h.height)}ve(t,a.label,0,-o,d,{color:c.color,strokeColor:c.textStrokeColor,strokeWidth:c.textStrokeWidth})}),t.restore()}drawTitle(){}};H(Ce,"id","radialLinear"),H(Ce,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:ns.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),H(Ce,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),H(Ce,"descriptors",{angleLines:{_fallback:"grid"}});Qn={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}},Lt=Object.keys(Qn);Ee=class extends ke{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 rl._date(t.adapters.date);i.init(e),Ze(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:Ja(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=Ir(i,o,r);return this._unit=e.unit||(n.autoSkip?tl(e.minUnit,this.min,this.max,this._getLabelCapacity(o)):Xf(this,a.length,e.minUnit,this.min,this.max)),this._majorUnit=!n.major.enabled||this._unit==="year"?void 0:Qf(this._unit),this.initOffsets(i),t.reverse&&a.reverse(),sl(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||tl(o.minUnit,e,n,this._getLabelCapacity(e)),a=Q(i.ticks.stepSize,1),l=r==="week"?o.isoWeekday:!1,c=Ae(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+m)}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 lt(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(zn(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){let e=this._offsets,n=this.getDecimalForPixel(t)/e.factor-e.end;return zn(this._table,n*this._tableRange+this._minPos,!0)}};H(us,"id","timeseries"),H(us,"defaults",Ee.defaults);Il=Object.freeze({__proto__:null,CategoryScale:cs,LinearScale:ds,LogarithmicScale:hs,RadialLinearScale:Ce,TimeScale:Ee,TimeSeriesScale:us}),Jf=[ol,xl,Ol,Il]});var op={};So(op,{CardView:()=>ps,default:()=>Zn});module.exports=Zl(op);var rt=require("obsidian"),jl=qs(bs());var Jl=["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"],tc=[{label:"\u{1F1EA}\u{1F1FA} Schengen 90/180 (example)",scope:{countries:Jl},window:{type:"rolling",days:180},threshold:90,note:"Example rule \u2014 add your own in Settings \u2192 CSV Card View."}],ni={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:tc,showResidency:!0},Xs="xlsx-card-view";var Eo=qs(bs()),ko=require("obsidian"),Qs=["Image","image","Cover","cover","Poster","poster","Thumbnail","thumbnail","Thumb","thumb","Photo","photo","Picture","picture","Img","img"];function Zs(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 ko.TFile?s.vault.getResourcePath(o):null}var ec=15;function vs(s){return s>=1&&s<=ec}function ys(s){return s.replace(/[\\/:*?"<>|#^[\]]/g,"").replace(/\s+/g," ").trim().slice(0,100)}function Mo(s){return s.toLowerCase().replace(/[^\p{L}\p{N}/_-]+/gu,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Gt(s){var i,o;if(!s||!s.trim())return{headers:[],rows:[]};let t=Eo.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 We(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 Do(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 kt(s){return s.split(/[\s_-]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function To(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=sc(e,t);return i&&i!==e&&i!=="\u2014"?i:""}function sc(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 Lo(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 Ao(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 Po(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));cC.remove());let r=document.body.createDiv({cls:"csv-select-picker"});r.style.position="fixed",r.style.zIndex="9999";let a=()=>{let C=s.getBoundingClientRect(),T=r.offsetHeight||280,k=C.bottom+4+T>window.innerHeight&&C.top-4-T>0;r.style.left=C.left+"px",r.style.top=k?C.top-4-T+"px":C.bottom+4+"px"};a();let l=C=>{!r.contains(C.target)&&C.target!==s&&d()},c=()=>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=C=>C.split(",").map(T=>T.trim()).filter(Boolean),m=new Set(f?p(t):[]),g=()=>n([...m].join(", ")),b=f?Array.from(new Set(e.flatMap(p))):Array.from(new Set(e.filter(Boolean))),x=[],_=0,E=()=>{u.querySelectorAll(".csv-picker-item").forEach((C,T)=>{C.toggleClass("csv-picker-item--hover",T===_),T===_&&C.scrollIntoView({block:"nearest"})})},w=C=>{if(!f){n(C.isClear?"":C.value),d();return}C.isClear?m.clear():(m.has(C.value)?m.delete(C.value):m.add(C.value),C.isAdd&&!b.includes(C.value)&&b.push(C.value)),g(),C.isAdd?(h.value="",S("")):S(h.value)},v=C=>f?m.has(C):C===t,y=()=>f?m.size>0:!!t,S=C=>{u.empty(),x=[];let T=C?b.filter(k=>k.toLowerCase().includes(C.toLowerCase())):b;if(y()){x.push({value:"",isClear:!0});let k=u.createDiv({cls:"csv-picker-item csv-picker-clear"});k.setText(f?"\u2715 Clear all":"\u2715 Clear"),k.addEventListener("mousedown",A=>{A.preventDefault(),w({value:"",isClear:!0})})}if(T.forEach(k=>{x.push({value:k});let A=u.createDiv({cls:`csv-picker-item ${v(k)?"active":""}`});A.setText(f?`${m.has(k)?"\u2713 ":""}${k}`:k),A.addEventListener("mousedown",P=>{P.preventDefault(),w({value:k})})}),C&&!b.some(k=>k.toLowerCase()===C.toLowerCase())){x.push({value:C,isAdd:!0});let k=u.createDiv({cls:"csv-picker-item csv-picker-add"});k.setText(`+ Add "${C}"`),k.addEventListener("mousedown",A=>{A.preventDefault(),w({value:C,isAdd:!0})})}!T.length&&!C&&u.createDiv({cls:"csv-picker-empty",text:"No options yet. Type to add."}),_=Math.min(_,Math.max(x.length-1,0)),E()};f&&r.createEl("button",{cls:"csv-picker-done",text:"Done"}).addEventListener("mousedown",C=>{C.preventDefault(),d()}),S(""),a(),h.addEventListener("input",()=>{_=0,S(h.value),a()});let D=typeof window!="undefined"&&((M=window.matchMedia)==null?void 0:M.call(window,"(pointer: coarse)").matches);setTimeout(()=>{document.addEventListener("mousedown",l),D||(window.addEventListener("scroll",c,!0),window.addEventListener("resize",d))},0),h.addEventListener("keydown",C=>{if(C.key==="Escape"){d();return}if(C.key==="ArrowDown"){C.preventDefault(),x.length&&(_=(_+1)%x.length,E());return}if(C.key==="ArrowUp"){C.preventDefault(),x.length&&(_=(_-1+x.length)%x.length,E());return}if(C.key==="Enter")if(C.preventDefault(),x[_])w(x[_]);else{let T=h.value.trim();T&&(n(T),d())}})}function Ro(s,t,e){return!s[t]||t===e||(s[e]||(s[e]=s[t]),delete s[t]),s}var Ht=require("obsidian");var nc={source:["confirmed","inferred","conflict"],resolved:["yes","no"]};function Oo(s){var t;return(t=nc[s.trim().toLowerCase()])!=null?t:null}function Js(s){return/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(s.trim())}var Fo=/^\d{4}-\d{2}-\d{2}$/;function sn(s,t,e,n){let i=Js(t)&&(e===""||Fo.test(e)),o=s.createEl("input",{cls:n,type:i?"date":"text",value:e});i||(o.placeholder=t);let r=Oo(t);if(r){let a=`csv-dl-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-${Math.random().toString(36).slice(2,7)}`,l=s.createEl("datalist");l.id=a,r.forEach(c=>l.createEl("option",{value:c})),o.setAttr("list",a)}return o}var je=class extends Ht.Modal{constructor(t,e,n,i,o,r,a={},l=()=>!1){super(t),this.headers=e,this.isNotesCol=n,this.isSelectCol=i,this.getColumnValues=o,this.onSubmit=r,this.optionPresets=a,this.isBooleanCol=l}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.headers.find(d=>["title","name"].includes(d.toLowerCase())),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:kt(d),cls:"csv-modal-label"});let u=(m=this.optionPresets[d])!=null?m:[],f=!this.isSelectCol(d)&&!It(d)&&!Js(d)&&vs(this.getColumnValues(d).length),p=!this.isNotesCol(d)&&(u.length>0||this.isSelectCol(d)&&!It(d)||f);if(this.isBooleanCol(d)){n[d]="0";let g=h.createDiv({cls:"csv-toggle"});g.createDiv({cls:"csv-toggle-knob"}),g.addEventListener("click",()=>{let b=!g.hasClass("is-on");g.toggleClass("is-on",b),n[d]=b?"1":"0"})}else if(this.isNotesCol(d)){let g=h.createEl("textarea",{cls:"csv-modal-textarea",placeholder:"Markdown supported\u2026"});g.addEventListener("input",()=>{n[d]=g.value})}else if(p){let g="__custom__",b=[];[...u,...this.getColumnValues(d)].forEach(E=>{let w=(E!=null?E:"").trim();w&&!b.some(v=>v.toLowerCase()===w.toLowerCase())&&b.push(w)});let x=h.createEl("select",{cls:"csv-modal-select"});x.createEl("option",{text:"\u2014",value:""}),b.forEach(E=>x.createEl("option",{text:E,value:E})),x.createEl("option",{text:"+ Custom\u2026",value:g});let _=h.createEl("input",{cls:"csv-modal-input csv-modal-custom",type:"text",placeholder:`Custom ${kt(d).toLowerCase()}`});_.hide(),_.addEventListener("input",()=>{n[d]=_.value}),_.addEventListener("keydown",E=>{E.key==="Enter"&&c()}),x.addEventListener("change",()=>{x.value===g?(_.show(),_.focus(),n[d]=_.value):(_.hide(),n[d]=x.value)})}else if(this.isSelectCol(d)){let b=h.createDiv({cls:"csv-modal-select-wrap"}).createDiv({cls:"csv-select-chip empty"});b.setText("\u2014 click to select \u2014"),b.addEventListener("click",x=>{x.stopPropagation(),Ot(b,n[d],this.getColumnValues(d),_=>{n[d]=_,b.setText(_||"\u2014 click to select \u2014"),b.toggleClass("empty",!_)},t,{multi:It(d)})})}else{let g=sn(h,d,"","csv-modal-input");if(g.addEventListener("input",()=>{n[d]=g.value}),g.addEventListener("keydown",b=>{b.key==="Enter"&&c()}),d===i&&o.size){let b=h.createDiv({cls:"csv-modal-dup-hint"});b.hide(),g.addEventListener("input",()=>{let x=o.get(g.value.trim().toLowerCase());x?(b.setText(`\u26A0 \u201C${x}\u201D is already in this file`),b.show()):b.hide()})}}});let r=t.createDiv({cls:"csv-modal-btns"});r.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),r.createEl("button",{text:"Add entry",cls:"csv-modal-submit"}).addEventListener("click",()=>c());let c=()=>{if(!Object.values(n).some(h=>h.trim())){new Ht.Notice("Fill in at least one field.");return}this.onSubmit(n),this.close()}}onClose(){this.contentEl.empty()}},Ue=class extends Ht.Modal{constructor(e,n,i,o,r,a,l,c,d,h){super(e);this.vvHandler=null;this.row={...n},this.notesCol=i,this.headers=o,this.filePath=r,this.renderComponent=new Ht.Component,this.isNotesCol=a,this.isSelectCol=l,this.getColumnValues=c,this.onSave=d,this.onDelete=h,this.modalEl.addClass("csv-note-expander-modal")}onOpen(){var p,m,g,b,x;this.renderComponent.load();let{contentEl:e}=this;e.empty(),e.addClass("csv-note-expander");let n=window.visualViewport;if(n){let _=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${n.height}px`)};_(),n.addEventListener("resize",_),n.addEventListener("scroll",_),this.vvHandler=_}let i=e.createDiv({cls:"csv-expander-header"});i.createDiv({cls:"csv-expander-title",text:(m=this.row[(p=this.headers.find(_=>["title","name","Title","Name"].includes(_)))!=null?p:this.headers[0]])!=null?m:"\u2014"});let o=i.createDiv({cls:"csv-expander-header-btns"}),r=e.createDiv({cls:"csv-expander-fields"}),a=this.headers.find(_=>["title","name","Title","Name"].includes(_)),l=this.headers.find(_=>["author","Author","director","Director","artist","Artist","creator","Creator"].includes(_));this.headers.forEach(_=>{if(this.isNotesCol(_))return;let E=r.createDiv({cls:"csv-expander-field-row"});if(E.createDiv({cls:"csv-expander-field-label",text:kt(_)}),this.isSelectCol(_)||!It(_)&&!Js(_)&&vs(this.getColumnValues(_).length)){let v=E.createDiv({cls:`csv-select-chip ${this.row[_]?"":"empty"}`});v.setText(this.row[_]||"\u2014"),v.addEventListener("click",y=>{y.stopPropagation(),Ot(v,this.row[_],this.getColumnValues(_),S=>{this.row[_]=S,v.setText(S||"\u2014"),v.toggleClass("empty",!S)},e,{multi:It(_)})})}else{let v=E.createDiv({cls:"csv-expander-field-value",text:this.row[_]||"\u2014"});v.addEventListener("click",()=>{var D;v.empty();let y=sn(v,_,(D=this.row[_])!=null?D:"","csv-inline-input");y.focus(),y.type==="text"&&y.select();let S=()=>{this.row[_]=y.value,v.empty(),v.setText(y.value||"\u2014")};y.addEventListener("blur",S),y.addEventListener("keydown",M=>{M.key==="Enter"&&y.blur(),M.key==="Escape"&&(v.empty(),v.setText(this.row[_]||"\u2014"))})})}});let c=!1,d=this.notesCol&&(g=this.row[this.notesCol])!=null?g:"",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 w=e.createDiv({cls:"csv-expander-editor"});w.style.display="none";let v=()=>{E.empty(),d.trim()?Ht.MarkdownRenderer.render(this.app,d,E,this.filePath,this.renderComponent):E.createDiv({cls:"csv-notes-empty",text:"+ Add note"})};v(),h=w.createEl("textarea",{cls:"csv-expander-textarea"}),h.value=d,h.addEventListener("input",()=>{d=h.value});let y=()=>{c||(c=!0,E.style.display="none",w.style.display="flex",h.value=d,h.focus())},S=()=>{c&&(c=!1,w.style.display="none",E.style.display="",d=h.value,v())};E.addEventListener("click",D=>{if(D.target.closest("a, button, input, textarea, [contenteditable]"))return;let C=window.getSelection();C&&C.toString().length>0||y()}),h.addEventListener("keydown",D=>{D.key==="Escape"&&(D.preventDefault(),h.blur())}),h.addEventListener("blur",S)}let u=e.createDiv({cls:"csv-expander-footer"});if(this.onDelete){let _=String((x=this.row[(b=this.headers.find(E=>["title","name","Title","Name"].includes(E)))!=null?b:this.headers[0]])!=null?x:"").trim();u.createEl("button",{cls:"csv-expander-delete-btn",text:"Delete"}).addEventListener("click",()=>{let E=_||"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 tn=class extends Ht.Modal{constructor(t,e,n,i,o,r,a){super(t),this.headers=e,this.filePath=n,this.current={...i,habitColumns:i.habitColumns?[...i.habitColumns]:void 0},this.autoDetectedHabits=o,this.availableModes=r,this.onSave=a}onOpen(){var S,D,M;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="\u2014 use global default \u2014",i=[n,...this.headers],o=(C,T,k)=>{let A=e.createDiv({cls:"csv-modal-row"});A.createEl("label",{text:C,cls:"csv-modal-label"});let P=A.createEl("select",{cls:"csv-modal-select"});i.forEach(O=>{let z=P.createEl("option",{text:O,value:O});(T!=null?T:n)===O&&(z.selected=!0)}),P.addEventListener("change",()=>k(P.value===n?void 0:P.value))};o("Category column (kanban grouping)",this.current.categoryColumn,C=>{this.current.categoryColumn=C}),o("Status column (row subgroups)",this.current.statusColumn,C=>{this.current.statusColumn=C}),o("Notes column",this.current.notesColumn,C=>{this.current.notesColumn=C});let r=e.createDiv({cls:"csv-modal-row"});r.createEl("label",{text:"Habit columns (dashboard)",cls:"csv-modal-label"});let a=r.createEl("p",{cls:"csv-modal-hint",text:"Select columns to track as habits. Auto-detected columns with binary values (0/1) are pre-selected."}),l=r.createDiv({cls:"csv-modal-checkbox-grid"}),c=new Set((S=this.current.habitColumns)!=null?S:this.autoDetectedHabits);this.headers.forEach(C=>{let T=l.createEl("label",{cls:"csv-modal-checkbox-label"}),k=T.createEl("input",{type:"checkbox"});k.checked=c.has(C),this.autoDetectedHabits.includes(C)&&!this.current.habitColumns&&T.addClass("auto-detected"),T.createSpan({text:C}),k.addEventListener("change",()=>{this.current.habitColumns||(this.current.habitColumns=[...this.autoDetectedHabits]),k.checked?this.current.habitColumns.includes(C)||this.current.habitColumns.push(C):this.current.habitColumns=this.current.habitColumns.filter(A=>A!==C)})});let d=e.createDiv({cls:"csv-modal-row"});d.createEl("label",{text:"Card fields (Library / Kanban)",cls:"csv-modal-label"}),d.createEl("p",{cls:"csv-modal-hint",text:"Columns shown under each card title. Rating renders as stars, theme/tag columns as pills. Leave all unchecked for title-only cards."});let h=d.createDiv({cls:"csv-modal-checkbox-grid"}),u=C=>this.headers.find(T=>C.some(k=>k.toLowerCase()===T.toLowerCase())),f=[u(["Author","Authors","Director","Artist","Creator","By"]),u(["Year","Date","Released"]),u(["Rating","Score","Score /5","Stars"]),u(["Theme","Tags","Tag","Mood"])].filter(C=>!!C),p=new Set((D=this.current.cardFields)!=null?D:f),m=!!this.current.cardFields;this.headers.forEach(C=>{let T=h.createEl("label",{cls:"csv-modal-checkbox-label"}),k=T.createEl("input",{type:"checkbox"});k.checked=p.has(C),f.includes(C)&&!m&&T.addClass("auto-detected"),T.createSpan({text:C}),k.addEventListener("change",()=>{this.current.cardFields||(this.current.cardFields=[...f]),k.checked?this.current.cardFields.includes(C)||this.current.cardFields.push(C):this.current.cardFields=this.current.cardFields.filter(A=>A!==C)})});let g="\u2014 title / primary field \u2014",b=e.createDiv({cls:"csv-modal-row"});b.createEl("label",{text:"Anki card front",cls:"csv-modal-label"}),b.createEl("p",{cls:"csv-modal-hint",text:"Column used as the front of each card when syncing to Anki. Other columns become the back."});let x=b.createEl("select",{cls:"csv-modal-select"});[g,...this.headers].forEach(C=>{var k;let T=x.createEl("option",{text:C,value:C});((k=this.current.ankiFrontCol)!=null?k:g)===C&&(T.selected=!0)}),x.addEventListener("change",()=>{this.current.ankiFrontCol=x.value===g?void 0:x.value});let _=e.createDiv({cls:"csv-modal-row"});_.createEl("label",{text:"Default view",cls:"csv-modal-label"});let E=_.createEl("select",{cls:"csv-modal-select"}),w=[["\u2014 use global default \u2014",""],...this.availableModes.map(C=>[C.label,C.id])],v=(M=this.current.defaultMode)!=null?M:"";v&&!this.availableModes.some(C=>C.id===v)&&w.push([`${v} (no longer available)`,v]),w.forEach(([C,T])=>{let k=E.createEl("option",{text:C,value:T});v===T&&(k.selected=!0)}),E.addEventListener("change",()=>{this.current.defaultMode=E.value?E.value:void 0});let y=t.createDiv({cls:"csv-modal-btns"});y.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),y.createEl("button",{text:"Save",cls:"csv-modal-submit"}).addEventListener("click",()=>{this.onSave(this.current),this.close()})}onClose(){this.contentEl.empty()}},en=class extends Ht.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 ii=195,ic={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"},oc={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"]},Io={AF:"Africa",AN:"Antarctica",AS:"Asia",EU:"Europe",NA:"N. America",OC:"Oceania",SA:"S. America"},Vo={};for(let[s,t]of Object.entries(oc))for(let e of t)Vo[e]=s;function wt(s){return ic[s]||s}function $t(s){return!s||s.length!==2?"":String.fromCodePoint(...s.toUpperCase().split("").map(t=>t.charCodeAt(0)+127397))}function Vt(s){if(!s||s.indexOf("?")!==-1)return null;let t=new Date(s+"T12:00:00Z");return isNaN(t.getTime())?null:t}function xs(s){let t=Vt(s.date_entered),e=Vt(s.date_left);return!t||!e?0:Math.max(Math.round((e.getTime()-t.getTime())/864e5),1)}function No(s,t=new Date){let e=t.getTime(),n=null,i=-1/0;for(let o of s){let r=Vt(o.date_entered);if(!(!r||r.getTime()>e)){if(o.date_left.trim()!==""){let a=Vt(o.date_left);if(!a||a.getTime()i&&(n=o,i=r.getTime())}}return n}function Bo(s){let t=b=>{var x,_,E,w,v,y,S,D;return{date_entered:(x=b.date_entered)!=null?x:"",date_left:(_=b.date_left)!=null?_:"",country:((E=b.country)!=null?E:"").trim().toUpperCase(),city:(w=b.city)!=null?w:"",visa_status:(v=b.visa_status)!=null?v:"",notes:(y=b.notes)!=null?y:"",source:((S=b.source)!=null?S:"").trim().toLowerCase(),resolved:(D=b.resolved)!=null?D:"",_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=Vt(b.date_entered),_=Vt(b.date_left);x&&_&&r.push([x.getTime(),_.getTime()])}let a=b=>{let x=Vt(b.date_entered),_=Vt(b.date_left);if(!x||!_)return!1;let E=x.getTime(),w=_.getTime();return r.some(([v,y])=>E<=y&&w>=v)},l=i.filter(b=>Vt(b.date_entered)&&Vt(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)+xs(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))),m=p.reduce((b,x)=>b+x.days,0),g=new Set;for(let b of c){let x=Vo[b];x&&g.add(x)}return{confirmed:n,inferred:i,conflicts:o,inferredVisible:l,confRanges:r,confirmedCountries:c,inferredOnlyCountries:h,allCountries:u,countryDays:p,totalConfirmedDays:m,visitedContinents:g,worldPct:Math.round(c.size/ii*100)}}var oi=864e5;function zo(s){if(!s||s.indexOf("?")!==-1)return null;let t=Date.parse(s+"T00:00:00Z");return isNaN(t)?null:t}function rc(s,t,e,n){let i=Math.max(s,e),o=Math.min(t,n);return o<=i?0:Math.round((o-i)/oi)}function ac(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*oi,end:t+oi,label:`in last ${n} days`}}function Ho(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=ac(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=zo(f.date_entered),m=zo(f.date_left);p===null||m===null||(a+=rc(p,m,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 $o=["#c9a96e","#4a6fa5","#5ba06e","#a05b8a","#6ea0a0","#a0855b","#7a6ea0","#a06e6e","#6e8fa0","#a09e5b"],lc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function cc(){let s=new Map,t=0;return e=>(s.has(e)||s.set(e,$o[t++%$o.length]),s.get(e))}function dc(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 ri(s){let t=xs(s);return t?`${t}d`:"\u2014"}function Ke(s){return s||"\u2014"}function Cs(s){return s.createDiv({cls:"csv-tv-table-wrap"}).createEl("table",{cls:"csv-tv-table"})}function _s(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=sn(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 Wo(s,t,e,n=()=>{},i=null,o=()=>{}){let r=Bo(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(dc(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&&(fc(u,r,l,()=>d(null)),u.scrollIntoView({behavior:"smooth",block:"nearest"}))},d=f=>{l=f&&f!==l?f:null,c()};hc(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&&pc(a,r.confirmed,i),gc(a,r,d),mc(a,r,d),bc(a,r,n);try{let f=await e();h.empty(),f?uc(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 hc(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/ii*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=>Io[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=xs(c);d>a&&(a=d,r=c)}if(r){let c=r.date_entered.slice(0,4);n("Longest trip",`${a}d`,`${$t(r.country)} ${wt(r.country)}${c?` \xB7 ${c}`:""}`)}let l=No(t.confirmed);if(l){let c=Vt(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 ${$t(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 uc(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 fc(s,t,e,n){var g,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:$t(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=(g=t.countryDays.find(x=>x.iso===e))==null?void 0:g.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=nn([...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=Cs(i),p=f.createEl("thead").createEl("tr");["","Entered","Left","Days","City","Visa"].forEach(x=>p.createEl("th",{text:x}));let m=f.createEl("tbody");for(let{r:x,inf:_}of u){let E=m.createEl("tr");E.createEl("td",{text:_?"\u{1F4F7}":"",cls:"csv-tv-flag",attr:_?{"data-tip":"Photo-inferred"}:{}}),E.createEl("td",{text:Ke(x.date_entered)}),E.createEl("td",{text:Ke(x.date_left)}),E.createEl("td",{text:ri(x)}),E.createEl("td",{text:x.city}),E.createEl("td",{text:x.visa_status})}}function pc(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=Ho(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 gc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Countries visited"});let n=Cs(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:$t(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($t).join(" ")})}}function mc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Timeline"});let n=cc(),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,m=new Set;for(let _ of o.get(c)){if(m.add(_.country),_._inf)continue;let E=Math.max(new Date(_.date_entered+"T12:00:00Z").getTime(),d),w=Math.min(new Date(_.date_left+"T12:00:00Z").getTime(),h);E<=w&&(p+=Math.max(Math.round((w-E)/864e5)+1,1))}let g=f.createDiv({cls:"csv-tv-tl-label"});g.createSpan({text:String(c)}),g.createSpan({cls:"csv-tv-tl-sub",text:`${p?`${p}d \xB7 `:""}${m.size} ${m.size===1?"country":"countries"}`});let b=f.createDiv({cls:"csv-tv-month-row"});lc.forEach(_=>b.createDiv({cls:"csv-tv-month-tick",text:_}));let x=f.createDiv({cls:"csv-tv-track"});for(let _ of o.get(c)){let E=Math.max(new Date(_.date_entered+"T12:00:00Z").getTime(),d),w=Math.min(new Date(_.date_left+"T12:00:00Z").getTime(),h);if(E>w)continue;let v=(E-d)/u*100,y=Math.max((w-E+864e5)/u*100,.5),S=n(_.country),D=x.createDiv({cls:`csv-tv-seg${_._inf?" csv-tv-seg-inf":""}`});D.style.left=`${v}%`,D.style.width=`${y}%`,_._inf?(D.style.borderColor=S,D.style.background=S+"22",D.style.color=S):D.style.background=S,D.setAttr("data-iso",_.country),D.setAttr("data-tip",`${wt(_.country)} ${_.date_entered} \u2192 ${_.date_left} (${xs(_)}d)${_.visa_status?" ["+_.visa_status+"]":""}${_._inf?" [photo]":""}`),D.addEventListener("click",()=>e(_.country)),y>4?D.createSpan({cls:"csv-tv-seg-lbl",text:`${$t(_.country)} ${_.country}`}):y>2&&D.createSpan({cls:"csv-tv-seg-lbl",text:$t(_.country)})}}a.createDiv({cls:"csv-tv-tl-legend"}).setText("Confirmed (solid) \xB7 Photo inferred (outlined)")}function nn(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 bc(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=Cs(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 nn(t.confirmed)){let a=o.createEl("tr");a.createEl("td",{text:$t(r.country),cls:"csv-tv-flag"}),a.createEl("td",{text:wt(r.country)}),_s(a.createEl("td"),r._src,"date_entered",e),_s(a.createEl("td"),r._src,"date_left",e),a.createEl("td",{text:ri(r)}),_s(a.createEl("td"),r._src,"city",e),_s(a.createEl("td"),r._src,"visa_status",e),_s(a.createEl("td"),r._src,"notes",e)}if(t.inferred.length){let r=s.createEl("details",{cls:"csv-tv-details"});r.createEl("summary",{text:`\u{1F4F7} Photo inferred trips (${t.inferred.length})`});let a=Cs(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 nn(t.inferred)){let h=c.createEl("tr");h.createEl("td",{text:$t(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:wt(d.country)}),h.createEl("td",{text:Ke(d.date_entered)}),h.createEl("td",{text:Ke(d.date_left)}),h.createEl("td",{text:ri(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=Cs(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 nn(t.conflicts)){let h=c.createEl("tr");h.createEl("td",{text:$t(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:d.country}),h.createEl("td",{text:`${Ke(d.date_entered)} \u2192 ${Ke(d.date_left)}`}),h.createEl("td",{text:d.notes})}}}var Ft=require("obsidian"),on=class extends Ft.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 Ft.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 Ft.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 Ft.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 Ft.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 Ft.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 Ft.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 Ft.Setting(t).setName("Reset column widths").addButton(n=>n.setButtonText("Reset").onClick(async()=>{this.plugin.settings.columnWidths={},await this.plugin.saveSettings(),new Ft.Notice("Column widths reset.")})),new Ft.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,_,E,w,v;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=(y,S,D,M="")=>{let C=u.createDiv({cls:"csv-rr-field"});C.createEl("label",{text:y});let T=C.createEl("input",{type:"text",value:S});M&&(T.placeholder=M),T.addEventListener("input",()=>{D(T.value),n()})},p=(b=r.scope.countries)!=null?b:r.scope.country?[r.scope.country]:[];f("Countries (ISO-2, comma)",p.join(", "),y=>{r.scope={countries:y.split(",").map(S=>S.trim().toUpperCase()).filter(Boolean)}},"US, GB");let m=u.createDiv({cls:"csv-rr-field"});m.createEl("label",{text:"Window"});let g=m.createEl("select");[["calendar-year","Calendar year"],["rolling","Rolling N days"],["all-time","All time"]].forEach(([y,S])=>{let D=g.createEl("option",{text:S,value:y});r.window.type===y&&(D.selected=!0)}),g.addEventListener("change",()=>{r.window={type:g.value,days:r.window.days},n(),this.renderResidencyRules(t)}),r.window.type==="rolling"&&f("Rolling days",String((x=r.window.days)!=null?x:180),y=>{let S=parseInt(y,10);r.window.days=isNaN(S)?void 0:S},"180"),f("Threshold (days)",String(r.threshold),y=>{let S=parseInt(y,10);r.threshold=isNaN(S)?0:S},"183"),f("Exempt visas (comma)",((E=(_=r.exempt)==null?void 0:_.visa_status)!=null?E:[]).join(", "),y=>{let S=y.split(",").map(D=>D.trim()).filter(Boolean);r.exempt=S.length?{visa_status:S}:void 0},"F-1, J-1"),f("On-exceed label",(w=r.onExceed)!=null?w:"",y=>{r.onExceed=y||void 0},"tax resident"),f("Note",(v=r.note)!=null?v:"",y=>{r.note=y||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 de=require("obsidian"),jo=qs(bs());async function Uo(s,t,e,n){var G,$;let i=t.split(` +`).map(L=>L.trim()).filter(Boolean),o="";for(let L of i)if(L.startsWith("file:")){o=L.replace("file:","").trim();break}if(!o){e.createEl("p",{text:"Error: No file specified. Use: file: yourfile.csv",cls:"csv-add-error"});return}let r=s.vault.getAbstractFileByPath(n.sourcePath),a=($=(G=r==null?void 0:r.parent)==null?void 0:G.path)!=null?$:"",l=We(o,a),c=s.vault.getAbstractFileByPath(l);if(!c||!(c instanceof de.TFile)){e.createEl("p",{text:`Error: File not found: ${l}`,cls:"csv-add-error"});return}let d=[],h=[];try{let L=await s.vault.read(c),V=Gt(L);d=V.headers,h=V.rows}catch(L){e.createEl("p",{text:`Error reading file: ${L}`,cls:"csv-add-error"});return}if(!d.length){e.createEl("p",{text:"Error: No columns found in file",cls:"csv-add-error"});return}let u=["0","1","true","false","yes","no",""],f=L=>{let V=h.map(W=>{var j;return((j=W[L])!=null?j:"").toLowerCase().trim()});return V.length>0&&V.every(W=>u.includes(W))},p=L=>{let V=L.toLowerCase();if(["date","day","datum"].includes(V))return!0;let W=h.slice(0,5).map(j=>{var U;return(U=j[L])!=null?U:""});return W.length>0&&W.every(j=>/^\d{4}-\d{2}-\d{2}$/.test(j))},m=L=>{let V=L.toLowerCase();return["notes","note","comments","description","journal"].includes(V)},g=d.filter(L=>f(L)&&!p(L)),b=d.filter(L=>p(L)),x=d.filter(L=>m(L)),_=d.filter(L=>!g.includes(L)&&!b.includes(L)&&!x.includes(L)),E=e.createDiv({cls:"csv-add-form csv-add-compact"}),w=E.createEl("button",{cls:"csv-add-trigger",text:"+ New entry"});w.style.display="none";let v=E.createDiv({cls:"csv-add-card"}),y=v.createDiv({cls:"csv-add-card-header"});y.createEl("span",{cls:"csv-add-card-title",text:"New entry"});let S=y.createEl("button",{cls:"csv-add-card-close",text:"\xD7"}),D=v.createDiv({cls:"csv-add-rows"}),M={},C={},T=(L,V)=>{let W=D.createDiv({cls:`csv-add-row csv-add-row-${V}`});return W.createEl("span",{cls:"csv-add-row-label",text:kt(L)}),W};b.forEach(L=>{let W=T(L,"date").createEl("input",{cls:"csv-add-row-control",type:"date"});W.value=new Date().toISOString().split("T")[0],M[L]=W}),g.forEach(L=>{C[L]=!1;let W=T(L,"toggle").createEl("label",{cls:"csv-add-switch"}),j=W.createEl("input",{type:"checkbox",cls:"csv-add-switch-input"});W.createEl("span",{cls:"csv-add-switch-track"}),j.addEventListener("change",()=>{C[L]=j.checked}),M[L]=j}),_.forEach(L=>{let V=T(L,"field"),W=new Set(h.map(j=>{var U;return((U=j[L])!=null?U:"").trim()}).filter(Boolean));if(vs(W.size)){let j=V.createEl("select",{cls:"csv-add-row-control"});j.createEl("option",{text:"\u2014",value:""}),Array.from(W).sort().forEach(F=>j.createEl("option",{text:F,value:F})),j.createEl("option",{text:"+ Custom",value:"__custom__"});let U=D.createDiv({cls:"csv-add-row csv-add-row-custom"});U.style.display="none";let B=U.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:`Custom ${kt(L).toLowerCase()}`});D.insertBefore(U,V.nextSibling),j.addEventListener("change",()=>{U.style.display=j.value==="__custom__"?"flex":"none",j.value==="__custom__"&&B.focus()}),M[L]=j,M[`${L}__custom`]=B}else M[L]=V.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:kt(L)})}),x.forEach(L=>{let V=D.createDiv({cls:"csv-add-row csv-add-row-notes"});V.createEl("span",{cls:"csv-add-row-label",text:kt(L)}),M[L]=V.createEl("textarea",{cls:"csv-add-row-textarea",placeholder:"Optional notes\u2026"})});let k=v.createEl("button",{text:"Add",cls:"csv-add-submit"}),A=y.querySelector(".csv-add-card-title"),P=()=>{if(!b.length)return;let L=M[b[0]];if(!L)return;let V=L.value,W=h.find(j=>j[b[0]]===V);A&&A.setText(W?`Updating ${V}`:"New entry"),v.classList.toggle("is-updating",!!W),k.setText(W?"Update":"Add"),g.forEach(j=>{var I;let U=M[j];if(!U)return;let B=((I=W==null?void 0:W[j])!=null?I:"").toLowerCase().trim(),F=B==="1"||B==="true"||B==="yes";U.checked=F,C[j]=F}),[..._,...x].forEach(j=>{var F,I;let U=M[j];if(!U)return;let B=(F=W==null?void 0:W[j])!=null?F:"";if(U instanceof HTMLSelectElement)if(Array.from(U.options).find(R=>R.value===B)){U.value=B;let R=(I=M[`${j}__custom`])==null?void 0:I.closest(".csv-add-row-custom");R&&(R.style.display="none")}else U.value="";else U instanceof HTMLTextAreaElement,U.value=B})};if(P(),b.length){let L=M[b[0]];L==null||L.addEventListener("change",P)}let O=()=>{v.style.display="block",w.style.display="none";let L=v.querySelector(".csv-add-row-control");L==null||L.focus()},z=()=>{v.style.display="none",w.style.display=""};w.addEventListener("click",O),S.addEventListener("click",z),k.addEventListener("click",async()=>{let L={};d.forEach(I=>{var N,R,Y,K;g.includes(I)?L[I]=C[I]?"1":"0":M[I]instanceof HTMLSelectElement&&M[I].value==="__custom__"?L[I]=(R=(N=M[`${I}__custom`])==null?void 0:N.value)!=null?R:"":M[I]instanceof HTMLTextAreaElement?L[I]=M[I].value:L[I]=(K=(Y=M[I])==null?void 0:Y.value)!=null?K:""});let V=b.length>0&&b.some(I=>{var N;return((N=L[I])!=null?N:"").trim()}),W=[..._,...x].some(I=>{var N;return((N=L[I])!=null?N:"").trim()}),j=g.some(I=>C[I]);if(!V&&!W&&!j){new de.Notice("Please fill at least one field");return}let U=[];try{let I=await s.vault.read(c);U=Gt(I).rows}catch(I){new de.Notice(`Error reading file: ${I}`);return}let B=!1,F=-1;if(b.length>0){let I=b[0],N=L[I];if(F=U.findIndex(R=>R[I]===N),F>=0){B=!0;let R=U[F];d.forEach(Y=>{var K;(g.includes(Y)||((K=L[Y])!=null?K:"").trim())&&(R[Y]=L[Y])})}else U.push(L)}else U.push(L);try{let I=jo.default.unparse(U,{columns:d});await s.vault.modify(c,I),new de.Notice(B?`Updated entry for ${L[b[0]]||""}`:`Added entry to ${c.basename}`),h.length=0,h.push(...U),b.length>0?P():(g.forEach(N=>{C[N]=!1;let R=M[N];R&&(R.checked=!1)}),[..._,...x].forEach(N=>{let R=M[N];R instanceof HTMLSelectElement?R.selectedIndex=0:(R instanceof HTMLTextAreaElement||R)&&(R.value="");let Y=M[`${N}__custom`];if(Y){Y.value="";let K=Y.closest(".csv-add-row-custom");K&&(K.style.display="none")}})),setTimeout(async()=>{let N=s.vault.getAbstractFileByPath(n.sourcePath);if(N instanceof de.TFile){let R=s.workspace.activeLeaf;R&&await R.openFile(N,{state:{mode:"preview"}})}},300)}catch(I){new de.Notice(`Error saving: ${I}`)}})}function rn(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 m=b=>{c.style.width=Math.max(60,f+b.clientX-u)+"px"},g=b=>{s.settings.columnWidths[l]=Math.max(60,f+b.clientX-u),h.removeEventListener("pointermove",m),h.removeEventListener("pointerup",g),s.persistSettings()};h.addEventListener("pointermove",m),h.addEventListener("pointerup",g)})}),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,m;let f=c.createEl("td");if(s.isNotesCol(u)){f.addClass("csv-table-notes-cell");let g=((p=l[u])!=null?p:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").split(` +`).filter(_=>_.trim()).slice(0,3).join(" \xB7 "),b=g?g.slice(0,200)+(g.length>200?"\u2026":""):"+ Add note",x=f.createSpan({text:b});g||x.addClass("csv-table-notes-empty"),f.title="Click to open note",f.addEventListener("click",_=>{_.stopPropagation(),s.openNoteExpander(l,u)})}else if(s.isSelectCol(u))s.renderSelectField(f,l,u);else{let g=(m=l[u])!=null?m:"";f.setText(g),g.length>80&&(f.title=g),vc(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 vc(s,t,e,n){t.addEventListener("click",()=>{var o;t.empty();let i=t.createEl("input",{cls:"csv-inline-input",value:(o=e[n])!=null?o:"",type:"text"});i.focus(),i.select(),i.addEventListener("blur",()=>{e[n]=i.value,s.scheduleSave(),t.empty(),t.setText(i.value||"\u2014")}),i.addEventListener("keydown",r=>{r.key==="Enter"&&i.blur(),r.key==="Escape"&&(t.empty(),t.setText(e[n]||"\u2014"))})})}function an(s){return!!(s.getCategoryCol()||s.getStatusCol()||Ko(s)||s.authorKey())}function Ko(s){return s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"])}function Es(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 Yo=["watched","read","finished","completed","done","yes","seen"],Go=["watching","reading","in progress","in-progress"],yc=["dropped","abandoned","dnf"];function xc(s){let t=s.toLowerCase();return Yo.includes(t)?"is-done":Go.includes(t)?"is-progress":yc.includes(t)?"is-dropped":""}function Ss(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 ws(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 qo(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=Ko(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 m;return Yo.includes(((m=p[i])!=null?m:"").toLowerCase().trim())}).length;u>0&&d(`${u} \xB7 ${Math.round(u/e.length*100)}%`,"done");let f=e.filter(p=>{var m;return Go.includes(((m=p[i])!=null?m:"").toLowerCase().trim())}).length;f>0&&d(String(f),"in progress")}if(o){let u=Ss(e,f=>{var p;return((p=f[o])!=null?p:"").split(",").map(m=>m.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=>Es(f[r])).filter(f=>f!==null);if(u.length){let f=u.reduce((p,m)=>p+m,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=Ss(e,p=>{var g;let m=((g=p[i])!=null?g:"").trim();return m?[m]:[]}),f=Array.from(u.entries()).sort((p,m)=>m[1]-p[1]).map(([p,m])=>({label:p,count:m,cls:xc(p),onClick:o?()=>h(p,null):void 0}));ws(n,`By ${i.toLowerCase()}`,f,e.length)}if(o){let u=Ss(e,p=>{var m;return((m=p[o])!=null?m:"").split(",").map(g=>g.trim()).filter(Boolean)}),f=Array.from(u.entries()).sort((p,m)=>m[1]-p[1]||p[0].localeCompare(m[0])).slice(0,12).map(([p,m])=>({label:p,count:m,onClick:()=>h(null,p)}));ws(n,`By ${o.toLowerCase()}`,f,e.length)}if(r){let u=new Map,f=0;if(e.forEach(p=>{var b;let m=Es(p[r]);if(m===null)return;let g=Math.min(5,Math.max(1,Math.round(m)));u.set(g,((b=u.get(g))!=null?b:0)+1),f++}),f>0){let p=[5,4,3,2,1].filter(m=>{var g;return((g=u.get(m))!=null?g:0)>0}).map(m=>({label:"\u2605".repeat(m),count:u.get(m),cls:"is-rating"}));ws(n,"Ratings",p,f)}}if(l){let u=Ss(e,f=>{var m;let p=((m=f[l])!=null?m:"").match(/\d{4}/);return p?[p[0]]:[]});if(u.size>1){let f=Array.from(u.entries()).sort((p,m)=>p[0].localeCompare(m[0])).map(([p,m])=>({label:p,count:m}));ws(n,"By year",f,e.length)}}if(a){let u=Ss(e,p=>{var g;let m=((g=p[a])!=null?g:"").trim();return m?[m]:[]}),f=Array.from(u.entries()).filter(([,p])=>p>1);if(f.length>=2){let p=f.sort((m,g)=>g[1]-m[1]||m[0].localeCompare(g[0])).slice(0,8).map(([m,g])=>({label:m,count:g}));ws(n,`Top ${a.toLowerCase()}s`,p,e.length)}}}function Nt(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),Po(s.headers,s.rows,n)}function ln(s,t){let e=Nt(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(g=>!s.isNotesCol(g)).forEach(g=>{let b=l.createEl("option",{text:g===n?`${g} (default)`:g,value:g});g===e&&(b.selected=!0)}),l.addEventListener("change",()=>{let g=s.fileCfg;g.kanbanGroupCol=l.value===n?void 0:l.value,s.saveFileCfg(g),s.renderView(!0)});let c=Lo(e,r.map(g=>{var b;return(b=g[e])!=null?b:""})),d=g=>{var _;let b=(_=g[e])!=null?_:"",x;if(c){let E=Ao(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(g=>d(g).forEach(b=>h.add(b)));let u=Array.from(h).sort();if(!u.length){let g=t.createDiv({cls:"csv-empty-state"});g.createEl("p",{text:s.searchQuery?"No matching entries found.":`No "${e}" values found.`}),s.searchQuery&&g.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(g=>{var b;return(b=g[o])!=null?b:""}).filter(Boolean)])).filter(g=>r.some(b=>{var x;return((x=b[o])!=null?x:"")==g})):[],m=t.createDiv({cls:"csv-kanban-board"});u.forEach(g=>{let b=r.filter(w=>d(w).includes(g));if(!b.length)return;let x=m.createDiv({cls:"csv-kanban-col"}),_=x.createDiv({cls:"csv-kanban-col-header"});_.createDiv({cls:"csv-kanban-col-title",text:g}),_.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 y=b.filter(D=>{var M;return((M=D[o])!=null?M:"")===v});if(!y.length)return;let S=E.createDiv({cls:"csv-kanban-status-group"});S.createDiv({cls:`csv-kanban-status-label status-${v.toLowerCase().replace(/\s+/g,"-")}`,text:v}),y.forEach(D=>ai(s,S,D,o,e))});let w=new Set(p);b.filter(v=>{var y;return!w.has((y=v[o])!=null?y:"")}).forEach(v=>ai(s,E,v,o,e))}else b.forEach(w=>ai(s,E,w,o,e))})}function ai(s,t,e,n,i){var y,S,D,M,C,T;let o=t.createDiv({cls:"csv-kanban-card"}),r=s.getNotesCol(),a=(S=(y=s.getImageCol)==null?void 0:y.call(s))!=null?S:null;if(a){let k=Zs(s.app,(D=e[a])!=null?D:"",(C=(M=s.file)==null?void 0:M.path)!=null?C:"");if(k){let A=o.createEl("img",{cls:"csv-kanban-card-img",attr:{src:k,loading:"lazy",alt:""}});A.addEventListener("error",()=>A.remove())}}let l=o.createDiv({cls:"csv-kanban-card-title-row"});l.createDiv({cls:"csv-kanban-card-title",text:s.getTitle(e)}).addEventListener("click",k=>{k.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",k=>{k.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(),m=new Set([n,f,p,i].filter(Boolean)),g=o.createDiv({cls:"csv-kanban-card-meta"});s.headers.forEach(k=>{if(m.has(k)||s.isNotesCol(k)||!e[k])return;let A=g.createDiv({cls:"csv-kanban-chip"});if(A.createSpan({cls:"csv-chip-label",text:k+": "}),s.isSelectCol(k)){let P=A.createSpan({cls:"csv-chip-value csv-chip-select",text:e[k]});P.addEventListener("click",O=>{O.stopPropagation(),Ot(P,e[k],s.getColumnValues(k),z=>{e[k]=z,P.setText(z||"\u2014"),s.scheduleSave()},s.contentEl,{multi:It(k)})})}else{let P=e[k].length>40?e[k].slice(0,38)+"\u2026":e[k],O=A.createSpan({cls:"csv-chip-value",text:P});e[k].length>40&&(O.title=e[k])}});let b=s.getNotesCol(),x=!!(b&&((T=e[b])!=null&&T.trim())),_=o.createDiv({cls:"csv-kanban-notes-preview"});if(x&&b){let k=e[b].replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();_.setText(k.slice(0,120)+(k.length>120?"\u2026":"")),_.title="Click to edit"}else _.addClass("csv-kanban-notes-preview--empty"),b&&_.setText("+ Add note");let E=o.createDiv({cls:"csv-kanban-notes-editor"});E.style.display="none";let w=()=>{var z,G,$;let k=s.contentEl.querySelector(".csv-content-area"),A=(z=k==null?void 0:k.scrollLeft)!=null?z:0,P=(G=k==null?void 0:k.scrollTop)!=null?G:0;_.style.display="none",E.style.display="block",E.empty();let O=E.createEl("textarea",{cls:"csv-notes-textarea"});O.value=($=b?e[b]:"")!=null?$:"",O.addEventListener("click",L=>L.stopPropagation()),O.addEventListener("mousedown",L=>L.stopPropagation()),O.addEventListener("input",()=>{O.style.height="auto",O.style.height=O.scrollHeight+"px"}),O.addEventListener("keydown",L=>{L.key==="Escape"&&v(O.value,k,A,P)}),O.addEventListener("blur",()=>v(O.value,k,A,P)),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=(k,A,P,O)=>{if(b&&(e[b]=k,s.scheduleSave()),E.style.display="none",_.style.display="",k.trim()){let z=k.replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();_.setText(z.slice(0,120)+(z.length>120?"\u2026":"")),_.removeClass("csv-kanban-notes-preview--empty"),_.title="Click to edit"}else _.addClass("csv-kanban-notes-preview--empty"),_.setText(b?"+ Add note":""),_.removeAttribute("title");A&&(A.scrollLeft=P,A.scrollTop=O,requestAnimationFrame(()=>{A.scrollLeft=P,A.scrollTop=O,requestAnimationFrame(()=>{A.scrollLeft=P,A.scrollTop=O})}),setTimeout(()=>{A.scrollLeft=P,A.scrollTop=O},50))};_.addEventListener("click",k=>{if(k.stopPropagation(),b&&matchMedia("(pointer: coarse)").matches){s.openNoteExpander(e,b);return}w()}),o.addEventListener("contextmenu",k=>s.openRowContextMenu(e,k))}function cn(s,t){var D,M;let e=Nt(s),n=s.getStatusCol(),i=(D=s.titleKey())!=null?D: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(C=>{var k;((k=C[e])!=null?k:"").split(",").map(A=>A.trim()).filter(Boolean).forEach(A=>r.add(A))});let a=new Set;n&&s.rows.forEach(C=>{var k;let T=((k=C[n])!=null?k:"").trim();T&&a.add(T)});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(C=>d.includes(C.toLowerCase())),f=Array.from(a).some(C=>h.includes(C.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(C=>{c.createEl("option",{text:C,value:C})})),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(C=>{p.createEl("option",{text:C,value:C})}),p.value=s.libraryGenreFilter;let m=s.resolveCol(["Year","year","Date","date"]),g=s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"]),b=s.resolveCol(["Theme","theme","Tags","tags","Tag","tag","Mood","mood"]),x=(M=s.fileCfg.librarySort)!=null?M:"status",_=l.createEl("select",{cls:"csv-library-filter-select"}),E=[["status","Sort: Status"],["title","Sort: Title"]];g&&E.push(["rating","Sort: Rating"]),m&&E.push(["year","Sort: Year"]),E.forEach(([C,T])=>{let k=_.createEl("option",{text:T,value:C});C===x&&(k.selected=!0)}),_.addEventListener("change",()=>{let C=s.fileCfg;C.librarySort=_.value==="status"?void 0:_.value,s.saveFileCfg(C),s.renderView(!0)});let w=()=>{s.libraryStatusFilter=c.value,s.libraryGenreFilter=p.value,s.renderView(!0)};c.addEventListener("change",w),p.addEventListener("change",w);let v=s.rows.filter(C=>{var T,k;if(s.libraryStatusFilter!=="all"&&n){let A=((T=C[n])!=null?T:"").toLowerCase();if(s.libraryStatusFilter==="__done__"){if(!d.includes(A))return!1}else if(s.libraryStatusFilter==="__inprogress__"){if(!h.includes(A))return!1}else if(s.libraryStatusFilter==="__notstarted__"){if(d.includes(A)||h.includes(A))return!1}else if(A!==s.libraryStatusFilter.toLowerCase())return!1}if(s.libraryGenreFilter!=="all"&&!((k=C[e])!=null?k:"").split(",").map(P=>P.trim().toLowerCase()).includes(s.libraryGenreFilter.toLowerCase()))return!1;if(s.searchQuery.trim()){let A=s.searchQuery.toLowerCase().trim();if(!s.headers.some(P=>{var O;return((O=C[P])!=null?O:"").toLowerCase().includes(A)}))return!1}return!0});(s.libraryStatusFilter!=="all"||s.libraryGenreFilter!=="all"||s.searchQuery.trim())&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${v.length} of ${s.rows.length} entries`});let y={};v.forEach(C=>{var k;let T=s.libraryGenreFilter!=="all"?[s.libraryGenreFilter]:((k=C[e])!=null?k:"Uncategorized").split(",").map(A=>A.trim()).filter(Boolean);T.length===0&&T.push("Uncategorized"),T.forEach(A=>{y[A]||(y[A]=[]),y[A].push(C)})});let S=t.createDiv({cls:"csv-library-sections"});if(Object.keys(y).sort().forEach(C=>{var j,U,B,F,I;let T=y[C],k=S.createEl("details",{cls:"csv-library-section"}),A=C.toLowerCase(),P=((j=s.fileCfg.collapsedGroups)!=null?j:[]).map(N=>N.toLowerCase());k.open=!((U=s.collapsedGroups)!=null&&U.has(A)||P.includes(A)),k.addEventListener("toggle",()=>{var Z;let N=s.fileCfg,R=((Z=N.collapsedGroups)!=null?Z:[]).map(X=>X.toLowerCase()),Y=new Set(R);k.open?Y.delete(A):Y.add(A);let K=Array.from(Y);K.length===R.length&&K.every(X=>R.includes(X))||(N.collapsedGroups=K,s.saveFileCfg(N))});let O=k.createEl("summary",{cls:"csv-library-section-header"});O.innerHTML=`\u25B6 ${C} ${T.length}`;let z=k.createDiv({cls:"csv-library-grid"}),G=(N,R)=>{var Y,K;return((Y=N[i])!=null?Y:"").localeCompare((K=R[i])!=null?K:"")},$=(N,R)=>N===null&&R===null?0:N===null?1:R===null?-1:R-N;T.sort((N,R)=>{var Y,K,Z,X;if(x==="title")return G(N,R);if(x==="rating"&&g)return $(Es((Y=N[g])!=null?Y:""),Es((K=R[g])!=null?K:""))||G(N,R);if(x==="year"&&m){let q=ut=>{var st;let J=((st=ut[m])!=null?st:"").match(/\d{4}/);return J?parseInt(J[0],10):null};return $(q(N),q(R))||G(N,R)}if(n){let q=((Z=N[n])!=null?Z:"").toLowerCase(),ut=((X=R[n])!=null?X:"").toLowerCase(),J=d.includes(q),st=d.includes(ut);if(J!==st)return J?-1:1;let at=h.includes(q),Rt=h.includes(ut);if(at!==Rt)return at?-1:1}return G(N,R)});let L=[o,m,g,b].filter(N=>!!N),V=(B=s.fileCfg.cardFields)!=null?B:L,W=(I=(F=s.getImageCol)==null?void 0:F.call(s))!=null?I:null;T.forEach(N=>{var X,q,ut,J,st,at,Rt;let R=z.createDiv({cls:"csv-library-card"});if(W){let it=Zs(s.app,(X=N[W])!=null?X:"",(ut=(q=s.file)==null?void 0:q.path)!=null?ut:"");if(it){let gt=R.createEl("img",{cls:"csv-library-card-img",attr:{src:it,loading:"lazy",alt:""}});gt.addEventListener("error",()=>gt.remove())}}let Y=R.createDiv({cls:"csv-library-card-title"});if(n){let it=((J=N[n])!=null?J:"").toLowerCase();d.includes(it)&&Y.createSpan({cls:"csv-library-done-dot"})}Y.createSpan({text:(st=N[i])!=null?st:"Untitled"});let K=[],Z=[];for(let it of V){if(!it)continue;let gt=String((at=N[it])!=null?at:"").trim();if(gt)if(it===g){let ft=To(gt,it);ft&&R.createDiv({cls:"csv-library-card-rating",text:ft})}else if(it===b)Z.push(...gt.split(",").map(ft=>ft.trim()).filter(Boolean));else if(it===m){let ft=gt.match(/\d{4}/);K.push(ft?ft[0]:gt)}else K.push(gt)}if(K.length&&R.createDiv({cls:"csv-library-card-meta",text:K.join(" \xB7 ")}),s.libraryGenreFilter!=="all"){let it=((Rt=N[e])!=null?Rt:"").split(",").map(gt=>gt.trim()).filter(gt=>gt&>.toLowerCase()!==s.libraryGenreFilter.toLowerCase());Z.push(...it)}if(Z.length){let it=R.createDiv({cls:"csv-library-card-tags"});Z.slice(0,3).forEach(gt=>{it.createSpan({cls:"csv-library-card-tag",text:gt})})}R.addEventListener("click",()=>{var it;s.openNoteExpander(N,(it=s.getNotesCol())!=null?it:"")}),R.addEventListener("contextmenu",it=>s.openRowContextMenu(N,it))})}),Object.keys(y).length===0){let C=S.createDiv({cls:"csv-empty-state"});C.createEl("p",{text:"No entries match your filters."}),C.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.libraryStatusFilter="all",s.libraryGenreFilter="all",s.searchQuery="",s.renderView()})}}var fn=require("obsidian");var Me=require("obsidian");var li=`--- obsidianUIMode: preview obsidianEditingMode: source --- -`,ti=` +`,ci=` --- Requires Dataview plugin with DataviewJS enabled -`;function jo(s){let{filePath:t,csvPath:e,habitCols:n,labels:i,dateCol:o}=s;return`${Jn}## Quick Add +`;function Xo(s){let{filePath:t,csvPath:e,habitCols:n,labels:i,dateCol:o}=s;return`${li}## Quick Add \`\`\`csv-add file: ${t} @@ -117,7 +117,7 @@ if (!csvData || !csvData.length) { } } \`\`\` -${ti}`}function Uo(s){let{filePath:t,csvPath:e,titleKey:n,categoryCol:i,statusCol:o,authorKey:r,yearCol:a,ratingCol:l,themeCol:c,compactGrid:d}=s;return`${Jn}## Add Entry +${ci}`}function Qo(s){let{filePath:t,csvPath:e,titleKey:n,categoryCol:i,statusCol:o,authorKey:r,yearCol:a,ratingCol:l,themeCol:c,compactGrid:d}=s;return`${li}## Add Entry \`\`\`csv-add file: ${t} @@ -295,7 +295,7 @@ if (!csvData || !csvData.length) { } } \`\`\` -${ti}`}function Yo(s){let{filePath:t,csvPath:e,headers:n}=s;return`${Jn}## Add Entry +${ci}`}function Zo(s){let{filePath:t,csvPath:e,headers:n}=s;return`${li}## Add Entry \`\`\`csv-add file: ${t} @@ -365,10 +365,12 @@ if (!csvData || !csvData.length) { } } \`\`\` -${ti}`}async function Ko(s){var c,d,h,u,f,p,g,b,y,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 S=s.getBooleanColumns();l=jo({filePath:a,csvPath:i,habitCols:S,labels:S.map(Et),dateCol:o})}else if(r){let S=(f=(u=(h=s.titleKey())!=null?h:s.resolveCol(["Quote","quote","Headline","headline","Phrase","phrase"]))!=null?u:s.headers[0])!=null?f:"Title";l=Uo({filePath:a,csvPath:i,titleKey:S,categoryCol:r,statusCol:(p=s.getStatusCol())!=null?p:"Status",authorKey:(g=s.authorKey())!=null?g:"",yearCol:(b=s.resolveCol(["Year","year","Released","released"]))!=null?b:"",ratingCol:(y=s.resolveCol(["Rating","rating","Score","score","Stars","stars"]))!=null?y:"",themeCol:(x=s.resolveCol(["Theme","theme","Subgenre","subgenre","Mood","mood"]))!=null?x:"",compactGrid:s.titleKey()!==null})}else l=Yo({filePath:a,csvPath:i,headers:s.headers});try{let S=s.app.vault.getAbstractFileByPath(n);S&&S instanceof ke.TFile?(await s.app.vault.modify(S,l),new ke.Notice(`Updated: ${n}`)):(await s.app.vault.create(n,l),new ke.Notice(`Created: ${n}`))}catch(S){let M=s.app.vault.getAbstractFileByPath(n);M instanceof ke.TFile&&(await s.app.vault.modify(M,l),new ke.Notice(`Updated: ${n}`))}}var le=require("obsidian"),hc="http://127.0.0.1:8765",uc=6;async function Go(s,t){let e;try{e=await(0,le.requestUrl)({url:hc,method:"POST",contentType:"application/json",body:JSON.stringify({action:s,version:uc,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 fc(s){var e,n,i;let t=s.fileCfg.ankiFrontCol;return t&&s.headers.includes(t)?t:(i=(n=(e=s.titleKey())!=null?e:s.resolveCol(["Quote","Headline","Phrase","Term","Word","Question","Front","Name","Title"]))!=null?n:s.headers[0])!=null?i:null}function ei(s){return s.replace(/&/g,"&").replace(//g,">")}function pc(s,t,e){return s.headers.filter(n=>{var i;return n!==e&&((i=t[n])!=null?i:"").trim()}).map(n=>`${ei(n)}: ${ei(t[n].trim())}`).join("
")}async function qo(s){if(!s.file)return;let t=fc(s);if(!t){new le.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 le.Notice(`Nothing to sync \u2014 no rows with a "${t}" value.`,6e3);return}let i=new le.Notice(`Syncing ${n.length} cards to Anki deck \u201C${e}\u201D\u2026`,0);try{await Go("createDeck",{deck:e});let o=n.map(c=>({deckName:e,modelName:"Basic",fields:{Front:ei(c[t].trim()),Back:pc(s,c,t)},options:{allowDuplicate:!1,duplicateScope:"deck"},tags:["csv-card-view"]})),r=await Go("addNotes",{notes:o}),a=r.filter(c=>c!=null).length,l=r.length-a;i.hide(),new le.Notice(`Anki sync: ${a} added${l?`, ${l} already present`:""} (deck \u201C${e}\u201D).`,6e3)}catch(o){i.hide(),new le.Notice(`Anki sync failed: ${o instanceof Error?o.message:String(o)}`,8e3)}}function Js(s){return s.resolveCol(["Type","type","Kind","kind","Item","item"])}function ii(s){var t;return(t=s.resolveCol(["Project","project","Projects","projects","Area","area"]))!=null?t:Jt(s)}function Jo(s){return s.resolveCol(["Due","due","Deadline","deadline","Due Date","Due date","due date"])}function tn(s){return s.resolveCol(["Priority","priority","Prio","prio","Importance","importance"])}var gc=["task","todo","to-do","action",""],mc=["task","todo","to-do","action","note","idea","reference","ref"],tr=["done","complete","completed","finished","closed","resolved","yes","x","\u2713","true"],bc={high:0,med:1,medium:1,normal:1,low:2};function $e(s){if(Jo(s)||tn(s))return!0;let t=Js(s);return t?s.rows.some(e=>{var n;return mc.includes(((n=e[t])!=null?n:"").trim().toLowerCase())}):!1}function yc(s,t,e){var n;return e?gc.includes(((n=t[e])!=null?n:"").trim().toLowerCase()):!0}function vc(s,t,e){if(yc(s,t,e))return"task";let n=(e?t[e]:"").trim().toLowerCase();return n==="idea"||n==="ideas"?"idea":"note"}function si(s,t,e){var n;return e?tr.includes(((n=t[e])!=null?n:"").trim().toLowerCase()):!1}function Xo(s){let t=bc[(s!=null?s:"").trim().toLowerCase()];return t===void 0?3:t}function Qo(s){return(s!=null?s:"").trim()?0:1}function xc(){return new Date().toISOString().slice(0,10)}function _c(s,t){let e=new Map;s.rows.forEach(o=>{var a,l;let r=((a=o[t])!=null?a:"").trim();r&&tr.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 er(s,t){var k;let e=ii(s),n=Js(s),i=s.getStatusCol(),o=Jo(s),r=tn(s),a=(k=s.titleKey())!=null?k:s.headers[0],l=t.createDiv({cls:"csv-library-filters"}),c=new Set;e&&s.rows.forEach(w=>{var _;((_=w[e])!=null?_:"").split(",").map(D=>D.trim()).filter(Boolean).forEach(D=>c.add(D))});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(w=>d.createEl("option",{text:w,value:w})),d.value=s.taskProjectFilter;let h=new Set;n&&s.rows.forEach(w=>{var D;let _=((D=w[n])!=null?D:"").trim();_&&h.add(_)});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(w=>u.createEl("option",{text:w,value:w})),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(w=>{var _,D;return!(s.taskProjectFilter!=="all"&&e&&!((_=w[e])!=null?_:"").split(",").map(P=>P.trim().toLowerCase()).includes(s.taskProjectFilter.toLowerCase())||s.taskTypeFilter!=="all"&&n&&((D=w[n])!=null?D:"").trim().toLowerCase()!==s.taskTypeFilter.toLowerCase()||p&&!s.headers.some(T=>{var P;return((P=w[T])!=null?P:"").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 b={},y={},x={},S={task:b,note:y,idea:x},M=w=>{var D;return e&&((D=w[e])!=null?D:"").split(",").map(T=>T.trim()).filter(Boolean)[0]||"\u2014"};g.forEach(w=>{var T;let _=S[vc(s,w,n)],D=M(w);((T=_[D])!=null?T:_[D]=[]).push(w)});let E=t.createDiv({cls:"csv-tasks"}),v=xc(),m=i?_c(s,i):"done";ni(E,"Tasks",b,(w,_)=>{_.sort((D,T)=>{var H,B,G,W,L,A;let P=si(s,D,i),R=si(s,T,i);if(P!==R)return P?1:-1;if(r){let V=Xo((H=D[r])!=null?H:"")-Xo((B=T[r])!=null?B:"");if(V)return V}if(o){let V=Qo((G=D[o])!=null?G:"")-Qo((W=T[o])!=null?W:"");if(V)return V;let $=((L=D[o])!=null?L:"").localeCompare((A=T[o])!=null?A:"");if($)return $}return s.getTitle(D).localeCompare(s.getTitle(T))}),_.forEach(D=>{var W;let T=si(s,D,i),P=w.createEl("tr"),R=P.createEl("td",{cls:"csv-tasks-check-cell"});if(i){let L=R.createEl("span",{cls:`csv-tasks-check ${T?"is-done":""}`,text:T?"\u2713":""});L.setAttr("title",T?"Mark not done":"Mark done"),L.addEventListener("click",A=>{A.stopPropagation(),D[i]=T?"":m,s.scheduleSave(),s.renderView(!0)})}Zo(s,P,D,a,T);let H=P.createEl("td",{cls:"csv-tasks-due"}),B=o?((W=D[o])!=null?W:"").slice(0,10):"";H.setText(B||"\u2014"),B&&!T&&B{var V;L.stopPropagation();let A=Array.from(new Set([...s.getColumnValues(r),"high","medium","low"]));Ot(G,(V=D[r])!=null?V:"",A,$=>{D[r]=$,s.scheduleSave(),s.renderView(!0)},s.contentEl)})),P.addEventListener("contextmenu",L=>s.openRowContextMenu(D,L))})},["","Name","Due","Priority"]);let C=(w,_)=>{_.sort((D,T)=>s.getTitle(D).localeCompare(s.getTitle(T))),_.forEach(D=>{let T=w.createEl("tr"),P=n&&D[n]||"",R=T.createEl("td",{cls:"csv-tasks-type-cell"});P&&R.createSpan({cls:"csv-tasks-type-pill",text:P}),Zo(s,T,D,a,!1),T.addEventListener("contextmenu",H=>s.openRowContextMenu(D,H))})};if(ni(E,"Notes",y,C,["Type","Name"]),ni(E,"Ideas",x,C,["Type","Name"]),Object.keys(b).length===0&&Object.keys(y).length===0&&Object.keys(x).length===0){let w=E.createDiv({cls:"csv-empty-state"});w.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")&&w.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.taskProjectFilter="all",s.taskTypeFilter="all",s.searchQuery="",s.renderView()})}}function ni(s,t,e,n,i){if(Object.keys(e).length===0)return;s.createDiv({cls:"csv-tasks-section-header",text:t});let o=s.createDiv({cls:"csv-tasks-section"});Object.keys(e).sort().forEach(r=>{let a=e[r],l=o.createEl("details",{cls:"csv-tasks-group"});l.open=!0;let c=l.createEl("summary",{cls:"csv-tasks-group-header"});c.innerHTML=`\u25B6 ${r} ${a.length}`;let d=l.createEl("table",{cls:"csv-tasks-table"}),u=d.createEl("thead").createEl("tr");i.forEach(p=>u.createEl("th",{text:p}));let f=d.createEl("tbody");n(f,a)})}function Zo(s,t,e,n,i){let o=t.createEl("td",{cls:"csv-tasks-name-cell"}),r=o.createSpan({cls:`csv-tasks-link ${i?"csv-tasks-done":""}`,text:e[n]||"Untitled"}),a=s.getNotesCol();r.addEventListener("click",()=>{a?s.openNoteExpander(e,a):s.openOrCreateNotes(e)});let l=s.notesFileExists(e),c=o.createEl("button",{cls:`csv-tasks-page-icon ${l?"exists":""}`,text:l?"\u{1F4C4}":"+"});c.setAttr("title",l?"Open page":"Create page"),c.addEventListener("click",d=>{d.stopPropagation(),s.openOrCreateNotes(e)})}function en(s){let t=[];return s.isTravelFile()&&t.push({id:"travel",label:"Travel"}),s.hasDateColumn()&&t.push({id:"dashboard",label:"Dashboard"}),$e(s)&&t.push({id:"tasks",label:"Tasks"}),Jt(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"}),Zs(s)&&t.push({id:"stats",label:"Stats"}),t}function sr(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=en(s),r=i.createEl("select",{cls:"csv-mode-select",attr:{"aria-label":"View mode"}});if(o.forEach(({id:b,label:y})=>{let x=r.createEl("option",{text:y,value:b});s.mode===b&&(x.selected=!0)}),r.addEventListener("change",()=>{s.mode=r.value,s.renderView()}),s.mode!=="dashboard"){let b=n.createEl("button",{cls:"csv-cfg-btn csv-search-toggle",text:"\u{1F50D}",title:"Search"}),y=n.createDiv({cls:"csv-search-wrap"}),x=y.createDiv({cls:"csv-search-input-wrap"}),S=x.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search...",value:s.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),M=x.createEl("button",{cls:"csv-search-clear",text:"\xD7",title:"Clear search"});M.toggleClass("is-hidden",!s.searchQuery),y.createEl("button",{cls:"csv-search-done",text:"Done",title:"Dismiss keyboard"}).addEventListener("click",m=>{if(m.preventDefault(),!S.value){e.removeClass("csv-toolbar--search-expanded"),b.removeClass("has-query"),s.searchQuery="",s.renderView(!0);return}S.blur()});let v=null;S.addEventListener("input",m=>{s.searchQuery=m.target.value,M.toggleClass("is-hidden",!s.searchQuery),b.toggleClass("has-query",!!s.searchQuery),v!==null&&window.clearTimeout(v),v=window.setTimeout(()=>{v=null,s.renderView(!0)},120)}),S.addEventListener("keydown",m=>{m.key==="Enter"&&(m.preventDefault(),S.blur())}),M.addEventListener("click",()=>{s.searchQuery="",S.value="",M.addClass("is-hidden"),b.removeClass("has-query"),S.focus({preventScroll:!0}),s.renderView(!0)}),s.searchQuery&&b.addClass("has-query"),b.addEventListener("click",()=>{e.addClass("csv-toolbar--search-expanded"),S.focus({preventScroll:!0})})}if(s.mode==="table"&&s.hasDateColumn()){let b=(g=s.fileCfg.sortNewestFirst)!=null?g:!0;n.createEl("button",{cls:`csv-cfg-btn ${b?"active":""}`,text:b?"\u2193 Newest":"\u2191 Oldest",title:"Toggle sort order"}).addEventListener("click",()=>{var S;let x=s.fileCfg;x.sortNewestFirst=!((S=x.sortNewestFirst)==null||S),s.saveFileCfg(x),s.tableSortCol=null,s.renderViewPreservingScroll()})}let a=()=>{var b,y;new Ks(s.app,s.headers,(y=(b=s.file)==null?void 0:b.path)!=null?y:"",s.fileCfg,s.autoDetectBooleanColumns(),en(s),x=>{s.saveFileCfg(x),x.defaultMode&&(s.mode=x.defaultMode),s.renderView()}).open()},l=()=>Ko(s),c=()=>s.backupToArchive(),d=()=>qo(s);n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u2699 Columns",title:"Configure columns for this file"}).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",b=>{let y=new sn.Menu;y.addItem(x=>x.setTitle("Columns").setIcon("settings").onClick(a)),y.addItem(x=>x.setTitle("Mobile dashboard").setIcon("smartphone").onClick(l)),y.addItem(x=>x.setTitle("Backup").setIcon("save").onClick(c)),y.addItem(x=>x.setTitle("Sync to Anki").setIcon("layers").onClick(d)),y.addSeparator(),y.addItem(x=>x.setTitle("Built 2026-06-15 18:46").setIcon("info").setDisabled(!0)),y.showAtMouseEvent(b)}),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary csv-info-btn",text:"\u24D8",title:"Built 2026-06-15 18:46 \u2014 click to confirm"}).addEventListener("click",()=>new sn.Notice("csv-card-view \u2014 built 2026-06-15 18:46",4e3))}function Cc(s){return s&&typeof s=="object"&&"basename"in s?s:null}var Sc=["Author","author","By","by","Source","source","Speaker","speaker","Artist","artist","Director","director"];async function nr(s,t,e,n){var x,S,M;let i=t.split(` -`).map(E=>E.trim()).filter(Boolean),o=E=>{var v,m;return(m=(v=i.find(C=>C.startsWith(E+":")))==null?void 0:v.slice(E.length+1).trim())!=null?m:""},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=(S=(x=a==null?void 0:a.parent)==null?void 0:x.path)!=null?S:"",c=js(r,l),d=Cc(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 E=Ee(await s.vault.read(d));h=E.headers,u=E.rows}catch(E){e.createEl("p",{text:`Error reading file: ${E}`,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=(M=h.find(E=>E.toLowerCase()===f.toLowerCase()))!=null?M:h[0],g=Sc.map(E=>h.find(v=>v===E)).find(Boolean),b=e.createDiv({cls:"csv-random-card"}),y=()=>{var _;b.empty();let E=u.filter(D=>{var T;return((T=D[p])!=null?T:"").trim()}),v=E.length?E:u,m=v[Math.floor(Math.random()*v.length)];b.createDiv({cls:"csv-random-text",text:m[p]||"\u2014"});let C=g?((_=m[g])!=null?_:"").trim():"";C&&b.createDiv({cls:"csv-random-sub",text:`\u2014 ${C}`});let k=b.createDiv({cls:"csv-random-foot"});k.createSpan({cls:"csv-random-src",text:d.basename}),k.createEl("button",{cls:"csv-random-btn",text:"\u21BB",title:"Another one"}).addEventListener("click",y)};y()}var co=null;async function jf(){if(co)return co;let s=await Promise.resolve().then(()=>(Pl(),Al));return s.Chart.register(s.LineController,s.LineElement,s.PointElement,s.LinearScale,s.CategoryScale,s.Filler,s.Tooltip),co=s,s}async function Rl(s,t){var V,$,U;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((F,I)=>{var O,j;return((O=F[e])!=null?O:"").localeCompare((j=I[e])!=null?j:"")});s.selectedDate||(s.selectedDate=o);let a=r.find(F=>F[e]===s.selectedDate),l=s.selectedDate===o;t.addClass("csv-dashboard");let c=[...new Set([...r.map(F=>F[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 F=c.indexOf(s.selectedDate);if(F>0)s.selectedDate=c[F-1],s.renderView();else if(F===-1&&c.length>0){let I=c.filter(O=>O0&&(s.selectedDate=I[I.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(F=>{let I=f.createEl("option",{text:F,value:F});F===s.selectedDate&&(I.selected=!0)}),f.addEventListener("change",()=>{s.selectedDate=f.value,s.renderView()}),d.createEl("button",{cls:"csv-dash-nav-btn",text:"\u25B6"}).addEventListener("click",()=>{let F=c.indexOf(s.selectedDate);if(F>=0&&FO>s.selectedDate);I.length>0&&(s.selectedDate=I[0],s.renderView())}}),l||d.createEl("button",{cls:"csv-dash-today-btn",text:"Today"}).addEventListener("click",()=>{s.selectedDate=o,s.renderView()}),!a){let F=t.createDiv({cls:"csv-dash-add-section"});F.createEl("p",{text:`No entry for ${s.selectedDate}`}),F.createEl("button",{cls:"csv-dash-add-btn",text:`+ Add entry for ${s.selectedDate}`}).addEventListener("click",()=>{let O={};s.headers.forEach(j=>O[j]=""),O[e]=s.selectedDate,s.rows.push(O),s.scheduleSave(),s.renderView()})}if(a){let F=t.createDiv({cls:"csv-dash-habits"});F.createEl("h3",{text:s.selectedDate===o?"Today":s.selectedDate,cls:"csv-dash-section-title"});let I=F.createDiv({cls:"csv-dash-habits-grid"});n.forEach(j=>{let N=s.isTruthy(a[j]),Y=I.createDiv({cls:`csv-dash-habit ${N?"checked":""}`}),K=Y.createEl("button",{cls:"csv-dash-habit-check",text:N?"\u25CF":"\u25CB"});Y.createSpan({cls:"csv-dash-habit-label",text:j}),K.addEventListener("click",()=>{a[j]=N?"0":"1",s.scheduleSave(),s.renderViewPreservingScroll()})});let O=n.filter(j=>s.isTruthy(a[j])).length;if(F.createDiv({cls:"csv-dash-habits-count",text:`${O} of ${n.length} complete`}),i&&((V=a[i])!=null&&V.trim())){let j=F.createDiv({cls:"csv-dash-notes-preview"});j.createEl("strong",{text:"Notes: "}),j.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 y=g.createDiv({cls:"csv-dash-chart-wrap"}).createEl("canvas",{cls:"csv-dash-chart"}),x=r.map(F=>{var O;return((O=F[e])!=null?O:"").slice(5)}),S=r.map(F=>n.filter(I=>s.isTruthy(F[I])).length);s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:M}=await jf();if(!y.isConnected)return;s.chartInstance=new M(y,{type:"line",data:{labels:x,datasets:[{label:"Habits done",data:S,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 E=t.createDiv({cls:"csv-dash-stats-section"});E.createEl("h3",{text:"Stats",cls:"csv-dash-section-title"});let v=r.length,m=r.reduce((F,I)=>F+n.filter(O=>s.isTruthy(I[O])).length,0),C=v>0?(m/v).toFixed(1):"0",k=r.filter(F=>n.every(I=>s.isTruthy(F[I]))).length,w=0,_=0,D=null;for(let F of r){let I=n.filter(N=>s.isTruthy(F[N])).length,O=s.parseDate(($=F[e])!=null?$:""),j=!0;D&&O&&Math.round((O.getTime()-D.getTime())/864e5)!==1&&(j=!1),I>=1&&(j||D===null)?(_++,_>w&&(w=_)):I>=1?(_=1,_>w&&(w=_)):_=0,D=O}let T=0,P=new Date;P.setHours(0,0,0,0);let R=P;for(let F=r.length-1;F>=0;F--){let I=s.parseDate((U=r[F][e])!=null?U:"");if(!I)break;let O=Math.round((R.getTime()-I.getTime())/(1e3*60*60*24));if(T===0&&O>1||T>0&&O!==1)break;if(n.filter(N=>s.isTruthy(r[F][N])).length>=1)T++,R=I;else break}let H=E.createDiv({cls:"csv-dash-stats-bar"});H.innerHTML=`${v} days logged \xB7 ${C} avg/day \xB7 ${k} perfect days \xB7 current streak ${T}d \xB7 best streak ${w}d`;let G=t.createDiv({cls:"csv-dash-cards-section"}).createDiv({cls:"csv-dash-cards-grid"}),W=new Date().getFullYear(),L={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(F=>{let I=r.filter(K=>s.isTruthy(K[F])),O=I.length>0?I[I.length-1][e]:null,j=new Set;I.forEach(K=>{var J;let X=s.parseDate((J=K[e])!=null?J:"");X&&j.add(X.getFullYear())});let N=r.filter(K=>{var J;let X=s.parseDate((J=K[e])!=null?J:"");return X&&X.getFullYear()===W}),Y=N.filter(K=>s.isTruthy(K[F])).length;return{habit:F,doneCount:I.length,doneThisYear:Y,totalThisYear:N.length,lastDone:O,years:Array.from(j).sort()}}).sort((F,I)=>!F.lastDone&&!I.lastDone?0:F.lastDone?I.lastDone?I.lastDone.localeCompare(F.lastDone):-1:1).forEach(({habit:F,doneCount:I,doneThisYear:O,totalThisYear:j,lastDone:N,years:Y})=>{var ot;let K=G.createDiv({cls:"csv-dash-habit-card"}),X=(ot=L[F.toLowerCase()])!=null?ot:"\u25CB",J=K.createDiv({cls:"csv-dash-habit-card-header"});if(J.createSpan({cls:"csv-dash-habit-icon",text:X}),J.createSpan({cls:"csv-dash-habit-card-name",text:Et(F)}),Y.length>0&&K.createDiv({cls:"csv-dash-habit-years"}).setText(Y.join(" \xB7 ")),K.createDiv({cls:"csv-dash-habit-card-thisyear",text:`${O} of ${j} complete this year`}),K.createDiv({cls:"csv-dash-habit-card-alltime",text:`${I} of ${v} all time`}),N){let dt=s.parseDate(N),re=dt?dt.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):N;K.createDiv({cls:"csv-dash-habit-card-last",text:`Last logged: ${re}`})}else K.createDiv({cls:"csv-dash-habit-card-last",text:"Never logged"});let Q=v>0?I/v*100:0,st=K.createDiv({cls:"csv-dash-habit-progress"}).createDiv({cls:"csv-dash-habit-progress-bar"});st.style.width=`${Q}%`,K.addEventListener("click",()=>{s.selectedHabit=s.selectedHabit===F?null:F,s.renderViewPreservingScroll()}),s.selectedHabit===F&&K.addClass("selected")}),s.selectedHabit&&n.includes(s.selectedHabit)&&Uf(s,t,r,e,s.selectedHabit)}function Uf(s,t,e,n,i){var w,_,D;let o=t.createDiv({cls:"csv-dash-timeline-section"}),r=o.createDiv({cls:"csv-dash-timeline-header"});r.createEl("h3",{text:`${Et(i)} Timeline`,cls:"csv-dash-section-title"});let a=r.createEl("select",{cls:"csv-dash-year-select"}),l=new Set;e.forEach(T=>{var R;let P=s.parseDate((R=T[n])!=null?R:"");P&&l.add(P.getFullYear())}),l.add(new Date().getFullYear()),Array.from(l).sort().reverse().forEach(T=>{let P=a.createEl("option",{text:String(T),value:String(T)});T===s.timelineYear&&(P.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(T=>{var P;d.set((P=T[n])!=null?P:"",s.isTruthy(T[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(T=>u.createSpan({cls:"csv-dash-timeline-month-label",text:T}));let p=h.createDiv({cls:"csv-dash-timeline-calendar"}),g=p.createDiv({cls:"csv-dash-timeline-day-labels"});for(let T=1;T<=31;T++)g.createDiv({cls:"csv-dash-timeline-day-label",text:T%5===0||T===1?String(T):""});for(let T=0;T<12;T++){let P=p.createDiv({cls:"csv-dash-timeline-month-col"}),R=new Date(s.timelineYear,T+1,0).getDate();for(let H=1;H<=31;H++){if(H>R){P.createDiv({cls:"csv-dash-timeline-cell empty"});continue}let B=`${s.timelineYear}-${String(T+1).padStart(2,"0")}-${String(H).padStart(2,"0")}`,G=(w=d.get(B))!=null?w:!1,W=d.has(B),L=new Date(s.timelineYear,T,H)>new Date,A=P.createDiv({cls:`csv-dash-timeline-cell ${L?"future":""} ${G?"done":""} ${W&&!G?"missed":""} ${!W&&!L?"no-entry":""}`});A.title=`${B}: ${L?"Future":G?"\u2713 Done":W?"\u2717 Missed":"No entry"}`}}let b=e.filter(T=>{var R;let P=s.parseDate((R=T[n])!=null?R:"");return P&&P.getFullYear()===s.timelineYear}),y=b.filter(T=>s.isTruthy(T[i])).length,x=b.length,S=0,M=0,E=0,v=null;for(let T of e){let P=s.isTruthy(T[i]),R=s.parseDate((_=T[n])!=null?_:""),H=!0;v&&R&&Math.round((R.getTime()-v.getTime())/864e5)!==1&&(H=!1),P&&(H||v===null)?(E++,E>M&&(M=E)):P?E=1:E=0,v=R}let m=new Date;m.setHours(0,0,0,0);let C=m;for(let T=e.length-1;T>=0;T--){let P=s.parseDate((D=e[T][n])!=null?D:"");if(!P)break;let R=Math.round((C.getTime()-P.getTime())/(1e3*60*60*24));if(S===0&&R>1||S>0&&R!==1)break;if(s.isTruthy(e[T][i]))S++,C=P;else break}let k=o.createDiv({cls:"csv-dash-timeline-stats"});k.innerHTML=`${y} of ${x} in ${s.timelineYear} \xB7 current streak ${S}d \xB7 best streak ${M}d`}function Ol(s,t){var x,S;let e=s.getFilteredRows();if(s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${e.length} of ${s.rows.length} entries`}),!e.length){let M=t.createDiv({cls:"csv-empty-state"});M.createEl("p",{text:s.searchQuery?"No matching entries found.":"No entries yet."}),s.searchQuery&&M.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=M=>{s.focusIndex=(M%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",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&&((S=n[o])!=null&&S.trim())){let M=c.createDiv({cls:"csv-focus-notes"});s.renderMarkdownInto(M,n[o])}let u=new Set([i,o,r].filter(Boolean)),f=s.headers.filter(M=>{var E;return!u.has(M)&&((E=n[M])!=null?E:"").trim()});if(f.length){let M=c.createDiv({cls:"csv-focus-meta"});f.forEach(E=>{let v=M.createDiv({cls:"csv-kanban-chip"});if(v.createSpan({cls:"csv-chip-label",text:E+": "}),s.isSelectCol(E)){let m=v.createSpan({cls:"csv-chip-value csv-chip-select",text:n[E]});m.addEventListener("click",C=>{C.stopPropagation(),Ot(m,n[E],s.getColumnValues(E),k=>{n[E]=k,m.setText(k||"\u2014"),s.scheduleSave()},s.contentEl,{multi:Wt(E)})})}else v.createSpan({cls:"csv-chip-value",text:n[E]})})}c.addEventListener("contextmenu",M=>s.openRowContextMenu(n,M));let p=a.createDiv({cls:"csv-focus-nav"}),g=p.createEl("button",{cls:"csv-focus-nav-btn",text:"\u2039",title:"Previous (\u2190)"}),b=p.createEl("button",{cls:"csv-focus-nav-btn csv-focus-nav-rand",text:"\u{1F500}",title:"Random entry"}),y=p.createEl("button",{cls:"csv-focus-nav-btn",text:"\u203A",title:"Next (\u2192)"});g.addEventListener("click",()=>l(s.focusIndex-1)),y.addEventListener("click",()=>l(s.focusIndex+1)),b.addEventListener("click",()=>{if(e.length<2)return;let M=s.focusIndex;for(;M===s.focusIndex;)M=Math.floor(Math.random()*e.length);l(M)}),a.addEventListener("keydown",M=>{M.key==="ArrowLeft"?(M.preventDefault(),l(s.focusIndex-1)):M.key==="ArrowRight"&&(M.preventDefault(),l(s.focusIndex+1))}),(s.focusNavPending||document.activeElement===document.body)&&(s.focusNavPending=!1,a.focus({preventScroll:!0}))}var Hs,cs=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.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 Ws}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=Ee(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&&!Jt(this)||i&&!this.hasDateColumn()||this.mode==="travel"&&!this.isTravelFile()||this.mode==="stats"&&!Zs(this)||this.mode==="tasks"&&!$e(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=Il.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())}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(["Notes","notes","Note","note","Summary","summary","Review","review","Quote","quote","Quotes","quotes","Comment","comment","Comments","comments","Description","description","Annotation","annotation"])}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())}getStatusCol(){var e;return this.fileCfg.statusColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(["Status","status","State","state","Progress","progress","Stage","stage","Read","read","Watched","watched","Seen","seen","Done","done","Completed","completed"])}getCategoryCol(){var e;return this.fileCfg.categoryColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(["Category","category","Categories","categories","Genre","genre","Genres","genres","Type","type","Types","types","Tag","tag","Tags","tags","Topic","topic","Topics","topics","Subject","subject","Section","section"])}titleKey(){var e;return(e=this.resolveCol(["Title","title","Name","name"]))!=null?e: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()}notesFilePath(e){var a,l,c;let n=qn(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)));let o=this.getNotesCol();o&&i.addItem(a=>a.setTitle("Open entry").setIcon("maximize").onClick(()=>this.openNoteExpander(e,o)));let r=this.getStatusCol();if(r){let a=this.getColumnValues(r);a.length&&(i.addSeparator(),a.forEach(l=>{l!==e[r]&&i.addItem(c=>c.setTitle(`Mark as: ${l}`).onClick(()=>{e[r]=l,this.scheduleSave(),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=this.headers.filter(p=>!this.isNotesCol(p)&&e[p]).map(p=>`${p}: "${e[p].replace(/"/g,'\\"')}"`),l=$e(this)?ii(this):null,c=l?((o=e[l])!=null?o:"").split(",").map(p=>mo(p.trim())).filter(Boolean).map(p=>`project-${p}`):[];c.length&&a.unshift(`tags: [${c.join(", ")}]`);let d=["---",...a,"---","",`# ${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 Ys(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)).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 b,y;let p=(y=(b=f.querySelector(".csv-kanban-col-title"))==null?void 0:b.textContent)!=null?y:"",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(b=>{var M,E;let y=(E=(M=b.querySelector(".csv-kanban-col-title"))==null?void 0:M.textContent)!=null?E:"",x=b.querySelector(".csv-kanban-col-body"),S=r.cols.get(y);x&&S!=null&&(x.scrollTop=S)})};a(),requestAnimationFrame(()=>{a(),requestAnimationFrame(a)}),setTimeout(a,50)}openAddModal(){let e={};if($e(this)){let n=Js(this);n&&(e[n]=["Task","Note","Idea"]);let i=tn(this);i&&(e[i]=["Low","Medium","High"])}new Us(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).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:Wt(i)})}),r}renderView(e=!1){var o;let n=this.contentEl;e?this.contentArea&&this.contentArea.empty():(n.empty(),n.addClass("csv-card-view-root"),this.renderComponent.unload(),this.renderComponent=new it.Component,this.renderComponent.load(),sr(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"?Ro(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"?Rl(this,i):this.mode==="library"?Wo(this,i):this.mode==="kanban-genre"?$o(this,i):this.mode==="stats"?zo(this,i):this.mode==="focus"?Ol(this,i):this.mode==="tasks"?er(this,i):Fo(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(Hs!==void 0)return Hs;let e=(0,it.normalizePath)(`${this.app.vault.configDir}/plugins/csv-card-view/world-map.svg`);try{Hs=await this.app.vault.adapter.read(e)}catch(n){Hs=null}return Hs}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 bo(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.length>0?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.autoDetectBooleanColumns()}autoDetectBooleanColumns(){let e=["0","1","true","false","yes","no",""];return this.headers.filter(n=>n===this.getDateCol()||this.isNotesCol(n)?!1:this.rows.map(o=>{var r;return((r=o[n])!=null?r:"").toLowerCase().trim()}).every(o=>e.includes(o)))}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){let n=(e!=null?e:"").toLowerCase().trim();return n==="1"||n==="true"||n==="yes"}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=en(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)}},Yf=[{id:"tasks",command:"Create tasks file",defaultName:"Tasks",headers:["Title","Type","Project","Status","Priority","Due","Notes"],mode:"tasks"},{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"}],$n=class extends it.Plugin{constructor(){super(...arguments);this.settings=Gn}async onload(){await this.loadSettings(),this.registerView(Ws,e=>new cs(e,this.settings,()=>this.saveSettings())),this.registerExtensions(["csv"],Ws),this.addSettingTab(new Qs(this.app,this)),this.registerMarkdownCodeBlockProcessor("csv-add",async(e,n,i)=>{await Io(this.app,e.trim(),n,i)}),this.registerMarkdownCodeBlockProcessor("csv-random",async(e,n,i)=>{await nr(this.app,e.trim(),n,i)}),this.addCommand({id:"add-entry",name:"Add entry to current CSV",checkCallback:e=>{let n=this.app.workspace.getActiveViewOfType(cs);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(cs);return n?(e||n.cycleMode(),!0):!1}});for(let e of Yf)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]&&(Co(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 Gs(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=qn(n),a=(0,it.normalizePath)(`${o}${r}.csv`);for(let c=2;this.app.vault.getAbstractFileByPath(a);c++)a=(0,it.normalizePath)(`${o}${r} ${c}.csv`);let l=await this.app.vault.create(a,e.headers.join(",")+` -`);this.settings.fileConfigs[l.path]={...this.settings.fileConfigs[l.path],defaultMode:e.mode},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({},Gn,await this.loadData()),this.settings.residencyRules=JSON.parse(JSON.stringify((e=this.settings.residencyRules)!=null?e:[]))}async saveSettings(){await this.saveData(this.settings)}}; +${ci}`}async function Jo(s){var c,d,h,u,f,p,m,g,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 _=s.getBooleanColumns();l=Xo({filePath:a,csvPath:i,habitCols:_,labels:_.map(kt),dateCol:o})}else if(r){let _=(f=(u=(h=s.titleKey())!=null?h:s.resolveCol(["Quote","quote","Headline","headline","Phrase","phrase"]))!=null?u:s.headers[0])!=null?f:"Title";l=Qo({filePath:a,csvPath:i,titleKey:_,categoryCol:r,statusCol:(p=s.getStatusCol())!=null?p:"Status",authorKey:(m=s.authorKey())!=null?m:"",yearCol:(g=s.resolveCol(["Year","year","Released","released"]))!=null?g:"",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=Zo({filePath:a,csvPath:i,headers:s.headers});try{let _=s.app.vault.getAbstractFileByPath(n);_&&_ instanceof Me.TFile?(await s.app.vault.modify(_,l),new Me.Notice(`Updated: ${n}`)):(await s.app.vault.create(n,l),new Me.Notice(`Created: ${n}`))}catch(_){let E=s.app.vault.getAbstractFileByPath(n);E instanceof Me.TFile&&(await s.app.vault.modify(E,l),new Me.Notice(`Updated: ${n}`))}}var he=require("obsidian"),_c="http://127.0.0.1:8765",Cc=6;async function tr(s,t){let e;try{e=await(0,he.requestUrl)({url:_c,method:"POST",contentType:"application/json",body:JSON.stringify({action:s,version:Cc,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 Sc(s){var e,n,i;let t=s.fileCfg.ankiFrontCol;return t&&s.headers.includes(t)?t:(i=(n=(e=s.titleKey())!=null?e:s.resolveCol(["Quote","Headline","Phrase","Term","Word","Question","Front","Name","Title"]))!=null?n:s.headers[0])!=null?i:null}function di(s){return s.replace(/&/g,"&").replace(//g,">")}function wc(s,t,e){return s.headers.filter(n=>{var i;return n!==e&&((i=t[n])!=null?i:"").trim()}).map(n=>`${di(n)}: ${di(t[n].trim())}`).join("
")}async function er(s){if(!s.file)return;let t=Sc(s);if(!t){new he.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 he.Notice(`Nothing to sync \u2014 no rows with a "${t}" value.`,6e3);return}let i=new he.Notice(`Syncing ${n.length} cards to Anki deck \u201C${e}\u201D\u2026`,0);try{await tr("createDeck",{deck:e});let o=n.map(c=>({deckName:e,modelName:"Basic",fields:{Front:di(c[t].trim()),Back:wc(s,c,t)},options:{allowDuplicate:!1,duplicateScope:"deck"},tags:["csv-card-view"]})),r=await tr("addNotes",{notes:o}),a=r.filter(c=>c!=null).length,l=r.length-a;i.hide(),new he.Notice(`Anki sync: ${a} added${l?`, ${l} already present`:""} (deck \u201C${e}\u201D).`,6e3)}catch(o){i.hide(),new he.Notice(`Anki sync failed: ${o instanceof Error?o.message:String(o)}`,8e3)}}function dn(s){return s.resolveCol(["Type","type","Kind","kind","Item","item"])}function fi(s){var t;return(t=s.resolveCol(["Project","project","Projects","projects","Area","area"]))!=null?t:Nt(s)}function or(s){return s.resolveCol(["Due","due","Deadline","deadline","Due Date","Due date","due date"])}function hn(s){return s.resolveCol(["Priority","priority","Prio","prio","Importance","importance"])}var Ec=["task","todo","to-do","action",""],kc=["task","todo","to-do","action","note","idea","reference","ref"],rr=["done","complete","completed","finished","closed","resolved","yes","x","\u2713","true"],Mc={high:0,med:1,medium:1,normal:1,low:2};function Ye(s){if(or(s)||hn(s))return!0;let t=dn(s);return t?s.rows.some(e=>{var n;return kc.includes(((n=e[t])!=null?n:"").trim().toLowerCase())}):!1}function Dc(s,t,e){var n;return e?Ec.includes(((n=t[e])!=null?n:"").trim().toLowerCase()):!0}function Tc(s,t,e){if(Dc(s,t,e))return"task";let n=(e?t[e]:"").trim().toLowerCase();return n==="idea"||n==="ideas"?"idea":"note"}function hi(s,t,e){var n;return e?rr.includes(((n=t[e])!=null?n:"").trim().toLowerCase()):!1}function sr(s){let t=Mc[(s!=null?s:"").trim().toLowerCase()];return t===void 0?3:t}function nr(s){return(s!=null?s:"").trim()?0:1}function Lc(){return new Date().toISOString().slice(0,10)}function Ac(s,t){let e=new Map;s.rows.forEach(o=>{var a,l;let r=((a=o[t])!=null?a:"").trim();r&&rr.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 ar(s,t){var D;let e=fi(s),n=dn(s),i=s.getStatusCol(),o=or(s),r=hn(s),a=(D=s.titleKey())!=null?D:s.headers[0],l=t.createDiv({cls:"csv-library-filters"}),c=new Set;e&&s.rows.forEach(M=>{var C;((C=M[e])!=null?C:"").split(",").map(T=>T.trim()).filter(Boolean).forEach(T=>c.add(T))});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 T;let C=((T=M[n])!=null?T:"").trim();C&&h.add(C)});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(),m=s.rows.filter(M=>{var C,T;return!(s.taskProjectFilter!=="all"&&e&&!((C=M[e])!=null?C:"").split(",").map(A=>A.trim().toLowerCase()).includes(s.taskProjectFilter.toLowerCase())||s.taskTypeFilter!=="all"&&n&&((T=M[n])!=null?T:"").trim().toLowerCase()!==s.taskTypeFilter.toLowerCase()||p&&!s.headers.some(k=>{var A;return((A=M[k])!=null?A:"").toLowerCase().includes(p)}))});(s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"||p)&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${m.length} of ${s.rows.length} entries`});let g={},b={},x={},_={task:g,note:b,idea:x},E=M=>{var T;return e&&((T=M[e])!=null?T:"").split(",").map(k=>k.trim()).filter(Boolean)[0]||"\u2014"};m.forEach(M=>{var k;let C=_[Tc(s,M,n)],T=E(M);((k=C[T])!=null?k:C[T]=[]).push(M)});let w=t.createDiv({cls:"csv-tasks"}),v=Lc(),y=i?Ac(s,i):"done";ui(w,"Tasks",g,(M,C)=>{C.sort((T,k)=>{var O,z,G,$,L,V;let A=hi(s,T,i),P=hi(s,k,i);if(A!==P)return A?1:-1;if(r){let W=sr((O=T[r])!=null?O:"")-sr((z=k[r])!=null?z:"");if(W)return W}if(o){let W=nr((G=T[o])!=null?G:"")-nr(($=k[o])!=null?$:"");if(W)return W;let j=((L=T[o])!=null?L:"").localeCompare((V=k[o])!=null?V:"");if(j)return j}return s.getTitle(T).localeCompare(s.getTitle(k))}),C.forEach(T=>{var $;let k=hi(s,T,i),A=M.createEl("tr"),P=A.createEl("td",{cls:"csv-tasks-check-cell"});if(i){let L=P.createEl("span",{cls:`csv-tasks-check ${k?"is-done":""}`,text:k?"\u2713":""});L.setAttr("title",k?"Mark not done":"Mark done"),L.addEventListener("click",V=>{V.stopPropagation(),T[i]=k?"":y,s.scheduleSave(),s.renderView(!0)})}ir(s,A,T,a,k);let O=A.createEl("td",{cls:"csv-tasks-due"}),z=o?(($=T[o])!=null?$:"").slice(0,10):"";O.setText(z||"\u2014"),z&&!k&&z{var W;L.stopPropagation();let V=Array.from(new Set([...s.getColumnValues(r),"high","medium","low"]));Ot(G,(W=T[r])!=null?W:"",V,j=>{T[r]=j,s.scheduleSave(),s.renderView(!0)},s.contentEl)})),A.addEventListener("contextmenu",L=>s.openRowContextMenu(T,L))})},["","Name","Due","Priority"]);let S=(M,C)=>{C.sort((T,k)=>s.getTitle(T).localeCompare(s.getTitle(k))),C.forEach(T=>{let k=M.createEl("tr"),A=n&&T[n]||"",P=k.createEl("td",{cls:"csv-tasks-type-cell"});A&&P.createSpan({cls:"csv-tasks-type-pill",text:A}),ir(s,k,T,a,!1),k.addEventListener("contextmenu",O=>s.openRowContextMenu(T,O))})};if(ui(w,"Notes",b,S,["Type","Name"]),ui(w,"Ideas",x,S,["Type","Name"]),Object.keys(g).length===0&&Object.keys(b).length===0&&Object.keys(x).length===0){let M=w.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 ui(s,t,e,n,i){if(Object.keys(e).length===0)return;s.createDiv({cls:"csv-tasks-section-header",text:t});let o=s.createDiv({cls:"csv-tasks-section"});Object.keys(e).sort().forEach(r=>{let a=e[r],l=o.createEl("details",{cls:"csv-tasks-group"});l.open=!0;let c=l.createEl("summary",{cls:"csv-tasks-group-header"});c.innerHTML=`\u25B6 ${r} ${a.length}`;let d=l.createEl("table",{cls:"csv-tasks-table"}),u=d.createEl("thead").createEl("tr");i.forEach(p=>u.createEl("th",{text:p}));let f=d.createEl("tbody");n(f,a)})}function ir(s,t,e,n,i){let o=t.createEl("td",{cls:"csv-tasks-name-cell"}),r=o.createSpan({cls:`csv-tasks-link ${i?"csv-tasks-done":""}`,text:e[n]||"Untitled"}),a=s.getNotesCol();r.addEventListener("click",()=>{a?s.openNoteExpander(e,a):s.openOrCreateNotes(e)});let l=s.notesFileExists(e),c=o.createEl("button",{cls:`csv-tasks-page-icon ${l?"exists":""}`,text:l?"\u{1F4C4}":"+"});c.setAttr("title",l?"Open page":"Create page"),c.addEventListener("click",d=>{d.stopPropagation(),s.openOrCreateNotes(e)})}function un(s){let t=[];return s.isTravelFile()&&t.push({id:"travel",label:"Travel"}),s.hasDateColumn()&&t.push({id:"dashboard",label:"Dashboard"}),Ye(s)&&t.push({id:"tasks",label:"Tasks"}),Nt(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"}),an(s)&&t.push({id:"stats",label:"Stats"}),t}function lr(s,t){var f,p,m;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=un(s),r=i.createEl("select",{cls:"csv-mode-select",attr:{"aria-label":"View mode"}});if(o.forEach(({id:g,label:b})=>{let x=r.createEl("option",{text:b,value:g});s.mode===g&&(x.selected=!0)}),r.addEventListener("change",()=>{s.mode=r.value,s.renderView()}),s.mode!=="dashboard"){let g=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"}),_=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",y=>{if(y.preventDefault(),!_.value){e.removeClass("csv-toolbar--search-expanded"),g.removeClass("has-query"),s.searchQuery="",s.renderView(!0);return}_.blur()});let v=null;_.addEventListener("input",y=>{s.searchQuery=y.target.value,E.toggleClass("is-hidden",!s.searchQuery),g.toggleClass("has-query",!!s.searchQuery),v!==null&&window.clearTimeout(v),v=window.setTimeout(()=>{v=null,s.renderView(!0)},120)}),_.addEventListener("keydown",y=>{y.key==="Enter"&&(y.preventDefault(),_.blur())}),E.addEventListener("click",()=>{s.searchQuery="",_.value="",E.addClass("is-hidden"),g.removeClass("has-query"),_.focus({preventScroll:!0}),s.renderView(!0)}),s.searchQuery&&g.addClass("has-query"),g.addEventListener("click",()=>{e.addClass("csv-toolbar--search-expanded"),_.focus({preventScroll:!0})})}if(s.mode==="table"&&s.hasDateColumn()){let g=(m=s.fileCfg.sortNewestFirst)!=null?m:!0;n.createEl("button",{cls:`csv-cfg-btn ${g?"active":""}`,text:g?"\u2193 Newest":"\u2191 Oldest",title:"Toggle sort order"}).addEventListener("click",()=>{var _;let x=s.fileCfg;x.sortNewestFirst=!((_=x.sortNewestFirst)==null||_),s.saveFileCfg(x),s.tableSortCol=null,s.renderViewPreservingScroll()})}let a=()=>{var g,b;new tn(s.app,s.headers,(b=(g=s.file)==null?void 0:g.path)!=null?b:"",s.fileCfg,s.autoDetectBooleanColumns(),un(s),x=>{s.saveFileCfg(x),x.defaultMode&&(s.mode=x.defaultMode),s.renderView()}).open()},l=()=>Jo(s),c=()=>s.backupToArchive(),d=()=>er(s);n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u2699 Columns",title:"Configure columns for this file"}).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",g=>{let b=new fn.Menu;b.addItem(x=>x.setTitle("Columns").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-06-29 01:33").setIcon("info").setDisabled(!0)),b.showAtMouseEvent(g)}),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary csv-info-btn",text:"\u24D8",title:"Built 2026-06-29 01:33 \u2014 click to confirm"}).addEventListener("click",()=>new fn.Notice("csv-card-view \u2014 built 2026-06-29 01:33",4e3))}function Pc(s){return s&&typeof s=="object"&&"basename"in s?s:null}var Rc=["Author","author","By","by","Source","source","Speaker","speaker","Artist","artist","Director","director"];async function cr(s,t,e,n){var x,_,E;let i=t.split(` +`).map(w=>w.trim()).filter(Boolean),o=w=>{var v,y;return(y=(v=i.find(S=>S.startsWith(w+":")))==null?void 0:v.slice(w.length+1).trim())!=null?y:""},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=(_=(x=a==null?void 0:a.parent)==null?void 0:x.path)!=null?_:"",c=We(r,l),d=Pc(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 w=Gt(await s.vault.read(d));h=w.headers,u=w.rows}catch(w){e.createEl("p",{text:`Error reading file: ${w}`,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(w=>w.toLowerCase()===f.toLowerCase()))!=null?E:h[0],m=Rc.map(w=>h.find(v=>v===w)).find(Boolean),g=e.createDiv({cls:"csv-random-card"}),b=()=>{var C;g.empty();let w=u.filter(T=>{var k;return((k=T[p])!=null?k:"").trim()}),v=w.length?w:u,y=v[Math.floor(Math.random()*v.length)];g.createDiv({cls:"csv-random-text",text:y[p]||"\u2014"});let S=m?((C=y[m])!=null?C:"").trim():"";S&&g.createDiv({cls:"csv-random-sub",text:`\u2014 ${S}`});let D=g.createDiv({cls:"csv-random-foot"});D.createSpan({cls:"csv-random-src",text:d.basename}),D.createEl("button",{cls:"csv-random-btn",text:"\u21BB",title:"Another one"}).addEventListener("click",b)};b()}var yo=null;async function tp(){if(yo)return yo;let s=await Promise.resolve().then(()=>(Nl(),Vl));return s.Chart.register(s.LineController,s.LineElement,s.PointElement,s.LinearScale,s.CategoryScale,s.Filler,s.Tooltip),yo=s,s}async function Bl(s,t){var W,j,U;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 I,N;return((I=B[e])!=null?I:"").localeCompare((N=F[e])!=null?N:"")});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(I=>I0&&(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&&BI>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 I={};s.headers.forEach(N=>I[N]=""),I[e]=s.selectedDate,s.rows.push(I),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(N=>{let R=s.isTruthy(a[N]),Y=F.createDiv({cls:`csv-dash-habit ${R?"checked":""}`}),K=Y.createEl("button",{cls:"csv-dash-habit-check",text:R?"\u25CF":"\u25CB"});Y.createSpan({cls:"csv-dash-habit-label",text:N}),K.addEventListener("click",()=>{a[N]=R?"0":"1",s.scheduleSave(),s.renderViewPreservingScroll()})});let I=n.filter(N=>s.isTruthy(a[N])).length;if(B.createDiv({cls:"csv-dash-habits-count",text:`${I} of ${n.length} complete`}),i&&((W=a[i])!=null&&W.trim())){let N=B.createDiv({cls:"csv-dash-notes-preview"});N.createEl("strong",{text:"Notes: "}),N.createSpan({text:a[i].slice(0,200)+(a[i].length>200?"\u2026":"")})}}let m=t.createDiv({cls:"csv-dash-chart-section"});m.createEl("h3",{text:"Progress",cls:"csv-dash-section-title"});let b=m.createDiv({cls:"csv-dash-chart-wrap"}).createEl("canvas",{cls:"csv-dash-chart"}),x=r.map(B=>{var I;return((I=B[e])!=null?I:"").slice(5)}),_=r.map(B=>n.filter(F=>s.isTruthy(B[F])).length);s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:E}=await tp();if(!b.isConnected)return;s.chartInstance=new E(b,{type:"line",data:{labels:x,datasets:[{label:"Habits done",data:_,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 w=t.createDiv({cls:"csv-dash-stats-section"});w.createEl("h3",{text:"Stats",cls:"csv-dash-section-title"});let v=r.length,y=r.reduce((B,F)=>B+n.filter(I=>s.isTruthy(F[I])).length,0),S=v>0?(y/v).toFixed(1):"0",D=r.filter(B=>n.every(F=>s.isTruthy(B[F]))).length,M=0,C=0,T=null;for(let B of r){let F=n.filter(R=>s.isTruthy(B[R])).length,I=s.parseDate((j=B[e])!=null?j:""),N=!0;T&&I&&Math.round((I.getTime()-T.getTime())/864e5)!==1&&(N=!1),F>=1&&(N||T===null)?(C++,C>M&&(M=C)):F>=1?(C=1,C>M&&(M=C)):C=0,T=I}let k=0,A=new Date;A.setHours(0,0,0,0);let P=A;for(let B=r.length-1;B>=0;B--){let F=s.parseDate((U=r[B][e])!=null?U:"");if(!F)break;let I=Math.round((P.getTime()-F.getTime())/(1e3*60*60*24));if(k===0&&I>1||k>0&&I!==1)break;if(n.filter(R=>s.isTruthy(r[B][R])).length>=1)k++,P=F;else break}let O=w.createDiv({cls:"csv-dash-stats-bar"});O.innerHTML=`${v} days logged \xB7 ${S} avg/day \xB7 ${D} perfect days \xB7 current streak ${k}d \xB7 best streak ${M}d`;let G=t.createDiv({cls:"csv-dash-cards-section"}).createDiv({cls:"csv-dash-cards-grid"}),$=new Date().getFullYear(),L={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(K=>s.isTruthy(K[B])),I=F.length>0?F[F.length-1][e]:null,N=new Set;F.forEach(K=>{var X;let Z=s.parseDate((X=K[e])!=null?X:"");Z&&N.add(Z.getFullYear())});let R=r.filter(K=>{var X;let Z=s.parseDate((X=K[e])!=null?X:"");return Z&&Z.getFullYear()===$}),Y=R.filter(K=>s.isTruthy(K[B])).length;return{habit:B,doneCount:F.length,doneThisYear:Y,totalThisYear:R.length,lastDone:I,years:Array.from(N).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:I,totalThisYear:N,lastDone:R,years:Y})=>{var st;let K=G.createDiv({cls:"csv-dash-habit-card"}),Z=(st=L[B.toLowerCase()])!=null?st:"\u25CB",X=K.createDiv({cls:"csv-dash-habit-card-header"});if(X.createSpan({cls:"csv-dash-habit-icon",text:Z}),X.createSpan({cls:"csv-dash-habit-card-name",text:kt(B)}),Y.length>0&&K.createDiv({cls:"csv-dash-habit-years"}).setText(Y.join(" \xB7 ")),K.createDiv({cls:"csv-dash-habit-card-thisyear",text:`${I} of ${N} complete this year`}),K.createDiv({cls:"csv-dash-habit-card-alltime",text:`${F} of ${v} all time`}),R){let at=s.parseDate(R),Rt=at?at.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):R;K.createDiv({cls:"csv-dash-habit-card-last",text:`Last logged: ${Rt}`})}else K.createDiv({cls:"csv-dash-habit-card-last",text:"Never logged"});let q=v>0?F/v*100:0,J=K.createDiv({cls:"csv-dash-habit-progress"}).createDiv({cls:"csv-dash-habit-progress-bar"});J.style.width=`${q}%`,K.addEventListener("click",()=>{s.selectedHabit=s.selectedHabit===B?null:B,s.renderViewPreservingScroll()}),s.selectedHabit===B&&K.addClass("selected")}),s.selectedHabit&&n.includes(s.selectedHabit)&&ep(s,t,r,e,s.selectedHabit)}function ep(s,t,e,n,i){var M,C,T;let o=t.createDiv({cls:"csv-dash-timeline-section"}),r=o.createDiv({cls:"csv-dash-timeline-header"});r.createEl("h3",{text:`${kt(i)} Timeline`,cls:"csv-dash-section-title"});let a=r.createEl("select",{cls:"csv-dash-year-select"}),l=new Set;e.forEach(k=>{var P;let A=s.parseDate((P=k[n])!=null?P:"");A&&l.add(A.getFullYear())}),l.add(new Date().getFullYear()),Array.from(l).sort().reverse().forEach(k=>{let A=a.createEl("option",{text:String(k),value:String(k)});k===s.timelineYear&&(A.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(k=>{var A;d.set((A=k[n])!=null?A:"",s.isTruthy(k[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(k=>u.createSpan({cls:"csv-dash-timeline-month-label",text:k}));let p=h.createDiv({cls:"csv-dash-timeline-calendar"}),m=p.createDiv({cls:"csv-dash-timeline-day-labels"});for(let k=1;k<=31;k++)m.createDiv({cls:"csv-dash-timeline-day-label",text:k%5===0||k===1?String(k):""});for(let k=0;k<12;k++){let A=p.createDiv({cls:"csv-dash-timeline-month-col"}),P=new Date(s.timelineYear,k+1,0).getDate();for(let O=1;O<=31;O++){if(O>P){A.createDiv({cls:"csv-dash-timeline-cell empty"});continue}let z=`${s.timelineYear}-${String(k+1).padStart(2,"0")}-${String(O).padStart(2,"0")}`,G=(M=d.get(z))!=null?M:!1,$=d.has(z),L=new Date(s.timelineYear,k,O)>new Date,V=A.createDiv({cls:`csv-dash-timeline-cell ${L?"future":""} ${G?"done":""} ${$&&!G?"missed":""} ${!$&&!L?"no-entry":""}`});V.title=`${z}: ${L?"Future":G?"\u2713 Done":$?"\u2717 Missed":"No entry"}`}}let g=e.filter(k=>{var P;let A=s.parseDate((P=k[n])!=null?P:"");return A&&A.getFullYear()===s.timelineYear}),b=g.filter(k=>s.isTruthy(k[i])).length,x=g.length,_=0,E=0,w=0,v=null;for(let k of e){let A=s.isTruthy(k[i]),P=s.parseDate((C=k[n])!=null?C:""),O=!0;v&&P&&Math.round((P.getTime()-v.getTime())/864e5)!==1&&(O=!1),A&&(O||v===null)?(w++,w>E&&(E=w)):A?w=1:w=0,v=P}let y=new Date;y.setHours(0,0,0,0);let S=y;for(let k=e.length-1;k>=0;k--){let A=s.parseDate((T=e[k][n])!=null?T:"");if(!A)break;let P=Math.round((S.getTime()-A.getTime())/(1e3*60*60*24));if(_===0&&P>1||_>0&&P!==1)break;if(s.isTruthy(e[k][i]))_++,S=A;else break}let D=o.createDiv({cls:"csv-dash-timeline-stats"});D.innerHTML=`${b} of ${x} in ${s.timelineYear} \xB7 current streak ${_}d \xB7 best streak ${E}d`}function zl(s,t){var x,_;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 E=t.createDiv({cls:"csv-empty-state"});E.createEl("p",{text:s.searchQuery?"No matching entries found.":"No entries yet."}),s.searchQuery&&E.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=E=>{s.focusIndex=(E%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",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&&((_=n[o])!=null&&_.trim())){let E=c.createDiv({cls:"csv-focus-notes"});s.renderMarkdownInto(E,n[o])}let u=new Set([i,o,r].filter(Boolean)),f=s.headers.filter(E=>{var w;return!u.has(E)&&((w=n[E])!=null?w:"").trim()});if(f.length){let E=c.createDiv({cls:"csv-focus-meta"});f.forEach(w=>{let v=E.createDiv({cls:"csv-kanban-chip"});if(v.createSpan({cls:"csv-chip-label",text:w+": "}),s.isSelectCol(w)){let y=v.createSpan({cls:"csv-chip-value csv-chip-select",text:n[w]});y.addEventListener("click",S=>{S.stopPropagation(),Ot(y,n[w],s.getColumnValues(w),D=>{n[w]=D,y.setText(D||"\u2014"),s.scheduleSave()},s.contentEl,{multi:It(w)})})}else v.createSpan({cls:"csv-chip-value",text:n[w]})})}c.addEventListener("contextmenu",E=>s.openRowContextMenu(n,E));let p=a.createDiv({cls:"csv-focus-nav"}),m=p.createEl("button",{cls:"csv-focus-nav-btn",text:"\u2039",title:"Previous (\u2190)"}),g=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)"});m.addEventListener("click",()=>l(s.focusIndex-1)),b.addEventListener("click",()=>l(s.focusIndex+1)),g.addEventListener("click",()=>{if(e.length<2)return;let E=s.focusIndex;for(;E===s.focusIndex;)E=Math.floor(Math.random()*e.length);l(E)}),a.addEventListener("keydown",E=>{E.key==="ArrowLeft"?(E.preventDefault(),l(s.focusIndex-1)):E.key==="ArrowRight"&&(E.preventDefault(),l(s.focusIndex+1))}),(s.focusNavPending||document.activeElement===document.body)&&(s.focusNavPending=!1,a.focus({preventScroll:!0}))}var Pt=require("obsidian"),$l=qs(bs());var sp=[{id:"table",label:"Table"},{id:"library",label:"Cards"},{id:"kanban-genre",label:"Kanban"}];function Hl(s){return s&&typeof s=="object"&&"basename"in s?s:null}function np(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 xo=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=Gt(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=Hl(e))})))}onunload(){this.saveTimer&&window.clearTimeout(this.saveTimer)}async reload(){let e=Hl(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=Gt(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=$l.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())}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(["Notes","notes","Note","note","Summary","summary","Review","review","Quote","quote","Quotes","quotes","Comment","comment","Comments","comments","Description","description","Annotation","annotation"])}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())}getStatusCol(){var e;return this.fileCfg.statusColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(["Status","status","State","state","Progress","progress","Stage","stage","Read","read","Watched","watched","Seen","seen","Done","done","Completed","completed"])}getCategoryCol(){var e;return this.fileCfg.categoryColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(["Category","category","Categories","categories","Genre","genre","Genres","genres","Type","type","Types","types","Tag","tag","Tags","tags","Topic","topic","Topics","topics","Subject","subject","Section","section"])}titleKey(){var e;return(e=this.resolveCol(["Title","title","Name","name"]))!=null?e: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(Qs)}getBooleanColumns(){var n;if((n=this.fileCfg.habitColumns)!=null&&n.length)return this.fileCfg.habitColumns.filter(i=>this.headers.includes(i));let e=["0","1","true","false","yes","no",""];return this.headers.filter(i=>i===this.getDateCol()||this.isNotesCol(i)?!1:this.rows.map(o=>{var r;return((r=o[i])!=null?r:"").toLowerCase().trim()}).every(o=>e.includes(o)))}getDateCol(){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(o=>{var r;return n.test((r=o[e])!=null?r:"")})?e:null}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=ys(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(r=>r.setTitle("Open / Create Notes file").setIcon("file-text").onClick(()=>void this.openOrCreateNotes(e))),i.addItem(r=>r.setTitle("Open entry").setIcon("maximize").onClick(()=>{var a;return this.openNoteExpander(e,(a=this.getNotesCol())!=null?a:"")}));let o=this.getStatusCol();if(o){let r=this.getColumnValues(o);r.length&&(i.addSeparator(),r.forEach(a=>{a!==e[o]&&i.addItem(l=>l.setTitle(`Mark as: ${a}`).onClick(()=>{e[o]=a,this.scheduleSave(),this.renderView()}))}))}i.addSeparator(),i.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),i.showAtMouseEvent(n)}openNoteExpander(e,n){var i,o;new Ue(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)).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)).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")&&!Nt(this.asView)&&(this.mode="table"),this.mode==="library"?cn(this.asView,i):this.mode==="kanban-genre"?ln(this.asView,i):rn(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=!!Nt(this.asView),r=i.createDiv({cls:"csv-mode-group"});sp.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 Wl(s,t,e,n){n("csv-view",(i,o,r)=>{var h,u,f;let a=np(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?We(a.file,l):a.file,d=new xo(o,s,t,e,{...a,file:c});r.addChild(d)})}var Gs,ps=class extends rt.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 rt.Component,this.renderComponent.load()}getViewType(){return Xs}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=Gt(r);this.headers=a.headers,this.rows=a.rows}catch(r){console.error("CardView load error",r),this.headers=[],this.rows=[],new rt.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&&!Nt(this)||i&&!this.hasDateColumn()||this.mode==="travel"&&!this.isTravelFile()||this.mode==="stats"&&!an(this)||this.mode==="tasks"&&!Ye(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=jl.default.unparse(this.rows,{columns:this.headers});await this.app.vault.modify(this.file,e)}catch(e){console.error("CardView save error",e),new rt.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())}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(["Notes","notes","Note","note","Summary","summary","Review","review","Quote","quote","Quotes","quotes","Comment","comment","Comments","comments","Description","description","Annotation","annotation"])}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())}getStatusCol(){var e;return this.fileCfg.statusColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(["Status","status","State","state","Progress","progress","Stage","stage","Read","read","Watched","watched","Seen","seen","Done","done","Completed","completed"])}getCategoryCol(){var e;return this.fileCfg.categoryColumn?(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(["Category","category","Categories","categories","Genre","genre","Genres","genres","Type","type","Types","types","Tag","tag","Tags","tags","Topic","topic","Topics","topics","Subject","subject","Section","section"])}titleKey(){var e;return(e=this.resolveCol(["Title","title","Name","name"]))!=null?e: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(Qs)}notesFilePath(e){var a,l,c;let n=ys(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,rt.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 rt.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 rt.Notice(`Restored \u201C${i}\u201D`,2500)})}openRowContextMenu(e,n){let i=new rt.Menu;i.addItem(r=>r.setTitle("Open / Create Notes file").setIcon("file-text").onClick(()=>this.openOrCreateNotes(e))),i.addItem(r=>r.setTitle("Open entry").setIcon("maximize").onClick(()=>{var a;return this.openNoteExpander(e,(a=this.getNotesCol())!=null?a:"")}));let o=this.getStatusCol();if(o){let r=this.getColumnValues(o);r.length&&(i.addSeparator(),r.forEach(a=>{a!==e[o]&&i.addItem(l=>l.setTitle(`Mark as: ${a}`).onClick(()=>{e[o]=a,this.scheduleSave(),this.renderViewPreservingScroll()}))}))}i.addSeparator(),i.addItem(r=>r.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=this.headers.filter(p=>!this.isNotesCol(p)&&e[p]).map(p=>`${p}: "${e[p].replace(/"/g,'\\"')}"`),l=Ye(this)?fi(this):null,c=l?((o=e[l])!=null?o:"").split(",").map(p=>Mo(p.trim())).filter(Boolean).map(p=>`project-${p}`):[];c.length&&a.unshift(`tags: [${c.join(", ")}]`);let d=["---",...a,"---","",`# ${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 rt.Notice(`Created: ${i.name}`)}await this.app.workspace.getLeaf("tab").openFile(i)}openNoteExpander(e,n){var i,o;new Ue(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)).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 g,b;let p=(b=(g=f.querySelector(".csv-kanban-col-title"))==null?void 0:g.textContent)!=null?b:"",m=f.querySelector(".csv-kanban-col-body");p&&m&&r.cols.set(p,m.scrollTop)}),this.renderView();let a=()=>{let f=this.contentEl.querySelector(".csv-content-area"),p=this.contentEl.querySelector(".csv-table-wrapper"),m=this.contentEl.querySelector(".csv-kanban-board");f&&(f.scrollTop=r.contentTop,f.scrollLeft=r.contentLeft),p&&(p.scrollLeft=r.tableLeft,p.scrollTop=r.tableTop),m&&(m.scrollLeft=r.boardLeft),this.contentEl.querySelectorAll(".csv-kanban-col").forEach(g=>{var E,w;let b=(w=(E=g.querySelector(".csv-kanban-col-title"))==null?void 0:E.textContent)!=null?w:"",x=g.querySelector(".csv-kanban-col-body"),_=r.cols.get(b);x&&_!=null&&(x.scrollTop=_)})};a(),requestAnimationFrame(()=>{a(),requestAnimationFrame(a)}),setTimeout(a,50)}openAddModal(){let e={};if(Ye(this)){let n=dn(this);n&&(e[n]=["Task","Note","Idea"]);let i=hn(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 rt.Notice(`Added: ${this.getTitle(n)}`)},e,n=>this.getBooleanColumns().includes(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:It(i)})}),r}renderView(e=!1){var o;let n=this.contentEl;e?this.contentArea&&this.contentArea.empty():(n.empty(),n.addClass("csv-card-view-root"),this.renderComponent.unload(),this.renderComponent=new rt.Component,this.renderComponent.load(),lr(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"?Wo(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"?Bl(this,i):this.mode==="library"?cn(this,i):this.mode==="kanban-genre"?ln(this,i):this.mode==="stats"?qo(this,i):this.mode==="focus"?zl(this,i):this.mode==="tasks"?ar(this,i):rn(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 rt.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 rt.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(Gs!==void 0)return Gs;let e=(0,rt.normalizePath)(`${this.app.vault.configDir}/plugins/csv-card-view/world-map.svg`);try{Gs=await this.app.vault.adapter.read(e)}catch(n){Gs=null}return Gs}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 Do(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.length>0?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.autoDetectBooleanColumns()}autoDetectBooleanColumns(){let e=["0","1","true","false","yes","no",""];return this.headers.filter(n=>n===this.getDateCol()||this.isNotesCol(n)?!1:this.rows.map(o=>{var r;return((r=o[n])!=null?r:"").toLowerCase().trim()}).every(o=>e.includes(o)))}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){let n=(e!=null?e:"").toLowerCase().trim();return n==="1"||n==="true"||n==="yes"}renderMarkdownInto(e,n){var i,o;rt.MarkdownRenderer.render(this.app,n,e,(o=(i=this.file)==null?void 0:i.path)!=null?o:"",this.renderComponent)}cycleMode(){let e=un(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)}},ip=[{id:"tasks",command:"Create tasks file",defaultName:"Tasks",headers:["Title","Type","Project","Status","Priority","Due","Notes"],mode:"tasks"},{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"}],Zn=class extends rt.Plugin{constructor(){super(...arguments);this.settings=ni}async onload(){await this.loadSettings(),this.registerView(Xs,e=>new ps(e,this.settings,()=>this.saveSettings())),this.registerExtensions(["csv"],Xs),this.addSettingTab(new on(this.app,this)),this.registerMarkdownCodeBlockProcessor("csv-add",async(e,n,i)=>{await Uo(this.app,e.trim(),n,i)}),this.registerMarkdownCodeBlockProcessor("csv-random",async(e,n,i)=>{await cr(this.app,e.trim(),n,i)}),Wl(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(ps);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(ps);return n?(e||n.cycleMode(),!0):!1}});for(let e of ip)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 rt.TFile&&e.extension==="csv"&&this.settings.fileConfigs[n]&&(Ro(this.settings.fileConfigs,n,e.path),await this.saveSettings())})),this.registerEvent(this.app.vault.on("delete",async e=>{e instanceof rt.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 rt.TFile){let l=this.app.workspace.activeLeaf;l&&await l.openFile(a,{state:{mode:"preview"}})}})})}async createTemplateFile(e){new en(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=ys(n),a=(0,rt.normalizePath)(`${o}${r}.csv`);for(let c=2;this.app.vault.getAbstractFileByPath(a);c++)a=(0,rt.normalizePath)(`${o}${r} ${c}.csv`);let l=await this.app.vault.create(a,e.headers.join(",")+` +`);this.settings.fileConfigs[l.path]={...this.settings.fileConfigs[l.path],defaultMode:e.mode},await this.saveSettings(),await this.app.workspace.getLeaf("tab").openFile(l),new rt.Notice(`Created: ${l.name}`)}).open()}async loadSettings(){var e;this.settings=Object.assign({},ni,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 332e10d..02d2750 100644 --- a/main.ts +++ b/main.ts @@ -18,7 +18,7 @@ import type { Chart as ChartType } from "chart.js"; // Import from src modules import { CSVRow, ViewMode, FileConfig, CardViewSettings, DEFAULT_SETTINGS, CARD_VIEW_TYPE } from "./src/types"; -import { sanitizeFilename, tagify, titleCase, formatRatingForDisplay, showSelectPicker, parseCSV, migrateFileConfigKey, sortRowsByColumn, isMultiValueColName } from "./src/utils"; +import { sanitizeFilename, tagify, titleCase, formatRatingForDisplay, showSelectPicker, parseCSV, migrateFileConfigKey, sortRowsByColumn, isMultiValueColName, IMAGE_COL_ALIASES } from "./src/utils"; import { AddEntryModal, NoteExpanderModal, FileConfigModal, SearchModal, PromptModal } from "./src/modals"; import { renderTravel } from "./src/travel-view"; import { CardViewSettingTab } from "./src/settings-tab"; @@ -32,6 +32,7 @@ import { renderDashboard } from "./src/view/dashboard"; import { renderStats, hasStatsColumns } from "./src/view/stats"; import { renderFocus } from "./src/view/focus"; import { renderTasks, hasTaskColumns, taskProjectCol, taskTypeCol, taskPriorityCol } from "./src/view/tasks"; +import { registerCsvViewBlock } from "./src/inline-view"; // World-map SVG asset, loaded lazily from the plugin dir and cached for the // session (undefined = not yet read, null = read failed/missing). @@ -238,6 +239,12 @@ export class CardView extends FileView { getTitle(row: CSVRow) { const k=this.titleKey(); return (k?row[k]:row[this.headers[0]])??"—"; } getSubtitle(row: CSVRow) { const k=this.authorKey(); return k?row[k]??"":""; } getColumnValues(h: string) { return Array.from(new Set(this.rows.map(r=>r[h]??"").filter(Boolean))).sort(); } + // Image column for card/kanban thumbnails — per-file override (reuses the + // cardImageColumn config) or detected by name (Image/Cover/Poster/…). + getImageCol(): string | null { + if (this.fileCfg.imageColumn) return this.headers.find(h => h.toLowerCase() === this.fileCfg.imageColumn!.toLowerCase()) ?? null; + return this.resolveCol(IMAGE_COL_ALIASES); + } // ── Notes file ───────────────────────────────────────────────────────────── @@ -298,10 +305,9 @@ export class CardView extends FileView { openRowContextMenu(row: CSVRow, e: MouseEvent): void { const menu = new Menu(); menu.addItem(i => i.setTitle("Open / Create Notes file").setIcon("file-text").onClick(() => this.openOrCreateNotes(row))); - const notesCol = this.getNotesCol(); - if (notesCol) { - menu.addItem(i => i.setTitle("Open entry").setIcon("maximize").onClick(() => this.openNoteExpander(row, notesCol))); - } + // Always offered — the expander edits every structured field; on files + // without a notes column it simply omits the notes editor. + menu.addItem(i => i.setTitle("Open entry").setIcon("maximize").onClick(() => this.openNoteExpander(row, this.getNotesCol() ?? ""))); const sc = this.getStatusCol(); if (sc) { const statuses = this.getColumnValues(sc); @@ -448,7 +454,9 @@ export class CardView extends FileView { this.renderViewPreservingScroll(); new Notice(`Added: ${this.getTitle(row)}`); }, - optionPresets + optionPresets, + // Habit/0-1 columns render as toggles in the add form. + (h) => this.getBooleanColumns().includes(h) ).open(); } @@ -739,6 +747,10 @@ export class CardView extends FileView { libraryStatusFilter: string = "all"; libraryGenreFilter: string = "all"; + // Group values (lowercased) collapsed by default in Cards view. Only the + // inline csv-view block populates this (via its `collapse:` directive); the + // full-page view leaves it empty, so every section opens as before. + collapsedGroups: Set = new Set(); // ── Tasks view ──────────────────────────────────────────────────────────────── @@ -837,6 +849,16 @@ export default class CardViewPlugin extends Plugin { await renderRandomCard(this.app, source.trim(), el, ctx); }); + // csv-view: an inline, editable table/cards/kanban view of a CSV file — + // a .base / Notion-DB-style embed. Reuses the full-view renderers via a + // lightweight host tied to the block's lifecycle. See src/inline-view.ts. + registerCsvViewBlock( + this.app, + this.settings, + () => this.saveSettings(), + (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/add-entry-form.ts b/src/add-entry-form.ts index 81bbad9..d6d0b03 100644 --- a/src/add-entry-form.ts +++ b/src/add-entry-form.ts @@ -1,7 +1,7 @@ import { App, Notice, TFile, MarkdownPostProcessorContext } from "obsidian"; import Papa from "papaparse"; import { CSVRow } from "./types"; -import { parseCSV, resolvePath, titleCase } from "./utils"; +import { parseCSV, resolvePath, titleCase, looksCategorical } from "./utils"; // ─── csv-add code block (mobile entry form) ────────────────────────────────── // Extracted from CardViewPlugin. Depends only on `app` (vault/workspace), @@ -137,7 +137,7 @@ export async function renderAddEntryForm(app: App, source: string, el: HTMLEleme otherCols.forEach(h => { const row = makeRow(h, "field"); const uniqueVals = new Set(rows.map(r => (r[h] ?? "").trim()).filter(Boolean)); - if (uniqueVals.size > 0 && uniqueVals.size <= 15) { + if (looksCategorical(uniqueVals.size)) { const select = row.createEl("select", { cls: "csv-add-row-control" }); select.createEl("option", { text: "—", value: "" }); Array.from(uniqueVals).sort().forEach(v => select.createEl("option", { text: v, value: v })); diff --git a/src/inline-view.ts b/src/inline-view.ts new file mode 100644 index 0000000..3e6948e --- /dev/null +++ b/src/inline-view.ts @@ -0,0 +1,552 @@ +// ─── csv-view code block: an inline, editable CSV view ─────────────────────── +// +// Renders a CSV file's data as a table / cards / kanban *inside a note* — the +// way a `.base` block or a Notion linked-database renders a view in a page. +// Reuses the full-view renderers (renderTable / renderLibrary / renderKanban) +// verbatim by giving them a host object that satisfies the same duck-typed +// surface CardView exposes, but lives in a markdown block instead of a leaf. +// +// ```csv-view +// file: ../movies.csv (sibling / ../ walked / vault-relative, like csv-add) +// mode: table (table | cards | kanban — default: table) +// height: 480 (optional max content height in px) +// ``` +// +// Edits (inline cell edits, status chips, drag-free status changes via the +// row menu, the inline note editor, + Add, delete) write back to the source +// CSV via app.vault.modify, the same path the full view uses. Other open +// views of the same file (a .csv tab, or another csv-view block) re-sync off +// the vault `modify` event. See HANDOFF for the concurrency model. + +import { + App, + TFile, + Component, + MarkdownRenderChild, + MarkdownRenderer, + MarkdownPostProcessorContext, + Menu, + Notice, + normalizePath, +} from "obsidian"; +import Papa from "papaparse"; +import type { CardView } from "../main"; +import { CSVRow, ViewMode, FileConfig, CardViewSettings } from "./types"; +import { parseCSV, resolvePath, sanitizeFilename, showSelectPicker, IMAGE_COL_ALIASES } from "./utils"; +import { AddEntryModal, NoteExpanderModal } from "./modals"; +import { renderTable } from "./view/table"; +import { renderLibrary } from "./view/library"; +import { renderKanbanGenre, effectiveGroupCol } from "./view/kanban"; + +/** Modes the inline view offers. A subset of the full ViewMode union. */ +type InlineMode = "table" | "library" | "kanban-genre"; + +const MODE_LABELS: { id: InlineMode; label: string }[] = [ + { id: "table", label: "Table" }, + { id: "library", label: "Cards" }, + { id: "kanban-genre", label: "Kanban" }, +]; + +/** + * Duck-typed TFile check — mirrors random-block.ts so the block is drivable + * with a stub vault in the smoke tests (cross-bundle instanceof is unreliable). + */ +function asFile(f: unknown): TFile | null { + return f && typeof f === "object" && "basename" in (f as object) ? (f as TFile) : null; +} + +interface BlockOptions { + file: string; + mode: InlineMode; + height: number | null; + collapse: string[]; // group values collapsed by default in Cards view +} + +/** Parse the `key: value` lines of a csv-view block. Forgiving, like csv-random. */ +function parseBlockSource(source: string): BlockOptions { + 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 rawMode = opt("mode").toLowerCase(); + const mode: InlineMode = + rawMode === "kanban" || rawMode === "kanban-genre" ? "kanban-genre" + : rawMode === "cards" || rawMode === "card" || rawMode === "library" ? "library" + : "table"; + + const heightRaw = parseInt(opt("height"), 10); + return { + file: opt("file"), + mode, + height: Number.isFinite(heightRaw) && heightRaw > 0 ? heightRaw : null, + collapse: opt("collapse").split(",").map(s => s.trim()).filter(Boolean), + }; +} + +/** + * Inline host for the CSV renderers. Tied to the markdown block's lifecycle + * via MarkdownRenderChild (ctx.addChild → onunload on block teardown), which + * also gives it registerEvent for the vault `modify` listener. It re-implements + * the model/interaction surface CardView exposes — the renderers reach the same + * members on either, so renderTable/renderLibrary/renderKanban work unchanged. + */ +export class InlineCardHost extends MarkdownRenderChild { + app: App; + settings: CardViewSettings; + persistSettings: () => Promise; + file: TFile | null = null; + private opts: BlockOptions; + // Component for MarkdownRenderer.render (notes preview / expander markdown). + // MarkdownRenderChild is itself a Component, so `this` works — kept as a + // named field to read the same as CardView's renderComponent call sites. + private get renderComponent(): Component { return this; } + + headers: string[] = []; + rows: CSVRow[] = []; + mode: ViewMode; + searchQuery = ""; + tableSortCol: string | null = null; + tableSortDir: "asc" | "desc" = "asc"; + libraryStatusFilter = "all"; + libraryGenreFilter = "all"; + // Group values (lowercased) collapsed by default in Cards view — from the + // block's `collapse:` directive. Read by renderLibrary. + collapsedGroups: Set = new Set(); + + private saveTimer: number | null = null; + // Serialized form of our own last write. On a vault `modify` event we re-read + // the file and skip the re-render when the content matches — that's how we + // ignore our own saves (no focus-stealing mid-edit) while still re-syncing + // when another view (a .csv tab, another block) changes the file. + private lastWritten: string | null = null; + private contentArea: HTMLElement | null = null; + + constructor( + containerEl: HTMLElement, + app: App, + settings: CardViewSettings, + persistSettings: () => Promise, + opts: BlockOptions, + ) { + super(containerEl); + this.app = app; + this.settings = settings; + this.persistSettings = persistSettings; + this.opts = opts; + this.mode = opts.mode; + this.collapsedGroups = new Set(opts.collapse.map(s => s.toLowerCase())); + } + + // contentEl is the block root the renderers query for `.csv-content-area` + // and pass to showSelectPicker. MarkdownRenderChild gives us containerEl. + get contentEl(): HTMLElement { return this.containerEl; } + + // The renderers + effectiveGroupCol are typed against CardView. InlineCardHost + // satisfies the duck-typed subset they actually reach (verified by the smoke + // tests, which drive the same renderers with plain object literals), but it + // isn't a structural CardView, so the cast is explicit and centralized here. + private get asView(): CardView { return this as unknown as CardView; } + + async onload(): Promise { + this.containerEl.addClass("csv-inline-view"); + if (!this.opts.file) { + this.renderError("No file specified. Use: file: yourfile.csv"); + return; + } + if (!(await this.reload())) return; + this.renderView(); + + // Re-sync when the source file changes underneath us (edited in a .csv + // tab, another csv-view block, or external sync). Skip our own writes. + this.registerEvent(this.app.vault.on("modify", async (f) => { + if (!this.file || f.path !== this.file.path) return; + const text = await this.app.vault.read(this.file); + if (text === this.lastWritten) return; // our own save — already rendered + const parsed = parseCSV(text); + this.headers = parsed.headers; + this.rows = parsed.rows; + this.renderView(); + })); + // A rename of the source file invalidates our cached handle. + this.registerEvent(this.app.vault.on("rename", (f, oldPath) => { + if (this.file && oldPath === this.file.path) this.file = asFile(f); + })); + } + + onunload(): void { + if (this.saveTimer) window.clearTimeout(this.saveTimer); + } + + /** Read the source file (path already resolved at registration). Returns false (and renders an error) on failure. */ + private async reload(): Promise { + const file = asFile(this.app.vault.getAbstractFileByPath(this.opts.file)); + if (!file) { + this.renderError(`File not found: ${this.opts.file}`); + return false; + } + this.file = file; + try { + const parsed = parseCSV(await this.app.vault.read(file)); + this.headers = parsed.headers; + this.rows = parsed.rows; + } catch (e) { + this.renderError(`Error reading file: ${e instanceof Error ? e.message : String(e)}`); + return false; + } + return true; + } + + private renderError(msg: string): void { + this.containerEl.empty(); + this.containerEl.createEl("p", { text: `csv-view: ${msg}`, cls: "csv-add-error" }); + } + + // ── Save ───────────────────────────────────────────────────────────────── + + scheduleSave(): void { + if (this.saveTimer) window.clearTimeout(this.saveTimer); + this.saveTimer = window.setTimeout(() => void this.doSave(), 600); + } + + private async doSave(): Promise { + if (!this.file) return; + try { + const csv = Papa.unparse(this.rows, { columns: this.headers }); + this.lastWritten = csv; // suppress the echo `modify` event from re-rendering + await this.app.vault.modify(this.file, csv); + } catch (e) { + new Notice(`Couldn't save ${this.file.name}: ${e instanceof Error ? e.message : String(e)}`, 8000); + } + } + + // ── Per-file config (shared with the full view via settings.fileConfigs) ─── + + get fileCfg(): FileConfig { + return this.file ? (this.settings.fileConfigs[this.file.path] ?? {}) : {}; + } + saveFileCfg(cfg: FileConfig): void { + if (!this.file) return; + this.settings.fileConfigs[this.file.path] = cfg; + void this.persistSettings(); + } + + // ── Column detection (mirrors CardView) ──────────────────────────────────── + + resolveCol(candidates: string[]): string | null { + for (const c of candidates) { + const found = this.headers.find(h => h.toLowerCase() === c.toLowerCase()); + if (found) return found; + } + return null; + } + getNotesCol(): string | null { + if (this.fileCfg.notesColumn) return this.fileCfg.notesColumn; + return this.resolveCol([ + "Notes", "notes", "Note", "note", "Summary", "summary", "Review", "review", + "Quote", "quote", "Quotes", "quotes", "Comment", "comment", "Comments", "comments", + "Description", "description", "Annotation", "annotation", + ]); + } + isNotesCol(h: string): boolean { + const notesCol = this.getNotesCol(); + if (notesCol) return h === notesCol; + return this.settings.notesColumns.some(n => n.toLowerCase() === h.toLowerCase()); + } + isSelectCol(h: string): boolean { + return this.settings.selectColumns.some(s => s.toLowerCase() === h.toLowerCase()); + } + getStatusCol(): string | null { + if (this.fileCfg.statusColumn) { + return this.headers.find(h => h.toLowerCase() === this.fileCfg.statusColumn!.toLowerCase()) ?? null; + } + return this.resolveCol([ + "Status", "status", "State", "state", "Progress", "progress", "Stage", "stage", + "Read", "read", "Watched", "watched", "Seen", "seen", "Done", "done", "Completed", "completed", + ]); + } + getCategoryCol(): string | null { + if (this.fileCfg.categoryColumn) { + return this.headers.find(h => h.toLowerCase() === this.fileCfg.categoryColumn!.toLowerCase()) ?? null; + } + return this.resolveCol([ + "Category", "category", "Categories", "categories", "Genre", "genre", "Genres", "genres", + "Type", "type", "Types", "types", "Tag", "tag", "Tags", "tags", + "Topic", "topic", "Topics", "topics", "Subject", "subject", "Section", "section", + ]); + } + titleKey(): string | undefined { + return this.resolveCol(["Title", "title", "Name", "name"]) ?? undefined; + } + authorKey(): string | undefined { + return this.resolveCol([ + "Author", "author", "Authors", "authors", "Director", "director", + "Artist", "artist", "Creator", "creator", "By", "by", + ]) ?? undefined; + } + getTitle(row: CSVRow): string { const k = this.titleKey(); return (k ? row[k] : row[this.headers[0]]) ?? "—"; } + getSubtitle(row: CSVRow): string { const k = this.authorKey(); return k ? row[k] ?? "" : ""; } + getColumnValues(h: string): string[] { + return Array.from(new Set(this.rows.map(r => r[h] ?? "").filter(Boolean))).sort(); + } + getImageCol(): string | null { + if (this.fileCfg.imageColumn) return this.headers.find(h => h.toLowerCase() === this.fileCfg.imageColumn!.toLowerCase()) ?? null; + return this.resolveCol(IMAGE_COL_ALIASES); + } + // Habit/0-1 columns — configured list or auto-detected (all values 0/1/ + // true/false/yes/no/empty). Drives the add-form toggles. + getBooleanColumns(): string[] { + if (this.fileCfg.habitColumns?.length) return this.fileCfg.habitColumns.filter(h => this.headers.includes(h)); + const boolPatterns = ["0", "1", "true", "false", "yes", "no", ""]; + return this.headers.filter(h => { + if (h === this.getDateCol() || this.isNotesCol(h)) return false; + return this.rows.map(r => (r[h] ?? "").toLowerCase().trim()).every(v => boolPatterns.includes(v)); + }); + } + getDateCol(): string | null { + if (this.headers.length === 0) return null; + const firstCol = this.headers[0]; + if (["date", "day", "datum"].includes(firstCol.toLowerCase())) return firstCol; + const datePattern = /^\d{4}-\d{2}-\d{2}$/; + const sample = this.rows.slice(0, 5); + if (sample.length > 0 && sample.every(r => datePattern.test(r[firstCol] ?? ""))) return firstCol; + return null; + } + + getFilteredRows(): CSVRow[] { + let result = this.rows; + if (this.searchQuery.trim()) { + const query = this.searchQuery.toLowerCase().trim(); + result = result.filter(row => this.headers.some(h => (row[h] ?? "").toLowerCase().includes(query))); + } + if (this.mode === "table" && this.tableSortCol && this.headers.includes(this.tableSortCol)) { + const col = this.tableSortCol, dir = this.tableSortDir; + return [...result].sort((a, b) => { + const cmp = (a[col] ?? "").localeCompare(b[col] ?? "", undefined, { numeric: true }); + return dir === "asc" ? cmp : -cmp; + }); + } + const dateCol = this.getDateCol(); + if (this.mode === "table" && dateCol) { + const sortNewest = this.fileCfg.sortNewestFirst ?? true; + result = [...result].sort((a, b) => { + const cmp = (a[dateCol] ?? "").localeCompare(b[dateCol] ?? ""); + return sortNewest ? -cmp : cmp; + }); + } + return result; + } + + // ── Notes sidecar files ───────────────────────────────────────────────── + + private notesFilePath(row: CSVRow): string { + const title = sanitizeFilename(this.getTitle(row)); + const csvFolder = this.file?.parent?.path ?? ""; + const sub = this.settings.notesSubfolder.trim(); + const folder = sub ? (csvFolder ? `${csvFolder}/${sub}` : sub) : csvFolder; + return normalizePath(`${folder}/${title}.md`); + } + notesFileExists(row: CSVRow): boolean { + return !!this.app.vault.getAbstractFileByPath(this.notesFilePath(row)); + } + async openOrCreateNotes(row: CSVRow): Promise { + const path = this.notesFilePath(row); + let file = this.app.vault.getAbstractFileByPath(path) as TFile | null; + if (!file) { + const props = this.headers.filter(h => !this.isNotesCol(h) && row[h]).map(h => `${h}: "${row[h].replace(/"/g, '\\"')}"`); + const fm = ["---", ...props, "---", "", `# ${this.getTitle(row)}`, "", ""].join("\n"); + const notesCol = this.headers.find(h => this.isNotesCol(h)); + const content = fm + (notesCol && row[notesCol]?.trim() ? row[notesCol] : ""); + const folderPath = path.substring(0, path.lastIndexOf("/")); + if (folderPath && !this.app.vault.getAbstractFileByPath(folderPath)) await this.app.vault.createFolder(folderPath); + file = await this.app.vault.create(path, content); + new Notice(`Created: ${file.name}`); + } + await this.app.workspace.getLeaf("tab").openFile(file); + } + + // ── Row interactions (mirror CardView; render into this block) ───────────── + + deleteWithUndo(row: CSVRow): void { + const idx = this.rows.indexOf(row); + if (idx < 0) return; + this.rows.splice(idx, 1); + this.scheduleSave(); + this.renderView(); + const title = this.getTitle(row) || "entry"; + const frag = document.createDocumentFragment(); + frag.createSpan({ text: `Deleted “${title}”. ` }); + const undoBtn = frag.createEl("button", { text: "Undo", cls: "csv-notice-undo" }); + const notice = new Notice(frag, 6000); + undoBtn.addEventListener("click", () => { + if (undoBtn.hasAttribute("disabled")) return; + undoBtn.setAttribute("disabled", "true"); + this.rows.splice(Math.min(idx, this.rows.length), 0, row); + this.scheduleSave(); + this.renderView(); + notice.hide(); + new Notice(`Restored “${title}”`, 2500); + }); + } + + openRowContextMenu(row: CSVRow, e: MouseEvent): void { + const menu = new Menu(); + menu.addItem(i => i.setTitle("Open / Create Notes file").setIcon("file-text").onClick(() => void this.openOrCreateNotes(row))); + // Always offered — the expander edits every structured field; on files + // without a notes column it simply omits the notes editor. + menu.addItem(i => i.setTitle("Open entry").setIcon("maximize").onClick(() => this.openNoteExpander(row, this.getNotesCol() ?? ""))); + const sc = this.getStatusCol(); + if (sc) { + const statuses = this.getColumnValues(sc); + if (statuses.length) { + menu.addSeparator(); + statuses.forEach(s => { + if (s === row[sc]) return; + menu.addItem(i => i.setTitle(`Mark as: ${s}`).onClick(() => { row[sc] = s; this.scheduleSave(); this.renderView(); })); + }); + } + } + menu.addSeparator(); + menu.addItem(i => i.setTitle("Delete").setIcon("trash").onClick(() => this.deleteWithUndo(row))); + menu.showAtMouseEvent(e); + } + + openNoteExpander(row: CSVRow, notesCol: string): void { + new NoteExpanderModal( + this.app, row, notesCol, this.headers, this.file?.path ?? "", + this.isNotesCol.bind(this), this.isSelectCol.bind(this), this.getColumnValues.bind(this), + (updatedRow) => { Object.assign(row, updatedRow); this.scheduleSave(); this.renderView(); }, + () => this.deleteWithUndo(row), + ).open(); + } + + openAddModal(): void { + new AddEntryModal( + this.app, this.headers, this.isNotesCol.bind(this), this.isSelectCol.bind(this), this.getColumnValues.bind(this), + (row) => { + this.rows.push(row); + this.scheduleSave(); + this.renderView(); + new Notice(`Added: ${this.getTitle(row)}`); + }, + {}, + // Habit/0-1 columns render as toggles in the add form. + (h) => this.getBooleanColumns().includes(h), + ).open(); + } + + renderSelectField(container: HTMLElement, row: CSVRow, h: string): HTMLElement { + const val = row[h] ?? ""; + const chip = container.createDiv({ cls: `csv-select-chip ${val ? "" : "empty"}` }); + chip.setText(val || "—"); + if (h.toLowerCase() === "status" && val) chip.addClass(`status-chip-${val.toLowerCase().replace(/\s+/g, "-")}`); + chip.addEventListener("click", e => { + e.stopPropagation(); + showSelectPicker(chip, row[h] ?? "", this.getColumnValues(h), (newVal) => { + row[h] = newVal; + chip.setText(newVal || "—"); + this.scheduleSave(); + }, this.contentEl); + }); + return chip; + } + + /** Render markdown text into an element, tied to this block's lifecycle. */ + renderMarkdownInto(el: HTMLElement, text: string): void { + void MarkdownRenderer.render(this.app, text, el, this.file?.path ?? "", this.renderComponent); + } + + // The full view debounces+preserves scroll across a leaf re-render; inline + // blocks are short, so a plain re-render reads fine. Alias keeps the + // renderers' `renderViewPreservingScroll()` calls working. + renderViewPreservingScroll(): void { this.renderView(); } + + // ── Render ───────────────────────────────────────────────────────────────── + + renderView(contentOnly = false): void { + const root = this.containerEl; + if (!contentOnly) { + root.empty(); + this.renderToolbar(root); + this.contentArea = root.createDiv({ cls: "csv-content-area" }); + if (this.opts.height) this.contentArea.style.maxHeight = this.opts.height + "px"; + } else if (this.contentArea) { + this.contentArea.empty(); + } + const content = this.contentArea; + if (!content) return; + content.toggleClass("csv-content-area--no-yscroll", this.mode === "kanban-genre" || this.mode === "table"); + + if (!this.headers.length) { + content.createDiv({ cls: "csv-empty-state" }).createEl("p", { text: "This file is empty." }); + return; + } + if (this.rows.length === 0) { + const wrap = content.createDiv({ cls: "csv-empty-state" }); + wrap.createEl("p", { text: "No entries yet." }); + wrap.createEl("button", { cls: "csv-empty-state-action", text: "+ Add the first entry" }) + .addEventListener("click", () => this.openAddModal()); + return; + } + // Cards/Kanban need a groupable column; fall back to table if there isn't one. + if ((this.mode === "library" || this.mode === "kanban-genre") && !effectiveGroupCol(this.asView)) { + this.mode = "table"; + } + if (this.mode === "library") renderLibrary(this.asView, content); + else if (this.mode === "kanban-genre") renderKanbanGenre(this.asView, content); + else renderTable(this.asView, content); + } + + private renderToolbar(root: HTMLElement): void { + const bar = root.createDiv({ cls: "csv-toolbar csv-inline-toolbar" }); + bar.createDiv({ cls: "csv-toolbar-title", text: this.file?.basename ?? "" }) + .addEventListener("click", () => { if (this.file) void this.app.workspace.getLeaf("tab").openFile(this.file); }); + const ctrl = bar.createDiv({ cls: "csv-toolbar-controls" }); + ctrl.createDiv({ cls: "csv-row-count", text: `${this.rows.length} entries` }); + + // Mode segmented control. Cards/Kanban only when a groupable column exists. + const groupable = !!effectiveGroupCol(this.asView); + const mg = ctrl.createDiv({ cls: "csv-mode-group" }); + MODE_LABELS.forEach(({ id, label }) => { + if ((id === "library" || id === "kanban-genre") && !groupable) return; + const btn = mg.createEl("button", { cls: `csv-mode-btn ${this.mode === id ? "active" : ""}`, text: label }); + btn.addEventListener("click", () => { this.mode = id; this.renderView(); }); + }); + + // Search. + const searchInput = ctrl.createEl("input", { + cls: "csv-search-input", type: "text", placeholder: "Search…", value: this.searchQuery, + attr: { inputmode: "search", enterkeyhint: "search", autocomplete: "off" }, + }); + let debounce: number | null = null; + searchInput.addEventListener("input", e => { + this.searchQuery = (e.target as HTMLInputElement).value; + if (debounce !== null) window.clearTimeout(debounce); + debounce = window.setTimeout(() => { debounce = null; this.renderView(true); }, 120); + }); + + ctrl.createEl("button", { cls: "csv-add-btn", text: "+ Add" }).addEventListener("click", () => this.openAddModal()); + } +} + +/** + * csv-view block processor. Each block gets its own host, tied to the block's + * lifecycle via ctx.addChild (re-rendered/removed → host.onunload). + */ +export function registerCsvViewBlock( + app: App, + settings: CardViewSettings, + persistSettings: () => Promise, + register: (lang: string, handler: (source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) => void) => void, +): void { + register("csv-view", (source, el, ctx) => { + const opts = parseBlockSource(source); + // Resolve the source file against the note that holds the block — captured + // here from ctx, since the host only keeps the active-file folder as a + // fallback. We pre-resolve by stashing the note folder on opts.file when + // it's a bare/relative path so reload() resolves correctly. + const noteFolder = app.vault.getAbstractFileByPath(ctx.sourcePath)?.parent?.path ?? ""; + const resolved = opts.file ? resolvePath(opts.file, noteFolder) : opts.file; + const host = new InlineCardHost(el, app, settings, persistSettings, { ...opts, file: resolved }); + ctx.addChild(host); + }); +} diff --git a/src/modals.ts b/src/modals.ts index 21abac1..a62142f 100644 --- a/src/modals.ts +++ b/src/modals.ts @@ -6,7 +6,7 @@ import { Notice, } from "obsidian"; import { CSVRow, FileConfig, ViewMode } from "./types"; -import { showSelectPicker, titleCase, isMultiValueColName } from "./utils"; +import { showSelectPicker, titleCase, isMultiValueColName, looksCategorical } from "./utils"; import { suggestionsFor, isDateCol, ISO_DATE } from "./field-types"; // ─── Shared field input ───────────────────────────────────────────────────── @@ -47,6 +47,10 @@ export class AddEntryModal extends Modal { isSelectCol: (h: string) => boolean; getColumnValues: (h: string) => string[]; onSubmit: (row: CSVRow) => void; + // True for 0/1 habit-style columns — they render as a toggle instead of a + // text field so logging a day is a tap, not typing "1". Optional so callers + // that don't track habits can omit it (defaults to never-boolean). + isBooleanCol: (h: string) => boolean; // Predefined options per column (keyed by header). Merged ahead of the // file's existing values in the dropdown — e.g. a tasks file passes // { Type: ["Task","Note","Idea"], Priority: ["Low","Medium","High"] } so a @@ -60,7 +64,8 @@ export class AddEntryModal extends Modal { isSelectCol: (h: string) => boolean, getColumnValues: (h: string) => string[], onSubmit: (row: CSVRow) => void, - optionPresets: Record = {} + optionPresets: Record = {}, + isBooleanCol: (h: string) => boolean = () => false ) { super(app); this.headers = headers; @@ -69,6 +74,7 @@ export class AddEntryModal extends Modal { this.getColumnValues = getColumnValues; this.onSubmit = onSubmit; this.optionPresets = optionPresets; + this.isBooleanCol = isBooleanCol; } onOpen(): void { @@ -107,9 +113,29 @@ export class AddEntryModal extends Modal { // modal's focus-trap, which on an empty column made the field unfillable // (it bounced back to the title). Multi-value columns (tags/genres) still // use the chip picker since a native select can't multi-select cleanly. - const useNativeSelect = !this.isNotesCol(h) && (presets.length > 0 || (this.isSelectCol(h) && !isMultiValueColName(h))); + // Pseudo-categorical: an un-configured column whose existing values are + // few enough to be a closed-ish vocabulary (e.g. Watched, Format) gets a + // dropdown of its values + "Custom…" too — not just the names listed in + // settings.selectColumns. Same heuristic as the mobile add form. + const autoCategorical = !this.isSelectCol(h) && !isMultiValueColName(h) + && !isDateCol(h) && looksCategorical(this.getColumnValues(h).length); + const useNativeSelect = !this.isNotesCol(h) && (presets.length > 0 || (this.isSelectCol(h) && !isMultiValueColName(h)) || autoCategorical); - if (this.isNotesCol(h)) { + if (this.isBooleanCol(h)) { + // Habit-style 0/1 column → a toggle. Off writes "0", on "1", so logging + // a day is a tap per habit instead of typing each value. Self-contained + // (own knob + CSS) rather than Obsidian's .checkbox-container so it + // renders consistently across themes. + values[h] = "0"; + const toggle = row.createDiv({ cls: "csv-toggle" }); + toggle.createDiv({ cls: "csv-toggle-knob" }); + toggle.addEventListener("click", () => { + const on = !toggle.hasClass("is-on"); + toggle.toggleClass("is-on", on); + values[h] = on ? "1" : "0"; + }); + + } else if (this.isNotesCol(h)) { const ta = row.createEl("textarea", { cls: "csv-modal-textarea", placeholder: "Markdown supported…" }); ta.addEventListener("input", () => { values[h] = ta.value; }); @@ -296,7 +322,12 @@ export class NoteExpanderModal extends Modal { // titleCase: Apple-style row labels, independent of CSV header casing. fieldRow.createDiv({ cls: "csv-expander-field-label", text: titleCase(h) }); - if (this.isSelectCol(h)) { + // Configured select column, or a pseudo-categorical one (few distinct + // values, e.g. Watched/Format) — both get the chip + option picker, so + // editing offers the same vocabulary the add form does. + const selectLike = this.isSelectCol(h) + || (!isMultiValueColName(h) && !isDateCol(h) && looksCategorical(this.getColumnValues(h).length)); + if (selectLike) { const chip = fieldRow.createDiv({ cls: `csv-select-chip ${this.row[h] ? "" : "empty"}` }); chip.setText(this.row[h] || "—"); chip.addEventListener("click", e => { @@ -325,63 +356,71 @@ export class NoteExpanderModal extends Modal { // click-to-edit pattern as the kanban card preview). Links and embeds // inside the markdown stay clickable — we suppress the edit-swap only // when the click landed on an anchor or the user is selecting text. - const notesDivider = contentEl.createDiv({ cls: "csv-expander-divider" }); - notesDivider.createDiv({ cls: "csv-expander-notes-label", text: this.notesCol }); - + // Notes section is only rendered when the file actually has a notes column. + // Files without one (e.g. an applications tracker that's all structured + // fields) still open the expander to edit every other field — the notes + // editor just isn't shown. `ta` stays null in that case; the Save handler + // guards on this.notesCol before writing back. let isEditing = false; - let currentText = this.row[this.notesCol] ?? ""; + let currentText = this.notesCol ? (this.row[this.notesCol] ?? "") : ""; + let ta: HTMLTextAreaElement | null = null; - const rendered = contentEl.createDiv({ cls: "csv-expander-rendered markdown-rendered" }); - rendered.title = "Click to edit"; - const editorWrap = contentEl.createDiv({ cls: "csv-expander-editor" }); - editorWrap.style.display = "none"; + if (this.notesCol) { + const notesDivider = contentEl.createDiv({ cls: "csv-expander-divider" }); + notesDivider.createDiv({ cls: "csv-expander-notes-label", text: this.notesCol }); - const renderMarkdown = () => { - rendered.empty(); - if (currentText.trim()) { - MarkdownRenderer.render(this.app, currentText, rendered, this.filePath, this.renderComponent); - } else { - rendered.createDiv({ cls: "csv-notes-empty", text: "+ Add note" }); - } - }; - renderMarkdown(); - - const ta = editorWrap.createEl("textarea", { cls: "csv-expander-textarea" }); - ta.value = currentText; - ta.addEventListener("input", () => { currentText = ta.value; }); - - const enterEdit = () => { - if (isEditing) return; - isEditing = true; - rendered.style.display = "none"; - editorWrap.style.display = "flex"; - ta.value = currentText; - ta.focus(); - }; - const exitEdit = () => { - if (!isEditing) return; - isEditing = false; + const rendered = contentEl.createDiv({ cls: "csv-expander-rendered markdown-rendered" }); + rendered.title = "Click to edit"; + const editorWrap = contentEl.createDiv({ cls: "csv-expander-editor" }); editorWrap.style.display = "none"; - rendered.style.display = ""; - currentText = ta.value; - renderMarkdown(); - }; - rendered.addEventListener("click", (e) => { - // Don't hijack clicks on links, buttons, or other interactive children — - // they should open as the user expects. - const target = e.target as HTMLElement; - if (target.closest("a, button, input, textarea, [contenteditable]")) return; - // Don't enter edit mode if the user just finished a text selection inside - // the rendered note; respects normal text-select semantics. - const sel = window.getSelection(); - if (sel && sel.toString().length > 0) return; - enterEdit(); - }); - // Esc inside the textarea returns to the preview. Click outside (blur) - // also exits — keeps the modal feeling lightweight. - ta.addEventListener("keydown", (e) => { if (e.key === "Escape") { e.preventDefault(); ta.blur(); } }); - ta.addEventListener("blur", exitEdit); + const renderMarkdown = () => { + rendered.empty(); + if (currentText.trim()) { + MarkdownRenderer.render(this.app, currentText, rendered, this.filePath, this.renderComponent); + } else { + rendered.createDiv({ cls: "csv-notes-empty", text: "+ Add note" }); + } + }; + renderMarkdown(); + + ta = editorWrap.createEl("textarea", { cls: "csv-expander-textarea" }); + ta.value = currentText; + ta.addEventListener("input", () => { currentText = ta!.value; }); + + const enterEdit = () => { + if (isEditing) return; + isEditing = true; + rendered.style.display = "none"; + editorWrap.style.display = "flex"; + ta!.value = currentText; + ta!.focus(); + }; + const exitEdit = () => { + if (!isEditing) return; + isEditing = false; + editorWrap.style.display = "none"; + rendered.style.display = ""; + currentText = ta!.value; + renderMarkdown(); + }; + + rendered.addEventListener("click", (e) => { + // Don't hijack clicks on links, buttons, or other interactive children — + // they should open as the user expects. + const target = e.target as HTMLElement; + if (target.closest("a, button, input, textarea, [contenteditable]")) return; + // Don't enter edit mode if the user just finished a text selection inside + // the rendered note; respects normal text-select semantics. + const sel = window.getSelection(); + if (sel && sel.toString().length > 0) return; + enterEdit(); + }); + // Esc inside the textarea returns to the preview. Click outside (blur) + // also exits — keeps the modal feeling lightweight. + ta.addEventListener("keydown", (e) => { if (e.key === "Escape") { e.preventDefault(); ta!.blur(); } }); + ta.addEventListener("blur", exitEdit); + } // ── Footer buttons ─────────────────────────────────────────────────────── // Layout: [Delete] ............... [Cancel] [Save & close] @@ -407,8 +446,11 @@ export class NoteExpanderModal extends Modal { .addEventListener("click", () => { // If still in edit mode (user clicked Save without blurring), grab // the live textarea content; otherwise currentText is already fresh. - if (isEditing) currentText = ta.value; - this.row[this.notesCol] = currentText; + // Only write back when there's a notes column (ta is null otherwise). + if (this.notesCol) { + if (isEditing && ta) currentText = ta.value; + this.row[this.notesCol] = currentText; + } this.onSave(this.row); this.close(); }); diff --git a/src/types.ts b/src/types.ts index f8c2cff..083b3dc 100644 --- a/src/types.ts +++ b/src/types.ts @@ -42,6 +42,10 @@ export interface FileConfig { kanbanGroupCol?: string; // Kanban "Group by" column. Unset = category column. // Year-like columns bucket into decades. librarySort?: LibrarySort; // Card-view section ordering. Unset = "status". + imageColumn?: string; // Column holding an image (path/wikilink/URL) for + // card/kanban thumbnails. Unset = auto-detect by name. + collapsedGroups?: string[]; // Card-view group values (lowercased) collapsed by + // default; remembers manual collapse/expand toggles. ankiFrontCol?: string; // Column used as the Anki card front on sync. // Unset = the title/primary field; every other // non-empty column becomes the card back. diff --git a/src/utils.ts b/src/utils.ts index 3bfd6e2..4128998 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,6 +1,46 @@ import Papa from "papaparse"; +import { App, TFile } from "obsidian"; import { CSVRow } from "./types"; +// Column-name aliases that mark a cell as holding an image, for card/kanban +// thumbnails. Matched case-insensitively against headers (see getImageCol). +export const IMAGE_COL_ALIASES = ["Image", "image", "Cover", "cover", "Poster", "poster", "Thumbnail", "thumbnail", "Thumb", "thumb", "Photo", "photo", "Picture", "picture", "Img", "img"]; + +/** + * Resolve a cell value into an src, or null if it isn't resolvable. + * Accepts: http(s)/data URLs (used as-is), `![[wikilink]]` / `[[wikilink]]`, + * `![](path)` markdown images, and bare vault paths / filenames (resolved + * relative to the CSV's own path via the link cache → getResourcePath). + */ +export function resolveImageSrc(app: App, raw: string, sourcePath: string): string | null { + let v = (raw ?? "").trim(); + if (!v) return null; + // Absolute URLs / data URIs pass through untouched. + if (/^(https?:|data:)/i.test(v)) return v; + // Unwrap ![[wikilink]] / [[wikilink]] and ![](path) markdown image syntax. + const wiki = v.match(/!?\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/); + if (wiki) v = wiki[1].trim(); + else { + const md = v.match(/!\[[^\]]*\]\(([^)]+)\)/); + if (md) v = md[1].trim(); + } + if (/^(https?:|data:)/i.test(v)) return v; // an md-image whose target was a URL + // Resolve as a vault link relative to the CSV file, then to a usable src. + const file = app.metadataCache.getFirstLinkpathDest(v, sourcePath); + if (file instanceof TFile) return app.vault.getResourcePath(file); + return null; +} + +// Largest distinct-value count at which a column still "looks categorical" — +// i.e. worth an option picker rather than a free-text input. The single source +// of truth for the add form, the entry editor, and the mobile add form, so all +// three offer the same pseudo-categorical columns (e.g. Watched, Format) the +// same way, not just the names configured in settings.selectColumns. +export const CATEGORICAL_MAX_DISTINCT = 15; +export function looksCategorical(distinctCount: number): boolean { + return distinctCount >= 1 && distinctCount <= CATEGORICAL_MAX_DISTINCT; +} + export function sanitizeFilename(name: string): string { return name.replace(/[\\/:*?"<>|#^[\]]/g,"").replace(/\s+/g," ").trim().slice(0,100); } diff --git a/src/view/kanban.ts b/src/view/kanban.ts index 66c8883..119b9ec 100644 --- a/src/view/kanban.ts +++ b/src/view/kanban.ts @@ -4,7 +4,7 @@ import type { CardView } from "../../main"; import { CSVRow } from "../types"; -import { showSelectPicker, isMultiValueColName, isYearLikeColumn, decadeLabel, pickFallbackGroupCol } from "../utils"; +import { showSelectPicker, isMultiValueColName, isYearLikeColumn, decadeLabel, pickFallbackGroupCol, resolveImageSrc } from "../utils"; /** * The column Cards/Kanban group by, resolved in priority order: @@ -66,11 +66,9 @@ export function renderKanbanGenre(view: CardView, container: HTMLElement): void // doesn't explode into 40 single-year columns. Everything else keeps the // comma-split multi-value behavior the genre kanban always had. const isYear = isYearLikeColumn(cc, filteredRows.map(r => r[cc] ?? "")); - // When the user explicitly grouped by a non-default column, rows with an - // empty value get a "—" bucket instead of silently vanishing (an explicit - // grouping should account for every row). The default genre view keeps - // its original drop-empties behavior. - const explicit = cc !== defaultCc; + // Rows with an empty group value get a "—" bucket instead of silently + // vanishing — every row should land in some column, including the default + // genre view (a movie with no genre still belongs on the board). const groupValues = (row: CSVRow): string[] => { const raw = row[cc] ?? ""; let vals: string[]; @@ -80,7 +78,7 @@ export function renderKanbanGenre(view: CardView, container: HTMLElement): void } else { vals = raw.split(",").map(s=>s.trim()).filter(Boolean); } - if (!vals.length && explicit) vals = ["—"]; + if (!vals.length) vals = ["—"]; return vals; }; @@ -120,6 +118,12 @@ export function renderKanbanGenre(view: CardView, container: HTMLElement): void groupEl.createDiv({cls:`csv-kanban-status-label status-${status.toLowerCase().replace(/\s+/g,"-")}`, text:status}); statusRows.forEach(row => renderKanbanCard(view, groupEl, row, sc, cc)); }); + // Rows whose status is blank or not among the known statuses (the empty + // strings dropped by `.filter(Boolean)` above) still belong in this + // column — render them ungrouped so they don't vanish while the column + // header still counts them. + const known = new Set(statuses); + genreRows.filter(r => !known.has(r[sc] ?? "")).forEach(row => renderKanbanCard(view, cb, row, sc, cc)); } else { genreRows.forEach(row => renderKanbanCard(view, cb, row, sc, cc)); } @@ -130,14 +134,25 @@ function renderKanbanCard(view: CardView, container: HTMLElement, row: CSVRow, s const card = container.createDiv({cls:"csv-kanban-card"}); const notesColForCard = view.getNotesCol(); + // Thumbnail (when an image column resolves). Lazy-loaded; broken srcs drop out. + const imageCol = view.getImageCol?.() ?? null; + if (imageCol) { + const src = resolveImageSrc(view.app, row[imageCol] ?? "", view.file?.path ?? ""); + if (src) { + const img = card.createEl("img", { cls: "csv-kanban-card-img", attr: { src, loading: "lazy", alt: "" } }); + img.addEventListener("error", () => img.remove()); + } + } + // Title row: title text on the left, small notes-file icon on the right. // Tapping the title opens the entry expander; the small icon creates or // opens the sidecar .md. Replaces the old hover-revealed bottom button row. const titleRow = card.createDiv({cls:"csv-kanban-card-title-row"}); const titleEl = titleRow.createDiv({cls:"csv-kanban-card-title", text:view.getTitle(row)}); - if (notesColForCard) { - titleEl.addEventListener("click", e => { e.stopPropagation(); view.openNoteExpander(row, notesColForCard); }); - } + // Tapping the title opens the entry editor. Works even when the file has no + // notes column (e.g. an applications tracker) — the expander still edits + // every structured field; its notes section just doesn't render. + titleEl.addEventListener("click", e => { e.stopPropagation(); view.openNoteExpander(row, notesColForCard ?? ""); }); const hasNotesFile = view.notesFileExists(row); const notesIconBtn = titleRow.createEl("button", { cls: `csv-kanban-notes-icon ${hasNotesFile ? "exists" : ""}`, diff --git a/src/view/library.ts b/src/view/library.ts index 5966250..d1f95aa 100644 --- a/src/view/library.ts +++ b/src/view/library.ts @@ -4,7 +4,7 @@ import type { CardView } from "../../main"; import { CSVRow, LibrarySort } from "../types"; -import { formatRatingForDisplay } from "../utils"; +import { formatRatingForDisplay, resolveImageSrc } from "../utils"; import { parseRating } from "./stats"; import { effectiveGroupCol } from "./kanban"; @@ -174,7 +174,26 @@ export function renderLibrary(view: CardView, container: HTMLElement): void { Object.keys(groups).sort().forEach(genre => { const items = groups[genre]; const section = sectionsWrap.createEl("details", { cls: "csv-library-section" }); - section.open = true; + // Collapsed by default if this group is in the inline `collapse:` directive + // (view.collapsedGroups) OR the file's remembered collapsed set + // (fileCfg.collapsedGroups). Manual toggles below persist to the latter, so + // collapse works — and is remembered — in the full-page Cards view too. + const gKey = genre.toLowerCase(); + const persisted = (view.fileCfg.collapsedGroups ?? []).map(s => s.toLowerCase()); + section.open = !(view.collapsedGroups?.has(gKey) || persisted.includes(gKey)); + section.addEventListener("toggle", () => { + const cfg = view.fileCfg; + const cur = (cfg.collapsedGroups ?? []).map(s => s.toLowerCase()); + const set = new Set(cur); + if (section.open) set.delete(gKey); else set.add(gKey); + const next = Array.from(set); + // Skip the write when nothing changed — guards against the spurious + // toggle event fired by the initial programmatic `section.open` set, so + // a render doesn't rewrite data.json every time. + if (next.length === cur.length && next.every(x => cur.includes(x))) return; + cfg.collapsedGroups = next; + view.saveFileCfg(cfg); + }); const summary = section.createEl("summary", { cls: "csv-library-section-header" }); summary.innerHTML = ` ${genre} ${items.length}`; @@ -227,10 +246,21 @@ export function renderLibrary(view: CardView, container: HTMLElement): void { // Otherwise auto-detect: author, year, rating, theme. const autoFields = [authorCol, yearCol, ratingCol, themeCol].filter((c): c is string => !!c); const cardFields = view.fileCfg.cardFields ?? autoFields; + const imageCol = view.getImageCol?.() ?? null; items.forEach(row => { const card = grid.createDiv({ cls: "csv-library-card" }); + // Cover image (when an image column resolves to a usable src). Lazy so a + // genre section with many cards doesn't fetch every image up front. + if (imageCol) { + const src = resolveImageSrc(view.app, row[imageCol] ?? "", view.file?.path ?? ""); + if (src) { + const img = card.createEl("img", { cls: "csv-library-card-img", attr: { src, loading: "lazy", alt: "" } }); + img.addEventListener("error", () => img.remove()); // drop broken images quietly + } + } + // Title with green dot for "done"-style status (watched, read, finished, etc.) const titleWrap = card.createDiv({ cls: "csv-library-card-title" }); if (sc) { @@ -281,12 +311,10 @@ export function renderLibrary(view: CardView, container: HTMLElement): void { }); } - // Click to expand + // Click to expand. Opens even without a notes column — the expander + // edits every structured field; its notes section just doesn't render. card.addEventListener("click", () => { - const notesCol = view.getNotesCol(); - if (notesCol) { - view.openNoteExpander(row, notesCol); - } + view.openNoteExpander(row, view.getNotesCol() ?? ""); }); card.addEventListener("contextmenu", e => view.openRowContextMenu(row, e)); }); diff --git a/styles.css b/styles.css index c3a5430..ab99ed5 100644 --- a/styles.css +++ b/styles.css @@ -923,8 +923,14 @@ otherwise leaves the last-touched row tinted and forces a recomposite per scroll frame — a major cause of table lag on iPhone. */ @media (hover: hover) { + /* `--background-modifier-hover` is barely perceptible in dark themes, so the + row looked like only some cells lit up. Use a text-tinted overlay that + reads clearly in both light and dark; the plain var is the fallback for + engines without color-mix. The row highlights uniformly because every + cell (incl. the action cell) is a . */ .csv-table tr:hover td { background: var(--background-modifier-hover); } - .csv-table tr:hover td.csv-cell--clipped::after { background: linear-gradient(to bottom, transparent, var(--background-modifier-hover)); } + .csv-table tr:hover td { background: color-mix(in srgb, var(--text-normal) 16%, transparent); } + .csv-table tr:hover td.csv-cell--clipped::after { background: linear-gradient(to bottom, transparent, color-mix(in srgb, var(--text-normal) 16%, transparent)); } } /* Long-content fade-out hint, scoped to cells JS measured as overflowing. The pseudo-element previously existed on every td (opacity:0 by default) @@ -3841,3 +3847,123 @@ select.csv-add-row-control { background-position: right 10px center; padding-right: 28px; } + +/* ─── Inline csv-view block ────────────────────────────────────────────────── + The `csv-view` code block embeds a table/cards/kanban view inside a note + (a .base / Notion-DB-style embed). The full view fills its leaf via flex:1; + inline there's no such parent, so the wrapper establishes a bounded, self- + contained box: the toolbar reuses .csv-toolbar chrome, the content area + scrolls internally, and kanban columns get a definite height to size to. */ +.csv-inline-view { + display: flex; + flex-direction: column; + max-height: 600px; /* `height:` directive overrides via inline max-height on .csv-content-area */ + margin: 0.5em 0; + border: 1px solid var(--csv-border); + border-radius: 10px; + overflow: hidden; + background: var(--background-primary); + box-shadow: var(--csv-shadow); +} + +/* Content area fills the remaining height so internal scroll works and the + kanban board (flex:1) has a parent height to stretch into. */ +.csv-inline-view .csv-content-area { + flex: 1 1 auto; + min-height: 0; + padding: 12px; +} + +/* Compact toolbar — slimmer than the full-view bar, and the title is a + click target that opens the source .csv in its own tab. */ +.csv-inline-toolbar { + padding: 8px 12px; +} +.csv-inline-toolbar .csv-toolbar-title { + display: block; + cursor: pointer; + text-decoration: none; +} +.csv-inline-toolbar .csv-toolbar-title:hover { + color: var(--csv-accent); + text-decoration: underline; +} + +/* Mode segmented control (Table / Cards / Kanban). The full view uses a +