[ES|QL] Use Kibana's bar target preference for Add date histogram snippet (#192038)

## Summary

This PR updates the `Add date histogram` snippet in the ES|QL text
editor to use Kibana's bar target preference/setting.


https://github.com/user-attachments/assets/812958d0-89f0-4414-b1fb-a600d1620d63


 

### 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
- [x] [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
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] 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—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—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:
Quynh Nguyen (Quinn) 2024-09-04 12:12:42 -05:00 committed by GitHub
parent 399e85b56c
commit 0f30af937f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 46 additions and 18 deletions

View file

@ -7,7 +7,7 @@
*/ */
import { ESQL_COMMON_NUMERIC_TYPES, ESQL_NUMBER_TYPES } from '../../shared/esql_types'; import { ESQL_COMMON_NUMERIC_TYPES, ESQL_NUMBER_TYPES } from '../../shared/esql_types';
import { ADD_DATE_HISTOGRAM_SNIPPET } from '../factories'; import { getAddDateHistogramSnippet } from '../factories';
import { roundParameterTypes } from './constants'; import { roundParameterTypes } from './constants';
import { setup, getFunctionSignaturesByReturnType, getFieldNamesByType } from './helpers'; import { setup, getFunctionSignaturesByReturnType, getFieldNamesByType } from './helpers';
@ -214,7 +214,7 @@ describe('autocomplete.suggest', () => {
const { assertSuggestions } = await setup(); const { assertSuggestions } = await setup();
const expected = [ const expected = [
'var0 = ', 'var0 = ',
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet(),
...getFieldNamesByType('any').map((field) => `${field} `), ...getFieldNamesByType('any').map((field) => `${field} `),
...allEvaFunctions, ...allEvaFunctions,
...allGroupingFunctions, ...allGroupingFunctions,
@ -237,7 +237,7 @@ describe('autocomplete.suggest', () => {
const fields = getFieldNamesByType('any').map((field) => `${field} `); const fields = getFieldNamesByType('any').map((field) => `${field} `);
await assertSuggestions('from a | stats a=c by d, /', [ await assertSuggestions('from a | stats a=c by d, /', [
'var0 = ', 'var0 = ',
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet(),
...fields, ...fields,
...allEvaFunctions, ...allEvaFunctions,
...allGroupingFunctions, ...allGroupingFunctions,
@ -249,7 +249,7 @@ describe('autocomplete.suggest', () => {
]); ]);
await assertSuggestions('from a | stats avg(b) by c, /', [ await assertSuggestions('from a | stats avg(b) by c, /', [
'var0 = ', 'var0 = ',
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet(),
...fields, ...fields,
...getFunctionSignaturesByReturnType('eval', 'any', { scalar: true }), ...getFunctionSignaturesByReturnType('eval', 'any', { scalar: true }),
...allGroupingFunctions, ...allGroupingFunctions,
@ -271,13 +271,13 @@ describe('autocomplete.suggest', () => {
...allGroupingFunctions, ...allGroupingFunctions,
]); ]);
await assertSuggestions('from a | stats avg(b) by var0 = /', [ await assertSuggestions('from a | stats avg(b) by var0 = /', [
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet(),
...getFieldNamesByType('any').map((field) => `${field} `), ...getFieldNamesByType('any').map((field) => `${field} `),
...allEvaFunctions, ...allEvaFunctions,
...allGroupingFunctions, ...allGroupingFunctions,
]); ]);
await assertSuggestions('from a | stats avg(b) by c, var0 = /', [ await assertSuggestions('from a | stats avg(b) by c, var0 = /', [
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet(),
...getFieldNamesByType('any').map((field) => `${field} `), ...getFieldNamesByType('any').map((field) => `${field} `),
...allEvaFunctions, ...allEvaFunctions,
...allGroupingFunctions, ...allGroupingFunctions,

View file

@ -11,7 +11,7 @@ import { evalFunctionDefinitions } from '../definitions/functions';
import { timeUnitsToSuggest } from '../definitions/literals'; import { timeUnitsToSuggest } from '../definitions/literals';
import { commandDefinitions as unmodifiedCommandDefinitions } from '../definitions/commands'; import { commandDefinitions as unmodifiedCommandDefinitions } from '../definitions/commands';
import { import {
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet,
getDateLiterals, getDateLiterals,
getSafeInsertText, getSafeInsertText,
TIME_SYSTEM_PARAMS, TIME_SYSTEM_PARAMS,
@ -657,7 +657,7 @@ describe('autocomplete', () => {
// STATS argument BY expression // STATS argument BY expression
testSuggestions('FROM index1 | STATS field BY f/', [ testSuggestions('FROM index1 | STATS field BY f/', [
'var0 = ', 'var0 = ',
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet(),
...getFunctionSignaturesByReturnType('stats', 'any', { grouping: true, scalar: true }), ...getFunctionSignaturesByReturnType('stats', 'any', { grouping: true, scalar: true }),
...getFieldNamesByType('any').map((field) => `${field} `), ...getFieldNamesByType('any').map((field) => `${field} `),
]); ]);
@ -870,7 +870,7 @@ describe('autocomplete', () => {
'by' 'by'
); );
testSuggestions('FROM a | STATS AVG(numberField) BY /', [ testSuggestions('FROM a | STATS AVG(numberField) BY /', [
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet(),
attachTriggerCommand('var0 = '), attachTriggerCommand('var0 = '),
...getFieldNamesByType('any') ...getFieldNamesByType('any')
.map((field) => `${field} `) .map((field) => `${field} `)
@ -880,7 +880,7 @@ describe('autocomplete', () => {
// STATS argument BY assignment (checking field suggestions) // STATS argument BY assignment (checking field suggestions)
testSuggestions('FROM a | STATS AVG(numberField) BY var0 = /', [ testSuggestions('FROM a | STATS AVG(numberField) BY var0 = /', [
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet(),
...getFieldNamesByType('any') ...getFieldNamesByType('any')
.map((field) => `${field} `) .map((field) => `${field} `)
.map(attachTriggerCommand), .map(attachTriggerCommand),

View file

@ -78,7 +78,7 @@ import {
getDateLiterals, getDateLiterals,
buildFieldsDefinitionsWithMetadata, buildFieldsDefinitionsWithMetadata,
TRIGGER_SUGGESTION_COMMAND, TRIGGER_SUGGESTION_COMMAND,
ADD_DATE_HISTOGRAM_SNIPPET, getAddDateHistogramSnippet,
} from './factories'; } from './factories';
import { EDITOR_MARKER, SINGLE_BACKTICK, METADATA_FIELDS } from '../shared/constants'; import { EDITOR_MARKER, SINGLE_BACKTICK, METADATA_FIELDS } from '../shared/constants';
import { getAstContext, removeMarkerArgFromArgsList } from '../shared/context'; import { getAstContext, removeMarkerArgFromArgsList } from '../shared/context';
@ -244,6 +244,7 @@ export async function suggest(
buildQueryUntilPreviousCommand(ast, correctedQuery), buildQueryUntilPreviousCommand(ast, correctedQuery),
ast ast
); );
const { getFieldsByType, getFieldsMap } = getFieldsByTypeRetriever( const { getFieldsByType, getFieldsMap } = getFieldsByTypeRetriever(
queryForFields, queryForFields,
resourceRetriever resourceRetriever
@ -298,7 +299,8 @@ export async function suggest(
{ option, ...rest }, { option, ...rest },
getFieldsByType, getFieldsByType,
getFieldsMap, getFieldsMap,
getPolicyMetadata getPolicyMetadata,
resourceRetriever?.getPreferences
); );
} }
} }
@ -1573,8 +1575,14 @@ async function getOptionArgsSuggestions(
}, },
getFieldsByType: GetFieldsByTypeFn, getFieldsByType: GetFieldsByTypeFn,
getFieldsMaps: GetFieldsMapFn, getFieldsMaps: GetFieldsMapFn,
getPolicyMetadata: GetPolicyMetadataFn getPolicyMetadata: GetPolicyMetadataFn,
getPreferences?: () => Promise<{ histogramBarTarget: number } | undefined>
) { ) {
let preferences: { histogramBarTarget: number } | undefined;
if (getPreferences) {
preferences = await getPreferences();
}
const optionDef = getCommandOption(option.name); const optionDef = getCommandOption(option.name);
const { nodeArg, argIndex, lastArg } = extractArgMeta(option, node); const { nodeArg, argIndex, lastArg } = extractArgMeta(option, node);
const suggestions = []; const suggestions = [];
@ -1778,9 +1786,9 @@ async function getOptionArgsSuggestions(
defaultMessage: 'Add date histogram', defaultMessage: 'Add date histogram',
} }
), ),
text: ADD_DATE_HISTOGRAM_SNIPPET, text: getAddDateHistogramSnippet(preferences?.histogramBarTarget),
asSnippet: true, asSnippet: true,
kind: 'Function', kind: 'Issue',
detail: i18n.translate( detail: i18n.translate(
'kbn-esql-validation-autocomplete.esql.autocomplete.addDateHistogramDetail', 'kbn-esql-validation-autocomplete.esql.autocomplete.addDateHistogramDetail',
{ {

View file

@ -30,7 +30,10 @@ const allFunctions = statsAggregationFunctionDefinitions
.concat(groupingFunctionDefinitions); .concat(groupingFunctionDefinitions);
export const TIME_SYSTEM_PARAMS = ['?t_start', '?t_end']; export const TIME_SYSTEM_PARAMS = ['?t_start', '?t_end'];
export const ADD_DATE_HISTOGRAM_SNIPPET = 'BUCKET($0, 10, ?t_start, ?t_end)';
export const getAddDateHistogramSnippet = (histogramBarTarget = 50) => {
return `BUCKET($0, ${histogramBarTarget}, ${TIME_SYSTEM_PARAMS.join(', ')})`;
};
export const TRIGGER_SUGGESTION_COMMAND = { export const TRIGGER_SUGGESTION_COMMAND = {
title: 'Trigger Suggestion Dialog', title: 'Trigger Suggestion Dialog',

View file

@ -28,6 +28,7 @@ export interface ESQLCallbacks {
{}, {},
{ name: string; sourceIndices: string[]; matchField: string; enrichFields: string[] } { name: string; sourceIndices: string[]; matchField: string; enrichFields: string[] }
>; >;
getPreferences?: () => Promise<{ histogramBarTarget: number }>;
} }
export type ReasonTypes = 'missingCommand' | 'unsupportedFunction' | 'unknownFunction'; export type ReasonTypes = 'missingCommand' | 'unsupportedFunction' | 'unknownFunction';

View file

@ -16159,6 +16159,7 @@ describe('validation logic', () => {
getSources: /Unknown index/, getSources: /Unknown index/,
getPolicies: /Unknown policy/, getPolicies: /Unknown policy/,
getFieldsFor: /Unknown column|Argument of|it is unsupported or not indexed/, getFieldsFor: /Unknown column|Argument of|it is unsupported or not indexed/,
getPreferences: /Unknown/,
}; };
return excludedCallback.map((callback) => contentByCallback[callback]) || []; return excludedCallback.map((callback) => contentByCallback[callback]) || [];
} }

View file

@ -1099,6 +1099,7 @@ export const ignoreErrorsMap: Record<keyof ESQLCallbacks, ErrorTypes[]> = {
getFieldsFor: ['unknownColumn', 'wrongArgumentType', 'unsupportedFieldType'], getFieldsFor: ['unknownColumn', 'wrongArgumentType', 'unsupportedFieldType'],
getSources: ['unknownIndex'], getSources: ['unknownIndex'],
getPolicies: ['unknownPolicy'], getPolicies: ['unknownPolicy'],
getPreferences: [],
}; };
/** /**

View file

@ -83,9 +83,17 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
const datePickerOpenStatusRef = useRef<boolean>(false); const datePickerOpenStatusRef = useRef<boolean>(false);
const { euiTheme } = useEuiTheme(); const { euiTheme } = useEuiTheme();
const kibana = useKibana<TextBasedEditorDeps>(); const kibana = useKibana<TextBasedEditorDeps>();
const { dataViews, expressions, indexManagementApiService, application, core, fieldsMetadata } = const {
kibana.services; dataViews,
expressions,
indexManagementApiService,
application,
core,
fieldsMetadata,
uiSettings,
} = kibana.services;
const timeZone = core?.uiSettings?.get('dateFormat:tz'); const timeZone = core?.uiSettings?.get('dateFormat:tz');
const histogramBarTarget = uiSettings?.get('histogram:barTarget') ?? 50;
const [code, setCode] = useState<string>(query.esql ?? ''); const [code, setCode] = useState<string>(query.esql ?? '');
// To make server side errors less "sticky", register the state of the code when submitting // To make server side errors less "sticky", register the state of the code when submitting
const [codeWhenSubmitted, setCodeStateOnSubmission] = useState(code); const [codeWhenSubmitted, setCodeStateOnSubmission] = useState(code);
@ -364,6 +372,11 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
} }
return policies.map(({ type, query: policyQuery, ...rest }) => rest); return policies.map(({ type, query: policyQuery, ...rest }) => rest);
}, },
getPreferences: async () => {
return {
histogramBarTarget,
};
},
}; };
return callbacks; return callbacks;
}, [ }, [
@ -378,6 +391,7 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
abortController, abortController,
indexManagementApiService, indexManagementApiService,
fieldsMetadata, fieldsMetadata,
histogramBarTarget,
]); ]);
const queryRunButtonProperties = useMemo(() => { const queryRunButtonProperties = useMemo(() => {