Skip to content

Commit

Permalink
Add treemap visualization
Browse files Browse the repository at this point in the history
  • Loading branch information
kuzmadom committed Oct 17, 2024
1 parent 9704106 commit eea95f8
Show file tree
Hide file tree
Showing 10 changed files with 341 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import preparePivotTableData from '../../../preparers/old-pivot-table/old-pivot-
import {prepareD3Pie, prepareHighchartsPie} from '../../../preparers/pie';
import preparePolylineData from '../../../preparers/polyline';
import {prepareD3Scatter, prepareHighchartsScatter} from '../../../preparers/scatter';
import prepareTreemapData from '../../../preparers/treemap';
import {prepareD3Treemap, prepareHighchartsTreemap} from '../../../preparers/treemap';
import type {PrepareFunction, PrepareFunctionResultData} from '../../../preparers/types';
import {getServerDateFormat} from '../../../utils/misc-helpers';
import {OversizeErrorType} from '../../constants/errors';
Expand Down Expand Up @@ -191,7 +191,12 @@ export default ({
break;

case WizardVisualizationId.Treemap:
prepare = prepareTreemapData;
prepare = prepareHighchartsTreemap;
rowsLimit = 800;
break;

case WizardVisualizationId.TreemapD3:
prepare = prepareD3Treemap;
rowsLimit = 800;
break;

Expand Down
12 changes: 10 additions & 2 deletions src/server/modes/charts/plugins/datalens/js/js.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import preparePivotTableData from '../preparers/old-pivot-table/old-pivot-table'
import {prepareD3Pie, prepareHighchartsPie} from '../preparers/pie';
import preparePolylineData from '../preparers/polyline';
import {prepareD3Scatter, prepareHighchartsScatter} from '../preparers/scatter';
import prepareTreemapData from '../preparers/treemap';
import {prepareD3Treemap, prepareHighchartsTreemap} from '../preparers/treemap';
import type {
LayerChartMeta,
PrepareFunction,
Expand Down Expand Up @@ -477,6 +477,8 @@ function prepareSingleResult({

const segments: ServerField[] = shared.segments || [];

console.log('---------visualization.id', visualization.id);

switch (visualization.id) {
case 'line':
case 'area':
Expand Down Expand Up @@ -558,7 +560,13 @@ function prepareSingleResult({
break;

case 'treemap':
prepare = prepareTreemapData;
prepare = prepareHighchartsTreemap;
rowsLimit = 800;
break;

case WizardVisualizationId.TreemapD3:
console.log('prepareD3Treemap', prepareD3Treemap);
prepare = prepareD3Treemap;
rowsLimit = 800;
break;

Expand Down
300 changes: 300 additions & 0 deletions src/server/modes/charts/plugins/datalens/preparers/treemap/d3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,300 @@
import type {ChartKitWidgetData, TreemapSeries, TreemapSeriesData} from '@gravity-ui/chartkit/build/types/widget-data';
import escape from 'lodash/escape';

import {
Feature,
MINIMUM_FRACTION_DIGITS,
isDateField,
isMarkdownField,
} from '../../../../../../../shared';
import type {WrappedMarkdown} from '../../../../../../../shared/utils/markdown';
import {wrapMarkdownValue} from '../../../../../../../shared/utils/markdown';
import {
mapAndColorizeHashTableByGradient,
mapAndColorizeHashTableByPalette,
} from '../../utils/color-helpers';
import {
chartKitFormatNumberWrapper,
findIndexInOrder,
formatDate,
isGradientMode,
isNumericalDataType,
} from '../../utils/misc-helpers';
import type {PrepareFunctionArgs} from '../types';

type TreemapItemName = string | null | WrappedMarkdown;

type TreemapItem = {
id: string;
name: TreemapItemName | TreemapItemName[];
parent?: string;
label?: string;
value?: number;
drillDownFilterValue?: string | null;
color?: string;
custom?: object;
};

export function prepareD3Treemap({
placeholders,
resultData,
colors,
colorsConfig,
idToTitle,
idToDataType,
features,
ChartEditor,
}: PrepareFunctionArgs): Partial<ChartKitWidgetData> {
// Dimensions
const d = placeholders[0].items;
const dTypes = d.map((item) => item.data_type);
const useMarkdown = d?.some(isMarkdownField);

// Measures
const m = placeholders[1].items;

const color = colors[0];
const colorFieldDataType = color ? idToDataType[color.guid] : null;

const gradientMode =
color &&
colorFieldDataType &&
isGradientMode({colorField: color, colorFieldDataType, colorsConfig});

const {data, order} = resultData;

let treemap: TreemapSeriesData[] = [];
const treemapIds: string[] = [];
const hashTable: Record<string, {value: string | null; label: string}> = {};
const valuesForColorData: Record<string, number> & {colorGuid?: string} = {};
const isFloat = m[0] && m[0].data_type === 'float';
const shouldEscapeUserValue = features[Feature.EscapeUserHtmlInDefaultHcTooltip];
let multimeasure = false;
let measureNamesLevel: number;
let colorData: Record<string, {backgroundColor: string}> = {};

if (color) {
// We make the property non-enumerable so that it does not participate in the formation of the palette
Object.defineProperty(valuesForColorData, 'colorGuid', {
enumerable: false,
value: color.guid,
});
}

const measureNames = m.map((measureItem) => idToTitle[measureItem.guid]);

// TODO: think about why. After all, you can put only one field in the measures (Size) (treemap.tsx)
if (measureNames.length > 1) {
multimeasure = true;

d.some((item, level) => {
if (item.type === 'PSEUDO') {
measureNamesLevel = level;

return true;
} else {
return false;
}
});
}

data.forEach((values) => {
let colorByDimension: string | null;
if (color && color.type === 'DIMENSION') {
const actualTitle = idToTitle[color.guid];
const i = findIndexInOrder(order, color, actualTitle);
const colorValue = values[i];

colorByDimension = colorValue;
}

const dPath: (string | null)[] = [];
let lastDimensionItem: TreemapSeriesData | undefined;
d.forEach((item, level) => {
if (item.type === 'PSEUDO') {
return;
}

const actualTitle = idToTitle[item.guid];

const i = findIndexInOrder(order, item, actualTitle);

const rawValue = values[i];
let value: string | null;

if (isDateField({data_type: dTypes[level]})) {
value = formatDate({
valueType: dTypes[level],
value: rawValue,
format: item.format,
});
} else if (isNumericalDataType(dTypes[level]) && item.formatting) {
value = chartKitFormatNumberWrapper(rawValue as unknown as number, {
lang: 'ru',
...item.formatting,
});
} else {
value = rawValue && shouldEscapeUserValue ? escape(rawValue as string) : rawValue;
}

const treemapId =
dPath.length >= 1 ? `id_${dPath[0]}/${value}` : `id_${dPath.join()}${value}`;

const name = isMarkdownField(item) ? wrapMarkdownValue(value as string) : value;

const treemapItem: TreemapSeriesData = {
id: treemapId,
name,
drillDownFilterValue: value,
value: 0,
};

if (dPath.length) {
treemapItem.parent = `id_${dPath.join('/')}`;
}

dPath.push(value);

treemapItem.id = `id_${dPath.join('/')}`;

if (level === d.length - 1) {
lastDimensionItem = treemapItem;
} else if (!treemapIds.includes(treemapItem.id)) {
treemap.push(treemapItem);
treemapIds.push(treemapItem.id);
}
});

const key = `id_${dPath.join('/')}`;
m.forEach((measureItem) => {
const actualTitle = idToTitle[measureItem.guid];
const i = findIndexInOrder(order, measureItem, actualTitle);
const value = values[i];
const label = chartKitFormatNumberWrapper(Number(value), {
lang: 'ru',
...(measureItem.formatting ?? {precision: isFloat ? MINIMUM_FRACTION_DIGITS : 0}),
});

if (multimeasure) {
const dPathSpecial = [...dPath];

dPathSpecial.splice(measureNamesLevel, 0, actualTitle);

const specialKey = `${dPathSpecial.join('/')}`;

hashTable[specialKey] = {value: value, label};
} else {
hashTable[key] = {value: value, label};
}

if (color) {
if (gradientMode) {
const colorTitle = idToTitle[color.guid];
const i = findIndexInOrder(order, color, colorTitle);
const colorValue = values[i];

valuesForColorData[key] = colorValue as unknown as number;
} else {
valuesForColorData[key] = colorByDimension as unknown as number;
}
}
});

if (lastDimensionItem) {
lastDimensionItem.value = Number(hashTable[key]?.value);
lastDimensionItem.label = hashTable[key]?.label;
let name: any[] = dPath;
if (useMarkdown) {
name = dPath.map((item) => (item ? wrapMarkdownValue(item) : item));
}
lastDimensionItem.name = name as any;

treemap.push(lastDimensionItem);
}
});

if (color) {
if (gradientMode) {
colorData = mapAndColorizeHashTableByGradient(
valuesForColorData,
colorsConfig,
).colorData;
} else {
colorData = mapAndColorizeHashTableByPalette(valuesForColorData, colorsConfig);
}

treemap = treemap.map((obj) => {
const item = {...obj};

const colorDataValue = colorData[obj.id];
if (colorDataValue) {
item.color = colorDataValue.backgroundColor;
}

return item;
});
}

let levels;

if (d.length === 1) {
levels = [
{
level: 1,
borderWidth: 1,
},
];
} else if (d.length === 2) {
levels = [
{
level: 1,
borderWidth: 3,
},
{
level: 2,
borderWidth: 1,
},
];
} else {
levels = [
{
level: 1,
borderWidth: 5,
},
{
level: 2,
borderWidth: 3,
},
{
level: 3,
borderWidth: 1,
},
];
}

if (useMarkdown) {
ChartEditor.updateConfig({useMarkdown: true});
}

const series: TreemapSeries = {
type: 'treemap',
name: '',
layoutAlgorithm: 'squarify' as TreemapSeries['layoutAlgorithm'],
dataLabels: {
enabled: true,
},
levels,
data: treemap,
};

const result: Partial<ChartKitWidgetData> = {
series: {
data: [series],
},
legend: {
enabled: false,
},
};

return result;
}
Loading

0 comments on commit eea95f8

Please sign in to comment.