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