Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Painless Lab] Fix float -> integer coercion bug #60201

Merged
merged 2 commits into from
Mar 17, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 6 additions & 27 deletions x-pack/plugins/painless_lab/public/application/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,15 @@
* you may not use this file except in compliance with the Elastic License.
*/

export interface ContextSetup {
params?: any;
document: Record<string, unknown>;
index: string;
}

// This should be an enumerated list
export type Context = string;

export interface Script {
source: string;
params?: Record<string, unknown>;
}

export interface Request {
script: Script;
context?: Context;
context_setup?: ContextSetup;
export interface RequestPayloadConfig {
code: string;
context: string;
parameters: string;
index: string;
document: string;
}

export interface Response {
Expand All @@ -47,15 +38,3 @@ export interface ExecutionError {
position: ExecutionErrorPosition;
script: string;
}

export type JsonArray = JsonValue[];
export type JsonValue = null | boolean | number | string | JsonObject | JsonArray;

export interface JsonObject {
[key: string]: JsonValue;
}

export type ContextChangeHandler = (change: {
context?: Partial<Context>;
contextSetup?: Partial<ContextSetup>;
}) => void;
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ import { CodeEditor } from '../../../../../../src/plugins/kibana_react/public';

interface Props {
code: string;
setCode: (code: string) => void;
onChange: (code: string) => void;
}

export function Editor({ code, setCode }: Props) {
export function Editor({ code, onChange }: Props) {
return (
<CodeEditor
languageId="painless"
// 99% width allows the editor to resize horizontally. 100% prevents it from resizing.
width="99%"
height="100%"
value={code}
onChange={setCode}
onChange={onChange}
options={{
fontSize: 12,
minimap: {
Expand Down
80 changes: 48 additions & 32 deletions x-pack/plugins/painless_lab/public/application/components/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import { HttpSetup } from 'kibana/public';
import React, { useState, useEffect } from 'react';
import { EuiFlexGroup, EuiFlexItem, EuiTitle } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { buildRequestPayload, formatJson, getFromLocalStorage } from '../lib/helpers';
import { ContextChangeHandler } from '../common/types';
import { buildRequestPayload, formatJson } from '../lib/helpers';
import { painlessContextOptions } from '../common/constants';
import { OutputPane } from './output_pane';
import { MainControls } from './main_controls';
import { Editor } from './editor';
Expand All @@ -21,39 +21,50 @@ interface Props {
http: HttpSetup;
}

const PAINLESS_LAB_KEY = 'painlessLabState';

export function Main({ http }: Props) {
const [code, setCode] = useState(getFromLocalStorage('painlessLabCode', exampleScript));
const [state, setState] = useState({
code: exampleScript,
context: painlessContextOptions[0].value,
parameters: '',
index: '',
document: '',
...JSON.parse(localStorage.getItem(PAINLESS_LAB_KEY) || '{}'),
});

const [isRequestFlyoutOpen, setRequestFlyoutOpen] = useState(false);
const { inProgress, response, submit } = useSubmitCode(http);

const [context, setContext] = useState(
getFromLocalStorage('painlessLabContext', 'painless_test_without_params')
);
// Live-update the output and persist state as the user changes it.
const { code, context, parameters, index, document } = state;
useEffect(() => {
submit(state);
localStorage.setItem(PAINLESS_LAB_KEY, JSON.stringify(state));
}, [state, submit]);

const [contextSetup, setContextSetup] = useState(
getFromLocalStorage('painlessLabContextSetup', {}, true)
);
const onCodeChange = (newCode: string) => {
setState({ ...state, code: newCode });
};

const { inProgress, response, submit } = useSubmitCode(http);
const onContextChange = (newContext: string) => {
setState({ ...state, context: newContext });
};

// Live-update the output as the user changes the input code.
useEffect(() => {
submit(code, context, contextSetup);
}, [submit, code, context, contextSetup]);
const onParametersChange = (newParameters: string) => {
setState({ ...state, parameters: newParameters });
};

const toggleRequestFlyout = () => {
setRequestFlyoutOpen(!isRequestFlyoutOpen);
const onIndexChange = (newIndex: string) => {
setState({ ...state, index: newIndex });
};

const contextChangeHandler: ContextChangeHandler = ({
context: nextContext,
contextSetup: nextContextSetup,
}) => {
if (nextContext) {
setContext(nextContext);
}
if (nextContextSetup) {
setContextSetup(nextContextSetup);
}
const onDocumentChange = (newDocument: string) => {
setState({ ...state, document: newDocument });
};

const toggleRequestFlyout = () => {
setRequestFlyoutOpen(!isRequestFlyoutOpen);
};

return (
Expand All @@ -68,16 +79,21 @@ export function Main({ http }: Props) {
</h1>
</EuiTitle>

<Editor code={code} setCode={setCode} />
<Editor code={code} onChange={onCodeChange} />
</EuiFlexItem>

<EuiFlexItem>
<OutputPane
isLoading={inProgress}
response={response}
context={context}
contextSetup={contextSetup}
isLoading={inProgress}
onContextChange={contextChangeHandler}
parameters={parameters}
index={index}
document={document}
onContextChange={onContextChange}
onParametersChange={onParametersChange}
onIndexChange={onIndexChange}
onDocumentChange={onDocumentChange}
/>
</EuiFlexItem>
</EuiFlexGroup>
Expand All @@ -86,13 +102,13 @@ export function Main({ http }: Props) {
isLoading={inProgress}
toggleRequestFlyout={toggleRequestFlyout}
isRequestFlyoutOpen={isRequestFlyoutOpen}
reset={() => setCode(exampleScript)}
reset={() => onCodeChange(exampleScript)}
/>

{isRequestFlyoutOpen && (
<RequestFlyout
onClose={() => setRequestFlyoutOpen(false)}
requestBody={formatJson(buildRequestPayload(code, context, contextSetup))}
requestBody={buildRequestPayload({ code, context, document, index, parameters })}
response={response ? formatJson(response.result || response.error) : ''}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,24 @@ import { i18n } from '@kbn/i18n';

import { CodeEditor } from '../../../../../../../src/plugins/kibana_react/public';
import { painlessContextOptions } from '../../common/constants';
import { ContextChangeHandler, ContextSetup } from '../../common/types';

interface Props {
context: string;
contextSetup: ContextSetup;
onContextChange: ContextChangeHandler;
context: any;
index: string;
document: string;
onContextChange: (change: any) => void;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can we add types here for change?

onIndexChange: (change: string) => void;
onDocumentChange: (change: string) => void;
}

export const ContextTab = ({ context, contextSetup, onContextChange }: Props) => (
export const ContextTab = ({
context,
index,
document,
onContextChange,
onIndexChange,
onDocumentChange,
}: Props) => (
<>
<EuiSpacer size="m" />
<EuiFormRow
Expand Down Expand Up @@ -65,7 +74,7 @@ export const ContextTab = ({ context, contextSetup, onContextChange }: Props) =>
<EuiSuperSelect
options={painlessContextOptions}
valueOfSelected={context}
onChange={(value: any) => onContextChange({ context: value })}
onChange={onContextChange}
itemLayoutAlign="top"
hasDividers
fullWidth
Expand All @@ -88,15 +97,7 @@ export const ContextTab = ({ context, contextSetup, onContextChange }: Props) =>
}
fullWidth
>
<EuiFieldText
fullWidth
value={contextSetup.index || ''}
onChange={e => {
onContextChange({
contextSetup: Object.assign({}, contextSetup, { index: e.target.value }),
});
}}
/>
<EuiFieldText fullWidth value={index || ''} onChange={e => onIndexChange(e.target.value)} />
</EuiFormRow>
)}
{['filter', 'score'].indexOf(context) !== -1 && (
Expand All @@ -122,11 +123,8 @@ export const ContextTab = ({ context, contextSetup, onContextChange }: Props) =>
<CodeEditor
languageId="json"
height={400}
value={contextSetup.document || ''}
onChange={(value: string) => {
const newContextSetup = Object.assign({}, contextSetup, { document: value });
onContextChange({ contextSetup: newContextSetup });
}}
value={document}
onChange={onDocumentChange}
options={{
fontSize: 12,
minimap: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,36 @@ import {
} from '@elastic/eui';
import { i18n } from '@kbn/i18n';

import { Response, ContextSetup, Context, ContextChangeHandler } from '../../common/types';
import { Response } from '../../common/types';
import { OutputTab } from './output_tab';
import { ParametersTab } from './parameters_tab';
import { ContextTab } from './context_tab';

interface Props {
context: Context;
contextSetup: ContextSetup;
isLoading: boolean;
onContextChange: ContextChangeHandler;
response?: Response;
context: string;
parameters: string;
index: string;
document: string;
onContextChange: (change: string) => void;
onParametersChange: (change: string) => void;
onIndexChange: (change: string) => void;
onDocumentChange: (change: string) => void;
}

export function OutputPane({ response, context, contextSetup, onContextChange, isLoading }: Props) {
export function OutputPane({
isLoading,
response,
context,
parameters,
index,
document,
onContextChange,
onParametersChange,
onIndexChange,
onDocumentChange,
}: Props) {
const outputTabLabel = (
<EuiFlexGroup gutterSize="s" alignItems="center">
<EuiFlexItem grow={false}>
Expand Down Expand Up @@ -67,7 +83,7 @@ export function OutputPane({ response, context, contextSetup, onContextChange, i
defaultMessage: 'Parameters',
}),
content: (
<ParametersTab contextSetup={contextSetup} onContextChange={onContextChange} />
<ParametersTab parameters={parameters} onParametersChange={onParametersChange} />
),
},
{
Expand All @@ -78,8 +94,11 @@ export function OutputPane({ response, context, contextSetup, onContextChange, i
content: (
<ContextTab
context={context}
contextSetup={contextSetup}
index={index}
document={document}
onContextChange={onContextChange}
onIndexChange={onIndexChange}
onDocumentChange={onDocumentChange}
/>
),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@ import {
import { FormattedMessage } from '@kbn/i18n/react';
import { i18n } from '@kbn/i18n';
import { CodeEditor } from '../../../../../../../src/plugins/kibana_react/public';
import { ContextChangeHandler, ContextSetup } from '../../common/types';

interface Props {
contextSetup: ContextSetup;
onContextChange: ContextChangeHandler;
parameters: string;
onParametersChange: (change: string) => void;
}

export function ParametersTab({ contextSetup, onContextChange }: Props) {
export function ParametersTab({ parameters, onParametersChange }: Props) {
return (
<>
<EuiSpacer size="m" />
Expand Down Expand Up @@ -64,8 +63,8 @@ export function ParametersTab({ contextSetup, onContextChange }: Props) {
<CodeEditor
languageId="json"
height={600}
value={contextSetup.params}
onChange={(value: string) => onContextChange({ contextSetup: { params: value } })}
value={parameters}
onChange={onParametersChange}
options={{
fontSize: 12,
minimap: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
import { useRef, useCallback, useState } from 'react';
import { HttpSetup } from 'kibana/public';
import { debounce } from 'lodash';
import { Response } from '../common/types';

import { API_BASE_PATH } from '../../../common/constants';
import { Response, RequestPayloadConfig } from '../common/types';
import { buildRequestPayload } from '../lib/helpers';
import { executeCode } from '../lib/execute_code';

const DEBOUNCE_MS = 800;

Expand All @@ -20,18 +21,19 @@ export const useSubmitCode = (http: HttpSetup) => {

const submit = useCallback(
debounce(
async (code: string, context: string, contextSetup: Record<string, any>) => {
async (config: RequestPayloadConfig) => {
setInProgress(true);

// Prevent an older request that resolves after a more recent request from clobbering it.
// We store the resulting ID in this closure for comparison when the request resolves.
const requestId = ++currentRequestIdRef.current;

try {
localStorage.setItem('painlessLabCode', code);
localStorage.setItem('painlessLabContext', context);
localStorage.setItem('painlessLabContextSetup', JSON.stringify(contextSetup));
const result = await executeCode(http, buildRequestPayload(code, context, contextSetup));
const result = await http.post(`${API_BASE_PATH}/execute`, {
// Stringify the string, because http runs it through JSON.parse, and we want to actually
// send a JSON string.
body: JSON.stringify(buildRequestPayload(config)),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it could be even more clear if we do the double stringification here with the comment. JSON.stringify(JSON.stringify(...)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, nvm I see we are building this up manually in buildRequestPayload.

});

if (currentRequestIdRef.current === requestId) {
setResponse(result);
Expand Down
Loading