Skip to content

Commit

Permalink
[Console Migration] Add action for auto indentation (#181613)
Browse files Browse the repository at this point in the history
Closes #180213

## Summary

This PR adds an action for applying indentation to the selected requests
in the Console Monaco editor.




https://github.com/elastic/kibana/assets/59341489/307af12b-6f65-4859-87bb-e1b4bf1cc331




Note: This PR doesn't auto-indent requests that contain comments. This
will be part of a follow-up work
(#182138).




<!--
### 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&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: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
ElenaStoeva and kibanamachine committed May 15, 2024
1 parent f50b829 commit 19818f2
Show file tree
Hide file tree
Showing 5 changed files with 316 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ export const MonacoEditor = ({ initialTextValue }: EditorProps) => {
return actionsProvider.current!.getDocumentationLink(docLinkVersion);
}, [docLinkVersion]);

const autoIndentCallback = useCallback(async () => {
return actionsProvider.current!.autoIndent();
}, []);

const sendRequestsCallback = useCallback(async () => {
await actionsProvider.current?.sendRequests(toasts, dispatch, trackUiMetric, http);
}, [dispatch, http, toasts, trackUiMetric]);
Expand Down Expand Up @@ -125,7 +129,7 @@ export const MonacoEditor = ({ initialTextValue }: EditorProps) => {
<ConsoleMenu
getCurl={getCurlCallback}
getDocumentation={getDocumenationLink}
autoIndent={() => {}}
autoIndent={autoIndentCallback}
notifications={notifications}
/>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,13 @@ import {
SELECTED_REQUESTS_CLASSNAME,
stringifyRequest,
trackSentRequests,
getAutoIndentedRequests,
} from './utils';

import type { AdjustedParsedRequest } from './types';

const AUTO_INDENTATION_ACTION_LABEL = 'Apply indentations';

export class MonacoEditorActionsProvider {
private parsedRequestsProvider: ConsoleParsedRequestsProvider;
private highlightedLines: monaco.editor.IEditorDecorationsCollection;
Expand Down Expand Up @@ -343,4 +346,57 @@ export class MonacoEditorActionsProvider {
): monaco.languages.ProviderResult<monaco.languages.CompletionList> {
return this.getSuggestions(model, position, context);
}

/*
This function returns the text in the provided range.
If no range is provided, it returns all text in the editor.
*/
private getTextInRange(selectionRange?: monaco.IRange): string {
const model = this.editor.getModel();
if (!model) {
return '';
}
if (selectionRange) {
const { startLineNumber, startColumn, endLineNumber, endColumn } = selectionRange;
return model.getValueInRange({
startLineNumber,
startColumn,
endLineNumber,
endColumn,
});
}
// If no range is provided, return all text in the editor
return model.getValue();
}

/**
* This function applies indentations to the request in the selected text.
*/
public async autoIndent() {
const parsedRequests = await this.getSelectedParsedRequests();
const selectionStartLineNumber = parsedRequests[0].startLineNumber;
const selectionEndLineNumber = parsedRequests[parsedRequests.length - 1].endLineNumber;
const selectedRange = new monaco.Range(
selectionStartLineNumber,
1,
selectionEndLineNumber,
this.editor.getModel()?.getLineMaxColumn(selectionEndLineNumber) ?? 1
);

if (parsedRequests.length < 1) {
return;
}

const selectedText = this.getTextInRange(selectedRange);
const allText = this.getTextInRange();

const autoIndentedText = getAutoIndentedRequests(parsedRequests, selectedText, allText);

this.editor.executeEdits(AUTO_INDENTATION_ACTION_LABEL, [
{
range: selectedRange,
text: autoIndentedText,
},
]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export {
replaceRequestVariables,
getCurlRequest,
trackSentRequests,
getAutoIndentedRequests,
} from './requests_utils';
export {
getDocumentationLinkFromAutocomplete,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import {
getAutoIndentedRequests,
getCurlRequest,
replaceRequestVariables,
stringifyRequest,
Expand Down Expand Up @@ -160,4 +161,195 @@ describe('requests_utils', () => {
expect(mockMetricsTracker.count).toHaveBeenNthCalledWith(2, 'POST__test');
});
});

describe('getAutoIndentedRequests', () => {
const sampleEditorTextLines = [
' ', // line 1
'GET _search ', // line 2
'{ ', // line 3
' "query": { ', // line 4
' "match_all": { } ', // line 5
' } ', // line 6
' } ', // line 7
' ', // line 8
'// single comment before Request 2 ', // line 9
' GET _all ', // line 10
' ', // line 11
'/* ', // line 12
' multi-line comment before Request 3', // line 13
'*/ ', // line 14
'POST /_bulk ', // line 15
'{ ', // line 16
' "index":{ ', // line 17
' "_index":"books" ', // line 18
' } ', // line 19
' } ', // line 20
'{ ', // line 21
'"name":"1984" ', // line 22
'}{"name":"Atomic habits"} ', // line 23
' ', // line 24
'GET _search // test comment ', // line 25
'{ ', // line 26
' "query": { ', // line 27
' "match_all": { } // comment', // line 28
' } ', // line 29
'} ', // line 30
' // some comment ', // line 31
' ', // line 32
];

const TEST_REQUEST_1 = {
method: 'GET',
url: '_search',
data: [{ query: { match_all: {} } }],
// Offsets are with respect to the sample editor text
startLineNumber: 2,
endLineNumber: 7,
startOffset: 1,
endOffset: 36,
};

const TEST_REQUEST_2 = {
method: 'GET',
url: '_all',
data: [],
// Offsets are with respect to the sample editor text
startLineNumber: 10,
endLineNumber: 10,
startOffset: 1,
endOffset: 36,
};

const TEST_REQUEST_3 = {
method: 'POST',
url: '/_bulk',
// Multi-data
data: [{ index: { _index: 'books' } }, { name: '1984' }, { name: 'Atomic habits' }],
// Offsets are with respect to the sample editor text
startLineNumber: 15,
endLineNumber: 23,
startOffset: 1,
endOffset: 36,
};

const TEST_REQUEST_4 = {
method: 'GET',
url: '_search',
data: [{ query: { match_all: {} } }],
// Offsets are with respect to the sample editor text
startLineNumber: 24,
endLineNumber: 30,
startOffset: 1,
endOffset: 36,
};

it('correctly auto-indents a single request with data', () => {
const formattedData = getAutoIndentedRequests(
[TEST_REQUEST_1],
sampleEditorTextLines
.slice(TEST_REQUEST_1.startLineNumber - 1, TEST_REQUEST_1.endLineNumber)
.join('\n'),
sampleEditorTextLines.join('\n')
);
const expectedResultLines = [
'GET _search',
'{',
' "query": {',
' "match_all": {}',
' }',
'}',
];

expect(formattedData).toBe(expectedResultLines.join('\n'));
});

it('correctly auto-indents a single request with no data', () => {
const formattedData = getAutoIndentedRequests(
[TEST_REQUEST_2],
sampleEditorTextLines
.slice(TEST_REQUEST_2.startLineNumber - 1, TEST_REQUEST_2.endLineNumber)
.join('\n'),
sampleEditorTextLines.join('\n')
);
const expectedResult = 'GET _all';

expect(formattedData).toBe(expectedResult);
});

it('correctly auto-indents a single request with multiple data', () => {
const formattedData = getAutoIndentedRequests(
[TEST_REQUEST_3],
sampleEditorTextLines
.slice(TEST_REQUEST_3.startLineNumber - 1, TEST_REQUEST_3.endLineNumber)
.join('\n'),
sampleEditorTextLines.join('\n')
);
const expectedResultLines = [
'POST /_bulk',
'{',
' "index": {',
' "_index": "books"',
' }',
'}',
'{',
' "name": "1984"',
'}',
'{',
' "name": "Atomic habits"',
'}',
];

expect(formattedData).toBe(expectedResultLines.join('\n'));
});

it('auto-indents multiple request with comments in between', () => {
const formattedData = getAutoIndentedRequests(
[TEST_REQUEST_1, TEST_REQUEST_2, TEST_REQUEST_3],
sampleEditorTextLines.slice(1, 23).join('\n'),
sampleEditorTextLines.join('\n')
);
const expectedResultLines = [
'GET _search',
'{',
' "query": {',
' "match_all": {}',
' }',
'}',
'',
'// single comment before Request 2',
'GET _all',
'',
'/*',
'multi-line comment before Request 3',
'*/',
'POST /_bulk',
'{',
' "index": {',
' "_index": "books"',
' }',
'}',
'{',
' "name": "1984"',
'}',
'{',
' "name": "Atomic habits"',
'}',
];

expect(formattedData).toBe(expectedResultLines.join('\n'));
});

it('does not auto-indent a request with comments', () => {
const requestText = sampleEditorTextLines
.slice(TEST_REQUEST_4.startLineNumber - 1, TEST_REQUEST_4.endLineNumber)
.join('\n');
const formattedData = getAutoIndentedRequests(
[TEST_REQUEST_4],
requestText,
sampleEditorTextLines.join('\n')
);

expect(formattedData).toBe(requestText);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type { DevToolsVariable } from '../../../../components';
import type { EditorRequest } from '../types';
import { variableTemplateRegex } from './constants';
import { removeTrailingWhitespaces } from './tokens_utils';
import { AdjustedParsedRequest } from '../types';

/*
* This function stringifies and normalizes the parsed request:
Expand Down Expand Up @@ -130,3 +131,64 @@ const replaceVariables = (text: string, variables: DevToolsVariable[]): string =
}
return text;
};

const containsComments = (text: string) => {
return text.indexOf('//') >= 0 || text.indexOf('/*') >= 0;
};

/**
* This function takes a string containing unformatted Console requests and
* returns a text in which the requests are auto-indented.
* @param requests The list of {@link AdjustedParsedRequest} that are in the selected text in the editor.
* @param selectedText The selected text in the editor.
* @param allText The whole text input in the editor.
*/
export const getAutoIndentedRequests = (
requests: AdjustedParsedRequest[],
selectedText: string,
allText: string
): string => {
const selectedTextLines = selectedText.split(`\n`);
const allTextLines = allText.split(`\n`);
const formattedTextLines: string[] = [];

let currentLineIndex = 0;
let currentRequestIndex = 0;

while (currentLineIndex < selectedTextLines.length) {
const request = requests[currentRequestIndex];
// Check if the current line is the start of the next request
if (
request &&
selectedTextLines[currentLineIndex] === allTextLines[request.startLineNumber - 1]
) {
// Start of a request
const requestLines = allTextLines.slice(request.startLineNumber - 1, request.endLineNumber);

if (requestLines.some((line) => containsComments(line))) {
// If request has comments, add it as it is - without formatting
// TODO: Format requests with comments
formattedTextLines.push(...requestLines);
} else {
// If no comments, add stringified parsed request
const stringifiedRequest = stringifyRequest(request);
const firstLine = stringifiedRequest.method + ' ' + stringifiedRequest.url;
formattedTextLines.push(firstLine);

if (stringifiedRequest.data && stringifiedRequest.data.length > 0) {
formattedTextLines.push(...stringifiedRequest.data);
}
}

currentLineIndex = currentLineIndex + requestLines.length;
currentRequestIndex++;
} else {
// Current line is a comment or whitespaces
// Trim white spaces and add it to the formatted text
formattedTextLines.push(selectedTextLines[currentLineIndex].trim());
currentLineIndex++;
}
}

return formattedTextLines.join('\n');
};

0 comments on commit 19818f2

Please sign in to comment.