[Lens] Duration formatter follow ups (#162871)

## Summary

Fix #162453 

This PR address few design feedback for the formatter area and adds
supports for the duration formatter within the TSDB -> Lens transition
feature.

List of features:
* new shared component for "synced prepend" in EUI form controls
`Prepend` + `PrependWidthProvider` 
* Integrate design feedback within the dimension editor 💄 
  * sync prepend width
  * `Human readable` -> `Friendly` relabel
* add support for duration formatter for the TSVB to Lens feature
  * Fix formatter bug for `Count` operation 🐛 
  * Add tests  
  * Add external Numeral link for Custom formatter  
  * Revisit UI for compact switch control 💄 
  * `From` -> `Convert` relabel for duration formatter 💄 
* Hide `Compact` and `Decimals` controls for `Friendly (approximate)`
output selection

<img width="331" alt="Screenshot 2023-08-01 at 10 53 46"
src="42ec154d-3a9d-410d-9949-f137a86214b6">
<img width="335" alt="Screenshot 2023-08-01 at 10 53 33"
src="9ffb8b12-fb01-47a8-9647-d498bb8bad86">
<img width="339" alt="Screenshot 2023-08-01 at 10 53 24"
src="c6825a32-f59f-4e8e-ad6d-1a24dfafd23d">
<img width="337" alt="Screenshot 2023-08-01 at 10 53 16"
src="0104aa92-03cb-47ca-ac64-aa0397c42321">

### 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-08-02 11:30:22 +02:00 committed by GitHub
parent 490c34c053
commit 10c09d140a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 313 additions and 165 deletions

View file

@ -104,7 +104,7 @@ export const inputFormats = {
M: 'months', M: 'months',
Y: 'years', Y: 'years',
}; };
type InputFormat = keyof typeof inputFormats; export type InputFormat = keyof typeof inputFormats;
export const outputFormats = { export const outputFormats = {
humanize: 'humanize', humanize: 'humanize',
@ -117,14 +117,16 @@ export const outputFormats = {
M: 'asMonths', M: 'asMonths',
Y: 'asYears', Y: 'asYears',
}; };
type OutputFormat = keyof typeof outputFormats; export type OutputFormat = keyof typeof outputFormats;
export const getDurationParams = (format: string) => { export const getDurationParams = (
format: string
): { from: InputFormat; to: OutputFormat; decimals: string } => {
const [from, to, decimals] = format.split(','); const [from, to, decimals] = format.split(',');
return { return {
from, from: from as InputFormat,
to, to: to as OutputFormat,
decimals, decimals,
}; };
}; };

View file

@ -12,11 +12,20 @@ import {
stubLogstashDataView, stubLogstashDataView,
} from '@kbn/data-views-plugin/common/data_view.stub'; } from '@kbn/data-views-plugin/common/data_view.stub';
import { stubLogstashFieldSpecMap } from '@kbn/data-views-plugin/common/field.stub'; import { stubLogstashFieldSpecMap } from '@kbn/data-views-plugin/common/field.stub';
import {
durationInputOptions,
durationOutputOptions,
InputFormat,
inputFormats,
OutputFormat,
outputFormats,
} from '../../../application/components/lib/durations';
import { MaxColumn as BaseMaxColumn } from '@kbn/visualizations-plugin/common'; import { MaxColumn as BaseMaxColumn } from '@kbn/visualizations-plugin/common';
import { Metric } from '../../../../common/types'; import { Metric } from '../../../../common/types';
import { createSeries } from '../__mocks__'; import { createSeries } from '../__mocks__';
import { createColumn, excludeMetaFromColumn, getFormat, isColumnWithMeta } from './column'; import { createColumn, excludeMetaFromColumn, getFormat, isColumnWithMeta } from './column';
import { MaxColumn } from './types'; import { MaxColumn } from './types';
import { DATA_FORMATTERS } from '../../../../common/enums';
describe('getFormat', () => { describe('getFormat', () => {
const dataViewWithoutSupportedFormatsFields = createStubDataView({ const dataViewWithoutSupportedFormatsFields = createStubDataView({
@ -73,6 +82,43 @@ describe('getFormat', () => {
}, },
}); });
}); });
test.each(
durationInputOptions.flatMap(({ value: fromValue }) =>
durationOutputOptions.flatMap(({ value: toValue }) =>
['1', '2', '3', ''].map((decimal) => ({ fromValue, toValue, decimal }))
)
)
)(
'should return a duration formatter for the format "$fromValue,$toValue,$decimal"',
({ fromValue, toValue, decimal }) => {
expect(getFormat(createSeries({ formatter: `${fromValue},${toValue},${decimal}` }))).toEqual({
format: {
id: DATA_FORMATTERS.DURATION,
params: {
fromUnit: inputFormats[fromValue as InputFormat],
toUnit: outputFormats[toValue as OutputFormat],
decimals: decimal ? parseInt(decimal, 10) : 2,
suffix: '',
},
},
});
}
);
test('should return a duration formatter with the suffix if detected', () => {
expect(getFormat(createSeries({ formatter: `Y,M,1`, value_template: '{{value}}/d' }))).toEqual({
format: {
id: DATA_FORMATTERS.DURATION,
params: {
fromUnit: 'years',
toUnit: 'asMonths',
decimals: 1,
suffix: '/d',
},
},
});
});
}); });
describe('createColumn', () => { describe('createColumn', () => {

View file

@ -15,6 +15,12 @@ import {
FormatParams, FormatParams,
} from '@kbn/visualizations-plugin/common/convert_to_lens'; } from '@kbn/visualizations-plugin/common/convert_to_lens';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import {
getDurationParams,
inputFormats,
isDuration,
outputFormats,
} from '../../../application/components/lib/durations';
import type { Metric, Series } from '../../../../common/types'; import type { Metric, Series } from '../../../../common/types';
import { DATA_FORMATTERS } from '../../../../common/enums'; import { DATA_FORMATTERS } from '../../../../common/enums';
import { getTimeScale } from '../metrics'; import { getTimeScale } from '../metrics';
@ -30,7 +36,8 @@ interface ExtraColumnFields {
isAssignTimeScale?: boolean; isAssignTimeScale?: boolean;
} }
const isSupportedFormat = (format: string) => ['bytes', 'number', 'percent'].includes(format); const isSupportedFormat = (format: string) =>
['bytes', 'number', 'percent'].includes(format) || isDuration(format);
export const getFormat = (series: Pick<Series, 'formatter' | 'value_template'>): FormatParams => { export const getFormat = (series: Pick<Series, 'formatter' | 'value_template'>): FormatParams => {
let suffix; let suffix;
@ -50,6 +57,21 @@ export const getFormat = (series: Pick<Series, 'formatter' | 'value_template'>):
}; };
} }
if (isDuration(series.formatter)) {
const { from, to, decimals } = getDurationParams(series.formatter);
return {
format: {
id: DATA_FORMATTERS.DURATION,
params: {
fromUnit: inputFormats[from] || from,
toUnit: outputFormats[to] || to,
decimals: decimals ? parseInt(decimals, 10) : 2,
suffix,
},
},
};
}
return { format: { id: series.formatter, ...(suffix && { params: { suffix, decimals: 2 } }) } }; return { format: { id: series.formatter, ...(suffix && { params: { suffix, decimals: 2 } }) } };
}; };

View file

@ -132,6 +132,8 @@ export const convertMetricAggregationColumnWithoutSpecialParams = (
operationType: aggregation.name, operationType: aggregation.name,
sourceField, sourceField,
...createColumn(series, metric, field, additionalArgs), ...createColumn(series, metric, field, additionalArgs),
// dataType has to be number in Lens to inherit the formatter
...(sourceField === 'document' ? { dataType: 'number' } : {}),
params: { ...getFormat(series) }, params: { ...getFormat(series) },
} as MetricAggregationColumnWithoutSpecialParams; } as MetricAggregationColumnWithoutSpecialParams;
}; };

View file

@ -43,6 +43,8 @@ export interface NumberValueFormat {
params?: { params?: {
decimals: number; decimals: number;
suffix?: string; suffix?: string;
fromUnit?: string;
toUnit?: string;
}; };
} }

View file

@ -1224,7 +1224,11 @@ export function DimensionEditor(props: DimensionEditorProps) {
!isFullscreen && !isFullscreen &&
selectedColumn && selectedColumn &&
(selectedColumn.dataType === 'number' || selectedColumn.operationType === 'range') ? ( (selectedColumn.dataType === 'number' || selectedColumn.operationType === 'range') ? (
<FormatSelector selectedColumn={selectedColumn} onChange={onFormatChange} /> <FormatSelector
selectedColumn={selectedColumn}
onChange={onFormatChange}
docLinks={props.core.docLinks}
/>
) : null} ) : null}
</> </>
</div> </div>

View file

@ -13,7 +13,7 @@ import { GenericIndexPatternColumn } from '../../..';
import { LensAppServices } from '../../../app_plugin/types'; import { LensAppServices } from '../../../app_plugin/types';
import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public';
import { I18nProvider } from '@kbn/i18n-react'; import { I18nProvider } from '@kbn/i18n-react';
import { coreMock } from '@kbn/core/public/mocks'; import { coreMock, docLinksServiceMock } from '@kbn/core/public/mocks';
import { EuiComboBox, EuiFieldNumber } from '@elastic/eui'; import { EuiComboBox, EuiFieldNumber } from '@elastic/eui';
jest.mock('lodash', () => { jest.mock('lodash', () => {
@ -39,6 +39,7 @@ const bytesColumn: GenericIndexPatternColumn = {
const getDefaultProps = () => ({ const getDefaultProps = () => ({
onChange: jest.fn(), onChange: jest.fn(),
selectedColumn: bytesColumn, selectedColumn: bytesColumn,
docLinks: docLinksServiceMock.createStartContract(),
}); });
function createMockServices(): LensAppServices { function createMockServices(): LensAppServices {
@ -122,7 +123,7 @@ describe('FormatSelector', () => {
}); });
describe('Duration', () => { describe('Duration', () => {
it('disables the decimals and compact controls for humanize approximate output', () => { it('hides the decimals and compact controls for humanize approximate output', () => {
const originalProps = getDefaultProps(); const originalProps = getDefaultProps();
let component = mountWithServices( let component = mountWithServices(
<FormatSelector <FormatSelector
@ -136,18 +137,12 @@ describe('FormatSelector', () => {
/> />
); );
expect( expect(component.exists('[data-test-subj="indexPattern-dimension-formatDecimals"]')).toBe(
component false
.find('[data-test-subj="indexPattern-dimension-formatDecimals"]') );
.last() expect(component.exists('[data-test-subj="lns-indexpattern-dimension-formatCompact"]')).toBe(
.prop('disabled') false
).toBe(true); );
expect(
component
.find('[data-test-subj="lns-indexpattern-dimension-formatCompact"]')
.first()
.prop('disabled')
).toBe(true);
act(() => { act(() => {
component component
@ -157,18 +152,12 @@ describe('FormatSelector', () => {
}); });
component = component.update(); component = component.update();
expect( expect(component.exists('[data-test-subj="indexPattern-dimension-formatDecimals"]')).toBe(
component true
.find('[data-test-subj="indexPattern-dimension-formatDecimals"]') );
.last() expect(component.exists('[data-test-subj="lns-indexpattern-dimension-formatCompact"]')).toBe(
.prop('disabled') true
).toBe(false); );
expect(
component
.find('[data-test-subj="lns-indexpattern-dimension-formatCompact"]')
.first()
.prop('disabled')
).toBe(false);
}); });
}); });
}); });

View file

@ -14,21 +14,25 @@ import {
EuiRange, EuiRange,
EuiFieldText, EuiFieldText,
EuiSwitch, EuiSwitch,
EuiCode, EuiFormLabel,
EuiLink,
useEuiTheme,
} from '@elastic/eui'; } from '@elastic/eui';
import { useDebouncedValue, TooltipWrapper } from '@kbn/visualization-ui-components'; import { useDebouncedValue } from '@kbn/visualization-ui-components';
import { useKibana } from '@kbn/kibana-react-plugin/public'; import { useKibana } from '@kbn/kibana-react-plugin/public';
import { import {
DEFAULT_DURATION_INPUT_FORMAT, DEFAULT_DURATION_INPUT_FORMAT,
DEFAULT_DURATION_OUTPUT_FORMAT, DEFAULT_DURATION_OUTPUT_FORMAT,
FORMATS_UI_SETTINGS, FORMATS_UI_SETTINGS,
} from '@kbn/field-formats-plugin/common'; } from '@kbn/field-formats-plugin/common';
import { FormattedMessage } from '@kbn/i18n-react'; import { css } from '@emotion/react';
import type { DocLinksStart } from '@kbn/core/public';
import { LensAppServices } from '../../../app_plugin/types'; import { LensAppServices } from '../../../app_plugin/types';
import { GenericIndexPatternColumn } from '../form_based'; import { GenericIndexPatternColumn } from '../form_based';
import { isColumnFormatted } from '../operations/definitions/helpers'; import { isColumnFormatted } from '../operations/definitions/helpers';
import { ValueFormatConfig } from '../operations/definitions/column_types'; import { ValueFormatConfig } from '../operations/definitions/column_types';
import { DurationRowInputs } from './formatting/duration_input'; import { DurationRowInputs } from './formatting/duration_input';
import { Prepend, PrependWidthProvider } from '../../../shared_components/prepend_provider';
const supportedFormats: Record< const supportedFormats: Record<
string, string,
@ -124,6 +128,7 @@ type FormatParamsKeys = keyof FormatParams;
interface FormatSelectorProps { interface FormatSelectorProps {
selectedColumn: GenericIndexPatternColumn; selectedColumn: GenericIndexPatternColumn;
onChange: (newFormat?: { id: string; params?: FormatParams }) => void; onChange: (newFormat?: { id: string; params?: FormatParams }) => void;
docLinks: DocLinksStart;
} }
const RANGE_MIN = 0; const RANGE_MIN = 0;
@ -163,7 +168,8 @@ function useDebouncedInputforParam<T extends FormatParamsKeys>(
export function FormatSelector(props: FormatSelectorProps) { export function FormatSelector(props: FormatSelectorProps) {
const { uiSettings } = useKibana<LensAppServices>().services; const { uiSettings } = useKibana<LensAppServices>().services;
const { selectedColumn, onChange } = props; const { euiTheme } = useEuiTheme();
const { selectedColumn, onChange, docLinks } = props;
const currentFormat = isColumnFormatted(selectedColumn) const currentFormat = isColumnFormatted(selectedColumn)
? selectedColumn.params?.format ? selectedColumn.params?.format
: undefined; : undefined;
@ -257,23 +263,9 @@ export function FormatSelector(props: FormatSelectorProps) {
const approximatedFormat = currentFormat?.id === 'duration' && durationTo === 'humanize'; const approximatedFormat = currentFormat?.id === 'duration' && durationTo === 'humanize';
return ( return (
<PrependWidthProvider>
<> <>
<EuiFormRow <EuiFormRow label={label} display="columnCompressed" fullWidth>
label={label}
display="columnCompressed"
fullWidth
helpText={
currentFormat?.id === 'custom' ? (
<FormattedMessage
id="xpack.lens.indexPattern.customFormat.description"
defaultMessage="Numeral.js format pattern (Default: {defaultPattern})"
values={{
defaultPattern: <EuiCode>{defaultNumeralPatternInKibana}</EuiCode>,
}}
/>
) : null
}
>
<div> <div>
<EuiComboBox <EuiComboBox
fullWidth fullWidth
@ -301,19 +293,9 @@ export function FormatSelector(props: FormatSelectorProps) {
/> />
</> </>
) : null} ) : null}
{selectedFormat.supportsDecimals ? ( {selectedFormat.supportsDecimals && !approximatedFormat ? (
<> <>
<EuiSpacer size="s" /> <EuiSpacer size="s" />
<TooltipWrapper
tooltipContent={i18n.translate(
'xpack.lens.indexPattern.format.decimalsDisabled',
{
defaultMessage: 'Use a precise duration output format to use decimals.',
}
)}
condition={approximatedFormat}
display="block"
>
<EuiRange <EuiRange
showInput="inputWithPopover" showInput="inputWithPopover"
value={decimals} value={decimals}
@ -334,11 +316,10 @@ export function FormatSelector(props: FormatSelectorProps) {
data-test-subj="indexPattern-dimension-formatDecimals" data-test-subj="indexPattern-dimension-formatDecimals"
compressed compressed
fullWidth fullWidth
prepend={decimalsLabel} prepend={<Prepend>{decimalsLabel}</Prepend>}
aria-label={decimalsLabel} aria-label={decimalsLabel}
disabled={approximatedFormat} disabled={approximatedFormat}
/> />
</TooltipWrapper>
</> </>
) : null} ) : null}
{selectedFormat.supportsSuffix ? ( {selectedFormat.supportsSuffix ? (
@ -352,34 +333,29 @@ export function FormatSelector(props: FormatSelectorProps) {
data-test-subj="indexPattern-dimension-formatSuffix" data-test-subj="indexPattern-dimension-formatSuffix"
compressed compressed
fullWidth fullWidth
prepend={suffixLabel} prepend={<Prepend>{suffixLabel}</Prepend>}
aria-label={suffixLabel} aria-label={suffixLabel}
/> />
</> </>
) : null} ) : null}
{selectedFormat.supportsCompact ? ( {selectedFormat.supportsCompact && !approximatedFormat ? (
<> <>
<EuiSpacer size="s" /> <EuiSpacer size="s" />
<TooltipWrapper
tooltipContent={i18n.translate(
'xpack.lens.indexPattern.format.compactDisabled',
{
defaultMessage:
'Use a precise duration output format to use a compact format.',
}
)}
condition={approximatedFormat}
display="block"
>
<EuiSwitch <EuiSwitch
compressed compressed
label={compactLabel} label={
<EuiFormLabel
css={css`
font-weight: ${euiTheme.font.weight.regular};
`}
>
{compactLabel}
</EuiFormLabel>
}
checked={Boolean(compact)} checked={Boolean(compact)}
onChange={() => setCompact(!compact)} onChange={() => setCompact(!compact)}
data-test-subj="lns-indexpattern-dimension-formatCompact" data-test-subj="lns-indexpattern-dimension-formatCompact"
disabled={approximatedFormat}
/> />
</TooltipWrapper>
</> </>
) : null} ) : null}
</> </>
@ -387,12 +363,32 @@ export function FormatSelector(props: FormatSelectorProps) {
</div> </div>
</EuiFormRow> </EuiFormRow>
{currentFormat?.id === 'custom' ? ( {currentFormat?.id === 'custom' ? (
<EuiFormRow display="columnCompressed" hasEmptyLabelSpace label=" "> <EuiFormRow
display="columnCompressed"
hasEmptyLabelSpace
label=" "
helpText={
<EuiLink
href={docLinks.links.indexPatterns.fieldFormattersNumber}
target="_blank"
external
>
{i18n.translate('xpack.lens.indexPattern.custom.externalDoc', {
defaultMessage: 'Numeral formatting syntax',
})}
</EuiLink>
}
>
<EuiFieldText <EuiFieldText
data-test-subj={'numberEditorFormatPattern'} data-test-subj={'numberEditorFormatPattern'}
prepend={i18n.translate('xpack.lens.indexPattern.custom.patternLabel', { compressed
prepend={
<Prepend>
{i18n.translate('xpack.lens.indexPattern.custom.patternLabel', {
defaultMessage: 'Format', defaultMessage: 'Format',
})} })}
</Prepend>
}
value={pattern} value={pattern}
placeholder={defaultNumeralPatternInKibana} placeholder={defaultNumeralPatternInKibana}
onChange={(e) => { onChange={(e) => {
@ -402,5 +398,6 @@ export function FormatSelector(props: FormatSelectorProps) {
</EuiFormRow> </EuiFormRow>
) : null} ) : null}
</> </>
</PrependWidthProvider>
); );
} }

View file

@ -9,11 +9,32 @@ import { EuiComboBox, EuiSpacer } from '@elastic/eui';
import { DURATION_INPUT_FORMATS, DURATION_OUTPUT_FORMATS } from '@kbn/field-formats-plugin/common'; import { DURATION_INPUT_FORMATS, DURATION_OUTPUT_FORMATS } from '@kbn/field-formats-plugin/common';
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
import React from 'react'; import React from 'react';
import { Prepend } from '../../../../shared_components/prepend_provider';
export const durationOutputOptions = DURATION_OUTPUT_FORMATS.map(({ text, method }) => ({ function getNewHumanizeOutputLabel({ text, method }: { text: string; method: string }): {
label: text, label: string;
value: string;
} {
if (method === 'humanize') {
return {
label: i18n.translate('xpack.lens.indexPattern.duration.humanizeLabel', {
defaultMessage: 'Friendly (approximate)',
}),
value: method, value: method,
})); };
}
if (method === 'humanizePrecise') {
return {
label: i18n.translate('xpack.lens.indexPattern.duration.humanizePreciseLabel', {
defaultMessage: 'Friendly (precise)',
}),
value: method,
};
}
return { label: text, value: method };
}
export const durationOutputOptions = DURATION_OUTPUT_FORMATS.map(getNewHumanizeOutputLabel);
export const durationInputOptions = DURATION_INPUT_FORMATS.map(({ text, kind }) => ({ export const durationInputOptions = DURATION_INPUT_FORMATS.map(({ text, kind }) => ({
label: text, label: text,
value: kind, value: kind,
@ -49,9 +70,13 @@ export const DurationRowInputs = ({
return ( return (
<> <>
<EuiComboBox <EuiComboBox
prepend={i18n.translate('xpack.lens.indexPattern.duration.fromLabel', { prepend={
defaultMessage: 'From', <Prepend>
{i18n.translate('xpack.lens.indexPattern.duration.fromLabel', {
defaultMessage: 'Convert',
})} })}
</Prepend>
}
isClearable={false} isClearable={false}
options={durationInputOptions} options={durationInputOptions}
selectedOptions={getSelectedOption(startValue, durationInputOptions)} selectedOptions={getSelectedOption(startValue, durationInputOptions)}
@ -62,9 +87,13 @@ export const DurationRowInputs = ({
/> />
<EuiSpacer size="s" /> <EuiSpacer size="s" />
<EuiComboBox <EuiComboBox
prepend={i18n.translate('xpack.lens.indexPattern.custom.toLabel', { prepend={
<Prepend>
{i18n.translate('xpack.lens.indexPattern.custom.toLabel', {
defaultMessage: 'To', defaultMessage: 'To',
})} })}
</Prepend>
}
isClearable={false} isClearable={false}
options={durationOutputOptions} options={durationOutputOptions}
selectedOptions={getSelectedOption(endValue, durationOutputOptions)} selectedOptions={getSelectedOption(endValue, durationOutputOptions)}

View file

@ -0,0 +1,55 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import {
type EuiResizeObserverProps,
useEuiTheme,
EuiFormLabel,
EuiResizeObserver,
} from '@elastic/eui';
import React, { createContext, useState, useContext, ReactChild, ReactChildren } from 'react';
export const PrependWidthContext = createContext<{
minWidth: number;
onResize: EuiResizeObserverProps['onResize'];
}>({
minWidth: 0,
onResize: () => {},
});
export const PrependWidthProvider = ({ children }: { children: ReactChild | ReactChildren }) => {
const [minPrependWidth, setMinPrependWidth] = useState(0);
const prependResizeObserver = ({ width }: { width: number }) => {
if (width > minPrependWidth) {
setMinPrependWidth(width);
}
};
return (
<PrependWidthContext.Provider
value={{ minWidth: minPrependWidth, onResize: prependResizeObserver }}
>
{children}
</PrependWidthContext.Provider>
);
};
export const Prepend = ({ children }: { children: ReactChild | ReactChildren }) => {
const { minWidth, onResize } = useContext(PrependWidthContext);
const { euiTheme } = useEuiTheme();
const paddingAffordance = parseInt(euiTheme.size.m, 10) * 2;
return (
<EuiFormLabel css={{ minWidth: Math.round(minWidth) + paddingAffordance }}>
<EuiResizeObserver onResize={onResize}>
{(resizeRef) => <span ref={resizeRef}>{children}</span>}
</EuiResizeObserver>
</EuiFormLabel>
);
};

View file

@ -637,7 +637,10 @@ export type DatasourceDimensionEditorProps<T = unknown> = DatasourceDimensionPro
forceRender?: boolean; forceRender?: boolean;
} }
>; >;
core: Pick<CoreStart, 'http' | 'notifications' | 'uiSettings' | 'overlays' | 'theme'>; core: Pick<
CoreStart,
'http' | 'notifications' | 'uiSettings' | 'overlays' | 'theme' | 'docLinks'
>;
dateRange: DateRange; dateRange: DateRange;
dimensionGroups: VisualizationDimensionGroupConfig[]; dimensionGroups: VisualizationDimensionGroupConfig[];
toggleFullscreen: () => void; toggleFullscreen: () => void;

View file

@ -20643,7 +20643,6 @@
"xpack.lens.indexPattern.cardinalityOf": "Compte unique de {name}", "xpack.lens.indexPattern.cardinalityOf": "Compte unique de {name}",
"xpack.lens.indexPattern.CounterRateOf": "Taux de compteur de {name}", "xpack.lens.indexPattern.CounterRateOf": "Taux de compteur de {name}",
"xpack.lens.indexPattern.cumulativeSumOf": "Somme cumulée de {name}", "xpack.lens.indexPattern.cumulativeSumOf": "Somme cumulée de {name}",
"xpack.lens.indexPattern.customFormat.description": "Modèle de format Numeral.js (Par défaut : {defaultPattern})",
"xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "Pour choisir l'intervalle, Lens divise la plage temporelle spécifiée par le paramètre avancé {targetBarSetting} et calcule le meilleur intervalle pour vos données. Par exemple, lorsque la plage temporelle est de 4 jours, les données sont divisées en compartiments horaires. Pour configurer le nombre de barres maximal, utilisez le paramètre avancé {maxBarSetting}.", "xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "Pour choisir l'intervalle, Lens divise la plage temporelle spécifiée par le paramètre avancé {targetBarSetting} et calcule le meilleur intervalle pour vos données. Par exemple, lorsque la plage temporelle est de 4 jours, les données sont divisées en compartiments horaires. Pour configurer le nombre de barres maximal, utilisez le paramètre avancé {maxBarSetting}.",
"xpack.lens.indexPattern.dateHistogram.restrictedInterval": "Intervalle fixé à {intervalValue} en raison de restrictions d'agrégation.", "xpack.lens.indexPattern.dateHistogram.restrictedInterval": "Intervalle fixé à {intervalValue} en raison de restrictions d'agrégation.",
"xpack.lens.indexPattern.derivativeOf": "Différences de {name}", "xpack.lens.indexPattern.derivativeOf": "Différences de {name}",

View file

@ -20657,7 +20657,6 @@
"xpack.lens.indexPattern.cardinalityOf": "{name}のユニークカウント", "xpack.lens.indexPattern.cardinalityOf": "{name}のユニークカウント",
"xpack.lens.indexPattern.CounterRateOf": "{name}のカウンターレート", "xpack.lens.indexPattern.CounterRateOf": "{name}のカウンターレート",
"xpack.lens.indexPattern.cumulativeSumOf": "{name}の累積和", "xpack.lens.indexPattern.cumulativeSumOf": "{name}の累積和",
"xpack.lens.indexPattern.customFormat.description": "Numeral.jsのフォーマットパターンデフォルト{defaultPattern}",
"xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "間隔を選択するために、Lensでは、指定された時間範囲が{targetBarSetting}詳細設定で分割され、データに最適な間隔が計算されます。たとえば、時間範囲が4日の場合、データは1時間のバケットに分割されます。バーの最大数を設定するには、{maxBarSetting}詳細設定を使用します。", "xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "間隔を選択するために、Lensでは、指定された時間範囲が{targetBarSetting}詳細設定で分割され、データに最適な間隔が計算されます。たとえば、時間範囲が4日の場合、データは1時間のバケットに分割されます。バーの最大数を設定するには、{maxBarSetting}詳細設定を使用します。",
"xpack.lens.indexPattern.dateHistogram.restrictedInterval": "アグリゲーションの制限により間隔は {intervalValue} に固定されています。", "xpack.lens.indexPattern.dateHistogram.restrictedInterval": "アグリゲーションの制限により間隔は {intervalValue} に固定されています。",
"xpack.lens.indexPattern.derivativeOf": "{name}の差異", "xpack.lens.indexPattern.derivativeOf": "{name}の差異",

View file

@ -20657,7 +20657,6 @@
"xpack.lens.indexPattern.cardinalityOf": "{name} 的唯一计数", "xpack.lens.indexPattern.cardinalityOf": "{name} 的唯一计数",
"xpack.lens.indexPattern.CounterRateOf": "{name} 的计数率", "xpack.lens.indexPattern.CounterRateOf": "{name} 的计数率",
"xpack.lens.indexPattern.cumulativeSumOf": "{name} 的累计和", "xpack.lens.indexPattern.cumulativeSumOf": "{name} 的累计和",
"xpack.lens.indexPattern.customFormat.description": "Numeral.js 格式模式(默认值:{defaultPattern}",
"xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "要选择时间间隔Lens 按 {targetBarSetting} 高级设置分割指定的时间范围,并为您的数据计算最佳时间间隔。例如,当时间间隔为 4 天时,数据将分割为每小时存储桶。要配置最大条形数,请使用 {maxBarSetting} 高级设置。", "xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "要选择时间间隔Lens 按 {targetBarSetting} 高级设置分割指定的时间范围,并为您的数据计算最佳时间间隔。例如,当时间间隔为 4 天时,数据将分割为每小时存储桶。要配置最大条形数,请使用 {maxBarSetting} 高级设置。",
"xpack.lens.indexPattern.dateHistogram.restrictedInterval": "由于聚合限制,时间间隔固定为 {intervalValue}。", "xpack.lens.indexPattern.dateHistogram.restrictedInterval": "由于聚合限制,时间间隔固定为 {intervalValue}。",
"xpack.lens.indexPattern.derivativeOf": "{name} 的差异", "xpack.lens.indexPattern.derivativeOf": "{name} 的差异",