@rango-dev/charts 0.1.1-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/charts.build.json +1 -0
  2. package/dist/components/BarChart/BarChart.constants.d.ts +47 -0
  3. package/dist/components/BarChart/BarChart.constants.d.ts.map +1 -0
  4. package/dist/components/BarChart/BarChart.d.ts +4 -0
  5. package/dist/components/BarChart/BarChart.d.ts.map +1 -0
  6. package/dist/components/BarChart/BarChart.helpers.d.ts +6 -0
  7. package/dist/components/BarChart/BarChart.helpers.d.ts.map +1 -0
  8. package/dist/components/BarChart/BarChart.styles.d.ts +8 -0
  9. package/dist/components/BarChart/BarChart.styles.d.ts.map +1 -0
  10. package/dist/components/BarChart/BarChart.types.d.ts +33 -0
  11. package/dist/components/BarChart/BarChart.types.d.ts.map +1 -0
  12. package/dist/components/BarChart/index.d.ts +3 -0
  13. package/dist/components/BarChart/index.d.ts.map +1 -0
  14. package/dist/hooks/useIsMobile.d.ts +3 -0
  15. package/dist/hooks/useIsMobile.d.ts.map +1 -0
  16. package/dist/index.d.ts +3 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +2 -0
  19. package/dist/index.js.map +7 -0
  20. package/dist/utils/amountConverter.d.ts +5 -0
  21. package/dist/utils/amountConverter.d.ts.map +1 -0
  22. package/dist/utils/common.d.ts +3 -0
  23. package/dist/utils/common.d.ts.map +1 -0
  24. package/package.json +41 -0
  25. package/readme.md +4 -0
  26. package/src/components/BarChart/BarChart.constants.ts +33 -0
  27. package/src/components/BarChart/BarChart.helpers.ts +56 -0
  28. package/src/components/BarChart/BarChart.styles.ts +48 -0
  29. package/src/components/BarChart/BarChart.tsx +388 -0
  30. package/src/components/BarChart/BarChart.types.ts +31 -0
  31. package/src/components/BarChart/index.ts +6 -0
  32. package/src/hooks/useIsMobile.ts +20 -0
  33. package/src/index.ts +6 -0
  34. package/src/utils/amountConverter.ts +47 -0
  35. package/src/utils/common.ts +22 -0
@@ -0,0 +1 @@
1
+ {"inputs":{"src/hooks/useIsMobile.ts":{"bytes":494,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/utils/amountConverter.ts":{"bytes":1092,"imports":[{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/utils/common.ts":{"bytes":381,"imports":[{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/components/BarChart/BarChart.constants.ts":{"bytes":949,"imports":[],"format":"esm"},"src/components/BarChart/BarChart.helpers.ts":{"bytes":1418,"imports":[{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/components/BarChart/BarChart.styles.ts":{"bytes":965,"imports":[{"path":"@rango-dev/ui","kind":"import-statement","external":true}],"format":"esm"},"src/components/BarChart/BarChart.tsx":{"bytes":11352,"imports":[{"path":"@rango-dev/ui","kind":"import-statement","external":true},{"path":"@visx/axis","kind":"import-statement","external":true},{"path":"@visx/event","kind":"import-statement","external":true},{"path":"@visx/grid","kind":"import-statement","external":true},{"path":"@visx/group","kind":"import-statement","external":true},{"path":"@visx/scale","kind":"import-statement","external":true},{"path":"@visx/shape","kind":"import-statement","external":true},{"path":"@visx/tooltip","kind":"import-statement","external":true},{"path":"dayjs","kind":"import-statement","external":true},{"path":"dayjs/plugin/utc.js","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"src/hooks/useIsMobile.ts","kind":"import-statement","original":"../../hooks/useIsMobile.js"},{"path":"src/utils/amountConverter.ts","kind":"import-statement","original":"../../utils/amountConverter.js"},{"path":"src/utils/common.ts","kind":"import-statement","original":"../../utils/common.js"},{"path":"src/components/BarChart/BarChart.constants.ts","kind":"import-statement","original":"./BarChart.constants.js"},{"path":"src/components/BarChart/BarChart.helpers.ts","kind":"import-statement","original":"./BarChart.helpers.js"},{"path":"src/components/BarChart/BarChart.styles.ts","kind":"import-statement","original":"./BarChart.styles.js"},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"src/components/BarChart/index.ts":{"bytes":149,"imports":[{"path":"src/components/BarChart/BarChart.tsx","kind":"import-statement","original":"./BarChart.js"}],"format":"esm"},"src/index.ts":{"bytes":177,"imports":[{"path":"src/components/BarChart/index.ts","kind":"import-statement","original":"./components/BarChart/index.js"}],"format":"esm"}},"outputs":{"dist/index.js.map":{"imports":[],"exports":[],"inputs":{},"bytes":27725},"dist/index.js":{"imports":[{"path":"@rango-dev/ui","kind":"import-statement","external":true},{"path":"@visx/axis","kind":"import-statement","external":true},{"path":"@visx/event","kind":"import-statement","external":true},{"path":"@visx/grid","kind":"import-statement","external":true},{"path":"@visx/group","kind":"import-statement","external":true},{"path":"@visx/scale","kind":"import-statement","external":true},{"path":"@visx/shape","kind":"import-statement","external":true},{"path":"@visx/tooltip","kind":"import-statement","external":true},{"path":"dayjs","kind":"import-statement","external":true},{"path":"dayjs/plugin/utc.js","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"@rango-dev/ui","kind":"import-statement","external":true}],"exports":["BarChart"],"entryPoint":"src/index.ts","inputs":{"src/components/BarChart/BarChart.tsx":{"bytesInOutput":3831},"src/hooks/useIsMobile.ts":{"bytesInOutput":269},"src/utils/amountConverter.ts":{"bytesInOutput":318},"src/utils/common.ts":{"bytesInOutput":129},"src/components/BarChart/BarChart.constants.ts":{"bytesInOutput":608},"src/components/BarChart/BarChart.helpers.ts":{"bytesInOutput":414},"src/components/BarChart/BarChart.styles.ts":{"bytesInOutput":623},"src/components/BarChart/index.ts":{"bytesInOutput":0},"src/index.ts":{"bytesInOutput":0}},"bytes":6331}}}
@@ -0,0 +1,47 @@
1
+ export declare const DEFAULT_MARGIN: {
2
+ top: number;
3
+ right: number;
4
+ bottom: number;
5
+ left: number;
6
+ };
7
+ export declare const TOOLTIP_DELAY_MS = 100;
8
+ export declare const TOOLTIP_HIDE_DELAY_MS = 300;
9
+ export declare const TOOLTIP_SHADOW = "0px 5px 20px 0px rgba(130, 130, 130, 0.20)";
10
+ export declare const DEFAULT_CHART_COLORS: string[];
11
+ export declare const bottomAxisData: {
12
+ desktop: {
13
+ 7: {
14
+ numBottomAxis: number;
15
+ startBottomAxis: number;
16
+ intervalBottomAxis: number;
17
+ };
18
+ 30: {
19
+ numBottomAxis: number;
20
+ startBottomAxis: number;
21
+ intervalBottomAxis: number;
22
+ };
23
+ 90: {
24
+ numBottomAxis: number;
25
+ startBottomAxis: number;
26
+ intervalBottomAxis: number;
27
+ };
28
+ };
29
+ mobile: {
30
+ 7: {
31
+ numBottomAxis: number;
32
+ startBottomAxis: number;
33
+ intervalBottomAxis: number;
34
+ };
35
+ 30: {
36
+ numBottomAxis: number;
37
+ startBottomAxis: number;
38
+ intervalBottomAxis: number;
39
+ };
40
+ 90: {
41
+ numBottomAxis: number;
42
+ startBottomAxis: number;
43
+ intervalBottomAxis: number;
44
+ };
45
+ };
46
+ };
47
+ //# sourceMappingURL=BarChart.constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BarChart.constants.d.ts","sourceRoot":"","sources":["../../../src/components/BarChart/BarChart.constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,cAAc;;;;;CAA6C,CAAC;AAEzE,eAAO,MAAM,gBAAgB,MAAM,CAAC;AACpC,eAAO,MAAM,qBAAqB,MAAM,CAAC;AACzC,eAAO,MAAM,cAAc,+CAA+C,CAAC;AAE3E,eAAO,MAAM,oBAAoB,EAAE,MAAM,EAaxC,CAAC;AAEF,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAW1B,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { BarChartPropTypes } from './BarChart.types.js';
2
+ import React from 'react';
3
+ export declare const BarChart: (props: BarChartPropTypes) => React.JSX.Element | null;
4
+ //# sourceMappingURL=BarChart.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BarChart.d.ts","sourceRoot":"","sources":["../../../src/components/BarChart/BarChart.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,iBAAiB,EAGlB,MAAM,qBAAqB,CAAC;AAa7B,OAAO,KAAsC,MAAM,OAAO,CAAC;AAmC3D,eAAO,MAAM,QAAQ,UAAW,iBAAiB,6BA8UhD,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { BarStackDataType } from './BarChart.types.js';
2
+ export declare const getTotalValueDates: (data: BarStackDataType[], buckets: string[]) => number[];
3
+ export declare const generateTickValues: (dates: string[], start: number, interval: number) => string[];
4
+ export declare const getTotalValue: (dataColumn: BarStackDataType) => number;
5
+ export declare const getDaysRange: (lengthValue: number) => 7 | 30 | 90;
6
+ //# sourceMappingURL=BarChart.helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BarChart.helpers.d.ts","sourceRoot":"","sources":["../../../src/components/BarChart/BarChart.helpers.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,eAAO,MAAM,kBAAkB,SACvB,gBAAgB,EAAE,WACf,MAAM,EAAE,aAclB,CAAC;AAGF,eAAO,MAAM,kBAAkB,UACtB,MAAM,EAAE,SACR,MAAM,YACH,MAAM,aAOjB,CAAC;AAEF,eAAO,MAAM,aAAa,eAAgB,gBAAgB,WAWzD,CAAC;AAEF,eAAO,MAAM,YAAY,gBAAiB,MAAM,gBAQ/C,CAAC"}
@@ -0,0 +1,8 @@
1
+ export declare const Container: any;
2
+ export declare const TooltipContainer: any;
3
+ export declare const TooltipInfoRow: any;
4
+ export declare const Line: any;
5
+ export declare const InfoContainer: any;
6
+ export declare const Circle: any;
7
+ export declare const NameWrapper: any;
8
+ //# sourceMappingURL=BarChart.styles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BarChart.styles.d.ts","sourceRoot":"","sources":["../../../src/components/BarChart/BarChart.styles.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,SAAS,KAEpB,CAAC;AAEH,eAAO,MAAM,gBAAgB,KAI3B,CAAC;AAEH,eAAO,MAAM,cAAc,KAQzB,CAAC;AAEH,eAAO,MAAM,IAAI,KAIf,CAAC;AAEH,eAAO,MAAM,aAAa,KAOxB,CAAC;AAEH,eAAO,MAAM,MAAM,KAIjB,CAAC;AAEH,eAAO,MAAM,WAAW,KAItB,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { SeriesPoint } from '@visx/shape/lib/types';
2
+ export interface BarChartPropTypes {
3
+ data: BarStackDataType[];
4
+ width: number;
5
+ height: number;
6
+ colorBucketMap: ColorBucketMapType;
7
+ buckets: string[];
8
+ margin?: {
9
+ top: number;
10
+ right: number;
11
+ bottom: number;
12
+ left: number;
13
+ };
14
+ getLabel?: (value: string) => string;
15
+ }
16
+ export type BarStackDataType = {
17
+ [key: string]: string;
18
+ };
19
+ export type ColorBucketMapType = Map<string, string>;
20
+ export type TooltipDataType = {
21
+ bar: {
22
+ bar: SeriesPoint<BarStackDataType>;
23
+ key: string;
24
+ index: number;
25
+ height: number;
26
+ width: number;
27
+ x: number;
28
+ y: number;
29
+ color: string;
30
+ };
31
+ hoveredIndex: number;
32
+ };
33
+ //# sourceMappingURL=BarChart.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BarChart.types.d.ts","sourceRoot":"","sources":["../../../src/components/BarChart/BarChart.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEzD,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,gBAAgB,EAAE,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE,kBAAkB,CAAC;IACnC,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,MAAM,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACtE,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;CACtC;AAED,MAAM,MAAM,gBAAgB,GAAG;IAC7B,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAErD,MAAM,MAAM,eAAe,GAAG;IAC5B,GAAG,EAAE;QACH,GAAG,EAAE,WAAW,CAAC,gBAAgB,CAAC,CAAC;QACnC,GAAG,EAAE,MAAM,CAAC;QACZ,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,KAAK,EAAE,MAAM,CAAC;QACd,CAAC,EAAE,MAAM,CAAC;QACV,CAAC,EAAE,MAAM,CAAC;QACV,KAAK,EAAE,MAAM,CAAC;KACf,CAAC;IACF,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { BarChart } from './BarChart.js';
2
+ export type { BarStackDataType, ColorBucketMapType, BarChartPropTypes, } from './BarChart.types.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/components/BarChart/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,YAAY,EACV,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,3 @@
1
+ declare const useIsMobile: () => boolean;
2
+ export default useIsMobile;
3
+ //# sourceMappingURL=useIsMobile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useIsMobile.d.ts","sourceRoot":"","sources":["../../src/hooks/useIsMobile.ts"],"names":[],"mappings":"AAEA,QAAA,MAAM,WAAW,eAehB,CAAC;AAEF,eAAe,WAAW,CAAC"}
@@ -0,0 +1,3 @@
1
+ export type { BarStackDataType, ColorBucketMapType, BarChartPropTypes, } from './components/BarChart/index.js';
2
+ export { BarChart } from './components/BarChart/index.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ var Bt=Object.defineProperty;var r=(t,e)=>Bt(t,"name",{value:e,configurable:!0});import{Divider as Z}from"@rango-dev/ui";import{AxisBottom as vt,AxisLeft as St}from"@visx/axis";import{localPoint as tt}from"@visx/event";import{Grid as Ct}from"@visx/grid";import{Group as Lt}from"@visx/group";import{scaleBand as Et,scaleLinear as Mt,scaleOrdinal as It}from"@visx/scale";import{BarStack as Nt}from"@visx/shape";import{useTooltip as Ot,useTooltipInPortal as Ft}from"@visx/tooltip";import ot from"dayjs";import wt from"dayjs/plugin/utc.js";import o,{Fragment as Pt,useEffect as _t,useRef as $t}from"react";import{useEffect as bt,useState as At}from"react";var Dt=r(()=>{let[t,e]=At(!1);return bt(()=>{let n=r(()=>{e(window.innerWidth<=640)},"handleResize");return n(),window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),t},"useIsMobile"),F=Dt;var kt=["","K","M","B"];function S(t){let e=Math.sign(t),n=0;for(;Math.abs(t)>1e3;)n=n+1,t=Math.floor(Math.abs(t)/10)/100;return e*Math.abs(t)+kt[n]}r(S,"AmountConverter");function w(t){return!t||isNaN(t)?"0":Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(t)}r(w,"compactNumberFormat");function P(t){let e=new Date(t),n=e.toLocaleDateString("en-US",{month:"short"});return`${e.getDate()} ${n}`}r(P,"getDayOfMonth");var _={top:40,right:0,bottom:0,left:20},$=100,V=300,H="0px 5px 20px 0px rgba(130, 130, 130, 0.20)",G=["#469BF5","#29DABA","#D629DA","#4658F5","#9DF546","#F01DA8","#FF8B66","#44F1E6","#29DA7A","#F17606","#8B62FF","#F4C932"],C={desktop:{7:{numBottomAxis:7,startBottomAxis:0,intervalBottomAxis:1},30:{numBottomAxis:6,startBottomAxis:4,intervalBottomAxis:5},90:{numBottomAxis:8,startBottomAxis:5,intervalBottomAxis:10}},mobile:{7:{numBottomAxis:3,startBottomAxis:1,intervalBottomAxis:2},30:{numBottomAxis:3,startBottomAxis:3,intervalBottomAxis:10},90:{numBottomAxis:3,startBottomAxis:10,intervalBottomAxis:30}}};var z=r((t,e)=>t.reduce((s,c)=>{let g=e.reduce((p,d)=>(p+=isNaN(Number(c[d]))?0:Number(c[d]),p),0);return s.push(g),s},[]),"getTotalValueDates"),j=r((t,e,n)=>{let s=[];for(let c=e;c<t.length;c+=n)s.push(t[c]);return s},"generateTickValues"),R=r(t=>{let e=0;return Object.keys(t).forEach(n=>{if(n!=="date"){let s=t[n];isNaN(Number(s))||(e+=Number(s))}}),e},"getTotalValue"),U=r(t=>t<15?7:t<50?30:90,"getDaysRange");import{styled as h}from"@rango-dev/ui";var W=h("div",{position:"relative"}),Y=h("div",{width:165,backgroundColor:"$background",borderRadius:"$sm"}),J=h("div",{display:"flex",alignItems:"center",fontSize:"$12",color:"$foreground",justifyContent:"space-between",padding:"$8 $10",fontWeight:"$medium"}),K=h("div",{height:1,width:"100%",backgroundColor:"$neutral300"}),q=h("div",{display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:"$10",color:"$foreground",padding:"$5 $10"}),Q=h("div",{width:"$6",height:"$6",borderRadius:3}),X=h("div",{display:"flex",alignItems:"center",justifyContent:"flex-start"});ot.extend(wt);var et=r(t=>{let{data:e,width:n,height:s,colorBucketMap:c,buckets:g,margin:p=_,getLabel:d}=t,u=F(),y=U(e.length),rt=u?C.mobile[y]:C.desktop[y],{intervalBottomAxis:nt,numBottomAxis:at,startBottomAxis:it}=rt,T,B=$t(null),{containerRef:st,TooltipInPortal:lt}=Ft({scroll:!0}),L=n-p.left-20,D=s-p.top-30,k=r(a=>a.date,"getDate"),pt=e.map(k),mt=j(pt,it,nt),{tooltipOpen:E,tooltipLeft:ct,tooltipTop:ut,tooltipData:f,hideTooltip:M,showTooltip:I}=Ot(),dt=z(e,g),b=Et({domain:e.map(k),paddingInner:y===7?.3:.46,paddingOuter:y===90?1:.3}),N=Math.max(...dt),A=Mt({domain:[0,N+N/5],nice:!0}),ft=It({domain:g,range:G});if(_t(()=>{function a(i){u&&B?.current&&!B.current.contains(i.target)&&M()}return r(a,"handleClickOutside"),document.addEventListener("click",a),()=>{document.removeEventListener("click",a)}},[B]),b.range([0,L]),A.range([D,0]),n<10)return null;let xt=r((a,i,l)=>{if(u){T&&clearTimeout(T);let m=tt(a),x=i.x+i.width/2;setTimeout(()=>{I({tooltipData:{bar:i,hoveredIndex:l},tooltipTop:m?.y,tooltipLeft:x})},$)}},"handleBarClick"),ht=r(()=>{u||(T=window.setTimeout(()=>{M()},V))},"handleMouseLeave"),gt=r((a,i,l)=>{if(!u){T&&clearTimeout(T);let m=tt(a),x=i.x+i.width/2+40;I({tooltipData:{bar:i,hoveredIndex:l},tooltipTop:m?.y,tooltipLeft:x})}},"handleMouseMove"),O=r(a=>S(Number(R(a).toFixed(2))),"getFormattedTotalValue");return o.createElement(W,null,o.createElement("svg",{ref:st,width:n,height:s},o.createElement("rect",{x:0,y:0,width:n,height:s,fill:"transparent",rx:14}),o.createElement(Ct,{top:p.top,left:p.left+10,xScale:b,yScale:A,width:L,height:D,stroke:"black",strokeOpacity:.1,numTicksRows:5,numTicksColumns:0,columnLineStyle:{display:"none"}}),o.createElement(Lt,{top:p.top,left:p.left+10},o.createElement(Nt,{data:e,keys:g,x:k,xScale:b,yScale:A,color:ft},a=>a.map(i=>i.bars.map((l,m)=>{let Tt=!(f?.hoveredIndex===m)&&E,yt=c.get(i.key)||l.color;return o.createElement("rect",{key:`bar-stack-${i.index}-${l.index}`,x:l.x,y:l.y,height:l.height,width:l.width,fill:yt,opacity:Tt?.5:1,onClick:v=>xt(v,l,m),onMouseLeave:ht,onMouseMove:v=>gt(v,l,m)})})))),o.createElement(vt,{top:D+p.top,left:p.left+10,scale:b,hideAxisLine:!0,hideTicks:!0,numTicks:at,tickValues:mt,tickFormat:a=>P(a),tickLabelProps:()=>({fontSize:u?10:12,fill:"#727272",textAnchor:"middle"})}),o.createElement(St,{hideAxisLine:!0,hideTicks:!0,numTicks:u?3:5,top:p.top,left:p.left,scale:A,tickFormat:a=>w(Number(a)),tickLabelProps:()=>({fontSize:u?10:12,fill:"#727272",textAnchor:"middle"})})),E&&f&&o.createElement(lt,{top:ut,left:ct,style:{backgroundColor:"transparent",boxShadow:"none",position:"absolute"}},o.createElement(Y,{ref:B,style:{boxShadow:H}},f.bar.bar.data.date&&o.createElement(J,null,o.createElement("div",null,ot.utc(f.bar.bar.data.date).local().format("YYYY/MM/DD").toString()),o.createElement("div",null,d?d(O(f.bar.bar.data)):O(f.bar.bar.data))),Array.from(c).map(a=>{let[i,l]=a,m=f.bar.bar.data[i],x=isNaN(Number(m))?"0":S(Number(Number(m).toFixed(2)));return o.createElement(Pt,{key:i},o.createElement(K,null),o.createElement(q,null,o.createElement(X,null,o.createElement(Q,{style:{backgroundColor:l}}),o.createElement(Z,{direction:"horizontal",size:"4"}),o.createElement("span",null,i)),o.createElement(Z,{direction:"horizontal",size:"10"}),o.createElement("span",null,d?d(x):x)))}))))},"BarChart");export{et as BarChart};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/components/BarChart/BarChart.tsx", "../src/hooks/useIsMobile.ts", "../src/utils/amountConverter.ts", "../src/utils/common.ts", "../src/components/BarChart/BarChart.constants.ts", "../src/components/BarChart/BarChart.helpers.ts", "../src/components/BarChart/BarChart.styles.ts"],
4
+ "sourcesContent": ["/* eslint-disable @typescript-eslint/no-magic-numbers */\nimport type {\n BarChartPropTypes,\n BarStackDataType,\n TooltipDataType,\n} from './BarChart.types.js';\nimport type { BarGroupBar, SeriesPoint } from '@visx/shape/lib/types';\n\nimport { Divider } from '@rango-dev/ui';\nimport { AxisBottom, AxisLeft } from '@visx/axis';\nimport { localPoint } from '@visx/event';\nimport { Grid } from '@visx/grid';\nimport { Group } from '@visx/group';\nimport { scaleBand, scaleLinear, scaleOrdinal } from '@visx/scale';\nimport { BarStack } from '@visx/shape';\nimport { useTooltip, useTooltipInPortal } from '@visx/tooltip';\nimport dayjs from 'dayjs';\nimport utc from 'dayjs/plugin/utc.js';\nimport React, { Fragment, useEffect, useRef } from 'react';\n\nimport useIsMobile from '../../hooks/useIsMobile.js';\nimport {\n AmountConverter,\n compactNumberFormat,\n} from '../../utils/amountConverter.js';\nimport { getDayOfMonth } from '../../utils/common.js';\n\nimport {\n bottomAxisData,\n DEFAULT_CHART_COLORS,\n DEFAULT_MARGIN,\n TOOLTIP_DELAY_MS,\n TOOLTIP_HIDE_DELAY_MS,\n TOOLTIP_SHADOW,\n} from './BarChart.constants.js';\nimport {\n generateTickValues,\n getDaysRange,\n getTotalValue,\n getTotalValueDates,\n} from './BarChart.helpers.js';\nimport {\n Circle,\n Container,\n InfoContainer,\n Line,\n NameWrapper,\n TooltipContainer,\n TooltipInfoRow,\n} from './BarChart.styles.js';\n\ndayjs.extend(utc);\n\nexport const BarChart = (props: BarChartPropTypes) => {\n const {\n data,\n width,\n height,\n colorBucketMap,\n buckets,\n margin = DEFAULT_MARGIN,\n getLabel,\n } = props;\n\n const isMobile = useIsMobile();\n const daysRange = getDaysRange(data.length);\n const bottomAxis = isMobile\n ? bottomAxisData.mobile[daysRange]\n : bottomAxisData.desktop[daysRange];\n\n const { intervalBottomAxis, numBottomAxis, startBottomAxis } = bottomAxis;\n\n let tooltipTimeout: number;\n const tooltipRef = useRef<HTMLInputElement>(null);\n const { containerRef, TooltipInPortal } = useTooltipInPortal({\n // TooltipInPortal is rendered in a separate child of <body />\n scroll: true,\n });\n\n // bounds\n const xMax = width - margin.left - 20;\n const yMax = height - margin.top - 30;\n\n // accessors\n const getDate = (d: BarStackDataType) => d.date;\n\n // handle bottom axis data\n const allDate = data.map(getDate);\n\n const bottomAxisValue = generateTickValues(\n allDate,\n startBottomAxis,\n intervalBottomAxis\n );\n\n const {\n tooltipOpen,\n tooltipLeft,\n tooltipTop,\n tooltipData,\n hideTooltip,\n showTooltip,\n } = useTooltip<TooltipDataType>();\n\n const totalValueDates = getTotalValueDates(data, buckets);\n\n // scales\n const dateScale = scaleBand<string>({\n domain: data.map(getDate),\n paddingInner: daysRange === 7 ? 0.3 : 0.46,\n paddingOuter: daysRange === 90 ? 1 : 0.3,\n });\n\n const totalValue = Math.max(...totalValueDates);\n\n const valueScale = scaleLinear<number>({\n domain: [0, totalValue + totalValue / 5],\n nice: true,\n });\n\n const colorScale = scaleOrdinal<string, string>({\n domain: buckets,\n range: DEFAULT_CHART_COLORS,\n });\n\n useEffect(() => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function handleClickOutside(event: any) {\n if (\n isMobile &&\n tooltipRef?.current &&\n !tooltipRef.current.contains(event.target)\n ) {\n hideTooltip();\n }\n }\n document.addEventListener('click', handleClickOutside);\n return () => {\n document.removeEventListener('click', handleClickOutside);\n };\n }, [tooltipRef]);\n\n dateScale.range([0, xMax]);\n valueScale.range([yMax, 0]);\n\n if (width < 10) {\n return null;\n }\n\n const handleBarClick = (\n event: React.MouseEvent<SVGRectElement, MouseEvent>,\n bar: Omit<BarGroupBar<string>, 'key' | 'value'> & {\n bar: SeriesPoint<BarStackDataType>;\n key: string;\n },\n index: number\n ) => {\n if (isMobile) {\n if (tooltipTimeout) {\n clearTimeout(tooltipTimeout);\n }\n const eventSvgCoords = localPoint(event);\n const left = bar.x + bar.width / 2;\n setTimeout(() => {\n showTooltip({\n tooltipData: { bar, hoveredIndex: index },\n tooltipTop: eventSvgCoords?.y,\n tooltipLeft: left,\n });\n }, TOOLTIP_DELAY_MS);\n }\n };\n\n const handleMouseLeave = () => {\n if (!isMobile) {\n tooltipTimeout = window.setTimeout(() => {\n hideTooltip();\n }, TOOLTIP_HIDE_DELAY_MS);\n }\n };\n\n const handleMouseMove = (\n event: React.MouseEvent<SVGRectElement, MouseEvent>,\n bar: Omit<BarGroupBar<string>, 'key' | 'value'> & {\n bar: SeriesPoint<BarStackDataType>;\n key: string;\n },\n index: number\n ) => {\n if (!isMobile) {\n if (tooltipTimeout) {\n clearTimeout(tooltipTimeout);\n }\n /*\n * TooltipInPortal expects coordinates to be relative to containerRef\n * localPoint returns coordinates relative to the nearest SVG, which\n * is what containerRef is set to in this example.\n */\n const eventSvgCoords = localPoint(event);\n const left = bar.x + bar.width / 2 + 40;\n\n // make sure to pass the index of the hovered bar\n showTooltip({\n tooltipData: { bar, hoveredIndex: index },\n tooltipTop: eventSvgCoords?.y,\n tooltipLeft: left,\n });\n }\n };\n\n const getFormattedTotalValue = (data: BarStackDataType) =>\n AmountConverter(Number(getTotalValue(data).toFixed(2)));\n\n return (\n <Container>\n <svg ref={containerRef} width={width} height={height}>\n <rect\n x={0}\n y={0}\n width={width}\n height={height}\n fill=\"transparent\"\n rx={14}\n />\n <Grid\n top={margin.top}\n left={margin.left + 10}\n xScale={dateScale}\n yScale={valueScale}\n width={xMax}\n height={yMax}\n stroke=\"black\"\n strokeOpacity={0.1}\n numTicksRows={5}\n numTicksColumns={0}\n columnLineStyle={{ display: 'none' }}\n />\n\n <Group top={margin.top} left={margin.left + 10}>\n <BarStack\n data={data}\n keys={buckets}\n x={getDate}\n xScale={dateScale}\n yScale={valueScale}\n color={colorScale}>\n {(barStacks) => {\n /*\n * barStacks returns an array of series objects broken down by key.\n */\n return barStacks.map((barStack) =>\n /*\n * each barStack contains an array of bars, which contain the data\n * for only that series for a given data point. the number of bars in a\n * given stack corresponds to the number of data points in our data array\n */\n\n barStack.bars.map((bar, index) => {\n /*\n * we can then assume that the data in each stack at a given index\n * is related to the data in all other stacks at that index.\n */\n const shouldBeHighlighted =\n tooltipData?.hoveredIndex === index;\n\n /*\n * we can then decide the opacity for our stacks based on whether the\n * tooltip is open, and whether the stack being hovered matches the\n * index passed to our tooltipData\n */\n const shouldHavePartialOpacity =\n !shouldBeHighlighted && tooltipOpen;\n\n const barColor =\n colorBucketMap.get(barStack.key) || bar.color;\n\n return (\n <rect\n key={`bar-stack-${barStack.index}-${bar.index}`}\n x={bar.x}\n y={bar.y}\n height={bar.height}\n width={bar.width}\n fill={barColor}\n opacity={shouldHavePartialOpacity ? 0.5 : 1}\n onClick={(event) => handleBarClick(event, bar, index)}\n onMouseLeave={handleMouseLeave}\n onMouseMove={(event) =>\n handleMouseMove(event, bar, index)\n }\n />\n );\n })\n );\n }}\n </BarStack>\n </Group>\n\n <AxisBottom\n top={yMax + margin.top}\n left={margin.left + 10}\n scale={dateScale}\n hideAxisLine\n hideTicks\n numTicks={numBottomAxis}\n tickValues={bottomAxisValue}\n tickFormat={(d) => getDayOfMonth(d)}\n tickLabelProps={() => ({\n fontSize: isMobile ? 10 : 12,\n fill: '#727272',\n textAnchor: 'middle',\n })}\n />\n\n <AxisLeft\n hideAxisLine\n hideTicks\n numTicks={isMobile ? 3 : 5}\n top={margin.top}\n left={margin.left}\n scale={valueScale}\n tickFormat={(d) => compactNumberFormat(Number(d))}\n tickLabelProps={() => ({\n fontSize: isMobile ? 10 : 12,\n fill: '#727272',\n textAnchor: 'middle',\n })}\n />\n </svg>\n\n {tooltipOpen && tooltipData && (\n <TooltipInPortal\n top={tooltipTop}\n left={tooltipLeft}\n style={{\n backgroundColor: 'transparent',\n boxShadow: 'none',\n position: 'absolute',\n }}>\n <TooltipContainer\n ref={tooltipRef}\n style={{ boxShadow: TOOLTIP_SHADOW }}>\n {tooltipData.bar.bar.data.date && (\n <TooltipInfoRow>\n <div>\n {dayjs\n .utc(tooltipData.bar.bar.data.date)\n .local()\n .format('YYYY/MM/DD')\n .toString()}\n </div>\n <div>\n {getLabel\n ? getLabel(getFormattedTotalValue(tooltipData.bar.bar.data))\n : getFormattedTotalValue(tooltipData.bar.bar.data)}\n </div>\n </TooltipInfoRow>\n )}\n {Array.from(colorBucketMap).map((mapItem) => {\n const [bucketItem, bucketColor] = mapItem;\n const value = tooltipData.bar.bar.data[bucketItem];\n const formattedValue = !isNaN(Number(value))\n ? AmountConverter(Number(Number(value).toFixed(2)))\n : '0';\n return (\n <Fragment key={bucketItem}>\n <Line />\n <InfoContainer>\n <NameWrapper>\n <Circle style={{ backgroundColor: bucketColor }} />\n <Divider direction=\"horizontal\" size={'4'} />\n <span>{bucketItem}</span>\n </NameWrapper>\n <Divider direction=\"horizontal\" size={'10'} />\n\n <span>\n {getLabel ? getLabel(formattedValue) : formattedValue}\n </span>\n </InfoContainer>\n </Fragment>\n );\n })}\n </TooltipContainer>\n </TooltipInPortal>\n )}\n </Container>\n );\n};\n", "import { useEffect, useState } from 'react';\n\nconst useIsMobile = () => {\n const [isMobile, setIsMobile] = useState<boolean>(false);\n\n useEffect(() => {\n const handleResize = () => {\n const mobileBreakpoint = 640;\n setIsMobile(window.innerWidth <= mobileBreakpoint);\n };\n\n handleResize();\n window.addEventListener('resize', handleResize);\n return () => window.removeEventListener('resize', handleResize);\n }, []);\n\n return isMobile;\n};\n\nexport default useIsMobile;\n", "const THRESHOLD = 1000;\nconst BASE_TEN = 10;\nconst PERCENTAGE_MULTIPLIER = 100;\n\nconst unitList = ['', 'K', 'M', 'B'];\nexport function AmountConverter(number: number) {\n const sign = Math.sign(number);\n let unit = 0;\n while (Math.abs(number) > THRESHOLD) {\n unit = unit + 1;\n number = Math.floor(Math.abs(number) / BASE_TEN) / PERCENTAGE_MULTIPLIER;\n }\n return sign * Math.abs(number) + unitList[unit];\n}\n\nexport function getPercentageChange(\n input: number | null,\n output: number | null\n) {\n if (!input || !output) {\n return null;\n }\n return parseFloat(\n Number((output / input - 1) * PERCENTAGE_MULTIPLIER).toFixed(2)\n );\n}\n\nexport function numberWithCommas(number: number) {\n if (!number || isNaN(number)) {\n return number;\n }\n\n return number.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n}\n\nexport function compactNumberFormat(number: number) {\n if (!number || isNaN(number)) {\n return '0';\n }\n\n const numberFormat = Intl.NumberFormat('en-US', {\n notation: 'compact',\n maximumFractionDigits: 1,\n }).format(number);\n\n return numberFormat;\n}\n", "export const monthsShort = [\n 'Jan',\n 'Feb',\n 'Mar',\n 'Apr',\n 'May',\n 'Jun',\n 'Jul',\n 'Aug',\n 'Sep',\n 'Oct',\n 'Nov',\n 'Dec',\n];\n\nexport function getDayOfMonth(dateString: string) {\n const date = new Date(dateString);\n const monthName = date.toLocaleDateString('en-US', { month: 'short' });\n const dayNumber = date.getDate();\n\n return `${dayNumber} ${monthName}`;\n}\n", "export const DEFAULT_MARGIN = { top: 40, right: 0, bottom: 0, left: 20 };\n\nexport const TOOLTIP_DELAY_MS = 100;\nexport const TOOLTIP_HIDE_DELAY_MS = 300;\nexport const TOOLTIP_SHADOW = '0px 5px 20px 0px rgba(130, 130, 130, 0.20)';\n\nexport const DEFAULT_CHART_COLORS: string[] = [\n '#469BF5',\n '#29DABA',\n '#D629DA',\n '#4658F5',\n '#9DF546',\n '#F01DA8',\n '#FF8B66',\n '#44F1E6',\n '#29DA7A',\n '#F17606',\n '#8B62FF',\n '#F4C932',\n];\n\nexport const bottomAxisData = {\n desktop: {\n 7: { numBottomAxis: 7, startBottomAxis: 0, intervalBottomAxis: 1 },\n 30: { numBottomAxis: 6, startBottomAxis: 4, intervalBottomAxis: 5 },\n 90: { numBottomAxis: 8, startBottomAxis: 5, intervalBottomAxis: 10 },\n },\n mobile: {\n 7: { numBottomAxis: 3, startBottomAxis: 1, intervalBottomAxis: 2 },\n 30: { numBottomAxis: 3, startBottomAxis: 3, intervalBottomAxis: 10 },\n 90: { numBottomAxis: 3, startBottomAxis: 10, intervalBottomAxis: 30 },\n },\n};\n", "/* eslint-disable @typescript-eslint/no-magic-numbers */\nimport type { BarStackDataType } from './BarChart.types.js';\n\nexport const getTotalValueDates = (\n data: BarStackDataType[],\n buckets: string[]\n) => {\n const totalValueDates = data.reduce((accumulator, currentData) => {\n const totalValuePerDate = buckets.reduce((dailyTotal, currentBucket) => {\n dailyTotal += !isNaN(Number(currentData[currentBucket]))\n ? Number(currentData[currentBucket])\n : 0;\n return dailyTotal;\n }, 0);\n accumulator.push(totalValuePerDate);\n return accumulator;\n }, [] as number[]);\n\n return totalValueDates;\n};\n\n// Function to generate tick values at intervals of 5, starting from the 5th element\nexport const generateTickValues = (\n dates: string[],\n start: number,\n interval: number\n) => {\n const tickValues = [];\n for (let i = start; i < dates.length; i += interval) {\n tickValues.push(dates[i]);\n }\n return tickValues;\n};\n\nexport const getTotalValue = (dataColumn: BarStackDataType) => {\n let result = 0;\n Object.keys(dataColumn).forEach((key) => {\n if (key !== 'date') {\n const value = dataColumn[key];\n if (!isNaN(Number(value))) {\n result += Number(value);\n }\n }\n });\n return result;\n};\n\nexport const getDaysRange = (lengthValue: number) => {\n if (lengthValue < 15) {\n return 7;\n }\n if (lengthValue < 50) {\n return 30;\n }\n return 90;\n};\n", "import { styled } from '@rango-dev/ui';\n\nexport const Container = styled('div', {\n position: 'relative',\n});\n\nexport const TooltipContainer = styled('div', {\n width: 165,\n backgroundColor: '$background',\n borderRadius: '$sm',\n});\n\nexport const TooltipInfoRow = styled('div', {\n display: 'flex',\n alignItems: 'center',\n fontSize: '$12',\n color: '$foreground',\n justifyContent: 'space-between',\n padding: '$8 $10',\n fontWeight: '$medium',\n});\n\nexport const Line = styled('div', {\n height: 1,\n width: '100%',\n backgroundColor: '$neutral300',\n});\n\nexport const InfoContainer = styled('div', {\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n fontSize: '$10',\n color: '$foreground',\n padding: '$5 $10',\n});\n\nexport const Circle = styled('div', {\n width: '$6',\n height: '$6',\n borderRadius: 3,\n});\n\nexport const NameWrapper = styled('div', {\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'flex-start',\n});\n"],
5
+ "mappings": "iFAQA,OAAS,WAAAA,MAAe,gBACxB,OAAS,cAAAC,GAAY,YAAAC,OAAgB,aACrC,OAAS,cAAAC,OAAkB,cAC3B,OAAS,QAAAC,OAAY,aACrB,OAAS,SAAAC,OAAa,cACtB,OAAS,aAAAC,GAAW,eAAAC,GAAa,gBAAAC,OAAoB,cACrD,OAAS,YAAAC,OAAgB,cACzB,OAAS,cAAAC,GAAY,sBAAAC,OAA0B,gBAC/C,OAAOC,OAAW,QAClB,OAAOC,OAAS,sBAChB,OAAOC,GAAS,YAAAC,GAAU,aAAAC,GAAW,UAAAC,OAAc,QClBnD,OAAS,aAAAC,GAAW,YAAAC,OAAgB,QAEpC,IAAMC,GAAcC,EAAA,IAAM,CACxB,GAAM,CAACC,EAAUC,CAAW,EAAIC,GAAkB,EAAK,EAEvD,OAAAC,GAAU,IAAM,CACd,IAAMC,EAAeL,EAAA,IAAM,CAEzBE,EAAY,OAAO,YAAc,GAAgB,CACnD,EAHqB,gBAKrB,OAAAG,EAAa,EACb,OAAO,iBAAiB,SAAUA,CAAY,EACvC,IAAM,OAAO,oBAAoB,SAAUA,CAAY,CAChE,EAAG,CAAC,CAAC,EAEEJ,CACT,EAfoB,eAiBbK,EAAQP,GCff,IAAMQ,GAAW,CAAC,GAAI,IAAK,IAAK,GAAG,EAC5B,SAASC,EAAgBC,EAAgB,CAC9C,IAAMC,EAAO,KAAK,KAAKD,CAAM,EACzBE,EAAO,EACX,KAAO,KAAK,IAAIF,CAAM,EAAI,KACxBE,EAAOA,EAAO,EACdF,EAAS,KAAK,MAAM,KAAK,IAAIA,CAAM,EAAI,EAAQ,EAAI,IAErD,OAAOC,EAAO,KAAK,IAAID,CAAM,EAAIF,GAASI,CAAI,CAChD,CARgBC,EAAAJ,EAAA,mBA8BT,SAASK,EAAoBC,EAAgB,CAClD,MAAI,CAACA,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AA,CAAQ,UAAU,aAAa,KAAM,IAAK,EAC3C1B,EAAA,cAAC,YAAMiB,CAAW,CACpB,EACAjB,EAAA,cAAC0B,EAAA,CAAQ,UAAU,aAAa,KAAM,KAAM,EAE5C1B,EAAA,cAAC,YACExD,EAAWA,EAAS4E,CAAc,EAAIA,CACzC,CACF,CACF,CAEJ,CAAC,CACH,CACF,CAEJ,CAEJ,EA9UwB",
6
+ "names": ["Divider", "AxisBottom", "AxisLeft", "localPoint", "Grid", "Group", "scaleBand", "scaleLinear", "scaleOrdinal", "BarStack", "useTooltip", "useTooltipInPortal", "dayjs", "utc", "React", "Fragment", "useEffect", "useRef", "useEffect", "useState", "useIsMobile", "__name", "isMobile", "setIsMobile", "useState", "useEffect", "handleResize", "useIsMobile_default", "unitList", "AmountConverter", "number", "sign", "unit", "__name", "compactNumberFormat", "number", "__name", "getDayOfMonth", "dateString", "date", "monthName", "__name", "DEFAULT_MARGIN", "TOOLTIP_DELAY_MS", "TOOLTIP_HIDE_DELAY_MS", "TOOLTIP_SHADOW", "DEFAULT_CHART_COLORS", "bottomAxisData", "getTotalValueDates", "__name", "data", "buckets", "accumulator", "currentData", "totalValuePerDate", "dailyTotal", "currentBucket", "generateTickValues", "dates", "start", "interval", "tickValues", "i", "getTotalValue", "dataColumn", "result", "key", "value", "getDaysRange", "lengthValue", "styled", "Container", "TooltipContainer", "TooltipInfoRow", "Line", "InfoContainer", "Circle", "NameWrapper", "dayjs", "utc", "BarChart", "__name", "props", "data", "width", "height", "colorBucketMap", "buckets", "margin", "DEFAULT_MARGIN", "getLabel", "isMobile", "useIsMobile_default", "daysRange", "getDaysRange", "bottomAxis", "bottomAxisData", "intervalBottomAxis", "numBottomAxis", "startBottomAxis", "tooltipTimeout", "tooltipRef", "useRef", "containerRef", "TooltipInPortal", "useTooltipInPortal", "xMax", "yMax", "getDate", "d", "allDate", "bottomAxisValue", "generateTickValues", "tooltipOpen", "tooltipLeft", "tooltipTop", "tooltipData", "hideTooltip", "showTooltip", "useTooltip", "totalValueDates", "getTotalValueDates", "dateScale", "scaleBand", "totalValue", "valueScale", "scaleLinear", "colorScale", "scaleOrdinal", "DEFAULT_CHART_COLORS", "useEffect", "handleClickOutside", "event", "handleBarClick", "bar", "index", "eventSvgCoords", "localPoint", "left", "TOOLTIP_DELAY_MS", "handleMouseLeave", "TOOLTIP_HIDE_DELAY_MS", "handleMouseMove", "getFormattedTotalValue", "AmountConverter", "getTotalValue", "React", "Container", "Grid", "Group", "BarStack", "barStacks", "barStack", "shouldHavePartialOpacity", "barColor", "AxisBottom", "getDayOfMonth", "AxisLeft", "compactNumberFormat", "TooltipContainer", "TOOLTIP_SHADOW", "TooltipInfoRow", "mapItem", "bucketItem", "bucketColor", "value", "formattedValue", "Fragment", "Line", "InfoContainer", "NameWrapper", "Circle", "Divider"]
7
+ }
@@ -0,0 +1,5 @@
1
+ export declare function AmountConverter(number: number): string;
2
+ export declare function getPercentageChange(input: number | null, output: number | null): number | null;
3
+ export declare function numberWithCommas(number: number): string | number;
4
+ export declare function compactNumberFormat(number: number): string;
5
+ //# sourceMappingURL=amountConverter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"amountConverter.d.ts","sourceRoot":"","sources":["../../src/utils/amountConverter.ts"],"names":[],"mappings":"AAKA,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,UAQ7C;AAED,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,MAAM,EAAE,MAAM,GAAG,IAAI,iBAQtB;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,mBAM9C;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,UAWjD"}
@@ -0,0 +1,3 @@
1
+ export declare const monthsShort: string[];
2
+ export declare function getDayOfMonth(dateString: string): string;
3
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../src/utils/common.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,UAavB,CAAC;AAEF,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,UAM/C"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@rango-dev/charts",
3
+ "version": "0.1.1-next.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "source": "./src/index.ts",
7
+ "main": "./dist/index.js",
8
+ "exports": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "typings": "./dist/index.d.ts",
13
+ "files": [
14
+ "dist",
15
+ "src"
16
+ ],
17
+ "scripts": {
18
+ "build": "node ../../scripts/build/command.mjs --path widget/charts",
19
+ "ts-check": "tsc --declaration --emitDeclarationOnly -p ./tsconfig.json",
20
+ "clean": "rimraf dist",
21
+ "format": "prettier --write '{.,src}/**/*.{ts,tsx}'",
22
+ "lint": "eslint \"**/*.{ts,tsx}\" --ignore-path ../../.eslintignore"
23
+ },
24
+ "peerDependencies": {
25
+ "react": ">=16",
26
+ "react-dom": ">=16"
27
+ },
28
+ "dependencies": {
29
+ "@rango-dev/ui": "^0.37.1-next.2",
30
+ "@visx/axis": "2.18.0",
31
+ "@visx/event": "2.17.0",
32
+ "@visx/grid": "2.18.0",
33
+ "@visx/scale": "2.18.0",
34
+ "@visx/shape": "2.18.0",
35
+ "@visx/tooltip": "2.17.0",
36
+ "dayjs": "^1.11.6"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ }
41
+ }
package/readme.md ADDED
@@ -0,0 +1,4 @@
1
+ # @rango-dev/charts
2
+
3
+ Rango charts
4
+
@@ -0,0 +1,33 @@
1
+ export const DEFAULT_MARGIN = { top: 40, right: 0, bottom: 0, left: 20 };
2
+
3
+ export const TOOLTIP_DELAY_MS = 100;
4
+ export const TOOLTIP_HIDE_DELAY_MS = 300;
5
+ export const TOOLTIP_SHADOW = '0px 5px 20px 0px rgba(130, 130, 130, 0.20)';
6
+
7
+ export const DEFAULT_CHART_COLORS: string[] = [
8
+ '#469BF5',
9
+ '#29DABA',
10
+ '#D629DA',
11
+ '#4658F5',
12
+ '#9DF546',
13
+ '#F01DA8',
14
+ '#FF8B66',
15
+ '#44F1E6',
16
+ '#29DA7A',
17
+ '#F17606',
18
+ '#8B62FF',
19
+ '#F4C932',
20
+ ];
21
+
22
+ export const bottomAxisData = {
23
+ desktop: {
24
+ 7: { numBottomAxis: 7, startBottomAxis: 0, intervalBottomAxis: 1 },
25
+ 30: { numBottomAxis: 6, startBottomAxis: 4, intervalBottomAxis: 5 },
26
+ 90: { numBottomAxis: 8, startBottomAxis: 5, intervalBottomAxis: 10 },
27
+ },
28
+ mobile: {
29
+ 7: { numBottomAxis: 3, startBottomAxis: 1, intervalBottomAxis: 2 },
30
+ 30: { numBottomAxis: 3, startBottomAxis: 3, intervalBottomAxis: 10 },
31
+ 90: { numBottomAxis: 3, startBottomAxis: 10, intervalBottomAxis: 30 },
32
+ },
33
+ };
@@ -0,0 +1,56 @@
1
+ /* eslint-disable @typescript-eslint/no-magic-numbers */
2
+ import type { BarStackDataType } from './BarChart.types.js';
3
+
4
+ export const getTotalValueDates = (
5
+ data: BarStackDataType[],
6
+ buckets: string[]
7
+ ) => {
8
+ const totalValueDates = data.reduce((accumulator, currentData) => {
9
+ const totalValuePerDate = buckets.reduce((dailyTotal, currentBucket) => {
10
+ dailyTotal += !isNaN(Number(currentData[currentBucket]))
11
+ ? Number(currentData[currentBucket])
12
+ : 0;
13
+ return dailyTotal;
14
+ }, 0);
15
+ accumulator.push(totalValuePerDate);
16
+ return accumulator;
17
+ }, [] as number[]);
18
+
19
+ return totalValueDates;
20
+ };
21
+
22
+ // Function to generate tick values at intervals of 5, starting from the 5th element
23
+ export const generateTickValues = (
24
+ dates: string[],
25
+ start: number,
26
+ interval: number
27
+ ) => {
28
+ const tickValues = [];
29
+ for (let i = start; i < dates.length; i += interval) {
30
+ tickValues.push(dates[i]);
31
+ }
32
+ return tickValues;
33
+ };
34
+
35
+ export const getTotalValue = (dataColumn: BarStackDataType) => {
36
+ let result = 0;
37
+ Object.keys(dataColumn).forEach((key) => {
38
+ if (key !== 'date') {
39
+ const value = dataColumn[key];
40
+ if (!isNaN(Number(value))) {
41
+ result += Number(value);
42
+ }
43
+ }
44
+ });
45
+ return result;
46
+ };
47
+
48
+ export const getDaysRange = (lengthValue: number) => {
49
+ if (lengthValue < 15) {
50
+ return 7;
51
+ }
52
+ if (lengthValue < 50) {
53
+ return 30;
54
+ }
55
+ return 90;
56
+ };
@@ -0,0 +1,48 @@
1
+ import { styled } from '@rango-dev/ui';
2
+
3
+ export const Container = styled('div', {
4
+ position: 'relative',
5
+ });
6
+
7
+ export const TooltipContainer = styled('div', {
8
+ width: 165,
9
+ backgroundColor: '$background',
10
+ borderRadius: '$sm',
11
+ });
12
+
13
+ export const TooltipInfoRow = styled('div', {
14
+ display: 'flex',
15
+ alignItems: 'center',
16
+ fontSize: '$12',
17
+ color: '$foreground',
18
+ justifyContent: 'space-between',
19
+ padding: '$8 $10',
20
+ fontWeight: '$medium',
21
+ });
22
+
23
+ export const Line = styled('div', {
24
+ height: 1,
25
+ width: '100%',
26
+ backgroundColor: '$neutral300',
27
+ });
28
+
29
+ export const InfoContainer = styled('div', {
30
+ display: 'flex',
31
+ alignItems: 'center',
32
+ justifyContent: 'space-between',
33
+ fontSize: '$10',
34
+ color: '$foreground',
35
+ padding: '$5 $10',
36
+ });
37
+
38
+ export const Circle = styled('div', {
39
+ width: '$6',
40
+ height: '$6',
41
+ borderRadius: 3,
42
+ });
43
+
44
+ export const NameWrapper = styled('div', {
45
+ display: 'flex',
46
+ alignItems: 'center',
47
+ justifyContent: 'flex-start',
48
+ });
@@ -0,0 +1,388 @@
1
+ /* eslint-disable @typescript-eslint/no-magic-numbers */
2
+ import type {
3
+ BarChartPropTypes,
4
+ BarStackDataType,
5
+ TooltipDataType,
6
+ } from './BarChart.types.js';
7
+ import type { BarGroupBar, SeriesPoint } from '@visx/shape/lib/types';
8
+
9
+ import { Divider } from '@rango-dev/ui';
10
+ import { AxisBottom, AxisLeft } from '@visx/axis';
11
+ import { localPoint } from '@visx/event';
12
+ import { Grid } from '@visx/grid';
13
+ import { Group } from '@visx/group';
14
+ import { scaleBand, scaleLinear, scaleOrdinal } from '@visx/scale';
15
+ import { BarStack } from '@visx/shape';
16
+ import { useTooltip, useTooltipInPortal } from '@visx/tooltip';
17
+ import dayjs from 'dayjs';
18
+ import utc from 'dayjs/plugin/utc.js';
19
+ import React, { Fragment, useEffect, useRef } from 'react';
20
+
21
+ import useIsMobile from '../../hooks/useIsMobile.js';
22
+ import {
23
+ AmountConverter,
24
+ compactNumberFormat,
25
+ } from '../../utils/amountConverter.js';
26
+ import { getDayOfMonth } from '../../utils/common.js';
27
+
28
+ import {
29
+ bottomAxisData,
30
+ DEFAULT_CHART_COLORS,
31
+ DEFAULT_MARGIN,
32
+ TOOLTIP_DELAY_MS,
33
+ TOOLTIP_HIDE_DELAY_MS,
34
+ TOOLTIP_SHADOW,
35
+ } from './BarChart.constants.js';
36
+ import {
37
+ generateTickValues,
38
+ getDaysRange,
39
+ getTotalValue,
40
+ getTotalValueDates,
41
+ } from './BarChart.helpers.js';
42
+ import {
43
+ Circle,
44
+ Container,
45
+ InfoContainer,
46
+ Line,
47
+ NameWrapper,
48
+ TooltipContainer,
49
+ TooltipInfoRow,
50
+ } from './BarChart.styles.js';
51
+
52
+ dayjs.extend(utc);
53
+
54
+ export const BarChart = (props: BarChartPropTypes) => {
55
+ const {
56
+ data,
57
+ width,
58
+ height,
59
+ colorBucketMap,
60
+ buckets,
61
+ margin = DEFAULT_MARGIN,
62
+ getLabel,
63
+ } = props;
64
+
65
+ const isMobile = useIsMobile();
66
+ const daysRange = getDaysRange(data.length);
67
+ const bottomAxis = isMobile
68
+ ? bottomAxisData.mobile[daysRange]
69
+ : bottomAxisData.desktop[daysRange];
70
+
71
+ const { intervalBottomAxis, numBottomAxis, startBottomAxis } = bottomAxis;
72
+
73
+ let tooltipTimeout: number;
74
+ const tooltipRef = useRef<HTMLInputElement>(null);
75
+ const { containerRef, TooltipInPortal } = useTooltipInPortal({
76
+ // TooltipInPortal is rendered in a separate child of <body />
77
+ scroll: true,
78
+ });
79
+
80
+ // bounds
81
+ const xMax = width - margin.left - 20;
82
+ const yMax = height - margin.top - 30;
83
+
84
+ // accessors
85
+ const getDate = (d: BarStackDataType) => d.date;
86
+
87
+ // handle bottom axis data
88
+ const allDate = data.map(getDate);
89
+
90
+ const bottomAxisValue = generateTickValues(
91
+ allDate,
92
+ startBottomAxis,
93
+ intervalBottomAxis
94
+ );
95
+
96
+ const {
97
+ tooltipOpen,
98
+ tooltipLeft,
99
+ tooltipTop,
100
+ tooltipData,
101
+ hideTooltip,
102
+ showTooltip,
103
+ } = useTooltip<TooltipDataType>();
104
+
105
+ const totalValueDates = getTotalValueDates(data, buckets);
106
+
107
+ // scales
108
+ const dateScale = scaleBand<string>({
109
+ domain: data.map(getDate),
110
+ paddingInner: daysRange === 7 ? 0.3 : 0.46,
111
+ paddingOuter: daysRange === 90 ? 1 : 0.3,
112
+ });
113
+
114
+ const totalValue = Math.max(...totalValueDates);
115
+
116
+ const valueScale = scaleLinear<number>({
117
+ domain: [0, totalValue + totalValue / 5],
118
+ nice: true,
119
+ });
120
+
121
+ const colorScale = scaleOrdinal<string, string>({
122
+ domain: buckets,
123
+ range: DEFAULT_CHART_COLORS,
124
+ });
125
+
126
+ useEffect(() => {
127
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
128
+ function handleClickOutside(event: any) {
129
+ if (
130
+ isMobile &&
131
+ tooltipRef?.current &&
132
+ !tooltipRef.current.contains(event.target)
133
+ ) {
134
+ hideTooltip();
135
+ }
136
+ }
137
+ document.addEventListener('click', handleClickOutside);
138
+ return () => {
139
+ document.removeEventListener('click', handleClickOutside);
140
+ };
141
+ }, [tooltipRef]);
142
+
143
+ dateScale.range([0, xMax]);
144
+ valueScale.range([yMax, 0]);
145
+
146
+ if (width < 10) {
147
+ return null;
148
+ }
149
+
150
+ const handleBarClick = (
151
+ event: React.MouseEvent<SVGRectElement, MouseEvent>,
152
+ bar: Omit<BarGroupBar<string>, 'key' | 'value'> & {
153
+ bar: SeriesPoint<BarStackDataType>;
154
+ key: string;
155
+ },
156
+ index: number
157
+ ) => {
158
+ if (isMobile) {
159
+ if (tooltipTimeout) {
160
+ clearTimeout(tooltipTimeout);
161
+ }
162
+ const eventSvgCoords = localPoint(event);
163
+ const left = bar.x + bar.width / 2;
164
+ setTimeout(() => {
165
+ showTooltip({
166
+ tooltipData: { bar, hoveredIndex: index },
167
+ tooltipTop: eventSvgCoords?.y,
168
+ tooltipLeft: left,
169
+ });
170
+ }, TOOLTIP_DELAY_MS);
171
+ }
172
+ };
173
+
174
+ const handleMouseLeave = () => {
175
+ if (!isMobile) {
176
+ tooltipTimeout = window.setTimeout(() => {
177
+ hideTooltip();
178
+ }, TOOLTIP_HIDE_DELAY_MS);
179
+ }
180
+ };
181
+
182
+ const handleMouseMove = (
183
+ event: React.MouseEvent<SVGRectElement, MouseEvent>,
184
+ bar: Omit<BarGroupBar<string>, 'key' | 'value'> & {
185
+ bar: SeriesPoint<BarStackDataType>;
186
+ key: string;
187
+ },
188
+ index: number
189
+ ) => {
190
+ if (!isMobile) {
191
+ if (tooltipTimeout) {
192
+ clearTimeout(tooltipTimeout);
193
+ }
194
+ /*
195
+ * TooltipInPortal expects coordinates to be relative to containerRef
196
+ * localPoint returns coordinates relative to the nearest SVG, which
197
+ * is what containerRef is set to in this example.
198
+ */
199
+ const eventSvgCoords = localPoint(event);
200
+ const left = bar.x + bar.width / 2 + 40;
201
+
202
+ // make sure to pass the index of the hovered bar
203
+ showTooltip({
204
+ tooltipData: { bar, hoveredIndex: index },
205
+ tooltipTop: eventSvgCoords?.y,
206
+ tooltipLeft: left,
207
+ });
208
+ }
209
+ };
210
+
211
+ const getFormattedTotalValue = (data: BarStackDataType) =>
212
+ AmountConverter(Number(getTotalValue(data).toFixed(2)));
213
+
214
+ return (
215
+ <Container>
216
+ <svg ref={containerRef} width={width} height={height}>
217
+ <rect
218
+ x={0}
219
+ y={0}
220
+ width={width}
221
+ height={height}
222
+ fill="transparent"
223
+ rx={14}
224
+ />
225
+ <Grid
226
+ top={margin.top}
227
+ left={margin.left + 10}
228
+ xScale={dateScale}
229
+ yScale={valueScale}
230
+ width={xMax}
231
+ height={yMax}
232
+ stroke="black"
233
+ strokeOpacity={0.1}
234
+ numTicksRows={5}
235
+ numTicksColumns={0}
236
+ columnLineStyle={{ display: 'none' }}
237
+ />
238
+
239
+ <Group top={margin.top} left={margin.left + 10}>
240
+ <BarStack
241
+ data={data}
242
+ keys={buckets}
243
+ x={getDate}
244
+ xScale={dateScale}
245
+ yScale={valueScale}
246
+ color={colorScale}>
247
+ {(barStacks) => {
248
+ /*
249
+ * barStacks returns an array of series objects broken down by key.
250
+ */
251
+ return barStacks.map((barStack) =>
252
+ /*
253
+ * each barStack contains an array of bars, which contain the data
254
+ * for only that series for a given data point. the number of bars in a
255
+ * given stack corresponds to the number of data points in our data array
256
+ */
257
+
258
+ barStack.bars.map((bar, index) => {
259
+ /*
260
+ * we can then assume that the data in each stack at a given index
261
+ * is related to the data in all other stacks at that index.
262
+ */
263
+ const shouldBeHighlighted =
264
+ tooltipData?.hoveredIndex === index;
265
+
266
+ /*
267
+ * we can then decide the opacity for our stacks based on whether the
268
+ * tooltip is open, and whether the stack being hovered matches the
269
+ * index passed to our tooltipData
270
+ */
271
+ const shouldHavePartialOpacity =
272
+ !shouldBeHighlighted && tooltipOpen;
273
+
274
+ const barColor =
275
+ colorBucketMap.get(barStack.key) || bar.color;
276
+
277
+ return (
278
+ <rect
279
+ key={`bar-stack-${barStack.index}-${bar.index}`}
280
+ x={bar.x}
281
+ y={bar.y}
282
+ height={bar.height}
283
+ width={bar.width}
284
+ fill={barColor}
285
+ opacity={shouldHavePartialOpacity ? 0.5 : 1}
286
+ onClick={(event) => handleBarClick(event, bar, index)}
287
+ onMouseLeave={handleMouseLeave}
288
+ onMouseMove={(event) =>
289
+ handleMouseMove(event, bar, index)
290
+ }
291
+ />
292
+ );
293
+ })
294
+ );
295
+ }}
296
+ </BarStack>
297
+ </Group>
298
+
299
+ <AxisBottom
300
+ top={yMax + margin.top}
301
+ left={margin.left + 10}
302
+ scale={dateScale}
303
+ hideAxisLine
304
+ hideTicks
305
+ numTicks={numBottomAxis}
306
+ tickValues={bottomAxisValue}
307
+ tickFormat={(d) => getDayOfMonth(d)}
308
+ tickLabelProps={() => ({
309
+ fontSize: isMobile ? 10 : 12,
310
+ fill: '#727272',
311
+ textAnchor: 'middle',
312
+ })}
313
+ />
314
+
315
+ <AxisLeft
316
+ hideAxisLine
317
+ hideTicks
318
+ numTicks={isMobile ? 3 : 5}
319
+ top={margin.top}
320
+ left={margin.left}
321
+ scale={valueScale}
322
+ tickFormat={(d) => compactNumberFormat(Number(d))}
323
+ tickLabelProps={() => ({
324
+ fontSize: isMobile ? 10 : 12,
325
+ fill: '#727272',
326
+ textAnchor: 'middle',
327
+ })}
328
+ />
329
+ </svg>
330
+
331
+ {tooltipOpen && tooltipData && (
332
+ <TooltipInPortal
333
+ top={tooltipTop}
334
+ left={tooltipLeft}
335
+ style={{
336
+ backgroundColor: 'transparent',
337
+ boxShadow: 'none',
338
+ position: 'absolute',
339
+ }}>
340
+ <TooltipContainer
341
+ ref={tooltipRef}
342
+ style={{ boxShadow: TOOLTIP_SHADOW }}>
343
+ {tooltipData.bar.bar.data.date && (
344
+ <TooltipInfoRow>
345
+ <div>
346
+ {dayjs
347
+ .utc(tooltipData.bar.bar.data.date)
348
+ .local()
349
+ .format('YYYY/MM/DD')
350
+ .toString()}
351
+ </div>
352
+ <div>
353
+ {getLabel
354
+ ? getLabel(getFormattedTotalValue(tooltipData.bar.bar.data))
355
+ : getFormattedTotalValue(tooltipData.bar.bar.data)}
356
+ </div>
357
+ </TooltipInfoRow>
358
+ )}
359
+ {Array.from(colorBucketMap).map((mapItem) => {
360
+ const [bucketItem, bucketColor] = mapItem;
361
+ const value = tooltipData.bar.bar.data[bucketItem];
362
+ const formattedValue = !isNaN(Number(value))
363
+ ? AmountConverter(Number(Number(value).toFixed(2)))
364
+ : '0';
365
+ return (
366
+ <Fragment key={bucketItem}>
367
+ <Line />
368
+ <InfoContainer>
369
+ <NameWrapper>
370
+ <Circle style={{ backgroundColor: bucketColor }} />
371
+ <Divider direction="horizontal" size={'4'} />
372
+ <span>{bucketItem}</span>
373
+ </NameWrapper>
374
+ <Divider direction="horizontal" size={'10'} />
375
+
376
+ <span>
377
+ {getLabel ? getLabel(formattedValue) : formattedValue}
378
+ </span>
379
+ </InfoContainer>
380
+ </Fragment>
381
+ );
382
+ })}
383
+ </TooltipContainer>
384
+ </TooltipInPortal>
385
+ )}
386
+ </Container>
387
+ );
388
+ };
@@ -0,0 +1,31 @@
1
+ import type { SeriesPoint } from '@visx/shape/lib/types';
2
+
3
+ export interface BarChartPropTypes {
4
+ data: BarStackDataType[];
5
+ width: number;
6
+ height: number;
7
+ colorBucketMap: ColorBucketMapType;
8
+ buckets: string[];
9
+ margin?: { top: number; right: number; bottom: number; left: number };
10
+ getLabel?: (value: string) => string;
11
+ }
12
+
13
+ export type BarStackDataType = {
14
+ [key: string]: string;
15
+ };
16
+
17
+ export type ColorBucketMapType = Map<string, string>;
18
+
19
+ export type TooltipDataType = {
20
+ bar: {
21
+ bar: SeriesPoint<BarStackDataType>;
22
+ key: string;
23
+ index: number;
24
+ height: number;
25
+ width: number;
26
+ x: number;
27
+ y: number;
28
+ color: string;
29
+ };
30
+ hoveredIndex: number;
31
+ };
@@ -0,0 +1,6 @@
1
+ export { BarChart } from './BarChart.js';
2
+ export type {
3
+ BarStackDataType,
4
+ ColorBucketMapType,
5
+ BarChartPropTypes,
6
+ } from './BarChart.types.js';
@@ -0,0 +1,20 @@
1
+ import { useEffect, useState } from 'react';
2
+
3
+ const useIsMobile = () => {
4
+ const [isMobile, setIsMobile] = useState<boolean>(false);
5
+
6
+ useEffect(() => {
7
+ const handleResize = () => {
8
+ const mobileBreakpoint = 640;
9
+ setIsMobile(window.innerWidth <= mobileBreakpoint);
10
+ };
11
+
12
+ handleResize();
13
+ window.addEventListener('resize', handleResize);
14
+ return () => window.removeEventListener('resize', handleResize);
15
+ }, []);
16
+
17
+ return isMobile;
18
+ };
19
+
20
+ export default useIsMobile;
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export type {
2
+ BarStackDataType,
3
+ ColorBucketMapType,
4
+ BarChartPropTypes,
5
+ } from './components/BarChart/index.js';
6
+ export { BarChart } from './components/BarChart/index.js';
@@ -0,0 +1,47 @@
1
+ const THRESHOLD = 1000;
2
+ const BASE_TEN = 10;
3
+ const PERCENTAGE_MULTIPLIER = 100;
4
+
5
+ const unitList = ['', 'K', 'M', 'B'];
6
+ export function AmountConverter(number: number) {
7
+ const sign = Math.sign(number);
8
+ let unit = 0;
9
+ while (Math.abs(number) > THRESHOLD) {
10
+ unit = unit + 1;
11
+ number = Math.floor(Math.abs(number) / BASE_TEN) / PERCENTAGE_MULTIPLIER;
12
+ }
13
+ return sign * Math.abs(number) + unitList[unit];
14
+ }
15
+
16
+ export function getPercentageChange(
17
+ input: number | null,
18
+ output: number | null
19
+ ) {
20
+ if (!input || !output) {
21
+ return null;
22
+ }
23
+ return parseFloat(
24
+ Number((output / input - 1) * PERCENTAGE_MULTIPLIER).toFixed(2)
25
+ );
26
+ }
27
+
28
+ export function numberWithCommas(number: number) {
29
+ if (!number || isNaN(number)) {
30
+ return number;
31
+ }
32
+
33
+ return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
34
+ }
35
+
36
+ export function compactNumberFormat(number: number) {
37
+ if (!number || isNaN(number)) {
38
+ return '0';
39
+ }
40
+
41
+ const numberFormat = Intl.NumberFormat('en-US', {
42
+ notation: 'compact',
43
+ maximumFractionDigits: 1,
44
+ }).format(number);
45
+
46
+ return numberFormat;
47
+ }
@@ -0,0 +1,22 @@
1
+ export const monthsShort = [
2
+ 'Jan',
3
+ 'Feb',
4
+ 'Mar',
5
+ 'Apr',
6
+ 'May',
7
+ 'Jun',
8
+ 'Jul',
9
+ 'Aug',
10
+ 'Sep',
11
+ 'Oct',
12
+ 'Nov',
13
+ 'Dec',
14
+ ];
15
+
16
+ export function getDayOfMonth(dateString: string) {
17
+ const date = new Date(dateString);
18
+ const monthName = date.toLocaleDateString('en-US', { month: 'short' });
19
+ const dayNumber = date.getDate();
20
+
21
+ return `${dayNumber} ${monthName}`;
22
+ }