chartjs-chart-treemap 4.2.2 → 5.0.0-next.10

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,13 +1,13 @@
1
1
  /*!
2
- * chartjs-chart-treemap v0.0.0-development
2
+ * chartjs-chart-treemap v5.0.0-next.10
3
3
  * https://chartjs-chart-treemap.pages.dev/
4
4
  * (c) 2026 Jukka Kurkela
5
5
  * Released under the MIT license
6
6
  */
7
- import { DatasetController, Chart, registry, Element } from 'chart.js';
8
- import { toTRBL, toTRBLCorners, isObject, defined, toFont, valueOrDefault, isArray, isNumber, clipArea, unclipArea, addRoundedRectPath } from 'chart.js/helpers';
7
+ import { DatasetController, registry, Chart, Element } from 'chart.js';
8
+ import { toTRBL, toTRBLCorners, isObject, toFont, isArray, defined, isNumber, valueOrDefault, clipArea, unclipArea, addRoundedRectPath } from 'chart.js/helpers';
9
9
 
10
- var version = "0.0.0-development";
10
+ var version = "5.0.0-next.10";
11
11
 
12
12
  function scaleRect(sq, xScale, yScale, sp) {
13
13
  const sp2 = sp * 2;
@@ -26,26 +26,12 @@ function scaleRect(sq, xScale, yScale, sp) {
26
26
  function rectNotEqual(r1, r2) {
27
27
  return !r1 || !r2 || r1.x !== r2.x || r1.y !== r2.y || r1.w !== r2.w || r1.h !== r2.h || r1.rtl !== r2.rtl || r1.unsorted !== r2.unsorted;
28
28
  }
29
- function arrayNotEqual(a, b) {
30
- let i;
31
- let n;
32
- if (!a || !b) {
33
- return true;
34
- }
35
- if (a === b) {
36
- return false;
37
- }
38
- if (a.length !== b.length) {
39
- return true;
40
- }
41
- for(i = 0, n = a.length; i < n; ++i){
42
- if (a[i] !== b[i]) {
43
- return true;
44
- }
45
- }
46
- return false;
47
- }
48
29
 
30
+ const layoutDefaults = {
31
+ displayMode: 'containerBoxes',
32
+ rtl: false,
33
+ spacing: 0.5
34
+ };
49
35
  function limit(value, min, max) {
50
36
  return Math.max(Math.min(value, max), min);
51
37
  }
@@ -71,6 +57,14 @@ function parseBorderRadius(value, maxW, maxH) {
71
57
 
72
58
  function getDims(itm, w2, s2, key) {
73
59
  const a = itm._normalized;
60
+ if (!a) {
61
+ return {
62
+ d1: 0,
63
+ d2: 0,
64
+ h: 0,
65
+ w: 0
66
+ };
67
+ }
74
68
  const ar = w2 * a / s2;
75
69
  const d1 = Math.sqrt(a * ar);
76
70
  const d2 = a / d1;
@@ -84,24 +78,14 @@ function getDims(itm, w2, s2, key) {
84
78
  };
85
79
  }
86
80
  const getX = (rect, w)=>rect.rtl ? rect.x + rect.iw - w : rect.x + rect._ix;
87
- function buildRow(rect, itm, dims, sum) {
88
- const r = {
89
- _data: itm._data,
90
- a: itm._normalized,
91
- h: dims.h,
92
- s: sum,
93
- v: itm.value,
94
- vs: itm.values,
95
- w: dims.w,
96
- x: getX(rect, dims.w),
97
- y: rect.y + rect._iy
98
- };
99
- if (itm.group) {
100
- r.g = itm.group;
101
- r.l = itm.level;
102
- r.gs = itm.groupSum;
103
- }
104
- return r;
81
+ function assignRow(rect, itm, dims, sum) {
82
+ itm.a = itm._normalized;
83
+ itm.h = dims.h;
84
+ itm.s = sum;
85
+ itm.w = dims.w;
86
+ itm.x = getX(rect, dims.w);
87
+ itm.y = rect.y + rect._iy;
88
+ delete itm._normalized;
105
89
  }
106
90
  class Rect {
107
91
  get area() {
@@ -127,19 +111,17 @@ class Rect {
127
111
  const row = arr.get();
128
112
  const w2 = side * side;
129
113
  const s2 = sum * sum;
130
- const ret = [];
131
114
  let maxd2 = 0;
132
115
  let totd1 = 0;
133
116
  for (const itm of row){
134
117
  const dims = getDims(itm, w2, s2, key);
135
118
  totd1 += dims.d1;
136
119
  maxd2 = Math.max(maxd2, dims.d2);
137
- ret.push(buildRow(this, itm, dims, arr.sum));
120
+ assignRow(this, itm, dims, arr.sum);
138
121
  this[key] += dims.d1;
139
122
  }
140
123
  this[dir === 'x' ? '_iy' : '_ix'] += maxd2;
141
124
  this[key] -= totd1;
142
- return ret;
143
125
  }
144
126
  constructor(r){
145
127
  r = r || {
@@ -234,7 +216,7 @@ class StatArray {
234
216
  const isOlderPart = (act, req)=>req > act || act.length > req.length && act.startsWith(req);
235
217
  const getGroupKey = (lvl)=>String(lvl);
236
218
  const hasGroupValue = (value)=>value !== undefined && value !== null && value !== '';
237
- function scanTreeObject(keys, treeLeafKey, obj, tree = [], lvl = 0, result = []) {
219
+ function scanTreeObject(keys, leafKey, obj, tree = [], lvl = 0, result = []) {
238
220
  const objIndex = lvl - 1;
239
221
  if (keys[0] in obj && lvl > 0) {
240
222
  const record = tree.reduce((reduced, item, i)=>{
@@ -243,7 +225,7 @@ function scanTreeObject(keys, treeLeafKey, obj, tree = [], lvl = 0, result = [])
243
225
  }
244
226
  return reduced;
245
227
  }, {});
246
- record[treeLeafKey] = tree[objIndex];
228
+ record[leafKey] = tree[objIndex];
247
229
  keys.forEach((k)=>{
248
230
  record[k] = obj[k];
249
231
  });
@@ -253,15 +235,18 @@ function scanTreeObject(keys, treeLeafKey, obj, tree = [], lvl = 0, result = [])
253
235
  const child = obj[childKey];
254
236
  if (isObject(child)) {
255
237
  tree.push(childKey);
256
- scanTreeObject(keys, treeLeafKey, child, tree, lvl + 1, result);
238
+ scanTreeObject(keys, leafKey, child, tree, lvl + 1, result);
257
239
  }
258
240
  }
259
241
  }
260
242
  tree.splice(objIndex, 1);
261
243
  return result;
262
244
  }
263
- function normalizeTreeToArray(keys, treeLeafKey, obj) {
264
- const data = scanTreeObject(keys, treeLeafKey, obj);
245
+ function flattenTree(tree, keys, leafKey) {
246
+ return normalizeTreeToArray(keys, leafKey, tree);
247
+ }
248
+ function normalizeTreeToArray(keys, leafKey, obj) {
249
+ const data = scanTreeObject(keys, leafKey, obj);
265
250
  if (!data.length) {
266
251
  return data;
267
252
  }
@@ -279,21 +264,6 @@ function normalizeTreeToArray(keys, treeLeafKey, obj) {
279
264
  });
280
265
  return data;
281
266
  }
282
- function flatten(input) {
283
- const stack = [
284
- ...input
285
- ];
286
- const res = [];
287
- while(stack.length){
288
- const next = stack.pop();
289
- if (Array.isArray(next)) {
290
- stack.push(...next);
291
- } else {
292
- res.push(next);
293
- }
294
- }
295
- return res.reverse();
296
- }
297
267
  function getPath(groups, value, defaultValue) {
298
268
  const path = [];
299
269
  for (const grp of groups){
@@ -305,7 +275,7 @@ function getPath(groups, value, defaultValue) {
305
275
  }
306
276
  return path.length ? path.join('.') : defaultValue;
307
277
  }
308
- function resolveGroup(value, treeLeafKey, allGroups, groupIndex) {
278
+ function resolveGroup(value, leafKey, allGroups, groupIndex) {
309
279
  for(let idx = groupIndex; idx < allGroups.length; idx++){
310
280
  const groupKey = getGroupKey(allGroups[idx]);
311
281
  if (hasGroupValue(value[groupKey])) {
@@ -316,11 +286,11 @@ function resolveGroup(value, treeLeafKey, allGroups, groupIndex) {
316
286
  };
317
287
  }
318
288
  }
319
- if (hasGroupValue(value[treeLeafKey])) {
289
+ if (hasGroupValue(value[leafKey])) {
320
290
  return {
321
- group: treeLeafKey,
291
+ group: leafKey,
322
292
  groupIndex,
323
- value: value[treeLeafKey]
293
+ value: value[leafKey]
324
294
  };
325
295
  }
326
296
  return undefined;
@@ -338,7 +308,7 @@ function ensureGroup(tmp, data, groupValue, addKeys) {
338
308
  });
339
309
  data[groupValue] = [];
340
310
  }
341
- function group(values, grp, keys, treeLeafKey, mainGrp, mainValue, groups = [], allGroups = groups, groupIndex = groups.length - 1) {
311
+ function group(values, grp, keys, leafKey, mainGrp, mainValue, groups = [], allGroups = groups, groupIndex = groups.length - 1) {
342
312
  const key = keys[0];
343
313
  const addKeys = keys.slice(1);
344
314
  const tmp = Object.create(null);
@@ -352,7 +322,7 @@ function group(values, grp, keys, treeLeafKey, mainGrp, mainValue, groups = [],
352
322
  let n;
353
323
  for(i = 0, n = values.length; i < n; ++i){
354
324
  const v = values[i];
355
- const itemGroup = resolveGroup(v, treeLeafKey, resolvedAllGroups, resolvedGroupIndex);
325
+ const itemGroup = resolveGroup(v, leafKey, resolvedAllGroups, resolvedGroupIndex);
356
326
  if (!itemGroup) {
357
327
  return [];
358
328
  }
@@ -407,10 +377,8 @@ function index(values, key) {
407
377
  return key;
408
378
  }
409
379
  function sort(values, key) {
410
- if (key) {
380
+ {
411
381
  values.sort((a, b)=>+b[key] - +a[key]);
412
- } else {
413
- values.sort((a, b)=>+b - +a);
414
382
  }
415
383
  }
416
384
  function sum(values, key) {
@@ -418,7 +386,7 @@ function sum(values, key) {
418
386
  let i;
419
387
  let n;
420
388
  for(s = 0, i = 0, n = values.length; i < n; ++i){
421
- s += key ? +values[i][key] : +values[i];
389
+ s += +values[i][key] ;
422
390
  }
423
391
  return s;
424
392
  }
@@ -441,6 +409,7 @@ function requireVersion(pkg, min, ver, strict = true) {
441
409
  return true;
442
410
  }
443
411
 
412
+ const WEIGHT_KEY = '_weight';
444
413
  function compareAspectRatio(oldStat, newStat, args) {
445
414
  if (oldStat.sum === 0) {
446
415
  return true;
@@ -453,139 +422,177 @@ function compareAspectRatio(oldStat, newStat, args) {
453
422
  const nr = Math.max(l2 * newStat.nmax / ns2, ns2 / (l2 * newStat.nmin));
454
423
  return nr <= or;
455
424
  }
456
- function squarify(values, rectangle, keys = [], grp, lvl, gsum) {
457
- values = values || [];
458
- const rows = [];
459
- const rect = new Rect(rectangle);
460
- const row = new StatArray('value', rect.area / sum(values, keys[0]));
461
- let length = rect.side;
462
- const n = values.length;
463
- let i;
464
- let o;
465
- if (!n) {
466
- return rows;
467
- }
468
- const tmp = values.slice();
469
- const key = index(tmp, keys[0]);
470
- if (!rectangle?.unsorted) {
471
- sort(tmp, key);
472
- }
473
- const val = (idx)=>key ? +tmp[idx][key] : +tmp[idx];
474
- const gval = (idx)=>grp && tmp[idx][grp];
475
- for(i = 0; i < n; ++i){
476
- o = {
477
- _data: values[tmp[i]._idx],
478
- group: undefined,
479
- groupSum: gsum,
480
- level: undefined,
481
- value: val(i)
425
+ function toNodes(values, keys, grp, lvl) {
426
+ const items = values ? values.slice() : [];
427
+ const key = index(items, keys[0]);
428
+ return items.map((item)=>{
429
+ const node = {
430
+ _data: values[item._idx],
431
+ v: key ? +item[key] : +item,
432
+ vs: undefined
482
433
  };
483
434
  if (grp) {
484
- o.level = tmp[i].groupIndex ?? lvl;
485
- o.group = gval(i);
486
- const tmpRef = tmp[i];
487
- o.values = keys.reduce((obj, k)=>{
488
- obj[k] = +tmpRef[k];
435
+ node.g = item[grp];
436
+ node.gs = undefined;
437
+ node.l = item.groupIndex ?? lvl;
438
+ node.vs = keys.reduce((obj, k)=>{
439
+ obj[k] = +item[k];
489
440
  return obj;
490
441
  }, {});
491
442
  }
492
- o = row.pushIf(o, compareAspectRatio, length);
443
+ return node;
444
+ });
445
+ }
446
+ function sortNodes(nodes, weighted = false) {
447
+ sort(nodes, weighted ? WEIGHT_KEY : 'v');
448
+ }
449
+ function packInto(nodes, rectangle, weighted = false) {
450
+ const n = nodes.length;
451
+ if (!n) {
452
+ return;
453
+ }
454
+ const key = weighted ? WEIGHT_KEY : 'v';
455
+ const rect = new Rect(rectangle);
456
+ const row = new StatArray(key, rect.area / sum(nodes, key));
457
+ let length = rect.side;
458
+ let o;
459
+ for(let i = 0; i < n; ++i){
460
+ o = row.pushIf(nodes[i], compareAspectRatio, length);
493
461
  if (o) {
494
- rows.push(rect.map(row));
462
+ rect.map(row);
495
463
  length = rect.side;
496
464
  row.reset();
497
465
  row.push(o);
498
466
  }
499
467
  }
500
468
  if (row.length) {
501
- rows.push(rect.map(row));
469
+ rect.map(row);
502
470
  }
503
- return flatten(rows);
504
471
  }
505
472
 
473
+ const WIDTH_CACHE_LIMIT = 4096;
506
474
  const widthCache = new Map();
507
- function shouldDrawCaption(displayMode, rect, options) {
508
- if (!options || options.display === false) {
509
- return false;
510
- }
511
- if (displayMode === 'headerBoxes') {
512
- return true;
475
+ const fontFor = (fonts, index)=>fonts[Math.min(index, fonts.length - 1)];
476
+ function measureLabelSize(ctx, lines, fonts) {
477
+ const fontsKey = fonts.reduce((prev, item)=>{
478
+ prev += item.string;
479
+ return prev;
480
+ }, '');
481
+ const mapKey = lines.join() + fontsKey + (ctx._measureText ? '-spriting' : '');
482
+ let size = widthCache.get(mapKey);
483
+ if (!size) {
484
+ ctx.save();
485
+ const count = lines.length;
486
+ let width = 0;
487
+ let height = 0;
488
+ for(let i = 0; i < count; i++){
489
+ const font = fonts[Math.min(i, fonts.length - 1)];
490
+ ctx.font = font.string;
491
+ const text = lines[i];
492
+ width = Math.max(width, ctx.measureText(text).width);
493
+ height += font.lineHeight;
494
+ }
495
+ ctx.restore();
496
+ size = {
497
+ height,
498
+ width
499
+ };
500
+ if (widthCache.size >= WIDTH_CACHE_LIMIT) {
501
+ widthCache.clear();
502
+ }
503
+ widthCache.set(mapKey, size);
513
504
  }
514
- const { w, h } = rect;
515
- const font = toFont(options.font || {});
516
- const min = font.lineHeight;
517
- const padding = Math.max(Math.min(valueOrDefault(options.padding, 3) * 2, Math.min(w, h)), 0);
518
- return w - padding > min && h - padding > min;
505
+ return size;
519
506
  }
520
- function getCaptionHeight(displayMode, rect, font, padding) {
521
- if (displayMode !== 'headerBoxes') {
522
- return font.lineHeight + padding * 2;
523
- }
524
- const captionHeight = font.lineHeight + padding * 2;
525
- return rect.h < 2 * captionHeight ? rect.h / 3 : captionHeight;
507
+ function measureLines(ctx, lines, styles, fonts) {
508
+ let width = 0;
509
+ let height = 0;
510
+ lines.forEach((line, i)=>{
511
+ const font = fontFor(fonts, styles[i]);
512
+ width = Math.max(width, measureLabelSize(ctx, [
513
+ line
514
+ ], [
515
+ font
516
+ ]).width);
517
+ height += font.lineHeight;
518
+ });
519
+ return {
520
+ height,
521
+ width
522
+ };
526
523
  }
527
- function drawText(ctx, rect, options, item, element) {
528
- const { captions, labels, displayMode } = options;
529
- ctx.save();
524
+ function toFonts(fonts, fitRatio) {
525
+ return fonts.map((f)=>{
526
+ const { lineHeight: _lineHeight, ...font } = f;
527
+ return toFont({
528
+ ...font,
529
+ size: Math.floor(f.size * fitRatio)
530
+ });
531
+ });
532
+ }
533
+
534
+ function clipToPadding(ctx, rect, padding, clipY) {
535
+ const x = Math.max(0, padding);
536
+ const y = Math.max(0, clipY);
530
537
  ctx.beginPath();
531
- ctx.rect(rect.x, rect.y, rect.w, rect.h);
538
+ ctx.rect(rect.x + x, rect.y + y, Math.max(0, rect.w - 2 * x), Math.max(0, rect.h - 2 * y));
532
539
  ctx.clip();
533
- const isLeaf = item && (!defined(item.l) || item.isLeaf);
534
- if (isLeaf && labels.display) {
535
- drawLabel(ctx, rect, options, item, element);
536
- } else if (!isLeaf && shouldDrawCaption(displayMode, rect, captions)) {
537
- drawCaption(ctx, rect, options, item, element);
538
- }
539
- ctx.restore();
540
540
  }
541
- function callbackContext(element, item) {
542
- const context = element.$context || {
543
- active: !!element.active,
544
- raw: item,
545
- type: 'data'
546
- };
547
- context.active = !!element.active;
548
- context.raw = item;
549
- return context;
541
+ function drawTextBlock(ctx, rect, block) {
542
+ const { align, colors, fonts, lines, padding, styles, textAlign, top, width } = block;
543
+ const lineAlign = textAlign || align;
544
+ const x = calculateLineX(rect, align, lineAlign, padding, width);
545
+ ctx.textAlign = lineAlign;
546
+ ctx.textBaseline = 'middle';
547
+ let offset = 0;
548
+ lines.forEach((line, i)=>{
549
+ const style = styles[i];
550
+ const font = fontFor(fonts, style);
551
+ ctx.font = font.string;
552
+ ctx.fillStyle = colors[Math.min(style, colors.length - 1)];
553
+ ctx.fillText(line, x, top + offset + font.lineHeight / 2);
554
+ offset += font.lineHeight;
555
+ });
550
556
  }
551
- function resolveOption(option, context) {
552
- return typeof option === 'function' ? option(context) : option;
557
+ function calculateBlockTop(rect, options, labelSize) {
558
+ const { position, padding } = options;
559
+ if (position === 'top') {
560
+ return rect.y + padding;
561
+ }
562
+ if (position === 'bottom') {
563
+ return rect.y + rect.h - padding - labelSize.height;
564
+ }
565
+ return rect.y + (rect.h - labelSize.height) / 2 + padding;
553
566
  }
554
- function resolveCaptionText(captions, element, item) {
555
- return resolveOption(captions.formatter, callbackContext(element, item)) || item.g || '';
567
+ function calculateBlockLeft(rect, align, padding, width) {
568
+ if (align === 'left') {
569
+ return rect.x + padding;
570
+ }
571
+ if (align === 'right') {
572
+ return rect.x + rect.w - padding - width;
573
+ }
574
+ return rect.x + (rect.w - width) / 2;
556
575
  }
557
- function drawCaption(ctx, rect, options, item, element) {
558
- const { captions, spacing, rtl, displayMode } = options;
559
- const { color, hoverColor, font, hoverFont, padding, align } = captions;
560
- const oColor = (rect.active ? hoverColor : color) || color;
561
- const oAlign = align || (rtl ? 'right' : 'left');
562
- const optFont = (rect.active ? hoverFont : font) || font;
563
- const oFont = toFont(optFont);
564
- const fonts = [
565
- oFont
566
- ];
567
- if (oFont.lineHeight > rect.h) {
568
- return;
576
+ function calculateLineX(rect, align, lineAlign, padding, width) {
577
+ if (align === lineAlign) {
578
+ if (align === 'left') {
579
+ return rect.x + padding;
580
+ }
581
+ if (align === 'right') {
582
+ return rect.x + rect.w - padding;
583
+ }
584
+ return rect.x + rect.w / 2;
569
585
  }
570
- let text = resolveCaptionText(captions, element, item);
571
- if (!text) {
572
- return;
586
+ const left = calculateBlockLeft(rect, align, padding, width);
587
+ if (lineAlign === 'left') {
588
+ return left;
573
589
  }
574
- const captionSize = measureLabelSize(ctx, [
575
- text
576
- ], fonts);
577
- if (captionSize.width + 2 * padding > rect.w) {
578
- text = sliceTextToFitWidth(ctx, text, rect.w - 2 * padding, fonts);
579
- }
580
- const lh = oFont.lineHeight / 2;
581
- const x = calculateX(rect, oAlign, padding);
582
- ctx.fillStyle = oColor;
583
- ctx.font = oFont.string;
584
- ctx.textAlign = oAlign;
585
- ctx.textBaseline = 'middle';
586
- const y = displayMode === 'headerBoxes' ? rect.y + rect.h / 2 : rect.y + padding + spacing + lh;
587
- ctx.fillText(text, x, y);
590
+ if (lineAlign === 'right') {
591
+ return left + width;
592
+ }
593
+ return left + width / 2;
588
594
  }
595
+
589
596
  function sliceTextToFitWidth(ctx, text, width, fonts) {
590
597
  const ellipsis = '...';
591
598
  const ellipsisWidth = measureLabelSize(ctx, [
@@ -612,44 +619,40 @@ function sliceTextToFitWidth(ctx, text, width, fonts) {
612
619
  const slicedText = text.slice(0, Math.max(0, lowerBoundLen - 1));
613
620
  return slicedText ? slicedText + ellipsis : '';
614
621
  }
615
- function measureLabelSize(ctx, lines, fonts) {
616
- const fontsKey = fonts.reduce((prev, item)=>{
617
- prev += item.string;
618
- return prev;
619
- }, '');
620
- const mapKey = lines.join() + fontsKey + (ctx._measureText ? '-spriting' : '');
621
- let size = widthCache.get(mapKey);
622
- if (!size) {
623
- ctx.save();
624
- const count = lines.length;
625
- let width = 0;
626
- let height = 0;
627
- for(let i = 0; i < count; i++){
628
- const font = fonts[Math.min(i, fonts.length - 1)];
629
- ctx.font = font.string;
630
- const text = lines[i];
631
- width = Math.max(width, ctx.measureText(text).width);
632
- height += font.lineHeight;
622
+ function applyEllipsis(ctx, lines, styles, fonts, maxWidth, maxHeight) {
623
+ const keptLines = [];
624
+ const keptStyles = [];
625
+ let used = 0;
626
+ for(let i = 0; i < lines.length; i++){
627
+ const font = fontFor(fonts, styles[i]);
628
+ if (keptLines.length && used + font.lineHeight > maxHeight) {
629
+ break;
630
+ }
631
+ used += font.lineHeight;
632
+ keptLines.push(lines[i]);
633
+ keptStyles.push(styles[i]);
634
+ }
635
+ const dropped = keptLines.length < lines.length;
636
+ const last = keptLines.length - 1;
637
+ for(let i = 0; i < keptLines.length; i++){
638
+ const font = fontFor(fonts, keptStyles[i]);
639
+ const tooWide = measureLabelSize(ctx, [
640
+ keptLines[i]
641
+ ], [
642
+ font
643
+ ]).width > maxWidth;
644
+ if (tooWide || dropped && i === last) {
645
+ keptLines[i] = sliceTextToFitWidth(ctx, keptLines[i], maxWidth, [
646
+ font
647
+ ]);
633
648
  }
634
- ctx.restore();
635
- size = {
636
- height,
637
- width
638
- };
639
- widthCache.set(mapKey, size);
640
649
  }
641
- return size;
642
- }
643
- function toFonts(fonts, fitRatio) {
644
- return fonts.map((f)=>{
645
- const { lineHeight: _lineHeight, ...font } = f;
646
- return toFont({
647
- ...font,
648
- size: Math.floor(f.size * fitRatio)
649
- });
650
- });
650
+ return {
651
+ lines: keptLines,
652
+ styles: keptStyles
653
+ };
651
654
  }
652
- function labelToDraw(_ctx, rect, options, labelSize) {
655
+ function labelToDraw(rect, options, labelSize) {
653
656
  const { overflow, padding } = options;
654
657
  const { width, height } = labelSize;
655
658
  if (overflow === 'hidden') {
@@ -662,175 +665,458 @@ function labelToDraw(_ctx, rect, options, labelSize) {
662
665
  }
663
666
  return true;
664
667
  }
665
- function getFontFromOptions(rect, labels) {
666
- const { font, hoverFont } = labels;
668
+
669
+ function wrapToWidth(ctx, text, font, width) {
670
+ if (width <= 0) {
671
+ return [
672
+ text
673
+ ];
674
+ }
675
+ const fits = (value)=>measureLabelSize(ctx, [
676
+ value
677
+ ], [
678
+ font
679
+ ]).width <= width;
680
+ const lines = [];
681
+ let line = '';
682
+ const pushWord = (word)=>{
683
+ if (fits(word)) {
684
+ line = word;
685
+ return;
686
+ }
687
+ let chunk = '';
688
+ for (const char of word){
689
+ if (chunk && !fits(chunk + char)) {
690
+ lines.push(chunk);
691
+ chunk = '';
692
+ }
693
+ chunk += char;
694
+ }
695
+ line = chunk;
696
+ };
697
+ for (const word of text.split(' ')){
698
+ const candidate = line ? `${line} ${word}` : word;
699
+ if (fits(candidate)) {
700
+ line = candidate;
701
+ continue;
702
+ }
703
+ if (line) {
704
+ lines.push(line);
705
+ line = '';
706
+ }
707
+ pushWord(word);
708
+ }
709
+ if (line) {
710
+ lines.push(line);
711
+ }
712
+ return lines.length ? lines : [
713
+ ''
714
+ ];
715
+ }
716
+ function toLines(ctx, content, fonts, width, wrap) {
717
+ const paragraphs = (isArray(content) ? content : [
718
+ content
719
+ ]).map((entry)=>`${entry}`);
720
+ const lines = [];
721
+ const styles = [];
722
+ paragraphs.forEach((paragraph, index)=>{
723
+ const font = fontFor(fonts, index);
724
+ for (const piece of paragraph.split('\n')){
725
+ for (const line of wrap ? wrapToWidth(ctx, piece, font, width) : [
726
+ piece
727
+ ]){
728
+ lines.push(line);
729
+ styles.push(index);
730
+ }
731
+ }
732
+ });
733
+ return {
734
+ lines,
735
+ styles
736
+ };
737
+ }
738
+
739
+ function shouldDrawCaption(displayMode, rect, options) {
740
+ if (!options || options.display === false) {
741
+ return false;
742
+ }
743
+ if (displayMode === 'headerBoxes') {
744
+ return true;
745
+ }
746
+ const { w, h } = rect;
747
+ const font = toFont(options.font || {});
748
+ const min = font.lineHeight;
749
+ const padding = Math.max(Math.min(valueOrDefault(options.padding, 3) * 2, Math.min(w, h)), 0);
750
+ return w - padding > min && h - padding > min;
751
+ }
752
+ function getCaptionHeight(displayMode, rect, font, padding) {
753
+ if (displayMode !== 'headerBoxes') {
754
+ return font.lineHeight + padding * 2;
755
+ }
756
+ const captionHeight = font.lineHeight + padding * 2;
757
+ return rect.h < 2 * captionHeight ? rect.h / 3 : captionHeight;
758
+ }
759
+ function drawText(ctx, rect, options, item, element, layout) {
760
+ const { captions, labels } = options;
761
+ const { displayMode } = layout;
762
+ const isLeaf = item && (!defined(item.l) || item.isLeaf);
763
+ let block;
764
+ if (isLeaf) {
765
+ if (labels.display) {
766
+ block = labelBlock(ctx, rect, options, item, element);
767
+ }
768
+ } else if (shouldDrawCaption(displayMode, rect, captions)) {
769
+ block = captionBlock(ctx, rect, options, item, element, layout);
770
+ }
771
+ if (!block) {
772
+ return;
773
+ }
774
+ ctx.save();
775
+ clipToPadding(ctx, rect, block.padding, block.clipY);
776
+ drawTextBlock(ctx, rect, block);
777
+ ctx.restore();
778
+ }
779
+ function callbackContext(element, item) {
780
+ const context = element.$context || {
781
+ active: !!element.active,
782
+ raw: item,
783
+ type: 'data'
784
+ };
785
+ context.active = !!element.active;
786
+ context.raw = item;
787
+ return context;
788
+ }
789
+ function resolveOption(option, context) {
790
+ return typeof option === 'function' ? option(context) : option;
791
+ }
792
+ function resolveCaptionText(captions, element, item) {
793
+ return resolveOption(captions.formatter, callbackContext(element, item)) || item.g || '';
794
+ }
795
+ function captionText(ctx, rect, captions, element, item, fonts) {
796
+ const text = resolveCaptionText(captions, element, item);
797
+ if (!text) {
798
+ return undefined;
799
+ }
800
+ const padding = captions.padding;
801
+ if (measureLabelSize(ctx, [
802
+ text
803
+ ], fonts).width + 2 * padding <= rect.w) {
804
+ return text;
805
+ }
806
+ const overflow = captions.overflow || 'ellipsis';
807
+ if (overflow === 'hidden') {
808
+ return undefined;
809
+ }
810
+ if (overflow === 'cut') {
811
+ return text;
812
+ }
813
+ return sliceTextToFitWidth(ctx, text, rect.w - 2 * padding, fonts);
814
+ }
815
+ function captionBlock(ctx, rect, options, item, element, layout) {
816
+ const { displayMode, rtl, spacing } = layout;
817
+ const { captions } = options;
818
+ const { color, hoverColor, font, hoverFont, padding, align } = captions;
667
819
  const optFont = (rect.active ? hoverFont : font) || font;
668
- return Array.isArray(optFont) ? optFont.map((f)=>toFont(f)) : [
669
- toFont(optFont)
820
+ const oFont = toFont(optFont);
821
+ if (oFont.lineHeight > rect.h) {
822
+ return;
823
+ }
824
+ const text = captionText(ctx, rect, captions, element, item, [
825
+ oFont
826
+ ]);
827
+ if (text === undefined) {
828
+ return;
829
+ }
830
+ const fonts = [
831
+ oFont
670
832
  ];
833
+ const top = displayMode === 'headerBoxes' ? rect.y + (rect.h - oFont.lineHeight) / 2 : rect.y + padding + spacing;
834
+ return {
835
+ align: align || (rtl ? 'right' : 'left'),
836
+ clipY: displayMode === 'headerBoxes' ? 0 : padding,
837
+ colors: [
838
+ (rect.active ? hoverColor : color) || color
839
+ ],
840
+ fonts,
841
+ lines: [
842
+ text
843
+ ],
844
+ padding,
845
+ styles: [
846
+ 0
847
+ ],
848
+ textAlign: captions.textAlign,
849
+ top,
850
+ width: measureLabelSize(ctx, [
851
+ text
852
+ ], fonts).width
853
+ };
671
854
  }
672
- function drawLabel(ctx, rect, options, item, element) {
855
+ function labelBlock(ctx, rect, options, item, element) {
673
856
  const labels = options.labels;
674
857
  const content = resolveOption(labels.formatter, callbackContext(element, item));
675
858
  if (!content) {
676
859
  return;
677
860
  }
678
- const contents = isArray(content) ? content : [
679
- content
680
- ];
861
+ const { align, color, hoverColor, overflow, padding, wrap } = labels;
862
+ const maxWidth = rect.w - padding * 2;
863
+ const maxHeight = rect.h - padding * 2;
681
864
  let fonts = getFontFromOptions(rect, labels);
682
- let labelSize = measureLabelSize(ctx, contents, fonts);
683
- const lblToDraw = labelToDraw(ctx, rect, labels, labelSize);
865
+ let { lines, styles } = toLines(ctx, content, fonts, maxWidth, !!wrap);
866
+ let labelSize = measureLines(ctx, lines, styles, fonts);
867
+ const lblToDraw = labelToDraw(rect, labels, labelSize);
684
868
  if (!lblToDraw) {
685
869
  return;
686
870
  }
687
871
  if (isNumber(lblToDraw)) {
688
- labelSize = {
689
- height: labelSize.height * lblToDraw,
690
- width: labelSize.width * lblToDraw
691
- };
692
872
  fonts = toFonts(fonts, lblToDraw);
873
+ if (wrap) {
874
+ const rewrapped = toLines(ctx, content, fonts, maxWidth, true);
875
+ lines = rewrapped.lines;
876
+ styles = rewrapped.styles;
877
+ labelSize = measureLines(ctx, lines, styles, fonts);
878
+ } else {
879
+ labelSize = {
880
+ height: labelSize.height * lblToDraw,
881
+ width: labelSize.width * lblToDraw
882
+ };
883
+ }
884
+ }
885
+ if (overflow === 'ellipsis') {
886
+ const trimmed = applyEllipsis(ctx, lines, styles, fonts, maxWidth, maxHeight);
887
+ lines = trimmed.lines;
888
+ styles = trimmed.styles;
889
+ labelSize = measureLines(ctx, lines, styles, fonts);
693
890
  }
694
- const { color, hoverColor, align } = labels;
695
891
  const optColor = (rect.active ? hoverColor : color) || color;
696
- const colors = isArray(optColor) ? optColor : [
697
- optColor
892
+ return {
893
+ align,
894
+ clipY: padding,
895
+ colors: isArray(optColor) ? optColor : [
896
+ optColor
897
+ ],
898
+ fonts,
899
+ lines,
900
+ padding,
901
+ styles,
902
+ textAlign: labels.textAlign,
903
+ top: calculateBlockTop(rect, labels, labelSize),
904
+ width: labelSize.width
905
+ };
906
+ }
907
+ function getFontFromOptions(rect, labels) {
908
+ const { font, hoverFont } = labels;
909
+ const optFont = (rect.active ? hoverFont : font) || font;
910
+ return Array.isArray(optFont) ? optFont.map((f)=>toFont(f)) : [
911
+ toFont(optFont)
698
912
  ];
699
- const xyPoint = calculateXYLabel(rect, labels, labelSize);
700
- ctx.textAlign = align;
701
- ctx.textBaseline = 'middle';
702
- let lhs = 0;
703
- contents.forEach((l, i)=>{
704
- const c = colors[Math.min(i, colors.length - 1)];
705
- const f = fonts[Math.min(i, fonts.length - 1)];
706
- const lh = f.lineHeight;
707
- ctx.font = f.string;
708
- ctx.fillStyle = c;
709
- ctx.fillText(l, xyPoint.x, xyPoint.y + lh / 2 + lhs);
710
- lhs += lh;
711
- });
712
913
  }
713
- function drawDivider(ctx, rect, options, item) {
714
- const dividers = options.dividers;
715
- const children = item._data?.children;
716
- if (!dividers.display || !Array.isArray(children) || !children.length) {
717
- return;
914
+
915
+ function buildHierarchy(values, gidx, keys, layout, weighted, parentGroupValue) {
916
+ const { groups, leafKey, unsorted } = layout;
917
+ const glen = groups.length;
918
+ const g = getGroupKey(groups[gidx]);
919
+ const gdata = group(values, g, keys, leafKey, undefined, parentGroupValue, groups.filter((_item, index)=>index <= gidx), groups, gidx);
920
+ const nodes = toNodes(gdata, keys, g, gidx);
921
+ for (const node of nodes){
922
+ const record = node._data;
923
+ const nextGroupIndex = record.groupIndex + 1;
924
+ const children = gidx < glen - 1 && nextGroupIndex < glen ? buildHierarchy(record.children, nextGroupIndex, keys, layout, weighted, node.g) : [];
925
+ Object.defineProperty(node, '_children', {
926
+ configurable: true,
927
+ value: children,
928
+ writable: true
929
+ });
930
+ node.isLeaf = !children.length;
718
931
  }
719
- const { x, y, w, h } = rect;
720
- const { lineColor, lineCapStyle, lineDash, lineDashOffset, lineWidth } = dividers;
721
- ctx.save();
722
- ctx.strokeStyle = lineColor;
723
- ctx.lineCap = lineCapStyle;
724
- ctx.setLineDash(lineDash);
725
- ctx.lineDashOffset = lineDashOffset;
726
- ctx.lineWidth = lineWidth;
727
- ctx.beginPath();
728
- if (w > h) {
729
- const w2 = w / 2;
730
- ctx.moveTo(x + w2, y);
731
- ctx.lineTo(x + w2, y + h);
732
- } else {
733
- const h2 = h / 2;
734
- ctx.moveTo(x, y + h2);
735
- ctx.lineTo(x + w, y + h2);
932
+ if (weighted) {
933
+ applyValueScale(nodes, scaleFor(layout));
736
934
  }
737
- ctx.stroke();
738
- ctx.restore();
935
+ const withOthers = layout.others ? applyOthers(nodes, layout.others, weighted) : nodes;
936
+ if (!unsorted) {
937
+ sortNodes(withOthers, weighted);
938
+ }
939
+ return withOthers;
739
940
  }
740
- function calculateXYLabel(rect, options, labelSize) {
741
- const { align, position, padding } = options;
742
- const x = calculateX(rect, align, padding);
743
- let y;
744
- if (position === 'top') {
745
- y = rect.y + padding;
746
- } else if (position === 'bottom') {
747
- y = rect.y + rect.h - padding - labelSize.height;
748
- } else {
749
- y = rect.y + (rect.h - labelSize.height) / 2 + padding;
941
+ function applyValueScale(nodes, scale) {
942
+ for (const node of nodes){
943
+ const children = node._children;
944
+ let weight;
945
+ if (children?.length) {
946
+ applyValueScale(children, scale);
947
+ weight = children.reduce((total, child)=>total + child[WEIGHT_KEY], 0);
948
+ } else {
949
+ const scaled = scale(node.v, node._data);
950
+ weight = Number.isFinite(scaled) && scaled > 0 ? scaled : 0;
951
+ }
952
+ Object.defineProperty(node, WEIGHT_KEY, {
953
+ configurable: true,
954
+ value: weight,
955
+ writable: true
956
+ });
750
957
  }
751
- return {
752
- x,
753
- y
958
+ }
959
+ function applyOthers(nodes, others, weighted) {
960
+ const { label = 'Other', minCount = 2, threshold } = others;
961
+ if (!(threshold > 0) || nodes.some((node)=>node._children?.length)) {
962
+ return nodes;
963
+ }
964
+ const weightOf = (node)=>weighted ? node[WEIGHT_KEY] : node.v;
965
+ const total = nodes.reduce((sum, node)=>sum + weightOf(node), 0);
966
+ if (!(total > 0)) {
967
+ return nodes;
968
+ }
969
+ const small = nodes.filter((node)=>weightOf(node) / total < threshold);
970
+ if (small.length < Math.max(2, minCount)) {
971
+ return nodes;
972
+ }
973
+ const kept = nodes.filter((node)=>!small.includes(node));
974
+ const bucket = {
975
+ _data: {
976
+ label,
977
+ others: small.map((node)=>node._data)
978
+ },
979
+ h: 0,
980
+ isLeaf: true,
981
+ isOthers: true,
982
+ s: 0,
983
+ v: small.reduce((sum, node)=>sum + node.v, 0),
984
+ vs: sumValues(small),
985
+ w: 0,
986
+ x: 0,
987
+ y: 0
754
988
  };
989
+ const grouped = nodes.find((node)=>node.g !== undefined);
990
+ if (grouped) {
991
+ bucket.g = label;
992
+ bucket.l = grouped.l;
993
+ }
994
+ if (weighted) {
995
+ Object.defineProperty(bucket, WEIGHT_KEY, {
996
+ configurable: true,
997
+ value: small.reduce((sum, node)=>sum + weightOf(node), 0),
998
+ writable: true
999
+ });
1000
+ }
1001
+ kept.push(bucket);
1002
+ return kept;
755
1003
  }
756
- function calculateX(rect, align, padding) {
757
- if (align === 'left') {
758
- return rect.x + padding;
759
- } else if (align === 'right') {
760
- return rect.x + rect.w - padding;
1004
+ function sumValues(nodes) {
1005
+ const totals = {};
1006
+ for (const node of nodes){
1007
+ for (const [key, value] of Object.entries(node.vs || {})){
1008
+ totals[key] = (totals[key] || 0) + value;
1009
+ }
761
1010
  }
762
- return rect.x + rect.w / 2;
1011
+ return Object.keys(totals).length ? totals : undefined;
763
1012
  }
764
-
765
- function buildData(tree, dataset, keys, mainRect) {
766
- const treeLeafKey = dataset.treeLeafKey || '_leaf';
767
- if (isObject(tree)) {
768
- tree = normalizeTreeToArray(keys, treeLeafKey, tree);
1013
+ const VALUE_SCALES = {
1014
+ log: (value)=>Math.log1p(Math.max(value, 0)),
1015
+ sqrt: (value)=>Math.sqrt(Math.max(value, 0))
1016
+ };
1017
+ function flattenNodes(nodes) {
1018
+ const flat = nodes.slice();
1019
+ for (const node of nodes){
1020
+ if (node._children?.length) {
1021
+ flat.push(...flattenNodes(node._children));
1022
+ }
1023
+ }
1024
+ return flat;
1025
+ }
1026
+ function layoutLevel(nodes, rect, layout, weighted, parentSum) {
1027
+ if (parentSum !== undefined) {
1028
+ for (const node of nodes){
1029
+ node.gs = parentSum;
1030
+ }
1031
+ }
1032
+ packInto(nodes, rect, weighted);
1033
+ for (const node of nodes){
1034
+ if (node._children?.length) {
1035
+ layoutLevel(node._children, getSubRect(node, rect, layout), layout, weighted, node.s);
1036
+ }
1037
+ }
1038
+ }
1039
+ function layoutNodes(nodes, rect, layout) {
1040
+ layoutLevel(nodes, rect, layout, isWeighted(layout));
1041
+ applyHeaderBoxes(flattenNodes(nodes), layout);
1042
+ }
1043
+ function isWeighted(layout) {
1044
+ const scale = layout.valueScale;
1045
+ return scale !== 'linear' && scale !== undefined;
1046
+ }
1047
+ function scaleFor(layout) {
1048
+ const scale = layout.valueScale;
1049
+ if (typeof scale === 'function') {
1050
+ return scale;
1051
+ }
1052
+ return VALUE_SCALES[scale] || ((value)=>value);
1053
+ }
1054
+ function getSubRect(sq, rect, layout) {
1055
+ const { borderWidth, captions, displayMode } = layout;
1056
+ const sp = displayMode === 'headerBoxes' ? 0 : layout.spacing;
1057
+ const bw = displayMode === 'headerBoxes' ? {
1058
+ b: 0,
1059
+ l: 0,
1060
+ r: 0,
1061
+ t: 0
1062
+ } : parseBorderWidth(borderWidth, sq.w / 2, sq.h / 2);
1063
+ const subRect = {
1064
+ ...rect,
1065
+ h: sq.h - 2 * sp - bw.t - bw.b,
1066
+ w: sq.w - 2 * sp - bw.l - bw.r,
1067
+ x: sq.x + sp + bw.l,
1068
+ y: sq.y + sp + bw.t
1069
+ };
1070
+ if (shouldDrawCaption(displayMode, subRect, captions)) {
1071
+ const captionHeight = getCaptionHeight(displayMode, subRect, toFont(captions.font), valueOrDefault(captions.padding, 3));
1072
+ subRect.y += captionHeight;
1073
+ subRect.h -= captionHeight;
1074
+ }
1075
+ return subRect;
1076
+ }
1077
+ function buildNodes(tree, keys, layout) {
1078
+ const { groups, leafKey, unsorted } = layout;
1079
+ const input = isObject(tree) ? normalizeTreeToArray(keys, leafKey, tree) : tree;
1080
+ const weighted = isWeighted(layout);
1081
+ let nodes;
1082
+ if (groups.length) {
1083
+ nodes = buildHierarchy(input, 0, keys, layout, weighted);
1084
+ } else {
1085
+ nodes = toNodes(input || [], keys);
1086
+ if (weighted) {
1087
+ applyValueScale(nodes, scaleFor(layout));
1088
+ }
1089
+ if (layout.others) {
1090
+ nodes = applyOthers(nodes, layout.others, weighted);
1091
+ }
1092
+ if (!unsorted) {
1093
+ sortNodes(nodes, weighted);
1094
+ }
1095
+ }
1096
+ return nodes;
1097
+ }
1098
+ function applyHeaderBoxes(nodes, layout) {
1099
+ const { captions, displayMode } = layout;
1100
+ if (displayMode !== 'headerBoxes') {
1101
+ return;
769
1102
  }
770
- const groups = dataset.groups || [];
771
- const glen = groups.length;
772
- const sp = dataset.displayMode === 'headerBoxes' ? 0 : valueOrDefault(dataset.spacing, 0);
773
- const captions = dataset.captions || {};
774
1103
  const font = toFont(captions.font);
775
1104
  const padding = valueOrDefault(captions.padding, 3);
776
- function getSubRect(sq, rect) {
777
- const bw = dataset.displayMode === 'headerBoxes' ? {
778
- b: 0,
779
- l: 0,
780
- r: 0,
781
- t: 0
782
- } : parseBorderWidth(dataset.borderWidth, sq.w / 2, sq.h / 2);
783
- const subRect = {
784
- ...rect,
785
- h: sq.h - 2 * sp - bw.t - bw.b,
786
- w: sq.w - 2 * sp - bw.l - bw.r,
787
- x: sq.x + sp + bw.l,
788
- y: sq.y + sp + bw.t
789
- };
790
- if (shouldDrawCaption(dataset.displayMode, subRect, captions)) {
791
- const captionHeight = getCaptionHeight(dataset.displayMode, subRect, font, padding);
792
- subRect.y += captionHeight;
793
- subRect.h -= captionHeight;
1105
+ for (const node of nodes){
1106
+ if (node.isLeaf) {
1107
+ continue;
794
1108
  }
795
- return subRect;
796
- }
797
- function recur(treeElements, gidx, rect, parent, gs) {
798
- const g = getGroupKey(groups[gidx]);
799
- const gdata = group(treeElements, g, keys, treeLeafKey, undefined, parent, groups.filter((_item, index)=>index <= gidx), groups, gidx);
800
- const gsq = squarify(gdata, rect, keys, g, gidx, gs);
801
- const ret = gsq.slice();
802
- if (gidx < glen - 1) {
803
- gsq.forEach((sq)=>{
804
- const subRect = getSubRect(sq, rect);
805
- const children = [];
806
- const nextGroupIndex = sq._data.groupIndex + 1;
807
- if (nextGroupIndex < glen) {
808
- children.push(...recur(sq._data.children, nextGroupIndex, subRect, sq.g, sq.s));
809
- }
810
- ret.push(...children);
811
- sq.isLeaf = !children.length;
812
- });
1109
+ if (shouldDrawCaption(displayMode, node, captions)) {
1110
+ node.h = getCaptionHeight(displayMode, node, font, padding);
1111
+ node.hidden = false;
813
1112
  } else {
814
- gsq.forEach((sq)=>{
815
- sq.isLeaf = true;
816
- });
1113
+ node.hidden = true;
817
1114
  }
818
- return ret;
819
1115
  }
820
- const result = glen ? recur(tree, 0, mainRect) : squarify(tree, mainRect, keys);
821
- return result.map((d)=>{
822
- if (dataset.displayMode !== 'headerBoxes' || d.isLeaf) {
823
- return d;
824
- }
825
- if (!shouldDrawCaption(dataset.displayMode, d, captions)) {
826
- return undefined;
827
- }
828
- const captionHeight = getCaptionHeight(dataset.displayMode, d, font, padding);
829
- return {
830
- ...d,
831
- h: captionHeight
832
- };
833
- }).filter(Boolean);
1116
+ }
1117
+
1118
+ function clampFraction(value, fallback) {
1119
+ return value === undefined ? fallback : Math.min(Math.max(value, 0), 1);
834
1120
  }
835
1121
  function registerTooltipPositioner() {
836
1122
  const tooltipPlugin = registry.plugins.get('tooltip');
@@ -866,12 +1152,9 @@ class TreemapController extends DatasetController {
866
1152
  const w = xScale.right - xScale.left;
867
1153
  const h = yScale.bottom - yScale.top;
868
1154
  const rect = {
869
- h,
1155
+ ...this._regionBounds(w, h),
870
1156
  rtl: !!this.options.rtl,
871
- unsorted: !!this.options.unsorted,
872
- w,
873
- x: 0,
874
- y: 0
1157
+ unsorted: !!this.options.unsorted
875
1158
  };
876
1159
  if (rectNotEqual(this._rect, rect)) {
877
1160
  this._rect = rect;
@@ -884,42 +1167,130 @@ class TreemapController extends DatasetController {
884
1167
  yScale.configure();
885
1168
  }
886
1169
  }
887
- update(mode) {
1170
+ _regionBounds(w, h) {
1171
+ const region = this.options.region;
1172
+ if (!region) {
1173
+ return {
1174
+ h,
1175
+ w,
1176
+ x: 0,
1177
+ y: 0
1178
+ };
1179
+ }
1180
+ const left = clampFraction(region.left, 0);
1181
+ const top = clampFraction(region.top, 0);
1182
+ const width = clampFraction(region.width, 1);
1183
+ const height = clampFraction(region.height, 1);
1184
+ if (!this._regionWarned && (left + width > 1 || top + height > 1)) {
1185
+ this._regionWarned = true;
1186
+ console.warn('chartjs-chart-treemap: a dataset region reaches outside the chart area and is clipped to it.');
1187
+ }
1188
+ return {
1189
+ h: h * Math.min(height, 1 - top),
1190
+ w: w * Math.min(width, 1 - left),
1191
+ x: w * left,
1192
+ y: h * top
1193
+ };
1194
+ }
1195
+ _layoutOptions() {
888
1196
  const dataset = this.getDataset();
889
- const { data } = this.getMeta();
890
- const groups = dataset.groups || [];
1197
+ const options = this.options;
1198
+ return {
1199
+ borderWidth: dataset.borderWidth,
1200
+ captions: dataset.captions || {},
1201
+ displayMode: options.displayMode,
1202
+ groups: options.groups || [],
1203
+ leafKey: options.leafKey,
1204
+ others: options.others || false,
1205
+ spacing: valueOrDefault(dataset.spacing, 0),
1206
+ unsorted: !!options.unsorted,
1207
+ valueScale: options.valueScale || 'linear'
1208
+ };
1209
+ }
1210
+ buildOrUpdateElements(_resetNewElements) {
1211
+ this.parse(0, 0);
1212
+ const meta = this.getMeta();
1213
+ const count = meta._parsed.length;
1214
+ const elements = meta.data;
1215
+ if (elements.length > count) {
1216
+ elements.splice(count, elements.length - count);
1217
+ }
1218
+ while(elements.length < count){
1219
+ elements.push(new this.dataElementType());
1220
+ }
1221
+ }
1222
+ parse(_start, _count) {
1223
+ const dataset = this.getDataset();
1224
+ if (dataset.tree !== undefined) {
1225
+ throw new Error('chartjs-chart-treemap v5: the "tree" option was renamed to "data". ' + 'See https://chartjs-chart-treemap.pages.dev/usage/');
1226
+ }
1227
+ const options = this.options;
891
1228
  const keys = [
892
- dataset.key || ''
893
- ].concat(dataset.sumKeys || []);
894
- dataset.tree = dataset.tree || dataset.data || [];
895
- const tree = dataset.tree;
896
- const treeVersion = dataset.treeVersion;
1229
+ options.key || ''
1230
+ ].concat(options.sumKeys || []);
1231
+ const nodes = buildNodes(dataset.data || [], keys, this._layoutOptions());
1232
+ const flat = flattenNodes(nodes);
1233
+ const fingerprint = flat.map((node)=>`${node.v}\u0000${node.g}\u0000${node.l}`).join('\u0001');
1234
+ if (this._fingerprint === fingerprint) {
1235
+ return;
1236
+ }
1237
+ this._fingerprint = fingerprint;
1238
+ this._nodes = nodes;
1239
+ this.getMeta()._parsed = flat;
1240
+ this._layoutDirty = true;
1241
+ }
1242
+ getContext(index, active, mode) {
1243
+ const base = DatasetController.prototype.getContext;
1244
+ const context = base.call(this, index, active, mode);
1245
+ const parsed = typeof index === 'number' ? this.getParsed(index) : undefined;
1246
+ if (parsed) {
1247
+ context.raw = parsed;
1248
+ context.parsed = parsed;
1249
+ }
1250
+ return context;
1251
+ }
1252
+ getLabelAndValue(index) {
1253
+ const node = this.getParsed(index);
1254
+ if (!node) {
1255
+ return {
1256
+ label: '',
1257
+ value: ''
1258
+ };
1259
+ }
1260
+ const dataset = this.getDataset();
1261
+ const label = node.g ?? node._data?.label ?? dataset.label;
1262
+ const text = label === undefined ? '' : `${label}`;
1263
+ const others = node.isOthers ? node._data?.others?.length : undefined;
1264
+ return {
1265
+ label: others ? `${text} (${others} items)` : text,
1266
+ value: `${node.v}`
1267
+ };
1268
+ }
1269
+ update(mode) {
1270
+ const { data } = this.getMeta();
897
1271
  if (mode === 'reset') {
898
1272
  this.configure();
899
1273
  }
900
- if (this._rectChanged || arrayNotEqual(this._keys || [], keys) || arrayNotEqual(this._groups || [], groups) || this._prevTree !== tree || this._prevTreeVersion !== treeVersion) {
901
- this._groups = groups.slice();
902
- this._keys = keys.slice();
903
- this._prevTree = tree;
904
- this._prevTreeVersion = treeVersion;
1274
+ if (this._layoutDirty || this._rectChanged) {
1275
+ layoutNodes(this._nodes, this._rect, this._layoutOptions());
1276
+ this._layoutDirty = false;
905
1277
  this._rectChanged = false;
906
- dataset.data = buildData(tree, dataset, this._keys, this._rect);
907
- this._dataCheck();
908
- this._resyncElements();
909
1278
  }
910
1279
  this.updateElements(data, 0, data.length, mode);
911
1280
  }
912
1281
  updateElements(rects, start, count, mode) {
913
1282
  const reset = mode === 'reset';
914
- const dataset = this.getDataset();
915
1283
  const firstOpts = this.resolveDataElementOptions(start, mode);
916
1284
  this._rect.options = firstOpts;
917
1285
  const sharedOptions = this.getSharedOptions(firstOpts);
918
1286
  const includeOptions = this.includeOptions(mode, sharedOptions || {});
919
1287
  const { xScale, yScale } = this.getMeta();
1288
+ const spacing = this.options.spacing;
920
1289
  for(let i = start; i < start + count; i++){
921
1290
  const options = sharedOptions || this.resolveDataElementOptions(i, mode);
922
- const properties = scaleRect(dataset.data[i], xScale, yScale, options.spacing);
1291
+ const node = this.getParsed(i);
1292
+ const properties = scaleRect(node, xScale, yScale, spacing);
1293
+ properties.hidden = properties.hidden || !!node.hidden;
923
1294
  if (reset) {
924
1295
  properties.width = 0;
925
1296
  properties.height = 0;
@@ -934,23 +1305,29 @@ class TreemapController extends DatasetController {
934
1305
  draw() {
935
1306
  const { ctx, chartArea } = this.chart;
936
1307
  const metadata = this.getMeta().data || [];
937
- const dataset = this.getDataset();
938
- const data = dataset.data;
1308
+ const { displayMode, rtl, spacing } = this.options;
1309
+ const layout = {
1310
+ displayMode,
1311
+ rtl,
1312
+ spacing
1313
+ };
939
1314
  clipArea(ctx, chartArea);
940
1315
  for(let i = 0, ilen = metadata.length; i < ilen; ++i){
941
1316
  const rect = metadata[i];
942
1317
  if (!rect.hidden) {
943
- rect.draw(ctx, data[i]);
1318
+ rect.draw(ctx, this.getParsed(i), layout);
944
1319
  }
945
1320
  }
946
1321
  unclipArea(ctx);
947
1322
  }
948
1323
  constructor(chart, datasetIndex){
949
1324
  super(chart, datasetIndex);
950
- this._groups = undefined;
951
- this._keys = undefined;
952
1325
  this._rect = undefined;
953
1326
  this._rectChanged = true;
1327
+ this._regionWarned = false;
1328
+ this._nodes = [];
1329
+ this._layoutDirty = true;
1330
+ this._fingerprint = undefined;
954
1331
  }
955
1332
  }
956
1333
  TreemapController.id = 'treemap';
@@ -967,7 +1344,18 @@ TreemapController.defaults = {
967
1344
  type: 'number'
968
1345
  }
969
1346
  },
970
- dataElementType: 'treemap'
1347
+ dataElementType: 'treemap',
1348
+ displayMode: layoutDefaults.displayMode,
1349
+ groups: [],
1350
+ key: '',
1351
+ leafKey: '_leaf',
1352
+ others: false,
1353
+ region: undefined,
1354
+ rtl: layoutDefaults.rtl,
1355
+ spacing: layoutDefaults.spacing,
1356
+ sumKeys: [],
1357
+ unsorted: false,
1358
+ valueScale: 'linear'
971
1359
  };
972
1360
  TreemapController.descriptors = {
973
1361
  _indexable: false,
@@ -992,10 +1380,9 @@ TreemapController.overrides = {
992
1380
  tooltip: {
993
1381
  callbacks: {
994
1382
  label (item) {
995
- const dataset = item.dataset;
996
- const dataItem = dataset.data[item.dataIndex];
997
- const label = dataItem.g || dataItem._data.label || dataset.label;
998
- return (label ? `${label}: ` : '') + dataItem.v;
1383
+ const node = item.parsed;
1384
+ const label = node.g || node._data?.label || item.dataset.label;
1385
+ return (label ? `${label}: ` : '') + node.v;
999
1386
  },
1000
1387
  title (items) {
1001
1388
  if (items.length) {
@@ -1026,7 +1413,7 @@ TreemapController.overrides = {
1026
1413
  }
1027
1414
  };
1028
1415
  TreemapController.beforeRegister = ()=>{
1029
- requireVersion('chart.js', '3.8', Chart.version);
1416
+ requireVersion('chart.js', '4.0', Chart.version);
1030
1417
  };
1031
1418
  TreemapController.afterRegister = ()=>{
1032
1419
  registerTooltipPositioner();
@@ -1097,7 +1484,7 @@ function addNormalRectPath(ctx, rect) {
1097
1484
  }
1098
1485
 
1099
1486
  class TreemapElement extends Element {
1100
- draw(ctx, data) {
1487
+ draw(ctx, data, layout = layoutDefaults) {
1101
1488
  if (!data) {
1102
1489
  return;
1103
1490
  }
@@ -1117,8 +1504,7 @@ class TreemapElement extends Element {
1117
1504
  addRectPath(ctx, inner);
1118
1505
  ctx.fillStyle = options.backgroundColor;
1119
1506
  ctx.fill();
1120
- drawDivider(ctx, inner, options, data);
1121
- drawText(ctx, inner, options, data, this);
1507
+ drawText(ctx, inner, options, data, this, layout);
1122
1508
  ctx.restore();
1123
1509
  }
1124
1510
  inRange(mouseX, mouseY, useFinalPosition) {
@@ -1167,18 +1553,10 @@ TreemapElement.defaults = {
1167
1553
  const label = ctx.raw._data?.label;
1168
1554
  return ctx.raw.g || (typeof label === 'string' ? label : '');
1169
1555
  },
1170
- padding: 3
1171
- },
1172
- displayMode: 'containerBoxes',
1173
- dividers: {
1174
- display: false,
1175
- lineCapStyle: 'butt',
1176
- lineColor: 'black',
1177
- lineDash: [],
1178
- lineDashOffset: 0,
1179
- lineWidth: 1
1556
+ overflow: 'ellipsis',
1557
+ padding: 3,
1558
+ textAlign: undefined
1180
1559
  },
1181
- label: undefined,
1182
1560
  labels: {
1183
1561
  align: 'center',
1184
1562
  color: 'black',
@@ -1199,11 +1577,10 @@ TreemapElement.defaults = {
1199
1577
  },
1200
1578
  overflow: 'cut',
1201
1579
  padding: 3,
1202
- position: 'middle'
1203
- },
1204
- rtl: false,
1205
- spacing: 0.5,
1206
- unsorted: false
1580
+ position: 'middle',
1581
+ textAlign: undefined,
1582
+ wrap: false
1583
+ }
1207
1584
  };
1208
1585
  TreemapElement.descriptors = {
1209
1586
  _indexable: false,
@@ -1222,4 +1599,4 @@ TreemapElement.defaultRoutes = {
1222
1599
  borderColor: 'borderColor'
1223
1600
  };
1224
1601
 
1225
- export { TreemapController, TreemapElement };
1602
+ export { TreemapController, TreemapElement, flattenTree };