diff --git a/main.js b/main.js index d7b599d..fbaa638 100644 --- a/main.js +++ b/main.js @@ -11,7 +11,7 @@ `)>-1?s.split(` `):s}function $f(s,t){let{element:e,datasetIndex:n,index:i}=t,o=s.getDatasetMeta(n).controller,{label:r,value:a}=o.getLabelAndValue(i);return{chart:s,label:r,parsed:o.getParsed(i),raw:s.data.datasets[n].data[i],formattedValue:a,dataset:o.getDataset(),dataIndex:i,datasetIndex:n,element:e}}function Za(s,t){let e=s.chart.ctx,{body:n,footer:i,title:o}=s,{boxWidth:r,boxHeight:a}=t,l=bt(t.bodyFont),c=bt(t.titleFont),d=bt(t.footerFont),h=o.length,u=i.length,f=n.length,g=_t(t.padding),p=g.height,m=0,b=n.reduce((E,S)=>E+S.before.length+S.lines.length+S.after.length,0);if(b+=s.beforeBody.length+s.afterBody.length,h&&(p+=h*c.lineHeight+(h-1)*t.titleSpacing+t.titleMarginBottom),b){let E=t.displayColors?Math.max(a,l.lineHeight):l.lineHeight;p+=f*E+(b-f)*l.lineHeight+(b-1)*t.bodySpacing}u&&(p+=t.footerMarginTop+u*d.lineHeight+(u-1)*t.footerSpacing);let x=0,C=function(E){m=Math.max(m,e.measureText(E).width+x)};return e.save(),e.font=c.string,rt(s.title,C),e.font=l.string,rt(s.beforeBody.concat(s.afterBody),C),x=t.displayColors?r+2+t.boxPadding:0,rt(n,E=>{rt(E.before,C),rt(E.lines,C),rt(E.after,C)}),x=0,e.font=d.string,rt(s.footer,C),e.restore(),m+=g.width,{width:m,height:p}}function Hf(s,t){let{y:e,height:n}=t;return es.height-n/2?"bottom":"center"}function zf(s,t,e,n){let{x:i,width:o}=n,r=e.caretSize+e.caretPadding;if(s==="left"&&i+o+r>t.width||s==="right"&&i-o-r<0)return!0}function Wf(s,t,e,n){let{x:i,width:o}=e,{width:r,chartArea:{left:a,right:l}}=s,c="center";return n==="center"?c=i<=(a+l)/2?"left":"right":i<=o/2?c="left":i>=r-o/2&&(c="right"),zf(c,s,t,e)&&(c="center"),c}function Ja(s,t,e){let n=e.yAlign||t.yAlign||Hf(s,e);return{xAlign:e.xAlign||t.xAlign||Wf(s,t,e,n),yAlign:n}}function jf(s,t){let{x:e,width:n}=s;return t==="right"?e-=n:t==="center"&&(e-=n/2),e}function Uf(s,t,e){let{y:n,height:i}=s;return t==="top"?n+=e:t==="bottom"?n-=i+e:n-=i/2,n}function tl(s,t,e,n){let{caretSize:i,caretPadding:o,cornerRadius:r}=s,{xAlign:a,yAlign:l}=e,c=i+o,{topLeft:d,topRight:h,bottomLeft:u,bottomRight:f}=_e(r),g=jf(t,a),p=Uf(t,l,c);return l==="center"?a==="left"?g+=c:a==="right"&&(g-=c):a==="left"?g-=Math.max(d,u)+i:a==="right"&&(g+=Math.max(h,f)+i),{x:vt(g,0,n.width-t.width),y:vt(p,0,n.height-t.height)}}function Un(s,t,e){let n=_t(e.padding);return t==="center"?s.x+s.width/2:t==="right"?s.x+s.width-n.right:s.x+n.left}function el(s){return ee([],he(s))}function Kf(s,t,e){return de(s,{tooltip:t,tooltipItems:e,type:"tooltip"})}function sl(s,t){let e=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return e?s.override(e):s}function Lt(s,t,e,n){let i=s[t].call(e,n);return typeof i=="undefined"?zl[t].call(e,n):i}function Gf(s,t,e,n){let i=s.indexOf(t);if(i===-1)return Yf(s,t,e,n);let o=s.lastIndexOf(t);return i!==o?e:i}function nl(s){let t=this.getLabels();return s>=0&&sg&&(S=Fi(w*S/g/f)*f),tt(l)||(y=Math.pow(10,l),S=Math.ceil(S*y)/y),i==="ticks"?(v=Math.floor(p/S)*S,_=Math.ceil(m/S)*S):(v=p,_=m),b&&x&&o&&Wr((a-r)/o,S/1e3)?(w=Math.round(Math.min((a-r)/S,d)),S=(a-r)/w,v=r,_=a):C?(v=b?r:v,_=x?a:_,w=c-1,S=(_-v)/w):(w=(_-v)/S,ls(w,Math.round(w),S/1e3)?w=Math.round(w):w=Math.ceil(w));let T=Math.max(Vi(S),Vi(v));y=Math.pow(10,tt(l)?T:l),v=Math.round(v*y)/y,_=Math.round(_*y)/y;let k=0;for(b&&(u&&v!==r?(e.push({value:r}),va)break;e.push({value:M})}return x&&u&&_!==a?e.length&&ls(e[e.length-1].value,a,il(a,E,s))?e[e.length-1].value=a:e.push({value:a}):(!x||_===a)&&e.push({value:_}),e}function il(s,t,{horizontal:e,minRotation:n}){let i=zt(n),o=(e?Math.sin(i):Math.cos(i))||.001,r=.75*t*(""+s).length;return Math.min(t/o,r)}function ol(s){return s/Math.pow(10,sn(s))===1}function rl(s,t,e){let n=Math.pow(10,e),i=Math.floor(s/n);return Math.ceil(t/n)-i}function Qf(s,t){let e=t-s,n=sn(e);for(;rl(s,t,n)>10;)n++;for(;rl(s,t,n)<10;)n--;return Math.min(n,sn(s))}function Zf(s,{min:t,max:e}){t=Tt(s.min,t);let n=[],i=sn(t),o=Qf(t,e),r=o<0?Math.pow(10,Math.abs(o)):1,a=Math.pow(10,o),l=i>o?Math.pow(10,i):0,c=Math.round((t-l)*r)/r,d=Math.floor((t-l)/a/10)*a*10,h=Math.floor((c-d)/Math.pow(10,o)),u=Tt(s.min,Math.round((l+d+h*Math.pow(10,o))*r)/r);for(;u=10?h=h<15?15:20:h++,h>=20&&(o++,h=2,r=o>=0?1:r),u=Math.round((l+d+h*Math.pow(10,o))*r)/r;let f=Tt(s.max,u);return n.push({value:f,major:ol(f),significand:h}),n}function To(s){let t=s.ticks;if(t.display&&s.display){let e=_t(t.backdropPadding);return J(t.font&&t.font.size,ut.font.size)+e.height}return 0}function Jf(s,t,e){return e=dt(e)?e:[e],{w:Zr(s,t.string,e),h:e.length*t.lineHeight}}function al(s,t,e,n,i){return s===n||s===i?{start:t-e/2,end:t+e/2}:si?{start:t-e,end:t}:{start:t,end:t+e}}function tg(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 sg(s,t,e){let n=s.drawingArea,{extra:i,additionalAngle:o,padding:r,size:a}=e,l=s.getPointPosition(t,n+i+r,o),c=Math.round(An(xt(l.angle+mt))),d=ag(l.y,a.h,c),h=og(c),u=rg(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 ng(s,t){if(!t)return!0;let{left:e,top:n,right:i,bottom:o}=s;return!(Zt({x:e,y:n},t)||Zt({x:e,y:o},t)||Zt({x:i,y:n},t)||Zt({x:i,y:o},t))}function ig(s,t,e){let n=[],i=s._pointLabels.length,o=s.options,{centerPointLabels:r,display:a}=o.pointLabels,l={extra:To(o)/2,additionalAngle:r?nt/i:0},c;for(let d=0;d270||e<90)&&(s-=t),s}function lg(s,t,e){let{left:n,top:i,right:o,bottom:r}=e,{backdropColor:a}=t;if(!tt(a)){let l=_e(t.borderRadius),c=_t(t.backdropPadding);s.fillStyle=a;let d=n-c.left,h=i-c.top,u=o-n+c.width,f=r-i+c.height;Object.values(l).some(g=>g!==0)?(s.beginPath(),us(s,{x:d,y:h,w:u,h:f,radius:l}),s.fill()):s.fillRect(d,h,u,f)}}function cg(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));lg(e,r,o);let a=bt(r.font),{x:l,y:c,textAlign:d}=o;Ce(e,s._pointLabels[i],l,c+a.lineHeight/2,a,{color:r.color,textAlign:d,textBaseline:"middle"})}}function Ul(s,t,e,n){let{ctx:i}=s;if(e)i.arc(s.xCenter,s.yCenter,t,0,ht);else{let o=s.getPointPosition(0,t);i.moveTo(o.x,o.y);for(let r=1;r=Pt.indexOf(e);o--){let r=Pt[o];if(ni[r].common&&s._adapter.diff(i,n,r)>=t-1)return r}return Pt[e?Pt.indexOf(e):0]}function fg(s){for(let t=Pt.indexOf(s)+1,e=Pt.length;t=t?e[n]:e[i];s[o]=!0}}function gg(s,t,e,n){let i=s._adapter,o=+i.startOf(t[0].value,n),r=t[t.length-1].value,a,l;for(a=o;a<=r;a=+i.add(a,1,n))l=e[a],l>=0&&(t[l].major=!0);return t}function ul(s,t,e){let n=[],i={},o=t.length,r,a;for(r=0;r=s[n].pos&&t<=s[i].pos&&({lo:n,hi:i}=Qt(s,"pos",t)),{pos:o,time:a}=s[n],{pos:r,time:l}=s[i]):(t>=s[n].time&&t<=s[i].time&&({lo:n,hi:i}=Qt(s,"time",t)),{time:o,pos:a}=s[n],{time:r,pos:l}=s[i]);let c=r-o;return c?a+(l-a)*(t-o)/c:a}var yo,se,ga,ph,qn,Zs,co,ya,wh,At,Ne,Be,ie,$e,we,ps,He,ze,pl,xo,ml,bl,vl,St,Js,Xn,Yn,qh,Da,xl,tn,Ma,Zn,Rt,uu,Ta,La,Te,ms,Co,Kt,_o,Fa,kl,Gs,ko,Pu,Ou,Fu,Gn,$a,ne,Ee,Zu,Yt,We,je,Ll,Do,Wa,Rl,Fl,ti,Vl,Qa,Of,ei,Bl,en,$l,jn,Hl,Xs,zl,Qs,Wl,jl,Yf,qf,bs,Cs,vs,sn,Ve,ys,ke,ni,Pt,Me,xs,Kl,pg,Gl=fi(()=>{fa();yo=class{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,n,i){let o=e.listeners[i],r=e.duration;o.forEach(a=>a({chart:t,initial:e.initial,numSteps:r,currentStep:Math.min(n-e.start,r)}))}_refresh(){this._request||(this._running=!0,this._request=Hi.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(t=Date.now()){let e=0;this._charts.forEach((n,i)=>{if(!n.running||!n.items.length)return;let o=n.items,r=o.length-1,a=!1,l;for(;r>=0;--r)l=o[r],l._active?(l._total>n.duration&&(n.duration=l._total),l.tick(t),a=!0):(o[r]=o[o.length-1],o.pop());a&&(i.draw(),this._notify(i,n,t,"progress")),o.length||(n.running=!1,this._notify(i,n,t,"complete"),n.initial=!1),e+=o.length}),this._lastDate=t,e===0&&(this._running=!1)}_getAnims(t){let e=this._charts,n=e.get(t);return n||(n={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,n)),n}listen(t,e,n){this._getAnims(t).listeners[e].push(n)}add(t,e){!e||!e.length||this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){let e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce((n,i)=>Math.max(n,i._duration),0),this._refresh())}running(t){if(!this._running)return!1;let e=this._charts.get(t);return!(!e||!e.running||!e.items.length)}stop(t){let e=this._charts.get(t);if(!e||!e.items.length)return;let n=e.items,i=n.length-1;for(;i>=0;--i)n[i].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}},se=new yo,ga="transparent",ph={boolean(s,t,e){return e>.5?t:s},color(s,t,e){let n=Ki(s||ga),i=n.valid&&Ki(t||ga);return i&&i.valid?i.mix(n,e).hexString():t},number(s,t,e){return s+(t-s)*e}},qn=class{constructor(t,e,n,i){let o=e[n];i=fs([t.to,i,o,t.from]);let r=fs([t.from,o,i]);this._active=!0,this._fn=t.fn||ph[t.type||typeof r],this._easing=ns[t.easing]||ns.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=n,this._from=r,this._to=i,this._promises=void 0}active(){return this._active}update(t,e,n){if(this._active){this._notify(!1);let i=this._target[this._prop],o=n-this._start,r=this._duration-o;this._start=n,this._duration=Math.floor(Math.max(r,t.duration)),this._total+=o,this._loop=!!t.loop,this._to=fs([t.to,e,i,t.from]),this._from=fs([t.from,i,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){let e=t-this._start,n=this._duration,i=this._prop,o=this._from,r=this._loop,a=this._to,l;if(this._active=o!==a&&(r||e1?2-l:l,l=this._easing(Math.min(1,Math.max(0,l))),this._target[i]=this._fn(o,a,l)}wait(){let t=this._promises||(this._promises=[]);return new Promise((e,n)=>{t.push({res:e,rej:n})})}_notify(t){let e=t?"res":"rej",n=this._promises||[];for(let i=0;i{let o=t[i];if(!et(o))return;let r={};for(let a of e)r[a]=o[a];(dt(o.properties)&&o.properties||[i]).forEach(a=>{(a===i||!n.has(a))&&n.set(a,r)})})}_animateOptions(t,e){let n=e.options,i=bh(t,n);if(!i)return[];let o=this._createAnimations(i,n);return n.$shared&&mh(t.options.$animations,n).then(()=>{t.options=n},()=>{}),o}_createAnimations(t,e){let n=this._properties,i=[],o=t.$animations||(t.$animations={}),r=Object.keys(e),a=Date.now(),l;for(l=r.length-1;l>=0;--l){let c=r[l];if(c.charAt(0)==="$")continue;if(c==="options"){i.push(...this._animateOptions(t,e));continue}let d=e[c],h=o[c],u=n.get(c);if(h)if(u&&h.active()){h.update(u,d,a);continue}else h.cancel();if(!u||!u.duration){t[c]=d;continue}o[c]=h=new qn(u,t,c,d),i.push(h)}return i}update(t,e){if(this._properties.size===0){Object.assign(t,e);return}let n=this._createAnimations(t,e);if(n.length)return se.add(this._chart,n),!0}};co=s=>s==="reset"||s==="none",ya=(s,t)=>t?s:Object.assign({},s),wh=(s,t,e)=>s&&!t.hidden&&t._stacked&&{keys:fl(e,!0),values:null},At=class{constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){let t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=ao(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&js(this._cachedMeta),this.index=t}linkScales(){let t=this.chart,e=this._cachedMeta,n=this.getDataset(),i=(h,u,f,g)=>h==="x"?u:h==="r"?g:f,o=e.xAxisID=J(n.xAxisID,lo(t,"x")),r=e.yAxisID=J(n.yAxisID,lo(t,"y")),a=e.rAxisID=J(n.rAxisID,lo(t,"r")),l=e.indexAxis,c=e.iAxisID=i(l,o,r,a),d=e.vAxisID=i(l,r,o,a);e.xScale=this.getScaleForId(o),e.yScale=this.getScaleForId(r),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(c),e.vScale=this.getScaleForId(d)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){let e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){let t=this._cachedMeta;this._data&&Bi(this._data,this),t._stacked&&js(t)}_dataCheck(){let t=this.getDataset(),e=t.data||(t.data=[]),n=this._data;if(et(e)){let i=this._cachedMeta;this._data=xh(e,i)}else if(n!==e){if(n){Bi(n,this);let i=this._cachedMeta;js(i),i._parsed=[]}e&&Object.isExtensible(e)&&Gr(e,this),this._syncList=[],this._data=e}}addElements(){let t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){let e=this._cachedMeta,n=this.getDataset(),i=!1;this._dataCheck();let o=e._stacked;e._stacked=ao(e.vScale,e),e.stack!==n.stack&&(i=!0,js(e),e.stack=n.stack),this._resyncElements(t),(i||o!==e._stacked)&&(va(this,e._parsed),e._stacked=ao(e.vScale,e))}configure(){let t=this.chart.config,e=t.datasetScopeKeys(this._type),n=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(n,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){let{_cachedMeta:n,_data:i}=this,{iScale:o,_stacked:r}=n,a=o.axis,l=t===0&&e===i.length?!0:n._sorted,c=t>0&&n._parsed[t-1],d,h,u;if(this._parsing===!1)n._parsed=i,n._sorted=!0,u=i;else{dt(i[t])?u=this.parseArrayData(n,i,t,e):et(i[t])?u=this.parseObjectData(n,i,t,e):u=this.parsePrimitiveData(n,i,t,e);let f=()=>h[a]===null||c&&h[a]p||h=0;--u)if(!g()){this.updateRangeFromParsed(c,t,f,l);break}}return c}getAllParsedValues(t){let e=this._cachedMeta._parsed,n=[],i,o,r;for(i=0,o=e.length;i=0&&tthis.getContext(n,i,e),p=c.resolveNamedOptions(u,f,g,h);return p.$shared&&(p.$shared=l,o[r]=Object.freeze(ya(p,l))),p}_resolveAnimations(t,e,n){let i=this.chart,o=this._cachedDataOpts,r=`animation-${e}`,a=o[r];if(a)return a;let l;if(i.options.animation!==!1){let d=this.chart.config,h=d.datasetAnimationScopeKeys(this._type,e),u=d.getOptionScopes(this.getDataset(),h);l=d.createResolver(u,this.getContext(t,n,e))}let c=new Zs(i,l&&l.animations);return l&&l._cacheable&&(o[r]=Object.freeze(c)),c}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||co(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){let n=this.resolveDataElementOptions(t,e),i=this._sharedOptions,o=this.getSharedOptions(n),r=this.includeOptions(e,o)||o!==i;return this.updateSharedOptions(o,e,n),{sharedOptions:o,includeOptions:r}}updateElement(t,e,n,i){co(i)?Object.assign(t,n):this._resolveAnimations(e,i).update(t,n)}updateSharedOptions(t,e,n){t&&!co(e)&&this._resolveAnimations(void 0,e).update(t,n)}_setStyle(t,e,n,i){t.active=i;let o=this.getStyle(e,i);this._resolveAnimations(e,n,i).update(t,{options:!i&&this.getSharedOptions(o)||o})}removeHoverStyle(t,e,n){this._setStyle(t,n,"active",!1)}setHoverStyle(t,e,n){this._setStyle(t,n,"active",!0)}_removeDatasetHoverStyle(){let t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){let t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){let e=this._data,n=this._cachedMeta.data;for(let[a,l,c]of this._syncList)this[a](l,c);this._syncList=[];let i=n.length,o=e.length,r=Math.min(o,i);r&&this.parse(0,r),o>i?this._insertElements(i,o-i,t):o{for(c.length+=e,a=c.length-1;a>=r;a--)c[a]=c[a-e]};for(l(o),a=t;ad.controller.options.grouped),o=n.options.stacked,r=[],a=this._cachedMeta.controller.getParsed(e),l=a&&a[n.axis],c=d=>{let h=d._parsed.find(f=>f[n.axis]===l),u=h&&h[d.vScale.axis];if(tt(u)||isNaN(u))return!0};for(let d of i)if(!(e!==void 0&&c(d))&&((o===!1||r.indexOf(d.stack)===-1||o===void 0&&d.stack===void 0)&&r.push(d.stack),d.index===t))break;return r.length||r.push(void 0),r}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){let t=this.chart.scales,e=this.chart.options.indexAxis;return Object.keys(t).filter(n=>t[n].axis===e).shift()}_getAxis(){let t={},e=this.getFirstScaleIdForIndexAxis();for(let n of this.chart.data.datasets)t[J(this.chart.options.indexAxis==="x"?n.xAxisID:n.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,n){let i=this._getStacks(t,n),o=e!==void 0?i.indexOf(e):-1;return o===-1?i.length-1:o}_getRuler(){let t=this.options,e=this._cachedMeta,n=e.iScale,i=[],o,r;for(o=0,r=e.data.length;o=0;--n)e=Math.max(e,t[n].size(this.resolveDataElementOptions(n))/2);return e>0&&e}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart.data.labels||[],{xScale:i,yScale:o}=e,r=this.getParsed(t),a=i.getLabelForValue(r.x),l=o.getLabelForValue(r.y),c=r._custom;return{label:n[t]||"",value:"("+a+", "+l+(c?", "+c:"")+")"}}update(t){let e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,n,i){let o=i==="reset",{iScale:r,vScale:a}=this._cachedMeta,{sharedOptions:l,includeOptions:c}=this._getSharedOptions(e,i),d=r.axis,h=a.axis;for(let u=e;u+n[l];if(et(n[t])){let{key:l="value"}=this._parsing;o=c=>+ce(n[c],l)}let r,a;for(r=t,a=t+e;r0&&!isNaN(t)?ht*(Math.abs(t)/e):0}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart,i=n.data.labels||[],o=ds(e._parsed[t],n.options.locale);return{label:i[t]||"",value:o}}getMaxBorderWidth(t){let e=0,n=this.chart,i,o,r,a,l;if(!t){for(i=0,o=n.data.datasets.length;it!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),U(ie,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data,{labels:{pointStyle:n,textAlign:i,color:o,useBorderRadius:r,borderRadius:a}}=t.legend.options;return e.labels.length&&e.datasets.length?e.labels.map((l,c)=>{let h=t.getDatasetMeta(0).controller.getStyle(c);return{text:l,fillStyle:h.backgroundColor,fontColor:o,hidden:!t.getDataVisibility(c),lineDash:h.borderDash,lineDashOffset:h.borderDashOffset,lineJoin:h.borderJoinStyle,lineWidth:h.borderWidth,strokeStyle:h.borderColor,textAlign:i,pointStyle:n,borderRadius:r&&(a||h.borderRadius),index:c}}):[]}},onClick(t,e,n){n.chart.toggleDataVisibility(e.index),n.chart.update()}}}});$e=class extends At{initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){let e=this._cachedMeta,{dataset:n,data:i=[],_dataset:o}=e,r=this.chart._animationsDisabled,{start:a,count:l}=Wi(e,i,r);this._drawStart=a,this._drawCount=l,ji(e)&&(a=0,l=i.length),n._chart=this.chart,n._datasetIndex=this.index,n._decimated=!!o._decimated,n.points=i;let c=this.resolveDatasetElementOptions(t);this.options.showLine||(c.borderWidth=0),c.segment=this.options.segment,this.updateElement(n,void 0,{animated:!r,options:c},t),this.updateElements(i,a,l,t)}updateElements(t,e,n,i){let o=i==="reset",{iScale:r,vScale:a,_stacked:l,_dataset:c}=this._cachedMeta,{sharedOptions:d,includeOptions:h}=this._getSharedOptions(e,i),u=r.axis,f=a.axis,{spanGaps:g,segment:p}=this.options,m=Oe(g)?g:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||i==="none",x=e+n,C=t.length,E=e>0&&this.getParsed(e-1);for(let S=0;S=x){v.skip=!0;continue}let _=this.getParsed(S),w=tt(_[f]),T=v[u]=r.getPixelForValue(_[u],S),k=v[f]=o||w?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,_,l):_[f],S);v.skip=isNaN(T)||isNaN(k)||w,v.stop=S>0&&Math.abs(_[u]-E[u])>m,p&&(v.parsed=_,v.raw=c.data[S]),h&&(v.options=d||this.resolveDataElementOptions(S,y.active?"active":i)),b||this.updateElement(y,S,v,i),E=_}}getMaxOverflow(){let t=this._cachedMeta,e=t.dataset,n=e.options&&e.options.borderWidth||0,i=t.data||[];if(!i.length)return n;let o=i[0].size(this.resolveDataElementOptions(0)),r=i[i.length-1].size(this.resolveDataElementOptions(i.length-1));return Math.max(n,o,r)/2}draw(){let t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}};U($e,"id","line"),U($e,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),U($e,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});we=class extends At{constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){let e=this._cachedMeta,n=this.chart,i=n.data.labels||[],o=ds(e._parsed[t].r,n.options.locale);return{label:i[t]||"",value:o}}parseObjectData(t,e,n,i){return Ji.bind(this)(t,e,n,i)}update(t){let e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){let t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach((n,i)=>{let o=this.getParsed(i).r;!isNaN(o)&&this.chart.getDataVisibility(i)&&(oe.max&&(e.max=o))}),e}_updateRadius(){let t=this.chart,e=t.chartArea,n=t.options,i=Math.min(e.right-e.left,e.bottom-e.top),o=Math.max(i/2,0),r=Math.max(n.cutoutPercentage?o/100*n.cutoutPercentage:1,0),a=(o-r)/t.getVisibleDatasetCount();this.outerRadius=o-a*this.index,this.innerRadius=this.outerRadius-a}updateElements(t,e,n,i){let o=i==="reset",r=this.chart,l=r.options.animation,c=this._cachedMeta.rScale,d=c.xCenter,h=c.yCenter,u=c.getIndexAngle(0)-.5*nt,f=u,g,p=360/this.countVisibleElements();for(g=0;g{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++}),e}_computeAngle(t,e,n){return this.chart.getDataVisibility(t)?zt(this.resolveDataElementOptions(t,e).angle||n):0}};U(we,"id","polarArea"),U(we,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),U(we,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){let e=t.data;if(e.labels.length&&e.datasets.length){let{labels:{pointStyle:n,color:i}}=t.legend.options;return e.labels.map((o,r)=>{let l=t.getDatasetMeta(0).controller.getStyle(r);return{text:o,fillStyle:l.backgroundColor,strokeStyle:l.borderColor,fontColor:i,lineWidth:l.borderWidth,pointStyle:n,hidden:!t.getDataVisibility(r),index:r}})}return[]}},onClick(t,e,n){n.chart.toggleDataVisibility(e.index),n.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}});ps=class extends ie{};U(ps,"id","pie"),U(ps,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});He=class extends At{getLabelAndValue(t){let e=this._cachedMeta.vScale,n=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(n[e.axis])}}parseObjectData(t,e,n,i){return Ji.bind(this)(t,e,n,i)}update(t){let e=this._cachedMeta,n=e.dataset,i=e.data||[],o=e.iScale.getLabels();if(n.points=i,t!=="resize"){let r=this.resolveDatasetElementOptions(t);this.options.showLine||(r.borderWidth=0);let a={_loop:!0,_fullLoop:o.length===i.length,options:r};this.updateElement(n,void 0,a,t)}this.updateElements(i,0,i.length,t)}updateElements(t,e,n,i){let o=this._cachedMeta.rScale,r=i==="reset";for(let a=e;a0&&this.getParsed(e-1);for(let E=e;E0&&Math.abs(y[f]-C[f])>b,m&&(v.parsed=y,v.raw=c.data[E]),u&&(v.options=h||this.resolveDataElementOptions(E,S.active?"active":i)),x||this.updateElement(S,E,v,i),C=y}this.updateSharedOptions(h,i,d)}getMaxOverflow(){let t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let a=0;for(let l=e.length-1;l>=0;--l)a=Math.max(a,e[l].size(this.resolveDataElementOptions(l))/2);return a>0&&a}let n=t.dataset,i=n.options&&n.options.borderWidth||0;if(!e.length)return i;let o=e[0].size(this.resolveDataElementOptions(0)),r=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(i,o,r)/2}};U(ze,"id","scatter"),U(ze,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),U(ze,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});pl=Object.freeze({__proto__:null,BarController:Ne,BubbleController:Be,DoughnutController:ie,LineController:$e,PieController:ps,PolarAreaController:we,RadarController:He,ScatterController:ze});xo=class s{constructor(t){U(this,"options");this.options=t||{}}static override(t){Object.assign(s.prototype,t)}init(){}formats(){return Ie()}parse(){return Ie()}format(){return Ie()}add(){return Ie()}diff(){return Ie()}startOf(){return Ie()}endOf(){return Ie()}},ml={_date:xo};bl={evaluateInteractionItems:nn,modes:{index(s,t,e,n){let i=Se(t,s),o=e.axis||"x",r=e.includeInvisible||!1,a=e.intersect?uo(s,i,o,n,r):fo(s,i,o,!1,n,r),l=[];return a.length?(s.getSortedVisibleDatasetMetas().forEach(c=>{let d=a[0].index,h=c.data[d];h&&!h.skip&&l.push({element:h,datasetIndex:c.index,index:d})}),l):[]},dataset(s,t,e,n){let i=Se(t,s),o=e.axis||"xy",r=e.includeInvisible||!1,a=e.intersect?uo(s,i,o,n,r):fo(s,i,o,!1,n,r);if(a.length>0){let l=a[0].datasetIndex,c=s.getDatasetMeta(l).data;a=[];for(let d=0;d{typeof p.beforeLayout=="function"&&p.beforeLayout()});let d=l.reduce((p,m)=>m.box.options&&m.box.options.display===!1?p:p+1,0)||1,h=Object.freeze({outerWidth:t,outerHeight:e,padding:i,availableWidth:o,availableHeight:r,vBoxMaxWidth:o/2/d,hBoxMaxHeight:r/2}),u=Object.assign({},i);yl(u,_t(n));let f=Object.assign({maxPadding:u,w:o,h:r,x:i.left,y:i.top},i),g=jh(l.concat(c),h);qs(a.fullSize,f,h,g),qs(l,f,h,g),qs(c,f,h,g)&&qs(l,f,h,g),Yh(f),wa(a.leftAndTop,f,h,g),f.x+=f.w,f.y+=f.h,wa(a.rightAndBottom,f,h,g),s.chartArea={left:f.left,top:f.top,right:f.left+f.w,bottom:f.top+f.h,height:f.h,width:f.w},rt(a.chartArea,p=>{let m=p.box;Object.assign(m,s.chartArea),m.update(f.w,f.h,{left:0,top:0,right:0,bottom:0})})}},Js=class{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,n){}removeEventListener(t,e,n){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,n,i){return e=Math.max(0,e||t.width),n=n||t.height,{width:e,height:Math.max(0,i?Math.floor(e/i):n)}}isAttached(t){return!0}updateConfig(t){}},Xn=class extends Js{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}},Yn="$chartjs",qh={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},Da=s=>s===null||s==="";xl=la?{passive:!0}:!1;tn=new Map,Ma=0;Zn=class extends Js{acquireContext(t,e){let n=t&&t.getContext&&t.getContext("2d");return n&&n.canvas===t?(Xh(t,e),n):null}releaseContext(t){let e=t.canvas;if(!e[Yn])return!1;let n=e[Yn].initial;["height","width"].forEach(o=>{let r=n[o];tt(r)?e.removeAttribute(o):e.setAttribute(o,r)});let i=n.style||{};return Object.keys(i).forEach(o=>{e.style[o]=i[o]}),e.width=e.width,delete e[Yn],!0}addEventListener(t,e,n){this.removeEventListener(t,e);let i=t.$proxies||(t.$proxies={}),r={attach:tu,detach:eu,resize:iu}[e]||ou;i[e]=r(t,e,n)}removeEventListener(t,e){let n=t.$proxies||(t.$proxies={}),i=n[e];if(!i)return;({attach:go,detach:go,resize:go}[e]||Zh)(t,e,i),n[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,n,i){return aa(t,e,n,i)}isAttached(t){let e=t&&Bn(t);return!!(e&&e.isConnected)}};Rt=class{constructor(){U(this,"x");U(this,"y");U(this,"active",!1);U(this,"options");U(this,"$animations")}tooltipPosition(t){let{x:e,y:n}=this.getProps(["x","y"],t);return{x:e,y:n}}hasValue(){return Oe(this.x)&&Oe(this.y)}getProps(t,e){let n=this.$animations;if(!e||!n)return this;let i={};return t.forEach(o=>{i[o]=n[o]&&n[o].active()?n[o]._to:this[o]}),i}};U(Rt,"defaults",{}),U(Rt,"defaultRoutes");uu=s=>s==="left"?"right":s==="right"?"left":s,Ta=(s,t,e)=>t==="top"||t==="left"?s[t]+e:s[t]-e,La=(s,t)=>Math.min(t||s,s);Te=class s extends Rt{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:n,_suggestedMax:i}=this;return t=Tt(t,Number.POSITIVE_INFINITY),e=Tt(e,Number.NEGATIVE_INFINITY),n=Tt(n,Number.POSITIVE_INFINITY),i=Tt(i,Number.NEGATIVE_INFINITY),{min:Tt(t,n),max:Tt(e,i),minDefined:gt(t),maxDefined:gt(e)}}getMinMax(t){let{min:e,max:n,minDefined:i,maxDefined:o}=this.getUserBounds(),r;if(i&&o)return{min:e,max:n};let a=this.getMatchingVisibleMetas();for(let l=0,c=a.length;ln?n:e,n=i&&e>n?e:n,{min:Tt(e,Tt(n,e)),max:Tt(n,Tt(e,n))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){let t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){ct(this.options.beforeUpdate,[this])}update(t,e,n){let{beginAtZero:i,grace:o,ticks:r}=this.options,a=r.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=n=Object.assign({left:0,right:0,top:0,bottom:0},n),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+n.left+n.right:this.height+n.top+n.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=ea(this,o,i),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();let l=a=o||n<=1||!this.isHorizontal()){this.labelRotation=i;return}let d=this._getLabelSizes(),h=d.widest.width,u=d.highest.height,f=vt(this.chart.width-h,0,this.maxWidth);a=t.offset?this.maxWidth/n:f/(n-1),h+6>a&&(a=f/(n-(t.offset?.5:1)),l=this.maxHeight-Ys(t.grid)-e.padding-Pa(t.title,this.chart.options.font),c=Math.sqrt(h*h+u*u),r=An(Math.min(Math.asin(vt((d.highest.height+6)/a,-1,1)),Math.asin(vt(l/c,-1,1))-Math.asin(vt(u/c,-1,1)))),r=Math.max(i,Math.min(o,r))),this.labelRotation=r}afterCalculateLabelRotation(){ct(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){ct(this.options.beforeFit,[this])}fit(){let t={width:0,height:0},{chart:e,options:{ticks:n,title:i,grid:o}}=this,r=this._isVisible(),a=this.isHorizontal();if(r){let l=Pa(i,e.options.font);if(a?(t.width=this.maxWidth,t.height=Ys(o)+l):(t.height=this.maxHeight,t.width=Ys(o)+l),n.display&&this.ticks.length){let{first:c,last:d,widest:h,highest:u}=this._getLabelSizes(),f=n.padding*2,g=zt(this.labelRotation),p=Math.cos(g),m=Math.sin(g);if(a){let b=n.mirror?0:m*h.width+p*u.height;t.height=Math.min(this.maxHeight,t.height+b+f)}else{let b=n.mirror?0:p*h.width+m*u.height;t.width=Math.min(this.maxWidth,t.width+b+f)}this._calculatePadding(c,d,m,p)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,n,i){let{ticks:{align:o,padding:r},position:a}=this.options,l=this.labelRotation!==0,c=a!=="top"&&this.axis==="x";if(this.isHorizontal()){let d=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1),u=0,f=0;l?c?(u=i*t.width,f=n*e.height):(u=n*t.height,f=i*e.width):o==="start"?f=e.width:o==="end"?u=t.width:o!=="inner"&&(u=t.width/2,f=e.width/2),this.paddingLeft=Math.max((u-d+r)*this.width/(this.width-d),0),this.paddingRight=Math.max((f-h+r)*this.width/(this.width-h),0)}else{let d=e.height/2,h=t.height/2;o==="start"?(d=0,h=t.height):o==="end"&&(d=e.height,h=0),this.paddingTop=d+r,this.paddingBottom=h+r}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){ct(this.options.afterFit,[this])}isHorizontal(){let{axis:t,position:e}=this.options;return e==="top"||e==="bottom"||t==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){this.beforeTickToLabelConversion(),this.generateTickLabels(t);let e,n;for(e=0,n=t.length;e({width:r[w]||0,height:a[w]||0});return{first:_(0),last:_(e-1),widest:_(y),highest:_(v),widths:r,heights:a}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){let e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);let e=this._startPixel+t*this._length;return jr(this._alignToPixels?xe(this.chart,e,0):e)}getDecimalForPixel(t){let e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){let{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){let e=this.ticks||[];if(t>=0&&ta*i?a/n:l/i:l*i0}_computeGridLineItems(t){let e=this.axis,n=this.chart,i=this.options,{grid:o,position:r,border:a}=i,l=o.offset,c=this.isHorizontal(),h=this.ticks.length+(l?1:0),u=Ys(o),f=[],g=a.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,b=function(R){return xe(n,R,p)},x,C,E,S,y,v,_,w,T,k,M,L;if(r==="top")x=b(this.bottom),v=this.bottom-u,w=x-m,k=b(t.top)+m,L=t.bottom;else if(r==="bottom")x=b(this.top),k=t.top,L=b(t.bottom)-m,v=x+m,w=this.top+u;else if(r==="left")x=b(this.right),y=this.right-u,_=x-m,T=b(t.left)+m,M=t.right;else if(r==="right")x=b(this.left),T=t.left,M=b(t.right)-m,y=x+m,_=this.left+u;else if(e==="x"){if(r==="center")x=b((t.top+t.bottom)/2+.5);else if(et(r)){let R=Object.keys(r)[0],D=r[R];x=b(this.chart.scales[R].getPixelForValue(D))}k=t.top,L=t.bottom,v=x+m,w=v+u}else if(e==="y"){if(r==="center")x=b((t.left+t.right)/2);else if(et(r)){let R=Object.keys(r)[0],D=r[R];x=b(this.chart.scales[R].getPixelForValue(D))}y=x-m,_=y-u,T=t.left,M=t.right}let I=J(i.ticks.maxTicksLimit,h),P=Math.max(1,Math.ceil(h/I));for(C=0;C0&&(F-=G/2);break}$={left:F,top:B,width:G+A.width,height:z+A.height,color:P.backdropColor}}m.push({label:E,font:w,textOffset:M,options:{rotation:p,color:D,strokeColor:W,strokeWidth:O,textAlign:j,textBaseline:L,translation:[S,y],backdrop:$}})}return m}_getXAxisLabelAlignment(){let{position:t,ticks:e}=this.options;if(-zt(this.labelRotation))return t==="top"?"left":"right";let i="center";return e.align==="start"?i="left":e.align==="end"?i="right":e.align==="inner"&&(i="inner"),i}_getYAxisLabelAlignment(t){let{position:e,ticks:{crossAlign:n,mirror:i,padding:o}}=this.options,r=this._getLabelSizes(),a=t+o,l=r.widest.width,c,d;return e==="left"?i?(d=this.right+o,n==="near"?c="left":n==="center"?(c="center",d+=l/2):(c="right",d+=l)):(d=this.right-a,n==="near"?c="right":n==="center"?(c="center",d-=l/2):(c="left",d=this.left)):e==="right"?i?(d=this.left+o,n==="near"?c="right":n==="center"?(c="center",d-=l/2):(c="left",d-=l)):(d=this.left+a,n==="near"?c="left":n==="center"?(c="center",d+=l/2):(c="right",d=this.right)):c="right",{textAlign:c,x:d}}_computeLabelArea(){if(this.options.ticks.mirror)return;let t=this.chart,e=this.options.position;if(e==="left"||e==="right")return{top:0,left:this.left,bottom:t.height,right:this.right};if(e==="top"||e==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:t.width}}drawBackground(){let{ctx:t,options:{backgroundColor:e},left:n,top:i,width:o,height:r}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(n,i,o,r),t.restore())}getLineWidthForValue(t){let e=this.options.grid;if(!this._isVisible()||!e.display)return 0;let i=this.ticks.findIndex(o=>o.value===t);return i>=0?e.setContext(this.getContext(i)).lineWidth:0}drawGrid(t){let e=this.options.grid,n=this.ctx,i=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t)),o,r,a=(l,c,d)=>{!d.width||!d.color||(n.save(),n.lineWidth=d.width,n.strokeStyle=d.color,n.setLineDash(d.borderDash||[]),n.lineDashOffset=d.borderDashOffset,n.beginPath(),n.moveTo(l.x,l.y),n.lineTo(c.x,c.y),n.stroke(),n.restore())};if(e.display)for(o=0,r=i.length;o{this.draw(o)}}]:[{z:n,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:i,draw:()=>{this.drawBorder()}},{z:e,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(t){let e=this.chart.getSortedVisibleDatasetMetas(),n=this.axis+"AxisID",i=[],o,r;for(o=0,r=e.length;o{let o=n||this._getRegistryForType(i);n||o.isForType(i)||o===this.plugins&&i.id?this._exec(t,o,i):rt(i,r=>{let a=n||this._getRegistryForType(r);this._exec(t,a,r)})})}_exec(t,e,n){let i=Ln(t);ct(n["before"+i],[],n),e[t](n),ct(n["after"+i],[],n)}_getRegistryForType(t){for(let e=0;eo.filter(a=>!r.some(l=>a.plugin.id===l.plugin.id));this._notify(i(e,n),t,"stop"),this._notify(i(n,e),t,"start")}};Fa=new Map,kl=new Set;Gs=(s,t,e)=>{let n=ce(t,e);n!==void 0&&s.add(n)},ko=class{constructor(t){this._config=Au(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=El(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){let t=this._config;this.clearCache(),Sl(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return Wn(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,e){return Wn(`${t}.transition.${e}`,()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,e){return Wn(`${t}-${e}`,()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]])}pluginScopeKeys(t){let e=t.id,n=this.type;return Wn(`${n}-plugin-${e}`,()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]])}_cachedScopes(t,e){let n=this._scopeCache,i=n.get(t);return(!i||e)&&(i=new Map,n.set(t,i)),i}getOptionScopes(t,e,n){let{options:i,type:o}=this,r=this._cachedScopes(t,n),a=r.get(e);if(a)return a;let l=new Set;e.forEach(d=>{t&&(l.add(t),d.forEach(h=>Gs(l,t,h))),d.forEach(h=>Gs(l,i,h)),d.forEach(h=>Gs(l,ye[o]||{},h)),d.forEach(h=>Gs(l,ut,h)),d.forEach(h=>Gs(l,On,h))});let c=Array.from(l);return c.length===0&&c.push(Object.create(null)),kl.has(e)&&r.set(e,c),c}chartOptionScopes(){let{options:t,type:e}=this;return[t,ye[e]||{},ut.datasets[e]||{},{type:e},ut,On]}resolveNamedOptions(t,e,n,i=[""]){let o={$shared:!0},{resolver:r,subPrefixes:a}=Ia(this._resolverCache,t,i),l=r;if(Ru(r,e)){o.$shared=!1,n=ae(n)?n():n;let c=this.createResolver(t,n,a);l=Re(r,n,c)}for(let c of e)o[c]=l[c];return o}createResolver(t,e,n=[""],i){let{resolver:o}=Ia(this._resolverCache,t,n);return et(e)?Re(o,e,void 0,i):o}};Pu=s=>et(s)&&Object.getOwnPropertyNames(s).some(t=>ae(s[t]));Ou="4.5.1",Fu=["top","bottom","left","right","chartArea"];Gn={},$a=s=>{let t=wl(s);return Object.values(Gn).filter(e=>e.canvas===t).pop()};ne=class{static register(...t){Kt.add(...t),Ha()}static unregister(...t){Kt.remove(...t),Ha()}constructor(t,e){let n=this.config=new ko(e),i=wl(t),o=$a(i);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");let r=n.createResolver(n.chartOptionScopes(),this.getContext());this.platform=new(n.platform||_l(i)),this.platform.updateConfig(n);let a=this.platform.acquireContext(i,r.aspectRatio),l=a&&a.canvas,c=l&&l.height,d=l&&l.width;if(this.id=Nr(),this.ctx=a,this.canvas=l,this.width=d,this.height=c,this._options=r,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new _o,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=qr(h=>this.update(h),r.resizeDelay||0),this._dataChanges=[],Gn[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}se.listen(this,"complete",Ba),se.listen(this,"progress",Iu),this._initialize(),this.attached&&this.update()}get aspectRatio(){let{options:{aspectRatio:t,maintainAspectRatio:e},width:n,height:i,_aspectRatio:o}=this;return tt(t)?e&&o?o:i?n/i:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return Kt}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():to(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Yi(this.canvas,this.ctx),this}stop(){return se.stop(this),this}resize(t,e){se.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){let n=this.options,i=this.canvas,o=n.maintainAspectRatio&&this.aspectRatio,r=this.platform.getMaximumSize(i,t,e,o),a=n.devicePixelRatio||this.platform.getDevicePixelRatio(),l=this.width?"resize":"attach";this.width=r.width,this.height=r.height,this._aspectRatio=this.aspectRatio,to(this,a,!0)&&(this.notifyPlugins("resize",{size:r}),ct(n.onResize,[this,r],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){let e=this.options.scales||{};rt(e,(n,i)=>{n.id=i})}buildOrUpdateScales(){let t=this.options,e=t.scales,n=this.scales,i=Object.keys(n).reduce((r,a)=>(r[a]=!1,r),{}),o=[];e&&(o=o.concat(Object.keys(e).map(r=>{let a=e[r],l=Eo(r,a),c=l==="r",d=l==="x";return{options:a,dposition:c?"chartArea":d?"bottom":"left",dtype:c?"radialLinear":d?"category":"linear"}}))),rt(o,r=>{let a=r.options,l=a.id,c=Eo(l,a),d=J(a.type,r.dtype);(a.position===void 0||Va(a.position,c)!==Va(r.dposition))&&(a.position=r.dposition),i[l]=!0;let h=null;if(l in n&&n[l].type===d)h=n[l];else{let u=Kt.getScale(d);h=new u({id:l,type:d,ctx:this.ctx,chart:this}),n[h.id]=h}h.init(a,t)}),rt(i,(r,a)=>{r||delete n[a]}),rt(n,r=>{St.configure(this,r,r.options),St.addBox(this,r)})}_updateMetasets(){let t=this._metasets,e=this.data.datasets.length,n=t.length;if(t.sort((i,o)=>i.index-o.index),n>e){for(let i=e;ie.length&&delete this._stacks,t.forEach((n,i)=>{e.filter(o=>o===n._dataset).length===0&&this._destroyDatasetMeta(i)})}buildOrUpdateControllers(){let t=[],e=this.data.datasets,n,i;for(this._removeUnreferencedMetasets(),n=0,i=e.length;n{this.getDatasetMeta(e).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){let e=this.config;e.update();let n=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),i=this._animationsDisabled=!n.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0})===!1)return;let o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let r=0;for(let c=0,d=this.data.datasets.length;c{c.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(Na("z","_idx"));let{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){rt(this.scales,t=>{St.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){let t=this.options,e=new Set(Object.keys(this._listeners)),n=new Set(t.events);(!Oi(e,n)||!!this._responsiveListeners!==t.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){let{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(let{method:n,start:i,count:o}of e){let r=n==="_removeElements"?-o:o;Vu(t,i,r)}}_getUniformDataChanges(){let t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];let e=this.data.datasets.length,n=o=>new Set(t.filter(r=>r[0]===o).map((r,a)=>a+","+r.splice(1).join(","))),i=n(0);for(let o=1;oo.split(",")).map(o=>({method:o[1],start:+o[2],count:+o[3]}))}_updateLayout(t){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;St.update(this,this.width,this.height,t);let e=this.chartArea,n=e.width<=0||e.height<=0;this._layers=[],rt(this.boxes,i=>{n&&i.position==="chartArea"||(i.configure&&i.configure(),this._layers.push(...i._layers()))},this),this._layers.forEach((i,o)=>{i._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})!==!1){for(let e=0,n=this.data.datasets.length;e=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){let e=this.ctx,n={meta:t,index:t.index,cancelable:!0},i=ro(this,t);this.notifyPlugins("beforeDatasetDraw",n)!==!1&&(i&&zs(e,i),t.controller.draw(),i&&Ws(e),n.cancelable=!1,this.notifyPlugins("afterDatasetDraw",n))}isPointInArea(t){return Zt(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,n,i){let o=bl.modes[e];return typeof o=="function"?o(this,t,n,i):[]}getDatasetMeta(t){let e=this.data.datasets[t],n=this._metasets,i=n.filter(o=>o&&o._dataset===e).pop();return i||(i={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},n.push(i)),i}getContext(){return this.$context||(this.$context=de(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){let e=this.data.datasets[t];if(!e)return!1;let n=this.getDatasetMeta(t);return typeof n.hidden=="boolean"?!n.hidden:!e.hidden}setDatasetVisibility(t,e){let n=this.getDatasetMeta(t);n.hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,n){let i=n?"show":"hide",o=this.getDatasetMeta(t),r=o.controller._resolveAnimations(void 0,i);as(e)?(o.data[e].hidden=!n,this.update()):(this.setDatasetVisibility(t,n),r.update(o,{visible:n}),this.update(a=>a.datasetIndex===t?i:void 0))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){let e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),se.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,o,r),t[o]=r},i=(o,r,a)=>{o.offsetX=r,o.offsetY=a,this._eventHandler(o)};rt(this.options.events,o=>n(o,i))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});let t=this._responsiveListeners,e=this.platform,n=(l,c)=>{e.addEventListener(this,l,c),t[l]=c},i=(l,c)=>{t[l]&&(e.removeEventListener(this,l,c),delete t[l])},o=(l,c)=>{this.canvas&&this.resize(l,c)},r,a=()=>{i("attach",a),this.attached=!0,this.resize(),n("resize",o),n("detach",r)};r=()=>{this.attached=!1,i("resize",o),this._stop(),this._resize(0,0),n("attach",a)},e.isAttached(this.canvas)?a():r()}unbindEvents(){rt(this._listeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._listeners={},rt(this._responsiveListeners,(t,e)=>{this.platform.removeEventListener(this,e,t)}),this._responsiveListeners=void 0}updateHoverStyle(t,e,n){let i=n?"set":"remove",o,r,a,l;for(e==="dataset"&&(o=this.getDatasetMeta(t[0].datasetIndex),o.controller["_"+i+"DatasetHoverStyle"]()),a=0,l=t.length;a{let a=this.getDatasetMeta(o);if(!a)throw new Error("No dataset found at index "+o);return{datasetIndex:o,element:a.data[r],index:r}});!Hs(n,e)&&(this._active=n,this._lastEvent=null,this._updateHoverStyles(n,e))}notifyPlugins(t,e,n){return this._plugins.notify(this,t,e,n)}isPluginEnabled(t){return this._plugins._cache.filter(e=>e.plugin.id===t).length===1}_updateHoverStyles(t,e,n){let i=this.options.hover,o=(l,c)=>l.filter(d=>!c.some(h=>d.datasetIndex===h.datasetIndex&&d.index===h.index)),r=o(e,t),a=n?t:o(t,e);r.length&&this.updateHoverStyle(r,i.mode,!1),a.length&&i.mode&&this.updateHoverStyle(a,i.mode,!0)}_eventHandler(t,e){let n={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},i=r=>(r.options.events||this.options.events).includes(t.native.type);if(this.notifyPlugins("beforeEvent",n,i)===!1)return;let o=this._handleEvent(t,e,n.inChartArea);return n.cancelable=!1,this.notifyPlugins("afterEvent",n,i),(o||n.changed)&&this.render(),this}_handleEvent(t,e,n){let{_active:i=[],options:o}=this,r=e,a=this._getActiveElements(t,i,n,r),l=Hr(t),c=Nu(t,this._lastEvent,n,l);n&&(this._lastEvent=null,ct(o.onHover,[t,a,this],this),l&&ct(o.onClick,[t,a,this],this));let d=!Hs(a,i);return(d||e)&&(this._active=a,this._updateHoverStyles(a,i,e)),this._lastEvent=c,d}_getActiveElements(t,e,n,i){if(t.type==="mouseout")return[];if(!n)return e;let o=this.options.hover;return this.getElementsAtEventForMode(t,o.mode,o,i)}};U(ne,"defaults",ut),U(ne,"instances",Gn),U(ne,"overrides",ye),U(ne,"registry",Kt),U(ne,"version",Ou),U(ne,"getChart",$a);Ee=class extends Rt{constructor(e){super();U(this,"circumference");U(this,"endAngle");U(this,"fullCircles");U(this,"innerRadius");U(this,"outerRadius");U(this,"pixelMargin");U(this,"startAngle");this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,e&&Object.assign(this,e)}inRange(e,n,i){let o=this.getProps(["x","y"],i),{angle:r,distance:a}=Ni(o,{x:e,y:n}),{startAngle:l,endAngle:c,innerRadius:d,outerRadius:h,circumference:u}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),f=(this.options.spacing+this.options.borderWidth)/2,g=J(u,c-l),p=cs(r,l,c)&&l!==c,m=g>=ht||p,b=te(a,d+f,h+f);return m&&b}getCenterPoint(e){let{x:n,y:i,startAngle:o,endAngle:r,innerRadius:a,outerRadius:l}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],e),{offset:c,spacing:d}=this.options,h=(o+r)/2,u=(a+l+d+c)/2;return{x:n+Math.cos(h)*u,y:i+Math.sin(h)*u}}tooltipPosition(e){return this.getCenterPoint(e)}draw(e){let{options:n,circumference:i}=this,o=(n.offset||0)/4,r=(n.spacing||0)/2,a=n.circular;if(this.pixelMargin=n.borderAlign==="inner"?.33:0,this.fullCircles=i>ht?Math.floor(i/ht):0,i===0||this.innerRadius<0||this.outerRadius<0)return;e.save();let l=(this.startAngle+this.endAngle)/2;e.translate(Math.cos(l)*o,Math.sin(l)*o);let c=1-Math.sin(Math.min(nt,i||0)),d=o*c;e.fillStyle=n.backgroundColor,e.strokeStyle=n.borderColor,Wu(e,this,d,r,a),ju(e,this,d,r,a),e.restore()}};U(Ee,"id","arc"),U(Ee,"defaults",{borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0,selfJoin:!1}),U(Ee,"defaultRoutes",{backgroundColor:"backgroundColor"}),U(Ee,"descriptors",{_scriptable:!0,_indexable:e=>e!=="borderDash"});Zu=typeof Path2D=="function";Yt=class extends Rt{constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){let n=this.options;if((n.tension||n.cubicInterpolationMode==="monotone")&&!n.stepped&&!this._pointsUpdated){let i=n.spanGaps?this._loop:this._fullLoop;ra(this._points,n,t,i,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=ua(this,this.options.segment))}first(){let t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){let t=this.segments,e=this.points,n=t.length;return n&&e[t[n-1].end]}interpolate(t,e){let n=this.options,i=t[e],o=this.points,r=oo(this,{property:e,start:i,end:i});if(!r.length)return;let a=[],l=qu(n),c,d;for(c=0,d=r.length;ct!=="borderDash"&&t!=="fill"});We=class extends Rt{constructor(e){super();U(this,"parsed");U(this,"skip");U(this,"stop");this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,e&&Object.assign(this,e)}inRange(e,n,i){let o=this.options,{x:r,y:a}=this.getProps(["x","y"],i);return Math.pow(e-r,2)+Math.pow(n-a,2)s.replace("rgb(","rgba(").replace(")",", 0.5)"));Rl={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(s,t,e){if(!e.enabled)return;let{data:{datasets:n},options:i}=s.config,{elements:o}=i,r=ja(n)||df(i)||o&&ja(o)||hf();if(!e.forceOverride&&r)return;let a=cf(s);n.forEach(a)}};Fl={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(s,t,e)=>{if(!e.enabled){Ua(s);return}let n=s.width;s.data.datasets.forEach((i,o)=>{let{_data:r,indexAxis:a}=i,l=s.getDatasetMeta(o),c=r||i.data;if(fs([a,s.options.indexAxis])==="y"||!l.controller.supportsDecimation)return;let d=s.scales[l.xAxisID];if(d.type!=="linear"&&d.type!=="time"||s.options.parsing)return;let{start:h,count:u}=gf(l,c),f=e.threshold||4*n;if(u<=f){Ol(i);return}tt(r)&&(i._data=c,delete i.data,Object.defineProperty(i,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(p){this._data=p}}));let g;switch(e.algorithm){case"lttb":g=uf(c,h,u,n,e);break;case"min-max":g=ff(c,h,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${e.algorithm}'`)}i._decimated=g})},destroy(s){Ua(s)}};ti=class{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,n){let{x:i,y:o,radius:r}=this;return e=e||{start:0,end:ht},t.arc(i,o,r,e.end,e.start,!0),!n.bounds}interpolate(t){let{x:e,y:n,radius:i}=this,o=t.angle;return{x:e+Math.cos(o)*i,y:n+Math.sin(o)*i,angle:o}}};Vl={id:"filler",afterDatasetsUpdate(s,t,e){let n=(s.data.datasets||[]).length,i=[],o,r,a,l;for(r=0;r=0;--r){let a=i[r].$filler;a&&(a.line.updateControlPoints(o,a.axis),n&&a.fill&&bo(s.ctx,a,o))}},beforeDatasetsDraw(s,t,e){if(e.drawTime!=="beforeDatasetsDraw")return;let n=s.getSortedVisibleDatasetMetas();for(let i=n.length-1;i>=0;--i){let o=n[i].$filler;Ya(o)&&bo(s.ctx,o,s.chartArea)}},beforeDatasetDraw(s,t,e){let n=t.meta.$filler;!Ya(n)||e.drawTime!=="beforeDatasetDraw"||bo(s.ctx,n,s.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}},Qa=(s,t)=>{let{boxHeight:e=t,boxWidth:n=t}=s;return s.usePointStyle&&(e=Math.min(e,t),n=s.pointStyleWidth||Math.min(n,t)),{boxWidth:n,boxHeight:e,itemHeight:Math.max(t,e)}},Of=(s,t)=>s!==null&&t!==null&&s.datasetIndex===t.datasetIndex&&s.index===t.index,ei=class extends Rt{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,n){this.maxWidth=t,this.maxHeight=e,this._margins=n,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){let t=this.options.labels||{},e=ct(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter(n=>t.filter(n,this.chart.data))),t.sort&&(e=e.sort((n,i)=>t.sort(n,i,this.chart.data))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){let{options:t,ctx:e}=this;if(!t.display){this.width=this.height=0;return}let n=t.labels,i=bt(n.font),o=i.size,r=this._computeTitleHeight(),{boxWidth:a,itemHeight:l}=Qa(n,o),c,d;e.font=i.string,this.isHorizontal()?(c=this.maxWidth,d=this._fitRows(r,o,a,l)+10):(d=this.maxHeight,c=this._fitCols(r,i,a,l)+10),this.width=Math.min(c,t.maxWidth||this.maxWidth),this.height=Math.min(d,t.maxHeight||this.maxHeight)}_fitRows(t,e,n,i){let{ctx:o,maxWidth:r,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],c=this.lineWidths=[0],d=i+a,h=t;o.textAlign="left",o.textBaseline="middle";let u=-1,f=-d;return this.legendItems.forEach((g,p)=>{let m=n+e/2+o.measureText(g.text).width;(p===0||c[c.length-1]+m+2*a>r)&&(h+=d,c[c.length-(p>0?0:1)]=0,f+=d,u++),l[p]={left:0,top:f,row:u,width:m,height:i},c[c.length-1]+=m+a}),h}_fitCols(t,e,n,i){let{ctx:o,maxHeight:r,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],c=this.columnSizes=[],d=r-t,h=a,u=0,f=0,g=0,p=0;return this.legendItems.forEach((m,b)=>{let{itemWidth:x,itemHeight:C}=Ff(n,e,o,m,i);b>0&&f+C+2*a>d&&(h+=u+a,c.push({width:u,height:f}),g+=u+a,p++,u=f=0),l[b]={left:g,top:f,col:p,width:x,height:C},u=Math.max(u,x),f+=C+a}),h+=u,c.push({width:u,height:f}),h}adjustHitBoxes(){if(!this.options.display)return;let t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:n,labels:{padding:i},rtl:o}}=this,r=Fe(o,this.left,this.width);if(this.isHorizontal()){let a=0,l=Ct(n,this.left+i,this.right-this.lineWidths[a]);for(let c of e)a!==c.row&&(a=c.row,l=Ct(n,this.left+i,this.right-this.lineWidths[a])),c.top+=this.top+t+i,c.left=r.leftForLtr(r.x(l),c.width),l+=c.width+i}else{let a=0,l=Ct(n,this.top+t+i,this.bottom-this.columnSizes[a].height);for(let c of e)c.col!==a&&(a=c.col,l=Ct(n,this.top+t+i,this.bottom-this.columnSizes[a].height)),c.top=l,c.left+=this.left+i,c.left=r.leftForLtr(r.x(c.left),c.width),l+=c.height+i}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){let t=this.ctx;zs(t,this),this._draw(),Ws(t)}}_draw(){let{options:t,columnSizes:e,lineWidths:n,ctx:i}=this,{align:o,labels:r}=t,a=ut.color,l=Fe(t.rtl,this.left,this.width),c=bt(r.font),{padding:d}=r,h=c.size,u=h/2,f;this.drawTitle(),i.textAlign=l.textAlign("left"),i.textBaseline="middle",i.lineWidth=.5,i.font=c.string;let{boxWidth:g,boxHeight:p,itemHeight:m}=Qa(r,h),b=function(y,v,_){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;i.save();let w=J(_.lineWidth,1);if(i.fillStyle=J(_.fillStyle,a),i.lineCap=J(_.lineCap,"butt"),i.lineDashOffset=J(_.lineDashOffset,0),i.lineJoin=J(_.lineJoin,"miter"),i.lineWidth=w,i.strokeStyle=J(_.strokeStyle,a),i.setLineDash(J(_.lineDash,[])),r.usePointStyle){let T={radius:p*Math.SQRT2/2,pointStyle:_.pointStyle,rotation:_.rotation,borderWidth:w},k=l.xPlus(y,g/2),M=v+u;Gi(i,T,k,M,r.pointStyleWidth&&g)}else{let T=v+Math.max((h-p)/2,0),k=l.leftForLtr(y,g),M=_e(_.borderRadius);i.beginPath(),Object.values(M).some(L=>L!==0)?us(i,{x:k,y:T,w:g,h:p,radius:M}):i.rect(k,T,g,p),i.fill(),w!==0&&i.stroke()}i.restore()},x=function(y,v,_){Ce(i,_.text,y,v+m/2,c,{strikethrough:_.hidden,textAlign:l.textAlign(_.textAlign)})},C=this.isHorizontal(),E=this._computeTitleHeight();C?f={x:Ct(o,this.left+d,this.right-n[0]),y:this.top+d+E,line:0}:f={x:this.left+d,y:Ct(o,this.top+E+d,this.bottom-e[0].height),line:0},so(this.ctx,t.textDirection);let S=m+d;this.legendItems.forEach((y,v)=>{i.strokeStyle=y.fontColor,i.fillStyle=y.fontColor;let _=i.measureText(y.text).width,w=l.textAlign(y.textAlign||(y.textAlign=r.textAlign)),T=g+u+_,k=f.x,M=f.y;l.setWidth(this.width),C?v>0&&k+T+d>this.right&&(M=f.y+=S,f.line++,k=f.x=Ct(o,this.left+d,this.right-n[f.line])):v>0&&M+S>this.bottom&&(k=f.x=k+e[f.line].width+d,f.line++,M=f.y=Ct(o,this.top+E+d,this.bottom-e[f.line].height));let L=l.x(k);if(b(L,M,y),k=Xr(w,k+g+u,C?k+T:this.right,t.rtl),x(l.x(k),M,y),C)f.x+=T+d;else if(typeof y.text!="string"){let I=c.lineHeight;f.y+=Nl(y,I)+d}else f.y+=S}),no(this.ctx,t.textDirection)}drawTitle(){let t=this.options,e=t.title,n=bt(e.font),i=_t(e.padding);if(!e.display)return;let o=Fe(t.rtl,this.left,this.width),r=this.ctx,a=e.position,l=n.size/2,c=i.top+l,d,h=this.left,u=this.width;if(this.isHorizontal())u=Math.max(...this.lineWidths),d=this.top+c,h=Ct(t.align,h,this.right-u);else{let g=this.columnSizes.reduce((p,m)=>Math.max(p,m.height),0);d=c+Ct(t.align,this.top,this.bottom-g-t.labels.padding-this._computeTitleHeight())}let f=Ct(a,h,h+u);r.textAlign=o.textAlign(Rn(a)),r.textBaseline="middle",r.strokeStyle=e.color,r.fillStyle=e.color,r.font=n.string,Ce(r,e.text,f,d,n)}_computeTitleHeight(){let t=this.options.title,e=bt(t.font),n=_t(t.padding);return t.display?e.lineHeight+n.height:0}_getLegendItemAt(t,e){let n,i,o;if(te(t,this.left,this.right)&&te(e,this.top,this.bottom)){for(o=this.legendHitBoxes,n=0;ns.chart.options.color,boxWidth:40,padding:10,generateLabels(s){let t=s.data.datasets,{labels:{usePointStyle:e,pointStyle:n,textAlign:i,color:o,useBorderRadius:r,borderRadius:a}}=s.legend.options;return s._getSortedDatasetMetas().map(l=>{let c=l.controller.getStyle(e?0:void 0),d=_t(c.borderWidth);return{text:t[l.index].label,fillStyle:c.backgroundColor,fontColor:o,hidden:!l.visible,lineCap:c.borderCapStyle,lineDash:c.borderDash,lineDashOffset:c.borderDashOffset,lineJoin:c.borderJoinStyle,lineWidth:(d.width+d.height)/4,strokeStyle:c.borderColor,pointStyle:n||c.pointStyle,rotation:c.rotation,textAlign:i||c.textAlign,borderRadius:r&&(a||c.borderRadius),datasetIndex:l.index}},this)}},title:{color:s=>s.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:s=>!s.startsWith("on"),labels:{_scriptable:s=>!["generateLabels","filter","sort"].includes(s)}}},en=class extends Rt{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){let n=this.options;if(this.left=0,this.top=0,!n.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=t,this.height=this.bottom=e;let i=dt(n.text)?n.text.length:1;this._padding=_t(n.padding);let o=i*bt(n.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){let t=this.options.position;return t==="top"||t==="bottom"}_drawArgs(t){let{top:e,left:n,bottom:i,right:o,options:r}=this,a=r.align,l=0,c,d,h;return this.isHorizontal()?(d=Ct(a,n,o),h=e+t,c=o-n):(r.position==="left"?(d=n+t,h=Ct(a,i,e),l=nt*-.5):(d=o-t,h=Ct(a,e,i),l=nt*.5),c=i-e),{titleX:d,titleY:h,maxWidth:c,rotation:l}}draw(){let t=this.ctx,e=this.options;if(!e.display)return;let n=bt(e.font),o=n.lineHeight/2+this._padding.top,{titleX:r,titleY:a,maxWidth:l,rotation:c}=this._drawArgs(o);Ce(t,e.text,0,0,n,{color:e.color,maxWidth:l,rotation:c,textAlign:Rn(e.align),textBaseline:"middle",translation:[r,a]})}};$l={id:"title",_element:en,start(s,t,e){Bf(s,e)},stop(s){let t=s.titleBlock;St.removeBox(s,t),delete s.titleBlock},beforeUpdate(s,t,e){let n=s.titleBlock;St.configure(s,n,e),n.options=e},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}},jn=new WeakMap,Hl={id:"subtitle",start(s,t,e){let n=new en({ctx:s.ctx,options:e,chart:s});St.configure(s,n,e),St.addBox(s,n),jn.set(s,n)},stop(s){St.removeBox(s,jn.get(s)),jn.delete(s)},beforeUpdate(s,t,e){let n=jn.get(s);St.configure(s,n,e),n.options=e},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}},Xs={average(s){if(!s.length)return!1;let t,e,n=new Set,i=0,o=0;for(t=0,e=s.length;ta+l)/n.size,y:i/o}},nearest(s,t){if(!s.length)return!1;let e=t.x,n=t.y,i=Number.POSITIVE_INFINITY,o,r,a;for(o=0,r=s.length;o0){let t=s[0],e=t.chart.data.labels,n=e?e.length:0;if(this&&this.options&&this.options.mode==="dataset")return t.dataset.label||"";if(t.label)return t.label;if(n>0&&t.dataIndex{let r={before:[],lines:[],after:[]},a=sl(n,o);ee(r.before,he(Lt(a,"beforeLabel",this,o))),ee(r.lines,Lt(a,"label",this,o)),ee(r.after,he(Lt(a,"afterLabel",this,o))),i.push(r)}),i}getAfterBody(t,e){return el(Lt(e.callbacks,"afterBody",this,t))}getFooter(t,e){let{callbacks:n}=e,i=Lt(n,"beforeFooter",this,t),o=Lt(n,"footer",this,t),r=Lt(n,"afterFooter",this,t),a=[];return a=ee(a,he(i)),a=ee(a,he(o)),a=ee(a,he(r)),a}_createItems(t){let e=this._active,n=this.chart.data,i=[],o=[],r=[],a=[],l,c;for(l=0,c=e.length;lt.filter(d,h,u,n))),t.itemSort&&(a=a.sort((d,h)=>t.itemSort(d,h,n))),rt(a,d=>{let h=sl(t.callbacks,d);i.push(Lt(h,"labelColor",this,d)),o.push(Lt(h,"labelPointStyle",this,d)),r.push(Lt(h,"labelTextColor",this,d))}),this.labelColors=i,this.labelPointStyles=o,this.labelTextColors=r,this.dataPoints=a,a}update(t,e){let n=this.options.setContext(this.getContext()),i=this._active,o,r=[];if(!i.length)this.opacity!==0&&(o={opacity:0});else{let a=Xs[n.position].call(this,i,this._eventPosition);r=this._createItems(n),this.title=this.getTitle(r,n),this.beforeBody=this.getBeforeBody(r,n),this.body=this.getBody(r,n),this.afterBody=this.getAfterBody(r,n),this.footer=this.getFooter(r,n);let l=this._size=Za(this,n),c=Object.assign({},a,l),d=Ja(this.chart,n,c),h=tl(n,c,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,o={opacity:1,x:h.x,y:h.y,width:l.width,height:l.height,caretX:a.x,caretY:a.y}}this._tooltipItems=r,this.$context=void 0,o&&this._resolveAnimations().update(this,o),t&&n.external&&n.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,n,i){let o=this.getCaretPosition(t,n,i);e.lineTo(o.x1,o.y1),e.lineTo(o.x2,o.y2),e.lineTo(o.x3,o.y3)}getCaretPosition(t,e,n){let{xAlign:i,yAlign:o}=this,{caretSize:r,cornerRadius:a}=n,{topLeft:l,topRight:c,bottomLeft:d,bottomRight:h}=_e(a),{x:u,y:f}=t,{width:g,height:p}=e,m,b,x,C,E,S;return o==="center"?(E=f+p/2,i==="left"?(m=u,b=m-r,C=E+r,S=E-r):(m=u+g,b=m+r,C=E-r,S=E+r),x=m):(i==="left"?b=u+Math.max(l,d)+r:i==="right"?b=u+g-Math.max(c,h)-r:b=this.caretX,o==="top"?(C=f,E=C-r,m=b-r,x=b+r):(C=f+p,E=C+r,m=b+r,x=b-r),S=C),{x1:m,x2:b,x3:x,y1:C,y2:E,y3:S}}drawTitle(t,e,n){let i=this.title,o=i.length,r,a,l;if(o){let c=Fe(n.rtl,this.x,this.width);for(t.x=Un(this,n.titleAlign,n),e.textAlign=c.textAlign(n.titleAlign),e.textBaseline="middle",r=bt(n.titleFont),a=n.titleSpacing,e.fillStyle=n.titleColor,e.font=r.string,l=0;lx!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,us(t,{x:p,y:g,w:c,h:l,radius:b}),t.fill(),t.stroke(),t.fillStyle=r.backgroundColor,t.beginPath(),us(t,{x:m,y:g+1,w:c-2,h:l-2,radius:b}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(p,g,c,l),t.strokeRect(p,g,c,l),t.fillStyle=r.backgroundColor,t.fillRect(m,g+1,c-2,l-2))}t.fillStyle=this.labelTextColors[n]}drawBody(t,e,n){let{body:i}=this,{bodySpacing:o,bodyAlign:r,displayColors:a,boxHeight:l,boxWidth:c,boxPadding:d}=n,h=bt(n.bodyFont),u=h.lineHeight,f=0,g=Fe(n.rtl,this.x,this.width),p=function(_){e.fillText(_,g.x(t.x+f),t.y+u/2),t.y+=u+o},m=g.textAlign(r),b,x,C,E,S,y,v;for(e.textAlign=r,e.textBaseline="middle",e.font=h.string,t.x=Un(this,m,n),e.fillStyle=n.bodyColor,rt(this.beforeBody,p),f=a&&m!=="right"?r==="center"?c/2+d:c+2+d:0,E=0,y=i.length;E0&&e.stroke()}_updateAnimationTarget(t){let e=this.chart,n=this.$animations,i=n&&n.x,o=n&&n.y;if(i||o){let r=Xs[t.position].call(this,this._active,this._eventPosition);if(!r)return;let a=this._size=Za(this,t),l=Object.assign({},r,this._size),c=Ja(e,t,l),d=tl(t,l,c,e);(i._to!==d.x||o._to!==d.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=a.width,this.height=a.height,this.caretX=r.x,this.caretY=r.y,this._resolveAnimations().update(this,d))}}_willRender(){return!!this.opacity}draw(t){let e=this.options.setContext(this.getContext()),n=this.opacity;if(!n)return;this._updateAnimationTarget(e);let i={width:this.width,height:this.height},o={x:this.x,y:this.y};n=Math.abs(n)<.001?0:n;let r=_t(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=n,this.drawBackground(o,t,i,e),so(t,e.textDirection),o.y+=r.top,this.drawTitle(o,t,e),this.drawBody(o,t,e),this.drawFooter(o,t,e),no(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){let n=this._active,i=t.map(({datasetIndex:a,index:l})=>{let c=this.chart.getDatasetMeta(a);if(!c)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:c.data[l],index:l}}),o=!Hs(n,i),r=this._positionChanged(i,e);(o||r)&&(this._active=i,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,n=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;let i=this.options,o=this._active||[],r=this._getActiveElements(t,o,e,n),a=this._positionChanged(r,t),l=e||!Hs(r,o)||a;return l&&(this._active=r,(i.enabled||i.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),l}_getActiveElements(t,e,n,i){let o=this.options;if(t.type==="mouseout")return[];if(!i)return e.filter(a=>this.chart.data.datasets[a.datasetIndex]&&this.chart.getDatasetMeta(a.datasetIndex).controller.getParsed(a.index)!==void 0);let r=this.chart.getElementsAtEventForMode(t,o.mode,o,n);return o.reverse&&r.reverse(),r}_positionChanged(t,e){let{caretX:n,caretY:i,options:o}=this,r=Xs[o.position].call(this,t,e);return r!==!1&&(n!==r.x||i!==r.y)}};U(Qs,"positioners",Xs);Wl={id:"tooltip",_element:Qs,positioners:Xs,afterInit(s,t,e){e&&(s.tooltip=new Qs({chart:s,options:e}))},beforeUpdate(s,t,e){s.tooltip&&s.tooltip.initialize(e)},reset(s,t,e){s.tooltip&&s.tooltip.initialize(e)},afterDraw(s){let t=s.tooltip;if(t&&t._willRender()){let e={tooltip:t};if(s.notifyPlugins("beforeTooltipDraw",{...e,cancelable:!0})===!1)return;t.draw(s.ctx),s.notifyPlugins("afterTooltipDraw",e)}},afterEvent(s,t){if(s.tooltip){let e=t.replay;s.tooltip.handleEvent(t.event,e,t.inChartArea)&&(t.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(s,t)=>t.bodyFont.size,boxWidth:(s,t)=>t.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:zl},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:s=>s!=="filter"&&s!=="itemSort"&&s!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]},jl=Object.freeze({__proto__:null,Colors:Rl,Decimation:Fl,Filler:Vl,Legend:Bl,SubTitle:Hl,Title:$l,Tooltip:Wl}),Yf=(s,t,e,n)=>(typeof t=="string"?(e=s.push(t)-1,n.unshift({index:e,label:t})):isNaN(t)&&(e=null),e);qf=(s,t)=>s===null?null:vt(Math.round(s),0,t);bs=class extends Te{constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){let e=this._addedLabels;if(e.length){let n=this.getLabels();for(let{index:i,label:o}of e)n[i]===o&&n.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(tt(t))return null;let n=this.getLabels();return e=isFinite(e)&&n[e]===t?e:Gf(n,t,J(e,t),this._addedLabels),qf(e,n.length-1)}determineDataLimits(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),{min:n,max:i}=this.getMinMax(!0);this.options.bounds==="ticks"&&(t||(n=0),e||(i=this.getLabels().length-1)),this.min=n,this.max=i}buildTicks(){let t=this.min,e=this.max,n=this.options.offset,i=[],o=this.getLabels();o=t===0&&e===o.length-1?o:o.slice(t,e+1),this._valueRange=Math.max(o.length-(n?0:1),1),this._startValue=this.min-(n?.5:0);for(let r=t;r<=e;r++)i.push({value:r});return i}getLabelForValue(t){return nl.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return typeof t!="number"&&(t=this.parse(t)),t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){let e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}};U(bs,"id","category"),U(bs,"defaults",{ticks:{callback:nl}});Cs=class extends Te{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return tt(t)||(typeof t=="number"||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){let{beginAtZero:t}=this.options,{minDefined:e,maxDefined:n}=this.getUserBounds(),{min:i,max:o}=this,r=l=>i=e?i:l,a=l=>o=n?o:l;if(t){let l=Ut(i),c=Ut(o);l<0&&c<0?a(0):l>0&&c>0&&r(0)}if(i===o){let l=o===0?1:Math.abs(o*.05);a(o+l),t||r(i-l)}this.min=i,this.max=o}getTickLimit(){let t=this.options.ticks,{maxTicksLimit:e,stepSize:n}=t,i;return n?(i=Math.ceil(this.max/n)-Math.floor(this.min/n)+1,i>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${n} would result generating up to ${i} ticks. Limiting to 1000.`),i=1e3)):(i=this.computeTickLimit(),e=e||11),e&&(i=Math.min(e,i)),i}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){let t=this.options,e=t.ticks,n=this.getTickLimit();n=Math.max(2,n);let i={maxTicks:n,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:e.includeBounds!==!1},o=this._range||this,r=Xf(i,o);return t.bounds==="ticks"&&Ii(r,this,"value"),t.reverse?(r.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),r}configure(){let t=this.ticks,e=this.min,n=this.max;if(super.configure(),this.options.offset&&t.length){let i=(n-e)/Math.max(t.length-1,1)/2;e-=i,n+=i}this._startValue=e,this._endValue=n,this._valueRange=n-e}getLabelForValue(t){return ds(t,this.chart.options.locale,this.options.ticks.format)}},vs=class extends Cs{determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=gt(t)?t:0,this.max=gt(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){let t=this.isHorizontal(),e=t?this.width:this.height,n=zt(this.options.ticks.minRotation),i=(t?Math.sin(n):Math.cos(n))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,o.lineHeight/i))}getPixelForValue(t){return t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}};U(vs,"id","linear"),U(vs,"defaults",{ticks:{callback:hs.formatters.numeric}});sn=s=>Math.floor(le(s)),Ve=(s,t)=>Math.pow(10,sn(s)+t);ys=class extends Te{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){let n=Cs.prototype.parse.apply(this,[t,e]);if(n===0){this._zero=!0;return}return gt(n)&&n>0?n:null}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!0);this.min=gt(t)?Math.max(0,t):null,this.max=gt(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!gt(this._userMin)&&(this.min=t===Ve(this.min,0)?Ve(this.min,-1):Ve(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){let{minDefined:t,maxDefined:e}=this.getUserBounds(),n=this.min,i=this.max,o=a=>n=t?n:a,r=a=>i=e?i:a;n===i&&(n<=0?(o(1),r(10)):(o(Ve(n,-1)),r(Ve(i,1)))),n<=0&&o(Ve(i,-1)),i<=0&&r(Ve(n,1)),this.min=n,this.max=i}buildTicks(){let t=this.options,e={min:this._userMin,max:this._userMax},n=Zf(e,this);return t.bounds==="ticks"&&Ii(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}getLabelForValue(t){return t===void 0?"0":ds(t,this.chart.options.locale,this.options.ticks.format)}configure(){let t=this.min;super.configure(),this._startValue=le(t),this._valueRange=le(this.max)-le(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(le(t)-this._startValue)/this._valueRange)}getValueForPixel(t){let e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}};U(ys,"id","logarithmic"),U(ys,"defaults",{ticks:{callback:hs.formatters.logarithmic,major:{enabled:!0}}});ke=class extends Cs{constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){let t=this._padding=_t(To(this.options)/2),e=this.width=this.maxWidth-t.width,n=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+n/2+t.top),this.drawingArea=Math.floor(Math.min(e,n)/2)}determineDataLimits(){let{min:t,max:e}=this.getMinMax(!1);this.min=gt(t)&&!isNaN(t)?t:0,this.max=gt(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/To(this.options))}generateTickLabels(t){Cs.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((e,n)=>{let i=ct(this.options.pointLabels.callback,[e,n],this);return i||i===0?i:""}).filter((e,n)=>this.chart.getDataVisibility(n))}fit(){let t=this.options;t.display&&t.pointLabels.display?tg(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,n,i){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((n-i)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,n,i))}getIndexAngle(t){let e=ht/(this._pointLabels.length||1),n=this.options.startAngle||0;return xt(t*e+zt(n))}getDistanceFromCenterForValue(t){if(tt(t))return NaN;let e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(tt(t))return NaN;let e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){let e=this._pointLabels||[];if(t>=0&&t{if(h!==0||h===0&&this.min<0){l=this.getDistanceFromCenterForValue(d.value);let u=this.getContext(h),f=i.setContext(u),g=o.setContext(u);dg(this,f,l,r,g)}}),n.display){for(t.save(),a=r-1;a>=0;a--){let d=n.setContext(this.getPointLabelContext(a)),{color:h,lineWidth:u}=d;!u||!h||(t.lineWidth=u,t.strokeStyle=h,t.setLineDash(d.borderDash),t.lineDashOffset=d.borderDashOffset,l=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),c=this.getPointPosition(a,l),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(c.x,c.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){let t=this.ctx,e=this.options,n=e.ticks;if(!n.display)return;let i=this.getIndexAngle(0),o,r;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(i),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach((a,l)=>{if(l===0&&this.min>=0&&!e.reverse)return;let c=n.setContext(this.getContext(l)),d=bt(c.font);if(o=this.getDistanceFromCenterForValue(this.ticks[l].value),c.showLabelBackdrop){t.font=d.string,r=t.measureText(a.label).width,t.fillStyle=c.backdropColor;let h=_t(c.backdropPadding);t.fillRect(-r/2-h.left,-o-d.size/2-h.top,r+h.width,d.size+h.height)}Ce(t,a.label,0,-o,d,{color:c.color,strokeColor:c.textStrokeColor,strokeWidth:c.textStrokeWidth})}),t.restore()}drawTitle(){}};U(ke,"id","radialLinear"),U(ke,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:hs.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),U(ke,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),U(ke,"descriptors",{angleLines:{_fallback:"grid"}});ni={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Pt=Object.keys(ni);Me=class extends Te{constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){let n=t.time||(t.time={}),i=this._adapter=new ml._date(t.adapters.date);i.init(e),rs(n.displayFormats,i.formats()),this._parseOpts={parser:n.parser,round:n.round,isoWeekday:n.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return t===void 0?null:cl(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){let t=this.options,e=this._adapter,n=t.time.unit||"day",{min:i,max:o,minDefined:r,maxDefined:a}=this.getUserBounds();function l(c){!r&&!isNaN(c.min)&&(i=Math.min(i,c.min)),!a&&!isNaN(c.max)&&(o=Math.max(o,c.max))}(!r||!a)&&(l(this._getLabelBounds()),(t.bounds!=="ticks"||t.ticks.source!=="labels")&&l(this.getMinMax(!1))),i=gt(i)&&!isNaN(i)?i:+e.startOf(Date.now(),n),o=gt(o)&&!isNaN(o)?o:+e.endOf(Date.now(),n)+1,this.min=Math.min(i,o-1),this.max=Math.max(i+1,o)}_getLabelBounds(){let t=this.getLabelTimestamps(),e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],n=t[t.length-1]),{min:e,max:n}}buildTicks(){let t=this.options,e=t.time,n=t.ticks,i=n.source==="labels"?this.getLabelTimestamps():this._generate();t.bounds==="ticks"&&i.length&&(this.min=this._userMin||i[0],this.max=this._userMax||i[i.length-1]);let o=this.min,r=this.max,a=Kr(i,o,r);return this._unit=e.unit||(n.autoSkip?dl(e.minUnit,this.min,this.max,this._getLabelCapacity(o)):ug(this,a.length,e.minUnit,this.min,this.max)),this._majorUnit=!n.major.enabled||this._unit==="year"?void 0:fg(this._unit),this.initOffsets(i),t.reverse&&a.reverse(),ul(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(t=>+t.value))}initOffsets(t=[]){let e=0,n=0,i,o;this.options.offset&&t.length&&(i=this.getDecimalForValue(t[0]),t.length===1?e=1-i:e=(this.getDecimalForValue(t[1])-i)/2,o=this.getDecimalForValue(t[t.length-1]),t.length===1?n=o:n=(o-this.getDecimalForValue(t[t.length-2]))/2);let r=t.length<3?.5:.25;e=vt(e,0,r),n=vt(n,0,r),this._offsets={start:e,end:n,factor:1/(e+1+n)}}_generate(){let t=this._adapter,e=this.min,n=this.max,i=this.options,o=i.time,r=o.unit||dl(o.minUnit,e,n,this._getLabelCapacity(e)),a=J(i.ticks.stepSize,1),l=r==="week"?o.isoWeekday:!1,c=Oe(l)||l===!0,d={},h=e,u,f;if(c&&(h=+t.startOf(h,"isoWeek",l)),h=+t.startOf(h,c?"day":r),t.diff(n,e,r)>1e5*a)throw new Error(e+" and "+n+" are too far apart with stepSize of "+a+" "+r);let g=i.ticks.source==="data"&&this.getDataTimestamps();for(u=h,f=0;u+p)}getLabelForValue(t){let e=this._adapter,n=this.options.time;return n.tooltipFormat?e.format(t,n.tooltipFormat):e.format(t,n.displayFormats.datetime)}format(t,e){let i=this.options.time.displayFormats,o=this._unit,r=e||i[o];return this._adapter.format(t,r)}_tickFormatFunction(t,e,n,i){let o=this.options,r=o.ticks.callback;if(r)return ct(r,[t,e,n],this);let a=o.time.displayFormats,l=this._unit,c=this._majorUnit,d=l&&a[l],h=c&&a[c],u=n[e],f=c&&h&&u&&u.major;return this._adapter.format(t,i||(f?h:d))}generateTickLabels(t){let e,n,i;for(e=0,n=t.length;e0?a:1}getDataTimestamps(){let t=this._cache.data||[],e,n;if(t.length)return t;let i=this.getMatchingVisibleMetas();if(this._normalized&&i.length)return this._cache.data=i[0].controller.getAllParsedValues(this);for(e=0,n=i.length;e=e&&c<=n&&i.push(c);if(i.length<2)return[{time:e,pos:0},{time:n,pos:1}];for(r=0,a=i.length;ri-o)}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;let e=this.getDataTimestamps(),n=this.getLabelTimestamps();return e.length&&n.length?t=this.normalize(e.concat(n)):t=e.length?e:n,t=this._cache.all=t,t}getDecimalForValue(t){return(Kn(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){let e=this._offsets,n=this.getDecimalForPixel(t)/e.factor-e.end;return Kn(this._table,n*this._tableRange+this._minPos,!0)}};U(xs,"id","timeseries"),U(xs,"defaults",Me.defaults);Kl=Object.freeze({__proto__:null,CategoryScale:bs,LinearScale:vs,LogarithmicScale:ys,RadialLinearScale:ke,TimeScale:Me,TimeSeriesScale:xs}),pg=[pl,Ll,jl,Kl]});var Rg={};zo(Rg,{CardView:()=>Es,default:()=>hi});module.exports=Sc(Rg);var it=require("obsidian"),pc=an(Ds());var Ec=["AT","BE","CZ","DK","EE","FI","FR","DE","GR","HU","IS","IT","LV","LI","LT","LU","MT","NL","NO","PL","PT","SK","SI","ES","SE","CH"],kc=[{label:"\u{1F1EA}\u{1F1FA} Schengen 90/180 (example)",scope:{countries:Ec},window:{type:"rolling",days:180},threshold:90,note:"Example rule \u2014 add your own in Settings \u2192 CSV Card View."}],mi={defaultMode:"kanban-genre",notesColumns:["notes","note","Notes","Note","description","Description","review","Review"],statusColumn:"status",categoryColumn:"category",notesSubfolder:"Notes",columnWidths:{},selectColumns:["Category","Type","Rating","Status","rating","type","category","status","Score /5"],fileConfigs:{},residencyRules:kc,showResidency:!0},ln="xlsx-card-view";var jo=an(Ds()),Uo=require("obsidian"),Ke=["Image","image","Cover","cover","Poster","poster","Thumbnail","thumbnail","Thumb","thumb","Photo","photo","Picture","picture","Img","img"],Ye=["Title","title","Name","name"],Ge=["Category","category","Categories","categories","Genre","genre","Genres","genres","Type","type","Types","types","Tag","tag","Tags","tags","Topic","topic","Topics","topics","Subject","subject","Section","section"],qe=["Status","status","State","state","Progress","progress","Stage","stage","Read","read","Watched","watched","Seen","seen","Done","done","Completed","completed"],Xe=["Notes","notes","Note","note","Summary","summary","Review","review","Quote","quote","Quotes","quotes","Comment","comment","Comments","comments","Description","description","Annotation","annotation"];function cn(s,t,e){let n=(t!=null?t:"").trim();if(!n)return null;if(/^(https?:|data:)/i.test(n))return n;let i=n.match(/!?\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/);if(i)n=i[1].trim();else{let r=n.match(/!\[[^\]]*\]\(([^)]+)\)/);r&&(n=r[1].trim())}if(/^(https?:|data:)/i.test(n))return n;let o=s.metadataCache.getFirstLinkpathDest(n,e);return o instanceof Uo.TFile?s.vault.getResourcePath(o):null}var wc=15;function Xt(s){return s>=1&&s<=wc}var Dc=["0","1","true","false","yes","no",""];function Qe(s){return s.length>0&&s.every(t=>Dc.includes(t))}function Ze(s){let t=(s!=null?s:"").toLowerCase().trim();return t==="1"||t==="true"||t==="yes"}function Ms(s){return s.replace(/[\\/:*?"<>|#^[\]]/g,"").replace(/\s+/g," ").trim().slice(0,100)}function Ko(s){return s.toLowerCase().replace(/[^\p{L}\p{N}/_-]+/gu,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Nt(s){var i,o;if(!s||!s.trim())return{headers:[],rows:[]};let t=jo.default.parse(s,{header:!0,skipEmptyLines:!0}),e=((i=t.meta.fields)!=null?i:[]).map(String),n=((o=t.data)!=null?o:[]).map(r=>{let a={};return e.forEach(l=>{a[l]=r[l]!=null?String(r[l]):""}),a});return{headers:e,rows:n}}function ue(s,t){if(!s)return s;let e=s.startsWith("./")||s.startsWith("../")||s==="."||s==="..";if(!e&&s.includes("/"))return s;if(!e)return t?`${t}/${s}`:s;let n=t?t.split("/").filter(Boolean):[];for(let i of s.split("/"))if(!(i===""||i===".")){if(i===".."){n.pop();continue}n.push(i)}return n.join("/")}function Yo(s,t,e){let n=e==="asc"?1:-1;return[...s].sort((i,o)=>{var u,f;let r=((u=i[t])!=null?u:"").trim(),a=((f=o[t])!=null?f:"").trim();if(!r&&!a)return 0;if(!r)return 1;if(!a)return-1;let l=parseFloat(r),c=parseFloat(a);return(!isNaN(l)&&!isNaN(c)&&/^-?[\d.]/.test(r)&&/^-?[\d.]/.test(a)?l-c:r.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"}))*n})}function Et(s){return s.split(/[\s_-]+/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function Go(s,t){let e=(s!=null?s:"").trim();if(!e||e.toLowerCase()==="unrated"||e==="\u2014"||e==="-")return"";if(/[★⭐☆]/.test(e))return e;if(/^\d+$/.test(e)){let o=parseInt(e,10);if(o>=1&&o<=5)return"\u2605".repeat(o)}let i=Mc(e,t);return i&&i!==e&&i!=="\u2014"?i:""}function Mc(s,t){var o;let e=t.toLowerCase();if(!["rating","score","score /5"].includes(e))return s;let n=s.toLowerCase().trim();return(o={excellent:"\u2605\u2605\u2605\u2605\u2605",great:"\u2605\u2605\u2605\u2605\u2605",good:"\u2605\u2605\u2605\u2605\u2606",fair:"\u2605\u2605\u2605\u2606\u2606",poor:"\u2605\u2605\u2606\u2606\u2606",bad:"\u2605\u2606\u2606\u2606\u2606",5:"\u2605\u2605\u2605\u2605\u2605",4:"\u2605\u2605\u2605\u2605\u2606",3:"\u2605\u2605\u2605\u2606\u2606",2:"\u2605\u2605\u2606\u2606\u2606",1:"\u2605\u2606\u2606\u2606\u2606",0:"\u2606\u2606\u2606\u2606\u2606",unrated:"\u2014","":"\u2014"}[n])!=null?o:s}function qo(s,t){if(/^(year|released|decade)$/i.test((s!=null?s:"").trim()))return!0;let e=t.map(i=>(i!=null?i:"").trim()).filter(Boolean);return e.length<3?!1:e.filter(i=>/^(1[89]|20)\d{2}$/.test(i)).length/e.length>=.8}function Xo(s){let t=(s!=null?s:"").match(/\b(1[89]\d{2}|20\d{2})\b/);return t?`${Math.floor(parseInt(t[1],10)/10)*10}s`:null}function Qo(s,t,e){var r;if(!t.length)return null;let n=Math.max(12,t.length/3),i=null,o=1/0;for(let a of s){if(e.has(a))continue;let l=new Set;for(let d of t)((r=d[a])!=null?r:"").split(",").forEach(h=>{let u=h.trim();u&&l.add(u)});if(l.size<2||l.size>n)continue;let c=Math.abs(Math.log(l.size/8));ck.remove());let r=document.body.createDiv({cls:"csv-select-picker"});r.style.position="fixed",r.style.zIndex="9999";let a=()=>{let k=s.getBoundingClientRect(),M=r.offsetHeight||280,L=k.bottom+4+M>window.innerHeight&&k.top-4-M>0;r.style.left=k.left+"px",r.style.top=L?k.top-4-M+"px":k.bottom+4+"px"};a();let l=k=>{!r.contains(k.target)&&k.target!==s&&d()},c=k=>{r.contains(k.target)||d()},d=()=>{r.remove(),document.removeEventListener("mousedown",l),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",d)},h=r.createEl("input",{cls:"csv-picker-search",type:"text",placeholder:"Search or add\u2026"});h.focus();let u=r.createDiv({cls:"csv-picker-list"}),f=!!(o!=null&&o.multi),g=k=>k.split(",").map(M=>M.trim()).filter(Boolean),p=new Set(f?g(t):[]),m=()=>n([...p].join(", ")),b=f?Array.from(new Set(e.flatMap(g))):Array.from(new Set(e.filter(Boolean))),x=[],C=0,E=()=>{u.querySelectorAll(".csv-picker-item").forEach((k,M)=>{k.toggleClass("csv-picker-item--hover",M===C),M===C&&k.scrollIntoView({block:"nearest"})})},S=k=>{if(!f){n(k.isClear?"":k.value),d();return}k.isClear?p.clear():(p.has(k.value)?p.delete(k.value):p.add(k.value),k.isAdd&&!b.includes(k.value)&&b.push(k.value)),m(),k.isAdd?(h.value="",_("")):_(h.value)},y=k=>f?p.has(k):k===t,v=()=>f?p.size>0:!!t,_=k=>{u.empty(),x=[];let M=k?b.filter(L=>L.toLowerCase().includes(k.toLowerCase())):b;if(v()){x.push({value:"",isClear:!0});let L=u.createDiv({cls:"csv-picker-item csv-picker-clear"});L.setText(f?"\u2715 Clear all":"\u2715 Clear"),L.addEventListener("mousedown",I=>{I.preventDefault(),S({value:"",isClear:!0})})}if(M.forEach(L=>{x.push({value:L});let I=u.createDiv({cls:`csv-picker-item ${y(L)?"active":""}`});I.setText(f?`${p.has(L)?"\u2713 ":""}${L}`:L),I.addEventListener("mousedown",P=>{P.preventDefault(),S({value:L})})}),k&&!b.some(L=>L.toLowerCase()===k.toLowerCase())){x.push({value:k,isAdd:!0});let L=u.createDiv({cls:"csv-picker-item csv-picker-add"});L.setText(`+ Add "${k}"`),L.addEventListener("mousedown",I=>{I.preventDefault(),S({value:k,isAdd:!0})})}!M.length&&!k&&u.createDiv({cls:"csv-picker-empty",text:"No options yet. Type to add."}),C=Math.min(C,Math.max(x.length-1,0)),E()};f&&r.createEl("button",{cls:"csv-picker-done",text:"Done"}).addEventListener("mousedown",k=>{k.preventDefault(),d()}),_(""),a(),h.addEventListener("input",()=>{C=0,_(h.value),a()});let w=typeof window!="undefined"&&((T=window.matchMedia)==null?void 0:T.call(window,"(pointer: coarse)").matches);setTimeout(()=>{document.addEventListener("mousedown",l),w||(window.addEventListener("scroll",c,!0),window.addEventListener("resize",d))},0),h.addEventListener("keydown",k=>{if(k.key==="Escape"){d();return}if(k.key==="ArrowDown"){k.preventDefault(),x.length&&(C=(C+1)%x.length,E());return}if(k.key==="ArrowUp"){k.preventDefault(),x.length&&(C=(C-1+x.length)%x.length,E());return}if(k.key==="Enter")if(k.preventDefault(),x[C])S(x[C]);else{let M=h.value.trim();M&&(n(M),d())}})}function Zo(s,t,e){return!s[t]||t===e||(s[e]||(s[e]=s[t]),delete s[t]),s}var Tc={source:["confirmed","inferred","conflict"],resolved:["yes","no"]};function Jo(s){var t;return(t=Tc[s.trim().toLowerCase()])!=null?t:null}function kt(s){return/(^|[_\s-])(date|due|deadline)([_\s-]|$)/i.test(s.trim())}var dn=/^\d{4}-\d{2}-\d{2}$/;var It=require("obsidian");function fn(s,t,e,n,i=kt){let o=i(t)&&(e===""||dn.test(e.slice(0,10))),r=o?e.slice(0,10):e,a=s.createEl("input",{cls:n,type:o?"date":"text",value:r});o||(a.placeholder=t);let l=Jo(t);if(l){let c=`csv-dl-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-${Math.random().toString(36).slice(2,7)}`,d=s.createEl("datalist");d.id=c,l.forEach(h=>d.createEl("option",{value:h})),a.setAttr("list",c)}return a}var Je=class extends It.Modal{constructor(t,e,n,i,o,r,a={},l=()=>!1,c,d,h=kt){super(t),this.headers=e,this.isNotesCol=n,this.isSelectCol=i,this.getColumnValues=o,this.onSubmit=r,this.optionPresets=a,this.isBooleanCol=l,this.isCategoricalCol=c!=null?c:u=>this.isSelectCol(u)||Xt(this.getColumnValues(u).length),this.titleCol=d!=null?d:this.headers.find(u=>["title","name"].includes(u.toLowerCase())),this.isDateCol=h}onOpen(){let{contentEl:t}=this;t.empty(),t.addClass("csv-add-modal"),t.createEl("h2",{text:"Add new entry",cls:"csv-modal-title"});let e=t.createDiv({cls:"csv-modal-form"}),n={};this.headers.forEach(d=>n[d]="");let i=this.titleCol,o=new Map;i&&this.getColumnValues(i).forEach(d=>{let h=d.trim().toLowerCase();h&&!o.has(h)&&o.set(h,d.trim())}),this.headers.forEach(d=>{var m;let h=e.createDiv({cls:"csv-modal-row"});h.createEl("label",{text:Et(d),cls:"csv-modal-label"});let u=(m=this.optionPresets[d])!=null?m:[],f=d===i,g=wt(d),p=!f&&!this.isNotesCol(d)&&!g&&(u.length>0||this.isCategoricalCol(d));if(this.isBooleanCol(d)){n[d]="0";let b=h.createDiv({cls:"csv-toggle"});b.createDiv({cls:"csv-toggle-knob"}),b.addEventListener("click",()=>{let x=!b.hasClass("is-on");b.toggleClass("is-on",x),n[d]=x?"1":"0"})}else if(this.isNotesCol(d)){let b=h.createEl("textarea",{cls:"csv-modal-textarea",placeholder:"Markdown supported\u2026"});b.addEventListener("input",()=>{n[d]=b.value})}else if(p){let b="__custom__",x=[];[...u,...this.getColumnValues(d)].forEach(S=>{let y=(S!=null?S:"").trim();y&&!x.some(v=>v.toLowerCase()===y.toLowerCase())&&x.push(y)});let C=h.createEl("select",{cls:"csv-modal-select"});C.createEl("option",{text:"\u2014",value:""}),x.forEach(S=>C.createEl("option",{text:S,value:S})),C.createEl("option",{text:"+ Custom\u2026",value:b});let E=h.createEl("input",{cls:"csv-modal-input csv-modal-custom",type:"text",placeholder:`Custom ${Et(d).toLowerCase()}`});E.hide(),E.addEventListener("input",()=>{n[d]=E.value}),E.addEventListener("keydown",S=>{S.key==="Enter"&&c()}),C.addEventListener("change",()=>{C.value===b?(E.show(),E.focus(),n[d]=E.value):(E.hide(),n[d]=C.value)})}else if(!f&&g&&this.isSelectCol(d)){let x=h.createDiv({cls:"csv-modal-select-wrap"}).createDiv({cls:"csv-select-chip empty"});x.setText("\u2014 click to select \u2014"),x.addEventListener("click",C=>{C.stopPropagation(),Ft(x,n[d],this.getColumnValues(d),E=>{n[d]=E,x.setText(E||"\u2014 click to select \u2014"),x.toggleClass("empty",!E)},t,{multi:wt(d)})})}else{let b=fn(h,d,"","csv-modal-input",x=>this.isDateCol(x));if(b.addEventListener("input",()=>{n[d]=b.value}),b.addEventListener("keydown",x=>{x.key==="Enter"&&c()}),d===i&&o.size){let x=h.createDiv({cls:"csv-modal-dup-hint"});x.hide(),b.addEventListener("input",()=>{let C=o.get(b.value.trim().toLowerCase());C?(x.setText(`\u26A0 \u201C${C}\u201D is already in this file`),x.show()):x.hide()})}}});let r=t.createDiv({cls:"csv-modal-btns"});r.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),r.createEl("button",{text:"Add entry",cls:"csv-modal-submit"}).addEventListener("click",()=>c());let c=()=>{if(!Object.values(n).some(h=>h.trim())){new It.Notice("Fill in at least one field.");return}this.onSubmit(n),this.close()}}onClose(){this.contentEl.empty()}},ts=class extends It.Modal{constructor(e,n,i,o,r,a,l,c,d,h,u,f,g=()=>!1,p=kt){super(e);this.vvHandler=null;this.row={...n},this.notesCol=i,this.headers=o,this.filePath=r,this.renderComponent=new It.Component,this.isNotesCol=a,this.isSelectCol=l,this.getColumnValues=c,this.onSave=d,this.onDelete=h,this.isCategoricalCol=u!=null?u:m=>this.isSelectCol(m)||!kt(m)&&Xt(this.getColumnValues(m).length),this.titleCol=f!=null?f:this.headers.find(m=>["title","name","Title","Name"].includes(m)),this.isBooleanCol=g,this.isDateCol=p,this.modalEl.addClass("csv-note-expander-modal")}onOpen(){var g,p,m,b,x;this.renderComponent.load();let{contentEl:e}=this;e.empty(),e.addClass("csv-note-expander");let n=window.visualViewport;if(n){let C=()=>{this.modalEl.style.setProperty("--csv-modal-vh",`${n.height}px`)};C(),n.addEventListener("resize",C),n.addEventListener("scroll",C),this.vvHandler=C}let i=e.createDiv({cls:"csv-expander-header"});i.createDiv({cls:"csv-expander-title",text:(p=this.row[(g=this.titleCol)!=null?g:this.headers[0]])!=null?p:"\u2014"});let o=i.createDiv({cls:"csv-expander-header-btns"}),r=e.createDiv({cls:"csv-expander-fields"}),a=this.titleCol,l=this.headers.find(C=>["author","Author","director","Director","artist","Artist","creator","Creator"].includes(C));this.headers.forEach(C=>{var v;if(this.isNotesCol(C))return;let E=r.createDiv({cls:"csv-expander-field-row"});if(E.createDiv({cls:"csv-expander-field-label",text:Et(C)}),this.isBooleanCol(C)){let _=Ze((v=this.row[C])!=null?v:""),w=E.createDiv({cls:`csv-toggle ${_?"is-on":""}`});w.createDiv({cls:"csv-toggle-knob"}),w.addEventListener("click",()=>{let T=!w.hasClass("is-on");w.toggleClass("is-on",T),this.row[C]=T?"1":"0"});return}let S=wt(C);if(C!==a&&(S?this.isSelectCol(C):this.isCategoricalCol(C))){let _=E.createDiv({cls:`csv-select-chip ${this.row[C]?"":"empty"}`});_.setText(this.row[C]||"\u2014"),_.addEventListener("click",w=>{w.stopPropagation(),Ft(_,this.row[C],this.getColumnValues(C),T=>{this.row[C]=T,_.setText(T||"\u2014"),_.toggleClass("empty",!T)},e,{multi:wt(C)})})}else{let _=E.createDiv({cls:"csv-expander-field-value",text:this.row[C]||"\u2014"});_.addEventListener("click",()=>{var k;if(_.querySelector("input"))return;_.empty();let w=fn(_,C,(k=this.row[C])!=null?k:"","csv-inline-input",this.isDateCol);w.focus(),w.type==="text"&&w.select(),w.addEventListener("click",M=>M.stopPropagation());let T=()=>{this.row[C]=w.value,_.empty(),_.setText(w.value||"\u2014")};w.addEventListener("blur",T),w.addEventListener("keydown",M=>{M.key==="Enter"&&w.blur(),M.key==="Escape"&&(_.empty(),_.setText(this.row[C]||"\u2014"))})})}});let c=!1,d=this.notesCol&&(m=this.row[this.notesCol])!=null?m:"",h=null;if(this.notesCol){e.createDiv({cls:"csv-expander-divider"}).createDiv({cls:"csv-expander-notes-label",text:this.notesCol});let E=e.createDiv({cls:"csv-expander-rendered markdown-rendered"});E.title="Click to edit";let S=e.createDiv({cls:"csv-expander-editor"});S.style.display="none";let y=()=>{E.empty(),d.trim()?It.MarkdownRenderer.render(this.app,d,E,this.filePath,this.renderComponent):E.createDiv({cls:"csv-notes-empty",text:"+ Add note"})};y(),h=S.createEl("textarea",{cls:"csv-expander-textarea"}),h.value=d,h.addEventListener("input",()=>{d=h.value});let v=()=>{c||(c=!0,E.style.display="none",S.style.display="flex",h.value=d,h.focus())},_=()=>{c&&(c=!1,S.style.display="none",E.style.display="",d=h.value,y())};E.addEventListener("click",w=>{if(w.target.closest("a, button, input, textarea, [contenteditable]"))return;let k=window.getSelection();k&&k.toString().length>0||v()}),h.addEventListener("keydown",w=>{w.key==="Escape"&&(w.preventDefault(),h.blur())}),h.addEventListener("blur",_)}let u=e.createDiv({cls:"csv-expander-footer"});if(this.onDelete){let C=String((x=this.row[(b=this.titleCol)!=null?b:this.headers[0]])!=null?x:"").trim();u.createEl("button",{cls:"csv-expander-delete-btn",text:"Delete"}).addEventListener("click",()=>{let E=C||"this entry";window.confirm(`Delete "${E}"? This can't be undone.`)&&(this.onDelete(),this.close())})}let f=u.createDiv({cls:"csv-expander-footer-right"});f.createEl("button",{cls:"csv-modal-cancel",text:"Cancel"}).addEventListener("click",()=>this.close()),f.createEl("button",{cls:"csv-expander-save-btn",text:"Save & close"}).addEventListener("click",()=>{this.notesCol&&(c&&h&&(d=h.value),this.row[this.notesCol]=d),this.onSave(this.row),this.close()})}onClose(){let e=window.visualViewport;e&&this.vvHandler&&(e.removeEventListener("resize",this.vvHandler),e.removeEventListener("scroll",this.vvHandler)),this.vvHandler=null,this.renderComponent.unload(),this.contentEl.empty()}};var hn=class extends It.Modal{constructor(t,e,n,i,o,r,a,l,c,d,h,u,f,g=()=>0){super(t),this.headers=e,this.filePath=n,this.current={...i,habitColumns:i.habitColumns?[...i.habitColumns]:void 0,categoricalColumns:i.categoricalColumns?[...i.categoricalColumns]:void 0},this.autoDetectedHabits=o,this.autoDetectedCategorical=r,this.autoDetectedRoles=a,this.availableModes=l,this.onSave=c,this.getHeaders=d,this.getFileCfg=h,this.onAddColumn=u,this.onRemoveColumn=f,this.onCleanupBooleanColumn=g}onOpen(){var I,P,R;let{contentEl:t}=this;t.empty(),t.addClass("csv-add-modal"),t.createEl("h2",{text:"View settings for this file",cls:"csv-modal-title"}),t.createEl("p",{text:"These settings apply only to this file and override the global defaults.",cls:"csv-modal-desc"});let e=t.createDiv({cls:"csv-modal-form"}),n=()=>{this.headers=this.getHeaders();let D=this.getFileCfg();this.current={...D,habitColumns:D.habitColumns?[...D.habitColumns]:void 0,categoricalColumns:D.categoricalColumns?[...D.categoricalColumns]:void 0},this.onOpen()},i=e.createDiv({cls:"csv-modal-row"});i.createEl("label",{text:"Columns",cls:"csv-modal-label"}),i.createEl("p",{cls:"csv-modal-hint",text:`Type and Function are each exclusive per column \u2014 picking one clears it from whichever column held it before. "auto" means it's already doing that by column name, with nothing saved here yet. Card field is independent and can combine with anything. Checkbox columns get a "Clean up" action that rewrites every row to strict 1/0 right away \u2014 not deferred to Save.`});let o=[{value:"text",label:"Text"},{value:"checkbox",label:"Checkbox"},{value:"categorical",label:"Categorical"},{value:"date",label:"Date"}],r=[{value:"",label:"\u2014 no function \u2014"},{value:"title",label:"Title"},{value:"category",label:"Column group (Kanban lanes)"},{value:"status",label:"Row group / Status / Checkmark"},{value:"notes",label:"Notes"},{value:"image",label:"Image (card / kanban thumbnail)"},{value:"anki",label:"Anki card front"}],a=D=>{var $,A,z;let W=($=this.current.habitColumns)!=null?$:this.autoDetectedHabits,O=(A=this.current.categoricalColumns)!=null?A:this.autoDetectedCategorical,j=(z=this.current.dateColumns)!=null?z:this.headers.filter(G=>kt(G));return W.includes(D)?{type:"checkbox",auto:!this.current.habitColumns}:O.includes(D)?{type:"categorical",auto:!this.current.categoricalColumns}:j.includes(D)?{type:"date",auto:!this.current.dateColumns}:{type:"text",auto:!1}},l=(D,W)=>{this.current.habitColumns||(this.current.habitColumns=[...this.autoDetectedHabits]),this.current.categoricalColumns||(this.current.categoricalColumns=[...this.autoDetectedCategorical]),this.current.dateColumns||(this.current.dateColumns=this.headers.filter(O=>kt(O))),this.current.habitColumns=this.current.habitColumns.filter(O=>O!==D),this.current.categoricalColumns=this.current.categoricalColumns.filter(O=>O!==D),this.current.dateColumns=this.current.dateColumns.filter(O=>O!==D),W==="checkbox"?this.current.habitColumns.push(D):W==="categorical"?this.current.categoricalColumns.push(D):W==="date"&&this.current.dateColumns.push(D)},c=(P=(I=this.current.titleColumn)!=null?I:this.autoDetectedRoles.title)!=null?P:this.headers[0],h=i.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),u=h.createEl("thead").createEl("tr");["Column","Type","Visibility"].forEach(D=>u.createEl("th",{text:D}));let f=h.createEl("tbody"),g=()=>{var W;f.empty();let D=new Set((W=this.current.cardFields)!=null?W:this.headers);this.headers.forEach(O=>{let j=f.createEl("tr"),$=j.createEl("td",{cls:"csv-modal-colcfg-name"});$.createSpan({text:O});let A=$.createEl("button",{cls:"csv-modal-column-remove",text:"\u2715",attr:{title:`Remove "${O}" \u2014 deletes this column's data from every row`}});A.addEventListener("click",()=>{if(A.hasClass("confirm")){this.onRemoveColumn(O),n();return}f.querySelectorAll(".csv-modal-column-remove.confirm").forEach(F=>{F.removeClass("confirm"),F.setText("\u2715")}),A.addClass("confirm"),A.setText("Confirm?"),window.setTimeout(()=>{A.isConnected&&(A.removeClass("confirm"),A.setText("\u2715"))},3e3)});let z=j.createEl("td",{cls:"csv-modal-colcfg-type-cell"});if(O===c)z.createSpan({cls:"csv-modal-colcfg-fixed",text:"Text"});else{let F=z.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-type"}),{type:N,auto:H}=a(O);if(o.forEach(V=>{let K=F.createEl("option",{text:V.label,value:V.value});V.value===N&&(K.selected=!0)}),H&&F.addClass("auto-detected"),F.addEventListener("change",()=>{l(O,F.value),g()}),H&&z.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"}),N==="checkbox"){let V=z.createEl("button",{cls:"csv-modal-colcfg-cleanup-btn",text:"Clean up",attr:{title:`Rewrite every row in "${O}" to strict 1/0 (yes/true/1 \u2192 1, everything else \u2192 0)`}});V.addEventListener("click",()=>{if(V.hasClass("confirm")){let K=this.onCleanupBooleanColumn(O);new It.Notice(K>0?`"${O}": normalized ${K} row${K===1?"":"s"} to 1/0.`:`"${O}" is already strict 1/0 \u2014 nothing to change.`);return}f.querySelectorAll(".csv-modal-colcfg-cleanup-btn.confirm").forEach(K=>{K.removeClass("confirm"),K.setText("Clean up")}),V.addClass("confirm"),V.setText("Confirm?"),window.setTimeout(()=>{V.isConnected&&(V.removeClass("confirm"),V.setText("Clean up"))},3e3)})}}let B=j.createEl("td",{cls:"csv-modal-colcfg-card-cell"}).createEl("input",{type:"checkbox"});B.checked=D.has(O),B.addEventListener("change",()=>{this.current.cardFields||(this.current.cardFields=[...this.headers]),B.checked?this.current.cardFields.includes(O)||this.current.cardFields.push(O):this.current.cardFields=this.current.cardFields.filter(F=>F!==O)})})};g();let p=t.createDiv({cls:"csv-modal-section",attr:{style:"margin-top: 24px;"}});p.createEl("h3",{text:"Column Functions",cls:"csv-modal-h3"}),p.createEl("p",{cls:"csv-modal-desc",text:"Assign specific roles to your columns. 'auto' means it's already doing that by column name. Selecting '\u2014 none \u2014' disables the function entirely."});let b=p.createDiv({cls:"csv-modal-colcfg-table-wrap"}).createEl("table",{cls:"csv-modal-colcfg-table"}),x=b.createEl("thead").createEl("tr");["Function","Column"].forEach(D=>x.createEl("th",{text:D}));let C=b.createEl("tbody"),E=()=>{C.empty(),r.forEach(D=>{var G,B,F,N,H,V,K,Y,q,X,Z,at;if(D.value==="")return;let W=C.createEl("tr");W.createEl("td",{cls:"csv-modal-colcfg-name"}).setText(D.label);let j=W.createEl("td",{cls:"csv-modal-colcfg-type-cell"}),$=j.createEl("select",{cls:"csv-modal-select csv-modal-colcfg-role"});$.createEl("option",{text:"\u2014 none \u2014",value:""});let A="",z=!1;D.value==="title"?(A=(B=(G=this.current.titleColumn)!=null?G:this.autoDetectedRoles.title)!=null?B:"",z=this.current.titleColumn===void 0&&!!this.autoDetectedRoles.title):D.value==="category"?(A=(N=(F=this.current.categoryColumn)!=null?F:this.autoDetectedRoles.category)!=null?N:"",z=this.current.categoryColumn===void 0&&!!this.autoDetectedRoles.category):D.value==="status"?(A=(V=(H=this.current.statusColumn)!=null?H:this.autoDetectedRoles.status)!=null?V:"",z=this.current.statusColumn===void 0&&!!this.autoDetectedRoles.status):D.value==="notes"?(A=(Y=(K=this.current.notesColumn)!=null?K:this.autoDetectedRoles.notes)!=null?Y:"",z=this.current.notesColumn===void 0&&!!this.autoDetectedRoles.notes):D.value==="image"?(A=(X=(q=this.current.imageColumn)!=null?q:this.autoDetectedRoles.image)!=null?X:"",z=this.current.imageColumn===void 0&&!!this.autoDetectedRoles.image):D.value==="anki"&&(A=(at=(Z=this.current.ankiFrontCol)!=null?Z:this.autoDetectedRoles.anki)!=null?at:"",z=this.current.ankiFrontCol===void 0&&!!this.autoDetectedRoles.anki),this.headers.forEach(Q=>{let st=$.createEl("option",{text:Q,value:Q});Q===A&&(st.selected=!0)}),z&&A!==""&&$.addClass("auto-detected"),$.addEventListener("change",()=>{let Q=$.value;Q&&(D.value!=="title"&&this.current.titleColumn===Q&&(this.current.titleColumn=void 0),D.value!=="category"&&this.current.categoryColumn===Q&&(this.current.categoryColumn=void 0),D.value!=="status"&&this.current.statusColumn===Q&&(this.current.statusColumn=void 0),D.value!=="notes"&&this.current.notesColumn===Q&&(this.current.notesColumn=void 0),D.value!=="image"&&this.current.imageColumn===Q&&(this.current.imageColumn=void 0),D.value!=="anki"&&this.current.ankiFrontCol===Q&&(this.current.ankiFrontCol=void 0)),D.value==="title"?this.current.titleColumn=Q:D.value==="category"?this.current.categoryColumn=Q:D.value==="status"?this.current.statusColumn=Q:D.value==="notes"?this.current.notesColumn=Q:D.value==="image"?this.current.imageColumn=Q:D.value==="anki"&&(this.current.ankiFrontCol=Q),E()}),z&&A!==""&&j.createSpan({cls:"csv-modal-colcfg-auto-badge",text:"auto"})})};E();let S=i.createDiv({cls:"csv-modal-add-column"}),y=S.createEl("input",{cls:"csv-modal-input",type:"text",placeholder:"New column name"}),v=S.createEl("button",{cls:"csv-modal-cancel",text:"+ Add column"}),_=()=>{let D=this.onAddColumn(y.value);if(D){new It.Notice(D);return}n()};v.addEventListener("click",_),y.addEventListener("keydown",D=>{D.key==="Enter"&&(D.preventDefault(),_())});let w=e.createDiv({cls:"csv-modal-row"});w.createEl("label",{text:"Default view",cls:"csv-modal-label"});let T=w.createEl("select",{cls:"csv-modal-select"}),k=[["\u2014 use global default \u2014",""],...this.availableModes.map(D=>[D.label,D.id])],M=(R=this.current.defaultMode)!=null?R:"";M&&!this.availableModes.some(D=>D.id===M)&&k.push([`${M} (no longer available)`,M]),k.forEach(([D,W])=>{let O=T.createEl("option",{text:D,value:W});M===W&&(O.selected=!0)}),T.addEventListener("change",()=>{this.current.defaultMode=T.value?T.value:void 0});let L=t.createDiv({cls:"csv-modal-btns"});L.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),L.createEl("button",{text:"Save",cls:"csv-modal-submit"}).addEventListener("click",()=>{this.onSave(this.current),this.close()})}onClose(){this.contentEl.empty()}},un=class extends It.Modal{constructor(e,n,i,o,r){super(e);this.title=n;this.initial=i;this.placeholder=o;this.onSubmit=r}onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("csv-add-modal"),e.createEl("h2",{text:this.title,cls:"csv-modal-title"});let n=e.createEl("input",{cls:"csv-modal-field",type:"text"});n.value=this.initial,n.placeholder=this.placeholder,window.setTimeout(()=>{n.focus(),n.select()},0);let i=()=>{let r=n.value.trim();r&&(this.onSubmit(r),this.close())};n.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),i())});let o=e.createDiv({cls:"csv-modal-btns"});o.createEl("button",{text:"Cancel",cls:"csv-modal-cancel"}).addEventListener("click",()=>this.close()),o.createEl("button",{text:"Create",cls:"csv-modal-submit"}).addEventListener("click",i)}onClose(){this.contentEl.empty()}};var bi=195,Lc={AF:"Afghanistan",AL:"Albania",DZ:"Algeria",AD:"Andorra",AO:"Angola",AR:"Argentina",AM:"Armenia",AU:"Australia",AT:"Austria",AZ:"Azerbaijan",BD:"Bangladesh",BY:"Belarus",BE:"Belgium",BO:"Bolivia",BA:"Bosnia",BW:"Botswana",BR:"Brazil",BG:"Bulgaria",KH:"Cambodia",CM:"Cameroon",CA:"Canada",CL:"Chile",CN:"China",CO:"Colombia",HR:"Croatia",CU:"Cuba",CY:"Cyprus",CZ:"Czechia",DK:"Denmark",DO:"Dominican Rep.",EC:"Ecuador",EG:"Egypt",ET:"Ethiopia",FI:"Finland",FR:"France",GE:"Georgia",DE:"Germany",GH:"Ghana",GR:"Greece",GT:"Guatemala",GY:"Guyana",HT:"Haiti",HN:"Honduras",HU:"Hungary",IS:"Iceland",IN:"India",ID:"Indonesia",IR:"Iran",IQ:"Iraq",IE:"Ireland",IL:"Israel",IT:"Italy",JP:"Japan",JO:"Jordan",KZ:"Kazakhstan",KE:"Kenya",KP:"N. Korea",KR:"S. Korea",KW:"Kuwait",KG:"Kyrgyzstan",LA:"Laos",LV:"Latvia",LB:"Lebanon",LY:"Libya",LI:"Liechtenstein",LT:"Lithuania",LU:"Luxembourg",MY:"Malaysia",ML:"Mali",MT:"Malta",MR:"Mauritania",MX:"Mexico",MD:"Moldova",MN:"Mongolia",ME:"Montenegro",MA:"Morocco",MZ:"Mozambique",MM:"Myanmar",NA:"Namibia",NP:"Nepal",NL:"Netherlands",NZ:"New Zealand",NI:"Nicaragua",NE:"Niger",NG:"Nigeria",NO:"Norway",OM:"Oman",PK:"Pakistan",PA:"Panama",PG:"Papua New Guinea",PY:"Paraguay",PE:"Peru",PH:"Philippines",PL:"Poland",PT:"Portugal",QA:"Qatar",RO:"Romania",RU:"Russia",RW:"Rwanda",SA:"Saudi Arabia",SN:"Senegal",RS:"Serbia",SG:"Singapore",SK:"Slovakia",SI:"Slovenia",SO:"Somalia",ZA:"South Africa",SS:"South Sudan",ES:"Spain",LK:"Sri Lanka",SD:"Sudan",SE:"Sweden",CH:"Switzerland",SY:"Syria",TJ:"Tajikistan",TZ:"Tanzania",TH:"Thailand",TN:"Tunisia",TR:"Turkey",TM:"Turkmenistan",UG:"Uganda",UA:"Ukraine",AE:"UAE",GB:"United Kingdom",US:"United States",UY:"Uruguay",UZ:"Uzbekistan",VN:"Vietnam",YE:"Yemen",ZM:"Zambia",ZW:"Zimbabwe",MC:"Monaco",BZ:"Belize"},Ac={AF:["DZ","AO","BJ","BW","BF","BI","CM","CV","CF","TD","KM","CD","CG","CI","DJ","EG","GQ","ER","ET","GA","GM","GH","GN","GW","KE","LS","LR","LY","MG","MW","ML","MR","MU","MA","MZ","NA","NE","NG","RE","RW","ST","SN","SC","SL","SO","ZA","SS","SD","TZ","TG","TN","UG","ZM","ZW"],AN:["AQ"],AS:["AF","AM","AZ","BH","BD","BT","BN","KH","CN","CY","GE","IN","ID","IR","IQ","IL","JP","JO","KZ","KW","KG","LA","LB","MY","MV","MN","MM","NP","KP","OM","PK","PS","PH","QA","RU","SA","SG","KR","LK","SY","TW","TJ","TH","TL","TR","TM","AE","UZ","VN","YE"],EU:["AL","AD","AT","BY","BE","BA","BG","HR","CZ","DK","EE","FI","FR","DE","GR","HU","IS","IE","IT","XK","LV","LI","LT","LU","MT","MD","MC","ME","NL","MK","NO","PL","PT","RO","RU","SM","RS","SK","SI","ES","SE","CH","UA","GB","VA"],NA:["AG","BS","BB","BZ","CA","CR","CU","DM","DO","SV","GD","GT","HT","HN","JM","MX","NI","PA","KN","LC","VC","TT","US"],OC:["AU","FJ","KI","MH","FM","NR","NZ","PW","PG","WS","SB","TO","TV","VU"],SA:["AR","BO","BR","CL","CO","EC","GY","PY","PE","SR","UY","VE"]},tr={AF:"Africa",AN:"Antarctica",AS:"Asia",EU:"Europe",NA:"N. America",OC:"Oceania",SA:"S. America"},er={};for(let[s,t]of Object.entries(Ac))for(let e of t)er[e]=s;function Dt(s){return Lc[s]||s}function jt(s){return!s||s.length!==2?"":String.fromCodePoint(...s.toUpperCase().split("").map(t=>t.charCodeAt(0)+127397))}function Bt(s){if(!s||s.indexOf("?")!==-1)return null;let t=new Date(s+"T12:00:00Z");return isNaN(t.getTime())?null:t}function Ts(s){let t=Bt(s.date_entered),e=Bt(s.date_left);return!t||!e?0:Math.max(Math.round((e.getTime()-t.getTime())/864e5),1)}function sr(s,t=new Date){let e=t.getTime(),n=null,i=-1/0;for(let o of s){let r=Bt(o.date_entered);if(!(!r||r.getTime()>e)){if(o.date_left.trim()!==""){let a=Bt(o.date_left);if(!a||a.getTime()i&&(n=o,i=r.getTime())}}return n}function nr(s){let t=b=>{var x,C,E,S,y,v,_,w;return{date_entered:(x=b.date_entered)!=null?x:"",date_left:(C=b.date_left)!=null?C:"",country:((E=b.country)!=null?E:"").trim().toUpperCase(),city:(S=b.city)!=null?S:"",visa_status:(y=b.visa_status)!=null?y:"",notes:(v=b.notes)!=null?v:"",source:((_=b.source)!=null?_:"").trim().toLowerCase(),resolved:(w=b.resolved)!=null?w:"",_src:b}},e=s.map(t).filter(b=>b.country),n=e.filter(b=>b.source==="confirmed"),i=e.filter(b=>b.source==="inferred"),o=e.filter(b=>b.source==="conflict"),r=[];for(let b of n){let x=Bt(b.date_entered),C=Bt(b.date_left);x&&C&&r.push([x.getTime(),C.getTime()])}let a=b=>{let x=Bt(b.date_entered),C=Bt(b.date_left);if(!x||!C)return!1;let E=x.getTime(),S=C.getTime();return r.some(([y,v])=>E<=v&&S>=y)},l=i.filter(b=>Bt(b.date_entered)&&Bt(b.date_left)&&!a(b)),c=new Set(n.map(b=>b.country)),d=new Set(i.map(b=>b.country)),h=new Set([...d].filter(b=>!c.has(b))),u=new Set([...c,...d]),f=new Map;for(let b of n)f.set(b.country,(f.get(b.country)||0)+Ts(b));let g=[...f.entries()].map(([b,x])=>({iso:b,days:x})).sort((b,x)=>x.days-b.days||Dt(b.iso).localeCompare(Dt(x.iso))),p=g.reduce((b,x)=>b+x.days,0),m=new Set;for(let b of c){let x=er[b];x&&m.add(x)}return{confirmed:n,inferred:i,conflicts:o,inferredVisible:l,confRanges:r,confirmedCountries:c,inferredOnlyCountries:h,allCountries:u,countryDays:g,totalConfirmedDays:p,visitedContinents:m,worldPct:Math.round(c.size/bi*100)}}var vi=864e5;function ir(s){if(!s||s.indexOf("?")!==-1)return null;let t=Date.parse(s+"T00:00:00Z");return isNaN(t)?null:t}function Pc(s,t,e,n){let i=Math.max(s,e),o=Math.min(t,n);return o<=i?0:Math.round((o-i)/vi)}function Rc(s,t){var i;let e=s.window;if(e.type==="all-time")return{start:-1/0,end:1/0,label:"all time"};if(e.type==="calendar-year"){let o=new Date(t).getUTCFullYear();return{start:Date.UTC(o,0,1),end:Date.UTC(o+1,0,1),label:`in ${o}`}}let n=(i=e.days)!=null?i:180;return{start:t-n*vi,end:t+vi,label:`in last ${n} days`}}function or(s,t,e=Date.now()){var d,h,u;let n=(d=s.scope.countries)!=null?d:s.scope.country?[s.scope.country]:[],i=new Set(n.map(f=>f.toUpperCase())),o=new Set(((u=(h=s.exempt)==null?void 0:h.visa_status)!=null?u:[]).map(f=>f.toLowerCase().trim())),r=Rc(s,e),a=0;for(let f of t){if(!i.has((f.country||"").toUpperCase())||o.has((f.visa_status||"").toLowerCase().trim()))continue;let g=ir(f.date_entered),p=ir(f.date_left);g===null||p===null||(a+=Pc(g,p,r.start,r.end))}let l=s.threshold-a,c=a>=s.threshold?"over":a/s.threshold>=.8?"warn":"ok";return{rule:s,used:a,threshold:s.threshold,remaining:l,windowLabel:r.label,status:c}}var rr=["#c9a96e","#4a6fa5","#5ba06e","#a05b8a","#6ea0a0","#a0855b","#7a6ea0","#a06e6e","#6e8fa0","#a09e5b"],Oc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Fc(){let s=new Map,t=0;return e=>(s.has(e)||s.set(e,rr[t++%rr.length]),s.get(e))}function Ic(s){let t=document.body.createDiv({cls:"csv-tv-tooltip"}),e=null,n=(r,a)=>{let c=r+14,d=a+16,h=t.offsetWidth,u=t.offsetHeight;c+h+8>window.innerWidth&&(c=r-h-14),d+u+8>window.innerHeight&&(d=a-u-16),t.style.left=`${Math.max(8,c)}px`,t.style.top=`${Math.max(8,d)}px`},i=r=>{var c,d;let a=(d=(c=r.target)==null?void 0:c.closest("[data-tip]"))!=null?d:null,l=(a==null?void 0:a.getAttribute("data-tip"))||"";if(!a||!l){e&&(e=null,t.removeClass("is-on"));return}a!==e&&(e=a,t.setText(l),t.addClass("is-on")),n(r.clientX,r.clientY)},o=()=>{e=null,t.removeClass("is-on")};return s.addEventListener("pointermove",i),s.addEventListener("pointerleave",o),()=>{s.removeEventListener("pointermove",i),s.removeEventListener("pointerleave",o),t.remove()}}function yi(s){let t=Ts(s);return t?`${t}d`:"\u2014"}function es(s){return s||"\u2014"}function As(s){return s.createDiv({cls:"csv-tv-table-wrap"}).createEl("table",{cls:"csv-tv-table"})}function Ls(s,t,e,n){s.addClass("csv-tv-editable"),s.title="Click to edit";let i=()=>{s.empty(),s.setText(t[e]?t[e]:"\u2014")};i(),s.addEventListener("click",()=>{var r;if(s.querySelector("input"))return;s.empty();let o=fn(s,e,(r=t[e])!=null?r:"","csv-inline-input");o.focus(),o.type==="text"&&o.select(),o.addEventListener("blur",()=>{t[e]=o.value,n(),i()}),o.addEventListener("keydown",a=>{var l;a.key==="Enter"&&o.blur(),a.key==="Escape"&&(o.value=(l=t[e])!=null?l:"",o.blur())})})}async function ar(s,t,e,n=()=>{},i=null,o=()=>{}){let r=nr(t),a=s.createDiv({cls:"csv-tv"});if(!r.confirmed.length&&!r.inferred.length){a.createDiv({cls:"csv-empty-state",text:"No travel rows found. Expected columns: country, date_entered, date_left, source."});return}o(Ic(a));let l=null,c=()=>{a.querySelectorAll(".country-path").forEach(f=>{let g=(f.getAttribute("data-iso")||"").toUpperCase();f.classList.toggle("cp-selected",!!l&&g===l)}),a.querySelectorAll(".csv-tv-seg").forEach(f=>{f.classList.toggle("is-dim",!!l&&f.getAttribute("data-iso")!==l)}),a.querySelectorAll("tr[data-iso]").forEach(f=>{f.classList.toggle("is-selected",!!l&&f.getAttribute("data-iso")===l)}),u.empty(),l&&(Bc(u,r,l,()=>d(null)),u.scrollIntoView({behavior:"smooth",block:"nearest"}))},d=f=>{l=f&&f!==l?f:null,c()};Vc(a,r);let h=a.createDiv({cls:"csv-tv-mapwrap"});h.createDiv({cls:"csv-tv-map-loading",text:"Loading map\u2026"});let u=a.createDiv({cls:"csv-tv-detailwrap"});i&&i.length&&$c(a,r.confirmed,i),Hc(a,r,d),zc(a,r,d),Wc(a,r,n);try{let f=await e();h.empty(),f?Nc(h,f,r,d):h.createDiv({cls:"csv-tv-map-loading",text:"World map asset not found (world-map.svg)."})}catch(f){h.empty(),h.createDiv({cls:"csv-tv-map-loading",text:"Couldn't load world map."})}}function Vc(s,t){let e=s.createDiv({cls:"csv-tv-stats"}),n=(c,d,h="")=>{let u=e.createDiv({cls:"csv-tv-stat"});u.createDiv({cls:"csv-tv-stat-label",text:c}),u.createDiv({cls:"csv-tv-stat-value",text:d}),h&&u.createDiv({cls:"csv-tv-stat-sub",text:h})},i=Math.round(t.allCountries.size/bi*100);n("Countries",String(t.confirmedCountries.size),`${t.worldPct}% of world`),n("Incl. photos",String(t.allCountries.size),`${i}% of world`),n("Continents",`${t.visitedContinents.size} / 7`,[...t.visitedContinents].map(c=>tr[c]||c).sort().join(", ")),n("Confirmed trips",String(t.confirmed.length)),n("Confirmed days",String(t.totalConfirmedDays));let o=new Set(t.confirmed.map(c=>c.city.trim().toLowerCase()).filter(Boolean));o.size&&n("Cities",String(o.size));let r=null,a=0;for(let c of t.confirmed){let d=Ts(c);d>a&&(a=d,r=c)}if(r){let c=r.date_entered.slice(0,4);n("Longest trip",`${a}d`,`${jt(r.country)} ${Dt(r.country)}${c?` \xB7 ${c}`:""}`)}let l=sr(t.confirmed);if(l){let c=Bt(l.date_entered),d=Math.max(1,Math.round((Date.now()-c.getTime())/864e5)+1),h=s.createDiv({cls:"csv-tv-now"});h.createSpan({cls:"csv-tv-now-loc",text:`\u{1F4CD} Currently in ${jt(l.country)} ${Dt(l.country)}`}),h.createSpan({cls:"csv-tv-now-sub",text:` \u2014 since ${l.date_entered} (day ${d})${l.city?` \xB7 ${l.city}`:""}`})}}function Nc(s,t,e,n){let i=s.createDiv({cls:"csv-tv-map"});i.innerHTML=t,i.querySelectorAll(".country-path").forEach(r=>{let a=(r.getAttribute("data-iso")||"").toUpperCase();if(r.classList.remove("cp-unvisited","cp-confirmed","cp-inferred"),a&&e.confirmedCountries.has(a)){r.classList.add("cp-confirmed");let l=e.countryDays.find(c=>c.iso===a);r.setAttr("aria-label",`${Dt(a)} \u2014 ${l&&l.days?l.days+"d confirmed":"confirmed"}`),r.setAttr("data-tip",`${Dt(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",`${Dt(a)} \u2014 photo evidence`),r.setAttr("data-tip",`${Dt(a)} \xB7 photo evidence \xB7 click for trips`)):a?(r.classList.add("cp-unvisited"),r.setAttr("data-tip",Dt(a))):r.classList.add("cp-unvisited");a&&r.addEventListener("click",()=>{e.allCountries.has(a)?n(a):n(null)})}),i.querySelectorAll(".country-path").forEach(r=>{try{let a=r.getBoundingClientRect();a.width&&a.height&&Math.max(a.width,a.height)<12&&r.classList.add("cp-tiny")}catch(a){}});let o=s.createDiv({cls:"csv-tv-map-legend"});o.createSpan({cls:"csv-tv-leg"}).innerHTML=' Confirmed',o.createSpan({cls:"csv-tv-leg"}).innerHTML=' Photo evidence'}function Bc(s,t,e,n){var m,b;let i=s.createDiv({cls:"csv-tv-detail"}),o=i.createDiv({cls:"csv-tv-detail-head"});o.createSpan({cls:"csv-tv-detail-flag",text:jt(e)});let r=o.createDiv({cls:"csv-tv-detail-titles"});r.createDiv({cls:"csv-tv-detail-name",text:Dt(e)});let a=t.confirmed.filter(x=>x.country===e),l=t.inferred.filter(x=>x.country===e),c=(b=(m=t.countryDays.find(x=>x.iso===e))==null?void 0:m.days)!=null?b:0,d=new Set([...a,...l].map(x=>x.city.trim()).filter(Boolean)),h=[];a.length&&h.push(`${a.length} confirmed trip${a.length===1?"":"s"}`),c&&h.push(`${c}d total`),l.length&&h.push(`${l.length} photo-inferred`),d.size&&h.push(`${d.size} cit${d.size===1?"y":"ies"}`),r.createDiv({cls:"csv-tv-detail-sub",text:h.join(" \xB7 ")}),o.createEl("button",{cls:"csv-tv-detail-close",text:"\u2715",title:"Close"}).addEventListener("click",n);let u=gn([...a.map(x=>({r:x,inf:!1,date_entered:x.date_entered})),...l.map(x=>({r:x,inf:!0,date_entered:x.date_entered}))]);if(!u.length)return;let f=As(i),g=f.createEl("thead").createEl("tr");["","Entered","Left","Days","City","Visa"].forEach(x=>g.createEl("th",{text:x}));let p=f.createEl("tbody");for(let{r:x,inf:C}of u){let E=p.createEl("tr");E.createEl("td",{text:C?"\u{1F4F7}":"",cls:"csv-tv-flag",attr:C?{"data-tip":"Photo-inferred"}:{}}),E.createEl("td",{text:es(x.date_entered)}),E.createEl("td",{text:es(x.date_left)}),E.createEl("td",{text:yi(x)}),E.createEl("td",{text:x.city}),E.createEl("td",{text:x.visa_status})}}function $c(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Residency counters"});let n=s.createDiv({cls:"csv-tv-res-grid"});for(let i of e){let o=or(i,t),r=n.createDiv({cls:`csv-tv-res-card csv-tv-res-${o.status}`});r.createDiv({cls:"csv-tv-res-label",text:i.label});let a=r.createDiv({cls:"csv-tv-res-nums"});a.createSpan({cls:"csv-tv-res-used",text:String(o.used)}),a.createSpan({cls:"csv-tv-res-thresh",text:` / ${o.threshold}`}),a.createSpan({cls:"csv-tv-res-window",text:` ${o.windowLabel}`});let l=r.createDiv({cls:"csv-tv-res-bar"});l.createDiv({cls:"csv-tv-res-fill"}).style.width=`${Math.min(100,Math.round(o.used/o.threshold*100))}%`;let c=o.status==="over"?i.onExceed?`Over \u2014 ${i.onExceed}`:"Limit reached":`${o.remaining} day${o.remaining===1?"":"s"} left`;r.createDiv({cls:"csv-tv-res-status",text:c}),i.note&&r.createDiv({cls:"csv-tv-res-note",text:i.note})}s.createDiv({cls:"csv-tv-res-disclaimer",text:"Indicators only \u2014 not legal or tax advice. Based on confirmed trips."})}function Hc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Countries visited"});let n=As(s),i=n.createEl("thead").createEl("tr");["","Country","Total days"].forEach(r=>i.createEl("th",{text:r}));let o=n.createEl("tbody");for(let{iso:r,days:a}of t.countryDays){let l=o.createEl("tr",{cls:"csv-tv-row-click",attr:{"data-iso":r}});l.createEl("td",{text:jt(r),cls:"csv-tv-flag"}),l.createEl("td",{text:Dt(r)}),l.createEl("td",{text:a?`${a}d`:"\u2014"}),l.addEventListener("click",()=>e(r))}if(t.inferredOnlyCountries.size){let r=s.createDiv({cls:"csv-tv-photo-only"});r.createSpan({text:"\u{1F4F7} Photo evidence only: "}),r.createSpan({text:[...t.inferredOnlyCountries].sort().map(jt).join(" ")})}}function zc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Timeline"});let n=Fc(),i=[...t.confirmed.map(c=>({...c,_inf:!1})),...t.inferredVisible.map(c=>({...c,_inf:!0}))].filter(c=>c.date_entered&&c.date_left&&c.date_entered.indexOf("?")===-1),o=new Map;for(let c of i){let d=parseInt(c.date_entered.slice(0,4)),h=parseInt(c.date_left.slice(0,4));if(!(isNaN(d)||isNaN(h)))for(let u=d;u<=h;u++)o.has(u)||o.set(u,[]),o.get(u).push(c)}let r=[...o.keys()].sort((c,d)=>d-c),a=s.createDiv({cls:"csv-tv-timeline"});for(let c of r){let d=new Date(`${c}-01-01T12:00:00Z`).getTime(),h=new Date(`${c}-12-31T12:00:00Z`).getTime(),u=h-d,f=a.createDiv({cls:"csv-tv-tl-year"}),g=0,p=new Set;for(let C of o.get(c)){if(p.add(C.country),C._inf)continue;let E=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),d),S=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),h);E<=S&&(g+=Math.max(Math.round((S-E)/864e5)+1,1))}let m=f.createDiv({cls:"csv-tv-tl-label"});m.createSpan({text:String(c)}),m.createSpan({cls:"csv-tv-tl-sub",text:`${g?`${g}d \xB7 `:""}${p.size} ${p.size===1?"country":"countries"}`});let b=f.createDiv({cls:"csv-tv-month-row"});Oc.forEach(C=>b.createDiv({cls:"csv-tv-month-tick",text:C}));let x=f.createDiv({cls:"csv-tv-track"});for(let C of o.get(c)){let E=Math.max(new Date(C.date_entered+"T12:00:00Z").getTime(),d),S=Math.min(new Date(C.date_left+"T12:00:00Z").getTime(),h);if(E>S)continue;let y=(E-d)/u*100,v=Math.max((S-E+864e5)/u*100,.5),_=n(C.country),w=x.createDiv({cls:`csv-tv-seg${C._inf?" csv-tv-seg-inf":""}`});w.style.left=`${y}%`,w.style.width=`${v}%`,C._inf?(w.style.borderColor=_,w.style.background=_+"22",w.style.color=_):w.style.background=_,w.setAttr("data-iso",C.country),w.setAttr("data-tip",`${Dt(C.country)} ${C.date_entered} \u2192 ${C.date_left} (${Ts(C)}d)${C.visa_status?" ["+C.visa_status+"]":""}${C._inf?" [photo]":""}`),w.addEventListener("click",()=>e(C.country)),v>4?w.createSpan({cls:"csv-tv-seg-lbl",text:`${jt(C.country)} ${C.country}`}):v>2&&w.createSpan({cls:"csv-tv-seg-lbl",text:jt(C.country)})}}a.createDiv({cls:"csv-tv-tl-legend"}).setText("Confirmed (solid) \xB7 Photo inferred (outlined)")}function gn(s){return[...s].sort((t,e)=>!t.date_entered&&!e.date_entered?0:t.date_entered?e.date_entered?e.date_entered.localeCompare(t.date_entered):-1:1)}function Wc(s,t,e){s.createDiv({cls:"csv-tv-sec-title",text:"Confirmed trips"}),s.createDiv({cls:"csv-tv-edit-hint",text:"Dates, city, visa and notes are editable \u2014 click a cell. Edit country in Table view."});let n=As(s),i=n.createEl("thead").createEl("tr");["","Country","Entered","Left","Duration","City","Visa","Notes"].forEach(r=>i.createEl("th",{text:r}));let o=n.createEl("tbody");for(let r of gn(t.confirmed)){let a=o.createEl("tr");a.createEl("td",{text:jt(r.country),cls:"csv-tv-flag"}),a.createEl("td",{text:Dt(r.country)}),Ls(a.createEl("td"),r._src,"date_entered",e),Ls(a.createEl("td"),r._src,"date_left",e),a.createEl("td",{text:yi(r)}),Ls(a.createEl("td"),r._src,"city",e),Ls(a.createEl("td"),r._src,"visa_status",e),Ls(a.createEl("td"),r._src,"notes",e)}if(t.inferred.length){let r=s.createEl("details",{cls:"csv-tv-details"});r.createEl("summary",{text:`\u{1F4F7} Photo inferred trips (${t.inferred.length})`});let a=As(r),l=a.createEl("thead").createEl("tr");["","Country","Entered","Left","Days","City"].forEach(d=>l.createEl("th",{text:d}));let c=a.createEl("tbody");for(let d of gn(t.inferred)){let h=c.createEl("tr");h.createEl("td",{text:jt(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:Dt(d.country)}),h.createEl("td",{text:es(d.date_entered)}),h.createEl("td",{text:es(d.date_left)}),h.createEl("td",{text:yi(d)}),h.createEl("td",{text:d.city})}}if(t.conflicts.length){let r=s.createEl("details",{cls:"csv-tv-details csv-tv-details-warn"});r.createEl("summary",{text:`\u26A0 ${t.conflicts.length} conflict(s) \u2014 photo evidence contradicts a confirmed entry`});let a=As(r),l=a.createEl("thead").createEl("tr");["","Country (photos)","Dates","Detail"].forEach(d=>l.createEl("th",{text:d}));let c=a.createEl("tbody");for(let d of gn(t.conflicts)){let h=c.createEl("tr");h.createEl("td",{text:jt(d.country),cls:"csv-tv-flag"}),h.createEl("td",{text:d.country}),h.createEl("td",{text:`${es(d.date_entered)} \u2192 ${es(d.date_left)}`}),h.createEl("td",{text:d.notes})}}}var Vt=require("obsidian"),pn=class extends Vt.PluginSettingTab{constructor(t,e){super(t,e),this.plugin=e}display(){let{containerEl:t}=this;t.empty(),t.createEl("h2",{text:"XLSX Card View"}),new Vt.Setting(t).setName("Default view mode").addDropdown(n=>n.addOption("kanban-genre","Kanban").addOption("table","Table").setValue(this.plugin.settings.defaultMode).onChange(async i=>{this.plugin.settings.defaultMode=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Status column name").addText(n=>n.setValue(this.plugin.settings.statusColumn).onChange(async i=>{this.plugin.settings.statusColumn=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Category/Genre column name").addText(n=>n.setValue(this.plugin.settings.categoryColumn).onChange(async i=>{this.plugin.settings.categoryColumn=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Notes column names").setDesc("Comma-separated.").addText(n=>n.setValue(this.plugin.settings.notesColumns.join(", ")).onChange(async i=>{this.plugin.settings.notesColumns=i.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Select/dropdown columns").setDesc("Comma-separated column names that use a dropdown picker.").addText(n=>n.setValue(this.plugin.settings.selectColumns.join(", ")).onChange(async i=>{this.plugin.settings.selectColumns=i.split(",").map(o=>o.trim()),await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Notes subfolder").addText(n=>n.setPlaceholder("Notes").setValue(this.plugin.settings.notesSubfolder).onChange(async i=>{this.plugin.settings.notesSubfolder=i,await this.plugin.saveSettings()})),new Vt.Setting(t).setName("Reset column widths").addButton(n=>n.setButtonText("Reset").onClick(async()=>{this.plugin.settings.columnWidths={},await this.plugin.saveSettings(),new Vt.Notice("Column widths reset.")})),new Vt.Setting(t).setName("Residency counters (travel view)").setDesc("Show residency / tax day-gauges in the travel view.").addToggle(n=>n.setValue(this.plugin.settings.showResidency!==!1).onChange(async i=>{this.plugin.settings.showResidency=i,await this.plugin.saveSettings()})),t.createEl("h3",{text:"Residency rules"}),t.createEl("p",{cls:"setting-item-description",text:"Each rule counts days in the listed countries within the window, minus exempt visa rows, against the threshold. Counts confirmed trips only. Indicators, not legal/tax advice."});let e=t.createDiv({cls:"csv-rr-wrap"});this.renderResidencyRules(e)}renderResidencyRules(t){var o;t.empty();let e=(o=this.plugin.settings.residencyRules)!=null?o:this.plugin.settings.residencyRules=[],n=()=>void this.plugin.saveSettings();e.forEach((r,a)=>{var b,x,C,E,S,y;let l=t.createDiv({cls:"csv-rr-card"}),c=l.createDiv({cls:"csv-rr-head"}),d=c.createEl("input",{cls:"csv-rr-label",type:"text",value:r.label});d.placeholder="Label (e.g. \u{1F1EA}\u{1F1FA} Schengen 90/180)",d.addEventListener("input",()=>{r.label=d.value,n()});let h=c.createEl("button",{cls:"csv-rr-del",text:"\u2715"});h.setAttr("aria-label","Remove rule"),h.addEventListener("click",async()=>{e.splice(a,1),await this.plugin.saveSettings(),this.renderResidencyRules(t)});let u=l.createDiv({cls:"csv-rr-grid"}),f=(v,_,w,T="")=>{let k=u.createDiv({cls:"csv-rr-field"});k.createEl("label",{text:v});let M=k.createEl("input",{type:"text",value:_});T&&(M.placeholder=T),M.addEventListener("input",()=>{w(M.value),n()})},g=(b=r.scope.countries)!=null?b:r.scope.country?[r.scope.country]:[];f("Countries (ISO-2, comma)",g.join(", "),v=>{r.scope={countries:v.split(",").map(_=>_.trim().toUpperCase()).filter(Boolean)}},"US, GB");let p=u.createDiv({cls:"csv-rr-field"});p.createEl("label",{text:"Window"});let m=p.createEl("select");[["calendar-year","Calendar year"],["rolling","Rolling N days"],["all-time","All time"]].forEach(([v,_])=>{let w=m.createEl("option",{text:_,value:v});r.window.type===v&&(w.selected=!0)}),m.addEventListener("change",()=>{r.window={type:m.value,days:r.window.days},n(),this.renderResidencyRules(t)}),r.window.type==="rolling"&&f("Rolling days",String((x=r.window.days)!=null?x:180),v=>{let _=parseInt(v,10);r.window.days=isNaN(_)?void 0:_},"180"),f("Threshold (days)",String(r.threshold),v=>{let _=parseInt(v,10);r.threshold=isNaN(_)?0:_},"183"),f("Exempt visas (comma)",((E=(C=r.exempt)==null?void 0:C.visa_status)!=null?E:[]).join(", "),v=>{let _=v.split(",").map(w=>w.trim()).filter(Boolean);r.exempt=_.length?{visa_status:_}:void 0},"F-1, J-1"),f("On-exceed label",(S=r.onExceed)!=null?S:"",v=>{r.onExceed=v||void 0},"tax resident"),f("Note",(y=r.note)!=null?y:"",v=>{r.note=v||void 0},"optional caveat")}),t.createDiv({cls:"csv-rr-btns"}).createEl("button",{cls:"csv-rr-add",text:"+ Add rule"}).addEventListener("click",async()=>{e.push({label:"New rule",scope:{countries:[]},window:{type:"calendar-year"},threshold:183}),await this.plugin.saveSettings(),this.renderResidencyRules(t)})}};var fe=require("obsidian"),lr=an(Ds());async function cr(s,t,e,n,i={}){var O,j,$;let o=t.split(` `).map(A=>A.trim()).filter(Boolean),r="";for(let A of o)if(A.startsWith("file:")){r=A.replace("file:","").trim();break}if(!r){e.createEl("p",{text:"Error: No file specified. Use: file: yourfile.csv",cls:"csv-add-error"});return}let a=s.vault.getAbstractFileByPath(n.sourcePath),l=(j=(O=a==null?void 0:a.parent)==null?void 0:O.path)!=null?j:"",c=ue(r,l),d=s.vault.getAbstractFileByPath(c);if(!d||!(d instanceof fe.TFile)){e.createEl("p",{text:`Error: File not found: ${c}`,cls:"csv-add-error"});return}let h=($=i[c])!=null?$:{},u=[],f=[];try{let A=await s.vault.read(d),z=Nt(A);u=z.headers,f=z.rows}catch(A){e.createEl("p",{text:`Error reading file: ${A}`,cls:"csv-add-error"});return}if(!u.length){e.createEl("p",{text:"Error: No columns found in file",cls:"csv-add-error"});return}let g=A=>{let z=A.toLowerCase();if(["date","day","datum"].includes(z))return!0;let G=f.slice(0,5).map(B=>{var F;return(F=B[A])!=null?F:""});return G.length>0&&G.every(B=>/^\d{4}-\d{2}-\d{2}$/.test(B))},p=A=>{let z=A.toLowerCase();return["notes","note","comments","description","journal"].includes(z)},m=h.habitColumns?h.habitColumns.filter(A=>u.includes(A)):u.filter(A=>!g(A)&&Qe(f.map(z=>{var G;return((G=z[A])!=null?G:"").toLowerCase().trim()}))),b=u.filter(A=>g(A)),x=u.filter(A=>p(A)),C=u.filter(A=>!m.includes(A)&&!b.includes(A)&&!x.includes(A)),E=h.titleColumn?u.find(A=>A.toLowerCase()===h.titleColumn.toLowerCase()):u.find(A=>["title","name"].includes(A.toLowerCase())),S=e.createDiv({cls:"csv-add-form csv-add-compact"}),y=S.createEl("button",{cls:"csv-add-trigger",text:"+ New entry"});y.style.display="none";let v=S.createDiv({cls:"csv-add-card"}),_=v.createDiv({cls:"csv-add-card-header"});_.createEl("span",{cls:"csv-add-card-title",text:"New entry"});let w=_.createEl("button",{cls:"csv-add-card-close",text:"\xD7"}),T=v.createDiv({cls:"csv-add-rows"}),k={},M={},L=(A,z)=>{let G=T.createDiv({cls:`csv-add-row csv-add-row-${z}`});return G.createEl("span",{cls:"csv-add-row-label",text:Et(A)}),G};b.forEach(A=>{let G=L(A,"date").createEl("input",{cls:"csv-add-row-control",type:"date"});G.value=new Date().toISOString().split("T")[0],k[A]=G}),m.forEach(A=>{M[A]=!1;let G=L(A,"toggle").createEl("label",{cls:"csv-add-switch"}),B=G.createEl("input",{type:"checkbox",cls:"csv-add-switch-input"});G.createEl("span",{cls:"csv-add-switch-track"}),B.addEventListener("change",()=>{M[A]=B.checked}),k[A]=B}),C.forEach(A=>{let z=L(A,"field"),G=new Set(f.map(F=>{var N;return((N=F[A])!=null?N:"").trim()}).filter(Boolean));if(A!==E&&(h.categoricalColumns?h.categoricalColumns.includes(A):Xt(G.size))){let F=z.createEl("select",{cls:"csv-add-row-control"});F.createEl("option",{text:"\u2014",value:""}),Array.from(G).sort().forEach(V=>F.createEl("option",{text:V,value:V})),F.createEl("option",{text:"+ Custom",value:"__custom__"});let N=T.createDiv({cls:"csv-add-row csv-add-row-custom"});N.style.display="none";let H=N.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:`Custom ${Et(A).toLowerCase()}`});T.insertBefore(N,z.nextSibling),F.addEventListener("change",()=>{N.style.display=F.value==="__custom__"?"flex":"none",F.value==="__custom__"&&H.focus()}),k[A]=F,k[`${A}__custom`]=H}else k[A]=z.createEl("input",{cls:"csv-add-row-control",type:"text",placeholder:Et(A)})}),x.forEach(A=>{let z=T.createDiv({cls:"csv-add-row csv-add-row-notes"});z.createEl("span",{cls:"csv-add-row-label",text:Et(A)}),k[A]=z.createEl("textarea",{cls:"csv-add-row-textarea",placeholder:"Optional notes\u2026"})});let I=v.createEl("button",{text:"Add",cls:"csv-add-submit"}),P=_.querySelector(".csv-add-card-title"),R=()=>{if(!b.length)return;let A=k[b[0]];if(!A)return;let z=A.value,G=f.find(B=>B[b[0]]===z);P&&P.setText(G?`Updating ${z}`:"New entry"),v.classList.toggle("is-updating",!!G),I.setText(G?"Update":"Add"),m.forEach(B=>{var H;let F=k[B];if(!F)return;let N=Ze((H=G==null?void 0:G[B])!=null?H:"");F.checked=N,M[B]=N}),[...C,...x].forEach(B=>{var H,V;let F=k[B];if(!F)return;let N=(H=G==null?void 0:G[B])!=null?H:"";if(F instanceof HTMLSelectElement)if(Array.from(F.options).find(Y=>Y.value===N)){F.value=N;let Y=(V=k[`${B}__custom`])==null?void 0:V.closest(".csv-add-row-custom");Y&&(Y.style.display="none")}else F.value="";else F instanceof HTMLTextAreaElement,F.value=N})};if(R(),b.length){let A=k[b[0]];A==null||A.addEventListener("change",R)}let D=()=>{v.style.display="block",y.style.display="none";let A=v.querySelector(".csv-add-row-control");A==null||A.focus()},W=()=>{v.style.display="none",y.style.display=""};y.addEventListener("click",D),w.addEventListener("click",W),I.addEventListener("click",async()=>{let A={};u.forEach(V=>{var K,Y,q,X;m.includes(V)?A[V]=M[V]?"1":"0":k[V]instanceof HTMLSelectElement&&k[V].value==="__custom__"?A[V]=(Y=(K=k[`${V}__custom`])==null?void 0:K.value)!=null?Y:"":k[V]instanceof HTMLTextAreaElement?A[V]=k[V].value:A[V]=(X=(q=k[V])==null?void 0:q.value)!=null?X:""});let z=b.length>0&&b.some(V=>{var K;return((K=A[V])!=null?K:"").trim()}),G=[...C,...x].some(V=>{var K;return((K=A[V])!=null?K:"").trim()}),B=m.some(V=>M[V]);if(!z&&!G&&!B){new fe.Notice("Please fill at least one field");return}let F=[];try{let V=await s.vault.read(d);F=Nt(V).rows}catch(V){new fe.Notice(`Error reading file: ${V}`);return}let N=!1,H=-1;if(b.length>0){let V=b[0],K=A[V];if(H=F.findIndex(Y=>Y[V]===K),H>=0){N=!0;let Y=F[H];u.forEach(q=>{var X;(m.includes(q)||((X=A[q])!=null?X:"").trim())&&(Y[q]=A[q])})}else F.push(A)}else F.push(A);try{let V=lr.default.unparse(F,{columns:u});await s.vault.modify(d,V),new fe.Notice(N?`Updated entry for ${A[b[0]]||""}`:`Added entry to ${d.basename}`),f.length=0,f.push(...F),b.length>0?R():(m.forEach(K=>{M[K]=!1;let Y=k[K];Y&&(Y.checked=!1)}),[...C,...x].forEach(K=>{let Y=k[K];Y instanceof HTMLSelectElement?Y.selectedIndex=0:(Y instanceof HTMLTextAreaElement||Y)&&(Y.value="");let q=k[`${K}__custom`];if(q){q.value="";let X=q.closest(".csv-add-row-custom");X&&(X.style.display="none")}})),setTimeout(async()=>{let K=s.vault.getAbstractFileByPath(n.sourcePath);if(K instanceof fe.TFile){let Y=s.workspace.activeLeaf;Y&&await Y.openFile(K,{state:{mode:"preview"}})}},300)}catch(V){new fe.Notice(`Error saving: ${V}`)}})}function mn(s,t){let e=s.getFilteredRows();s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${e.length} of ${s.rows.length} entries`});let i=t.createDiv({cls:"csv-table-wrapper"}).createEl("table",{cls:"csv-table"}),o=i.createEl("thead").createEl("tr");s.headers.forEach(l=>{let c=o.createEl("th");c.setText(l),c.addClass("csv-th-sortable"),s.tableSortCol===l&&c.createSpan({cls:"csv-th-sort-indicator",text:s.tableSortDir==="asc"?" \u25B2":" \u25BC"}),c.title="Click to sort",c.addEventListener("click",g=>{g.target.closest(".csv-col-resize-handle")||(s.tableSortCol!==l?(s.tableSortCol=l,s.tableSortDir="asc"):s.tableSortDir==="asc"?s.tableSortDir="desc":s.tableSortCol=null,s.renderView())});let d=s.settings.columnWidths[l];d&&(c.style.width=d+"px");let h=c.createDiv({cls:"csv-col-resize-handle"}),u=0,f=0;h.addEventListener("pointerdown",g=>{g.preventDefault(),g.stopPropagation(),h.setPointerCapture(g.pointerId),u=g.clientX,f=c.offsetWidth;let p=b=>{c.style.width=Math.max(60,f+b.clientX-u)+"px"},m=b=>{s.settings.columnWidths[l]=Math.max(60,f+b.clientX-u),h.removeEventListener("pointermove",p),h.removeEventListener("pointerup",m),s.persistSettings()};h.addEventListener("pointermove",p),h.addEventListener("pointerup",m)})}),o.createEl("th",{text:""});let r=matchMedia("(pointer: coarse)").matches,a=i.createEl("tbody");e.forEach(l=>{let c=a.createEl("tr");c.addEventListener("contextmenu",u=>s.openRowContextMenu(l,u)),s.headers.forEach(u=>{var g,p;let f=c.createEl("td");if(s.isNotesCol(u)){f.addClass("csv-table-notes-cell");let m=((g=l[u])!=null?g:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").split(` -`).filter(C=>C.trim()).slice(0,3).join(" \xB7 "),b=m?m.slice(0,200)+(m.length>200?"\u2026":""):"+ Add note",x=f.createSpan({text:b});m||x.addClass("csv-table-notes-empty"),f.title="Click to open note",f.addEventListener("click",C=>{C.stopPropagation(),s.openNoteExpander(l,u)})}else if(s.isSelectCol(u))s.renderSelectField(f,l,u);else{let m=(p=l[u])!=null?p:"";f.setText(m),m.length>80&&(f.title=m),Ps(s,f,l,u)}});let d=c.createEl("td",{cls:"csv-table-action"}),h=s.notesFileExists(l);d.createEl("button",{cls:`csv-table-notes-btn ${h?"exists":""}`,text:h?"\u{1F4C4}":"\u271A",title:h?"Open notes":"Create notes"}).addEventListener("click",()=>s.openOrCreateNotes(l)),d.createEl("button",{cls:"csv-table-del-btn",text:"\u2715",title:"Delete row (Undo available)"}).addEventListener("click",()=>s.deleteWithUndo(l))}),r||requestAnimationFrame(()=>{a.querySelectorAll("td:not(.csv-table-notes-cell):not(.csv-table-action)").forEach(l=>{l.scrollHeight>l.clientHeight+1&&l.addClass("csv-cell--clipped")})})}function Ps(s,t,e,n){t.addEventListener("click",i=>{var d,h;if(t.querySelector("input"))return;t.empty();let o=(d=s.fileCfg.dateColumns)==null?void 0:d.includes(n),r=((h=e[n])!=null?h:"").trim(),a=o||kt(n)&&(r===""||dn.test(r)),l=a?r.slice(0,10):r,c=t.createEl("input",{cls:"csv-inline-input",value:l,type:a?"date":"text"});c.focus(),a||c.select(),c.addEventListener("click",u=>u.stopPropagation()),c.addEventListener("blur",()=>{e[n]=c.value,s.scheduleSave(),t.empty(),t.setText(c.value||"\u2014")}),c.addEventListener("keydown",u=>{u.key==="Enter"&&c.blur(),u.key==="Escape"&&(t.empty(),t.setText(e[n]||"\u2014"))})})}function bn(s){return!!(s.getCategoryCol()||s.getStatusCol()||dr(s)||s.authorKey())}function dr(s){return s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"])}function Fs(s){var i;let t=(s!=null?s:"").trim();if(!t)return null;let e=((i=t.match(/★/g))!=null?i:[]).length;if(e>0)return e;let n=parseFloat(t);return isNaN(n)||n<=0?null:Math.min(5,n)}var hr=["watched","read","finished","completed","done","yes","seen"],ur=["watching","reading","in progress","in-progress"],jc=["dropped","abandoned","dnf"];function Uc(s){let t=s.toLowerCase();return hr.includes(t)?"is-done":ur.includes(t)?"is-progress":jc.includes(t)?"is-dropped":""}function Rs(s,t){let e=new Map;return s.forEach(n=>t(n).forEach(i=>{var o;return e.set(i,((o=e.get(i))!=null?o:0)+1)})),e}function Os(s,t,e,n){if(!e.length)return;let i=s.createDiv({cls:"csv-stats-section"});i.createDiv({cls:"csv-stats-section-title",text:t});let o=Math.max(...e.map(r=>r.count));e.forEach(r=>{var h;let a=i.createDiv({cls:"csv-stats-bar-row"});a.createDiv({cls:"csv-stats-bar-label",text:r.label,attr:{title:r.label}});let c=a.createDiv({cls:"csv-stats-bar-track"}).createDiv({cls:`csv-stats-bar-fill ${(h=r.cls)!=null?h:""}`});c.style.width=`${Math.max(2,Math.round(r.count/o*100))}%`;let d=n>0?Math.round(r.count/n*100):0;a.createDiv({cls:"csv-stats-bar-count",text:`${r.count} \xB7 ${d}%`}),r.onClick&&(a.addClass("is-clickable"),a.title=`Show "${r.label}" in the library`,a.addEventListener("click",r.onClick))})}function fr(s,t){let e=s.getFilteredRows();if(s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Stats over ${e.length} of ${s.rows.length} entries`}),!e.length){t.createEl("p",{text:"No entries to chart.",cls:"csv-empty-state"});return}let n=t.createDiv({cls:"csv-stats-wrap"}),i=s.getStatusCol(),o=s.getCategoryCol(),r=dr(s),a=s.authorKey(),l=s.resolveCol(["Year","year"]),c=n.createDiv({cls:"csv-stats-overview"}),d=(u,f)=>{let g=c.createDiv({cls:"csv-stats-chip"});g.createDiv({cls:"csv-stats-chip-value",text:u}),g.createDiv({cls:"csv-stats-chip-label",text:f})};if(d(String(e.length),"entries"),i){let u=e.filter(g=>{var p;return hr.includes(((p=g[i])!=null?p:"").toLowerCase().trim())}).length;u>0&&d(`${u} \xB7 ${Math.round(u/e.length*100)}%`,"done");let f=e.filter(g=>{var p;return ur.includes(((p=g[i])!=null?p:"").toLowerCase().trim())}).length;f>0&&d(String(f),"in progress")}if(o){let u=Rs(e,f=>{var g;return((g=f[o])!=null?g:"").split(",").map(p=>p.trim()).filter(Boolean)});u.size>0&&d(String(u.size),o.toLowerCase()==="genre"||o.toLowerCase()==="genres"?"genres":"categories")}if(r){let u=e.map(f=>Fs(f[r])).filter(f=>f!==null);if(u.length){let f=u.reduce((g,p)=>g+p,0)/u.length;d(`\u2605 ${f.toFixed(1)}`,`avg of ${u.length} rated`)}}let h=(u,f)=>{s.libraryStatusFilter=u!=null?u:"all",s.libraryGenreFilter=f!=null?f:"all",s.mode="library",s.renderView()};if(i){let u=Rs(e,g=>{var m;let p=((m=g[i])!=null?m:"").trim();return p?[p]:[]}),f=Array.from(u.entries()).sort((g,p)=>p[1]-g[1]).map(([g,p])=>({label:g,count:p,cls:Uc(g),onClick:o?()=>h(g,null):void 0}));Os(n,`By ${i.toLowerCase()}`,f,e.length)}if(o){let u=Rs(e,g=>{var p;return((p=g[o])!=null?p:"").split(",").map(m=>m.trim()).filter(Boolean)}),f=Array.from(u.entries()).sort((g,p)=>p[1]-g[1]||g[0].localeCompare(p[0])).slice(0,12).map(([g,p])=>({label:g,count:p,onClick:()=>h(null,g)}));Os(n,`By ${o.toLowerCase()}`,f,e.length)}if(r){let u=new Map,f=0;if(e.forEach(g=>{var b;let p=Fs(g[r]);if(p===null)return;let m=Math.min(5,Math.max(1,Math.round(p)));u.set(m,((b=u.get(m))!=null?b:0)+1),f++}),f>0){let g=[5,4,3,2,1].filter(p=>{var m;return((m=u.get(p))!=null?m:0)>0}).map(p=>({label:"\u2605".repeat(p),count:u.get(p),cls:"is-rating"}));Os(n,"Ratings",g,f)}}if(l){let u=Rs(e,f=>{var p;let g=((p=f[l])!=null?p:"").match(/\d{4}/);return g?[g[0]]:[]});if(u.size>1){let f=Array.from(u.entries()).sort((g,p)=>g[0].localeCompare(p[0])).map(([g,p])=>({label:g,count:p}));Os(n,"By year",f,e.length)}}if(a){let u=Rs(e,g=>{var m;let p=((m=g[a])!=null?m:"").trim();return p?[p]:[]}),f=Array.from(u.entries()).filter(([,g])=>g>1);if(f.length>=2){let g=f.sort((p,m)=>m[1]-p[1]||p[0].localeCompare(m[0])).slice(0,8).map(([p,m])=>({label:p,count:m}));Os(n,`Top ${a.toLowerCase()}s`,g,e.length)}}}function $t(s){let t=s.fileCfg.kanbanGroupCol;if(t&&s.headers.includes(t))return t;let e=s.getCategoryCol();if(e)return e;let n=new Set;s.headers.forEach(r=>{s.isNotesCol(r)&&n.add(r)});let i=s.getDateCol();i&&n.add(i);let o=s.titleKey();return o&&n.add(o),Qo(s.headers,s.rows,n)}function vn(s,t){let e=$t(s);if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let n=s.getCategoryCol(),i=s.getStatusCol(),o=i===e?null:i,r=s.getFilteredRows();s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${r.length} of ${s.rows.length} entries`});let a=t.createDiv({cls:"csv-kanban-groupbar"});a.createSpan({cls:"csv-kanban-groupbar-label",text:"Group by"});let l=a.createEl("select",{cls:"csv-library-filter-select"});s.headers.filter(m=>!s.isNotesCol(m)).forEach(m=>{let b=l.createEl("option",{text:m===n?`${m} (default)`:m,value:m});m===e&&(b.selected=!0)}),l.addEventListener("change",()=>{let m=s.fileCfg;m.kanbanGroupCol=l.value===n?void 0:l.value,s.saveFileCfg(m),s.renderView(!0)});let c=qo(e,r.map(m=>{var b;return(b=m[e])!=null?b:""})),d=m=>{var C;let b=(C=m[e])!=null?C:"",x;if(c){let E=Xo(b);x=E?[E]:[]}else x=b.split(",").map(E=>E.trim()).filter(Boolean);return x.length||(x=["\u2014"]),x},h=new Set;r.forEach(m=>d(m).forEach(b=>h.add(b)));let u=Array.from(h).sort();if(!u.length){let m=t.createDiv({cls:"csv-empty-state"});m.createEl("p",{text:s.searchQuery?"No matching entries found.":`No "${e}" values found.`}),s.searchQuery&&m.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear search"}).addEventListener("click",()=>{s.searchQuery="",s.renderView()});return}let f=["In progress","Finished","Not started"],g=o?Array.from(new Set([...f,...r.map(m=>{var b;return(b=m[o])!=null?b:""}).filter(Boolean)])).filter(m=>r.some(b=>{var x;return((x=b[o])!=null?x:"")==m})):[],p=t.createDiv({cls:"csv-kanban-board"});u.forEach(m=>{let b=r.filter(S=>d(S).includes(m));if(!b.length)return;let x=p.createDiv({cls:"csv-kanban-col"}),C=x.createDiv({cls:"csv-kanban-col-header"});C.createDiv({cls:"csv-kanban-col-title",text:m}),C.createDiv({cls:"csv-kanban-col-count",text:String(b.length)});let E=x.createDiv({cls:"csv-kanban-col-body"});if(o&&g.length){g.forEach(v=>{let _=b.filter(T=>{var k;return((k=T[o])!=null?k:"")===v});if(!_.length)return;let w=E.createDiv({cls:"csv-kanban-status-group"});w.createDiv({cls:`csv-kanban-status-label status-${v.toLowerCase().replace(/\s+/g,"-")}`,text:v}),_.forEach(T=>xi(s,w,T,o,e))});let S=new Set(g),y=b.filter(v=>{var _;return!S.has((_=v[o])!=null?_:"")});if(y.length){let v=E.createDiv({cls:"csv-kanban-status-group"});v.createDiv({cls:"csv-kanban-status-label",text:"\u2014"}),y.forEach(_=>xi(s,v,_,o,e))}}else b.forEach(S=>xi(s,E,S,o,e))})}function xi(s,t,e,n,i){var _,w,T,k,M,L,I,P;let o=t.createDiv({cls:"csv-kanban-card"}),r=s.getNotesCol(),a=(w=(_=s.getImageCol)==null?void 0:_.call(s))!=null?w:null;if(a){let R=cn(s.app,(T=e[a])!=null?T:"",(M=(k=s.file)==null?void 0:k.path)!=null?M:"");if(R){let D=o.createEl("img",{cls:"csv-kanban-card-img",attr:{src:R,loading:"lazy",alt:""}});D.addEventListener("error",()=>D.remove())}}let l=o.createDiv({cls:"csv-kanban-card-title-row"});l.createDiv({cls:`csv-kanban-card-title ${(L=s.isHighlighted)!=null&&L.call(s,e)?"csv-title-highlight":""}`,text:s.getTitle(e)}).addEventListener("click",R=>{R.stopPropagation(),s.openNoteExpander(e,r!=null?r:"")});let d=s.notesFileExists(e);l.createEl("button",{cls:`csv-kanban-notes-icon ${d?"exists":""}`,text:d?"\u{1F4C4}":"+",title:d?"Open notes file":"Create notes file"}).addEventListener("click",R=>{R.stopPropagation(),s.openOrCreateNotes(e)});let u=s.getSubtitle(e);u&&o.createDiv({cls:"csv-kanban-card-sub",text:u});let f=s.titleKey(),g=s.authorKey(),p=new Set([n,f,g,i].filter(Boolean)),m=o.createDiv({cls:"csv-kanban-card-meta"});((I=s.fileCfg.cardFields)!=null?I:s.headers).forEach(R=>{if(!s.headers.includes(R)||p.has(R)||s.isNotesCol(R))return;let D=m.createDiv({cls:"csv-kanban-chip"});if(D.createSpan({cls:"csv-chip-label",text:R+": "}),s.isSelectCol(R)){let W=D.createSpan({cls:`csv-chip-value csv-chip-select${e[R]?"":" csv-chip-value--empty"}`,text:e[R]||"\u2014"});W.addEventListener("click",O=>{O.stopPropagation(),Ft(W,e[R],s.getColumnValues(R),j=>{e[R]=j,W.setText(j||"\u2014"),W.classList.toggle("csv-chip-value--empty",!j),s.scheduleSave()},s.contentEl,{multi:wt(R)})})}else{let W=e[R]?e[R].length>40?e[R].slice(0,38)+"\u2026":e[R]:"\u2014",O=D.createSpan({cls:`csv-chip-value${e[R]?"":" csv-chip-value--empty"}`,text:W});e[R]&&e[R].length>40&&(O.title=e[R])}});let x=s.getNotesCol(),C=!!(x&&((P=e[x])!=null&&P.trim())),E=o.createDiv({cls:"csv-kanban-notes-preview"});if(C&&x){let R=e[x].replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();E.setText(R.slice(0,120)+(R.length>120?"\u2026":"")),E.title="Click to edit"}else E.addClass("csv-kanban-notes-preview--empty"),x&&E.setText("+ Add note");let S=o.createDiv({cls:"csv-kanban-notes-editor"});S.style.display="none";let y=()=>{var j,$,A;let R=s.contentEl.querySelector(".csv-content-area"),D=(j=R==null?void 0:R.scrollLeft)!=null?j:0,W=($=R==null?void 0:R.scrollTop)!=null?$:0;E.style.display="none",S.style.display="block",S.empty();let O=S.createEl("textarea",{cls:"csv-notes-textarea"});O.value=(A=x?e[x]:"")!=null?A:"",O.addEventListener("click",z=>z.stopPropagation()),O.addEventListener("mousedown",z=>z.stopPropagation()),O.addEventListener("input",()=>{O.style.height="auto",O.style.height=O.scrollHeight+"px"}),O.addEventListener("keydown",z=>{z.key==="Escape"&&v(O.value,R,D,W)}),O.addEventListener("blur",()=>v(O.value,R,D,W)),O.focus({preventScroll:!0}),O.setSelectionRange(0,0),O.scrollTop=0,requestAnimationFrame(()=>{O.style.height="auto",O.style.height=Math.max(120,O.scrollHeight)+"px"})},v=(R,D,W,O)=>{if(x&&(e[x]=R,s.scheduleSave()),S.style.display="none",E.style.display="",R.trim()){let j=R.replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();E.setText(j.slice(0,120)+(j.length>120?"\u2026":"")),E.removeClass("csv-kanban-notes-preview--empty"),E.title="Click to edit"}else E.addClass("csv-kanban-notes-preview--empty"),E.setText(x?"+ Add note":""),E.removeAttribute("title");D&&(D.scrollLeft=W,D.scrollTop=O,requestAnimationFrame(()=>{D.scrollLeft=W,D.scrollTop=O,requestAnimationFrame(()=>{D.scrollLeft=W,D.scrollTop=O})}),setTimeout(()=>{D.scrollLeft=W,D.scrollTop=O},50))};E.addEventListener("click",R=>{if(R.stopPropagation(),x&&matchMedia("(pointer: coarse)").matches){s.openNoteExpander(e,x);return}y()}),o.addEventListener("contextmenu",R=>s.openRowContextMenu(e,R))}function yn(s,t){var w,T;let e=$t(s),n=s.getStatusCol(),i=(w=s.titleKey())!=null?w:s.headers[0],o=s.authorKey();if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let r=new Set;s.rows.forEach(k=>{var L;((L=k[e])!=null?L:"").split(",").map(I=>I.trim()).filter(Boolean).forEach(I=>r.add(I))});let a=new Set;n&&s.rows.forEach(k=>{var L;let M=((L=k[n])!=null?L:"").trim();M&&a.add(M)});let l=t.createDiv({cls:"csv-library-filters"}),c=l.createEl("select",{cls:"csv-library-filter-select"});c.createEl("option",{text:"All",value:"all"});let d=["watched","read","finished","completed","done","yes","seen"],h=["watching","reading","in progress","in-progress"],u=Array.from(a).some(k=>d.includes(k.toLowerCase())),f=Array.from(a).some(k=>h.includes(k.toLowerCase()));(u||f)&&(c.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),u&&c.createEl("option",{text:"\u2713 Done",value:"__done__"}),f&&c.createEl("option",{text:"\u25D0 In Progress",value:"__inprogress__"}),c.createEl("option",{text:"\u25CB Not Started",value:"__notstarted__"})),a.size>0&&(c.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),Array.from(a).sort().forEach(k=>{c.createEl("option",{text:k,value:k})})),c.value=s.libraryStatusFilter;let g=l.createEl("select",{cls:"csv-library-filter-select"});g.createEl("option",{text:"All genres",value:"all"}),Array.from(r).sort().forEach(k=>{g.createEl("option",{text:k,value:k})}),g.value=s.libraryGenreFilter;let p=s.resolveCol(["Year","year","Date","date"]),m=s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"]),b=s.resolveCol(["Theme","theme","Tags","tags","Tag","tag","Mood","mood"]),x=(T=s.fileCfg.librarySort)!=null?T:"status",C=l.createEl("select",{cls:"csv-library-filter-select"}),E=[["status","Sort: Status"],["title","Sort: Title"]];m&&E.push(["rating","Sort: Rating"]),p&&E.push(["year","Sort: Year"]),E.forEach(([k,M])=>{let L=C.createEl("option",{text:M,value:k});k===x&&(L.selected=!0)}),C.addEventListener("change",()=>{let k=s.fileCfg;k.librarySort=C.value==="status"?void 0:C.value,s.saveFileCfg(k),s.renderView(!0)});let S=()=>{s.libraryStatusFilter=c.value,s.libraryGenreFilter=g.value,s.renderView(!0)};c.addEventListener("change",S),g.addEventListener("change",S);let y=s.rows.filter(k=>{var M,L;if(s.libraryStatusFilter!=="all"&&n){let I=((M=k[n])!=null?M:"").toLowerCase();if(s.libraryStatusFilter==="__done__"){if(!d.includes(I))return!1}else if(s.libraryStatusFilter==="__inprogress__"){if(!h.includes(I))return!1}else if(s.libraryStatusFilter==="__notstarted__"){if(d.includes(I)||h.includes(I))return!1}else if(I!==s.libraryStatusFilter.toLowerCase())return!1}if(s.libraryGenreFilter!=="all"&&!((L=k[e])!=null?L:"").split(",").map(P=>P.trim().toLowerCase()).includes(s.libraryGenreFilter.toLowerCase()))return!1;if(s.searchQuery.trim()){let I=s.searchQuery.toLowerCase().trim();if(!s.headers.some(P=>{var R;return((R=k[P])!=null?R:"").toLowerCase().includes(I)}))return!1}return!0});(s.libraryStatusFilter!=="all"||s.libraryGenreFilter!=="all"||s.searchQuery.trim())&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${y.length} of ${s.rows.length} entries`});let v={};y.forEach(k=>{var L;let M=s.libraryGenreFilter!=="all"?[s.libraryGenreFilter]:((L=k[e])!=null?L:"Uncategorized").split(",").map(I=>I.trim()).filter(Boolean);M.length===0&&M.push("Uncategorized"),M.forEach(I=>{v[I]||(v[I]=[]),v[I].push(k)})});let _=t.createDiv({cls:"csv-library-sections"});if(Object.keys(v).sort().forEach(k=>{var A,z,G,B,F;let M=v[k],L=_.createEl("details",{cls:"csv-library-section"}),I=k.toLowerCase(),P=((A=s.fileCfg.collapsedGroups)!=null?A:[]).map(N=>N.toLowerCase());L.open=!((z=s.collapsedGroups)!=null&&z.has(I)||P.includes(I)),L.addEventListener("toggle",()=>{var Y;let N=s.fileCfg,H=((Y=N.collapsedGroups)!=null?Y:[]).map(q=>q.toLowerCase()),V=new Set(H);L.open?V.delete(I):V.add(I);let K=Array.from(V);K.length===H.length&&K.every(q=>H.includes(q))||(N.collapsedGroups=K,s.saveFileCfg(N))});let R=L.createEl("summary",{cls:"csv-library-section-header"});R.innerHTML=`\u25B6 ${k} ${M.length}`;let D=L.createDiv({cls:"csv-library-grid"}),W=(N,H)=>{var V,K;return((V=N[i])!=null?V:"").localeCompare((K=H[i])!=null?K:"")},O=(N,H)=>N===null&&H===null?0:N===null?1:H===null?-1:H-N;M.sort((N,H)=>{var V,K,Y,q;if(x==="title")return W(N,H);if(x==="rating"&&m)return O(Fs((V=N[m])!=null?V:""),Fs((K=H[m])!=null?K:""))||W(N,H);if(x==="year"&&p){let X=Z=>{var Q;let at=((Q=Z[p])!=null?Q:"").match(/\d{4}/);return at?parseInt(at[0],10):null};return O(X(N),X(H))||W(N,H)}if(n){let X=((Y=N[n])!=null?Y:"").toLowerCase(),Z=((q=H[n])!=null?q:"").toLowerCase(),at=d.includes(X),Q=d.includes(Z);if(at!==Q)return at?-1:1;let st=h.includes(X),lt=h.includes(Z);if(st!==lt)return st?-1:1}return W(N,H)});let j=(G=s.fileCfg.cardFields)!=null?G:s.headers,$=(F=(B=s.getImageCol)==null?void 0:B.call(s))!=null?F:null;M.forEach(N=>{var q,X,Z,at,Q,st,lt,Wt;let H=D.createDiv({cls:"csv-library-card"});if($){let ot=cn(s.app,(q=N[$])!=null?q:"",(Z=(X=s.file)==null?void 0:X.path)!=null?Z:"");if(ot){let pt=H.createEl("img",{cls:"csv-library-card-img",attr:{src:ot,loading:"lazy",alt:""}});pt.addEventListener("error",()=>pt.remove())}}let V=H.createDiv({cls:`csv-library-card-title ${(at=s.isHighlighted)!=null&&at.call(s,N)?"csv-title-highlight":""}`});if(n){let ot=((Q=N[n])!=null?Q:"").toLowerCase();d.includes(ot)&&V.createSpan({cls:"csv-library-done-dot"})}V.createSpan({text:(st=N[i])!=null?st:"Untitled"});let K=[],Y=[];for(let ot of j){if(!ot)continue;let pt=String((lt=N[ot])!=null?lt:"").trim();if(pt)if(ot===m){let ft=Go(pt,ot);ft&&H.createDiv({cls:"csv-library-card-rating",text:ft})}else if(ot===b)Y.push(...pt.split(",").map(ft=>ft.trim()).filter(Boolean));else if(ot===p){let ft=pt.match(/\d{4}/);K.push(ft?ft[0]:pt)}else K.push(pt)}if(K.length&&H.createDiv({cls:"csv-library-card-meta",text:K.join(" \xB7 ")}),s.libraryGenreFilter!=="all"){let ot=((Wt=N[e])!=null?Wt:"").split(",").map(pt=>pt.trim()).filter(pt=>pt&&pt.toLowerCase()!==s.libraryGenreFilter.toLowerCase());Y.push(...ot)}if(Y.length){let ot=H.createDiv({cls:"csv-library-card-tags"});Y.slice(0,3).forEach(pt=>{ot.createSpan({cls:"csv-library-card-tag",text:pt})})}H.addEventListener("click",()=>{var ot;s.openNoteExpander(N,(ot=s.getNotesCol())!=null?ot:"")}),H.addEventListener("contextmenu",ot=>s.openRowContextMenu(N,ot))})}),Object.keys(v).length===0){let k=_.createDiv({cls:"csv-empty-state"});k.createEl("p",{text:"No entries match your filters."}),k.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.libraryStatusFilter="all",s.libraryGenreFilter="all",s.searchQuery="",s.renderView()})}}var di=require("obsidian");var Le=require("obsidian");var Ci=`--- +`).filter(C=>C.trim()).slice(0,3).join(" \xB7 "),b=m?m.slice(0,200)+(m.length>200?"\u2026":""):"+ Add note",x=f.createSpan({text:b});m||x.addClass("csv-table-notes-empty"),f.title="Click to open note",f.addEventListener("click",C=>{C.stopPropagation(),s.openNoteExpander(l,u)})}else if(s.isSelectCol(u))s.renderSelectField(f,l,u);else{let m=(p=l[u])!=null?p:"";f.setText(m),m.length>80&&(f.title=m),Ps(s,f,l,u)}});let d=c.createEl("td",{cls:"csv-table-action"}),h=s.notesFileExists(l);d.createEl("button",{cls:`csv-table-notes-btn ${h?"exists":""}`,text:h?"\u{1F4C4}":"\u271A",title:h?"Open notes":"Create notes"}).addEventListener("click",()=>s.openOrCreateNotes(l)),d.createEl("button",{cls:"csv-table-del-btn",text:"\u2715",title:"Delete row (Undo available)"}).addEventListener("click",()=>s.deleteWithUndo(l))}),r||requestAnimationFrame(()=>{a.querySelectorAll("td:not(.csv-table-notes-cell):not(.csv-table-action)").forEach(l=>{l.scrollHeight>l.clientHeight+1&&l.addClass("csv-cell--clipped")})})}function Ps(s,t,e,n){t.addEventListener("click",i=>{var h,u;if(t.querySelector("input"))return;t.empty();let o=(h=s.fileCfg.dateColumns)==null?void 0:h.includes(n),r=((u=e[n])!=null?u:"").trim(),a=o||kt(n)&&(r===""||dn.test(r)),l=a?r.slice(0,10):r,c=t.createEl("input",{cls:"csv-inline-input",value:l,type:a?"date":"text"});c.focus(),a||c.select(),c.addEventListener("click",f=>f.stopPropagation());let d=!1;c.addEventListener("blur",()=>{var f;!d&&c.value!==l&&(e[n]=c.value,s.scheduleSave()),t.empty(),t.setText(((f=e[n])!=null?f:"")||"\u2014")}),c.addEventListener("keydown",f=>{f.key==="Enter"&&c.blur(),f.key==="Escape"&&(d=!0,c.blur())})})}function bn(s){return!!(s.getCategoryCol()||s.getStatusCol()||dr(s)||s.authorKey())}function dr(s){return s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"])}function Fs(s){var i;let t=(s!=null?s:"").trim();if(!t)return null;let e=((i=t.match(/★/g))!=null?i:[]).length;if(e>0)return e;let n=parseFloat(t);return isNaN(n)||n<=0?null:Math.min(5,n)}var hr=["watched","read","finished","completed","done","yes","seen"],ur=["watching","reading","in progress","in-progress"],jc=["dropped","abandoned","dnf"];function Uc(s){let t=s.toLowerCase();return hr.includes(t)?"is-done":ur.includes(t)?"is-progress":jc.includes(t)?"is-dropped":""}function Rs(s,t){let e=new Map;return s.forEach(n=>t(n).forEach(i=>{var o;return e.set(i,((o=e.get(i))!=null?o:0)+1)})),e}function Os(s,t,e,n){if(!e.length)return;let i=s.createDiv({cls:"csv-stats-section"});i.createDiv({cls:"csv-stats-section-title",text:t});let o=Math.max(...e.map(r=>r.count));e.forEach(r=>{var h;let a=i.createDiv({cls:"csv-stats-bar-row"});a.createDiv({cls:"csv-stats-bar-label",text:r.label,attr:{title:r.label}});let c=a.createDiv({cls:"csv-stats-bar-track"}).createDiv({cls:`csv-stats-bar-fill ${(h=r.cls)!=null?h:""}`});c.style.width=`${Math.max(2,Math.round(r.count/o*100))}%`;let d=n>0?Math.round(r.count/n*100):0;a.createDiv({cls:"csv-stats-bar-count",text:`${r.count} \xB7 ${d}%`}),r.onClick&&(a.addClass("is-clickable"),a.title=`Show "${r.label}" in the library`,a.addEventListener("click",r.onClick))})}function fr(s,t){let e=s.getFilteredRows();if(s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Stats over ${e.length} of ${s.rows.length} entries`}),!e.length){t.createEl("p",{text:"No entries to chart.",cls:"csv-empty-state"});return}let n=t.createDiv({cls:"csv-stats-wrap"}),i=s.getStatusCol(),o=s.getCategoryCol(),r=dr(s),a=s.authorKey(),l=s.resolveCol(["Year","year"]),c=n.createDiv({cls:"csv-stats-overview"}),d=(u,f)=>{let g=c.createDiv({cls:"csv-stats-chip"});g.createDiv({cls:"csv-stats-chip-value",text:u}),g.createDiv({cls:"csv-stats-chip-label",text:f})};if(d(String(e.length),"entries"),i){let u=e.filter(g=>{var p;return hr.includes(((p=g[i])!=null?p:"").toLowerCase().trim())}).length;u>0&&d(`${u} \xB7 ${Math.round(u/e.length*100)}%`,"done");let f=e.filter(g=>{var p;return ur.includes(((p=g[i])!=null?p:"").toLowerCase().trim())}).length;f>0&&d(String(f),"in progress")}if(o){let u=Rs(e,f=>{var g;return((g=f[o])!=null?g:"").split(",").map(p=>p.trim()).filter(Boolean)});u.size>0&&d(String(u.size),o.toLowerCase()==="genre"||o.toLowerCase()==="genres"?"genres":"categories")}if(r){let u=e.map(f=>Fs(f[r])).filter(f=>f!==null);if(u.length){let f=u.reduce((g,p)=>g+p,0)/u.length;d(`\u2605 ${f.toFixed(1)}`,`avg of ${u.length} rated`)}}let h=(u,f)=>{s.libraryStatusFilter=u!=null?u:"all",s.libraryGenreFilter=f!=null?f:"all",s.mode="library",s.renderView()};if(i){let u=Rs(e,g=>{var m;let p=((m=g[i])!=null?m:"").trim();return p?[p]:[]}),f=Array.from(u.entries()).sort((g,p)=>p[1]-g[1]).map(([g,p])=>({label:g,count:p,cls:Uc(g),onClick:o?()=>h(g,null):void 0}));Os(n,`By ${i.toLowerCase()}`,f,e.length)}if(o){let u=Rs(e,g=>{var p;return((p=g[o])!=null?p:"").split(",").map(m=>m.trim()).filter(Boolean)}),f=Array.from(u.entries()).sort((g,p)=>p[1]-g[1]||g[0].localeCompare(p[0])).slice(0,12).map(([g,p])=>({label:g,count:p,onClick:()=>h(null,g)}));Os(n,`By ${o.toLowerCase()}`,f,e.length)}if(r){let u=new Map,f=0;if(e.forEach(g=>{var b;let p=Fs(g[r]);if(p===null)return;let m=Math.min(5,Math.max(1,Math.round(p)));u.set(m,((b=u.get(m))!=null?b:0)+1),f++}),f>0){let g=[5,4,3,2,1].filter(p=>{var m;return((m=u.get(p))!=null?m:0)>0}).map(p=>({label:"\u2605".repeat(p),count:u.get(p),cls:"is-rating"}));Os(n,"Ratings",g,f)}}if(l){let u=Rs(e,f=>{var p;let g=((p=f[l])!=null?p:"").match(/\d{4}/);return g?[g[0]]:[]});if(u.size>1){let f=Array.from(u.entries()).sort((g,p)=>g[0].localeCompare(p[0])).map(([g,p])=>({label:g,count:p}));Os(n,"By year",f,e.length)}}if(a){let u=Rs(e,g=>{var m;let p=((m=g[a])!=null?m:"").trim();return p?[p]:[]}),f=Array.from(u.entries()).filter(([,g])=>g>1);if(f.length>=2){let g=f.sort((p,m)=>m[1]-p[1]||p[0].localeCompare(m[0])).slice(0,8).map(([p,m])=>({label:p,count:m}));Os(n,`Top ${a.toLowerCase()}s`,g,e.length)}}}function $t(s){let t=s.fileCfg.kanbanGroupCol;if(t&&s.headers.includes(t))return t;let e=s.getCategoryCol();if(e)return e;let n=new Set;s.headers.forEach(r=>{s.isNotesCol(r)&&n.add(r)});let i=s.getDateCol();i&&n.add(i);let o=s.titleKey();return o&&n.add(o),Qo(s.headers,s.rows,n)}function vn(s,t){let e=$t(s);if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let n=s.getCategoryCol(),i=s.getStatusCol(),o=i===e?null:i,r=s.getFilteredRows();s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${r.length} of ${s.rows.length} entries`});let a=t.createDiv({cls:"csv-kanban-groupbar"});a.createSpan({cls:"csv-kanban-groupbar-label",text:"Group by"});let l=a.createEl("select",{cls:"csv-library-filter-select"});s.headers.filter(m=>!s.isNotesCol(m)).forEach(m=>{let b=l.createEl("option",{text:m===n?`${m} (default)`:m,value:m});m===e&&(b.selected=!0)}),l.addEventListener("change",()=>{let m=s.fileCfg;m.kanbanGroupCol=l.value===n?void 0:l.value,s.saveFileCfg(m),s.renderView(!0)});let c=qo(e,r.map(m=>{var b;return(b=m[e])!=null?b:""})),d=m=>{var C;let b=(C=m[e])!=null?C:"",x;if(c){let E=Xo(b);x=E?[E]:[]}else x=b.split(",").map(E=>E.trim()).filter(Boolean);return x.length||(x=["\u2014"]),x},h=new Set;r.forEach(m=>d(m).forEach(b=>h.add(b)));let u=Array.from(h).sort();if(!u.length){let m=t.createDiv({cls:"csv-empty-state"});m.createEl("p",{text:s.searchQuery?"No matching entries found.":`No "${e}" values found.`}),s.searchQuery&&m.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear search"}).addEventListener("click",()=>{s.searchQuery="",s.renderView()});return}let f=["In progress","Finished","Not started"],g=o?Array.from(new Set([...f,...r.map(m=>{var b;return(b=m[o])!=null?b:""}).filter(Boolean)])).filter(m=>r.some(b=>{var x;return((x=b[o])!=null?x:"")==m})):[],p=t.createDiv({cls:"csv-kanban-board"});u.forEach(m=>{let b=r.filter(S=>d(S).includes(m));if(!b.length)return;let x=p.createDiv({cls:"csv-kanban-col"}),C=x.createDiv({cls:"csv-kanban-col-header"});C.createDiv({cls:"csv-kanban-col-title",text:m}),C.createDiv({cls:"csv-kanban-col-count",text:String(b.length)});let E=x.createDiv({cls:"csv-kanban-col-body"});if(o&&g.length){g.forEach(v=>{let _=b.filter(T=>{var k;return((k=T[o])!=null?k:"")===v});if(!_.length)return;let w=E.createDiv({cls:"csv-kanban-status-group"});w.createDiv({cls:`csv-kanban-status-label status-${v.toLowerCase().replace(/\s+/g,"-")}`,text:v}),_.forEach(T=>xi(s,w,T,o,e))});let S=new Set(g),y=b.filter(v=>{var _;return!S.has((_=v[o])!=null?_:"")});if(y.length){let v=E.createDiv({cls:"csv-kanban-status-group"});v.createDiv({cls:"csv-kanban-status-label",text:"\u2014"}),y.forEach(_=>xi(s,v,_,o,e))}}else b.forEach(S=>xi(s,E,S,o,e))})}function xi(s,t,e,n,i){var _,w,T,k,M,L,I,P;let o=t.createDiv({cls:"csv-kanban-card"}),r=s.getNotesCol(),a=(w=(_=s.getImageCol)==null?void 0:_.call(s))!=null?w:null;if(a){let R=cn(s.app,(T=e[a])!=null?T:"",(M=(k=s.file)==null?void 0:k.path)!=null?M:"");if(R){let D=o.createEl("img",{cls:"csv-kanban-card-img",attr:{src:R,loading:"lazy",alt:""}});D.addEventListener("error",()=>D.remove())}}let l=o.createDiv({cls:"csv-kanban-card-title-row"});l.createDiv({cls:`csv-kanban-card-title ${(L=s.isHighlighted)!=null&&L.call(s,e)?"csv-title-highlight":""}`,text:s.getTitle(e)}).addEventListener("click",R=>{R.stopPropagation(),s.openNoteExpander(e,r!=null?r:"")});let d=s.notesFileExists(e);l.createEl("button",{cls:`csv-kanban-notes-icon ${d?"exists":""}`,text:d?"\u{1F4C4}":"+",title:d?"Open notes file":"Create notes file"}).addEventListener("click",R=>{R.stopPropagation(),s.openOrCreateNotes(e)});let u=s.getSubtitle(e);u&&o.createDiv({cls:"csv-kanban-card-sub",text:u});let f=s.titleKey(),g=s.authorKey(),p=new Set([n,f,g,i].filter(Boolean)),m=o.createDiv({cls:"csv-kanban-card-meta"});((I=s.fileCfg.cardFields)!=null?I:s.headers).forEach(R=>{if(!s.headers.includes(R)||p.has(R)||s.isNotesCol(R))return;let D=m.createDiv({cls:"csv-kanban-chip"});if(D.createSpan({cls:"csv-chip-label",text:R+": "}),s.isSelectCol(R)){let W=D.createSpan({cls:`csv-chip-value csv-chip-select${e[R]?"":" csv-chip-value--empty"}`,text:e[R]||"\u2014"});W.addEventListener("click",O=>{O.stopPropagation(),Ft(W,e[R],s.getColumnValues(R),j=>{e[R]=j,W.setText(j||"\u2014"),W.classList.toggle("csv-chip-value--empty",!j),s.scheduleSave()},s.contentEl,{multi:wt(R)})})}else{let W=e[R]?e[R].length>40?e[R].slice(0,38)+"\u2026":e[R]:"\u2014",O=D.createSpan({cls:`csv-chip-value${e[R]?"":" csv-chip-value--empty"}`,text:W});e[R]&&e[R].length>40&&(O.title=e[R])}});let x=s.getNotesCol(),C=!!(x&&((P=e[x])!=null&&P.trim())),E=o.createDiv({cls:"csv-kanban-notes-preview"});if(C&&x){let R=e[x].replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();E.setText(R.slice(0,120)+(R.length>120?"\u2026":"")),E.title="Click to edit"}else E.addClass("csv-kanban-notes-preview--empty"),x&&E.setText("+ Add note");let S=o.createDiv({cls:"csv-kanban-notes-editor"});S.style.display="none";let y=()=>{var j,$,A;let R=s.contentEl.querySelector(".csv-content-area"),D=(j=R==null?void 0:R.scrollLeft)!=null?j:0,W=($=R==null?void 0:R.scrollTop)!=null?$:0;E.style.display="none",S.style.display="block",S.empty();let O=S.createEl("textarea",{cls:"csv-notes-textarea"});O.value=(A=x?e[x]:"")!=null?A:"",O.addEventListener("click",z=>z.stopPropagation()),O.addEventListener("mousedown",z=>z.stopPropagation()),O.addEventListener("input",()=>{O.style.height="auto",O.style.height=O.scrollHeight+"px"}),O.addEventListener("keydown",z=>{z.key==="Escape"&&v(O.value,R,D,W)}),O.addEventListener("blur",()=>v(O.value,R,D,W)),O.focus({preventScroll:!0}),O.setSelectionRange(0,0),O.scrollTop=0,requestAnimationFrame(()=>{O.style.height="auto",O.style.height=Math.max(120,O.scrollHeight)+"px"})},v=(R,D,W,O)=>{if(x&&(e[x]=R,s.scheduleSave()),S.style.display="none",E.style.display="",R.trim()){let j=R.replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim();E.setText(j.slice(0,120)+(j.length>120?"\u2026":"")),E.removeClass("csv-kanban-notes-preview--empty"),E.title="Click to edit"}else E.addClass("csv-kanban-notes-preview--empty"),E.setText(x?"+ Add note":""),E.removeAttribute("title");D&&(D.scrollLeft=W,D.scrollTop=O,requestAnimationFrame(()=>{D.scrollLeft=W,D.scrollTop=O,requestAnimationFrame(()=>{D.scrollLeft=W,D.scrollTop=O})}),setTimeout(()=>{D.scrollLeft=W,D.scrollTop=O},50))};E.addEventListener("click",R=>{if(R.stopPropagation(),x&&matchMedia("(pointer: coarse)").matches){s.openNoteExpander(e,x);return}y()}),o.addEventListener("contextmenu",R=>s.openRowContextMenu(e,R))}function yn(s,t){var w,T;let e=$t(s),n=s.getStatusCol(),i=(w=s.titleKey())!=null?w:s.headers[0],o=s.authorKey();if(!e){t.createEl("p",{text:"No groupable column found.",cls:"csv-empty-state"});return}let r=new Set;s.rows.forEach(k=>{var L;((L=k[e])!=null?L:"").split(",").map(I=>I.trim()).filter(Boolean).forEach(I=>r.add(I))});let a=new Set;n&&s.rows.forEach(k=>{var L;let M=((L=k[n])!=null?L:"").trim();M&&a.add(M)});let l=t.createDiv({cls:"csv-library-filters"}),c=l.createEl("select",{cls:"csv-library-filter-select"});c.createEl("option",{text:"All",value:"all"});let d=["watched","read","finished","completed","done","yes","seen"],h=["watching","reading","in progress","in-progress"],u=Array.from(a).some(k=>d.includes(k.toLowerCase())),f=Array.from(a).some(k=>h.includes(k.toLowerCase()));(u||f)&&(c.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),u&&c.createEl("option",{text:"\u2713 Done",value:"__done__"}),f&&c.createEl("option",{text:"\u25D0 In Progress",value:"__inprogress__"}),c.createEl("option",{text:"\u25CB Not Started",value:"__notstarted__"})),a.size>0&&(c.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"",attr:{disabled:"true"}}),Array.from(a).sort().forEach(k=>{c.createEl("option",{text:k,value:k})})),c.value=s.libraryStatusFilter;let g=l.createEl("select",{cls:"csv-library-filter-select"});g.createEl("option",{text:"All genres",value:"all"}),Array.from(r).sort().forEach(k=>{g.createEl("option",{text:k,value:k})}),g.value=s.libraryGenreFilter;let p=s.resolveCol(["Year","year","Date","date"]),m=s.resolveCol(["Rating","rating","Score","score","Score /5","Stars","stars"]),b=s.resolveCol(["Theme","theme","Tags","tags","Tag","tag","Mood","mood"]),x=(T=s.fileCfg.librarySort)!=null?T:"status",C=l.createEl("select",{cls:"csv-library-filter-select"}),E=[["status","Sort: Status"],["title","Sort: Title"]];m&&E.push(["rating","Sort: Rating"]),p&&E.push(["year","Sort: Year"]),E.forEach(([k,M])=>{let L=C.createEl("option",{text:M,value:k});k===x&&(L.selected=!0)}),C.addEventListener("change",()=>{let k=s.fileCfg;k.librarySort=C.value==="status"?void 0:C.value,s.saveFileCfg(k),s.renderView(!0)});let S=()=>{s.libraryStatusFilter=c.value,s.libraryGenreFilter=g.value,s.renderView(!0)};c.addEventListener("change",S),g.addEventListener("change",S);let y=s.rows.filter(k=>{var M,L;if(s.libraryStatusFilter!=="all"&&n){let I=((M=k[n])!=null?M:"").toLowerCase();if(s.libraryStatusFilter==="__done__"){if(!d.includes(I))return!1}else if(s.libraryStatusFilter==="__inprogress__"){if(!h.includes(I))return!1}else if(s.libraryStatusFilter==="__notstarted__"){if(d.includes(I)||h.includes(I))return!1}else if(I!==s.libraryStatusFilter.toLowerCase())return!1}if(s.libraryGenreFilter!=="all"&&!((L=k[e])!=null?L:"").split(",").map(P=>P.trim().toLowerCase()).includes(s.libraryGenreFilter.toLowerCase()))return!1;if(s.searchQuery.trim()){let I=s.searchQuery.toLowerCase().trim();if(!s.headers.some(P=>{var R;return((R=k[P])!=null?R:"").toLowerCase().includes(I)}))return!1}return!0});(s.libraryStatusFilter!=="all"||s.libraryGenreFilter!=="all"||s.searchQuery.trim())&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${y.length} of ${s.rows.length} entries`});let v={};y.forEach(k=>{var L;let M=s.libraryGenreFilter!=="all"?[s.libraryGenreFilter]:((L=k[e])!=null?L:"Uncategorized").split(",").map(I=>I.trim()).filter(Boolean);M.length===0&&M.push("Uncategorized"),M.forEach(I=>{v[I]||(v[I]=[]),v[I].push(k)})});let _=t.createDiv({cls:"csv-library-sections"});if(Object.keys(v).sort().forEach(k=>{var A,z,G,B,F;let M=v[k],L=_.createEl("details",{cls:"csv-library-section"}),I=k.toLowerCase(),P=((A=s.fileCfg.collapsedGroups)!=null?A:[]).map(N=>N.toLowerCase());L.open=!((z=s.collapsedGroups)!=null&&z.has(I)||P.includes(I)),L.addEventListener("toggle",()=>{var Y;let N=s.fileCfg,H=((Y=N.collapsedGroups)!=null?Y:[]).map(q=>q.toLowerCase()),V=new Set(H);L.open?V.delete(I):V.add(I);let K=Array.from(V);K.length===H.length&&K.every(q=>H.includes(q))||(N.collapsedGroups=K,s.saveFileCfg(N))});let R=L.createEl("summary",{cls:"csv-library-section-header"});R.innerHTML=`\u25B6 ${k} ${M.length}`;let D=L.createDiv({cls:"csv-library-grid"}),W=(N,H)=>{var V,K;return((V=N[i])!=null?V:"").localeCompare((K=H[i])!=null?K:"")},O=(N,H)=>N===null&&H===null?0:N===null?1:H===null?-1:H-N;M.sort((N,H)=>{var V,K,Y,q;if(x==="title")return W(N,H);if(x==="rating"&&m)return O(Fs((V=N[m])!=null?V:""),Fs((K=H[m])!=null?K:""))||W(N,H);if(x==="year"&&p){let X=Z=>{var Q;let at=((Q=Z[p])!=null?Q:"").match(/\d{4}/);return at?parseInt(at[0],10):null};return O(X(N),X(H))||W(N,H)}if(n){let X=((Y=N[n])!=null?Y:"").toLowerCase(),Z=((q=H[n])!=null?q:"").toLowerCase(),at=d.includes(X),Q=d.includes(Z);if(at!==Q)return at?-1:1;let st=h.includes(X),lt=h.includes(Z);if(st!==lt)return st?-1:1}return W(N,H)});let j=(G=s.fileCfg.cardFields)!=null?G:s.headers,$=(F=(B=s.getImageCol)==null?void 0:B.call(s))!=null?F:null;M.forEach(N=>{var q,X,Z,at,Q,st,lt,Wt;let H=D.createDiv({cls:"csv-library-card"});if($){let ot=cn(s.app,(q=N[$])!=null?q:"",(Z=(X=s.file)==null?void 0:X.path)!=null?Z:"");if(ot){let pt=H.createEl("img",{cls:"csv-library-card-img",attr:{src:ot,loading:"lazy",alt:""}});pt.addEventListener("error",()=>pt.remove())}}let V=H.createDiv({cls:`csv-library-card-title ${(at=s.isHighlighted)!=null&&at.call(s,N)?"csv-title-highlight":""}`});if(n){let ot=((Q=N[n])!=null?Q:"").toLowerCase();d.includes(ot)&&V.createSpan({cls:"csv-library-done-dot"})}V.createSpan({text:(st=N[i])!=null?st:"Untitled"});let K=[],Y=[];for(let ot of j){if(!ot)continue;let pt=String((lt=N[ot])!=null?lt:"").trim();if(pt)if(ot===m){let ft=Go(pt,ot);ft&&H.createDiv({cls:"csv-library-card-rating",text:ft})}else if(ot===b)Y.push(...pt.split(",").map(ft=>ft.trim()).filter(Boolean));else if(ot===p){let ft=pt.match(/\d{4}/);K.push(ft?ft[0]:pt)}else K.push(pt)}if(K.length&&H.createDiv({cls:"csv-library-card-meta",text:K.join(" \xB7 ")}),s.libraryGenreFilter!=="all"){let ot=((Wt=N[e])!=null?Wt:"").split(",").map(pt=>pt.trim()).filter(pt=>pt&&pt.toLowerCase()!==s.libraryGenreFilter.toLowerCase());Y.push(...ot)}if(Y.length){let ot=H.createDiv({cls:"csv-library-card-tags"});Y.slice(0,3).forEach(pt=>{ot.createSpan({cls:"csv-library-card-tag",text:pt})})}H.addEventListener("click",()=>{var ot;s.openNoteExpander(N,(ot=s.getNotesCol())!=null?ot:"")}),H.addEventListener("contextmenu",ot=>s.openRowContextMenu(N,ot))})}),Object.keys(v).length===0){let k=_.createDiv({cls:"csv-empty-state"});k.createEl("p",{text:"No entries match your filters."}),k.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.libraryStatusFilter="all",s.libraryGenreFilter="all",s.searchQuery="",s.renderView()})}}var di=require("obsidian");var Le=require("obsidian");var Ci=`--- obsidianUIMode: preview obsidianEditingMode: source --- @@ -365,7 +365,7 @@ if (!csvData || !csvData.length) { } } \`\`\` -${_i}`}async function br(s){var c,d,h,u,f,g,p,m,b,x;if(!s.file)return;let t=(d=(c=s.file.parent)==null?void 0:c.path)!=null?d:"",e=t?`${t}/Mobile`:"Mobile";await s.app.vault.adapter.exists(e)||await s.app.vault.adapter.mkdir(e);let n=`${e}/${s.file.basename}.md`,i=s.file.path,o=s.getDateCol(),r=s.getCategoryCol(),a="../"+s.file.name,l;if(o){let C=s.getBooleanColumns();l=gr({filePath:a,csvPath:i,habitCols:C,labels:C.map(Et),dateCol:o})}else if(r){let C=(f=(u=(h=s.titleKey())!=null?h:s.resolveCol(["Quote","quote","Headline","headline","Phrase","phrase"]))!=null?u:s.headers[0])!=null?f:"Title";l=pr({filePath:a,csvPath:i,titleKey:C,categoryCol:r,statusCol:(g=s.getStatusCol())!=null?g:"Status",authorKey:(p=s.authorKey())!=null?p:"",yearCol:(m=s.resolveCol(["Year","year","Released","released"]))!=null?m:"",ratingCol:(b=s.resolveCol(["Rating","rating","Score","score","Stars","stars"]))!=null?b:"",themeCol:(x=s.resolveCol(["Theme","theme","Subgenre","subgenre","Mood","mood"]))!=null?x:"",compactGrid:s.titleKey()!==null})}else l=mr({filePath:a,csvPath:i,headers:s.headers});try{let C=s.app.vault.getAbstractFileByPath(n);C&&C instanceof Le.TFile?(await s.app.vault.modify(C,l),new Le.Notice(`Updated: ${n}`)):(await s.app.vault.create(n,l),new Le.Notice(`Created: ${n}`))}catch(C){let E=s.app.vault.getAbstractFileByPath(n);E instanceof Le.TFile&&(await s.app.vault.modify(E,l),new Le.Notice(`Updated: ${n}`))}}var ge=require("obsidian"),Kc="http://127.0.0.1:8765",Yc=6;async function vr(s,t){let e;try{e=await(0,ge.requestUrl)({url:Kc,method:"POST",contentType:"application/json",body:JSON.stringify({action:s,version:Yc,params:t}),throw:!1})}catch(i){throw new Error("Couldn't reach Anki. Is the desktop app open with the AnkiConnect add-on installed?")}let n=e.json;if(n.error)throw new Error(n.error);return n.result}function Ei(s){var t,e,n;return(n=(e=(t=s.titleKey())!=null?t:s.resolveCol(["Quote","Headline","Phrase","Term","Word","Question","Front","Name","Title"]))!=null?e:s.headers[0])!=null?n:null}function Gc(s){let t=s.fileCfg.ankiFrontCol;return t&&s.headers.includes(t)?t:Ei(s)}function Si(s){return s.replace(/&/g,"&").replace(//g,">")}function qc(s,t,e){return s.headers.filter(n=>{var i;return n!==e&&((i=t[n])!=null?i:"").trim()}).map(n=>`${Si(n)}: ${Si(t[n].trim())}`).join("
")}async function yr(s){if(!s.file)return;let t=Gc(s);if(!t){new ge.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 ge.Notice(`Nothing to sync \u2014 no rows with a "${t}" value.`,6e3);return}let i=new ge.Notice(`Syncing ${n.length} cards to Anki deck \u201C${e}\u201D\u2026`,0);try{await vr("createDeck",{deck:e});let o=n.map(c=>({deckName:e,modelName:"Basic",fields:{Front:Si(c[t].trim()),Back:qc(s,c,t)},options:{allowDuplicate:!1,duplicateScope:"deck"},tags:["datadeck"]})),r=await vr("addNotes",{notes:o}),a=r.filter(c=>c!=null).length,l=r.length-a;i.hide(),new ge.Notice(`Anki sync: ${a} added${l?`, ${l} already present`:""} (deck \u201C${e}\u201D).`,6e3)}catch(o){i.hide(),new ge.Notice(`Anki sync failed: ${o instanceof Error?o.message:String(o)}`,8e3)}}var Lo=null;async function _s(){if(Lo)return Lo;let s=await Promise.resolve().then(()=>(Gl(),Yl));return s.Chart.register(s.LineController,s.ScatterController,s.LineElement,s.PointElement,s.LinearScale,s.CategoryScale,s.Filler,s.Tooltip,s.Legend),Lo=s,s}var ql={pi:Math.PI,e:Math.E},Xl={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sqrt:Math.sqrt,log:Math.log10,ln:Math.log,exp:Math.exp,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,sign:Math.sign},Ao={min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2};function mg(s){let t=[],e=0;for(;e{var u;return(u=e[n])!=null?u:null},o=()=>{var u;return(u=e[n++])!=null?u:null};function r(){let u=a();for(;;){let f=i();if((f==null?void 0:f.kind)==="op"&&(f.op==="+"||f.op==="-")){n++;let g=a(),p=u;u=f.op==="+"?b=>p(b)+g(b):b=>p(b)-g(b)}else return u}}function a(){let u=l();for(;;){let f=i();if((f==null?void 0:f.kind)==="op"&&(f.op==="*"||f.op==="/"||f.op==="%")){n++;let g=l(),p=u,m=f.op;u=m==="*"?b=>p(b)*g(b):m==="/"?b=>p(b)/g(b):b=>p(b)%g(b)}else if(f&&(f.kind==="num"||f.kind==="ident"||f.kind==="lparen")){let g=l(),p=u;u=m=>p(m)*g(m)}else return u}}function l(){let u=i();if((u==null?void 0:u.kind)==="op"&&u.op==="-"){n++;let f=l();return g=>-f(g)}return(u==null?void 0:u.kind)==="op"&&u.op==="+"?(n++,l()):c()}function c(){let u=d(),f=i();if((f==null?void 0:f.kind)==="op"&&f.op==="^"){n++;let g=l();return p=>Math.pow(u(p),g(p))}return u}function d(){var f,g,p,m,b;let u=o();if(!u)throw new Error("Unexpected end of formula");if(u.kind==="num"){let x=u.value;return()=>x}if(u.kind==="lparen"){let x=r();if(((f=o())==null?void 0:f.kind)!=="rparen")throw new Error("Missing closing )");return x}if(u.kind==="ident"){if(u.name==="x")return C=>C;if(u.name in ql){let C=ql[u.name];return()=>C}let x=((g=i())==null?void 0:g.kind)==="lparen";if(u.name in Xl||u.name in Ao){if(!x)throw new Error(`${u.name} needs parentheses, e.g. ${u.name}(x)`);n++;let C=r();if(u.name in Ao){if(((p=o())==null?void 0:p.kind)!=="comma")throw new Error(`${u.name}(a, b) needs two arguments`);let S=r();if(((m=o())==null?void 0:m.kind)!=="rparen")throw new Error("Missing closing )");let y=Ao[u.name];return v=>y(C(v),S(v))}if(((b=o())==null?void 0:b.kind)!=="rparen")throw new Error("Missing closing )");let E=Xl[u.name];return S=>E(C(S))}throw new Error(`Unknown name "${u.name}" \u2014 use x, pi, e, or a function like sin()`)}throw new Error(`Unexpected "${u.kind==="op"?u.op:u.kind}"`)}let h=r();if(n{var o;let n=0,i=0;for(let r of t){let a=((o=r[e])!=null?o:"").trim();a&&(n++,Po(a)!==null&&i++)}return i>=2&&i/n>=.7})}function bg(s){let t=s.length;if(t<2)return null;let e=0,n=0,i=0,o=0,r=0;for(let f of s)e+=f.x,n+=f.y,i+=f.x*f.x,o+=f.x*f.y,r+=f.y*f.y;let a=t*i-e*e;if(a===0)return null;let l=(t*o-e*n)/a,c=(n-l*e)/t,d=n/t,h=0,u=0;for(let f of s){let g=f.y-(l*f.x+c);h+=g*g,u+=(f.y-d)*(f.y-d)}return{slope:l,intercept:c,r2:u===0?1:1-h/u}}function Ro(s){var n;let t=(n=s.ownerDocument.defaultView)==null?void 0:n.getComputedStyle(s),e=(i,o)=>(t==null?void 0:t.getPropertyValue(i).trim())||o;return{accent:e("--interactive-accent","#378ADD"),muted:e("--text-muted","#888888"),grid:e("--background-modifier-border","rgba(128,128,128,0.25)"),fitLine:e("--text-faint","#999999"),formula:e("--color-orange","#e0883a")}}var on=s=>{if(!Number.isFinite(s))return String(s);let t=Math.abs(s);return t!==0&&(t>=1e6||t<.001)?s.toExponential(2):String(Math.round(s*1e3)/1e3)},Zl=s=>{let t=new Date(s);return isNaN(t.getTime())?String(s):t.toISOString().slice(0,10)};function Oo(s,t){var d,h;let e=[],n=s.connect?[...s.points].sort((u,f)=>u.x-f.x):s.points;n.length&&e.push({type:s.connect?"line":"scatter",label:s.yLabel,data:n,backgroundColor:t.accent,borderColor:t.accent,borderWidth:1.5,pointRadius:s.connect?3:4,pointHoverRadius:6,tension:.3});let i=n.map(u=>u.x),o=n.length?Math.min(...i):(d=s.xMin)!=null?d:0,r=n.length?Math.max(...i):(h=s.xMax)!=null?h:10,a=null;if(s.fit==="linear"){let u=bg(n);if(u&&r>o){e.push({type:"line",label:"Best fit",data:[{x:o,y:u.slope*o+u.intercept},{x:r,y:u.slope*r+u.intercept}],borderColor:t.fitLine,borderDash:[6,4],borderWidth:1.5,pointRadius:0,pointHitRadius:0});let f=` \xB7 R\xB2 = ${(Math.round(u.r2*1e3)/1e3).toFixed(3)}`;if(s.xIsDate){let g=u.slope*864e5;a=`Trend: ${g>=0?"+":""}${on(g)} ${s.yLabel}/day${f}`}else{let g=u.intercept>=0?"+":"\u2212";a=`y = ${on(u.slope)}x ${g} ${on(Math.abs(u.intercept))}${f}`}}}let l=null;if(s.formula.trim())try{let u=Ql(s.formula),f=[],g=160;for(let p=0;p<=g;p++){let m=o+(r-o)*p/g,b=u(m);Number.isFinite(b)&&f.push({x:m,y:b})}f.length&&e.push({type:"line",label:s.formula.trim(),data:f,borderColor:t.formula,borderWidth:1.5,pointRadius:0,pointHitRadius:0,tension:0})}catch(u){l=u instanceof Error?u.message:String(u)}return{config:{type:"scatter",data:{datasets:e},options:{responsive:!0,maintainAspectRatio:!1,scales:{x:{type:"linear",title:{display:!s.xIsDate&&!!s.xLabel,text:s.xLabel,color:t.muted},ticks:{color:t.muted,...s.xIsDate?{callback:u=>Zl(Number(u)),maxTicksLimit:8}:{}},grid:{color:t.grid}},y:{title:{display:!!s.yLabel,text:s.yLabel,color:t.muted},ticks:{color:t.muted},grid:{color:t.grid}}},plugins:{legend:{display:e.length>1,labels:{color:t.muted,boxWidth:12}},tooltip:{callbacks:{label:u=>{let f=u.raw,g=s.xIsDate?Zl(f.x):on(f.x);return`${f.label?`${f.label}: `:""}(${g}, ${on(f.y)})`}}}}}},fitText:a,formulaError:l}}var ii="(row number)";function Fo(s,t,e,n,i,o){let r=[],a=0;return s.forEach((l,c)=>{var u,f,g;let d=Po((u=l[e])!=null?u:""),h;if(t===ii)h=c+1;else if(n){let p=i((f=l[t])!=null?f:"");h=p?p.getTime():null}else h=Po((g=l[t])!=null?g:"");if(h===null||d===null){a++;return}r.push({x:h,y:d,label:o(l)})}),{points:r,skipped:a}}function ri(s){return s.rows.length>=2&&oi(s.headers,s.rows).length>=1}async function Jl(s,t){var L,I;let e=s.getFilteredRows(),n=oi(s.headers,s.rows);if(!n.length){t.createEl("p",{text:"No numeric column to chart.",cls:"csv-empty-state"});return}s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Chart over ${e.length} of ${s.rows.length} entries`});let i=s.fileCfg,o=s.getDateCol(),r=[...o?[o]:[],...n.filter(P=>P!==o),ii],a=i.chartXCol&&r.includes(i.chartXCol)?i.chartXCol:r[0],l=n,c=i.chartYCol&&l.includes(i.chartYCol)?i.chartYCol:(L=l.find(P=>P!==a))!=null?L:l[0],d=i.chartFit==="linear"?"linear":"none",h=(I=i.chartFormula)!=null?I:"",u=t.createDiv({cls:"csv-chart-view"}),f=u.createDiv({cls:"csv-chart-controls"}),g=P=>{s.saveFileCfg({...s.fileCfg,...P}),s.renderViewPreservingScroll()},p=(P,R,D,W)=>{let O=f.createDiv({cls:"csv-chart-control"});O.createSpan({cls:"csv-chart-control-label",text:P});let j=O.createEl("select",{cls:"csv-chart-select",attr:{"aria-label":P}});return R.forEach($=>{let A=j.createEl("option",{text:$,value:$});$===D&&(A.selected=!0)}),j.addEventListener("change",()=>W(j.value)),j};p("X",r,a,P=>g({chartXCol:P})),p("Y",l,c,P=>g({chartYCol:P})),f.createEl("button",{cls:`csv-cfg-btn csv-chart-fit-btn ${d==="linear"?"active":""}`,text:"Best fit",title:"Toggle a least-squares fit line"}).addEventListener("click",()=>g({chartFit:d==="linear"?"none":"linear"}));let b=f.createDiv({cls:"csv-chart-control csv-chart-formula-wrap"});b.createSpan({cls:"csv-chart-control-label",text:"y ="});let x=b.createEl("input",{cls:"csv-chart-formula-input",type:"text",value:h,placeholder:"overlay, e.g. 2x + 1",attr:{spellcheck:"false",autocomplete:"off",enterkeyhint:"done"}}),C=()=>{x.value.trim()!==h.trim()&&g({chartFormula:x.value})};x.addEventListener("change",C),x.addEventListener("keydown",P=>{P.key==="Enter"&&(P.preventDefault(),x.blur())});let E=a!==ii&&(a===o||s.isDateCol(a)),{points:S,skipped:y}=Fo(e,a,c,E,P=>s.parseDate(P),P=>s.getTitle(P)),v=u.createDiv({cls:"csv-chart-wrap"}),_=v.createEl("canvas",{cls:"csv-chart-canvas"}),w=u.createDiv({cls:"csv-chart-footer"});if(!S.length){v.remove(),w.remove(),u.createEl("p",{text:`No rows with both "${a}" and "${c}" values to plot.`,cls:"csv-empty-state"});return}let k=Oo({points:S,xIsDate:E,xLabel:a===ii?"row":a,yLabel:c,connect:E,fit:d,formula:h},Ro(t));k.fitText&&w.createSpan({cls:"csv-chart-fit-text",text:k.fitText}),k.formulaError&&w.createSpan({cls:"csv-chart-formula-error",text:`formula: ${k.formulaError}`}),y>0&&w.createSpan({cls:"csv-chart-skipped",text:`${y} row${y===1?"":"s"} skipped (no numeric value)`}),s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:M}=await _s();_.isConnected&&(s.chartInstance=new M(_,k.config))}function ai(s){return s.resolveCol(["Type","type","Kind","kind","Item","item"])}function Vo(s){var t;return(t=s.resolveCol(["Project","project","Projects","projects","Area","area"]))!=null?t:$t(s)}function sc(s){return s.resolveCol(["Due","due","Deadline","deadline","Due Date","Due date","due date"])}function li(s){return s.resolveCol(["Priority","priority","Prio","prio","Importance","importance"])}var vg=["task","todo","to-do","action",""],yg=["task","todo","to-do","action","note","idea","reference","ref"],nc=["done","complete","completed","finished","closed","resolved","yes","x","\u2713","true"],xg={high:0,med:1,medium:1,normal:1,low:2};function Ss(s){if(sc(s)||li(s))return!0;let t=ai(s);return t?s.rows.some(e=>{var n;return yg.includes(((n=e[t])!=null?n:"").trim().toLowerCase())}):!1}function Io(s,t,e){var n;return e?nc.includes(((n=t[e])!=null?n:"").trim().toLowerCase()):!1}function tc(s){let t=xg[(s!=null?s:"").trim().toLowerCase()];return t===void 0?3:t}function ec(s){return(s!=null?s:"").trim()?0:1}function Cg(){return new Date().toISOString().slice(0,10)}function _g(s,t){let e=new Map;s.rows.forEach(o=>{var a,l;let r=((a=o[t])!=null?a:"").trim();r&&nc.includes(r.toLowerCase())&&e.set(r,((l=e.get(r))!=null?l:0)+1)});let n="done",i=0;return e.forEach((o,r)=>{o>i&&(n=r,i=o)}),n}function ic(s,t){var T,k;let e=Vo(s),n=ai(s),i=s.getStatusCol(),o=sc(s),r=li(s),a=(T=s.titleKey())!=null?T:s.headers[0],l=t.createDiv({cls:"csv-library-filters"}),c=new Set;e&&s.rows.forEach(M=>{var L;((L=M[e])!=null?L:"").split(",").map(I=>I.trim()).filter(Boolean).forEach(I=>c.add(I))});let d=l.createEl("select",{cls:"csv-library-filter-select"});d.createEl("option",{text:e?"All projects":"All",value:"all"}),Array.from(c).sort().forEach(M=>d.createEl("option",{text:M,value:M})),d.value=s.taskProjectFilter;let h=new Set;n&&s.rows.forEach(M=>{var I;let L=((I=M[n])!=null?I:"").trim();L&&h.add(L)});let u=null;h.size>0&&(u=l.createEl("select",{cls:"csv-library-filter-select"}),u.createEl("option",{text:"All types",value:"all"}),Array.from(h).sort().forEach(M=>u.createEl("option",{text:M,value:M})),u.value=s.taskTypeFilter);let f=()=>{s.taskProjectFilter=d.value,u&&(s.taskTypeFilter=u.value),s.renderView(!0)};d.addEventListener("change",f),u==null||u.addEventListener("change",f);let g=s.searchQuery.toLowerCase().trim(),p=s.rows.filter(M=>{var L,I;return!(s.taskProjectFilter!=="all"&&e&&!((L=M[e])!=null?L:"").split(",").map(R=>R.trim().toLowerCase()).includes(s.taskProjectFilter.toLowerCase())||s.taskTypeFilter!=="all"&&n&&((I=M[n])!=null?I:"").trim().toLowerCase()!==s.taskTypeFilter.toLowerCase()||g&&!s.headers.some(P=>{var R;return((R=M[P])!=null?R:"").toLowerCase().includes(g)}))});(s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"||g)&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${p.length} of ${s.rows.length} entries`});let m={},b=M=>{var I;return e&&((I=M[e])!=null?I:"").split(",").map(P=>P.trim()).filter(Boolean)[0]||"\u2014"};p.forEach(M=>{var R,D,W;let L=n?((R=M[n])!=null?R:"").trim():"",I=vg.includes(L.toLowerCase())?"Tasks":L,P=b(M);m[I]||(m[I]={}),((W=(D=m[I])[P])!=null?W:D[P]=[]).push(M)});let x=t.createDiv({cls:"csv-tasks"}),C=Cg(),E=i?_g(s,i):"done",y=((k=s.fileCfg.cardFields)!=null?k:s.headers).filter(M=>M!==e&&M!==n&&M!==i),v=[];i&&v.push({name:"",cls:"csv-tasks-check-cell"}),y.forEach(M=>{let L="";M===a?L="csv-tasks-name-cell":M===o?L="csv-tasks-due":M===r?L="csv-tasks-priority":s.isNotesCol(M)?L="csv-tasks-generic-cell csv-tasks-notes-cell":L="csv-tasks-generic-cell",v.push({name:M,cls:L})});let _=(M,L)=>{L.sort((I,P)=>{var W,O,j,$,A,z;let R=Io(s,I,i),D=Io(s,P,i);if(R!==D)return R?1:-1;if(r){let G=tc((W=I[r])!=null?W:"")-tc((O=P[r])!=null?O:"");if(G)return G}if(o){let G=ec((j=I[o])!=null?j:"")-ec(($=P[o])!=null?$:"");if(G)return G;let B=((A=I[o])!=null?A:"").localeCompare((z=P[o])!=null?z:"");if(B)return B}return s.getTitle(I).localeCompare(s.getTitle(P))}),L.forEach(I=>{let P=Io(s,I,i),R=M.createEl("tr");if(i){let W=R.createEl("td",{cls:"csv-tasks-check-cell"}).createEl("span",{cls:`csv-tasks-check ${P?"is-done":""}`,text:P?"\u2713":""});W.setAttr("title",P?"Mark not done":"Mark done"),W.addEventListener("click",O=>{O.stopPropagation(),I[i]=P?"":E,s.scheduleSave(),s.renderView(!0)})}y.forEach(D=>{var W,O,j;if(D===a)Eg(s,R,I,a,P);else if(D===o){let $=R.createEl("td",{cls:"csv-tasks-due csv-tasks-editable"}),A=o?((W=I[o])!=null?W:"").slice(0,10):"";$.setText(A||"\u2014"),A&&!P&&A{var G;A.stopPropagation();let z=Array.from(new Set([...s.getColumnValues(r),"high","medium","low"]));Ft($,(G=I[r])!=null?G:"",z,B=>{I[r]=B,s.scheduleSave(),s.renderView(!0)},s.contentEl)})}else if(s.isNotesCol(D)){let $=((O=I[D])!=null?O:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim(),A=$?$.length>50?$.slice(0,48)+"\u2026":$:"\u2014",z=R.createEl("td",{text:A,cls:"csv-tasks-generic-cell csv-tasks-notes-cell csv-tasks-editable"});Ps(s,z,I,D)}else{let $=(j=I[D])!=null?j:"",A=$.length>40?$.slice(0,38)+"\u2026":$,z=R.createEl("td",{text:A||"\u2014",cls:"csv-tasks-generic-cell csv-tasks-editable"});Ps(s,z,I,D)}}),R.addEventListener("contextmenu",D=>s.openRowContextMenu(I,D))})},w=Object.keys(m).sort((M,L)=>M==="Tasks"?-1:L==="Tasks"?1:M.localeCompare(L));if(w.forEach(M=>{Sg(s,x,M==="Tasks"?M:Et(M),m[M],_,v)}),w.length===0){let M=x.createDiv({cls:"csv-empty-state"});M.createEl("p",{text:g||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"?"No entries match your filters.":"No tasks yet."}),(g||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all")&&M.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.taskProjectFilter="all",s.taskTypeFilter="all",s.searchQuery="",s.renderView()})}}function Sg(s,t,e,n,i,o){if(Object.keys(n).length===0)return;t.createDiv({cls:"csv-tasks-section-header",text:e});let r=t.createDiv({cls:"csv-tasks-section"});Object.keys(n).sort().forEach(a=>{let l=n[a],c=r.createEl("details",{cls:"csv-tasks-group"});c.open=!0;let d=c.createEl("summary",{cls:"csv-tasks-group-header"});d.innerHTML=`\u25B6 ${a} ${l.length}`;let u=c.createDiv({cls:"csv-tasks-table-wrapper"}).createEl("table",{cls:"csv-tasks-table"}),f=120;o.forEach(b=>{b.cls.includes("check-cell")?f+=30:b.cls.includes("priority")?f+=90:b.cls.includes("due")?f+=150:b.cls.includes("notes-cell")?f+=140:b.cls.includes("generic-cell")&&(f+=150)}),u.style.minWidth=`${f}px`;let p=u.createEl("thead").createEl("tr");o.forEach(b=>p.createEl("th",{text:b.name,cls:b.cls}));let m=u.createEl("tbody");i(m,l)})}function Eg(s,t,e,n,i){var h;let o=t.createEl("td",{cls:"csv-tasks-name-cell"}),r=(h=s.isHighlighted)!=null&&h.call(s,e)?"csv-title-highlight":"",a=o.createSpan({cls:`csv-tasks-link ${i?"csv-tasks-done":""} ${r}`,text:e[n]||"Untitled"}),l=s.getNotesCol();a.addEventListener("click",()=>{l?s.openNoteExpander(e,l):s.openOrCreateNotes(e)});let c=s.notesFileExists(e),d=o.createEl("button",{cls:`csv-tasks-page-icon ${c?"exists":""}`,text:c?"\u{1F4C4}":"+"});d.setAttr("title",c?"Open page":"Create page"),d.addEventListener("click",u=>{u.stopPropagation(),s.openOrCreateNotes(e)})}function ci(s){let t=[];return s.isTravelFile()&&t.push({id:"travel",label:"Travel"}),s.hasDateColumn()&&t.push({id:"dashboard",label:"Dashboard"}),Ss(s)&&t.push({id:"tasks",label:"Tasks"}),$t(s)&&(t.push({id:"library",label:"Cards"}),t.push({id:"kanban-genre",label:"Kanban"})),t.push({id:"table",label:"Table"}),s.rows.length>0&&t.push({id:"focus",label:"Focus"}),bn(s)&&t.push({id:"stats",label:"Stats"}),ri(s)&&t.push({id:"chart",label:"Chart"}),t}function oc(s,t){var f,g,p;let e=t.createDiv({cls:"csv-toolbar"});e.createDiv({cls:"csv-toolbar-title",text:(g=(f=s.file)==null?void 0:f.basename)!=null?g:""});let n=e.createDiv({cls:"csv-toolbar-controls"});n.createDiv({cls:"csv-row-count",text:`${s.rows.length} entries`});let i=n.createDiv({cls:"csv-mode-group"}),o=ci(s),r=i.createEl("select",{cls:"csv-mode-select",attr:{"aria-label":"View mode"}});if(o.forEach(({id:m,label:b})=>{let x=r.createEl("option",{text:b,value:m});s.mode===m&&(x.selected=!0)}),r.addEventListener("change",()=>{s.mode=r.value,s.renderView()}),s.mode!=="dashboard"){let m=n.createEl("button",{cls:"csv-cfg-btn csv-search-toggle",text:"\u{1F50D}",title:"Search"}),b=n.createDiv({cls:"csv-search-wrap"}),x=b.createDiv({cls:"csv-search-input-wrap"}),C=x.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search...",value:s.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),E=x.createEl("button",{cls:"csv-search-clear",text:"\xD7",title:"Clear search"});E.toggleClass("is-hidden",!s.searchQuery),b.createEl("button",{cls:"csv-search-done",text:"Done",title:"Dismiss keyboard"}).addEventListener("click",v=>{if(v.preventDefault(),!C.value){e.removeClass("csv-toolbar--search-expanded"),m.removeClass("has-query"),s.searchQuery="",s.renderView(!0);return}C.blur()});let y=null;C.addEventListener("input",v=>{s.searchQuery=v.target.value,E.toggleClass("is-hidden",!s.searchQuery),m.toggleClass("has-query",!!s.searchQuery),y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>{y=null,s.renderView(!0)},120)}),C.addEventListener("keydown",v=>{v.key==="Enter"&&(v.preventDefault(),C.blur())}),E.addEventListener("click",()=>{s.searchQuery="",C.value="",E.addClass("is-hidden"),m.removeClass("has-query"),C.focus({preventScroll:!0}),s.renderView(!0)}),s.searchQuery&&m.addClass("has-query"),m.addEventListener("click",()=>{e.addClass("csv-toolbar--search-expanded"),C.focus({preventScroll:!0})})}if(s.mode==="table"&&s.hasDateColumn()){let m=(p=s.fileCfg.sortNewestFirst)!=null?p:!0;n.createEl("button",{cls:`csv-cfg-btn ${m?"active":""}`,text:m?"\u2193 Newest":"\u2191 Oldest",title:"Toggle sort order"}).addEventListener("click",()=>{var C;let x=s.fileCfg;x.sortNewestFirst=!((C=x.sortNewestFirst)==null||C),s.saveFileCfg(x),s.tableSortCol=null,s.renderViewPreservingScroll()})}let a=()=>{var b,x;let m={title:s.resolveCol(Ye),category:s.resolveCol(Ge),status:s.resolveCol(qe),notes:s.resolveCol(Xe),image:s.resolveCol(Ke),anki:Ei(s)};new hn(s.app,s.headers,(x=(b=s.file)==null?void 0:b.path)!=null?x:"",s.fileCfg,s.autoDetectBooleanColumns(),s.autoDetectCategoricalColumns(),m,ci(s),C=>{s.saveFileCfg(C),C.defaultMode&&(s.mode=C.defaultMode),s.renderView()},()=>s.headers,()=>s.fileCfg,C=>s.addColumn(C),C=>s.removeColumn(C),C=>s.cleanupBooleanColumn(C)).open()},l=()=>br(s),c=()=>s.backupToArchive(),d=()=>yr(s);n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u2699 Config",title:"Configure this file's columns and views"}).addEventListener("click",a),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F4F1} Mobile",title:"Generate mobile dashboard with add form"}).addEventListener("click",l),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F4BE} Backup",title:"Copy this file to Archive/ with today's date"}).addEventListener("click",c),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F3B4} Anki",title:"Sync rows to Anki (needs Anki desktop + AnkiConnect)"}).addEventListener("click",d),n.createEl("button",{cls:"csv-add-btn",text:"+ Add"}).addEventListener("click",()=>s.openAddModal()),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-overflow",text:"\u22EF",title:"More actions"}).addEventListener("click",m=>{let b=new di.Menu;b.addItem(x=>x.setTitle("Config").setIcon("settings").onClick(a)),b.addItem(x=>x.setTitle("Mobile dashboard").setIcon("smartphone").onClick(l)),b.addItem(x=>x.setTitle("Backup").setIcon("save").onClick(c)),b.addItem(x=>x.setTitle("Sync to Anki").setIcon("layers").onClick(d)),b.addSeparator(),b.addItem(x=>x.setTitle("Built 2026-07-11 23:41").setIcon("info").setDisabled(!0)),b.showAtMouseEvent(m)}),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary csv-info-btn",text:"\u24D8",title:"Built 2026-07-11 23:41 \u2014 click to confirm"}).addEventListener("click",()=>new di.Notice("datadeck \u2014 built 2026-07-11 23:41",4e3))}function kg(s){return s&&typeof s=="object"&&"basename"in s?s:null}var wg=["Author","author","By","by","Source","source","Speaker","speaker","Artist","artist","Director","director"];async function rc(s,t,e,n){var x,C,E;let i=t.split(` +${_i}`}async function br(s){var c,d,h,u,f,g,p,m,b,x;if(!s.file)return;let t=(d=(c=s.file.parent)==null?void 0:c.path)!=null?d:"",e=t?`${t}/Mobile`:"Mobile";await s.app.vault.adapter.exists(e)||await s.app.vault.adapter.mkdir(e);let n=`${e}/${s.file.basename}.md`,i=s.file.path,o=s.getDateCol(),r=s.getCategoryCol(),a="../"+s.file.name,l;if(o){let C=s.getBooleanColumns();l=gr({filePath:a,csvPath:i,habitCols:C,labels:C.map(Et),dateCol:o})}else if(r){let C=(f=(u=(h=s.titleKey())!=null?h:s.resolveCol(["Quote","quote","Headline","headline","Phrase","phrase"]))!=null?u:s.headers[0])!=null?f:"Title";l=pr({filePath:a,csvPath:i,titleKey:C,categoryCol:r,statusCol:(g=s.getStatusCol())!=null?g:"Status",authorKey:(p=s.authorKey())!=null?p:"",yearCol:(m=s.resolveCol(["Year","year","Released","released"]))!=null?m:"",ratingCol:(b=s.resolveCol(["Rating","rating","Score","score","Stars","stars"]))!=null?b:"",themeCol:(x=s.resolveCol(["Theme","theme","Subgenre","subgenre","Mood","mood"]))!=null?x:"",compactGrid:s.titleKey()!==null})}else l=mr({filePath:a,csvPath:i,headers:s.headers});try{let C=s.app.vault.getAbstractFileByPath(n);C&&C instanceof Le.TFile?(await s.app.vault.modify(C,l),new Le.Notice(`Updated: ${n}`)):(await s.app.vault.create(n,l),new Le.Notice(`Created: ${n}`))}catch(C){let E=s.app.vault.getAbstractFileByPath(n);E instanceof Le.TFile&&(await s.app.vault.modify(E,l),new Le.Notice(`Updated: ${n}`))}}var ge=require("obsidian"),Kc="http://127.0.0.1:8765",Yc=6;async function vr(s,t){let e;try{e=await(0,ge.requestUrl)({url:Kc,method:"POST",contentType:"application/json",body:JSON.stringify({action:s,version:Yc,params:t}),throw:!1})}catch(i){throw new Error("Couldn't reach Anki. Is the desktop app open with the AnkiConnect add-on installed?")}let n=e.json;if(n.error)throw new Error(n.error);return n.result}function Ei(s){var t,e,n;return(n=(e=(t=s.titleKey())!=null?t:s.resolveCol(["Quote","Headline","Phrase","Term","Word","Question","Front","Name","Title"]))!=null?e:s.headers[0])!=null?n:null}function Gc(s){let t=s.fileCfg.ankiFrontCol;return t&&s.headers.includes(t)?t:Ei(s)}function Si(s){return s.replace(/&/g,"&").replace(//g,">")}function qc(s,t,e){return s.headers.filter(n=>{var i;return n!==e&&((i=t[n])!=null?i:"").trim()}).map(n=>`${Si(n)}: ${Si(t[n].trim())}`).join("
")}async function yr(s){if(!s.file)return;let t=Gc(s);if(!t){new ge.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 ge.Notice(`Nothing to sync \u2014 no rows with a "${t}" value.`,6e3);return}let i=new ge.Notice(`Syncing ${n.length} cards to Anki deck \u201C${e}\u201D\u2026`,0);try{await vr("createDeck",{deck:e});let o=n.map(c=>({deckName:e,modelName:"Basic",fields:{Front:Si(c[t].trim()),Back:qc(s,c,t)},options:{allowDuplicate:!1,duplicateScope:"deck"},tags:["datadeck"]})),r=await vr("addNotes",{notes:o}),a=r.filter(c=>c!=null).length,l=r.length-a;i.hide(),new ge.Notice(`Anki sync: ${a} added${l?`, ${l} already present`:""} (deck \u201C${e}\u201D).`,6e3)}catch(o){i.hide(),new ge.Notice(`Anki sync failed: ${o instanceof Error?o.message:String(o)}`,8e3)}}var Lo=null;async function _s(){if(Lo)return Lo;let s=await Promise.resolve().then(()=>(Gl(),Yl));return s.Chart.register(s.LineController,s.ScatterController,s.LineElement,s.PointElement,s.LinearScale,s.CategoryScale,s.Filler,s.Tooltip,s.Legend),Lo=s,s}var ql={pi:Math.PI,e:Math.E},Xl={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sqrt:Math.sqrt,log:Math.log10,ln:Math.log,exp:Math.exp,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,sign:Math.sign},Ao={min:Math.min,max:Math.max,pow:Math.pow,atan2:Math.atan2};function mg(s){let t=[],e=0;for(;e{var u;return(u=e[n])!=null?u:null},o=()=>{var u;return(u=e[n++])!=null?u:null};function r(){let u=a();for(;;){let f=i();if((f==null?void 0:f.kind)==="op"&&(f.op==="+"||f.op==="-")){n++;let g=a(),p=u;u=f.op==="+"?b=>p(b)+g(b):b=>p(b)-g(b)}else return u}}function a(){let u=l();for(;;){let f=i();if((f==null?void 0:f.kind)==="op"&&(f.op==="*"||f.op==="/"||f.op==="%")){n++;let g=l(),p=u,m=f.op;u=m==="*"?b=>p(b)*g(b):m==="/"?b=>p(b)/g(b):b=>p(b)%g(b)}else if(f&&(f.kind==="num"||f.kind==="ident"||f.kind==="lparen")){let g=l(),p=u;u=m=>p(m)*g(m)}else return u}}function l(){let u=i();if((u==null?void 0:u.kind)==="op"&&u.op==="-"){n++;let f=l();return g=>-f(g)}return(u==null?void 0:u.kind)==="op"&&u.op==="+"?(n++,l()):c()}function c(){let u=d(),f=i();if((f==null?void 0:f.kind)==="op"&&f.op==="^"){n++;let g=l();return p=>Math.pow(u(p),g(p))}return u}function d(){var f,g,p,m,b;let u=o();if(!u)throw new Error("Unexpected end of formula");if(u.kind==="num"){let x=u.value;return()=>x}if(u.kind==="lparen"){let x=r();if(((f=o())==null?void 0:f.kind)!=="rparen")throw new Error("Missing closing )");return x}if(u.kind==="ident"){if(u.name==="x")return C=>C;if(u.name in ql){let C=ql[u.name];return()=>C}let x=((g=i())==null?void 0:g.kind)==="lparen";if(u.name in Xl||u.name in Ao){if(!x)throw new Error(`${u.name} needs parentheses, e.g. ${u.name}(x)`);n++;let C=r();if(u.name in Ao){if(((p=o())==null?void 0:p.kind)!=="comma")throw new Error(`${u.name}(a, b) needs two arguments`);let S=r();if(((m=o())==null?void 0:m.kind)!=="rparen")throw new Error("Missing closing )");let y=Ao[u.name];return v=>y(C(v),S(v))}if(((b=o())==null?void 0:b.kind)!=="rparen")throw new Error("Missing closing )");let E=Xl[u.name];return S=>E(C(S))}throw new Error(`Unknown name "${u.name}" \u2014 use x, pi, e, or a function like sin()`)}throw new Error(`Unexpected "${u.kind==="op"?u.op:u.kind}"`)}let h=r();if(n{var o;let n=0,i=0;for(let r of t){let a=((o=r[e])!=null?o:"").trim();a&&(n++,Po(a)!==null&&i++)}return i>=2&&i/n>=.7})}function bg(s){let t=s.length;if(t<2)return null;let e=0,n=0,i=0,o=0,r=0;for(let f of s)e+=f.x,n+=f.y,i+=f.x*f.x,o+=f.x*f.y,r+=f.y*f.y;let a=t*i-e*e;if(a===0)return null;let l=(t*o-e*n)/a,c=(n-l*e)/t,d=n/t,h=0,u=0;for(let f of s){let g=f.y-(l*f.x+c);h+=g*g,u+=(f.y-d)*(f.y-d)}return{slope:l,intercept:c,r2:u===0?1:1-h/u}}function Ro(s){var n;let t=(n=s.ownerDocument.defaultView)==null?void 0:n.getComputedStyle(s),e=(i,o)=>(t==null?void 0:t.getPropertyValue(i).trim())||o;return{accent:e("--interactive-accent","#378ADD"),muted:e("--text-muted","#888888"),grid:e("--background-modifier-border","rgba(128,128,128,0.25)"),fitLine:e("--text-faint","#999999"),formula:e("--color-orange","#e0883a")}}var on=s=>{if(!Number.isFinite(s))return String(s);let t=Math.abs(s);return t!==0&&(t>=1e6||t<.001)?s.toExponential(2):String(Math.round(s*1e3)/1e3)},Zl=s=>{let t=new Date(s);return isNaN(t.getTime())?String(s):t.toISOString().slice(0,10)};function Oo(s,t){var d,h;let e=[],n=s.connect?[...s.points].sort((u,f)=>u.x-f.x):s.points;n.length&&e.push({type:s.connect?"line":"scatter",label:s.yLabel,data:n,backgroundColor:t.accent,borderColor:t.accent,borderWidth:1.5,pointRadius:s.connect?3:4,pointHoverRadius:6,tension:.3});let i=n.map(u=>u.x),o=n.length?Math.min(...i):(d=s.xMin)!=null?d:0,r=n.length?Math.max(...i):(h=s.xMax)!=null?h:10,a=null;if(s.fit==="linear"){let u=bg(n);if(u&&r>o){e.push({type:"line",label:"Best fit",data:[{x:o,y:u.slope*o+u.intercept},{x:r,y:u.slope*r+u.intercept}],borderColor:t.fitLine,borderDash:[6,4],borderWidth:1.5,pointRadius:0,pointHitRadius:0});let f=` \xB7 R\xB2 = ${(Math.round(u.r2*1e3)/1e3).toFixed(3)}`;if(s.xIsDate){let g=u.slope*864e5;a=`Trend: ${g>=0?"+":""}${on(g)} ${s.yLabel}/day${f}`}else{let g=u.intercept>=0?"+":"\u2212";a=`y = ${on(u.slope)}x ${g} ${on(Math.abs(u.intercept))}${f}`}}}let l=null;if(s.formula.trim())try{let u=Ql(s.formula),f=[],g=160;for(let p=0;p<=g;p++){let m=o+(r-o)*p/g,b=u(m);Number.isFinite(b)&&f.push({x:m,y:b})}f.length&&e.push({type:"line",label:s.formula.trim(),data:f,borderColor:t.formula,borderWidth:1.5,pointRadius:0,pointHitRadius:0,tension:0})}catch(u){l=u instanceof Error?u.message:String(u)}return{config:{type:"scatter",data:{datasets:e},options:{responsive:!0,maintainAspectRatio:!1,scales:{x:{type:"linear",title:{display:!s.xIsDate&&!!s.xLabel,text:s.xLabel,color:t.muted},ticks:{color:t.muted,...s.xIsDate?{callback:u=>Zl(Number(u)),maxTicksLimit:8}:{}},grid:{color:t.grid}},y:{title:{display:!!s.yLabel,text:s.yLabel,color:t.muted},ticks:{color:t.muted},grid:{color:t.grid}}},plugins:{legend:{display:e.length>1,labels:{color:t.muted,boxWidth:12}},tooltip:{callbacks:{label:u=>{let f=u.raw,g=s.xIsDate?Zl(f.x):on(f.x);return`${f.label?`${f.label}: `:""}(${g}, ${on(f.y)})`}}}}}},fitText:a,formulaError:l}}var ii="(row number)";function Fo(s,t,e,n,i,o){let r=[],a=0;return s.forEach((l,c)=>{var u,f,g;let d=Po((u=l[e])!=null?u:""),h;if(t===ii)h=c+1;else if(n){let p=i((f=l[t])!=null?f:"");h=p?p.getTime():null}else h=Po((g=l[t])!=null?g:"");if(h===null||d===null){a++;return}r.push({x:h,y:d,label:o(l)})}),{points:r,skipped:a}}function ri(s){return s.rows.length>=2&&oi(s.headers,s.rows).length>=1}async function Jl(s,t){var L,I;let e=s.getFilteredRows(),n=oi(s.headers,s.rows);if(!n.length){t.createEl("p",{text:"No numeric column to chart.",cls:"csv-empty-state"});return}s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Chart over ${e.length} of ${s.rows.length} entries`});let i=s.fileCfg,o=s.getDateCol(),r=[...o?[o]:[],...n.filter(P=>P!==o),ii],a=i.chartXCol&&r.includes(i.chartXCol)?i.chartXCol:r[0],l=n,c=i.chartYCol&&l.includes(i.chartYCol)?i.chartYCol:(L=l.find(P=>P!==a))!=null?L:l[0],d=i.chartFit==="linear"?"linear":"none",h=(I=i.chartFormula)!=null?I:"",u=t.createDiv({cls:"csv-chart-view"}),f=u.createDiv({cls:"csv-chart-controls"}),g=P=>{s.saveFileCfg({...s.fileCfg,...P}),s.renderViewPreservingScroll()},p=(P,R,D,W)=>{let O=f.createDiv({cls:"csv-chart-control"});O.createSpan({cls:"csv-chart-control-label",text:P});let j=O.createEl("select",{cls:"csv-chart-select",attr:{"aria-label":P}});return R.forEach($=>{let A=j.createEl("option",{text:$,value:$});$===D&&(A.selected=!0)}),j.addEventListener("change",()=>W(j.value)),j};p("X",r,a,P=>g({chartXCol:P})),p("Y",l,c,P=>g({chartYCol:P})),f.createEl("button",{cls:`csv-cfg-btn csv-chart-fit-btn ${d==="linear"?"active":""}`,text:"Best fit",title:"Toggle a least-squares fit line"}).addEventListener("click",()=>g({chartFit:d==="linear"?"none":"linear"}));let b=f.createDiv({cls:"csv-chart-control csv-chart-formula-wrap"});b.createSpan({cls:"csv-chart-control-label",text:"y ="});let x=b.createEl("input",{cls:"csv-chart-formula-input",type:"text",value:h,placeholder:"overlay, e.g. 2x + 1",attr:{spellcheck:"false",autocomplete:"off",enterkeyhint:"done"}}),C=()=>{x.value.trim()!==h.trim()&&g({chartFormula:x.value})};x.addEventListener("change",C),x.addEventListener("keydown",P=>{P.key==="Enter"&&(P.preventDefault(),x.blur())});let E=a!==ii&&(a===o||s.isDateCol(a)),{points:S,skipped:y}=Fo(e,a,c,E,P=>s.parseDate(P),P=>s.getTitle(P)),v=u.createDiv({cls:"csv-chart-wrap"}),_=v.createEl("canvas",{cls:"csv-chart-canvas"}),w=u.createDiv({cls:"csv-chart-footer"});if(!S.length){v.remove(),w.remove(),u.createEl("p",{text:`No rows with both "${a}" and "${c}" values to plot.`,cls:"csv-empty-state"});return}let k=Oo({points:S,xIsDate:E,xLabel:a===ii?"row":a,yLabel:c,connect:E,fit:d,formula:h},Ro(t));k.fitText&&w.createSpan({cls:"csv-chart-fit-text",text:k.fitText}),k.formulaError&&w.createSpan({cls:"csv-chart-formula-error",text:`formula: ${k.formulaError}`}),y>0&&w.createSpan({cls:"csv-chart-skipped",text:`${y} row${y===1?"":"s"} skipped (no numeric value)`}),s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:M}=await _s();_.isConnected&&(s.chartInstance=new M(_,k.config))}function ai(s){return s.resolveCol(["Type","type","Kind","kind","Item","item"])}function Vo(s){var t;return(t=s.resolveCol(["Project","project","Projects","projects","Area","area"]))!=null?t:$t(s)}function sc(s){return s.resolveCol(["Due","due","Deadline","deadline","Due Date","Due date","due date"])}function li(s){return s.resolveCol(["Priority","priority","Prio","prio","Importance","importance"])}var vg=["task","todo","to-do","action",""],yg=["task","todo","to-do","action","note","idea","reference","ref"],nc=["done","complete","completed","finished","closed","resolved","yes","x","\u2713","true"],xg={high:0,med:1,medium:1,normal:1,low:2};function Ss(s){if(sc(s)||li(s))return!0;let t=ai(s);return t?s.rows.some(e=>{var n;return yg.includes(((n=e[t])!=null?n:"").trim().toLowerCase())}):!1}function Io(s,t,e){var n;return e?nc.includes(((n=t[e])!=null?n:"").trim().toLowerCase()):!1}function tc(s){let t=xg[(s!=null?s:"").trim().toLowerCase()];return t===void 0?3:t}function ec(s){return(s!=null?s:"").trim()?0:1}function Cg(){return new Date().toISOString().slice(0,10)}function _g(s,t){let e=new Map;s.rows.forEach(o=>{var a,l;let r=((a=o[t])!=null?a:"").trim();r&&nc.includes(r.toLowerCase())&&e.set(r,((l=e.get(r))!=null?l:0)+1)});let n="done",i=0;return e.forEach((o,r)=>{o>i&&(n=r,i=o)}),n}function ic(s,t){var T,k;let e=Vo(s),n=ai(s),i=s.getStatusCol(),o=sc(s),r=li(s),a=(T=s.titleKey())!=null?T:s.headers[0],l=t.createDiv({cls:"csv-library-filters"}),c=new Set;e&&s.rows.forEach(M=>{var L;((L=M[e])!=null?L:"").split(",").map(I=>I.trim()).filter(Boolean).forEach(I=>c.add(I))});let d=l.createEl("select",{cls:"csv-library-filter-select"});d.createEl("option",{text:e?"All projects":"All",value:"all"}),Array.from(c).sort().forEach(M=>d.createEl("option",{text:M,value:M})),d.value=s.taskProjectFilter;let h=new Set;n&&s.rows.forEach(M=>{var I;let L=((I=M[n])!=null?I:"").trim();L&&h.add(L)});let u=null;h.size>0&&(u=l.createEl("select",{cls:"csv-library-filter-select"}),u.createEl("option",{text:"All types",value:"all"}),Array.from(h).sort().forEach(M=>u.createEl("option",{text:M,value:M})),u.value=s.taskTypeFilter);let f=()=>{s.taskProjectFilter=d.value,u&&(s.taskTypeFilter=u.value),s.renderView(!0)};d.addEventListener("change",f),u==null||u.addEventListener("change",f);let g=s.searchQuery.toLowerCase().trim(),p=s.rows.filter(M=>{var L,I;return!(s.taskProjectFilter!=="all"&&e&&!((L=M[e])!=null?L:"").split(",").map(R=>R.trim().toLowerCase()).includes(s.taskProjectFilter.toLowerCase())||s.taskTypeFilter!=="all"&&n&&((I=M[n])!=null?I:"").trim().toLowerCase()!==s.taskTypeFilter.toLowerCase()||g&&!s.headers.some(P=>{var R;return((R=M[P])!=null?R:"").toLowerCase().includes(g)}))});(s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"||g)&&t.createDiv({cls:"csv-library-result-count",text:`Showing ${p.length} of ${s.rows.length} entries`});let m={},b=M=>{var I;return e&&((I=M[e])!=null?I:"").split(",").map(P=>P.trim()).filter(Boolean)[0]||"\u2014"};p.forEach(M=>{var R,D,W;let L=n?((R=M[n])!=null?R:"").trim():"",I=vg.includes(L.toLowerCase())?"Tasks":L,P=b(M);m[I]||(m[I]={}),((W=(D=m[I])[P])!=null?W:D[P]=[]).push(M)});let x=t.createDiv({cls:"csv-tasks"}),C=Cg(),E=i?_g(s,i):"done",y=((k=s.fileCfg.cardFields)!=null?k:s.headers).filter(M=>M!==e&&M!==n&&M!==i),v=[];i&&v.push({name:"",cls:"csv-tasks-check-cell"}),y.forEach(M=>{let L="";M===a?L="csv-tasks-name-cell":M===o?L="csv-tasks-due":M===r?L="csv-tasks-priority":s.isNotesCol(M)?L="csv-tasks-generic-cell csv-tasks-notes-cell":L="csv-tasks-generic-cell",v.push({name:M,cls:L})});let _=(M,L)=>{L.sort((I,P)=>{var W,O,j,$,A,z;let R=Io(s,I,i),D=Io(s,P,i);if(R!==D)return R?1:-1;if(r){let G=tc((W=I[r])!=null?W:"")-tc((O=P[r])!=null?O:"");if(G)return G}if(o){let G=ec((j=I[o])!=null?j:"")-ec(($=P[o])!=null?$:"");if(G)return G;let B=((A=I[o])!=null?A:"").localeCompare((z=P[o])!=null?z:"");if(B)return B}return s.getTitle(I).localeCompare(s.getTitle(P))}),L.forEach(I=>{let P=Io(s,I,i),R=M.createEl("tr");if(i){let W=R.createEl("td",{cls:"csv-tasks-check-cell"}).createEl("span",{cls:`csv-tasks-check ${P?"is-done":""}`,text:P?"\u2713":""});W.setAttr("title",P?"Mark not done":"Mark done"),W.addEventListener("click",O=>{O.stopPropagation(),I[i]=P?"":E,s.scheduleSave(),s.renderView(!0)})}y.forEach(D=>{var W,O,j;if(D===a)Eg(s,R,I,a,P);else if(D===o){let $=R.createEl("td",{cls:"csv-tasks-due csv-tasks-editable"}),A=o?((W=I[o])!=null?W:"").slice(0,10):"";$.setText(A||"\u2014"),A&&!P&&A{var G;A.stopPropagation();let z=Array.from(new Set([...s.getColumnValues(r),"high","medium","low"]));Ft($,(G=I[r])!=null?G:"",z,B=>{I[r]=B,s.scheduleSave(),s.renderView(!0)},s.contentEl)})}else if(s.isNotesCol(D)){let $=((O=I[D])!=null?O:"").replace(/#{1,6}\s/g,"").replace(/[*_>`]/g,"").replace(/\n+/g," ").trim(),A=$?$.length>50?$.slice(0,48)+"\u2026":$:"\u2014",z=R.createEl("td",{text:A,cls:"csv-tasks-generic-cell csv-tasks-notes-cell csv-tasks-editable"});Ps(s,z,I,D)}else{let $=(j=I[D])!=null?j:"",A=$.length>40?$.slice(0,38)+"\u2026":$,z=R.createEl("td",{text:A||"\u2014",cls:"csv-tasks-generic-cell csv-tasks-editable"});Ps(s,z,I,D)}}),R.addEventListener("contextmenu",D=>s.openRowContextMenu(I,D))})},w=Object.keys(m).sort((M,L)=>M==="Tasks"?-1:L==="Tasks"?1:M.localeCompare(L));if(w.forEach(M=>{Sg(s,x,M==="Tasks"?M:Et(M),m[M],_,v)}),w.length===0){let M=x.createDiv({cls:"csv-empty-state"});M.createEl("p",{text:g||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all"?"No entries match your filters.":"No tasks yet."}),(g||s.taskProjectFilter!=="all"||s.taskTypeFilter!=="all")&&M.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear filters"}).addEventListener("click",()=>{s.taskProjectFilter="all",s.taskTypeFilter="all",s.searchQuery="",s.renderView()})}}function Sg(s,t,e,n,i,o){if(Object.keys(n).length===0)return;t.createDiv({cls:"csv-tasks-section-header",text:e});let r=t.createDiv({cls:"csv-tasks-section"});Object.keys(n).sort().forEach(a=>{let l=n[a],c=r.createEl("details",{cls:"csv-tasks-group"});c.open=!0;let d=c.createEl("summary",{cls:"csv-tasks-group-header"});d.innerHTML=`\u25B6 ${a} ${l.length}`;let u=c.createDiv({cls:"csv-tasks-table-wrapper"}).createEl("table",{cls:"csv-tasks-table"}),f=120;o.forEach(b=>{b.cls.includes("check-cell")?f+=30:b.cls.includes("priority")?f+=90:b.cls.includes("due")?f+=150:b.cls.includes("notes-cell")?f+=140:b.cls.includes("generic-cell")&&(f+=150)}),u.style.minWidth=`${f}px`;let p=u.createEl("thead").createEl("tr");o.forEach(b=>p.createEl("th",{text:b.name,cls:b.cls}));let m=u.createEl("tbody");i(m,l)})}function Eg(s,t,e,n,i){var h;let o=t.createEl("td",{cls:"csv-tasks-name-cell"}),r=(h=s.isHighlighted)!=null&&h.call(s,e)?"csv-title-highlight":"",a=o.createSpan({cls:`csv-tasks-link ${i?"csv-tasks-done":""} ${r}`,text:e[n]||"Untitled"}),l=s.getNotesCol();a.addEventListener("click",()=>{l?s.openNoteExpander(e,l):s.openOrCreateNotes(e)});let c=s.notesFileExists(e),d=o.createEl("button",{cls:`csv-tasks-page-icon ${c?"exists":""}`,text:c?"\u{1F4C4}":"+"});d.setAttr("title",c?"Open page":"Create page"),d.addEventListener("click",u=>{u.stopPropagation(),s.openOrCreateNotes(e)})}function ci(s){let t=[];return s.isTravelFile()&&t.push({id:"travel",label:"Travel"}),s.hasDateColumn()&&t.push({id:"dashboard",label:"Dashboard"}),Ss(s)&&t.push({id:"tasks",label:"Tasks"}),$t(s)&&(t.push({id:"library",label:"Cards"}),t.push({id:"kanban-genre",label:"Kanban"})),t.push({id:"table",label:"Table"}),s.rows.length>0&&t.push({id:"focus",label:"Focus"}),bn(s)&&t.push({id:"stats",label:"Stats"}),ri(s)&&t.push({id:"chart",label:"Chart"}),t}function oc(s,t){var f,g,p;let e=t.createDiv({cls:"csv-toolbar"});e.createDiv({cls:"csv-toolbar-title",text:(g=(f=s.file)==null?void 0:f.basename)!=null?g:""});let n=e.createDiv({cls:"csv-toolbar-controls"});n.createDiv({cls:"csv-row-count",text:`${s.rows.length} entries`});let i=n.createDiv({cls:"csv-mode-group"}),o=ci(s),r=i.createEl("select",{cls:"csv-mode-select",attr:{"aria-label":"View mode"}});if(o.forEach(({id:m,label:b})=>{let x=r.createEl("option",{text:b,value:m});s.mode===m&&(x.selected=!0)}),r.addEventListener("change",()=>{s.mode=r.value,s.renderView()}),s.mode!=="dashboard"){let m=n.createEl("button",{cls:"csv-cfg-btn csv-search-toggle",text:"\u{1F50D}",title:"Search"}),b=n.createDiv({cls:"csv-search-wrap"}),x=b.createDiv({cls:"csv-search-input-wrap"}),C=x.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search...",value:s.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),E=x.createEl("button",{cls:"csv-search-clear",text:"\xD7",title:"Clear search"});E.toggleClass("is-hidden",!s.searchQuery),b.createEl("button",{cls:"csv-search-done",text:"Done",title:"Dismiss keyboard"}).addEventListener("click",v=>{if(v.preventDefault(),!C.value){e.removeClass("csv-toolbar--search-expanded"),m.removeClass("has-query"),s.searchQuery="",s.renderView(!0);return}C.blur()});let y=null;C.addEventListener("input",v=>{s.searchQuery=v.target.value,E.toggleClass("is-hidden",!s.searchQuery),m.toggleClass("has-query",!!s.searchQuery),y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>{y=null,s.renderView(!0)},120)}),C.addEventListener("keydown",v=>{v.key==="Enter"&&(v.preventDefault(),C.blur())}),E.addEventListener("click",()=>{s.searchQuery="",C.value="",E.addClass("is-hidden"),m.removeClass("has-query"),C.focus({preventScroll:!0}),s.renderView(!0)}),s.searchQuery&&m.addClass("has-query"),m.addEventListener("click",()=>{e.addClass("csv-toolbar--search-expanded"),C.focus({preventScroll:!0})})}if(s.mode==="table"&&s.hasDateColumn()){let m=(p=s.fileCfg.sortNewestFirst)!=null?p:!0;n.createEl("button",{cls:`csv-cfg-btn ${m?"active":""}`,text:m?"\u2193 Newest":"\u2191 Oldest",title:"Toggle sort order"}).addEventListener("click",()=>{var C;let x=s.fileCfg;x.sortNewestFirst=!((C=x.sortNewestFirst)==null||C),s.saveFileCfg(x),s.tableSortCol=null,s.renderViewPreservingScroll()})}let a=()=>{var b,x;let m={title:s.resolveCol(Ye),category:s.resolveCol(Ge),status:s.resolveCol(qe),notes:s.resolveCol(Xe),image:s.resolveCol(Ke),anki:Ei(s)};new hn(s.app,s.headers,(x=(b=s.file)==null?void 0:b.path)!=null?x:"",s.fileCfg,s.autoDetectBooleanColumns(),s.autoDetectCategoricalColumns(),m,ci(s),C=>{s.saveFileCfg(C),C.defaultMode&&(s.mode=C.defaultMode),s.renderView()},()=>s.headers,()=>s.fileCfg,C=>s.addColumn(C),C=>s.removeColumn(C),C=>s.cleanupBooleanColumn(C)).open()},l=()=>br(s),c=()=>s.backupToArchive(),d=()=>yr(s);n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u2699 Config",title:"Configure this file's columns and views"}).addEventListener("click",a),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F4F1} Mobile",title:"Generate mobile dashboard with add form"}).addEventListener("click",l),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F4BE} Backup",title:"Copy this file to Archive/ with today's date"}).addEventListener("click",c),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary",text:"\u{1F3B4} Anki",title:"Sync rows to Anki (needs Anki desktop + AnkiConnect)"}).addEventListener("click",d),n.createEl("button",{cls:"csv-add-btn",text:"+ Add"}).addEventListener("click",()=>s.openAddModal()),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-overflow",text:"\u22EF",title:"More actions"}).addEventListener("click",m=>{let b=new di.Menu;b.addItem(x=>x.setTitle("Config").setIcon("settings").onClick(a)),b.addItem(x=>x.setTitle("Mobile dashboard").setIcon("smartphone").onClick(l)),b.addItem(x=>x.setTitle("Backup").setIcon("save").onClick(c)),b.addItem(x=>x.setTitle("Sync to Anki").setIcon("layers").onClick(d)),b.addSeparator(),b.addItem(x=>x.setTitle("Built 2026-07-11 23:42").setIcon("info").setDisabled(!0)),b.showAtMouseEvent(m)}),n.createEl("button",{cls:"csv-cfg-btn csv-cfg-btn-secondary csv-info-btn",text:"\u24D8",title:"Built 2026-07-11 23:42 \u2014 click to confirm"}).addEventListener("click",()=>new di.Notice("datadeck \u2014 built 2026-07-11 23:42",4e3))}function kg(s){return s&&typeof s=="object"&&"basename"in s?s:null}var wg=["Author","author","By","by","Source","source","Speaker","speaker","Artist","artist","Director","director"];async function rc(s,t,e,n){var x,C,E;let i=t.split(` `).map(S=>S.trim()).filter(Boolean),o=S=>{var y,v;return(v=(y=i.find(_=>_.startsWith(S+":")))==null?void 0:y.slice(S.length+1).trim())!=null?v:""},r=o("file");if(!r){e.createEl("p",{text:"Error: No file specified. Use: file: yourfile.csv",cls:"csv-add-error"});return}let a=s.vault.getAbstractFileByPath(n.sourcePath),l=(C=(x=a==null?void 0:a.parent)==null?void 0:x.path)!=null?C:"",c=ue(r,l),d=kg(s.vault.getAbstractFileByPath(c));if(!d){e.createEl("p",{text:`Error: File not found: ${c}`,cls:"csv-add-error"});return}let h=[],u=[];try{let S=Nt(await s.vault.read(d));h=S.headers,u=S.rows}catch(S){e.createEl("p",{text:`Error reading file: ${S}`,cls:"csv-add-error"});return}if(!u.length){e.createEl("p",{text:"No entries in file.",cls:"csv-add-error"});return}let f=o("field"),g=(E=h.find(S=>S.toLowerCase()===f.toLowerCase()))!=null?E:h[0],p=wg.map(S=>h.find(y=>y===S)).find(Boolean),m=e.createDiv({cls:"csv-random-card"}),b=()=>{var k;m.empty();let S=u.filter(M=>{var L;return((L=M[g])!=null?L:"").trim()}),y=S.length?S:u,v=y[Math.floor(Math.random()*y.length)];m.createDiv({cls:"csv-random-text",text:v[g]||"\u2014"});let _=p?((k=v[p])!=null?k:"").trim():"";_&&m.createDiv({cls:"csv-random-sub",text:`\u2014 ${_}`});let w=m.createDiv({cls:"csv-random-foot"});w.createSpan({cls:"csv-random-src",text:d.basename}),w.createEl("button",{cls:"csv-random-btn",text:"\u21BB",title:"Another one"}).addEventListener("click",b)};b()}async function ac(s,t){var A,z,G;let e=s.getDateCol();if(!e){t.createEl("p",{text:"No date column detected.",cls:"csv-empty-state"});return}let n=s.getBooleanColumns(),i=s.getNotesCol(),o=s.formatDate(new Date),r=[...s.rows].sort((B,F)=>{var N,H;return((N=B[e])!=null?N:"").localeCompare((H=F[e])!=null?H:"")});s.selectedDate||(s.selectedDate=o);let a=r.find(B=>B[e]===s.selectedDate),l=s.selectedDate===o;t.addClass("csv-dashboard");let c=[...new Set([...r.map(B=>B[e]),o])].filter(Boolean).sort(),d=t.createDiv({cls:"csv-dash-nav"});d.createEl("button",{cls:"csv-dash-nav-btn csv-dash-back-btn",text:"\u25C0"}).addEventListener("click",()=>{let B=c.indexOf(s.selectedDate);if(B>0)s.selectedDate=c[B-1],s.renderView();else if(B===-1&&c.length>0){let F=c.filter(N=>N0&&(s.selectedDate=F[F.length-1],s.renderView())}});let u=d.createDiv({cls:"csv-dash-date"});l&&u.createSpan({cls:"csv-dash-today-dot"});let f=u.createEl("select",{cls:"csv-dash-date-select"});if(c.forEach(B=>{let F=f.createEl("option",{text:B,value:B});B===s.selectedDate&&(F.selected=!0)}),f.addEventListener("change",()=>{s.selectedDate=f.value,s.renderView()}),d.createEl("button",{cls:"csv-dash-nav-btn",text:"\u25B6"}).addEventListener("click",()=>{let B=c.indexOf(s.selectedDate);if(B>=0&&BN>s.selectedDate);F.length>0&&(s.selectedDate=F[0],s.renderView())}}),l||d.createEl("button",{cls:"csv-dash-today-btn",text:"Today"}).addEventListener("click",()=>{s.selectedDate=o,s.renderView()}),!a){let B=t.createDiv({cls:"csv-dash-add-section"});B.createEl("p",{text:`No entry for ${s.selectedDate}`}),B.createEl("button",{cls:"csv-dash-add-btn",text:`+ Add entry for ${s.selectedDate}`}).addEventListener("click",()=>{let N={};s.headers.forEach(H=>N[H]=""),N[e]=s.selectedDate,s.rows.push(N),s.scheduleSave(),s.renderView()})}if(a){let B=t.createDiv({cls:"csv-dash-habits"});B.createEl("h3",{text:s.selectedDate===o?"Today":s.selectedDate,cls:"csv-dash-section-title"});let F=B.createDiv({cls:"csv-dash-habits-grid"});n.forEach(H=>{let V=s.isTruthy(a[H]),K=F.createDiv({cls:`csv-dash-habit ${V?"checked":""}`}),Y=K.createEl("button",{cls:"csv-dash-habit-check",text:V?"\u25CF":"\u25CB"});K.createSpan({cls:"csv-dash-habit-label",text:H}),Y.addEventListener("click",()=>{a[H]=V?"0":"1",s.scheduleSave(),s.renderViewPreservingScroll()})});let N=n.filter(H=>s.isTruthy(a[H])).length;if(B.createDiv({cls:"csv-dash-habits-count",text:`${N} of ${n.length} complete`}),i&&((A=a[i])!=null&&A.trim())){let H=B.createDiv({cls:"csv-dash-notes-preview"});H.createEl("strong",{text:"Notes: "}),H.createSpan({text:a[i].slice(0,200)+(a[i].length>200?"\u2026":"")})}}let p=t.createDiv({cls:"csv-dash-chart-section"});p.createEl("h3",{text:"Progress",cls:"csv-dash-section-title"});let b=p.createDiv({cls:"csv-dash-chart-wrap"}).createEl("canvas",{cls:"csv-dash-chart"}),x=r.map(B=>{var N;return((N=B[e])!=null?N:"").slice(5)}),C=r.map(B=>n.filter(F=>s.isTruthy(B[F])).length);s.chartInstance&&(s.chartInstance.destroy(),s.chartInstance=null);let{Chart:E}=await _s();if(!b.isConnected)return;s.chartInstance=new E(b,{type:"line",data:{labels:x,datasets:[{label:"Habits done",data:C,borderColor:"#378ADD",backgroundColor:"rgba(55,138,221,0.08)",borderWidth:1.5,pointRadius:3,tension:.3,fill:!0}]},options:{responsive:!0,maintainAspectRatio:!1,scales:{y:{min:0,max:n.length||8,ticks:{stepSize:1}}},plugins:{tooltip:{enabled:!0}}}});let S=t.createDiv({cls:"csv-dash-stats-section"});S.createEl("h3",{text:"Stats",cls:"csv-dash-section-title"});let y=r.length,v=r.reduce((B,F)=>B+n.filter(N=>s.isTruthy(F[N])).length,0),_=y>0?(v/y).toFixed(1):"0",w=r.filter(B=>n.every(F=>s.isTruthy(B[F]))).length,T=0,k=0,M=null;for(let B of r){let F=n.filter(V=>s.isTruthy(B[V])).length,N=s.parseDate((z=B[e])!=null?z:""),H=!0;M&&N&&Math.round((N.getTime()-M.getTime())/864e5)!==1&&(H=!1),F>=1&&(H||M===null)?(k++,k>T&&(T=k)):F>=1?(k=1,k>T&&(T=k)):k=0,M=N}let L=0,I=new Date;I.setHours(0,0,0,0);let P=I;for(let B=r.length-1;B>=0;B--){let F=s.parseDate((G=r[B][e])!=null?G:"");if(!F)break;let N=Math.round((P.getTime()-F.getTime())/(1e3*60*60*24));if(L===0&&N>1||L>0&&N!==1)break;if(n.filter(V=>s.isTruthy(r[B][V])).length>=1)L++,P=F;else break}let R=S.createDiv({cls:"csv-dash-stats-bar"});R.innerHTML=`${y} days logged \xB7 ${_} avg/day \xB7 ${w} perfect days \xB7 current streak ${L}d \xB7 best streak ${T}d`;let W=t.createDiv({cls:"csv-dash-cards-section"}).createDiv({cls:"csv-dash-cards-grid"}),O=new Date().getFullYear(),j={language:"\u25CB",read:"\u2261",gym:"\u229E",vitamins:"\u2299",cardio:"\u2191",meditate:"\u25CE",challenge:"\u273F",journal:"\u270E",exercise:"\u229E",water:"\u{1F4A7}",sleep:"\u{1F319}",study:"\u{1F4DA}"};n.map(B=>{let F=r.filter(Y=>s.isTruthy(Y[B])),N=F.length>0?F[F.length-1][e]:null,H=new Set;F.forEach(Y=>{var X;let q=s.parseDate((X=Y[e])!=null?X:"");q&&H.add(q.getFullYear())});let V=r.filter(Y=>{var X;let q=s.parseDate((X=Y[e])!=null?X:"");return q&&q.getFullYear()===O}),K=V.filter(Y=>s.isTruthy(Y[B])).length;return{habit:B,doneCount:F.length,doneThisYear:K,totalThisYear:V.length,lastDone:N,years:Array.from(H).sort()}}).sort((B,F)=>!B.lastDone&&!F.lastDone?0:B.lastDone?F.lastDone?F.lastDone.localeCompare(B.lastDone):-1:1).forEach(({habit:B,doneCount:F,doneThisYear:N,totalThisYear:H,lastDone:V,years:K})=>{var st;let Y=W.createDiv({cls:"csv-dash-habit-card"}),q=(st=j[B.toLowerCase()])!=null?st:"\u25CB",X=Y.createDiv({cls:"csv-dash-habit-card-header"});if(X.createSpan({cls:"csv-dash-habit-icon",text:q}),X.createSpan({cls:"csv-dash-habit-card-name",text:Et(B)}),K.length>0&&Y.createDiv({cls:"csv-dash-habit-years"}).setText(K.join(" \xB7 ")),Y.createDiv({cls:"csv-dash-habit-card-thisyear",text:`${N} of ${H} complete this year`}),Y.createDiv({cls:"csv-dash-habit-card-alltime",text:`${F} of ${y} all time`}),V){let lt=s.parseDate(V),Wt=lt?lt.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):V;Y.createDiv({cls:"csv-dash-habit-card-last",text:`Last logged: ${Wt}`})}else Y.createDiv({cls:"csv-dash-habit-card-last",text:"Never logged"});let Z=y>0?F/y*100:0,Q=Y.createDiv({cls:"csv-dash-habit-progress"}).createDiv({cls:"csv-dash-habit-progress-bar"});Q.style.width=`${Z}%`,Y.addEventListener("click",()=>{s.selectedHabit=s.selectedHabit===B?null:B,s.renderViewPreservingScroll()}),s.selectedHabit===B&&Y.addClass("selected")}),s.selectedHabit&&n.includes(s.selectedHabit)&&Dg(s,t,r,e,s.selectedHabit)}function Dg(s,t,e,n,i){var T,k,M;let o=t.createDiv({cls:"csv-dash-timeline-section"}),r=o.createDiv({cls:"csv-dash-timeline-header"});r.createEl("h3",{text:`${Et(i)} Timeline`,cls:"csv-dash-section-title"});let a=r.createEl("select",{cls:"csv-dash-year-select"}),l=new Set;e.forEach(L=>{var P;let I=s.parseDate((P=L[n])!=null?P:"");I&&l.add(I.getFullYear())}),l.add(new Date().getFullYear()),Array.from(l).sort().reverse().forEach(L=>{let I=a.createEl("option",{text:String(L),value:String(L)});L===s.timelineYear&&(I.selected=!0)}),a.addEventListener("change",()=>{s.timelineYear=parseInt(a.value),s.renderViewPreservingScroll()}),r.createEl("button",{cls:"csv-dash-timeline-close",text:"\u2715"}).addEventListener("click",()=>{s.selectedHabit=null,s.renderViewPreservingScroll()});let d=new Map;e.forEach(L=>{var I;d.set((I=L[n])!=null?I:"",s.isTruthy(L[i]))});let h=o.createDiv({cls:"csv-dash-timeline-grid-wrap"}),u=h.createDiv({cls:"csv-dash-timeline-months"});["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].forEach(L=>u.createSpan({cls:"csv-dash-timeline-month-label",text:L}));let g=h.createDiv({cls:"csv-dash-timeline-calendar"}),p=g.createDiv({cls:"csv-dash-timeline-day-labels"});for(let L=1;L<=31;L++)p.createDiv({cls:"csv-dash-timeline-day-label",text:L%5===0||L===1?String(L):""});for(let L=0;L<12;L++){let I=g.createDiv({cls:"csv-dash-timeline-month-col"}),P=new Date(s.timelineYear,L+1,0).getDate();for(let R=1;R<=31;R++){if(R>P){I.createDiv({cls:"csv-dash-timeline-cell empty"});continue}let D=`${s.timelineYear}-${String(L+1).padStart(2,"0")}-${String(R).padStart(2,"0")}`,W=(T=d.get(D))!=null?T:!1,O=d.has(D),j=new Date(s.timelineYear,L,R)>new Date,$=I.createDiv({cls:`csv-dash-timeline-cell ${j?"future":""} ${W?"done":""} ${O&&!W?"missed":""} ${!O&&!j?"no-entry":""}`});$.title=`${D}: ${j?"Future":W?"\u2713 Done":O?"\u2717 Missed":"No entry"}`}}let m=e.filter(L=>{var P;let I=s.parseDate((P=L[n])!=null?P:"");return I&&I.getFullYear()===s.timelineYear}),b=m.filter(L=>s.isTruthy(L[i])).length,x=m.length,C=0,E=0,S=0,y=null;for(let L of e){let I=s.isTruthy(L[i]),P=s.parseDate((k=L[n])!=null?k:""),R=!0;y&&P&&Math.round((P.getTime()-y.getTime())/864e5)!==1&&(R=!1),I&&(R||y===null)?(S++,S>E&&(E=S)):I?S=1:S=0,y=P}let v=new Date;v.setHours(0,0,0,0);let _=v;for(let L=e.length-1;L>=0;L--){let I=s.parseDate((M=e[L][n])!=null?M:"");if(!I)break;let P=Math.round((_.getTime()-I.getTime())/(1e3*60*60*24));if(C===0&&P>1||C>0&&P!==1)break;if(s.isTruthy(e[L][i]))C++,_=I;else break}let w=o.createDiv({cls:"csv-dash-timeline-stats"});w.innerHTML=`${b} of ${x} in ${s.timelineYear} \xB7 current streak ${C}d \xB7 best streak ${E}d`}function lc(s,t){var x,C,E;let e=s.getFilteredRows();if(s.searchQuery.trim()&&t.createDiv({cls:"csv-search-results",text:`Found ${e.length} of ${s.rows.length} entries`}),!e.length){let S=t.createDiv({cls:"csv-empty-state"});S.createEl("p",{text:s.searchQuery?"No matching entries found.":"No entries yet."}),s.searchQuery&&S.createEl("button",{cls:"csv-clear-filters-btn",text:"Clear search"}).addEventListener("click",()=>{s.searchQuery="",s.renderView()});return}s.focusIndex>=e.length&&(s.focusIndex=e.length-1),s.focusIndex<0&&(s.focusIndex=0);let n=e[s.focusIndex],i=(x=s.titleKey())!=null?x:s.headers[0],o=s.getNotesCol(),r=s.authorKey(),a=t.createDiv({cls:"csv-focus-wrap",attr:{tabindex:"0"}}),l=S=>{s.focusIndex=(S%e.length+e.length)%e.length,s.focusNavPending=!0,s.renderView(!0)},c=a.createDiv({cls:"csv-focus-card"});c.createDiv({cls:"csv-focus-position",text:`${s.focusIndex+1} / ${e.length}`});let d=c.createDiv({cls:`csv-focus-title ${(C=s.isHighlighted)!=null&&C.call(s,n)?"csv-title-highlight":""}`,text:s.getTitle(n)});o&&(d.addClass("is-clickable"),d.title="Open entry",d.addEventListener("click",()=>s.openNoteExpander(n,o)));let h=s.getSubtitle(n);if(h&&c.createDiv({cls:"csv-focus-sub",text:h}),o&&o!==i&&((E=n[o])!=null&&E.trim())){let S=c.createDiv({cls:"csv-focus-notes"});s.renderMarkdownInto(S,n[o])}let u=new Set([i,o,r].filter(Boolean)),f=s.headers.filter(S=>{var y;return!u.has(S)&&((y=n[S])!=null?y:"").trim()});if(f.length){let S=c.createDiv({cls:"csv-focus-meta"});f.forEach(y=>{let v=S.createDiv({cls:"csv-kanban-chip"});if(v.createSpan({cls:"csv-chip-label",text:y+": "}),s.isSelectCol(y)){let _=v.createSpan({cls:"csv-chip-value csv-chip-select",text:n[y]});_.addEventListener("click",w=>{w.stopPropagation(),Ft(_,n[y],s.getColumnValues(y),T=>{n[y]=T,_.setText(T||"\u2014"),s.scheduleSave()},s.contentEl,{multi:wt(y)})})}else v.createSpan({cls:"csv-chip-value",text:n[y]})})}c.addEventListener("contextmenu",S=>s.openRowContextMenu(n,S));let g=a.createDiv({cls:"csv-focus-nav"}),p=g.createEl("button",{cls:"csv-focus-nav-btn",text:"\u2039",title:"Previous (\u2190)"}),m=g.createEl("button",{cls:"csv-focus-nav-btn csv-focus-nav-rand",text:"\u{1F500}",title:"Random entry"}),b=g.createEl("button",{cls:"csv-focus-nav-btn",text:"\u203A",title:"Next (\u2192)"});p.addEventListener("click",()=>l(s.focusIndex-1)),b.addEventListener("click",()=>l(s.focusIndex+1)),m.addEventListener("click",()=>{if(e.length<2)return;let S=s.focusIndex;for(;S===s.focusIndex;)S=Math.floor(Math.random()*e.length);l(S)}),a.addEventListener("keydown",S=>{S.key==="ArrowLeft"?(S.preventDefault(),l(s.focusIndex-1)):S.key==="ArrowRight"&&(S.preventDefault(),l(s.focusIndex+1))}),(s.focusNavPending||document.activeElement===document.body)&&(s.focusNavPending=!1,a.focus({preventScroll:!0}))}var Ot=require("obsidian"),dc=an(Ds());var Mg=[{id:"table",label:"Table"},{id:"library",label:"Cards"},{id:"kanban-genre",label:"Kanban"}];function cc(s){return s&&typeof s=="object"&&"basename"in s?s:null}function Tg(s){let t=s.split(` `).map(r=>r.trim()).filter(Boolean),e=r=>{var a,l;return(l=(a=t.find(c=>c.toLowerCase().startsWith(r+":")))==null?void 0:a.slice(r.length+1).trim())!=null?l:""},n=e("mode").toLowerCase(),i=n==="kanban"||n==="kanban-genre"?"kanban-genre":n==="cards"||n==="card"||n==="library"?"library":"table",o=parseInt(e("height"),10);return{file:e("file"),mode:i,height:Number.isFinite(o)&&o>0?o:null,collapse:e("collapse").split(",").map(r=>r.trim()).filter(Boolean)}}var No=class extends Ot.MarkdownRenderChild{constructor(e,n,i,o,r){super(e);this.file=null;this.headers=[];this.rows=[];this.searchQuery="";this.tableSortCol=null;this.tableSortDir="asc";this.libraryStatusFilter="all";this.libraryGenreFilter="all";this.collapsedGroups=new Set;this.saveTimer=null;this.lastWritten=null;this.contentArea=null;this.app=n,this.settings=i,this.persistSettings=o,this.opts=r,this.mode=r.mode,this.collapsedGroups=new Set(r.collapse.map(a=>a.toLowerCase()))}get renderComponent(){return this}get contentEl(){return this.containerEl}get asView(){return this}async onload(){if(this.containerEl.addClass("csv-inline-view"),!this.opts.file){this.renderError("No file specified. Use: file: yourfile.csv");return}await this.reload()&&(this.renderView(),this.registerEvent(this.app.vault.on("modify",async e=>{if(!this.file||e.path!==this.file.path)return;let n=await this.app.vault.read(this.file);if(n===this.lastWritten)return;let i=Nt(n);this.headers=i.headers,this.rows=i.rows,this.renderView()})),this.registerEvent(this.app.vault.on("rename",(e,n)=>{this.file&&n===this.file.path&&(this.file=cc(e))})))}onunload(){this.saveTimer&&window.clearTimeout(this.saveTimer)}async reload(){let e=cc(this.app.vault.getAbstractFileByPath(this.opts.file));if(!e)return this.renderError(`File not found: ${this.opts.file}`),!1;this.file=e;try{let n=Nt(await this.app.vault.read(e));this.headers=n.headers,this.rows=n.rows}catch(n){return this.renderError(`Error reading file: ${n instanceof Error?n.message:String(n)}`),!1}return!0}renderError(e){this.containerEl.empty(),this.containerEl.createEl("p",{text:`csv-view: ${e}`,cls:"csv-add-error"})}scheduleSave(){this.saveTimer&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>void this.doSave(),600)}async doSave(){if(this.file)try{let e=dc.default.unparse(this.rows,{columns:this.headers});this.lastWritten=e,await this.app.vault.modify(this.file,e)}catch(e){new Ot.Notice(`Couldn't save ${this.file.name}: ${e instanceof Error?e.message:String(e)}`,8e3)}}get fileCfg(){var e;return this.file?(e=this.settings.fileConfigs[this.file.path])!=null?e:{}:{}}saveFileCfg(e){this.file&&(this.settings.fileConfigs[this.file.path]=e,this.persistSettings())}isHighlighted(e){var n;return((n=this.fileCfg.highlightedTitles)!=null?n:[]).includes(this.getTitle(e))}toggleHighlight(e){let n=this.getTitle(e),i=this.fileCfg,o=i.highlightedTitles?[...i.highlightedTitles]:[],r=o.indexOf(n);r>=0?o.splice(r,1):o.push(n),i.highlightedTitles=o,this.saveFileCfg(i)}resolveCol(e){for(let n of e){let i=this.headers.find(o=>o.toLowerCase()===n.toLowerCase());if(i)return i}return null}getNotesCol(){return this.fileCfg.notesColumn!==void 0?this.fileCfg.notesColumn===""?null:this.fileCfg.notesColumn:this.resolveCol(Xe)}isNotesCol(e){let n=this.getNotesCol();return n?e===n:this.settings.notesColumns.some(i=>i.toLowerCase()===e.toLowerCase())}isSelectCol(e){return this.settings.selectColumns.some(n=>n.toLowerCase()===e.toLowerCase())}isCategoricalCol(e){var i;let n=(i=this.titleKey())!=null?i:this.headers[0];return e===n||this.getDateCol()===e||wt(e)?!1:this.fileCfg.categoricalColumns?this.fileCfg.categoricalColumns.includes(e):this.isSelectCol(e)||Xt(this.getColumnValues(e).length)}getStatusCol(){var e;return this.fileCfg.statusColumn!==void 0?this.fileCfg.statusColumn===""?null:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.statusColumn.toLowerCase()))!=null?e:null:this.resolveCol(qe)}getCategoryCol(){var e;return this.fileCfg.categoryColumn!==void 0?this.fileCfg.categoryColumn===""?null:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.categoryColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ge)}titleKey(){var e,n;return this.fileCfg.titleColumn!==void 0?this.fileCfg.titleColumn===""?void 0:(e=this.headers.find(i=>i.toLowerCase()===this.fileCfg.titleColumn.toLowerCase()))!=null?e:void 0:(n=this.resolveCol(Ye))!=null?n:void 0}authorKey(){var e;return(e=this.resolveCol(["Author","author","Authors","authors","Director","director","Artist","artist","Creator","creator","By","by"]))!=null?e:void 0}getTitle(e){var i;let n=this.titleKey();return(i=n?e[n]:e[this.headers[0]])!=null?i:"\u2014"}getSubtitle(e){var i;let n=this.authorKey();return n&&(i=e[n])!=null?i:""}getColumnValues(e){return Array.from(new Set(this.rows.map(n=>{var i;return(i=n[e])!=null?i:""}).filter(Boolean))).sort()}getImageCol(){var e;return this.fileCfg.imageColumn!==void 0?this.fileCfg.imageColumn===""?null:(e=this.headers.find(n=>n.toLowerCase()===this.fileCfg.imageColumn.toLowerCase()))!=null?e:null:this.resolveCol(Ke)}getBooleanColumns(){return this.fileCfg.habitColumns?this.fileCfg.habitColumns.filter(e=>this.headers.includes(e)):this.headers.filter(e=>{if(e===this.getDateCol()||this.isNotesCol(e))return!1;let n=this.rows.map(i=>{var o;return((o=i[e])!=null?o:"").toLowerCase().trim()});return Qe(n)})}getDateCol(){var o,r;if(this.fileCfg.dateColumns&&this.fileCfg.dateColumns.length>0){let a=this.fileCfg.dateColumns[0];return(o=this.headers.find(l=>l===a))!=null?o:null}if(this.headers.length===0)return null;let e=this.headers[0];if(["date","day","datum"].includes(e.toLowerCase()))return e;let n=/^\d{4}-\d{2}-\d{2}$/,i=this.rows.slice(0,5);return i.length>0&&i.every(a=>{var l;return n.test((l=a[e])!=null?l:"")})?e:(r=this.headers.find(a=>this.isDateCol(a)))!=null?r:null}isDateCol(e){var n;return(n=this.fileCfg.dateColumns)!=null&&n.includes(e)?!0:kt(e)}getFilteredRows(){var i;let e=this.rows;if(this.searchQuery.trim()){let o=this.searchQuery.toLowerCase().trim();e=e.filter(r=>this.headers.some(a=>{var l;return((l=r[a])!=null?l:"").toLowerCase().includes(o)}))}if(this.mode==="table"&&this.tableSortCol&&this.headers.includes(this.tableSortCol)){let o=this.tableSortCol,r=this.tableSortDir;return[...e].sort((a,l)=>{var d,h;let c=((d=a[o])!=null?d:"").localeCompare((h=l[o])!=null?h:"",void 0,{numeric:!0});return r==="asc"?c:-c})}let n=this.getDateCol();if(this.mode==="table"&&n){let o=(i=this.fileCfg.sortNewestFirst)!=null?i:!0;e=[...e].sort((r,a)=>{var c,d;let l=((c=r[n])!=null?c:"").localeCompare((d=a[n])!=null?d:"");return o?-l:l})}return e}notesFilePath(e){var a,l,c;let n=Ms(this.getTitle(e)),i=(c=(l=(a=this.file)==null?void 0:a.parent)==null?void 0:l.path)!=null?c:"",o=this.settings.notesSubfolder.trim(),r=o?i?`${i}/${o}`:o:i;return(0,Ot.normalizePath)(`${r}/${n}.md`)}notesFileExists(e){return!!this.app.vault.getAbstractFileByPath(this.notesFilePath(e))}async openOrCreateNotes(e){var o;let n=this.notesFilePath(e),i=this.app.vault.getAbstractFileByPath(n);if(!i){let a=["---",...this.headers.filter(h=>!this.isNotesCol(h)&&e[h]).map(h=>`${h}: "${e[h].replace(/"/g,'\\"')}"`),"---","",`# ${this.getTitle(e)}`,"",""].join(` `),l=this.headers.find(h=>this.isNotesCol(h)),c=a+(l&&((o=e[l])!=null&&o.trim())?e[l]:""),d=n.substring(0,n.lastIndexOf("/"));d&&!this.app.vault.getAbstractFileByPath(d)&&await this.app.vault.createFolder(d),i=await this.app.vault.create(n,c),new Ot.Notice(`Created: ${i.name}`)}await this.app.workspace.getLeaf("tab").openFile(i)}deleteWithUndo(e){let n=this.rows.indexOf(e);if(n<0)return;this.rows.splice(n,1),this.scheduleSave(),this.renderView();let i=this.getTitle(e)||"entry",o=document.createDocumentFragment();o.createSpan({text:`Deleted \u201C${i}\u201D. `});let r=o.createEl("button",{text:"Undo",cls:"csv-notice-undo"}),a=new Ot.Notice(o,6e3);r.addEventListener("click",()=>{r.hasAttribute("disabled")||(r.setAttribute("disabled","true"),this.rows.splice(Math.min(n,this.rows.length),0,e),this.scheduleSave(),this.renderView(),a.hide(),new Ot.Notice(`Restored \u201C${i}\u201D`,2500))})}openRowContextMenu(e,n){let i=new Ot.Menu;i.addItem(a=>a.setTitle("Open / Create Notes file").setIcon("file-text").onClick(()=>void this.openOrCreateNotes(e))),i.addItem(a=>a.setTitle("Open entry").setIcon("maximize").onClick(()=>{var l;return this.openNoteExpander(e,(l=this.getNotesCol())!=null?l:"")}));let o=this.getStatusCol();if(o){let a=this.getColumnValues(o);a.length&&(i.addSeparator(),a.forEach(l=>{l!==e[o]&&i.addItem(c=>c.setTitle(`Mark as: ${l}`).onClick(()=>{e[o]=l,this.scheduleSave(),this.renderView()}))}))}i.addSeparator();let r=this.isHighlighted(e);i.addItem(a=>a.setTitle(r?"Remove highlight":"Highlight").setIcon("highlighter").onClick(()=>{this.toggleHighlight(e),this.renderView()})),i.addSeparator(),i.addItem(a=>a.setTitle("Delete").setIcon("trash").onClick(()=>this.deleteWithUndo(e))),i.showAtMouseEvent(n)}openNoteExpander(e,n){var i,o;new ts(this.app,e,n,this.headers,(o=(i=this.file)==null?void 0:i.path)!=null?o:"",this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),r=>{Object.assign(e,r),this.scheduleSave(),this.renderView()},()=>this.deleteWithUndo(e),this.isCategoricalCol.bind(this),this.titleKey(),r=>this.getBooleanColumns().includes(r),r=>this.isDateCol(r)).open()}openAddModal(){new Je(this.app,this.headers,this.isNotesCol.bind(this),this.isSelectCol.bind(this),this.getColumnValues.bind(this),e=>{this.rows.push(e),this.scheduleSave(),this.renderView(),new Ot.Notice(`Added: ${this.getTitle(e)}`)},{},e=>this.getBooleanColumns().includes(e),e=>this.isCategoricalCol(e),this.titleKey(),e=>this.isDateCol(e)).open()}renderSelectField(e,n,i){var a;let o=(a=n[i])!=null?a:"",r=e.createDiv({cls:`csv-select-chip ${o?"":"empty"}`});return r.setText(o||"\u2014"),i.toLowerCase()==="status"&&o&&r.addClass(`status-chip-${o.toLowerCase().replace(/\s+/g,"-")}`),r.addEventListener("click",l=>{var c;l.stopPropagation(),Ft(r,(c=n[i])!=null?c:"",this.getColumnValues(i),d=>{n[i]=d,r.setText(d||"\u2014"),this.scheduleSave()},this.contentEl)}),r}renderMarkdownInto(e,n){var i,o;Ot.MarkdownRenderer.render(this.app,n,e,(o=(i=this.file)==null?void 0:i.path)!=null?o:"",this.renderComponent)}renderViewPreservingScroll(){this.renderView()}renderView(e=!1){let n=this.containerEl;e?this.contentArea&&this.contentArea.empty():(n.empty(),this.renderToolbar(n),this.contentArea=n.createDiv({cls:"csv-content-area"}),this.opts.height&&(this.contentArea.style.maxHeight=this.opts.height+"px"));let i=this.contentArea;if(i){if(i.toggleClass("csv-content-area--no-yscroll",this.mode==="kanban-genre"||this.mode==="table"),!this.headers.length){i.createDiv({cls:"csv-empty-state"}).createEl("p",{text:"This file is empty."});return}if(this.rows.length===0){let o=i.createDiv({cls:"csv-empty-state"});o.createEl("p",{text:"No entries yet."}),o.createEl("button",{cls:"csv-empty-state-action",text:"+ Add the first entry"}).addEventListener("click",()=>this.openAddModal());return}(this.mode==="library"||this.mode==="kanban-genre")&&!$t(this.asView)&&(this.mode="table"),this.mode==="library"?yn(this.asView,i):this.mode==="kanban-genre"?vn(this.asView,i):mn(this.asView,i)}}renderToolbar(e){var c,d;let n=e.createDiv({cls:"csv-toolbar csv-inline-toolbar"});n.createDiv({cls:"csv-toolbar-title",text:(d=(c=this.file)==null?void 0:c.basename)!=null?d:""}).addEventListener("click",()=>{this.file&&this.app.workspace.getLeaf("tab").openFile(this.file)});let i=n.createDiv({cls:"csv-toolbar-controls"});i.createDiv({cls:"csv-row-count",text:`${this.rows.length} entries`});let o=!!$t(this.asView),r=i.createDiv({cls:"csv-mode-group"});Mg.forEach(({id:h,label:u})=>{if((h==="library"||h==="kanban-genre")&&!o)return;r.createEl("button",{cls:`csv-mode-btn ${this.mode===h?"active":""}`,text:u}).addEventListener("click",()=>{this.mode=h,this.renderView()})});let a=i.createEl("input",{cls:"csv-search-input",type:"text",placeholder:"Search\u2026",value:this.searchQuery,attr:{inputmode:"search",enterkeyhint:"search",autocomplete:"off"}}),l=null;a.addEventListener("input",h=>{this.searchQuery=h.target.value,l!==null&&window.clearTimeout(l),l=window.setTimeout(()=>{l=null,this.renderView(!0)},120)}),i.createEl("button",{cls:"csv-add-btn",text:"+ Add"}).addEventListener("click",()=>this.openAddModal())}};function hc(s,t,e,n){n("csv-view",(i,o,r)=>{var h,u,f;let a=Tg(i),l=(f=(u=(h=s.vault.getAbstractFileByPath(r.sourcePath))==null?void 0:h.parent)==null?void 0:u.path)!=null?f:"",c=a.file?ue(a.file,l):a.file,d=new No(o,s,t,e,{...a,file:c});r.addChild(d)})}var fc=require("obsidian");function Lg(s){let t=s.split(` diff --git a/src/view/table.ts b/src/view/table.ts index abf985b..0cf6504 100644 --- a/src/view/table.ts +++ b/src/view/table.ts @@ -141,13 +141,29 @@ export function makeEditable(view: CardView, el: HTMLElement, row: CSVRow, h: st type: isDate ? "date" : "text" }); - input.focus(); + input.focus(); if (!isDate) input.select(); // selecting text is mostly useful for text inputs, dates have a native picker - + // Prevent clicks on the input from bubbling up to row/document listeners input.addEventListener("click", ev => ev.stopPropagation()); - - input.addEventListener("blur", () => { row[h] = input.value; view.scheduleSave(); el.empty(); el.setText(input.value || "—"); }); - input.addEventListener("keydown", ev => { if (ev.key === "Enter") input.blur(); if (ev.key === "Escape") { el.empty(); el.setText(row[h] || "—"); } }); + + // Commit on blur — but only when the value actually changed from what we + // put into the input. Saving unconditionally meant every click-in/ + // click-out dirtied the file (debounced vault write + sync churn), and + // for a date cell the write-back was the 10-char truncated pickerValue — + // silently clobbering any extra data just by touching the cell. + let cancelled = false; + input.addEventListener("blur", () => { + if (!cancelled && input.value !== pickerValue) { + row[h] = input.value; + view.scheduleSave(); + } + el.empty(); + el.setText((row[h] ?? "") || "—"); + }); + input.addEventListener("keydown", ev => { + if (ev.key === "Enter") input.blur(); + if (ev.key === "Escape") { cancelled = true; input.blur(); } + }); }); }