@graphique/geom-label
Version:
For creating labels based on data in Graphique
2 lines • 14.8 kB
JavaScript
;var Ht=Object.create;var pt=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,Ut=Object.prototype.hasOwnProperty;var Jt=(o,n)=>{for(var i in n)pt(o,i,{get:n[i],enumerable:!0})},Et=(o,n,i,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of qt(n))!Ut.call(o,s)&&s!==i&&pt(o,s,{get:()=>n[s],enumerable:!(a=Xt(n,s))||a.enumerable});return o};var tt=(o,n,i)=>(i=o!=null?Ht(Zt(o)):{},Et(n||!o||!o.__esModule?pt(i,"default",{value:o,enumerable:!0}):i,o)),Kt=o=>Et(pt({},"__esModule",{value:!0}),o);var Qt={};Jt(Qt,{Entrance:()=>Gt,GeomLabel:()=>Ot,Legend:()=>wt});module.exports=Kt(Qt);var r=tt(require("react"),1),Mt=require("react-move"),dt=require("d3-ease"),It=require("d3-interpolate"),it=require("jotai"),p=require("@graphique/graphique");var Gt=(i=>(i.DATA="data",i.BOTTOM="bottom",i))(Gt||{});var W=tt(require("react"),1),Ct=require("jotai"),j=require("@graphique/graphique");var b=tt(require("react"),1),At=require("jotai"),N=require("@graphique/graphique"),Ft=({data:o})=>{let[{x:n,y:i}]=(0,At.useAtom)(N.labelsState),[{tooltip:a}]=(0,At.useAtom)(N.themeState),[s,v]=(0,b.useState)("");return(0,b.useEffect)(()=>{let m=setTimeout(()=>v((0,N.nodeToString)(i)));return()=>clearTimeout(m)},[i]),o?b.default.createElement(N.TooltipContainer,null,o.map(m=>{let k=(0,N.formatMissing)(m.group);return b.default.createElement("div",{key:`group-tooltip-${m.label||k}`},b.default.createElement("div",{style:{marginTop:4,marginBottom:4}},(m.label||m.group!=="__group")&&b.default.createElement(b.default.Fragment,null,m.mark,b.default.createElement("div",{style:{display:"flex",alignItems:"flex-end",fontWeight:500}},b.default.createElement("div",{style:{marginBottom:4}},b.default.createElement("span",{style:{fontSize:a?.groupLabel?.fontSize||a?.font?.size}},m.formattedMeasure||k)))),b.default.createElement("div",{style:{display:"flex",marginBottom:2}},n&&b.default.createElement("div",{style:{fontSize:a?.xLabel?.fontSize||a?.font?.size}},`${n}:`),b.default.createElement("div",{style:{marginLeft:1,fontWeight:500,fontSize:a?.xLabel?.fontSize||(a?.font?.size||12)+1}},m.formattedX)),b.default.createElement("div",{style:{display:"flex"}},s&&b.default.createElement("div",{style:{fontSize:a?.yLabel?.fontSize||a?.font?.size}},`${s}:`),b.default.createElement("div",{style:{marginLeft:1,fontWeight:500,fontSize:a?.yLabel?.fontSize||(a?.font?.size||12)+1}},m.formattedY))))})):null};var Tt=({aes:o,group:n})=>{let{ggState:i}=(0,j.useGG)()||{},{id:a,scales:s,height:v,width:m}=i||{width:0,height:0},[{datum:k,position:h,xFormat:C,yFormat:G,measureFormat:P,content:w}]=(0,Ct.useAtom)(j.tooltipState),[{x:S,y:V}]=(0,Ct.useAtom)(j.labelsState),l=(0,W.useMemo)(()=>k&&k[0],[k]),D=(0,W.useMemo)(()=>{let E={given:l&&o?.label&&o.label(l),keyed:l&&o?.key&&o.key(l)};return E?.given||E?.keyed},[o,l]),O=s?.xScale,d=s?.yScale,z=(0,W.useMemo)(()=>s?.xScale.bandwidth?s?.xScale.bandwidth()/2:0,[s]),c=(0,W.useMemo)(()=>s?.yScale?.bandwidth?s.yScale.bandwidth()/2:0,[s]),L=(0,W.useMemo)(()=>l&&n&&n(l),[l,n]),y=[{x:l&&o?.x&&O&&O(o.x(l)),y:l&&o?.y&&d&&d(o.y(l)),xLab:S?.toString(),yLab:V?.toString(),formattedX:l&&o?.x&&(C?C(o.x(l)):o.x(l)),formattedY:l&&o?.y&&(G?G(o.y(l)):o.y(l)),group:L,label:D,formattedMeasure:P&&(D||String(L))&&P(D||L),datum:k,containerWidth:m}],F=w?l&&W.default.createElement("div",null,w(y)):l&&W.default.createElement(Ft,{data:y});return l&&y[0].x!==void 0&&y[0].y!==void 0?W.default.createElement("div",null,W.default.createElement(j.YTooltip,{id:a,left:(y[0].x||0)+z,top:h===j.TooltipPosition.DATA?-(v-(y[0].y||0)-c):-v,value:F})):null};var Ot=({data:o,aes:n,attr:i,focusedStyle:a,unfocusedStyle:s,focusedKeys:v=[],onDatumFocus:m,onDatumSelection:k,entrance:h="bottom",onExit:C,showTooltip:G=!1,brushAction:P,isClipped:w=!1,isAnimated:S=!0})=>{let{ggState:V}=(0,p.useGG)()||{},{id:l,data:D,aes:O,scales:d,copiedScales:z,width:c,height:L,margin:y}=V||{width:0},[F,u]=(0,it.useAtom)(p.themeState),[{xDomain:E,yDomain:_}]=(0,it.useAtom)(p.zoomState),[{isFixed:bt}]=(0,it.useAtom)(p.xScaleState),[{isFixed:vt}]=(0,it.useAtom)(p.yScaleState),kt=(0,p.usePageVisibility)(),f={...{fillOpacity:1,strokeOpacity:1,strokeWidth:3,dy:3.8},...i},{defaultFill:lt,animationDuration:q,font:nt}=F,B=(0,r.useMemo)(()=>o||D,[D,o]),e=(0,r.useMemo)(()=>n?{...O,...n}:O,[O,n]),H=(0,r.useMemo)(()=>e&&(0,p.defineGroupAccessor)(e),[e,p.defineGroupAccessor]),g=(0,r.useCallback)(t=>e?.key?e.key(t):`${e?.x&&e.x(t)}-${e?.y&&e.y(t)}-${H&&H(t)}`,[e,H]),Q=(0,r.useMemo)(()=>{if(!e?.label)throw new Error("GeomLabel needs a label mapped in `aes.label`");return e?.label??(()=>"")},[e]),Z=(0,r.useMemo)(()=>B?B.filter(t=>e?.x&&(e.x(t)===null||typeof e.x(t)>"u"||(0,p.isDate)(e.x(t))&&Number.isNaN(e.x(t)?.valueOf()))):[],[B,e]),U=(0,r.useMemo)(()=>B?B.filter(t=>e?.y&&(e.y(t)===null||typeof e.y(t)>"u")):[],[B]),$=(0,r.useMemo)(()=>{let t=B?.filter(A=>e?.x&&e?.x(A)!==null&&!(typeof e?.x(A)>"u")&&((0,p.isDate)(e?.x(A))?!Number.isNaN(e?.x(A)?.valueOf()):!0)&&e.y&&e.y(A)!==null&&!(typeof e.y(A)>"u"));return Array.from(new Set(t?.map(A=>g(A)))).flatMap(A=>{let Y=t?.filter(K=>g(K)===A);return Y&&Y.length>1?Y.map((K,ft)=>({...K,gg_gen_index:ft})):Y?.flat()})},[B,g]),[at,jt]=(0,r.useState)(!0);(0,r.useEffect)(()=>{let t=setTimeout(()=>jt(!1),0);return()=>clearTimeout(t)},[]),(0,r.useEffect)(()=>{at&&Z.length>0&&console.warn(`Ignoring ${Z.length} labels with missing x values.`),at&&U.length>0&&console.warn(`Ignoring ${U.length} labels with missing y values.`)},[at,Z,U]);let ht=(0,r.useMemo)(()=>L&&y?L-y.bottom:void 0,[L,y]);(0,r.useEffect)(()=>{u(t=>({...t,geoms:{...t.geoms,label:{fillOpacity:f?.style?.fillOpacity||f?.fillOpacity,stroke:f?.stroke,strokeWidth:f?.style?.strokeWidth||f?.strokeWidth,strokeOpacity:f?.style?.strokeOpacity||f?.strokeOpacity}}}))},[i,u]);let ut={transition:"fill-opacity 200ms",fillOpacity:f.fillOpacity,strokeOpacity:f.strokeOpacity,...f.style},Dt={...ut,...a},Lt={...ut,fillOpacity:.2,strokeOpacity:.2,...s},mt=(0,r.useMemo)(()=>t=>f.fill||(e?.fill&&z?.fillScale?z.fillScale(e.fill(t)):lt),[e,z,f,lt]),ct=(0,r.useMemo)(()=>t=>f.stroke||(e?.stroke&&z?.strokeScale?z.strokeScale(e.stroke(t)):"#fff"),[e,z,f]),J=(0,r.useMemo)(()=>d?.xScale.bandwidth?t=>(d?.xScale(e?.x&&e.x(t))||0)+d?.xScale.bandwidth()/2+.9:t=>d?.xScale&&e?.x&&(d.xScale(e.x(t))||0),[d,e]),R=(0,r.useMemo)(()=>d?.yScale.bandwidth?t=>(d?.yScale(e?.y&&e.y(t))||0)+d?.yScale.bandwidth()/2:t=>d?.yScale&&e?.y&&(d.yScale(e.y(t))||0),[d,e]),Vt=(0,r.useRef)(null),rt=Vt.current?.getElementsByTagName("text"),[Yt,zt]=(0,r.useState)(w);return(0,r.useEffect)(()=>{if(E?.current||_?.current)zt(!0);else{let t=setTimeout(()=>zt(w),q);return()=>clearTimeout(t)}},[bt,vt,E?.current,_?.current,q]),r.default.createElement(r.default.Fragment,null,r.default.createElement("g",{ref:Vt,clipPath:Yt?`url(#__gg_canvas_${l})`:void 0},!at&&kt&&r.default.createElement(Mt.NodeGroup,{data:[...$],keyAccessor:t=>e?.key?g(t):`${g(t)}-${t.gg_gen_index}`,start:t=>({x:J(t),y:h==="data"?R(t):ht,fill:"transparent",stroke:"transparent"}),enter:t=>({x:S?[J(t)]:J(t),y:S?[R(t)]:R(t),fill:S?[mt(t)]:mt(t),stroke:S?[ct(t)]:ct(t),timing:{duration:q,ease:dt.easeCubic}}),update:t=>({x:S?[J(t)]:J(t),y:S?[R(t)]:R(t),fill:S?[mt(t)]:mt(t),stroke:S?[ct(t)]:ct(t),timing:{duration:q,ease:dt.easeCubic}}),leave:()=>({fill:S?["transparent"]:"transparent",stroke:S?["transparent"]:"transparent",y:S?[ht]:ht,timing:{duration:q,ease:dt.easeCubic}}),interpolation:(t,T)=>(0,It.interpolate)(t,T)},t=>r.default.createElement(r.default.Fragment,null,t.map(({state:T,key:A,data:Y})=>{let K={};v.includes(A)&&(K=Dt),v?.length>0&&!v.includes(A)&&(K=Lt);let ft=J(Y)??0;return r.default.createElement("text",{key:A,...i,fillOpacity:T.fillOpacity,strokeOpacity:T.strokeOpacity,stroke:T.stroke,fill:T.fill,strokeWidth:f.strokeWidth,paintOrder:"stroke",pointerEvents:"none",textAnchor:f.textAnchor??(ft>c/2?"end":void 0),dx:f?.dx??(ft>c/2?-7:7),dy:f?.dy,x:T.x,y:T.y,style:{pointerEvents:"none",fontFamily:f?.style?.fontFamily??f?.fontFamily??nt?.family??"-apple-system, sans-serif",fontSize:f?.fontSize??11,fontWeight:f?.fontWeight??600,strokeLinecap:"round",strokeLinejoin:"round",...ut,...K},"data-testid":"__gg_geom_label"},Q(Y))})))),(G||P)&&e&&r.default.createElement(r.default.Fragment,null,r.default.createElement(p.EventArea,{data:$,showTooltip:G,brushAction:P,aes:e,x:J,y:R,onDatumFocus:m,onMouseOver:({i:t})=>{let T=$.flatMap((A,Y)=>v.includes(g(A))?Y:[]);rt&&(0,p.focusNodes)({nodes:rt,focusedIndex:[...T,...[t].flat()],focusedStyles:Dt,unfocusedStyles:Lt})},onClick:k?({d:t,i:T})=>{k(t,T)}:void 0,onMouseLeave:()=>{rt&&G&&((0,p.unfocusNodes)({nodes:rt,baseStyles:ut}),v?.length>0&&(0,p.focusNodes)({nodes:rt,focusedIndex:$.flatMap((t,T)=>v.includes(g(t))?T:[]),focusedStyles:Dt,unfocusedStyles:Lt})),C&&C()}}),G&&r.default.createElement(Tt,{aes:e,group:H})))};Ot.displayName="GeomLabel";var xt=tt(require("react"),1),ot=require("@graphique/graphique"),Nt=require("jotai");var M=tt(require("react"),1),I=require("@graphique/graphique"),yt=require("jotai"),Bt=({legendData:o,legendScales:n,orientation:i,labelFormat:a,fontSize:s=12,onSelection:v})=>{let[m,k]=(0,M.useState)(n.groups||[]),[{geoms:h,legend:C}]=(0,yt.useAtom)(I.themeState),[{domain:G}]=(0,yt.useAtom)(I.fillScaleState),[{domain:P}]=(0,yt.useAtom)(I.strokeScaleState),w=G||P||n.groups,{ggState:S,updateData:V}=(0,I.useGG)()||{},{scales:l,data:D}=S||{};(0,M.useEffect)(()=>{k(l?.groups||[])},[l,D]);let O=n.groupAccessor?n.groupAccessor:()=>n.groups&&n.groups[0],d=i===I.LegendOrientation.H,z=c=>{let L=m,y;L.includes(c)?L.length===1?y=n.groups:y=L.filter(u=>u!==c):y=[...L,c],k(y);let F=Array.from(new Set(D?.map(u=>O(u))));if(v&&v(c),D&&V){let u;F.includes(c)?F.length===1?u=o:u=D.filter(E=>O(E)!==c):u=o.filter(E=>F.includes(O(E))||O(E)===c),V(u)}};return M.default.createElement("div",{style:{marginTop:8,display:"flex",flexDirection:d?"row":"column",flexWrap:"wrap",alignItems:d?"center":void 0}},h?.label?.fillOpacity&&w?.map((c,L,y)=>M.default.createElement("div",{key:c,style:{display:"flex",alignItems:"center",marginBottom:d?6:2}},M.default.createElement("div",{tabIndex:0,role:"button",style:{cursor:"pointer",marginRight:L<y.length-1&&d?12:2,fontSize:s,opacity:m.includes(c)?1:.5,transition:"opacity 200ms",display:"flex",alignItems:"center"},onKeyPress:F=>{["Enter"," "].includes(F.key)&&z(c)},onClick:()=>z(c)},M.default.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center"}},M.default.createElement("svg",{width:12,height:12},M.default.createElement("circle",{r:4,cx:6,cy:6,fill:h?.label?.fill||(n.fillScale?n.fillScale(c):"none"),stroke:h?.label?.stroke||(n.strokeScale?n.strokeScale(c):"none"),strokeWidth:1.8,fillOpacity:m.includes(c)?h?.label?.fillOpacity:.5,strokeOpacity:m.includes(c)?h?.label?.strokeOpacity:.5,style:{transition:"fill-opacity 200ms"}}))),M.default.createElement("div",{style:{marginLeft:4,fontSize:s,color:C?.labelColor??"currentcolor"}},a?a(c,L):(0,I.formatMissing)(c))))))};var x=tt(require("react"),1),gt=require("jotai"),et=require("@graphique/graphique"),Wt=require("d3-interpolate"),st=require("d3-selection"),Pt=require("d3-axis"),St=require("d3-array"),_t=require("d3-transition"),$t=({scales:o,tickFormat:n,width:i=320,tickSize:a=6,height:s=30+a,margin:v,numTicks:m=i/64,fontSize:k=10})=>{let h=(0,x.useRef)(null),C=(0,x.useRef)(null),G=(0,x.useRef)(null),P=(0,x.useRef)(null),w=(0,x.useRef)(null),S=o?.fillScale||o?.strokeScale,[{geoms:V,font:l,legend:D,animationDuration:O}]=(0,gt.useAtom)(et.themeState),[{reverse:d}]=(0,gt.useAtom)(et.fillScaleState),[{reverse:z}]=(0,gt.useAtom)(et.strokeScaleState),[c,L]=(0,x.useState)(!0);(0,x.useEffect)(()=>{let _=setTimeout(()=>L(!1),0);return()=>clearTimeout(_)},[]);let y=d||z,F=256,u={top:4,right:0,bottom:16+a,left:0,...v},E=(0,x.useCallback)((_,bt)=>{if(h.current&&C.current&&G.current&&P.current&&w.current){let vt=(g,Q,Z)=>{let U=g.getContext("2d");for(let $=0;$<Z;$+=1)U&&Q&&(U.fillStyle=Q($/(Z-1)),U.fillRect(y?Z-$:$,0,1,1));return g},kt=O??1e3,X,f,lt=g=>g.selectAll(".tick line").attr("y1",u.top+u.bottom-s),q=(0,st.select)(C.current),nt=(0,st.select)(G.current),B=(0,st.select)(P.current),e=(0,st.select)(w.current),H=(0,_t.transition)().duration(kt);if(!_?.interpolate){if(_?.interpolator){if(X=Object.assign(_.copy().interpolator((0,Wt.interpolateRound)(u.left,i-u.right)),{range(){return[u.left,i-u.right]}}),e.attr("x",u.left).attr("y",u.top).attr("width",i-u.left-u.right).attr("height",s-u.top-u.bottom).attr("preserveAspectRatio","none").attr("xlink:href",vt(C.current,_.interpolator(),F).toDataURL()),c&&e.style("opacity",0).transition(H).style("opacity",o?.fillScale&&V?.label?.fillOpacity||o?.strokeScale&&V?.label?.strokeOpacity||void 0),!X.ticks&&f===void 0){let g=Math.round(m+1);f=(0,St.range)(g).map(Q=>(0,St.quantile)(_.domain(),Q/(g-1)))}q.remove()}}y&&X.domain(X.domain().reverse()),nt.attr("transform",`translate(0,${s-u.bottom})`).transition(H).call((0,Pt.axisBottom)(X).ticks(m,typeof n=="string"?n:void 0).tickFormat(typeof n=="function"?n:void 0).tickSize(a).tickValues(f)),nt.call(g=>g.select(".domain").remove()).selectAll("line").attr("stroke",D?.tickColor||"currentColor").style("opacity",D?.tickColor?1:.85),nt.selectAll(".tick").select("text").style("font-family",bt||"sans-serif").style("font-size",k).attr("fill",D?.labelColor||"currentColor").style("opacity",D?.labelColor?1:.85),B.attr("transform",`translate(0,${s-u.bottom})`).transition(H).call((0,Pt.axisBottom)(X).ticks(m,typeof n=="string"?n:void 0).tickSize(1).tickFormat(()=>"")).selectAll("line").attr("stroke","#111"),B.call(g=>g.select(".domain").remove()).call(g=>g.selectAll(".tick").select("text").remove()).call(lt)}},[i,s,m,n,a,u,D,V,o,k,c,y,O]);return(0,x.useEffect)(()=>{E(S,l?.family)},[l,S,E]),x.default.createElement("div",null,l?.family&&x.default.createElement("svg",{ref:h,width:i,height:s,viewBox:`0 0 ${i} ${s}`,style:{overflow:"visible",display:"block"}},x.default.createElement("image",{ref:w}),x.default.createElement("g",{ref:G}),x.default.createElement("g",{ref:P})),x.default.createElement("canvas",{ref:C,width:F,height:1}))};var wt=({title:o,style:n,orientation:i=ot.LegendOrientation.V,format:a,numTicks:s,width:v,onSelection:m})=>{let{ggState:k}=(0,ot.useGG)()||{},{copiedScales:h,copiedData:C,aes:G}=k||{},[{font:P}]=(0,Nt.useAtom)(ot.themeState),{groups:w}=h||{},S=G?.fill||G?.stroke,{fontSize:V}={...n};return S?xt.default.createElement("div",{style:{marginTop:12,fontFamily:P?.family,...n}},o,C&&h&&w?xt.default.createElement(Bt,{legendData:C,orientation:i,legendScales:h,labelFormat:a,fontSize:V,onSelection:m}):xt.default.createElement($t,{scales:h,tickFormat:a,numTicks:s,fontSize:V,width:v})):null};0&&(module.exports={Entrance,GeomLabel,Legend});
//# sourceMappingURL=index.cjs.map