devextreme
Version:
JavaScript/TypeScript Component Suite for Responsive Web Development
537 lines (521 loc) • 18.4 kB
JavaScript
/**
* DevExtreme (esm/__internal/viz/tree_map/tree_map.base.js)
* Version: 26.1.6
* Build date: Fri Oct 16 2026
*
* Copyright (c) 2012 - 2026 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
import "../../viz/tree_map/tiling.squarified";
import "../../viz/tree_map/colorizing.discrete";
import {
registerComponent as componentRegistrator
} from "../../core/component_registrator";
import {
noop
} from "../../core/utils/m_common";
import BaseWidget from "../../viz/core/base_widget";
import {
plugin
} from "../../viz/core/data_source";
import {
setupWidgetPrototype
} from "../../viz/core/helpers";
import {
patchFontOptions
} from "../../viz/core/utils";
import {
getColorizer,
setDefaultColorizer
} from "../../viz/tree_map/colorizing";
import {
buildRectAppearance,
buildTextAppearance
} from "../../viz/tree_map/common";
import Node from "../../viz/tree_map/node";
import {
getAlgorithm as getTilingAlgorithm,
setDefaultAlgorithm
} from "../../viz/tree_map/tiling";
const directions = {
lefttoprightbottom: [1, 1],
leftbottomrighttop: [1, -1],
righttopleftbottom: [-1, 1],
rightbottomlefttop: [-1, -1]
};
setDefaultAlgorithm("squarified");
setDefaultColorizer("discrete");
const emptyRect = [0, 0, 0, 0];
function pickPositiveInteger(val) {
return val > 0 ? Math.round(val) : 0
}
function traverseDataItems(root, dataItems, level, params) {
const nodes = [];
const allNodes = params.nodes;
let totalValue = 0;
dataItems.forEach(dataItem => {
const node = new Node;
node._id = allNodes.length;
node.ctx = params.ctx;
node.parent = root;
node.level = level;
node.index = nodes.length;
node.data = dataItem;
params.buildNode(node);
allNodes.push(node);
nodes.push(node);
const items = dataItem[params.itemsField];
if (null !== items && void 0 !== items && items.length) {
traverseDataItems(node, items, level + 1, params)
}
if (dataItem[params.valueField] > 0) {
node.value = Number(dataItem[params.valueField])
}
totalValue += node.value
});
root.nodes = nodes;
root.value = totalValue
}
function processNodes(context, root, process) {
const {
nodes: nodes
} = root;
nodes.forEach(node => {
process(context, node);
if (node.isNode()) {
processNodes(context, node, process)
}
})
}
function createLeaf(context, node) {
const tile = context.renderer.simpleRect().append(context.group);
context.setTrackerData(node, tile);
return tile
}
function createGroup(context, node) {
const outer = context.renderer.simpleRect().append(context.group);
const inner = context.renderer.simpleRect().append(context.group);
context.setTrackerData(node, inner);
return {
outer: outer,
inner: inner
}
}
const createTile = [createLeaf, createGroup];
function processTileAppearance(context, node) {
node.color = node.data[context.colorField] || context.getColor(node) || node.parent.color;
node.updateStyles();
node.tile = !node.ctx.forceReset && node.tile || createTile[Number(node.isNode())](context, node);
node.applyState()
}
function createLabel(context, currentNode, settings) {
const labelData = currentNode.data[context.labelField];
currentNode.label = labelData ? String(labelData) : null;
const textData = currentNode.customLabel || currentNode.label;
if (textData) {
currentNode.text = context.renderer.text(textData).attr(settings.attr).css(settings.css).append(context.group);
context.setTrackerData(currentNode, currentNode.text)
}
}
function processLabelAppearance(context, node) {
node.updateLabelStyle();
if (node.labelState.visible) {
createLabel(context, node, node.labelState)
}
}
function calculateRects(context, root) {
const {
nodes: nodes
} = root;
const items = [];
const rects = [];
let sum = 0;
const ii = nodes.length;
items.length = ii;
rects.length = ii;
for (let i = 0; i < ii; i += 1) {
sum += nodes[i].value;
items[i] = {
value: nodes[i].value,
i: i
}
}
if (sum > 0) {
context.algorithm({
items: items.slice(),
sum: sum,
rect: root.innerRect.slice(),
isRotated: nodes[0].level % 2 !== 0,
directions: context.directions
})
}
for (let i = 0; i < ii; i += 1) {
rects[i] = items[i].rect || emptyRect
}
root.rects = rects
}
function marginateRect(rect, margin) {
return [rect[0] + margin, rect[1] + margin, rect[2] - margin, rect[3] - margin]
}
function buildTileRect(rect, outer, edgeOffset, innerOffset) {
return [rect[0] + (rect[0] === outer[0] ? edgeOffset : +innerOffset), rect[1] + (rect[1] === outer[1] ? edgeOffset : +innerOffset), rect[2] - (rect[2] === outer[2] ? edgeOffset : -innerOffset), rect[3] - (rect[3] === outer[3] ? edgeOffset : -innerOffset)]
}
function setRectAttrs(element, rect) {
element.attr({
x: rect[0],
y: rect[1],
width: Math.max(rect[2] - rect[0], 0),
height: Math.max(rect[3] - rect[1], 0)
})
}
function processTiling(context, node) {
let rect = node.parent.rects[node.index];
const {
rectOffsets: rectOffsets
} = context;
if (node.isNode()) {
setRectAttrs(node.tile.outer, buildTileRect(rect, node.parent.innerRect, rectOffsets.headerEdge, rectOffsets.headerInner));
rect = marginateRect(rect, context.groupPadding);
const headerHeight = Math.min(context.headerHeight, rect[3] - rect[1]);
node.rect = [rect[0], rect[1], rect[2], rect[1] + headerHeight];
setRectAttrs(node.tile.inner, marginateRect(node.rect, rectOffsets.headerEdge));
rect[1] += headerHeight;
node.innerRect = rect;
calculateRects(context, node)
} else {
node.rect = rect;
setRectAttrs(node.tile, buildTileRect(rect, node.parent.innerRect, rectOffsets.tileEdge, rectOffsets.tileInner))
}
}
function layoutTextNode(node, params) {
const {
rect: rect,
text: text
} = node;
const bBox = text.getBBox();
const {
paddingLeftRight: paddingLeftRight,
paddingTopBottom: paddingTopBottom
} = params;
const effectiveWidth = rect[2] - rect[0] - 2 * paddingLeftRight;
text.setMaxSize(effectiveWidth, rect[3] - rect[1] - paddingTopBottom, node.isNode() ? {
textOverflow: params.groupLabelOverflow,
wordWrap: "none"
} : {
textOverflow: params.tileLabelOverflow,
wordWrap: params.tileLabelWordWrap,
hideOverflowEllipsis: true
});
text.move(params.rtlEnabled ? rect[2] - paddingLeftRight - bBox.x - bBox.width : rect[0] + paddingLeftRight - bBox.x, rect[1] + paddingTopBottom - bBox.y)
}
function processLabelsLayout(context, node) {
if (node.text && node.labelState.visible) {
layoutTextNode(node, node.labelParams)
}
}
class TreeMapBase extends BaseWidget {
_getDefaultSize() {
return {
width: 400,
height: 400
}
}
_init() {
this._rectOffsets = {};
this._handlers = Object.create(this._handlers);
this._context = {
suspend: () => {
if (!this._applyingChanges) {
this._suspendChanges()
}
},
resume: () => {
if (!this._applyingChanges) {
this._resumeChanges()
}
},
change: codes => {
this._change(codes)
},
settings: [{}, {}],
calculateState: this._handlers.calculateState,
calculateLabelState: buildTextAppearance
};
this._root = {
nodes: []
};
this._topNode = this._root;
super._init()
}
_initCore() {
const renderer = this._renderer;
this._createProxyType();
this._tilesGroup = renderer.g().linkOn(renderer.root, "tiles").linkAppend();
this._labelsGroup = renderer.g().linkOn(renderer.root, "labels").linkAppend()
}
_disposeCore() {
if (this._filter) {
this._filter.dispose()
}
this._labelsGroup.linkOff();
this._tilesGroup.linkOff()
}
_applySize(rect) {
this._tilingRect = rect.slice();
this._change(["TILING"])
}
_changeDataSource() {
this._isDataExpected = true;
this._isSyncData = true;
this._updateDataSource();
this._isSyncData = false;
if (this._isDataExpected) {
this._suspendChanges()
}
}
_dataSourceChangedHandler() {
if (this._isDataExpected) {
this._isDataExpected = false;
this._change(["NODES_CREATE"]);
if (!this._isSyncData) {
this._resumeChanges()
}
} else {
this._requestChange(["NODES_CREATE"])
}
}
_change_DATA_SOURCE() {
this._changeDataSource()
}
_change_TILE_SETTINGS() {
this._changeTileSettings()
}
_change_GROUP_SETTINGS() {
this._changeGroupSettings()
}
_change_MAX_DEPTH() {
this._changeMaxDepth()
}
_change_NODES_CREATE() {
this._buildNodes()
}
_change_NODES_RESET() {
this._resetNodes()
}
_change_TILES() {
this._applyTilesAppearance()
}
_change_LABELS() {
this._applyLabelsAppearance()
}
_change_TILING() {
this._performTiling()
}
_change_LABELS_LAYOUT() {
this._performLabelsLayout()
}
_applyChanges() {
super._applyChanges();
if (!this._isDataExpected) {
this._drawn()
}
this._context.forceReset = false
}
_buildNodes() {
const root = new Node;
this._root = root;
this._topNode = root;
root._id = 0;
root.parent = {};
root.data = {};
root.level = -1;
root.index = -1;
root.ctx = this._context;
root.label = null;
this._nodes = [root];
this._handlers.beginBuildNodes();
const processedData = this._processDataSourceItems(this._dataSourceItems() || []);
traverseDataItems(root, processedData.items, 0, {
itemsField: !processedData.isPlain && this._getOption("childrenField", true) || "items",
valueField: this._getOption("valueField", true) || "value",
buildNode: this._handlers.buildNode,
ctx: this._context,
nodes: this._nodes
});
this._onNodesCreated();
this._handlers.endBuildNodes();
this._change(["NODES_RESET"])
}
_processDataSourceItems(items) {
return {
items: items,
isPlain: false
}
}
_changeTileSettings() {
const options = this._getOption("tile");
const offsets = this._rectOffsets;
const borderWidth = pickPositiveInteger(options.border.width);
const edgeOffset = borderWidth / 2;
const innerOffset = borderWidth % 2 ? .5 : 0;
const labelOptions = options.label;
const settings = this._context.settings[0];
this._change(["TILES", "LABELS"]);
settings.state = this._handlers.calculateState(options);
this._filter = this._filter || this._renderer.shadowFilter("-50%", "-50%", "200%", "200%");
this._filter.attr(labelOptions.shadow);
this._calculateLabelSettings(settings, labelOptions, this._filter.id);
if (offsets.tileEdge !== edgeOffset || offsets.tileInner !== innerOffset) {
offsets.tileEdge = edgeOffset;
offsets.tileInner = innerOffset;
this._change(["TILING"])
}
}
_changeGroupSettings() {
const options = this._getOption("group");
const labelOptions = options.label;
const offsets = this._rectOffsets;
const borderWidth = pickPositiveInteger(options.border.width);
const edgeOffset = borderWidth / 2;
const innerOffset = borderWidth % 2 ? .5 : 0;
const groupPadding = pickPositiveInteger(options.padding);
const settings = this._context.settings[1];
this._change(["TILES", "LABELS"]);
settings.state = this._handlers.calculateState(options);
this._calculateLabelSettings(settings, labelOptions);
const headerHeight = options.headerHeight >= 0 ? pickPositiveInteger(options.headerHeight) : settings.labelParams.height + 2 * pickPositiveInteger(labelOptions.paddingTopBottom);
if (this._headerHeight !== headerHeight) {
this._headerHeight = headerHeight;
this._change(["TILING"])
}
if (this._groupPadding !== groupPadding) {
this._groupPadding = groupPadding;
this._change(["TILING"])
}
if (offsets.headerEdge !== edgeOffset || offsets.headerInner !== innerOffset) {
offsets.headerEdge = edgeOffset;
offsets.headerInner = innerOffset;
this._change(["TILING"])
}
}
_calculateLabelSettings(settings, options, filter) {
const bBox = this._getTextBBox(options.font);
const paddingLeftRight = pickPositiveInteger(options.paddingLeftRight);
const paddingTopBottom = pickPositiveInteger(options.paddingTopBottom);
const tileLabelOptions = this._getOption("tile.label");
const groupLabelOptions = this._getOption("group.label");
settings.labelState = buildTextAppearance(options, filter);
settings.labelState.visible = !("visible" in options) || !!options.visible;
settings.labelParams = {
height: bBox.height,
rtlEnabled: this._getOption("rtlEnabled", true),
paddingTopBottom: paddingTopBottom,
paddingLeftRight: paddingLeftRight,
tileLabelWordWrap: tileLabelOptions.wordWrap,
tileLabelOverflow: tileLabelOptions.textOverflow,
groupLabelOverflow: groupLabelOptions.textOverflow
}
}
_changeMaxDepth() {
const option = this._getOption("maxDepth", true);
const maxDepth = option >= 1 ? Math.round(option) : 1 / 0;
if (this._maxDepth !== maxDepth) {
this._maxDepth = maxDepth;
this._change(["NODES_RESET"])
}
}
_resetNodes() {
this._tilesGroup.clear();
this._renderer.initDefsElements();
this._context.forceReset = true;
this._context.minLevel = this._topNode.level + 1;
this._context.maxLevel = this._context.minLevel + this._maxDepth - 1;
this._change(["TILES", "LABELS", "TILING"])
}
_processNodes(context, process) {
processNodes(context, this._topNode, process)
}
_applyTilesAppearance() {
const colorizer = getColorizer(this._getOption("colorizer"), this._themeManager, this._topNode);
this._processNodes({
renderer: this._renderer,
group: this._tilesGroup,
setTrackerData: this._handlers.setTrackerData,
colorField: this._getOption("colorField", true) || "color",
getColor: colorizer
}, processTileAppearance)
}
_applyLabelsAppearance() {
this._labelsGroup.clear();
this._processNodes({
renderer: this._renderer,
group: this._labelsGroup,
setTrackerData: this._handlers.setTrackerData,
labelField: this._getOption("labelField", true) || "name"
}, processLabelAppearance);
this._change(["LABELS_LAYOUT"])
}
_performTiling() {
const layoutDirection = String(this._getOption("layoutDirection", true)).toLowerCase();
const context = {
algorithm: getTilingAlgorithm(this._getOption("layoutAlgorithm", true)),
directions: directions[layoutDirection] || directions.lefttoprightbottom,
headerHeight: this._headerHeight,
groupPadding: this._groupPadding,
rectOffsets: this._rectOffsets
};
this._topNode.innerRect = this._tilingRect;
calculateRects(context, this._topNode);
this._processNodes(context, processTiling);
this._change(["LABELS_LAYOUT"]);
this._onTilingPerformed()
}
_performLabelsLayout() {
this._processNodes(null, processLabelsLayout)
}
_getTextBBox(fontOptions) {
const renderer = this._renderer;
const text = this._textForCalculations || renderer.text("0", 0, 0);
this._textForCalculations = text;
text.css(patchFontOptions(fontOptions)).append(renderer.root);
const bBox = text.getBBox();
text.remove();
return bBox
}
}
setupWidgetPrototype(TreeMapBase, {
_handlers: {
beginBuildNodes: noop,
buildNode: noop,
endBuildNodes: noop,
setTrackerData: noop,
calculateState: options => buildRectAppearance(options)
},
_rootClass: "dxtm-tree-map",
_rootClassPrefix: "dxtm",
_themeSection: "treeMap",
_fontFields: ["tile.label.font", "group.label.font"],
_initialChanges: ["DATA_SOURCE"],
_createProxyType: noop,
_optionChangesMap: {
dataSource: "DATA_SOURCE",
valueField: "NODES_CREATE",
childrenField: "NODES_CREATE",
colorField: "TILES",
colorizer: "TILES",
labelField: "LABELS",
tile: "TILE_SETTINGS",
group: "GROUP_SETTINGS",
maxDepth: "MAX_DEPTH",
layoutAlgorithm: "TILING",
layoutDirection: "TILING"
},
_themeDependentChanges: ["TILE_SETTINGS", "GROUP_SETTINGS", "MAX_DEPTH"],
_optionChangesOrder: ["DATA_SOURCE", "TILE_SETTINGS", "GROUP_SETTINGS", "MAX_DEPTH"],
_customChangesOrder: ["NODES_CREATE", "NODES_RESET", "TILES", "LABELS", "TILING", "LABELS_LAYOUT"],
_onNodesCreated: noop,
_onTilingPerformed: noop
});
componentRegistrator("dxTreeMap", TreeMapBase);
TreeMapBase.addPlugin(plugin);
export default TreeMapBase;