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

feat(heatmap): allow rotation of x axis labels #1514

Merged
merged 41 commits into from
Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
7c08e5c
feat: allow rotation of x axis labels
rshen91 Dec 1, 2021
52c7a98
feat: add rotation to y axis label
rshen91 Dec 1, 2021
587c9db
Merge remote-tracking branch 'upstream/master' into heatmap-rotation-…
rshen91 Dec 6, 2021
6bd128a
feat: add overflow to config for truncation
rshen91 Dec 7, 2021
a156574
feat: implement overflow through config for user to set
rshen91 Dec 7, 2021
8eba89b
test: update story to show truncation
rshen91 Dec 7, 2021
985e299
feat: add alternating ability for x axis labels
rshen91 Dec 7, 2021
6a5671f
test: add vrts
rshen91 Dec 8, 2021
8287a2a
fix: code review
rshen91 Dec 9, 2021
a98d1c4
Merge remote-tracking branch 'upstream/master' into heatmap-rotation-…
rshen91 Dec 16, 2021
1f51475
test: update vrts
rshen91 Dec 16, 2021
d126289
Merge branch 'master' into pr/1514
markov00 Dec 21, 2021
63e40b2
Limit the rotation to [-90,+90] range and fix the alignment
markov00 Dec 27, 2021
4e7bf9b
Merge branch 'master' into pr/1514
markov00 Dec 27, 2021
1270693
Extend screenspace scale compressor to consider different left/right …
markov00 Jan 26, 2022
3061bda
Add 2dim vectors base operations
markov00 Jan 26, 2022
3a96395
Add optimal rect rotation fn
markov00 Jan 26, 2022
c88f9a2
Add transform for Vec2 array
markov00 Jan 26, 2022
8806f97
Compute axis space based on label rotations
markov00 Feb 4, 2022
a3a9d36
Remove alternate and rotation on y
markov00 Feb 8, 2022
628d6f3
Cleanup time axis
markov00 Feb 9, 2022
b227f04
Merge remote-tracking branch 'upstream/master' into pr/1514
markov00 Feb 9, 2022
4085b23
Render truncated text on x
markov00 Feb 10, 2022
6684c02
Reduce ticks on time axis
markov00 Feb 10, 2022
9710525
Reduce ticks on time scale
markov00 Feb 14, 2022
726485a
Merge branch 'master' into pr/1514
markov00 Feb 14, 2022
ea3fc48
Cleanu up APIs
markov00 Feb 14, 2022
3d9f2b9
Fix up commits
markov00 Feb 14, 2022
976b8d4
Move the theme constraints to chart theme selector
markov00 Feb 15, 2022
e5cbede
Fix test files
markov00 Feb 15, 2022
dcf27f6
Simplify x axis size code
markov00 Feb 15, 2022
401c3d8
Cleanup scale compressor code
markov00 Feb 15, 2022
b45f82a
Update VRTs and tests
markov00 Feb 15, 2022
6373d19
Remove unused fn
markov00 Feb 15, 2022
cccab73
Remove a test case in favour of showing the titles in an existing scr…
markov00 Feb 15, 2022
535a58c
Render x axis ticks as an extension of the gridline
markov00 Feb 22, 2022
57795ae
Consider the grid stroke width in the grid width/height calculation
markov00 Feb 22, 2022
ceab0e6
Force the rotation to a minimum optimized angle to avoid overlaps
markov00 Feb 23, 2022
a2d71ab
Move VR test and update screenshots
markov00 Feb 23, 2022
a5a92e5
Fix missing prop
markov00 Feb 23, 2022
9b8cd96
Merge branch 'master' into heatmap-rotation-labels
markov00 Feb 23, 2022
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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions integration/tests/heatmap_stories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,16 @@ describe('Heatmap stories', () => {
'http://localhost:9001/?path=/story/heatmap-alpha--basic&knob-Show%20x%20axis%20title=true&knob-Show%20y%20axis%20title=true',
);
});

monfera marked this conversation as resolved.
Show resolved Hide resolved
markov00 marked this conversation as resolved.
Show resolved Hide resolved
test('rotate categorical axis labels', async () => {
await common.expectChartAtUrlToMatchScreenshot(
'http://localhost:9001/?path=/story/heatmap-alpha--label-rotation&globals=theme:light&knob-Y-axis auto width=true&knob-Y-axis width=50&knob-X-Axis visible=true&knob-X-Axis label fontSize=12&knob-X-Axis label padding=6&knob-X-Axis label rotation=45&knob-Use categorical data=true&knob-Show legend=',
);
});

test('rotate time axis labels', async () => {
await common.expectChartAtUrlToMatchScreenshot(
'http://localhost:9001/?path=/story/heatmap-alpha--label-rotation&globals=theme:light&knob-Y-axis auto width=true&knob-Y-axis width=50&knob-X-Axis visible=true&knob-X-Axis label fontSize=12&knob-X-Axis label padding=6&knob-X-Axis label rotation=45&knob-Use categorical data=&knob-Show legend=',
);
});
});
9 changes: 2 additions & 7 deletions packages/charts/api/charts.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1086,7 +1086,7 @@ export type GroupId = string;
export type GroupKeysOrKeyFn<T> = Array<keyof T> | GroupByKeyFn<T>;

// @alpha
export const Heatmap: <D extends BaseDatum = any>(props: SFProps<HeatmapSpec<D>, "chartType" | "specType", "data" | "timeZone" | "valueAccessor" | "valueFormatter" | "xAccessor" | "yAccessor" | "xSortPredicate" | "ySortPredicate" | "xScale" | "xAxisLabelFormatter" | "xAxisTitle" | "yAxisTitle" | "yAxisLabelFormatter" | "xAxisLabelName" | "yAxisLabelName", "name" | "onBrushEnd" | "highlightedData", "id" | "colorScale">) => null;
export const Heatmap: <D extends BaseDatum = any>(props: SFProps<HeatmapSpec<D>, "chartType" | "specType", "data" | "timeZone" | "valueAccessor" | "valueFormatter" | "xAccessor" | "yAccessor" | "xSortPredicate" | "ySortPredicate" | "xScale" | "xAxisTitle" | "yAxisTitle" | "xAxisLabelFormatter" | "yAxisLabelFormatter" | "xAxisLabelName" | "yAxisLabelName", "name" | "onBrushEnd" | "highlightedData", "id" | "colorScale">) => null;

// @alpha (undocumented)
export interface HeatmapBandsColorScale {
Expand Down Expand Up @@ -1222,19 +1222,16 @@ export interface HeatmapStyle {
// (undocumented)
xAxisLabel: Font & {
fontSize: Pixels;
width: Pixels | 'auto';
align: TextAlign;
baseline: TextBaseline;
visible: boolean;
padding: Pixels | Padding;
rotation: number;
};
// (undocumented)
yAxisLabel: Font & {
fontSize: Pixels;
width: Pixels | 'auto' | {
max: Pixels;
};
baseline: TextBaseline;
visible: boolean;
padding: Pixels | Padding;
};
Expand Down Expand Up @@ -2683,8 +2680,6 @@ export type YDomainRange = YDomainBase & DomainRange & LogScaleOptions;
// Warnings were encountered during analysis:
//
// src/chart_types/partition_chart/layout/types/config.ts:60:5 - (ae-forgotten-export) The symbol "TimeMs" needs to be exported by the entry point index.d.ts
// src/utils/themes/theme.ts:217:5 - (ae-forgotten-export) The symbol "TextAlign" needs to be exported by the entry point index.d.ts
// src/utils/themes/theme.ts:218:5 - (ae-forgotten-export) The symbol "TextBaseline" needs to be exported by the entry point index.d.ts

// (No @packageDocumentation comment for this package)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import { ChartType } from '../../..';
import { Color, Colors } from '../../../../common/colors';
import { Pixels } from '../../../../common/geometry';
import { Box, Font } from '../../../../common/text_utils';
import { Box, Font, TextAlign } from '../../../../common/text_utils';
import { Fill, Line, Rect, Stroke } from '../../../../geoms/types';
import { HeatmapBrushEvent } from '../../../../specs/settings';
import { Point } from '../../../../utils/point';
Expand Down Expand Up @@ -40,6 +40,7 @@ export interface TextBox extends Box {
value: NonNullable<PrimitiveValue>;
x: number;
y: number;
align: TextAlign;
}

/** @internal */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,12 @@ import { colorToRgba } from '../../../../common/color_library_wrappers';
import { fillTextColor } from '../../../../common/fill_text_color';
import { Pixels } from '../../../../common/geometry';
import { Box, Font, maximiseFontSize } from '../../../../common/text_utils';
import { ScaleContinuous } from '../../../../scales';
import { ScaleType } from '../../../../scales/constants';
import { LinearScale, OrdinalScale, RasterTimeScale } from '../../../../specs';
import { TextMeasure, withTextMeasure } from '../../../../utils/bbox/canvas_text_bbox_calculator';
import { TextMeasure } from '../../../../utils/bbox/canvas_text_bbox_calculator';
import { addIntervalToTime } from '../../../../utils/chrono/elasticsearch';
import { clamp, Datum } from '../../../../utils/common';
import { Dimensions, horizontalPad, innerPad, pad } from '../../../../utils/dimensions';
import { innerPad, pad } from '../../../../utils/dimensions';
import { Logger } from '../../../../utils/logger';
import { HeatmapStyle, Theme, Visible } from '../../../../utils/themes/theme';
import { PrimitiveValue } from '../../../partition_chart/layout/utils/group_by_rollup';
Expand Down Expand Up @@ -54,29 +53,6 @@ function getValuesInRange(
return values.slice(startIndex, endIndex);
}

function estimatedNonOverlappingTickCount(
chartWidth: number,
style: HeatmapStyle['xAxisLabel'],
sampleLabel: string,
): number {
return withTextMeasure((textMeasure) => {
const { width } = textMeasure(
sampleLabel,
{
fontFamily: style.fontFamily,
fontWeight: style.fontWeight,
fontVariant: style.fontVariant,
fontStyle: style.fontStyle,
},
style.fontSize,
);
const maxTicks = chartWidth / (width + horizontalPad(style.padding));
// Dividing by 2 is a temp fix to make sure {@link ScaleContinuous} won't produce
// to many ticks creating nice rounded tick values
// TODO add support for limiting the number of tick in {@link ScaleContinuous}
return Math.floor(maxTicks / 2);
});
}
/** @internal */
export function shapeViewModel<D extends BaseDatum = Datum>(
textMeasure: TextMeasure,
Expand Down Expand Up @@ -125,7 +101,7 @@ export function shapeViewModel<D extends BaseDatum = Datum>(
const currentGridHeight = elementSizes.grid.height;

// compute the position of each column label
const textXValues = getXTicks(spec, heatmapTheme, elementSizes.grid, xScale, heatmapTable);
const textXValues = getXTicks(spec, heatmapTheme.xAxisLabel, xScale, heatmapTable.xValues);

const { padding } = heatmapTheme.yAxisLabel;

Expand All @@ -136,6 +112,7 @@ export function shapeViewModel<D extends BaseDatum = Datum>(
// position of the Y labels
x: -pad(padding, 'right'),
y: cellHeight / 2 + (yScale(d.value) || 0),
align: 'right',
};
});

Expand Down Expand Up @@ -337,20 +314,23 @@ export function shapeViewModel<D extends BaseDatum = Datum>(
return pickHighlightedArea(area.x, area.y);
};

// vertical lines
const xLines = Array.from({ length: xValues.length + 1 }, (d, i) => ({
x1: elementSizes.grid.left + i * cellWidth,
x2: elementSizes.grid.left + i * cellWidth,
y1: elementSizes.grid.top,
y2: currentGridHeight,
}));
// ordered left-right vertical lines
const xLines = Array.from({ length: xValues.length + 1 }, (d, i) => {
const xAxisExtension = i % elementSizes.xAxisTickCadence === 0 ? 5 : 0;
return {
x1: elementSizes.grid.left + i * cellWidth,
x2: elementSizes.grid.left + i * cellWidth,
y1: elementSizes.grid.top,
y2: currentGridHeight + xAxisExtension,
};
});

// horizontal lines
const yLines = Array.from({ length: elementSizes.visibleNumberOfRows + 1 }, (d, i) => ({
x1: elementSizes.grid.left,
x2: elementSizes.grid.left + elementSizes.grid.width,
y1: i * cellHeight,
y2: i * cellHeight,
y1: elementSizes.grid.top + i * cellHeight,
y2: elementSizes.grid.top + i * cellHeight,
}));

const cells = Object.values(cellMap);
Expand Down Expand Up @@ -434,45 +414,21 @@ export function isRasterTimeScale(scale: RasterTimeScale | OrdinalScale | Linear

function getXTicks(
spec: HeatmapSpec,
style: HeatmapStyle,
grid: Dimensions,
xScale: ScaleBand<string | number>,
{ xValues, xNumericExtent }: HeatmapTable,
style: HeatmapStyle['xAxisLabel'],
scale: ScaleBand<string | number>,
values: NonNullable<PrimitiveValue>[],
): Array<TextBox> {
const getTextValue = (
formatter: HeatmapSpec['xAxisLabelFormatter'],
scaleCallback: (x: string | number) => number | undefined | null,
) => (value: string | number): TextBox => {
const isTimeScale = isRasterTimeScale(spec.xScale);
const isRotated = style.rotation !== 0;
return values.map<TextBox>((value) => {
return {
text: formatter(value),
text: spec.xAxisLabelFormatter(value),
value,
isValue: false,
...style.xAxisLabel,
x: scaleCallback(value) ?? 0,
y: style.xAxisLabel.fontSize / 2 + pad(style.xAxisLabel.padding, 'top'),
};
};
if (isRasterTimeScale(spec.xScale)) {
const sampleLabel = spec.xAxisLabelFormatter(xNumericExtent[0]);
const timeScale = new ScaleContinuous(
{
type: ScaleType.Time,
domain: xNumericExtent,
range: [0, grid.width],
nice: false,
},
{
desiredTickCount: estimatedNonOverlappingTickCount(grid.width, style.xAxisLabel, sampleLabel),
timeZone: spec.timeZone,
},
);
return timeScale.ticks().map<TextBox>(getTextValue(spec.xAxisLabelFormatter, (x) => timeScale.scale(x)));
}

return xValues.map<TextBox>((textBox: string | number) => {
return {
...getTextValue(spec.xAxisLabelFormatter, xScale)(textBox),
x: (xScale(textBox) || 0) + xScale.bandwidth() / 2,
...style,
y: style.fontSize / 2 + pad(style.padding, 'top'),
x: (scale(value) ?? 0) + (isTimeScale ? 0 : scale.bandwidth() / 2),
align: isRotated ? 'right' : isTimeScale ? 'left' : 'center',
};
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
* Side Public License, v 1.
*/

import { Color, Colors } from '../../../../common/colors';
import { Font } from '../../../../common/text_utils';
import { Color } from '../../../../common/colors';
import { clearCanvas, renderLayers, withContext } from '../../../../renderers/canvas';
import { radToDeg } from '../../../../utils/common';
import { horizontalPad } from '../../../../utils/dimensions';
import { renderMultiLine } from '../../../xy_chart/renderer/canvas/primitives/line';
import { renderRect } from '../../../xy_chart/renderer/canvas/primitives/rect';
import { renderText, wrapLines } from '../../../xy_chart/renderer/canvas/primitives/text';
import { renderText, TextFont, wrapLines } from '../../../xy_chart/renderer/canvas/primitives/text';
import { ShapeViewModel } from '../../layout/types/viewmodel_types';
import { ChartElementSizes } from '../../state/selectors/compute_chart_dimensions';

Expand All @@ -37,6 +38,7 @@ export function renderCanvas2d(
// text rendering must be y-flipped, which is a bit easier this way
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.lineCap = 'square';
// ctx.translate(chartCenter.x, chartCenter.y);
// this applies the mathematical x/y conversion (+y is North) which is easier when developing geometry
// functions - also, all renderers have flexibility (eg. SVG scale) and WebGL NDC is also +y up
Expand Down Expand Up @@ -117,34 +119,23 @@ export function renderCanvas2d(
// render text on Y axis
theme.yAxisLabel.visible &&
withContext(ctx, () => {
// the text is right aligned so the canvas needs to be aligned to the right of the Y axis box
ctx.translate(elementSizes.yAxis.left + elementSizes.yAxis.width, elementSizes.yAxis.top);
filteredYValues.forEach((yValue) => {
const font: Font = {
fontFamily: theme.yAxisLabel.fontFamily,
fontStyle: theme.yAxisLabel.fontStyle ? theme.yAxisLabel.fontStyle : 'normal',
fontVariant: 'normal',
fontWeight: 'normal',
textColor: Colors.Black.keyword,
};
const { padding } = theme.yAxisLabel;
const horizontalPadding =
typeof padding === 'number' ? padding * 2 : (padding.left ?? 0) + (padding.right ?? 0);
const [resultText] = wrapLines(
const font: TextFont = { ...theme.yAxisLabel, baseline: 'middle' /* fixed */, align: 'right' /* fixed */ };
const { padding } = theme.yAxisLabel;
const horizontalPadding = horizontalPad(padding);
filteredYValues.forEach(({ x, y, text }) => {
const textLines = wrapLines(
ctx,
yValue.text,
text,
font,
theme.yAxisLabel.fontSize,
heatmapViewModel.gridOrigin.x - horizontalPadding,
16,
theme.yAxisLabel.fontSize,
{ shouldAddEllipsis: true, wrapAtWord: false },
).lines;
renderText(
ctx,
{ x: yValue.x, y: yValue.y },
resultText,
// the alignment for y axis labels is fixed to the right
{ ...theme.yAxisLabel, align: 'right' },
);
// TODO improve the `wrapLines` code to handle results with short width
renderText(ctx, { x, y }, textLines.length > 0 ? textLines[0] : '…', font);
});
}),

Expand All @@ -153,9 +144,28 @@ export function renderCanvas2d(
theme.xAxisLabel.visible &&
withContext(ctx, () => {
ctx.translate(elementSizes.xAxis.left, elementSizes.xAxis.top);
heatmapViewModel.xValues.forEach((xValue) =>
renderText(ctx, { x: xValue.x, y: xValue.y }, xValue.text, theme.xAxisLabel),
);
heatmapViewModel.xValues
.filter((_, i) => i % elementSizes.xAxisTickCadence === 0)
.forEach(({ x, y, text, align }) => {
const textLines = wrapLines(
ctx,
text,
theme.xAxisLabel,
theme.xAxisLabel.fontSize,
// TODO wrap into multilines
Infinity,
16,
{ shouldAddEllipsis: true, wrapAtWord: false },
).lines;
renderText(
ctx,
{ x, y },
textLines.length > 0 ? textLines[0] : '…',
{ ...theme.xAxisLabel, baseline: 'middle', align },
// negative rotation due to the canvas rotation direction
radToDeg(-elementSizes.xLabelRotation),
);
});
}),

() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ const DEFAULT_PROPS: ReactiveChartStateProps = {
fullHeatmapHeight: 0,
rowHeight: 0,
visibleNumberOfRows: 0,
xAxisTickCadence: 1,
xLabelRotation: 0,
},
debug: false,
};
Expand Down
Loading