Skip to content

Commit

Permalink
Merge branch 'main' into 165194-fix-relative-date-range-content-reload
Browse files Browse the repository at this point in the history
  • Loading branch information
kibanamachine authored Sep 7, 2023
2 parents 9771373 + b194edc commit eecc420
Show file tree
Hide file tree
Showing 36 changed files with 181 additions and 307 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/create-deploy-tag.yml
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ jobs:
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Useful links:*\n\n • <https://docs.google.com/document/d/1c2LzojDh1wawjeMsKh4D_L2jpVJALhxukkmmL-TUbrs/edit#heading=h.50173f90utwr|Release process playbook>\n • <https://github.com/elastic/kibana/actions/runs/${{ github.run_id }}|GitHub Workflow run>\n • <https://buildkite.com/elastic/kibana-tests/builds?branch=main|Quality Gate pipeline>\n • <https://argo-workflows.us-central1.gcp.qa.cld.elstc.co/workflows?label=hash%3D${{ env.COMMIT }}|Argo Workflow>\n • <https://platform-logging.kb.us-central1.gcp.foundit.no/app/dashboards#/view/f710d7d0-00b9-11ee-93d2-8df4bca5a4c9?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-1d,to:now))|GPCTL Logs dashboard>"
"text": "*Useful links:*\n\n • <https://docs.google.com/document/d/1c2LzojDh1wawjeMsKh4D_L2jpVJALhxukkmmL-TUbrs/edit#heading=h.50173f90utwr|Release process playbook>\n • <https://github.com/elastic/kibana/actions/runs/${{ github.run_id }}|GitHub Workflow run>\n • <https://buildkite.com/elastic/kibana-tests/builds?branch=main|Quality Gate pipeline>\n • <https://argo-workflows.us-central1.gcp.qa.cld.elstc.co/workflows?label=hash%3D${{ env.COMMIT }}|Argo Workflow>\n • <https://platform-logging.kb.us-central1.gcp.foundit.no/app/dashboards#/view/f710d7d0-00b9-11ee-93d2-8df4bca5a4c9?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-1d,to:now))&service-name=kibana&_a=(controlGroupInput:(chainingSystem:HIERARCHICAL,controlStyle:oneLine,ignoreParentSettings:(ignoreFilters:!f,ignoreQuery:!f,ignoreTimerange:!f,ignoreValidations:!f),panels:('18201b8e-3aae-4459-947d-21e007b6a3a5':(explicitInput:(dataViewId:'logs-*',enhancements:(),fieldName:commit-hash,id:'18201b8e-3aae-4459-947d-21e007b6a3a5',selectedOptions:!('${{ env.COMMIT }}'),title:commit-hash),grow:!t,order:1,type:optionsListControl,width:medium),'41060e65-ce4c-414e-b8cf-492ccb19245f':(explicitInput:(dataViewId:'logs-*',enhancements:(),fieldName:service-name,id:'41060e65-ce4c-414e-b8cf-492ccb19245f',selectedOptions:!(kibana),title:service-name),grow:!t,order:0,type:optionsListControl,width:medium),ed96828e-efe9-43ad-be3f-0e04218f79af:(explicitInput:(dataViewId:'logs-*',enhancements:(),fieldName:to-env,id:ed96828e-efe9-43ad-be3f-0e04218f79af,selectedOptions:!(qa),title:to-env),grow:!t,order:2,type:optionsListControl,width:medium))))|GPCTL Logs dashboard>"
}
},
{
Expand Down
117 changes: 64 additions & 53 deletions packages/kbn-text-based-editor/src/text_based_languages_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ let clickedOutside = false;
let initialRender = true;
let updateLinesFromModel = false;
let currentCursorContent = '';
let lines = 1;

export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
query,
Expand All @@ -130,7 +131,6 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
const queryString: string = query[language] ?? '';
const kibana = useKibana<TextBasedEditorDeps>();
const { dataViews, expressions, indexManagementApiService } = kibana.services;
const [lines, setLines] = useState(1);
const [code, setCode] = useState(queryString ?? '');
const [codeOneLiner, setCodeOneLiner] = useState('');
const [editorHeight, setEditorHeight] = useState(
Expand Down Expand Up @@ -205,22 +205,6 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
[editorHeight]
);

const updateHeight = () => {
if (editor1.current) {
const linesCount = editorModel.current?.getLineCount() || 1;
if (linesCount === 1 || clickedOutside || initialRender) return;
const editorElement = editor1.current.getDomNode();
const contentHeight = Math.min(MAX_COMPACT_VIEW_LENGTH, editor1.current.getContentHeight());

if (editorElement) {
editorElement.style.height = `${contentHeight}px`;
}
const contentWidth = Number(editorElement?.style.width.replace('px', ''));
editor1.current.layout({ width: contentWidth, height: contentHeight });
setEditorHeight(contentHeight);
}
};

const restoreInitialMode = () => {
setIsCodeEditorExpandedFocused(false);
if (isCodeEditorExpanded) return;
Expand All @@ -240,43 +224,32 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
}
};

const updateHeight = useCallback((editor: monaco.editor.IStandaloneCodeEditor) => {
if (lines === 1 || clickedOutside || initialRender) return;
const editorElement = editor.getDomNode();
const contentHeight = Math.min(MAX_COMPACT_VIEW_LENGTH, editor.getContentHeight());

if (editorElement) {
editorElement.style.height = `${contentHeight}px`;
}
const contentWidth = Number(editorElement?.style.width.replace('px', ''));
editor.layout({ width: contentWidth, height: contentHeight });
setEditorHeight(contentHeight);
}, []);

const onEditorFocus = useCallback(() => {
setIsCompactFocused(true);
setIsCodeEditorExpandedFocused(true);
setShowLineNumbers(true);
setCodeOneLiner('');
clickedOutside = false;
initialRender = false;
updateLinesFromModel = true;
}, []);

useDebounceWithOptions(
() => {
if (!editorModel.current) return;
editor1.current?.onDidChangeModelContent((e) => {
if (updateLinesFromModel) {
setLines(editorModel.current?.getLineCount() || 1);
}
if (editor1?.current) {
const currentPosition = editor1.current?.getPosition();
const content = editorModel.current?.getValueInRange({
startLineNumber: 0,
startColumn: 0,
endLineNumber: currentPosition?.lineNumber ?? 1,
endColumn: currentPosition?.column ?? 1,
});
if (content) {
currentCursorContent = content || editor1.current?.getValue();
}
}
});
editor1.current?.onDidFocusEditorText(() => {
setIsCompactFocused(true);
setIsCodeEditorExpandedFocused(true);
setShowLineNumbers(true);
setCodeOneLiner('');
clickedOutside = false;
initialRender = false;
updateLinesFromModel = true;
});
// on CMD/CTRL + Enter submit the query
// eslint-disable-next-line no-bitwise
editor1.current?.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, function () {
onTextLangQuerySubmit();
});
if (!isCodeEditorExpanded) {
editor1.current?.onDidContentSizeChange(updateHeight);
}
if (warning && (!errors || !errors.length)) {
const parsedWarning = parseWarning(warning);
setEditorWarning(parsedWarning);
Expand Down Expand Up @@ -326,7 +299,7 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
if (containerWidth && (!isCompactFocused || force)) {
const hasLines = /\r|\n/.exec(queryString);
if (hasLines && !updateLinesFromModel) {
setLines(queryString.split(/\r|\n/).length);
lines = queryString.split(/\r|\n/).length;
}
const text = getInlineEditorText(queryString, Boolean(hasLines));
const queryLength = text.length;
Expand Down Expand Up @@ -701,7 +674,45 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
editorModel.current = model;
}
if (isCodeEditorExpanded) {
setLines(model?.getLineCount() || 1);
lines = model?.getLineCount() || 1;
}

editor.onDidChangeModelContent((e) => {
if (updateLinesFromModel) {
lines = model?.getLineCount() || 1;
}
const currentPosition = editor.getPosition();
const content = editorModel.current?.getValueInRange({
startLineNumber: 0,
startColumn: 0,
endLineNumber: currentPosition?.lineNumber ?? 1,
endColumn: currentPosition?.column ?? 1,
});
if (content) {
currentCursorContent = content || editor.getValue();
}
});

editor.onDidFocusEditorText(() => {
onEditorFocus();
});

editor.onKeyDown(() => {
onEditorFocus();
});

// on CMD/CTRL + Enter submit the query
editor.addCommand(
// eslint-disable-next-line no-bitwise
monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter,
function () {
onTextLangQuerySubmit();
}
);
if (!isCodeEditorExpanded) {
editor.onDidContentSizeChange((e) => {
updateHeight(editor);
});
}
}}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,49 @@ describe('Create case', () => {
});
});

it('should trim fields correctly while submit', async () => {
const newTags = ['coke ', ' pepsi'];
const newCategory = 'First ';

appMockRender.render(
<FormContext onSuccess={onFormSubmitSuccess}>
<CreateCaseFormFields {...defaultCreateCaseForm} />
<SubmitCaseButton />
</FormContext>
);

await waitForFormToRender(screen);

const titleInput = within(screen.getByTestId('caseTitle')).getByTestId('input');

userEvent.paste(titleInput, `${sampleDataWithoutTags.title} `);

const descriptionInput = within(screen.getByTestId('caseDescription')).getByTestId(
'euiMarkdownEditorTextArea'
);

userEvent.paste(descriptionInput, `${sampleDataWithoutTags.description} `);

const caseTags = screen.getByTestId('caseTags');

for (const tag of newTags) {
const tagsInput = await within(caseTags).findByTestId('comboBoxInput');
userEvent.type(tagsInput, `${tag}{enter}`);
}

const categoryComboBox = within(screen.getByTestId('categories-list')).getByRole('combobox');

userEvent.type(categoryComboBox, `${newCategory}{enter}`);

userEvent.click(screen.getByTestId('create-case-submit'));

await waitFor(() => {
expect(postCase).toHaveBeenCalled();
});

expect(postCase).toBeCalledWith({ request: { ...sampleData, category: 'First' } });
});

it('should toggle sync settings', async () => {
useGetConnectorsMock.mockReturnValue({
...sampleConnectorData,
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/observability/common/threshold_rule/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ export type CustomMetricAggTypes = Exclude<
Aggregators.CUSTOM | Aggregators.RATE | Aggregators.P95 | Aggregators.P99
>;

export interface MetricExpressionCustomMetric {
export interface CustomThresholdExpressionMetric {
name: string;
aggType: CustomMetricAggTypes;
field?: string;
Expand All @@ -243,7 +243,7 @@ export interface MetricExpressionCustomMetric {

export interface CustomMetricExpressionParams extends BaseMetricExpressionParams {
aggType: Aggregators.CUSTOM;
customMetrics: MetricExpressionCustomMetric[];
metrics: CustomThresholdExpressionMetric[];
equation?: string;
label?: string;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ CustomEquationEditorWithEquationErrors.args = {
expression: {
...BASE_ARGS.expression,
equation: 'Math.round(A / B)',
customMetrics: [
metrics: [
{ name: 'A', aggType: Aggregators.AVERAGE, field: 'system.cpu.user.pct' },
{ name: 'B', aggType: Aggregators.MAX, field: 'system.cpu.cores' },
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { OMITTED_AGGREGATIONS_FOR_CUSTOM_METRICS } from '../../../../../common/t
import {
Aggregators,
CustomMetricAggTypes,
MetricExpressionCustomMetric,
CustomThresholdExpressionMetric,
} from '../../../../../common/threshold_rule/types';

import { MetricExpression } from '../../types';
Expand Down Expand Up @@ -58,7 +58,7 @@ export function CustomEquationEditor({
dataView,
}: CustomEquationEditorProps) {
const [customMetrics, setCustomMetrics] = useState<CustomMetrics>(
expression?.customMetrics ?? [NEW_METRIC]
expression?.metrics ?? [NEW_METRIC]
);
const [customEqPopoverOpen, setCustomEqPopoverOpen] = useState(false);
const [equation, setEquation] = useState<string | undefined>(expression?.equation || undefined);
Expand All @@ -69,7 +69,7 @@ export function CustomEquationEditor({
const currentVars = previous?.map((m) => m.name) ?? [];
const name = first(xor(VAR_NAMES, currentVars))!;
const nextMetrics = [...(previous || []), { ...NEW_METRIC, name }];
debouncedOnChange({ ...expression, customMetrics: nextMetrics, equation });
debouncedOnChange({ ...expression, metrics: nextMetrics, equation });
return nextMetrics;
});
}, [debouncedOnChange, equation, expression]);
Expand All @@ -79,18 +79,18 @@ export function CustomEquationEditor({
setCustomMetrics((previous) => {
const nextMetrics = previous?.filter((row) => row.name !== name) ?? [NEW_METRIC];
const finalMetrics = (nextMetrics.length && nextMetrics) || [NEW_METRIC];
debouncedOnChange({ ...expression, customMetrics: finalMetrics, equation });
debouncedOnChange({ ...expression, metrics: finalMetrics, equation });
return finalMetrics;
});
},
[equation, expression, debouncedOnChange]
);

const handleChange = useCallback(
(metric: MetricExpressionCustomMetric) => {
(metric: CustomThresholdExpressionMetric) => {
setCustomMetrics((previous) => {
const nextMetrics = previous?.map((m) => (m.name === metric.name ? metric : m));
debouncedOnChange({ ...expression, customMetrics: nextMetrics, equation });
debouncedOnChange({ ...expression, metrics: nextMetrics, equation });
return nextMetrics;
});
},
Expand All @@ -100,7 +100,7 @@ export function CustomEquationEditor({
const handleEquationChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setEquation(e.target.value);
debouncedOnChange({ ...expression, customMetrics, equation: e.target.value });
debouncedOnChange({ ...expression, metrics: customMetrics, equation: e.target.value });
},
[debouncedOnChange, expression, customMetrics]
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ export function MetricRowWithAgg({
[name, aggType, onChange]
);

const isAggInvalid = get(errors, ['customMetrics', name, 'aggType']) != null;
const isFieldInvalid = get(errors, ['customMetrics', name, 'field']) != null || !field;
const isAggInvalid = get(errors, ['metrics', name, 'aggType']) != null;
const isFieldInvalid = get(errors, ['metrics', name, 'field']) != null || !field;

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
* 2.0.
*/
import { AggregationType, IErrorObject } from '@kbn/triggers-actions-ui-plugin/public';
import { MetricExpressionCustomMetric } from '../../../../../common/threshold_rule/types';
import { CustomThresholdExpressionMetric } from '../../../../../common/threshold_rule/types';
import { MetricExpression } from '../../types';

export type CustomMetrics = MetricExpression['customMetrics'];
export type CustomMetrics = MetricExpression['metrics'];

export interface AggregationTypes {
[x: string]: AggregationType;
Expand All @@ -27,7 +27,7 @@ export interface MetricRowBaseProps {
onDelete: (name: string) => void;
disableDelete: boolean;
disableAdd: boolean;
onChange: (metric: MetricExpressionCustomMetric) => void;
onChange: (metric: CustomThresholdExpressionMetric) => void;
aggregationTypes: AggregationTypes;
errors: IErrorObject;
}
Loading

0 comments on commit eecc420

Please sign in to comment.