[Lens] Fix chart padding on reference lines/annotations icon on the left side (#149573)

## Summary

Fix #149414 

Fixed margin computation for annotations icons on the left side. Added
unit tests.

<img width="1238" alt="Screenshot 2023-01-26 at 10 12 10"
src="https://user-images.githubusercontent.com/924948/214798802-6d176cf2-1bee-4f1e-bcaf-40bd970d857d.png">

### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

Co-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>
This commit is contained in:
Marco Liberati 2023-01-27 10:35:42 +01:00 committed by GitHub
parent 83dd5f84fc
commit c4a0ed2c19
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 147 additions and 1 deletions

View file

@ -0,0 +1,107 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { AxisConfiguration, mapVerticalToHorizontalPlacement } from '../../helpers';
function createCombinationsFrom(strings: string): string[] {
return strings.split('').flatMap((str, i, allStrings) => [
str,
...allStrings.slice(i + 1).flatMap((otherStr, _, rest) => {
return rest.length < 2
? `${str}${otherStr}`
: createCombinationsFrom(rest.join('')).map((comb) => `${str}${comb}`);
}),
]);
}
const DEFAULT_PADDING = 20;
const stringToPos = { l: 'left', r: 'right', b: 'bottom', t: 'top' } as const;
const stringToAxesId = { l: 'yLeft', r: 'yRight', x: 'x' } as const;
const posToId = { left: 'yLeft', right: 'yRight', bottom: 'x' } as const;
export type StringPos = keyof typeof stringToPos;
export type PosType = typeof stringToPos[StringPos];
export type StringId = keyof typeof stringToAxesId;
export type AxisTypeId = typeof stringToAxesId[StringId];
function buildPositionObject<T extends unknown>(
posString: string,
value: T
): Partial<Record<PosType, T>> {
const obj: Partial<Record<PosType, T>> = {};
for (const str of posString.split('') as unknown as StringPos[]) {
obj[stringToPos[str]] = value;
}
return obj;
}
function buildAxesIdObject(idsString: string): Partial<Record<AxisTypeId, boolean>> {
const obj: Partial<Record<AxisTypeId, boolean>> = {};
for (const str of idsString.split('') as unknown as StringId[]) {
obj[stringToAxesId[str]] = true;
}
return obj;
}
export function computeInputCombinations() {
return [{ referencePaddings: 'lrbt', labels: 'lrx', titles: 'lrx', axes: 'lr' }].flatMap(
({ referencePaddings, labels, titles, axes }) => {
// create all combinations of reference line paddings
// l, r, ..., lr, lb, lt, lrb, ...
const paddings = Array.from(new Set(createCombinationsFrom(referencePaddings)));
const axisLabels = Array.from(new Set(createCombinationsFrom(labels)));
const axisTitles = Array.from(new Set(createCombinationsFrom(titles)));
const axesMap = Array.from(new Set(createCombinationsFrom(axes)));
const allCombinations = [];
for (const p of paddings) {
const pObj = buildPositionObject(p, DEFAULT_PADDING);
for (const l of axisLabels) {
const lObj = buildAxesIdObject(l);
for (const t of axisTitles) {
const tObj = buildAxesIdObject(t);
for (const a of axesMap) {
const aObj = buildPositionObject(a, {} as AxisConfiguration);
// Add undefined values for missing axes
for (const emptyAxis of ['left', 'right'] as const) {
if (!(emptyAxis in aObj)) {
aObj[emptyAxis] = undefined;
}
}
for (const horizontal of [false, true]) {
const result: Partial<Record<PosType, number>> = {};
for (const pos of Object.keys(pObj) as PosType[]) {
const id = pos in posToId ? posToId[pos as Exclude<PosType, 'top'>] : null;
const isHorizontalAndLeftOrRight = pos in aObj && (horizontal || !aObj[pos]);
const isTop = !id;
const hasNoLabelAndTitle = id && !lObj[id] && !tObj[id];
if (isHorizontalAndLeftOrRight || isTop || hasNoLabelAndTitle) {
result[horizontal ? mapVerticalToHorizontalPlacement(pos) : pos] = pObj[pos];
}
}
allCombinations.push({
referencePadding: pObj,
labels: lObj,
titles: tObj,
axesMap: aObj,
isHorizontal: horizontal,
id: `[Paddings: ${p}][Labels: ${l}][Titles: ${t}][Axes: ${a}]${
horizontal ? '[isHorizontal]' : ''
}`,
result,
});
}
}
}
}
}
return allCombinations;
}
);
}

View file

@ -0,0 +1,39 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { AxisTypeId, computeInputCombinations, PosType } from './_mocks';
import { computeChartMargins } from './utils';
import { AxisConfiguration } from '../../helpers';
describe('reference lines helpers', () => {
describe('computeChartMargins', () => {
test.each(computeInputCombinations())(
'$id test',
// @ts-expect-error types are not inferred correctly
({
referencePadding,
labels,
titles,
axesMap,
isHorizontal,
result,
}: {
referencePadding: Partial<Record<PosType, number>>;
labels: Partial<Record<AxisTypeId, boolean>>;
titles: Partial<Record<AxisTypeId, boolean>>;
axesMap: Record<PosType, AxisConfiguration | undefined>;
isHorizontal: boolean;
result: Partial<Record<PosType, number>>;
}) => {
expect(
computeChartMargins(referencePadding, labels, titles, axesMap, isHorizontal)
).toEqual(result);
}
);
});
});

View file

@ -210,7 +210,7 @@ export const computeChartMargins = (
}
if (
referenceLinePaddings.left &&
(isHorizontal || (!labelVisibility?.yLeft && !titleVisibility?.yLeft))
(isHorizontal || !axesMap.left || (!labelVisibility?.yLeft && !titleVisibility?.yLeft))
) {
const placement = isHorizontal ? mapVerticalToHorizontalPlacement('left') : 'left';
result[placement] = referenceLinePaddings.left;