smart-labels 0.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 John Alexis Guerra Gómez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,457 @@
1
+ // smart-labels v0.0.1 Copyright (c) 2024 John Alexis Guerra Gómez
2
+ import * as d3 from 'd3';
3
+
4
+ // Based on https://observablehq.com/@d3/voronoi-labels by Mike Bostock
5
+
6
+ // ISC License
7
+
8
+ // Copyright 2018–2023 Observable, Inc.
9
+ // Permission to use, copy, modify, and/or distribute this software for any
10
+ // purpose with or without fee is hereby granted, provided that the above
11
+ // copyright notice and this permission notice appear in all copies.
12
+
13
+ // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14
+ // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15
+ // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16
+ // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17
+ // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18
+ // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19
+ // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20
+ function smartLabels(
21
+ data,
22
+ {
23
+ x = (d) => d[0], // x coordinate accessor, expected to be in pixels
24
+ y = (d) => d[1], // y coordinate accessor, expected to be in pixels
25
+ label = (d, i) => i, // Accessor for the label
26
+ fill = "#333", // label fill color
27
+ stroke = "white", // label stroke color
28
+ threshold = 2000, // Areas over this size would get labels
29
+ width = null,
30
+ height = null,
31
+ target = null, // Where do you want it to draw
32
+ font = "10px sans-serif",
33
+ hover = true, // Show label of the hovered point
34
+ onHover = (i) => i, // callback when hovered, will pass the index of the selected element
35
+ hoverFont = "bolder 12px sans-serif",
36
+ labelsInCentroids = true,
37
+
38
+ backgroundFill = "#fefefe01", // What to paint the bg rect of the labels. Needed for the onHover
39
+ strokeWidth = 5,
40
+
41
+ showVoronoi = false,
42
+ voronoiStroke = "#ccc",
43
+
44
+ showAnchors = false,
45
+ anchorsStroke = "orange",
46
+ anchorsFill = "none",
47
+
48
+ useOcclusion = true,
49
+ occludedStyle = "opacity: 0.2", // css style rules to be used on occluded labels
50
+
51
+ // For debugging
52
+ showPoints = false,
53
+ pointsFill = "#ccc",
54
+ pointsSelectedFill = "firebrick",
55
+ pointsStroke = "#ccc",
56
+ renderer = "svg",
57
+ debug = false,
58
+ } = {}
59
+ ) {
60
+ data = data.filter(
61
+ (d) =>
62
+ x(d) !== undefined && x(d) !== null && y(d) !== undefined && y(d) !== null
63
+ );
64
+
65
+ let xExtent = d3.extent(data, x),
66
+ yExtent = d3.extent(data, y);
67
+ width = width || xExtent[1] - xExtent[0];
68
+ height = height || yExtent[1] - yExtent[0];
69
+
70
+ if (debug) console.log("✅ smartLabels renderer", renderer);
71
+ if (renderer.toLocaleLowerCase() === "canvas") {
72
+ target =
73
+ d3.select(target) ||
74
+ d3.create("canvas").attr("width", width).attr("height", height);
75
+ useOcclusion = false;
76
+ } else {
77
+ target = target || d3.create("svg").attr("viewBox", [0, 0, width, height]);
78
+ }
79
+
80
+ const delaunay = d3.Delaunay.from(data, x, y);
81
+ const voronoi = delaunay.voronoi([
82
+ xExtent[0] - 1,
83
+ yExtent[0] - 1,
84
+ xExtent[1] + 1,
85
+ yExtent[1] + 1,
86
+ ]);
87
+
88
+ let cells = data.map((d, i) => [d, voronoi.cellPolygon(i)]);
89
+ // Replace null cells with the nearest one
90
+ cells = cells
91
+ .map(([d, cell]) => [d, getNearestCell(d, cell)])
92
+ .map(([d, cell]) => ({ d, cell, show: -d3.polygonArea(cell) > threshold }));
93
+
94
+ // cells can be null when we have duplicated coords
95
+ // https://github.com/d3/d3-delaunay/issues/106
96
+ function getNearestCell(d, cell) {
97
+ if (!cell) {
98
+ const i = delaunay.find(x(d), y(d));
99
+ if (i === -1) {
100
+ console.log("couldn't find cell", i, d, x(d), y(d));
101
+ return null;
102
+ }
103
+ cell = cells[i][1];
104
+ }
105
+ return cell;
106
+ }
107
+
108
+ function renderSVG() {
109
+ let anchors = null;
110
+ if (useOcclusion) {
111
+ target
112
+ .selectAll("style.smartLabels")
113
+ .data([0])
114
+ .join("style")
115
+ .attr("class", "smartLabels").html(`
116
+ svg g.labels > text.occluded:not(.selected) { ${occludedStyle} }
117
+ `);
118
+ }
119
+
120
+ const mouseRect = target
121
+ .selectAll("rect.smartLabels")
122
+ .data([0])
123
+ .join("rect")
124
+ .attr("class", "smartLabels")
125
+ .attr("width", width)
126
+ .attr("height", height)
127
+ .attr("fill", backgroundFill)
128
+ .attr("stroke", "none");
129
+
130
+ const orient = {
131
+ top: (text) => text.attr("text-anchor", "middle").attr("y", -6),
132
+ right: (text) =>
133
+ text.attr("text-anchor", "start").attr("dy", "0.35em").attr("x", 6),
134
+ bottom: (text) =>
135
+ text.attr("text-anchor", "middle").attr("dy", "0.71em").attr("y", 6),
136
+ left: (text) =>
137
+ text.attr("text-anchor", "end").attr("dy", "0.35em").attr("x", -6),
138
+ };
139
+
140
+ if (showAnchors || labelsInCentroids) {
141
+ anchors = target
142
+ .selectAll("g#anchors")
143
+ .data([cells])
144
+ .join("g")
145
+ .attr("pointer-events", "none")
146
+ .attr("id", "anchors")
147
+ .attr("stroke", anchorsStroke)
148
+ .attr("fill", anchorsFill)
149
+ .selectAll("path.anchor")
150
+ .data((d) => d)
151
+ .join("path")
152
+ .attr("class", "anchor")
153
+ .attr("display", ({ show }) => (show ? null : "none"))
154
+ .attr("d", ({ d, cell }) =>
155
+ cell ? `M${d3.polygonCentroid(cell)}L${x(d)},${y(d)}` : null
156
+ );
157
+ }
158
+
159
+ if (showVoronoi) {
160
+ target
161
+ .selectAll("path#voronoi")
162
+ .data([1])
163
+ .join("path")
164
+ .attr("id", "voronoi")
165
+ .attr("stroke", voronoiStroke)
166
+ .attr("pointer-events", "none")
167
+ .attr("d", voronoi.render());
168
+ }
169
+
170
+ let points;
171
+ if (showPoints) {
172
+ points = target
173
+ .selectAll("circle#points")
174
+ .data([1])
175
+ .join("path")
176
+ .attr("id", "points")
177
+ .attr("pointer-events", "none")
178
+ .attr("stroke", pointsStroke)
179
+ .attr("fill", pointsFill)
180
+ .attr("d", delaunay.renderPoints(null, 2));
181
+ }
182
+
183
+ const labels = target
184
+ .selectAll("g.labels")
185
+ .data([cells])
186
+ .join("g")
187
+ .attr("class", "labels")
188
+ .attr("fill", fill)
189
+
190
+ .attr("stroke", stroke)
191
+ .attr("stroke-width", strokeWidth)
192
+ .attr("paint-order", "stroke")
193
+ .attr("pointer-events", "none")
194
+ .selectAll("text")
195
+ .data((d) => d)
196
+ .join("text")
197
+ .style("font", font)
198
+ .each(function ({ d, cell }) {
199
+ if (!cell) return;
200
+ const [cx, cy] = d3.polygonCentroid(cell);
201
+ const angle =
202
+ (Math.round((Math.atan2(cy - y(d), cx - x(d)) / Math.PI) * 2) + 4) %
203
+ 4;
204
+
205
+ d3.select(this).call(
206
+ angle === 0
207
+ ? orient.right
208
+ : angle === 3
209
+ ? orient.top
210
+ : angle === 1
211
+ ? orient.bottom
212
+ : orient.left
213
+ );
214
+ })
215
+ .attr("transform", ({ d, cell }) => {
216
+ if (labelsInCentroids) {
217
+ const [cx, cy] = d3.polygonCentroid(cell);
218
+
219
+ return `translate(${cx}, ${cy})`;
220
+ } else {
221
+ return `translate(${x(d)}, ${y(d)})`;
222
+ }
223
+ })
224
+ .attr("display", ({ show }) => (show ? null : "none"))
225
+ .text(({ d }, i, all) => label(d, i, all));
226
+
227
+ let selected = null;
228
+ if (hover) {
229
+ mouseRect.on("mousemove", (event) => {
230
+ // Find the selected point
231
+ const i = delaunay.find(...d3.pointer(event));
232
+ if (i === selected) return;
233
+ selected = i;
234
+
235
+ // Update labels
236
+ labels
237
+ .attr("display", ({ show }, i) =>
238
+ i === selected || show ? null : "none"
239
+ )
240
+ .style("font", (_, i) => (i === selected ? hoverFont : font))
241
+ .classed("selected", (_, i) => i === selected)
242
+ .filter((_, i) => i === selected)
243
+ .raise();
244
+
245
+ anchors &&
246
+ anchors.attr("display", ({ show }, i) =>
247
+ show || i === selected ? null : "none"
248
+ );
249
+
250
+ if (showPoints) {
251
+ points
252
+ .attr("fill", (_, i) =>
253
+ i === selected ? pointsSelectedFill : pointsSelectedFill
254
+ )
255
+ .classed("selected", (_, i) => i === selected);
256
+ }
257
+
258
+ if (onHover && typeof onHover === "function") onHover(i);
259
+ });
260
+ }
261
+
262
+ // Setup a MutationObserver to wait for the element to be rendered
263
+ // https://stackoverflow.com/questions/15875128/is-there-element-rendered-event
264
+ if (useOcclusion) {
265
+ const observer = new MutationObserver(function () {
266
+ if (document.contains(target.node())) {
267
+ target.call(occlusion, "g.labels > text");
268
+ observer.disconnect();
269
+ }
270
+ });
271
+
272
+ observer.observe(document, {
273
+ attributes: false,
274
+ childList: true,
275
+ characterData: false,
276
+ subtree: true,
277
+ });
278
+ }
279
+ } // renderSVG
280
+
281
+ function renderCanvas() {
282
+ const context = target.node().getContext("2d");
283
+ // const ratio = window.devicePixelRatio || 1;
284
+ // target.attr("width", width * ratio).attr("height", height * ratio);
285
+ // context.scale(ratio, ratio);
286
+ // context.clearRect(0, 0, width, height);
287
+
288
+ if (showAnchors || labelsInCentroids) {
289
+ cells.forEach(({ d, cell, show }) => {
290
+ if (!show) return;
291
+ const [cx, cy] = d3.polygonCentroid(cell);
292
+ context.beginPath();
293
+ context.moveTo(cx, cy);
294
+ context.lineTo(x(d), y(d));
295
+ context.strokeStyle = anchorsStroke;
296
+ context.stroke();
297
+ });
298
+ }
299
+
300
+ if (showVoronoi) {
301
+ context.beginPath();
302
+ voronoi.render(context);
303
+ context.strokeStyle = voronoiStroke;
304
+ context.stroke();
305
+ }
306
+
307
+ if (showPoints) {
308
+ context.beginPath();
309
+ delaunay.renderPoints(context, 2);
310
+ context.fillStyle = pointsFill;
311
+ context.fill();
312
+ context.strokeStyle = pointsStroke;
313
+ context.stroke();
314
+ }
315
+
316
+ cells.forEach(({ d, cell, show }) => {
317
+ if (!show) return;
318
+ const [cx, cy] = d3.polygonCentroid(cell);
319
+ const angle =
320
+ (Math.round((Math.atan2(cy - y(d), cx - x(d)) / Math.PI) * 2) + 4) % 4;
321
+
322
+ context.save();
323
+ context.translate(
324
+ labelsInCentroids ? cx : x(d),
325
+ labelsInCentroids ? cy : y(d)
326
+ );
327
+ context.textAlign =
328
+ angle === 0
329
+ ? "left"
330
+ : angle === 1
331
+ ? "center"
332
+ : angle === 2
333
+ ? "right"
334
+ : "center";
335
+ context.textBaseline =
336
+ angle === 0
337
+ ? "middle"
338
+ : angle === 1
339
+ ? "top"
340
+ : angle === 2
341
+ ? "middle"
342
+ : "bottom";
343
+ context.font = font;
344
+ context.fillStyle = fill;
345
+ context.strokeStyle = stroke;
346
+ context.lineWidth = strokeWidth;
347
+ context.strokeText(label(d), 0, 0);
348
+ context.fillText(label(d), 0, 0);
349
+ context.restore();
350
+ });
351
+
352
+ let selected = null;
353
+ if (hover) {
354
+ if (debug) console.log("setting onmousemove", target);
355
+
356
+ target.on("mousemove", (event) => {
357
+ const [mx, my] = d3.pointer(event);
358
+ const i = delaunay.find(mx, my);
359
+ if (i === selected) return;
360
+ selected = i;
361
+
362
+ context.clearRect(0, 0, width, height);
363
+ cells.forEach(({ d, cell, show }, index) => {
364
+ if (!show && index !== selected) return;
365
+ const [cx, cy] = d3.polygonCentroid(cell);
366
+ const angle =
367
+ (Math.round((Math.atan2(cy - y(d), cx - x(d)) / Math.PI) * 2) + 4) %
368
+ 4;
369
+
370
+ context.save();
371
+ context.translate(
372
+ labelsInCentroids ? cx : x(d),
373
+ labelsInCentroids ? cy : y(d)
374
+ );
375
+ context.textAlign =
376
+ angle === 0
377
+ ? "left"
378
+ : angle === 1
379
+ ? "center"
380
+ : angle === 2
381
+ ? "right"
382
+ : "center";
383
+ context.textBaseline =
384
+ angle === 0
385
+ ? "middle"
386
+ : angle === 1
387
+ ? "top"
388
+ : angle === 2
389
+ ? "middle"
390
+ : "bottom";
391
+ context.font = index === selected ? hoverFont : font;
392
+ context.fillStyle = fill;
393
+ context.strokeStyle = stroke;
394
+ context.lineWidth = strokeWidth;
395
+ context.strokeText(label(d), 0, 0);
396
+ context.fillText(label(d), 0, 0);
397
+ context.restore();
398
+ });
399
+
400
+ if (onHover && typeof onHover === "function") onHover(i);
401
+ });
402
+ }
403
+ } // renderCanvas
404
+
405
+ if (renderer.toLocaleLowerCase() === "canvas") {
406
+ renderCanvas();
407
+ } else {
408
+ renderSVG();
409
+ }
410
+
411
+ return Object.assign(target.node(), { delaunay, voronoi, cells });
412
+ }
413
+
414
+ // https://observablehq.com/@d3/occlusion
415
+ // ISC License
416
+
417
+ // Copyright 2020-2023 Philippe Rivière
418
+ // Permission to use, copy, modify, and/or distribute this software for any
419
+ // purpose with or without fee is hereby granted, provided that the above
420
+ // copyright notice and this permission notice appear in all copies.
421
+
422
+ // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
423
+ // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
424
+ // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
425
+ // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
426
+ // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
427
+ // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
428
+ // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
429
+ function occlusion(svg, against = "text") {
430
+ const nodes = d3
431
+ .sort(svg.selectAll(against), (node) => +node.getAttribute("data-priority"))
432
+ .reverse()
433
+ .map((node) => {
434
+ const { x, y, width, height } = node.getBoundingClientRect();
435
+ return { node, x, y, width, height };
436
+ });
437
+
438
+ const visible = [];
439
+ for (const d of nodes) {
440
+ const occluded = visible.some((e) => intersectRect(d, e));
441
+ d3.select(d.node).classed("occluded", occluded);
442
+ if (!occluded) visible.push(d);
443
+ }
444
+ return visible;
445
+ }
446
+
447
+ // This intersection function works for rect and text, but not so much for circles.
448
+ function intersectRect(a, b) {
449
+ return !(
450
+ a.x + a.width < b.x ||
451
+ b.x + b.width < a.x ||
452
+ a.y + a.height < b.y ||
453
+ b.y + b.height < a.y
454
+ );
455
+ }
456
+
457
+ export { occlusion, smartLabels };