export function convertItemsWithSegments()

in packages/attribute-slicer-powerbi/src/visual-utils/convertItemsWithSegments.ts [49:121]


export function convertItemsWithSegments(
	dataView: powerbiVisualsApi.DataView,
	onCreateItem: any,
	settings?: IColorSettings,
	createIdBuilder?: () => ISelectionIdBuilder,
) {
	"use strict";
	let items: ItemWithValueSegments[];
	const dvCats = lodashGet(dataView, "categorical.categories");
	const categories = <PrimitiveValue[]>(
		lodashGet(dataView, "categorical.categories[0].values")
	);
	const values = lodashGet(dataView, "categorical.values");
	if (categories) {
		settings = <any>settings || {};

		// Whether or not the gradient coloring mode should be used
		const shouldUseGradient = settings.colorMode === ColorMode.Gradient;

		// We should only add gradients if the data supports gradients, and the user has gradients enabled
		const shouldAddGradients =
			dataSupportsGradients(dataView) && shouldUseGradient;

		// If the data supports default color, then use id.
		const defaultColor = dataSupportsDefaultColor(dataView)
			? colors[0]
			: undefined;

		// We should only colorize instances if the data supports colorized instances and the user isn't
		// trying to use gradients
		const shouldAddInstanceColors =
			dataSupportsColorizedInstances(dataView) && !shouldUseGradient;

		// Calculate the segments
		// Segment info is the list of segments that each row should contain, with the colors of the segements.
		// i.e. [<Sum of Id: Color Blue>, <Average Grade: Color Red>]
		const segmentInfo = calculateSegmentData(
			values,
			defaultColor,
			shouldAddGradients ? settings.gradient : undefined,
			shouldAddInstanceColors ? settings.instanceColors : undefined,
		);

		// Iterate through each of the rows (or categories)
		items = categories.map((category, rowIdx) => {
			const id = createIdBuilder
				? createIdBuilder()
						.withCategory(dvCats[0], rowIdx)
						.createSelectionId()
				: rowIdx;
			let rowTotal = 0;
			let segments: any;

			// If we have bars
			if (values) {
				const segmentData = createSegments(values, segmentInfo, rowIdx);
				segments = segmentData.segments;
				rowTotal = segmentData.total;
				if (settings && settings.reverseOrder) {
					segments.reverse();
				}
			}
			const item = onCreateItem(dvCats, rowIdx, rowTotal, id, segments);
			item.valueSegments = segments;
			return item;
		});

		// Computes the rendered values for each of the items
		computeRenderedValues(items);

		return { items, segmentInfo };
	}
}