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

Validate Painless Lab index field #60841

Merged
merged 9 commits into from
Mar 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
29 changes: 14 additions & 15 deletions x-pack/plugins/painless_lab/public/application/components/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ import React, { useState, useEffect } from 'react';
import { EuiFlexGroup, EuiFlexItem, EuiTitle } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { formatRequestPayload, formatJson } from '../lib/format';
import { exampleScript } from '../common/constants';
import { PayloadFormat } from '../common/types';
import { exampleScript } from '../constants';
import { PayloadFormat } from '../types';
import { useSubmitCode } from '../hooks';
import { useAppContext } from '../context';
import { OutputPane } from './output_pane';
import { MainControls } from './main_controls';
import { Editor } from './editor';
import { RequestFlyout } from './request_flyout';
import { useAppContext } from '../context';

export const Main = () => {
export const Main: React.FunctionComponent = () => {
const {
state,
updateState,
store: { payload, validation },
updatePayload,
services: {
http,
chrome: { getIsNavDrawerLocked$ },
Expand All @@ -31,10 +31,12 @@ export const Main = () => {
const [isRequestFlyoutOpen, setRequestFlyoutOpen] = useState(false);
const { inProgress, response, submit } = useSubmitCode(http);

// Live-update the output and persist state as the user changes it.
// Live-update the output and persist payload state as the user changes it.
useEffect(() => {
submit(state);
}, [state, submit]);
if (validation.isValid) {
submit(payload);
}
}, [payload, submit, validation.isValid]);

const toggleRequestFlyout = () => {
setRequestFlyoutOpen(!isRequestFlyoutOpen);
Expand Down Expand Up @@ -62,10 +64,7 @@ export const Main = () => {
</h1>
</EuiTitle>

<Editor
code={state.code}
onChange={nextCode => updateState(() => ({ code: nextCode }))}
/>
<Editor code={payload.code} onChange={nextCode => updatePayload({ code: nextCode })} />
</EuiFlexItem>

<EuiFlexItem>
Expand All @@ -78,15 +77,15 @@ export const Main = () => {
isLoading={inProgress}
toggleRequestFlyout={toggleRequestFlyout}
isRequestFlyoutOpen={isRequestFlyoutOpen}
reset={() => updateState(() => ({ code: exampleScript }))}
isNavDrawerLocked={isNavDrawerLocked}
reset={() => updatePayload({ code: exampleScript })}
/>

{isRequestFlyoutOpen && (
<RequestFlyout
links={links}
onClose={() => setRequestFlyoutOpen(false)}
requestBody={formatRequestPayload(state, PayloadFormat.PRETTY)}
requestBody={formatRequestPayload(payload, PayloadFormat.PRETTY)}
response={response ? formatJson(response.result || response.error) : ''}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ import { FormattedMessage } from '@kbn/i18n/react';
import { i18n } from '@kbn/i18n';

import { CodeEditor } from '../../../../../../../src/plugins/kibana_react/public';
import { painlessContextOptions } from '../../common/constants';
import { painlessContextOptions } from '../../constants';
import { useAppContext } from '../../context';

export const ContextTab: FunctionComponent = () => {
const { state, updateState, links } = useAppContext();
const { context, document, index, query } = state;
const {
store: { payload, validation },
updatePayload,
links,
} = useAppContext();
const { context, document, index, query } = payload;

return (
<>
Expand Down Expand Up @@ -60,7 +64,7 @@ export const ContextTab: FunctionComponent = () => {
<EuiSuperSelect
options={painlessContextOptions}
valueOfSelected={context}
onChange={nextContext => updateState(() => ({ context: nextContext }))}
onChange={nextContext => updatePayload({ context: nextContext })}
itemLayoutAlign="top"
hasDividers
fullWidth
Expand All @@ -72,25 +76,38 @@ export const ContextTab: FunctionComponent = () => {
label={
<EuiToolTip
content={i18n.translate('xpack.painlessLab.indexFieldTooltipText', {
defaultMessage:
"Index mappings must be compatible with the sample document's fields",
defaultMessage: `Index mappings must be compatible with the sample document's fields`,
})}
>
<span>
<FormattedMessage id="xpack.painlessLab.indexFieldLabel" defaultMessage="Index" />{' '}
<FormattedMessage
id="xpack.painlessLab.indexFieldLabel"
defaultMessage="Index name"
/>{' '}
<EuiIcon type="questionInCircle" color="subdued" />
</span>
</EuiToolTip>
}
fullWidth
isInvalid={!validation.fields.index}
error={
validation.fields.index
? []
: [
i18n.translate('xpack.painlessLab.indexFieldMissingErrorMessage', {
defaultMessage: 'Enter an index name',
}),
]
}
>
<EuiFieldText
fullWidth
value={index || ''}
onChange={e => {
const nextIndex = e.target.value;
updateState(() => ({ index: nextIndex }));
updatePayload({ index: nextIndex });
}}
isInvalid={!validation.fields.index}
/>
</EuiFormRow>
)}
Expand Down Expand Up @@ -126,7 +143,7 @@ export const ContextTab: FunctionComponent = () => {
languageId="json"
height={150}
value={query}
onChange={nextQuery => updateState(() => ({ query: nextQuery }))}
onChange={nextQuery => updatePayload({ query: nextQuery })}
options={{
fontSize: 12,
minimap: {
Expand All @@ -152,7 +169,7 @@ export const ContextTab: FunctionComponent = () => {
<span>
<FormattedMessage
id="xpack.painlessLab.documentFieldLabel"
defaultMessage="Sample document"
defaultMessage="Sample document (JSON)"
/>{' '}
<EuiIcon type="questionInCircle" color="subdued" />
</span>
Expand All @@ -165,7 +182,7 @@ export const ContextTab: FunctionComponent = () => {
languageId="json"
height={400}
value={document}
onChange={nextDocument => updateState(() => ({ document: nextDocument }))}
onChange={nextDocument => updatePayload({ document: nextDocument })}
options={{
fontSize: 12,
minimap: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
} from '@elastic/eui';
import { i18n } from '@kbn/i18n';

import { Response } from '../../common/types';
import { Response } from '../../types';
import { OutputTab } from './output_tab';
import { ParametersTab } from './parameters_tab';
import { ContextTab } from './context_tab';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import React from 'react';
import { EuiCodeBlock, EuiSpacer } from '@elastic/eui';

import { formatResponse } from '../../lib/format';
import { Response } from '../../common/types';
import { Response } from '../../types';

interface Props {
response?: Response;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ import { CodeEditor } from '../../../../../../../src/plugins/kibana_react/public
import { useAppContext } from '../../context';

export const ParametersTab: FunctionComponent = () => {
const { state, updateState, links } = useAppContext();
const {
store: { payload },
updatePayload,
links,
} = useAppContext();
return (
<>
<EuiSpacer size="m" />
Expand All @@ -35,7 +39,7 @@ export const ParametersTab: FunctionComponent = () => {
<span>
<FormattedMessage
id="xpack.painlessLab.parametersFieldLabel"
defaultMessage="Parameters"
defaultMessage="Parameters (JSON)"
/>{' '}
<EuiIcon type="questionInCircle" color="subdued" />
</span>
Expand All @@ -51,16 +55,13 @@ export const ParametersTab: FunctionComponent = () => {
</EuiLink>
</EuiText>
}
helpText={i18n.translate('xpack.painlessLab.helpIconAriaLabel', {
defaultMessage: 'Use JSON format',
})}
>
<EuiPanel paddingSize="s">
<CodeEditor
languageId="json"
height={600}
value={state.parameters}
onChange={nextParams => updateState(() => ({ parameters: nextParams }))}
value={payload.parameters}
onChange={nextParams => updatePayload({ parameters: nextParams })}
options={{
fontSize: 12,
minimap: {
Expand Down
66 changes: 0 additions & 66 deletions x-pack/plugins/painless_lab/public/application/context.tsx

This file was deleted.

95 changes: 95 additions & 0 deletions x-pack/plugins/painless_lab/public/application/context/context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import React, { createContext, ReactNode, useState, useContext } from 'react';
import { HttpSetup, ChromeStart } from 'src/core/public';

import { Links } from '../../links';
import { Store, Payload, Validation } from '../types';
import { initialPayload } from './initial_payload';

interface AppContextProviderArgs {
children: ReactNode;
value: {
http: HttpSetup;
links: Links;
chrome: ChromeStart;
};
}

interface ContextValue {
store: Store;
updatePayload: (changes: Partial<Payload>) => void;
services: {
http: HttpSetup;
chrome: ChromeStart;
};
links: Links;
}

const AppContext = createContext<ContextValue>(undefined as any);

const validatePayload = (payload: Payload): Validation => {
const { index } = payload;

// For now just validate that the user has entered an index.
const indexExists = Boolean(index || index.trim());

return {
isValid: indexExists,
fields: {
index: indexExists,
},
};
};

export const AppContextProvider = ({
children,
value: { http, links, chrome },
}: AppContextProviderArgs) => {
const PAINLESS_LAB_KEY = 'painlessLabState';

const [store, setStore] = useState<Store>(() => {
// Using a callback here ensures these values are only calculated on the first render.
const defaultPayload = {
...initialPayload,
...JSON.parse(localStorage.getItem(PAINLESS_LAB_KEY) || '{}'),
};

return {
payload: defaultPayload,
validation: validatePayload(defaultPayload),
};
});

const updatePayload = (changes: Partial<Payload>): void => {
const nextPayload = {
...store.payload,
...changes,
};
// Persist state locally so we can load it up when the user reopens the app.
localStorage.setItem(PAINLESS_LAB_KEY, JSON.stringify(nextPayload));

setStore({
payload: nextPayload,
validation: validatePayload(nextPayload),
});
};

return (
<AppContext.Provider value={{ updatePayload, store, services: { http, chrome }, links }}>
{children}
</AppContext.Provider>
);
};

export const useAppContext = () => {
const ctx = useContext(AppContext);
if (!ctx) {
throw new Error('AppContext can only be used inside of AppContextProvider!');
}
return ctx;
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
* you may not use this file except in compliance with the Elastic License.
*/

export const PAINLESS_LAB_KEY = 'painlessLabState';
export { AppContextProvider, useAppContext } from './context';
Loading