Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
127 commits
Select commit Hold shift + click to select a range
001b5e3
add create and edit extension
dominiqueclarke Feb 16, 2021
5e0fef4
add CustomFields component
dominiqueclarke Feb 16, 2021
6153431
add useUpdatePolicy
dominiqueclarke Feb 16, 2021
3951854
rename package folder to fleet_package
dominiqueclarke Feb 16, 2021
65aa933
add support for tcp and icmp monitor types
dominiqueclarke Feb 25, 2021
dab4bab
Merge branch 'master' of github.com:elastic/kibana into feature/91062…
dominiqueclarke Feb 25, 2021
5d194d7
add custom fields for tcp
dominiqueclarke Mar 2, 2021
2760c98
add icmp fields
dominiqueclarke Mar 4, 2021
a324199
Merge branch 'master' into feature/91062-fleet-integration
kibanamachine Mar 5, 2021
b01e492
add synthetics-* to fleet permissions
dominiqueclarke Mar 10, 2021
68d4cec
Merge branch 'feature/91062-fleet-integration' of https://github.com/…
dominiqueclarke Mar 10, 2021
ffb0d40
add advanced http and tcp fields
dominiqueclarke Mar 10, 2021
3e4498b
merge master
dominiqueclarke Mar 10, 2021
160f44f
adjust schedule configuration
dominiqueclarke Mar 10, 2021
4fcd960
adjust tsconfig
dominiqueclarke Mar 10, 2021
22253c5
update ComboBox
dominiqueclarke Mar 11, 2021
c1afdc1
memoize components for performance
dominiqueclarke Mar 11, 2021
cf965ad
add ResponseBodyIndexField
dominiqueclarke Mar 16, 2021
4cf4740
add KeyValueField
dominiqueclarke Mar 16, 2021
5d100ca
Updated RequestBodyField to support form type
dominiqueclarke Mar 16, 2021
fcda301
add form Mode type
dominiqueclarke Mar 16, 2021
eed0a4d
update header field to use KeyValuePairsField and account for whitespace
dominiqueclarke Mar 16, 2021
e7709c8
update HTTPAdvancedFields
dominiqueclarke Mar 16, 2021
dc2d31a
update CustomFields
dominiqueclarke Mar 16, 2021
8b1b9d7
Merge branch 'master' of github.com:elastic/kibana into feature/91062…
dominiqueclarke Mar 16, 2021
a739e60
Merge branch 'master' of github.com:elastic/kibana into feature/91062…
dominiqueclarke Mar 16, 2021
d0e9c34
update ComboBox to take onChange
dominiqueclarke Mar 17, 2021
d8d2631
remove ConfigKey from KeyValuePairsField
dominiqueclarke Mar 17, 2021
9343880
update HeaderField to use onChange
dominiqueclarke Mar 17, 2021
83fc354
update ScheduleField to use onChange
dominiqueclarke Mar 17, 2021
c668703
update types
dominiqueclarke Mar 17, 2021
3dd0a42
update TCPAdvancedFields to use onChange
dominiqueclarke Mar 17, 2021
17b7c13
update HTTPAdvancedFields to use onChange
dominiqueclarke Mar 17, 2021
0273c00
add central validation
dominiqueclarke Mar 17, 2021
62af94a
update response body to support form content type
dominiqueclarke Mar 17, 2021
1b72f9e
add validation file
dominiqueclarke Mar 22, 2021
5b304d7
update HeaderField to take defaultValue
dominiqueclarke Mar 22, 2021
a5a6d4e
update RequestBodyField to take onChange
dominiqueclarke Mar 22, 2021
316e57c
update types
dominiqueclarke Mar 22, 2021
9e4f35e
update ResponseBodyIndexField
dominiqueclarke Mar 22, 2021
e0db3d3
update HTTPAdvancedFields
dominiqueclarke Mar 22, 2021
e4f1d8b
update CustomFields to pass REQUEST_HEADERS_CHECK appropriately
dominiqueclarke Mar 22, 2021
83ccd99
import validation into SyntheticsPolicyCreateExtension
dominiqueclarke Mar 22, 2021
b1502af
stringify REQUEST_BODY_CHECK
dominiqueclarke Mar 22, 2021
9d9506b
update SyntheticsPolicyEditExtension
dominiqueclarke Mar 22, 2021
2192eef
Merge branch 'master' of github.com:elastic/kibana into feature/91062…
dominiqueclarke Mar 22, 2021
0eba5df
add ScheduleField tests
dominiqueclarke Mar 22, 2021
7973a95
add HeaderField tests
dominiqueclarke Mar 22, 2021
f9bd589
add KeyValuePairsField tests
dominiqueclarke Mar 22, 2021
9079339
add ResponseBodyIndexField tests
dominiqueclarke Mar 22, 2021
4d1df08
adjust types
dominiqueclarke Mar 22, 2021
bedc59c
add CustomFields tests
dominiqueclarke Mar 23, 2021
00cd389
add HTTPAdvanceFields tests
dominiqueclarke Mar 23, 2021
ec57e3b
add TCPAdvancedFields tests
dominiqueclarke Mar 23, 2021
cc3d843
add RequestBodyField tests
dominiqueclarke Mar 23, 2021
10e2012
update aria-labels for ScheduleField
dominiqueclarke Mar 23, 2021
d33ae4a
update aria-labels for ResponseBodyIndexField
dominiqueclarke Mar 23, 2021
8a9dbfb
add ComboBox tests
dominiqueclarke Mar 23, 2021
4c29af6
delete ResponseCheckField
dominiqueclarke Mar 23, 2021
b34af97
hide monitorType field when editing policy
dominiqueclarke Mar 24, 2021
0339582
add tests for useUpdatePolicy
dominiqueclarke Mar 27, 2021
1c18266
update CustomFields tests
dominiqueclarke Mar 29, 2021
b6a1161
update useUpdatePolicy tests
dominiqueclarke Mar 29, 2021
009f378
add SyntheticsPolicyCreateExtension tests
dominiqueclarke Mar 29, 2021
12ea76c
add SyntheticsPolicyCreateExtension tests
dominiqueclarke Mar 29, 2021
d489b4a
add SyntheticsPolicyEditExtension tests
dominiqueclarke Mar 29, 2021
a7c1d12
add docs to AdvancedHTTPOptions
dominiqueclarke Mar 29, 2021
d32da13
document TCPAdvanced options
dominiqueclarke Mar 29, 2021
fb4742d
only show max redirects for http
dominiqueclarke Mar 29, 2021
170f8f4
add help text and change timeout to seconds
dominiqueclarke Mar 29, 2021
51fd912
merge master
dominiqueclarke Mar 29, 2021
73198cf
add certs field
dominiqueclarke Mar 30, 2021
4ba9e15
add certs types
dominiqueclarke Mar 30, 2021
4d4c2ab
add Certs defaults
dominiqueclarke Mar 30, 2021
5ab2d44
update custom fields to include certs and add documentation
dominiqueclarke Mar 30, 2021
f894694
update custom fields to include certs and add documentation
dominiqueclarke Mar 30, 2021
8eda637
merge master
dominiqueclarke Mar 31, 2021
a5b5bac
[Fleet] Correctly parse falsy YAML fields in agent policy integrations
Zacqary Mar 31, 2021
7acb16c
Merge branch '95478-yaml-hbs-fix' of https://github.com/Zacqary/kiban…
dominiqueclarke Mar 31, 2021
a5305f4
update useUpdatePolicy for response_body_check_negative and response_…
dominiqueclarke Mar 31, 2021
accde67
Merge branch 'feature/91062-fleet-integration' of https://github.com/…
dominiqueclarke Mar 31, 2021
27fddd5
remove unused component
dominiqueclarke Mar 31, 2021
a068f96
ensure empty arrays are passed as null and add tests
dominiqueclarke Mar 31, 2021
5c06b30
handle conditonals
dominiqueclarke Mar 31, 2021
8766849
update fleet permissions to include synthetics*
dominiqueclarke Apr 2, 2021
aa8db12
adjust validation
dominiqueclarke Apr 2, 2021
9bc9b4d
move proxyurl and move full length fields to right side
dominiqueclarke Apr 2, 2021
d623b5f
only show TLS for HTTP and TCP
dominiqueclarke Apr 2, 2021
7a2f0f6
update schedule default to 3m
dominiqueclarke Apr 2, 2021
9faecf4
remove references to the word Heartbeat
dominiqueclarke Apr 2, 2021
b7c9137
add additional http verbs
dominiqueclarke Apr 2, 2021
d2223d4
refactor certs fields and add tls version
dominiqueclarke Apr 5, 2021
e831f62
add validation to Response status field
dominiqueclarke Apr 5, 2021
0d994dc
add username and password fields
dominiqueclarke Apr 6, 2021
eec7aaf
Merge branch 'master' into feature/91062-fleet-integration
kibanamachine Apr 6, 2021
6fbaf11
fix form field edit bug
dominiqueclarke Apr 6, 2021
b5ba505
Merge branch 'feature/91062-fleet-integration' of https://github.com/…
dominiqueclarke Apr 6, 2021
06746e7
Add missing Optional labels and remove extra optional content
dominiqueclarke Apr 6, 2021
0fd37fb
Refactor KeyValueField to allow deleting and adding fields
dominiqueclarke Apr 6, 2021
33afb84
adjust spacing between fields in ScheduleField
dominiqueclarke Apr 6, 2021
43577a3
use the same data model for all code in ResponseBodyField
dominiqueclarke Apr 6, 2021
2a31cde
adjust formatted message id
dominiqueclarke Apr 7, 2021
71b4121
remove isTLSEnabled from use_update_policy
dominiqueclarke Apr 7, 2021
41d33b4
update HTTPAdvancedFields test
dominiqueclarke Apr 7, 2021
26116bc
add validation for tcp host and port
dominiqueclarke Apr 7, 2021
7169552
add validation for timeout greater than schedule interval
dominiqueclarke Apr 7, 2021
88f2e2e
remove unused htmlId generator
dominiqueclarke Apr 7, 2021
744ffa5
merge master
dominiqueclarke Apr 7, 2021
291b974
update default values
dominiqueclarke Apr 7, 2021
8eae060
updated help text for combo box
dominiqueclarke Apr 7, 2021
4e4a138
add page view telemetry
dominiqueclarke Apr 8, 2021
6a7a808
Merge branch 'master' of github.com:elastic/kibana into feature/91062…
dominiqueclarke Apr 8, 2021
b6ce7bd
update ObservabilityFetchDataPlugins type
dominiqueclarke Apr 8, 2021
098350f
update references to SSL to TLS
dominiqueclarke Apr 8, 2021
46aed2c
update feature to use context
dominiqueclarke Apr 9, 2021
f69f1f8
merge master
dominiqueclarke Apr 12, 2021
aaf691f
remove unnecessary import
dominiqueclarke Apr 12, 2021
b431b8e
Merge branch 'master' of github.com:elastic/kibana into feature/91062…
dominiqueclarke Apr 12, 2021
0fae8f6
use exported context hook
dominiqueclarke Apr 13, 2021
01e4d12
updated min value for schedule field to 1
dominiqueclarke Apr 13, 2021
8ff4536
Merge branch 'master' into feature/91062-fleet-integration
kibanamachine Apr 13, 2021
e9b4fff
remove unnecessary ReactMardown
dominiqueclarke Apr 13, 2021
129dca6
Merge branch 'feature/91062-fleet-integration' of https://github.com/…
dominiqueclarke Apr 13, 2021
8da9919
convert password to cleartext field, add PEM help text, and change ch…
dominiqueclarke Apr 15, 2021
775835f
merge master
dominiqueclarke Apr 15, 2021
72a9ba4
merge master
dominiqueclarke Apr 17, 2021
055c750
Merge branch 'master' into feature/91062-fleet-integration
kibanamachine Apr 19, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type { GetDataStreamsResponse } from '../../../common';
import { getPackageSavedObjects } from '../../services/epm/packages/get';
import { defaultIngestErrorHandler } from '../../errors';

const DATA_STREAM_INDEX_PATTERN = 'logs-*-*,metrics-*-*,traces-*-*';
const DATA_STREAM_INDEX_PATTERN = 'logs-*-*,metrics-*-*,traces-*-*,synthetics-*-*';

interface ESDataStreamInfo {
name: string;
Expand Down
8 changes: 7 additions & 1 deletion x-pack/plugins/fleet/server/services/agent_policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,13 @@ class AgentPolicyService {
cluster: ['monitor'],
indices: [
{
names: ['logs-*', 'metrics-*', 'traces-*', '.logs-endpoint.diagnostic.collection-*'],
names: [
'logs-*',
'metrics-*',
'traces-*',
'.logs-endpoint.diagnostic.collection-*',
'synthetics-*',
],
privileges: ['auto_configure', 'create_doc'],
},
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export type HasData<T extends ObservabilityFetchDataPlugins> = (

export type ObservabilityFetchDataPlugins = Exclude<
ObservabilityApp,
'observability-overview' | 'stack_monitoring'
'observability-overview' | 'stack_monitoring' | 'fleet'
>;

export interface DataHandler<
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/observability/typings/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ export type ObservabilityApp =
| 'synthetics'
| 'observability-overview'
| 'stack_monitoring'
| 'ux';
| 'ux'
| 'fleet';

export type PromiseReturnType<Func> = Func extends (...args: any[]) => Promise<infer Value>
? Value
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/uptime/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"data",
"home",
"observability",
"ml"
"ml",
"fleet"
],
"requiredPlugins": [
"alerting",
Expand Down
22 changes: 22 additions & 0 deletions x-pack/plugins/uptime/public/apps/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,14 @@ import {
DataPublicPluginStart,
} from '../../../../../src/plugins/data/public';
import { alertTypeInitializers } from '../lib/alert_types';
import { FleetStart } from '../../../fleet/public';
import { FetchDataParams, ObservabilityPublicSetup } from '../../../observability/public';
import { PLUGIN } from '../../common/constants/plugin';
import { IStorageWrapper } from '../../../../../src/plugins/kibana_utils/public';
import {
LazySyntheticsPolicyCreateExtension,
LazySyntheticsPolicyEditExtension,
} from '../components/fleet_package';

export interface ClientPluginsSetup {
data: DataPublicPluginSetup;
Expand All @@ -42,6 +47,7 @@ export interface ClientPluginsStart {
embeddable: EmbeddableStart;
data: DataPublicPluginStart;
triggersActionsUi: TriggersAndActionsUIPublicPluginStart;
fleet?: FleetStart;
}

export interface UptimePluginServices extends Partial<CoreStart> {
Expand Down Expand Up @@ -143,6 +149,22 @@ export class UptimePlugin
plugins.triggersActionsUi.alertTypeRegistry.register(alertInitializer);
}
});

if (plugins.fleet) {
const { registerExtension } = plugins.fleet;

registerExtension({
package: 'synthetics',
view: 'package-policy-create',
component: LazySyntheticsPolicyCreateExtension,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thanks for making these Lazy

});

registerExtension({
package: 'synthetics',
view: 'package-policy-edit',
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

do we also need something for package-policy-delete? or it's covered in edit?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

These extensions only apply to particular views. There isn't a view for delete. Rather, you delete the policy simply in the existing fleet UI within the policies page.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

but we will need that when we want to delete monitors directly from uptime UI

component: LazySyntheticsPolicyEditExtension,
});
}
}

public stop(): void {}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import { render } from '../../lib/helper/rtl_helpers';
import { ComboBox } from './combo_box';

describe('<ComboBox />', () => {
const onChange = jest.fn();
const selectedOptions: string[] = [];

it('renders ComboBox', () => {
const { getByTestId } = render(
<ComboBox selectedOptions={selectedOptions} onChange={onChange} />
);

expect(getByTestId('syntheticsFleetComboBox')).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React, { useState, useCallback } from 'react';
import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui';

export interface Props {
onChange: (value: string[]) => void;
selectedOptions: string[];
}

export const ComboBox = ({ onChange, selectedOptions }: Props) => {
const [formattedSelectedOptions, setSelectedOptions] = useState<
Array<EuiComboBoxOptionOption<string>>
>(selectedOptions.map((option) => ({ label: option, key: option })));
const [isInvalid, setInvalid] = useState(false);

const onOptionsChange = useCallback(
(options: Array<EuiComboBoxOptionOption<string>>) => {
setSelectedOptions(options);
const formattedTags = options.map((option) => option.label);
onChange(formattedTags);
setInvalid(false);
},
[onChange, setSelectedOptions, setInvalid]
);

const onCreateOption = useCallback(
(tag: string) => {
const formattedTag = tag.trim();
const newOption = {
label: formattedTag,
};

onChange([...selectedOptions, formattedTag]);

// Select the option.
setSelectedOptions([...formattedSelectedOptions, newOption]);
},
[onChange, formattedSelectedOptions, selectedOptions, setSelectedOptions]
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

i am really surprised that you had to use useCallBack so much. with such a long list of dependencies, i am not sure, what performance aspect it provides.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

and this call back is just setting state object and calling onChange. Which is pretty much what you do in a component.

);

const onSearchChange = useCallback(
(searchValue: string) => {
if (!searchValue) {
setInvalid(false);

return;
}

setInvalid(!isValid(searchValue));
},
[setInvalid]
);

return (
<EuiComboBox<string>
data-test-subj="syntheticsFleetComboBox"
noSuggestions
selectedOptions={formattedSelectedOptions}
onCreateOption={onCreateOption}
onChange={onOptionsChange}
onSearchChange={onSearchChange}
isInvalid={isInvalid}
/>
);
};

const isValid = (value: string) => {
// Ensure that the tag is more than whitespace
return value.match(/\S+/) !== null;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React, { createContext, useContext, useMemo, useState } from 'react';
import {
IHTTPAdvancedFields,
ConfigKeys,
Mode,
ResponseBodyIndexPolicy,
HTTPMethod,
} from '../types';

interface IHTTPAdvancedFieldsContext {
setFields: React.Dispatch<React.SetStateAction<IHTTPAdvancedFields>>;
fields: IHTTPAdvancedFields;
defaultValues: IHTTPAdvancedFields;
}

interface IHTTPAdvancedFieldsContextProvider {
children: React.ReactNode;
defaultValues?: IHTTPAdvancedFields;
}

export const initialValues = {
[ConfigKeys.PASSWORD]: '',
[ConfigKeys.PROXY_URL]: '',
[ConfigKeys.RESPONSE_BODY_CHECK_NEGATIVE]: [],
[ConfigKeys.RESPONSE_BODY_CHECK_POSITIVE]: [],
[ConfigKeys.RESPONSE_BODY_INDEX]: ResponseBodyIndexPolicy.ON_ERROR,
[ConfigKeys.RESPONSE_HEADERS_CHECK]: {},
[ConfigKeys.RESPONSE_HEADERS_INDEX]: true,
[ConfigKeys.RESPONSE_STATUS_CHECK]: [],
[ConfigKeys.REQUEST_BODY_CHECK]: {
value: '',
type: Mode.TEXT,
},
[ConfigKeys.REQUEST_HEADERS_CHECK]: {},
[ConfigKeys.REQUEST_METHOD_CHECK]: HTTPMethod.GET,
[ConfigKeys.USERNAME]: '',
};

export const defaultContext: IHTTPAdvancedFieldsContext = {
setFields: (_fields: React.SetStateAction<IHTTPAdvancedFields>) => {
throw new Error('setFields was not initialized, set it when you invoke the context');
},
fields: initialValues,
defaultValues: initialValues,
};

export const HTTPAdvancedFieldsContext = createContext(defaultContext);

export const HTTPAdvancedFieldsContextProvider = ({
children,
defaultValues = initialValues,
}: IHTTPAdvancedFieldsContextProvider) => {
const [fields, setFields] = useState<IHTTPAdvancedFields>(defaultValues);

const value = useMemo(() => {
return { fields, setFields, defaultValues };
}, [fields, defaultValues]);

return <HTTPAdvancedFieldsContext.Provider value={value} children={children} />;
};
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

at the end you can export context as a hook, then you will not have to do useContext while consuming context

export const useHTTPAdvancedFieldsContext = () => useContext(HTTPAdvancedFieldsContext);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

if you want to further optimise context usage, i guess you can create even more context for state and dispatch actions
though will have to see how much value it will provide.
https://kentcdodds.com/blog/how-to-optimize-your-context-value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this is the example

import React from 'react'

const CountStateContext = React.createContext()
const CountUpdaterContext = React.createContext()

function CountProvider(props) {
  const [count, setCount] = React.useState(0)
  return (
    <CountStateContext.Provider value={count}>
      <CountUpdaterContext.Provider value={setCount}>
        {props.children}
      </CountUpdaterContext.Provider>
    </CountStateContext.Provider>
  )
}

function useCountState() {
  const countState = React.useContext(CountStateContext)
  if (typeof countState === 'undefined') {
    throw new Error('useCountState must be used within a CountProvider')
  }
  return countState
}

function useCountUpdater() {
  const setCount = React.useContext(CountUpdaterContext)
  if (typeof setCount === 'undefined') {
    throw new Error('useCountUpdater must be used within a CountProvider')
  }
  const increment = React.useCallback(() => setCount((c) => c + 1), [setCount])
  return increment
}

export {CountProvider, useCountState, useCountUpdater}


export const useHTTPAdvancedFieldsContext = () => useContext(HTTPAdvancedFieldsContext);
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React, { createContext, useContext, useMemo, useState } from 'react';
import { ITCPAdvancedFields, ConfigKeys } from '../types';

interface ITCPAdvancedFieldsContext {
setFields: React.Dispatch<React.SetStateAction<ITCPAdvancedFields>>;
fields: ITCPAdvancedFields;
defaultValues: ITCPAdvancedFields;
}

interface ITCPAdvancedFieldsContextProvider {
children: React.ReactNode;
defaultValues?: ITCPAdvancedFields;
}

export const initialValues = {
[ConfigKeys.PROXY_URL]: '',
[ConfigKeys.PROXY_USE_LOCAL_RESOLVER]: false,
[ConfigKeys.RESPONSE_RECEIVE_CHECK]: '',
[ConfigKeys.REQUEST_SEND_CHECK]: '',
};

const defaultContext: ITCPAdvancedFieldsContext = {
setFields: (_fields: React.SetStateAction<ITCPAdvancedFields>) => {
throw new Error('setFields was not initialized, set it when you invoke the context');
},
fields: initialValues, // mutable
defaultValues: initialValues, // immutable
};

export const TCPAdvancedFieldsContext = createContext(defaultContext);

export const TCPAdvancedFieldsContextProvider = ({
children,
defaultValues = initialValues,
}: ITCPAdvancedFieldsContextProvider) => {
const [fields, setFields] = useState<ITCPAdvancedFields>(defaultValues);

const value = useMemo(() => {
return { fields, setFields, defaultValues };
}, [fields, defaultValues]);

return <TCPAdvancedFieldsContext.Provider value={value} children={children} />;
};

export const useTCPAdvancedFieldsContext = () => useContext(TCPAdvancedFieldsContext);
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export {
SimpleFieldsContext,
SimpleFieldsContextProvider,
initialValues as defaultSimpleFields,
useSimpleFieldsContext,
} from './simple_fields_context';
export {
TCPAdvancedFieldsContext,
TCPAdvancedFieldsContextProvider,
initialValues as defaultTCPAdvancedFields,
useTCPAdvancedFieldsContext,
} from './advanced_fields_tcp_context';
export {
HTTPAdvancedFieldsContext,
HTTPAdvancedFieldsContextProvider,
initialValues as defaultHTTPAdvancedFields,
useHTTPAdvancedFieldsContext,
} from './advanced_fields_http_context';
export {
TLSFieldsContext,
TLSFieldsContextProvider,
initialValues as defaultTLSFields,
useTLSFieldsContext,
} from './tls_fields_context';
Loading