From 7dd5984287ed70ba48286f67bdd9fffcfedbec60 Mon Sep 17 00:00:00 2001 From: "Quynh Nguyen (Quinn)" <43350163+qn895@users.noreply.github.com> Date: Thu, 19 Sep 2024 18:44:40 -0500 Subject: [PATCH] [ES|QL] Fix new variables being suggested in incorrect places (#192405) ## Summary Fixes https://github.com/elastic/kibana/issues/191876 and another bug where var0 was being suggested within the case expression if it was not previously prefixed with `var0 =`. 1. No more suggestions for new variable assignment if cursor is within a function Before https://github.com/user-attachments/assets/01327c3e-f339-44f5-bb69-922318d2ded6 After https://github.com/user-attachments/assets/3eb490d4-46c3-4839-a1d9-06b61a030e97 2. No more suggestions within `case()` Before https://github.com/user-attachments/assets/36707c65-e2c8-458a-97c2-4b287cada3f8 After https://github.com/user-attachments/assets/bee088cd-2140-4e9e-bf09-22bd278a242d ### 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 - [ ] [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) --------- Co-authored-by: Elastic Machine (cherry picked from commit ef5aee1cc252e79aaa833eddeb686dc9492de98c) --- .../autocomplete.suggest.eval.test.ts | 3 +-- .../src/autocomplete/autocomplete.ts | 19 +++++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/kbn-esql-validation-autocomplete/src/autocomplete/__tests__/autocomplete.suggest.eval.test.ts b/packages/kbn-esql-validation-autocomplete/src/autocomplete/__tests__/autocomplete.suggest.eval.test.ts index c07b065b23ce8e..cc04ccb407e6e3 100644 --- a/packages/kbn-esql-validation-autocomplete/src/autocomplete/__tests__/autocomplete.suggest.eval.test.ts +++ b/packages/kbn-esql-validation-autocomplete/src/autocomplete/__tests__/autocomplete.suggest.eval.test.ts @@ -559,7 +559,7 @@ describe('autocomplete.suggest', () => { test('case', async () => { const { assertSuggestions } = await setup(); const comparisonOperators = ['==', '!=', '>', '<', '>=', '<='] - .map((op) => `${op} `) + .map((op) => `${op}`) .concat(','); // case( / ) suggest any field/eval function in this position as first argument @@ -626,7 +626,6 @@ describe('autocomplete.suggest', () => { // Notice no extra space after field name ...getFieldNamesByType('any').map((field) => `${field}`), ...getFunctionSignaturesByReturnType('eval', 'any', { scalar: true }, undefined, []), - 'var0 = ', ]); // case( field > 0, >) suggests fields like normal diff --git a/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.ts b/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.ts index a1be88b0b1436e..2a3d676507086b 100644 --- a/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.ts +++ b/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.ts @@ -111,6 +111,7 @@ import { } from '../definitions/types'; import { metadataOption } from '../definitions/options'; import { comparisonFunctions } from '../definitions/builtin'; +import { countBracketsUnclosed } from '../shared/helpers'; type GetFieldsByTypeFn = ( type: string | string[], @@ -554,8 +555,11 @@ async function getExpressionSuggestionsByType( const fieldsMap: Map = await (argDef ? getFieldsMap() : new Map()); const anyVariables = collectVariables(commands, fieldsMap, innerText); + const previousWord = findPreviousWord(innerText); // enrich with assignment has some special rules who are handled somewhere else - const canHaveAssignments = ['eval', 'stats', 'row'].includes(command.name); + const canHaveAssignments = + ['eval', 'stats', 'row'].includes(command.name) && + !comparisonFunctions.map((fn) => fn.name).includes(previousWord); const references = { fields: fieldsMap, variables: anyVariables }; @@ -1422,10 +1426,9 @@ async function getFunctionArgsSuggestions( suggestions.push( ...comparisonFunctions.map(({ name, description }) => ({ label: name, - text: name + ' ', + text: name, kind: 'Function' as ItemKind, detail: description, - command: TRIGGER_SUGGESTION_COMMAND, })) ); } @@ -1786,10 +1789,13 @@ async function getOptionArgsSuggestions( openSuggestions: true, })) ); + // Checks if cursor is still within function () + // by checking if the marker editor/cursor is within an unclosed parenthesis + const canHaveAssignment = countBracketsUnclosed('(', innerText) === 0; if (option.name === 'by') { // Add quick snippet for for stats ... by bucket(<>) - if (command.name === 'stats') { + if (command.name === 'stats' && canHaveAssignment) { suggestions.push({ label: i18n.translate( 'kbn-esql-validation-autocomplete.esql.autocomplete.addDateHistogram', @@ -1820,12 +1826,13 @@ async function getOptionArgsSuggestions( { functions: true, fields: false, - } + }, + { ignoreFn: canHaveAssignment ? [] : ['bucket', 'case'] } )) ); } - if (command.name === 'stats' && isNewExpression) { + if (command.name === 'stats' && isNewExpression && canHaveAssignment) { suggestions.push(buildNewVarDefinition(findNewVariable(anyVariables))); } }