Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add treemap visualization #1709

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/server/configs/shared/ql-chart-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import type {Request} from '@gravity-ui/expresskit';

import type {ServerI18n} from '../../../i18n/types';
import type {QlExtendedConfig} from '../../../shared';
import {QL_TYPE, WizardVisualizationId, isMonitoringOrPrometheusChart} from '../../../shared';
import {
QL_TYPE,
WizardVisualizationId,
isD3Visualization,
isMonitoringOrPrometheusChart,
} from '../../../shared';
import {mapQlConfigToLatestVersion} from '../../../shared/modules/config/ql';
import {getTranslationFn} from '../../../shared/modules/language';
import {identifyParams} from '../../modes/charts/plugins/ql/utils/identify-params';
Expand All @@ -24,6 +29,10 @@ export default {
const {visualization, chartType} = config;
const id = visualization.id;

if (isD3Visualization(id as WizardVisualizationId)) {
return QL_TYPE.D3_QL_NODE;
}

switch (id) {
case 'table': // Legacy
case WizardVisualizationId.FlatTable: // Available with WizardQLCommonVisualization feature
Expand Down Expand Up @@ -60,13 +69,6 @@ export default {
return QL_TYPE.METRIC_QL_NODE;
}
}
case WizardVisualizationId.LineD3:
case WizardVisualizationId.ScatterD3:
case WizardVisualizationId.BarXD3:
case WizardVisualizationId.PieD3:
case WizardVisualizationId.DonutD3: {
return QL_TYPE.D3_QL_NODE;
}
default:
return QL_TYPE.GRAPH_QL_NODE;
}
Expand Down
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
9 changes: 7 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 @@ -558,7 +558,12 @@ function prepareSingleResult({
break;

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

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

Expand Down
262 changes: 262 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,262 @@
import type {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Almost a complete copy of the data preparation for highcharts chart except for the difference in data format and things that didn't make sense

ChartKitWidgetData,
TreemapSeries,
TreemapSeriesData,
} from '@gravity-ui/chartkit/build/types/widget-data';
import escape from 'lodash/escape';

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

type TreemapItemName = string | null | WrappedMarkdown;
type ExtendedTreemapSeriesData = Omit<TreemapSeriesData, 'name'> & {
name: TreemapItemName | TreemapItemName[];
drillDownFilterValue: unknown;
label?: string;
};

type ExtendedTreemapSeries = TreemapSeries & {
custom?: {
exportSettings?: SeriesExportSettings;
};
};

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

const measures = placeholders.find((p) => p.id === PlaceholderId.Measures)?.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: ExtendedTreemapSeriesData[] = [];
const treemapIds: string[] = [];
const hashTable: Record<string, {value: string | null; label: string}> = {};
const valuesForColorData: Record<string, number> & {colorGuid?: string} = {};
const isFloat = measures[0] && measures[0].data_type === 'float';
const shouldEscapeUserValue = features[Feature.EscapeUserHtmlInDefaultHcTooltip];
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,
});
}

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: ExtendedTreemapSeriesData | undefined;
dimensions.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: ExtendedTreemapSeriesData = {
id: treemapId,
name,
drillDownFilterValue: value,
};

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

dPath.push(value);

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

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

const key = `id_${dPath.join('/')}`;
measures.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}),
});

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 = obj.id ? colorData[obj.id] : null;
if (colorDataValue) {
item.color = colorDataValue.backgroundColor;
}

return item;
});
}

const dimensionsSize = dimensions.length;
const maxPadding = 5;
const levels: TreemapSeries['levels'] = new Array(dimensionsSize)
.fill(null)
.map((_, index) => ({
index: index + 1,
padding: Math.min(maxPadding, (dimensionsSize - index) * 2 - 1),
}));

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

const exportSettingsCols = dimensions.map<ColumnExportSettings>((field, index) => {
return getExportColumnSettings({path: `name.${index}`, field});
});
exportSettingsCols.push(getExportColumnSettings({path: `value`, field: measures[0]}));

const series: ExtendedTreemapSeries = {
type: 'treemap',
name: '',
layoutAlgorithm: 'squarify' as TreemapSeries['layoutAlgorithm'],
dataLabels: {
enabled: true,
html: useMarkdown,
style: {
fontColor: 'var(--g-color-text-complementary)',
},
},
levels,
data: treemap as TreemapSeriesData[],
custom: {
exportSettings: {
columns: exportSettingsCols,
},
},
};

return {
series: {
data: [series],
},
legend: {
enabled: false,
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,21 @@ import {
MINIMUM_FRACTION_DIGITS,
isDateField,
isMarkdownField,
} from '../../../../../../shared';
import type {WrappedMarkdown} from '../../../../../../shared/utils/markdown';
import {wrapMarkdownValue} from '../../../../../../shared/utils/markdown';
} from '../../../../../../../shared';
import type {WrappedMarkdown} from '../../../../../../../shared/utils/markdown';
import {wrapMarkdownValue} from '../../../../../../../shared/utils/markdown';
import {
mapAndColorizeHashTableByGradient,
mapAndColorizeHashTableByPalette,
} from '../utils/color-helpers';
} from '../../utils/color-helpers';
import {
chartKitFormatNumberWrapper,
findIndexInOrder,
formatDate,
isGradientMode,
isNumericalDataType,
} from '../utils/misc-helpers';

import type {PrepareFunctionArgs} from './types';
} from '../../utils/misc-helpers';
import type {PrepareFunctionArgs} from '../types';

type TreemapItemName = string | null | WrappedMarkdown;

Expand All @@ -35,7 +34,7 @@ type TreemapItem = {
custom?: object;
};

function prepareTreemap({
export function prepareHighchartsTreemap({
placeholders,
resultData,
colors,
Expand Down Expand Up @@ -303,5 +302,3 @@ function prepareTreemap({

return {graphs};
}

export default prepareTreemap;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './d3';
export * from './highcharts';
Loading
Loading