smart-labels 0.0.3 → 0.0.4

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.
@@ -1,4 +1,4 @@
1
- // smart-labels v0.0.2 Copyright (c) 2024 John Alexis Guerra Gómez
1
+ // smart-labels v0.0.3 Copyright (c) 2024 John Alexis Guerra Gómez
2
2
  import * as d3 from 'd3';
3
3
 
4
4
  // Based on https://observablehq.com/@d3/voronoi-labels by Mike Bostock
@@ -74,12 +74,37 @@ function smartLabels(
74
74
  height = height || yExtent[1] - yExtent[0];
75
75
 
76
76
  if (debug) console.log("✅ smartLabels renderer", renderer);
77
+
78
+ function checkIfTargetMatchesRenderer(target, renderer) {
79
+ if (target && target.node) {
80
+ target = target.node();
81
+ }
82
+ if (renderer.toLocaleLowerCase() === "canvas") {
83
+ return target instanceof HTMLCanvasElement;
84
+ } else {
85
+ return target instanceof SVGElement;
86
+ }
87
+ }
88
+
89
+ if (!checkIfTargetMatchesRenderer(target, renderer)) {
90
+ if (debug) console.log("❌ smartLabels Target doesn't match the renderer", target, renderer);
91
+ throw new Error("Smartlabels Target doesn't match the renderer", target, renderer);
92
+ }
93
+
94
+ // Try to reuse the target
77
95
  if (renderer.toLocaleLowerCase() === "canvas") {
78
- target =
79
- d3.select(target) ||
80
- d3.create("canvas").attr("width", width).attr("height", height);
96
+ if (target) {
97
+ target = d3.select(target.node ? target.node() : target);
98
+ } else {
99
+ target = d3.create("canvas").attr("width", width).attr("height", height);
100
+ }
81
101
  useOcclusion = false;
82
102
  } else {
103
+ if (target) {
104
+ target = d3.select(target.node ? target.node() : target);
105
+ } else {
106
+ target = d3.create("svg").attr("viewBox", [0, 0, width, height]);
107
+ }
83
108
  target = target || d3.create("svg").attr("viewBox", [0, 0, width, height]);
84
109
  }
85
110
 
@@ -1,4 +1,4 @@
1
- // smart-labels v0.0.2 Copyright (c) 2024 John Alexis Guerra Gómez
1
+ // smart-labels v0.0.3 Copyright (c) 2024 John Alexis Guerra Gómez
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('d3')) :
4
4
  typeof define === 'function' && define.amd ? define(['d3'], factory) :
@@ -97,12 +97,37 @@ function smartLabels(
97
97
  height = height || yExtent[1] - yExtent[0];
98
98
 
99
99
  if (debug) console.log("✅ smartLabels renderer", renderer);
100
+
101
+ function checkIfTargetMatchesRenderer(target, renderer) {
102
+ if (target && target.node) {
103
+ target = target.node();
104
+ }
105
+ if (renderer.toLocaleLowerCase() === "canvas") {
106
+ return target instanceof HTMLCanvasElement;
107
+ } else {
108
+ return target instanceof SVGElement;
109
+ }
110
+ }
111
+
112
+ if (!checkIfTargetMatchesRenderer(target, renderer)) {
113
+ if (debug) console.log("❌ smartLabels Target doesn't match the renderer", target, renderer);
114
+ throw new Error("Smartlabels Target doesn't match the renderer", target, renderer);
115
+ }
116
+
117
+ // Try to reuse the target
100
118
  if (renderer.toLocaleLowerCase() === "canvas") {
101
- target =
102
- d3__namespace.select(target) ||
103
- d3__namespace.create("canvas").attr("width", width).attr("height", height);
119
+ if (target) {
120
+ target = d3__namespace.select(target.node ? target.node() : target);
121
+ } else {
122
+ target = d3__namespace.create("canvas").attr("width", width).attr("height", height);
123
+ }
104
124
  useOcclusion = false;
105
125
  } else {
126
+ if (target) {
127
+ target = d3__namespace.select(target.node ? target.node() : target);
128
+ } else {
129
+ target = d3__namespace.create("svg").attr("viewBox", [0, 0, width, height]);
130
+ }
106
131
  target = target || d3__namespace.create("svg").attr("viewBox", [0, 0, width, height]);
107
132
  }
108
133
 
@@ -1,2 +1,2 @@
1
- // smart-labels v0.0.2 Copyright (c) 2024 John Alexis Guerra Gómez
2
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("d3")):"function"==typeof define&&define.amd?define(["d3"],e):(t="undefined"!=typeof globalThis?globalThis:t||self).smartLabels=e(t.d3)}(this,(function(t){"use strict";function e(t){var e=Object.create(null);return t&&Object.keys(t).forEach((function(o){if("default"!==o){var n=Object.getOwnPropertyDescriptor(t,o);Object.defineProperty(e,o,n.get?n:{enumerable:!0,get:function(){return t[o]}})}})),e.default=t,Object.freeze(e)}var o=e(t);function n(t,e="text"){const n=o.sort(t.selectAll(e),(t=>+t.getAttribute("data-priority"))).reverse().map((t=>{const{x:e,y:o,width:n,height:r}=t.getBoundingClientRect();return{node:t,x:e,y:o,width:n,height:r}})),r=[];for(const t of n){const e=r.some((e=>{return n=e,!((o=t).x+o.width<n.x||n.x+n.width<o.x||o.y+o.height<n.y||n.y+n.height<o.y);var o,n}));o.select(t.node).classed("occluded",e),e||r.push(t)}return r}return function(t,{x:e=t=>t[0],y:r=t=>t[1],r:l=()=>3,label:a=(t,e)=>e,fill:s="#333",stroke:i="white",threshold:c=2e3,width:d=null,height:h=null,target:f=null,font:u="10px sans-serif",hover:g=!0,onHover:p=t=>t,hoverFont:y="bolder 12px sans-serif",labelsInCentroids:b=!0,backgroundFill:m="#fefefe01",strokeWidth:v=5,showVoronoi:x=!1,voronoiStroke:w="#ccc",showAnchors:k=!1,anchorsStroke:A="orange",anchorsFill:j="none",useOcclusion:P=!0,occludedStyle:C="opacity: 0.2",showPoints:L=!1,pointsFill:S="#ccc",pointsSelectedFill:M="firebrick",pointsStroke:O="#ccc",renderer:$="svg",debug:T=!1,selected:F=null,padding:I=3}={}){t=t.filter(((t,o)=>void 0!==e(t,o)&&null!==e(t,o)&&void 0!==r(t,o)&&null!==r(t,o)));let E=o.extent(t,e),B=o.extent(t,r);d=d||E[1]-E[0],h=h||B[1]-B[0],T&&console.log("✅ smartLabels renderer",$),"canvas"===$.toLocaleLowerCase()?(f=o.select(f)||o.create("canvas").attr("width",d).attr("height",h),P=!1):f=f||o.create("svg").attr("viewBox",[0,0,d,h]);const D=o.Delaunay.from(t,e,r),V=D.voronoi([E[0]-1,B[0]-1,E[1]+1,B[1]+1]);let R=t.map(((t,e)=>[t,V.cellPolygon(e)]));function W(t,o,n){if(!o){const l=D.find(e(t,n),r(t,n));if(-1===l)return console.log("couldn't find cell",l,t,e(t,n),r(t,n)),null;o=R[l][1]}return o}function q(n){T&&console.log("renderCanvasAnchorsVoronoiPoints","showAnchors",k,"labelsInCentroids",b,"showVoronoi",x,"showPoints",L),(k||b)&&R.forEach((({d:t,cell:l,show:a},s)=>{if(!a)return;const[i,c]=o.polygonCentroid(l);n.beginPath(),n.moveTo(i,c),n.lineTo(e(t,s),r(t,s)),n.strokeStyle=A,n.stroke()})),x&&(n.beginPath(),V.render(n),n.strokeStyle=w,n.stroke()),L&&(n.beginPath(),n.save(),n.globalAlpha=.7,n.fillStyle="black",t.forEach(((t,o)=>{n.beginPath(),n.arc(e(t,o),r(t,o),l(t,o),0,2*Math.PI)})),n.restore(),n.fillStyle=S,n.fill(),n.strokeStyle=O,n.stroke())}function z(t,n){R.forEach((({d:c,cell:d,show:h},f)=>{if(!h&&f!==n)return;const[g,p]=o.polygonCentroid(d),m=(Math.round(Math.atan2(p-r(c,f),g-e(c,f))/Math.PI*2)+4)%4;t.save();const x=l(c,f)+I,w=0===m?x:2===m?-x:x,k=1===m?x:3===m?-x:x;t.translate(b?g:e(c,f)+w,b?p:r(c,f)+k),t.textAlign=0===m?"left":1===m?"center":2===m?"right":"center",t.textBaseline=0===m?"middle":1===m?"top":2===m?"middle":"bottom",t.font=f===n?y:u,t.fillStyle=s,t.strokeStyle=i,t.lineWidth=v,t.strokeText(a(c,f),0,0),t.fillText(a(c,f),0,0),t.restore()}))}return R=R.map((([t,e],o)=>[t,W(t,e,o)])).map((([t,e])=>({d:t,cell:e,show:-o.polygonArea(e)>c}))),"canvas"===$.toLocaleLowerCase()?function(){const t=f.node().getContext("2d");q(t),z(t,F),g&&(T&&console.log("setting onmousemove",f),f.on("mousemove",(e=>{const[n,r]=o.pointer(e),l=D.find(n,r);l!==F&&(F=l,t.clearRect(0,0,d,h),q(t),p&&"function"==typeof p&&p(l),z(t,F))})))}():function(){let t=null;P&&f.selectAll("style.smartLabels").data([0]).join("style").attr("class","smartLabels").html(`\n svg g.labels > text.occluded:not(.selected) { ${C} }\n `);const c=f.selectAll("rect.smartLabels").data([0]).join("rect").attr("class","smartLabels").attr("width",d).attr("height",h).attr("fill",m).attr("stroke","none"),$={top:t=>t.attr("text-anchor","middle").attr("y",((t,e)=>-(l(t,e)+I))),right:t=>t.attr("text-anchor","start").attr("dy","0.35em").attr("x",((t,e)=>l(t,e)+I)),bottom:t=>t.attr("text-anchor","middle").attr("dy","0.71em").attr("y",((t,e)=>l(t,e)+I)),left:t=>t.attr("text-anchor","end").attr("dy","0.35em").attr("x",((t,e)=>-(l(t,e)+I)))};let T;(k||b)&&(t=f.selectAll("g#anchors").data([R]).join("g").attr("pointer-events","none").attr("id","anchors").attr("stroke",A).attr("fill",j).selectAll("path.anchor").data((t=>t)).join("path").attr("class","anchor").attr("display",(({show:t})=>t?null:"none")).attr("d",(({d:t,cell:n},l)=>n?`M${o.polygonCentroid(n)}L${e(t,l)},${r(t,l)}`:null))),x&&f.selectAll("path#voronoi").data([1]).join("path").attr("id","voronoi").attr("stroke",w).attr("pointer-events","none").attr("d",V.render()),L&&(T=f.selectAll("circle#points").data([1]).join("path").attr("id","points").attr("pointer-events","none").attr("stroke",O).attr("fill",S).attr("d",D.renderPoints(null,2)));const F=f.selectAll("g.labels").data([R]).join("g").attr("class","labels").attr("fill",s).attr("stroke",i).attr("stroke-width",v).attr("paint-order","stroke").attr("pointer-events","none").selectAll("text").data((t=>t)).join("text").style("font",u).each((function({d:t,cell:n},l){if(!n)return;const[a,s]=o.polygonCentroid(n),i=(Math.round(Math.atan2(s-r(t,l),a-e(t,l))/Math.PI*2)+4)%4;o.select(this).call(0===i?$.right:3===i?$.top:1===i?$.bottom:$.left)})).attr("transform",(({d:t,cell:n},l)=>{if(b){const[t,e]=o.polygonCentroid(n);return`translate(${t}, ${e})`}return`translate(${e(t,l)}, ${r(t,l)})`})).attr("display",(({show:t})=>t?null:"none")).text((({d:t},e,o)=>a(t,e,o)));let E=null;if(g&&c.on("mousemove",(e=>{const n=D.find(...o.pointer(e));n!==E&&(E=n,F.attr("display",(({show:t},e)=>e===E||t?null:"none")).style("font",((t,e)=>e===E?y:u)).classed("selected",((t,e)=>e===E)).filter(((t,e)=>e===E)).raise(),t&&t.attr("display",(({show:t},e)=>t||e===E?null:"none")),L&&T.attr("fill",((t,e)=>M)).classed("selected",((t,e)=>e===E)),p&&"function"==typeof p&&p(n))})),P){const t=new MutationObserver((function(){document.contains(f.node())&&(f.call(n,"g.labels > text"),t.disconnect())}));t.observe(document,{attributes:!1,childList:!0,characterData:!1,subtree:!0})}}(),Object.assign(f.node(),{delaunay:D,voronoi:V,cells:R})}}));
1
+ // smart-labels v0.0.3 Copyright (c) 2024 John Alexis Guerra Gómez
2
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("d3")):"function"==typeof define&&define.amd?define(["d3"],e):(t="undefined"!=typeof globalThis?globalThis:t||self).smartLabels=e(t.d3)}(this,(function(t){"use strict";function e(t){var e=Object.create(null);return t&&Object.keys(t).forEach((function(o){if("default"!==o){var n=Object.getOwnPropertyDescriptor(t,o);Object.defineProperty(e,o,n.get?n:{enumerable:!0,get:function(){return t[o]}})}})),e.default=t,Object.freeze(e)}var o=e(t);function n(t,e="text"){const n=o.sort(t.selectAll(e),(t=>+t.getAttribute("data-priority"))).reverse().map((t=>{const{x:e,y:o,width:n,height:r}=t.getBoundingClientRect();return{node:t,x:e,y:o,width:n,height:r}})),r=[];for(const t of n){const e=r.some((e=>{return n=e,!((o=t).x+o.width<n.x||n.x+n.width<o.x||o.y+o.height<n.y||n.y+n.height<o.y);var o,n}));o.select(t.node).classed("occluded",e),e||r.push(t)}return r}return function(t,{x:e=t=>t[0],y:r=t=>t[1],r:l=()=>3,label:a=(t,e)=>e,fill:s="#333",stroke:i="white",threshold:c=2e3,width:d=null,height:h=null,target:f=null,font:u="10px sans-serif",hover:g=!0,onHover:p=t=>t,hoverFont:y="bolder 12px sans-serif",labelsInCentroids:b=!0,backgroundFill:m="#fefefe01",strokeWidth:v=5,showVoronoi:x=!1,voronoiStroke:w="#ccc",showAnchors:k=!1,anchorsStroke:A="orange",anchorsFill:L="none",useOcclusion:j=!0,occludedStyle:C="opacity: 0.2",showPoints:P=!1,pointsFill:S="#ccc",pointsSelectedFill:M="firebrick",pointsStroke:O="#ccc",renderer:T="svg",debug:$=!1,selected:E=null,padding:F=3}={}){t=t.filter(((t,o)=>void 0!==e(t,o)&&null!==e(t,o)&&void 0!==r(t,o)&&null!==r(t,o)));let I=o.extent(t,e),B=o.extent(t,r);if(d=d||I[1]-I[0],h=h||B[1]-B[0],$&&console.log("✅ smartLabels renderer",T),!function(t,e){return t&&t.node&&(t=t.node()),"canvas"===e.toLocaleLowerCase()?t instanceof HTMLCanvasElement:t instanceof SVGElement}(f,T))throw $&&console.log("❌ smartLabels Target doesn't match the renderer",f,T),new Error("Smartlabels Target doesn't match the renderer",f,T);"canvas"===T.toLocaleLowerCase()?(f=f?o.select(f.node?f.node():f):o.create("canvas").attr("width",d).attr("height",h),j=!1):f=(f=f?o.select(f.node?f.node():f):o.create("svg").attr("viewBox",[0,0,d,h]))||o.create("svg").attr("viewBox",[0,0,d,h]);const V=o.Delaunay.from(t,e,r),D=V.voronoi([I[0]-1,B[0]-1,I[1]+1,B[1]+1]);let H=t.map(((t,e)=>[t,D.cellPolygon(e)]));function R(t,o,n){if(!o){const l=V.find(e(t,n),r(t,n));if(-1===l)return console.log("couldn't find cell",l,t,e(t,n),r(t,n)),null;o=H[l][1]}return o}function W(n){$&&console.log("renderCanvasAnchorsVoronoiPoints","showAnchors",k,"labelsInCentroids",b,"showVoronoi",x,"showPoints",P),(k||b)&&H.forEach((({d:t,cell:l,show:a},s)=>{if(!a)return;const[i,c]=o.polygonCentroid(l);n.beginPath(),n.moveTo(i,c),n.lineTo(e(t,s),r(t,s)),n.strokeStyle=A,n.stroke()})),x&&(n.beginPath(),D.render(n),n.strokeStyle=w,n.stroke()),P&&(n.beginPath(),n.save(),n.globalAlpha=.7,n.fillStyle="black",t.forEach(((t,o)=>{n.beginPath(),n.arc(e(t,o),r(t,o),l(t,o),0,2*Math.PI)})),n.restore(),n.fillStyle=S,n.fill(),n.strokeStyle=O,n.stroke())}function q(t,n){H.forEach((({d:c,cell:d,show:h},f)=>{if(!h&&f!==n)return;const[g,p]=o.polygonCentroid(d),m=(Math.round(Math.atan2(p-r(c,f),g-e(c,f))/Math.PI*2)+4)%4;t.save();const x=l(c,f)+F,w=0===m?x:2===m?-x:x,k=1===m?x:3===m?-x:x;t.translate(b?g:e(c,f)+w,b?p:r(c,f)+k),t.textAlign=0===m?"left":1===m?"center":2===m?"right":"center",t.textBaseline=0===m?"middle":1===m?"top":2===m?"middle":"bottom",t.font=f===n?y:u,t.fillStyle=s,t.strokeStyle=i,t.lineWidth=v,t.strokeText(a(c,f),0,0),t.fillText(a(c,f),0,0),t.restore()}))}return H=H.map((([t,e],o)=>[t,R(t,e,o)])).map((([t,e])=>({d:t,cell:e,show:-o.polygonArea(e)>c}))),"canvas"===T.toLocaleLowerCase()?function(){const t=f.node().getContext("2d");W(t),q(t,E),g&&($&&console.log("setting onmousemove",f),f.on("mousemove",(e=>{const[n,r]=o.pointer(e),l=V.find(n,r);l!==E&&(E=l,t.clearRect(0,0,d,h),W(t),p&&"function"==typeof p&&p(l),q(t,E))})))}():function(){let t=null;j&&f.selectAll("style.smartLabels").data([0]).join("style").attr("class","smartLabels").html(`\n svg g.labels > text.occluded:not(.selected) { ${C} }\n `);const c=f.selectAll("rect.smartLabels").data([0]).join("rect").attr("class","smartLabels").attr("width",d).attr("height",h).attr("fill",m).attr("stroke","none"),T={top:t=>t.attr("text-anchor","middle").attr("y",((t,e)=>-(l(t,e)+F))),right:t=>t.attr("text-anchor","start").attr("dy","0.35em").attr("x",((t,e)=>l(t,e)+F)),bottom:t=>t.attr("text-anchor","middle").attr("dy","0.71em").attr("y",((t,e)=>l(t,e)+F)),left:t=>t.attr("text-anchor","end").attr("dy","0.35em").attr("x",((t,e)=>-(l(t,e)+F)))};let $;(k||b)&&(t=f.selectAll("g#anchors").data([H]).join("g").attr("pointer-events","none").attr("id","anchors").attr("stroke",A).attr("fill",L).selectAll("path.anchor").data((t=>t)).join("path").attr("class","anchor").attr("display",(({show:t})=>t?null:"none")).attr("d",(({d:t,cell:n},l)=>n?`M${o.polygonCentroid(n)}L${e(t,l)},${r(t,l)}`:null))),x&&f.selectAll("path#voronoi").data([1]).join("path").attr("id","voronoi").attr("stroke",w).attr("pointer-events","none").attr("d",D.render()),P&&($=f.selectAll("circle#points").data([1]).join("path").attr("id","points").attr("pointer-events","none").attr("stroke",O).attr("fill",S).attr("d",V.renderPoints(null,2)));const E=f.selectAll("g.labels").data([H]).join("g").attr("class","labels").attr("fill",s).attr("stroke",i).attr("stroke-width",v).attr("paint-order","stroke").attr("pointer-events","none").selectAll("text").data((t=>t)).join("text").style("font",u).each((function({d:t,cell:n},l){if(!n)return;const[a,s]=o.polygonCentroid(n),i=(Math.round(Math.atan2(s-r(t,l),a-e(t,l))/Math.PI*2)+4)%4;o.select(this).call(0===i?T.right:3===i?T.top:1===i?T.bottom:T.left)})).attr("transform",(({d:t,cell:n},l)=>{if(b){const[t,e]=o.polygonCentroid(n);return`translate(${t}, ${e})`}return`translate(${e(t,l)}, ${r(t,l)})`})).attr("display",(({show:t})=>t?null:"none")).text((({d:t},e,o)=>a(t,e,o)));let I=null;if(g&&c.on("mousemove",(e=>{const n=V.find(...o.pointer(e));n!==I&&(I=n,E.attr("display",(({show:t},e)=>e===I||t?null:"none")).style("font",((t,e)=>e===I?y:u)).classed("selected",((t,e)=>e===I)).filter(((t,e)=>e===I)).raise(),t&&t.attr("display",(({show:t},e)=>t||e===I?null:"none")),P&&$.attr("fill",((t,e)=>M)).classed("selected",((t,e)=>e===I)),p&&"function"==typeof p&&p(n))})),j){const t=new MutationObserver((function(){document.contains(f.node())&&(f.call(n,"g.labels > text"),t.disconnect())}));t.observe(document,{attributes:!1,childList:!0,characterData:!1,subtree:!0})}}(),Object.assign(f.node(),{delaunay:V,voronoi:D,cells:H})}}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "smart-labels",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "A basic library for adding labels to a visualization when there is enough space",
5
5
  "type": "module",
6
6
  "main": "dist/smartLabels.min.js",
package/src/index.js CHANGED
@@ -72,12 +72,37 @@ export default function smartLabels(
72
72
  height = height || yExtent[1] - yExtent[0];
73
73
 
74
74
  if (debug) console.log("✅ smartLabels renderer", renderer);
75
+
76
+ function checkIfTargetMatchesRenderer(target, renderer) {
77
+ if (target && target.node) {
78
+ target = target.node();
79
+ }
80
+ if (renderer.toLocaleLowerCase() === "canvas") {
81
+ return target instanceof HTMLCanvasElement;
82
+ } else {
83
+ return target instanceof SVGElement;
84
+ }
85
+ }
86
+
87
+ if (!checkIfTargetMatchesRenderer(target, renderer)) {
88
+ if (debug) console.log("❌ smartLabels Target doesn't match the renderer", target, renderer);
89
+ throw new Error("Smartlabels Target doesn't match the renderer", target, renderer);
90
+ }
91
+
92
+ // Try to reuse the target
75
93
  if (renderer.toLocaleLowerCase() === "canvas") {
76
- target =
77
- d3.select(target) ||
78
- d3.create("canvas").attr("width", width).attr("height", height);
94
+ if (target) {
95
+ target = d3.select(target.node ? target.node() : target);
96
+ } else {
97
+ target = d3.create("canvas").attr("width", width).attr("height", height);
98
+ }
79
99
  useOcclusion = false;
80
100
  } else {
101
+ if (target) {
102
+ target = d3.select(target.node ? target.node() : target);
103
+ } else {
104
+ target = d3.create("svg").attr("viewBox", [0, 0, width, height]);
105
+ }
81
106
  target = target || d3.create("svg").attr("viewBox", [0, 0, width, height]);
82
107
  }
83
108