[Lens] Provide dimension title fallback in case of empty content (#154368)

## Summary

Fixes #151271 

This PR is a proposal to provide a fallback title in case the user
decides to provide an empty value for dimensions title.

<img width="1230" alt="Screenshot 2023-06-14 at 12 05 46"
src="521d00db-4c1e-4aff-a142-086fa3456884">
<img width="1238" alt="Screenshot 2023-06-14 at 12 05 35"
src="9a272fac-02e6-4585-81d1-5e0b2686eaf1">


Note that this applies only to the presentation of the dimension button,
but the title remains as empty space in the configuration itself.
Tests added with testing-library.

### 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)
This commit is contained in:
Marco Liberati 2023-06-19 10:04:35 +02:00 committed by GitHub
parent 83abc6e3c0
commit c8e8439554
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 165 additions and 67 deletions

View file

@ -0,0 +1,13 @@
/*
* 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 { i18n } from '@kbn/i18n';
export const emptyTitleText = i18n.translate('visualizationUiComponents.emptyTitle', {
defaultMessage: '[Untitled]',
});

View file

@ -0,0 +1,50 @@
/*
* 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 { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { DimensionButton, DimensionButtonProps } from './dimension_button';
describe('DimensionButton', () => {
function getDefaultProps(): Omit<DimensionButtonProps, 'label' | 'children'> {
return {
groupLabel: 'myGroup',
onClick: jest.fn(),
onRemoveClick: jest.fn(),
accessorConfig: { columnId: '1' },
message: undefined,
};
}
it('should fallback to the empty title if the dimension label is made of an empty string', () => {
render(
<DimensionButton {...getDefaultProps()} label="">
<div />
</DimensionButton>
);
expect(screen.getByTitle('Edit [Untitled] configuration')).toBeInTheDocument();
});
it('should fallback to the empty title if the dimension label is made up of whitespaces only', () => {
render(
<DimensionButton {...getDefaultProps()} label=" ">
<div />
</DimensionButton>
);
expect(screen.getByTitle('Edit [Untitled] configuration')).toBeInTheDocument();
});
it('should not fallback to the empty title if the dimension label has also valid chars beside whitespaces', () => {
render(
<DimensionButton {...getDefaultProps()} label="aaa ">
<div />
</DimensionButton>
);
expect(screen.getByTitle('Edit aaa configuration')).toBeInTheDocument();
});
});

View file

@ -21,13 +21,27 @@ import { euiThemeVars } from '@kbn/ui-theme';
import { DimensionButtonIcon } from './dimension_button_icon';
import { PaletteIndicator } from './palette_indicator';
import type { AccessorConfig, Message } from './types';
import { emptyTitleText } from './constants';
const triggerLinkA11yText = (label: string) =>
i18n.translate('visualizationUiComponents.dimensionButton.editConfig', {
defaultMessage: 'Edit {label} configuration',
values: { label },
values: {
label: label.trim().length ? label : emptyTitleText,
},
});
export interface DimensionButtonProps {
className?: string;
groupLabel: string;
children: React.ReactElement;
onClick: (id: string) => void;
onRemoveClick: (id: string) => void;
accessorConfig: AccessorConfig;
label: string;
message?: Message;
}
export function DimensionButton({
groupLabel,
children,
@ -37,16 +51,7 @@ export function DimensionButton({
label,
message,
...otherProps // from Drag&Drop integration
}: {
className?: string;
groupLabel: string;
children: React.ReactElement;
onClick: (id: string) => void;
onRemoveClick: (id: string) => void;
accessorConfig: AccessorConfig;
label: string;
message?: Message;
}) {
}: DimensionButtonProps) {
return (
<div
{...otherProps}

View file

@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
export * from './constants';
export * from './dimension_button';
export * from './empty_button';

View file

@ -0,0 +1,29 @@
/*
* 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 { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { DimensionTrigger } from './trigger';
describe('DimensionTrigger', () => {
it('should fallback to the empty title if the dimension label is made of an empty string', () => {
render(<DimensionTrigger id="dimensionEmpty" label="" />);
expect(screen.queryByText('[Untitled]')).toBeInTheDocument();
});
it('should fallback to the empty title if the dimension label is made up of whitespaces only', () => {
render(<DimensionTrigger id="dimensionEmpty" label=" " />);
expect(screen.queryByText('[Untitled]')).toBeInTheDocument();
});
it('should not fallback to the empty title if the dimension label has also valid chars beside whitespaces', () => {
render(<DimensionTrigger id="dimensionEmpty" label="aaa " />);
expect(screen.queryByText('aaa')).toBeInTheDocument();
});
});

View file

@ -9,9 +9,10 @@
import { EuiText, EuiFlexItem } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import React from 'react';
import { EuiTextProps } from '@elastic/eui/src/components/text/text';
import type { EuiTextProps } from '@elastic/eui/src/components/text/text';
import { css } from '@emotion/react';
import { euiThemeVars } from '@kbn/ui-theme';
import { emptyTitleText } from './constants';
export const defaultDimensionTriggerTooltip = (
<p>
@ -36,6 +37,10 @@ export const DimensionTrigger = ({
color?: EuiTextProps['color'];
dataTestSubj?: string;
}) => {
let safeLabel = label;
if (typeof label === 'string') {
safeLabel = label?.trim().length > 0 ? label : emptyTitleText;
}
return (
<EuiText
size="s"
@ -61,7 +66,7 @@ export const DimensionTrigger = ({
}
`}
>
{label}
{safeLabel}
</span>
</span>
</EuiFlexItem>

View file

@ -32,6 +32,7 @@ export {
EmptyDimensionButton,
LineStyleSettings,
TextDecorationSetting,
emptyTitleText,
} from './components';
export { isFieldLensCompatible } from './util';

View file

@ -71,7 +71,7 @@ import {
cloneLayer,
getNotifiableFeatures,
} from './utils';
import { isDraggedDataViewField } from '../../utils';
import { getUniqueLabelGenerator, isDraggedDataViewField } from '../../utils';
import { hasField, normalizeOperationDataType } from './pure_utils';
import { LayerPanel } from './layerpanel';
import {
@ -499,28 +499,15 @@ export function getFormBasedDatasource({
uniqueLabels(state: FormBasedPrivateState) {
const layers = state.layers;
const columnLabelMap = {} as Record<string, string>;
const counts = {} as Record<string, number>;
const makeUnique = (label: string) => {
let uniqueLabel = label;
const uniqueLabelGenerator = getUniqueLabelGenerator();
while (counts[uniqueLabel] >= 0) {
const num = ++counts[uniqueLabel];
uniqueLabel = i18n.translate('xpack.lens.indexPattern.uniqueLabel', {
defaultMessage: '{label} [{num}]',
values: { label, num },
});
}
counts[uniqueLabel] = 0;
return uniqueLabel;
};
Object.values(layers).forEach((layer) => {
if (!layer.columns) {
return;
}
Object.entries(layer.columns).forEach(([columnId, column]) => {
columnLabelMap[columnId] = makeUnique(column.label);
columnLabelMap[columnId] = uniqueLabelGenerator(column.label);
});
});

View file

@ -43,6 +43,7 @@ import type {
import { FieldSelect } from './field_select';
import type { Datasource, IndexPatternMap } from '../../types';
import { LayerPanel } from './layerpanel';
import { getUniqueLabelGenerator } from '../../utils';
function getLayerReferenceName(layerId: string) {
return `textBasedLanguages-datasource-layer-${layerId}`;
@ -509,28 +510,14 @@ export function getTextBasedDatasource({
uniqueLabels(state: TextBasedPrivateState) {
const layers = state.layers;
const columnLabelMap = {} as Record<string, string>;
const counts = {} as Record<string, number>;
const uniqueLabelGenerator = getUniqueLabelGenerator();
const makeUnique = (label: string) => {
let uniqueLabel = label;
while (counts[uniqueLabel] >= 0) {
const num = ++counts[uniqueLabel];
uniqueLabel = i18n.translate('xpack.lens.indexPattern.uniqueLabel', {
defaultMessage: '{label} [{num}]',
values: { label, num },
});
}
counts[uniqueLabel] = 0;
return uniqueLabel;
};
Object.values(layers).forEach((layer) => {
if (!layer.columns) {
return;
}
Object.values(layer.columns).forEach((column) => {
columnLabelMap[column.columnId] = makeUnique(column.fieldName);
columnLabelMap[column.columnId] = uniqueLabelGenerator(column.fieldName);
});
});

View file

@ -7,7 +7,7 @@
import { createDatatableUtilitiesMock } from '@kbn/data-plugin/common/mocks';
import { Datatable } from '@kbn/expressions-plugin/public';
import { inferTimeField, renewIDs } from './utils';
import { getUniqueLabelGenerator, inferTimeField, renewIDs } from './utils';
const datatableUtilities = createDatatableUtilitiesMock();
@ -157,4 +157,19 @@ describe('utils', () => {
`);
});
});
describe('getUniqueLabelGenerator', () => {
it('should handle empty labels', () => {
expect(getUniqueLabelGenerator()(' ')).toBe('[Untitled]');
});
it('should add a counter for multiple hits of the same label', () => {
const labelGenerator = getUniqueLabelGenerator();
expect(['myLabel', 'myLabel'].map(labelGenerator)).toEqual(['myLabel', 'myLabel [1]']);
});
it('should add a counter for multiple empty labels', () => {
const labelGenerator = getUniqueLabelGenerator();
expect([' ', ' '].map(labelGenerator)).toEqual(['[Untitled]', '[Untitled] [1]']);
});
});
});

View file

@ -19,6 +19,7 @@ import {
ClickTriggerEvent,
MultiClickTriggerEvent,
} from '@kbn/charts-plugin/public';
import { emptyTitleText } from '@kbn/visualization-ui-components/public';
import { RequestAdapter } from '@kbn/inspector-plugin/common';
import { ISearchStart } from '@kbn/data-plugin/public';
import type { DraggingIdentifier } from '@kbn/dom-drag-drop';
@ -363,6 +364,28 @@ export const getSearchWarningMessages = (
return [...warningsMap.values()].flat();
};
function getSafeLabel(label: string) {
return label.trim().length ? label : emptyTitleText;
}
export function getUniqueLabelGenerator() {
const counts = {} as Record<string, number>;
return function makeUnique(label: string) {
let uniqueLabel = getSafeLabel(label);
while (counts[uniqueLabel] >= 0) {
const num = ++counts[uniqueLabel];
uniqueLabel = i18n.translate('xpack.lens.uniqueLabel', {
defaultMessage: '{label} [{num}]',
values: { label: getSafeLabel(label), num },
});
}
counts[uniqueLabel] = 0;
return uniqueLabel;
};
}
export function nonNullable<T>(v: T): v is NonNullable<T> {
return v != null;
}

View file

@ -18,7 +18,7 @@ import {
} from '@kbn/event-annotation-plugin/common';
import { IconChartBarAnnotations } from '@kbn/chart-icons';
import { LayerTypes } from '@kbn/expression-xy-plugin/public';
import { isDraggedDataViewField } from '../../../utils';
import { getUniqueLabelGenerator, isDraggedDataViewField } from '../../../utils';
import type { FramePublicAPI, Visualization } from '../../../types';
import { isHorizontalChart } from '../state_helpers';
import type { XYState, XYDataLayerConfig, XYAnnotationLayerConfig, XYLayerConfig } from '../types';
@ -454,29 +454,15 @@ export const getAnnotationsConfiguration = ({
export const getUniqueLabels = (layers: XYLayerConfig[]) => {
const annotationLayers = getAnnotationsLayers(layers);
const columnLabelMap = {} as Record<string, string>;
const counts = {} as Record<string, number>;
const makeUnique = (label: string) => {
let uniqueLabel = label;
while (counts[uniqueLabel] >= 0) {
const num = ++counts[uniqueLabel];
uniqueLabel = i18n.translate('xpack.lens.uniqueLabel', {
defaultMessage: '{label} [{num}]',
values: { label, num },
});
}
counts[uniqueLabel] = 0;
return uniqueLabel;
};
const uniqueLabelGenerator = getUniqueLabelGenerator();
annotationLayers.forEach((layer) => {
if (!layer.annotations) {
return;
}
layer.annotations.forEach((l) => {
columnLabelMap[l.id] = makeUnique(l.label);
columnLabelMap[l.id] = uniqueLabelGenerator(l.label);
});
});
return columnLabelMap;

View file

@ -20249,7 +20249,6 @@
"xpack.lens.indexPattern.timeShiftMultipleWarning": "{label} utilise un décalage temporel de {columnTimeShift} qui n'est pas un multiple de l'intervalle de l'histogramme des dates de {interval}. Pour éviter une non-correspondance des données, utilisez un multiple de {interval} comme décalage temporel.",
"xpack.lens.indexPattern.timeShiftSmallWarning": "{label} utilise un décalage temporel de {columnTimeShift} qui est inférieur à l'intervalle de l'histogramme des dates de {interval}. Pour éviter une non-correspondance des données, utilisez un multiple de {interval} comme décalage temporel.",
"xpack.lens.indexPattern.tsdbRollupWarning": "{label} utilise une fonction qui n'est pas prise en charge par les données cumulées. Sélectionnez une autre fonction ou modifiez la plage temporelle.",
"xpack.lens.indexPattern.uniqueLabel": "{label} [{num}]",
"xpack.lens.indexPattern.valueCountOf": "Nombre de {name}",
"xpack.lens.indexPatternSuggestion.removeLayerLabel": "Afficher uniquement {indexPatternTitle}",
"xpack.lens.indexPatternSuggestion.removeLayerPositionLabel": "Afficher uniquement le calque {layerNumber}",

View file

@ -20248,7 +20248,6 @@
"xpack.lens.indexPattern.timeShiftMultipleWarning": "{label}は{columnTimeShift}の時間シフトを使用しています。これは{interval}の日付ヒストグラム間隔の乗数ではありません。不一致のデータを防止するには、時間シフトとして{interval}を使用します。",
"xpack.lens.indexPattern.timeShiftSmallWarning": "{label}は{columnTimeShift}の時間シフトを使用しています。これは{interval}の日付ヒストグラム間隔よりも小さいです。不一致のデータを防止するには、時間シフトとして{interval}を使用します。",
"xpack.lens.indexPattern.tsdbRollupWarning": "{label}は、ロールアップされたデータによってサポートされていない関数を使用しています。別の関数を選択するか、時間範囲を選択してください。",
"xpack.lens.indexPattern.uniqueLabel": "{label} [{num}]",
"xpack.lens.indexPattern.valueCountOf": "{name}のカウント",
"xpack.lens.indexPatternSuggestion.removeLayerLabel": "{indexPatternTitle}のみを表示",
"xpack.lens.indexPatternSuggestion.removeLayerPositionLabel": "レイヤー{layerNumber}のみを表示",

View file

@ -20248,7 +20248,6 @@
"xpack.lens.indexPattern.timeShiftMultipleWarning": "{label} 使用的时间偏移 {columnTimeShift} 不是 Date Histogram 时间间隔 {interval} 的倍数。要防止数据不匹配,请使用 {interval} 的倍数作为时间偏移。",
"xpack.lens.indexPattern.timeShiftSmallWarning": "{label} 使用的时间偏移 {columnTimeShift} 小于 Date Histogram 时间间隔 {interval}。要防止数据不匹配,请使用 {interval} 的倍数作为时间偏移。",
"xpack.lens.indexPattern.tsdbRollupWarning": "{label} 使用的函数不受汇总/打包数据支持。请选择其他函数,或更改时间范围。",
"xpack.lens.indexPattern.uniqueLabel": "{label} [{num}]",
"xpack.lens.indexPattern.valueCountOf": "{name} 的计数",
"xpack.lens.indexPatternSuggestion.removeLayerLabel": "仅显示 {indexPatternTitle}",
"xpack.lens.indexPatternSuggestion.removeLayerPositionLabel": "仅显示图层 {layerNumber}",