diff --git a/.bazelrc.common b/.bazelrc.common index 115c0214b1a53..3de2bceaad3a6 100644 --- a/.bazelrc.common +++ b/.bazelrc.common @@ -94,6 +94,12 @@ build --nolegacy_external_runfiles run --nolegacy_external_runfiles test --nolegacy_external_runfiles +# Runfiles should be enabled un order to use `exports_directories_only` in the yarn_install rule +# https://bazelbuild.github.io/rules_nodejs/Built-ins.html#yarn_install-exports_directories_only +build --enable_runfiles +run --enable_runfiles +test --enable_runfiles + # Turn on --incompatible_strict_action_env which was on by default # in Bazel 0.21.0 but turned off again in 0.22.0. Follow # https://github.com/bazelbuild/bazel/issues/7026 for more details. @@ -104,10 +110,11 @@ build --incompatible_strict_action_env run --incompatible_strict_action_env test --incompatible_strict_action_env +# DISABLED for now due to https://bazelbuild.github.io/rules_nodejs/Built-ins.html#yarn_install-exports_directories_only # Do not build runfile trees by default. If an execution strategy relies on runfile # symlink tree, the tree is created on-demand. See: https://github.com/bazelbuild/bazel/issues/6627 # and https://github.com/bazelbuild/bazel/commit/03246077f948f2790a83520e7dccc2625650e6df -build --nobuild_runfile_links +# build --nobuild_runfile_links # When running `bazel coverage` --instrument_test_targets needs to be set in order to # collect coverage information from test targets diff --git a/.node-version b/.node-version index 62df50f1eefe1..0a9f3027ffc44 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -14.17.0 +14.17.2 diff --git a/.nvmrc b/.nvmrc index 62df50f1eefe1..0a9f3027ffc44 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -14.17.0 +14.17.2 diff --git a/WORKSPACE.bazel b/WORKSPACE.bazel index ebf7bbc8488ac..f63eb0ed8a671 100644 --- a/WORKSPACE.bazel +++ b/WORKSPACE.bazel @@ -27,13 +27,13 @@ check_rules_nodejs_version(minimum_version_string = "3.6.0") # we can update that rule. node_repositories( node_repositories = { - "14.17.0-darwin_amd64": ("node-v14.17.0-darwin-x64.tar.gz", "node-v14.17.0-darwin-x64", "7b210652e11d1ee25650c164cf32381895e1dcb3e0ff1d0841d8abc1f47ac73e"), - "14.17.0-linux_arm64": ("node-v14.17.0-linux-arm64.tar.xz", "node-v14.17.0-linux-arm64", "712e5575cee20570a0a56f4d4b4572cb0f2ee2f4bce49433de18be0393e7df22"), - "14.17.0-linux_s390x": ("node-v14.17.0-linux-s390x.tar.xz", "node-v14.17.0-linux-s390x", "6419372b9e9ad37e0bce188dc5740f2f060aaa44454418e462b4088a310a1c0b"), - "14.17.0-linux_amd64": ("node-v14.17.0-linux-x64.tar.xz", "node-v14.17.0-linux-x64", "494b161759a3d19c70e3172d33ce1918dd8df9ad20d29d1652a8387a84e2d308"), - "14.17.0-windows_amd64": ("node-v14.17.0-win-x64.zip", "node-v14.17.0-win-x64", "6582a7259c433e9f667dcc4ed3e5d68bc514caba2eed40e4626c8b4c7e5ecd5c"), + "14.17.2-darwin_amd64": ("node-v14.17.2-darwin-x64.tar.gz", "node-v14.17.2-darwin-x64", "e45db91fc2136202868a5eb7c6d08b0a2b75394fafdf8538f650fa945b7dee16"), + "14.17.2-linux_arm64": ("node-v14.17.2-linux-arm64.tar.xz", "node-v14.17.2-linux-arm64", "3aff08c49b8c0c3443e7a9ea9bfe607867d79e6e5ccf204a5c8f13fb92a48abd"), + "14.17.2-linux_s390x": ("node-v14.17.2-linux-s390x.tar.xz", "node-v14.17.2-linux-s390x", "76f955856626a3e596b438855fdfe438937623dc71af9a25a8466409be470877"), + "14.17.2-linux_amd64": ("node-v14.17.2-linux-x64.tar.xz", "node-v14.17.2-linux-x64", "6cf9db7349407c177b36205feec949729d0ee9db485e19b10b0b1ffca65a3a46"), + "14.17.2-windows_amd64": ("node-v14.17.2-win-x64.zip", "node-v14.17.2-win-x64", "0e27897578752865fa61546d75b20f7cd62957726caab3c03f82c57a4aef5636"), }, - node_version = "14.17.0", + node_version = "14.17.2", node_urls = [ "https://nodejs.org/dist/v{version}/{filename}", ], @@ -59,6 +59,7 @@ yarn_install( "//:preinstall_check.js", "//:node_modules/.yarn-integrity", ], + exports_directories_only = True, symlink_node_modules = True, quiet = False, frozen_lockfile = False, diff --git a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddableeditorstate.md b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddableeditorstate.md index 63302f50204fe..b944c9dcc02a2 100644 --- a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddableeditorstate.md +++ b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddableeditorstate.md @@ -18,5 +18,6 @@ export interface EmbeddableEditorState | --- | --- | --- | | [embeddableId](./kibana-plugin-plugins-embeddable-public.embeddableeditorstate.embeddableid.md) | string | | | [originatingApp](./kibana-plugin-plugins-embeddable-public.embeddableeditorstate.originatingapp.md) | string | | +| [searchSessionId](./kibana-plugin-plugins-embeddable-public.embeddableeditorstate.searchsessionid.md) | string | Pass current search session id when navigating to an editor, Editors could use it continue previous search session | | [valueInput](./kibana-plugin-plugins-embeddable-public.embeddableeditorstate.valueinput.md) | EmbeddableInput | | diff --git a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddableeditorstate.searchsessionid.md b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddableeditorstate.searchsessionid.md new file mode 100644 index 0000000000000..815055fe9f55d --- /dev/null +++ b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddableeditorstate.searchsessionid.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-embeddable-public](./kibana-plugin-plugins-embeddable-public.md) > [EmbeddableEditorState](./kibana-plugin-plugins-embeddable-public.embeddableeditorstate.md) > [searchSessionId](./kibana-plugin-plugins-embeddable-public.embeddableeditorstate.searchsessionid.md) + +## EmbeddableEditorState.searchSessionId property + +Pass current search session id when navigating to an editor, Editors could use it continue previous search session + +Signature: + +```typescript +searchSessionId?: string; +``` diff --git a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddablepackagestate.md b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddablepackagestate.md index 1c0b1b8bf8b46..b3e851a6d0c30 100644 --- a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddablepackagestate.md +++ b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddablepackagestate.md @@ -18,5 +18,6 @@ export interface EmbeddablePackageState | --- | --- | --- | | [embeddableId](./kibana-plugin-plugins-embeddable-public.embeddablepackagestate.embeddableid.md) | string | | | [input](./kibana-plugin-plugins-embeddable-public.embeddablepackagestate.input.md) | Optional<EmbeddableInput, 'id'> | Optional<SavedObjectEmbeddableInput, 'id'> | | +| [searchSessionId](./kibana-plugin-plugins-embeddable-public.embeddablepackagestate.searchsessionid.md) | string | Pass current search session id when navigating to an editor, Editors could use it continue previous search session | | [type](./kibana-plugin-plugins-embeddable-public.embeddablepackagestate.type.md) | string | | diff --git a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddablepackagestate.searchsessionid.md b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddablepackagestate.searchsessionid.md new file mode 100644 index 0000000000000..3c515b1fb6674 --- /dev/null +++ b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.embeddablepackagestate.searchsessionid.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-embeddable-public](./kibana-plugin-plugins-embeddable-public.md) > [EmbeddablePackageState](./kibana-plugin-plugins-embeddable-public.embeddablepackagestate.md) > [searchSessionId](./kibana-plugin-plugins-embeddable-public.embeddablepackagestate.searchsessionid.md) + +## EmbeddablePackageState.searchSessionId property + +Pass current search session id when navigating to an editor, Editors could use it continue previous search session + +Signature: + +```typescript +searchSessionId?: string; +``` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.interpret.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.interpret.md index 46934e119aee0..434f2660e7eff 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.interpret.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.interpret.md @@ -7,7 +7,7 @@ Signature: ```typescript -interpret(ast: ExpressionAstNode, input: T): Observable; +interpret(ast: ExpressionAstNode, input: T): Observable>; ``` ## Parameters @@ -19,5 +19,5 @@ interpret(ast: ExpressionAstNode, input: T): Observable; Returns: -`Observable` +`Observable>` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.md index 30fe9f497f7ee..edaf1c9a9ce9e 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.md @@ -26,8 +26,8 @@ export declare class Executionstring | | | [input](./kibana-plugin-plugins-expressions-public.execution.input.md) | | Input | Initial input of the execution.N.B. It is initialized to null rather than undefined for legacy reasons, because in legacy interpreter it was set to null by default. | | [inspectorAdapters](./kibana-plugin-plugins-expressions-public.execution.inspectoradapters.md) | | InspectorAdapters | | -| [result](./kibana-plugin-plugins-expressions-public.execution.result.md) | | Observable<Output | ExpressionValueError> | Future that tracks result or error of this execution. | -| [state](./kibana-plugin-plugins-expressions-public.execution.state.md) | | ExecutionContainer<Output | ExpressionValueError> | Dynamic state of the execution. | +| [result](./kibana-plugin-plugins-expressions-public.execution.result.md) | | Observable<ExecutionResult<Output | ExpressionValueError>> | Future that tracks result or error of this execution. | +| [state](./kibana-plugin-plugins-expressions-public.execution.state.md) | | ExecutionContainer<ExecutionResult<Output | ExpressionValueError>> | Dynamic state of the execution. | ## Methods diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.result.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.result.md index 94f60ccee0f00..a386302a62805 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.result.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.result.md @@ -9,5 +9,5 @@ Future that tracks result or error of this execution. Signature: ```typescript -readonly result: Observable; +readonly result: Observable>; ``` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.start.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.start.md index 64cf81b376948..352226da6d72a 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.start.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.start.md @@ -11,7 +11,7 @@ N.B. `input` is initialized to `null` rather than `undefined` for legacy reasons Signature: ```typescript -start(input?: Input): Observable; +start(input?: Input): Observable>; ``` ## Parameters @@ -22,5 +22,5 @@ start(input?: Input): Observable; Returns: -`Observable` +`Observable>` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.state.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.state.md index ca8b57b760f29..61aa0cf4c5b5d 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.state.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.state.md @@ -9,5 +9,5 @@ Dynamic state of the execution. Signature: ```typescript -readonly state: ExecutionContainer; +readonly state: ExecutionContainer>; ``` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executioncontract.getdata.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executioncontract.getdata.md index dcd96cf5767bf..852e1f58cc6f3 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executioncontract.getdata.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executioncontract.getdata.md @@ -9,5 +9,5 @@ Returns the final output of expression, if any error happens still wraps that er Signature: ```typescript -getData: () => Promise; +getData: () => Observable>; ``` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executioncontract.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executioncontract.md index f2c050bbfe0ba..0ac776e4be2b8 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executioncontract.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executioncontract.md @@ -25,7 +25,7 @@ export declare class ExecutionContract() => void | Cancel the execution of the expression. This will set abort signal (available in execution context) to aborted state, letting expression functions to stop their execution. | | [execution](./kibana-plugin-plugins-expressions-public.executioncontract.execution.md) | | Execution<Input, Output, InspectorAdapters> | | | [getAst](./kibana-plugin-plugins-expressions-public.executioncontract.getast.md) | | () => ExpressionAstExpression | Get AST used to execute the expression. | -| [getData](./kibana-plugin-plugins-expressions-public.executioncontract.getdata.md) | | () => Promise<Output | ExpressionValueError> | Returns the final output of expression, if any error happens still wraps that error into ExpressionValueError type and returns that. This function never throws. | +| [getData](./kibana-plugin-plugins-expressions-public.executioncontract.getdata.md) | | () => Observable<ExecutionResult<Output | ExpressionValueError>> | Returns the final output of expression, if any error happens still wraps that error into ExpressionValueError type and returns that. This function never throws. | | [getExpression](./kibana-plugin-plugins-expressions-public.executioncontract.getexpression.md) | | () => string | Get string representation of the expression. Returns the original string if execution was started from a string. If execution was started from an AST this method returns a string generated from AST. | | [inspect](./kibana-plugin-plugins-expressions-public.executioncontract.inspect.md) | | () => InspectorAdapters | Get Inspector adapters provided to all functions of expression through execution context. | | [isPending](./kibana-plugin-plugins-expressions-public.executioncontract.ispending.md) | | boolean | | diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executor.run.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executor.run.md index 307e6b6bcd5c8..4eefc63d714d1 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executor.run.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.executor.run.md @@ -9,7 +9,7 @@ Execute expression and return result. Signature: ```typescript -run(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams): Observable; +run(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams): Observable>; ``` ## Parameters @@ -22,5 +22,5 @@ run(ast: string | ExpressionAstExpression, input: Input, params?: Returns: -`Observable` +`Observable>` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionsservicestart.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionsservicestart.md index 6b678fc4fbc26..9821f0f921e4d 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionsservicestart.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionsservicestart.md @@ -21,7 +21,7 @@ export interface ExpressionsServiceStart | [getFunction](./kibana-plugin-plugins-expressions-public.expressionsservicestart.getfunction.md) | (name: string) => ReturnType<Executor['getFunction']> | Get a registered ExpressionFunction by its name, which was registered using the registerFunction method. The returned ExpressionFunction instance is an internal representation of the function in Expressions service - do not mutate that object. | | [getRenderer](./kibana-plugin-plugins-expressions-public.expressionsservicestart.getrenderer.md) | (name: string) => ReturnType<ExpressionRendererRegistry['get']> | Get a registered ExpressionRenderer by its name, which was registered using the registerRenderer method. The returned ExpressionRenderer instance is an internal representation of the renderer in Expressions service - do not mutate that object. | | [getType](./kibana-plugin-plugins-expressions-public.expressionsservicestart.gettype.md) | (name: string) => ReturnType<Executor['getType']> | Get a registered ExpressionType by its name, which was registered using the registerType method. The returned ExpressionType instance is an internal representation of the type in Expressions service - do not mutate that object. | -| [run](./kibana-plugin-plugins-expressions-public.expressionsservicestart.run.md) | <Input, Output>(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams) => Promise<Output> | Executes expression string or a parsed expression AST and immediately returns the result.Below example will execute sleep 100 | clog expression with 123 initial input to the first function. +| [run](./kibana-plugin-plugins-expressions-public.expressionsservicestart.run.md) | <Input, Output>(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams) => Observable<ExecutionResult<Output | ExpressionValueError>> | Executes expression string or a parsed expression AST and immediately returns the result.Below example will execute sleep 100 | clog expression with 123 initial input to the first function. ```ts expressions.run('sleep 100 | clog', 123); diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionsservicestart.run.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionsservicestart.run.md index 9efca0011174c..0838d640d54e4 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionsservicestart.run.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionsservicestart.run.md @@ -24,5 +24,5 @@ expressions.run('...', null, { elasticsearchClient }); Signature: ```typescript -run: (ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams) => Promise; +run: (ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams) => Observable>; ``` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.md index 4ef1225ae0d7e..69f9d380422b6 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.md @@ -22,6 +22,7 @@ export interface IExpressionLoaderParams | [hasCompatibleActions](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.hascompatibleactions.md) | ExpressionRenderHandlerParams['hasCompatibleActions'] | | | [inspectorAdapters](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.inspectoradapters.md) | Adapters | | | [onRenderError](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.onrendererror.md) | RenderErrorHandlerFnType | | +| [partial](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.partial.md) | boolean | | | [renderMode](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.rendermode.md) | RenderMode | | | [searchContext](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.searchcontext.md) | SerializableState | | | [searchSessionId](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.searchsessionid.md) | string | | diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.partial.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.partial.md new file mode 100644 index 0000000000000..84c42c3f59f26 --- /dev/null +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.partial.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-expressions-public](./kibana-plugin-plugins-expressions-public.md) > [IExpressionLoaderParams](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.md) > [partial](./kibana-plugin-plugins-expressions-public.iexpressionloaderparams.partial.md) + +## IExpressionLoaderParams.partial property + +Signature: + +```typescript +partial?: boolean; +``` diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.md index 92ea071b23dfc..d38027753a6ff 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.md @@ -18,7 +18,7 @@ export interface ReactExpressionRendererProps extends IExpressionLoaderParams | [dataAttrs](./kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.dataattrs.md) | string[] | | | [debounce](./kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.debounce.md) | number | | | [expression](./kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.expression.md) | string | ExpressionAstExpression | | -| [onData$](./kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.ondata_.md) | <TData, TInspectorAdapters>(data: TData, adapters?: TInspectorAdapters) => void | | +| [onData$](./kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.ondata_.md) | <TData, TInspectorAdapters>(data: TData, adapters?: TInspectorAdapters, partial?: boolean) => void | | | [onEvent](./kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.onevent.md) | (event: ExpressionRendererEvent) => void | | | [padding](./kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.padding.md) | 'xs' | 's' | 'm' | 'l' | 'xl' | | | [reload$](./kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.reload_.md) | Observable<unknown> | An observable which can be used to re-run the expression without destroying the component | diff --git a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.ondata_.md b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.ondata_.md index 05ddb0b13a5be..47559d0f7653c 100644 --- a/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.ondata_.md +++ b/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.ondata_.md @@ -7,5 +7,5 @@ Signature: ```typescript -onData$?: (data: TData, adapters?: TInspectorAdapters) => void; +onData$?: (data: TData, adapters?: TInspectorAdapters, partial?: boolean) => void; ``` diff --git a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.interpret.md b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.interpret.md index 936e98be589a3..99804dd20841d 100644 --- a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.interpret.md +++ b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.interpret.md @@ -7,7 +7,7 @@ Signature: ```typescript -interpret(ast: ExpressionAstNode, input: T): Observable; +interpret(ast: ExpressionAstNode, input: T): Observable>; ``` ## Parameters @@ -19,5 +19,5 @@ interpret(ast: ExpressionAstNode, input: T): Observable; Returns: -`Observable` +`Observable>` diff --git a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.md b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.md index a4e324eef6674..47963e5e5ef46 100644 --- a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.md +++ b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.md @@ -26,8 +26,8 @@ export declare class Executionstring | | | [input](./kibana-plugin-plugins-expressions-server.execution.input.md) | | Input | Initial input of the execution.N.B. It is initialized to null rather than undefined for legacy reasons, because in legacy interpreter it was set to null by default. | | [inspectorAdapters](./kibana-plugin-plugins-expressions-server.execution.inspectoradapters.md) | | InspectorAdapters | | -| [result](./kibana-plugin-plugins-expressions-server.execution.result.md) | | Observable<Output | ExpressionValueError> | Future that tracks result or error of this execution. | -| [state](./kibana-plugin-plugins-expressions-server.execution.state.md) | | ExecutionContainer<Output | ExpressionValueError> | Dynamic state of the execution. | +| [result](./kibana-plugin-plugins-expressions-server.execution.result.md) | | Observable<ExecutionResult<Output | ExpressionValueError>> | Future that tracks result or error of this execution. | +| [state](./kibana-plugin-plugins-expressions-server.execution.state.md) | | ExecutionContainer<ExecutionResult<Output | ExpressionValueError>> | Dynamic state of the execution. | ## Methods diff --git a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.result.md b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.result.md index 06cf047ac4160..b3baac5be2fa3 100644 --- a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.result.md +++ b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.result.md @@ -9,5 +9,5 @@ Future that tracks result or error of this execution. Signature: ```typescript -readonly result: Observable; +readonly result: Observable>; ``` diff --git a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.start.md b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.start.md index dd0456ac09950..0eef7013cb3c6 100644 --- a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.start.md +++ b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.start.md @@ -11,7 +11,7 @@ N.B. `input` is initialized to `null` rather than `undefined` for legacy reasons Signature: ```typescript -start(input?: Input): Observable; +start(input?: Input): Observable>; ``` ## Parameters @@ -22,5 +22,5 @@ start(input?: Input): Observable; Returns: -`Observable` +`Observable>` diff --git a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.state.md b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.state.md index 41e7e693a1da4..b7c26e9dee85a 100644 --- a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.state.md +++ b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.execution.state.md @@ -9,5 +9,5 @@ Dynamic state of the execution. Signature: ```typescript -readonly state: ExecutionContainer; +readonly state: ExecutionContainer>; ``` diff --git a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.executor.run.md b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.executor.run.md index 2ab534eac2f3a..7b169d05dc31d 100644 --- a/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.executor.run.md +++ b/docs/development/plugins/expressions/server/kibana-plugin-plugins-expressions-server.executor.run.md @@ -9,7 +9,7 @@ Execute expression and return result. Signature: ```typescript -run(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams): Observable; +run(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams): Observable>; ``` ## Parameters @@ -22,5 +22,5 @@ run(ast: string | ExpressionAstExpression, input: Input, params?: Returns: -`Observable` +`Observable>` diff --git a/docs/maps/images/enable_filter_by_map_extent.png b/docs/maps/images/enable_filter_by_map_extent.png new file mode 100644 index 0000000000000..5132dc8f73dbe Binary files /dev/null and b/docs/maps/images/enable_filter_by_map_extent.png differ diff --git a/docs/maps/images/timeslider.gif b/docs/maps/images/timeslider.gif new file mode 100644 index 0000000000000..463adf9a9300d Binary files /dev/null and b/docs/maps/images/timeslider.gif differ diff --git a/docs/maps/index.asciidoc b/docs/maps/index.asciidoc index 20320c5a938c9..0922a4cc94c22 100644 --- a/docs/maps/index.asciidoc +++ b/docs/maps/index.asciidoc @@ -11,6 +11,7 @@ Create beautiful maps from your geographical data. With **Maps**, you can: * Build maps with multiple layers and indices. +* Animate spatial temporal data. * Upload GeoJSON. * Embed your map in dashboards. * Symbolize features using data values. @@ -39,6 +40,15 @@ Use multiple layers and indices to show all your data in a single map. Show how [role="screenshot"] image::maps/images/sample_data_ecommerce.png[] +[float] +=== Animate spatial temporal data +Data comes to life with animation. Hard to detect patterns in static data pop out with movement. Use time slider to animate your data and gain deeper insights. + +This animated map uses the time slider to show Portland buses over a period of 15 minutes. The routes come alive as the bus locations update with time. + +[role="screenshot"] +image::maps/images/timeslider.gif[] + [float] === Upload GeoJSON Use **Maps** to drag and drop your GeoJSON points, lines, and polygons into Elasticsearch, and then use them as layers in your map. diff --git a/docs/maps/search.asciidoc b/docs/maps/search.asciidoc index 031c7be077f52..ada7551f3e57d 100644 --- a/docs/maps/search.asciidoc +++ b/docs/maps/search.asciidoc @@ -8,7 +8,8 @@ Layers that request data from {es} are narrowed when you submit a <> with a configured time field are narrowed by the <>. -Layers narrowed by the time filter contain the clock icon image:maps/images/clock_icon.png[] next to the layer name in the legend. +These layers contain the clock icon image:maps/images/clock_icon.png[clock icon] next to the layer name in the legend. Use the time slider to quickly select time slices within the global time filter range. +Click previous and next buttons to advance the time slice backward or forward. Click play to animate your spatial temporal data. You can create a layer that requests data from {es} from the following: @@ -35,13 +36,30 @@ image::maps/images/global_search_bar.png[] [[maps-create-filter-from-map]] === Create filters from a map -You can create two types of filters by interacting with your map: +Create filters from your map to focus in on just the data you want. *Maps* provides three ways to create filters: -* <> -* <> +* <> +* <> +* <> + +[float] +[[maps-map-extent-filter]] +==== Filter dashboard by map extent + +A map extent shows uniform data across all panels. +As you pan and zoom your map, all panels will update to only include data that is visable in your map. + +To enable filtering your dashboard by map extent: + +* Open the main menu, and then click *Dashboard*. +* Select your dashboard from the list or click *Create dashboard*. +* If your dashboard does not have a map, add a map panel. +* Click the gear icon image:maps/images/gear_icon.png[gear icon] to open the map panel menu. +* Select *More* to view all panel options. +* Select *Enable filter by map extent*. [role="screenshot"] -image::maps/images/create_spatial_filter.png[] +image::maps/images/enable_filter_by_map_extent.png[] [float] [[maps-spatial-filters]] @@ -57,10 +75,12 @@ You can create spatial filters in two ways: Spatial filters have the following properties: * *Geometry label* enables you to provide a meaningful name for your spatial filter. -* *Spatial field* specifies the geo_point or geo_shape field used to determine if a document matches the spatial relation with the specified geometry. * *Spatial relation* determines the {ref}/query-dsl-geo-shape-query.html#_spatial_relations[spatial relation operator] to use at search time. * *Action* specifies whether to apply the filter to the current view or to a drilldown action. Only available when the map is a panel in a {kibana-ref}/dashboard.html[dashboard] with {kibana-ref}/drilldowns.html[drilldowns]. +[role="screenshot"] +image::maps/images/create_spatial_filter.png[] + [float] [[maps-phrase-filter]] ==== Phrase filters diff --git a/docs/user/dashboard/dashboard.asciidoc b/docs/user/dashboard/dashboard.asciidoc index af67b3016454b..516f4c66d47bb 100644 --- a/docs/user/dashboard/dashboard.asciidoc +++ b/docs/user/dashboard/dashboard.asciidoc @@ -27,12 +27,12 @@ Panels display your data in charts, tables, maps, and more, which allow you to c | Display the results from machine learning anomaly detection jobs. | <> -| Display an anomaly chart from the *Anomaly Explorer. +| Display an anomaly chart from the *Anomaly Explorer*. | <> | Display a table of live streaming logs. -| <> +| <> | Add context to your panels with <>, or add dynamic filters with <>. |=== @@ -131,6 +131,38 @@ If you change your mind and want to add the panel to the *Visualize Library*: . Enter the panel title, then click *Save*. +[float] +[[add-text]] +== Add context to panels + +To provide context to your dashboard panels, add *Text* panels that display important information, instructions, images, and more. + +You create *Text* panels using GitHub-flavored Markdown text. For information about GitHub-flavored Markdown text, click *Help*. + +. From the dashboard, click *All types*, then select *Text*. + +. In the *Markdown* field, enter the text, then click *Update*. + +For example, when you enter: + +[role="screenshot"] +image::images/markdown_example_1.png[] + +The following instructions are displayed: + +[role="screenshot"] +image::images/markdown_example_2.png[] + +Or when you enter: + +[role="screenshot"] +image::images/markdown_example_3.png[] + +The following image is displayed: + +[role="screenshot"] +image::images/markdown_example_4.png[] + [float] [[edit-panels]] == Edit panels @@ -316,8 +348,6 @@ include::lens-advanced.asciidoc[] include::create-panels-with-editors.asciidoc[] -include::enhance-dashboards.asciidoc[] - -include::drilldowns.asciidoc[] +include::make-dashboards-interactive.asciidoc[] include::aggregation-reference.asciidoc[] diff --git a/docs/user/dashboard/enhance-dashboards.asciidoc b/docs/user/dashboard/enhance-dashboards.asciidoc index c999ec9b68251..de8af34e6d32e 100644 --- a/docs/user/dashboard/enhance-dashboards.asciidoc +++ b/docs/user/dashboard/enhance-dashboards.asciidoc @@ -8,7 +8,7 @@ To make your dashboard look the way you want, use the editing options. [[add-controls]] === Add controls -To filter the data on your dashboard in real-time, add a *Controls* panel. +To filter the data on your dashboard in real-time, add a *Controls* panel or use a map panel to <>. {kib} supports two types of *Controls*: diff --git a/docs/user/dashboard/images/drilldown_on_data_table.gif b/docs/user/dashboard/images/drilldown_on_data_table.gif new file mode 100644 index 0000000000000..926b0ff43aea6 Binary files /dev/null and b/docs/user/dashboard/images/drilldown_on_data_table.gif differ diff --git a/docs/user/dashboard/images/drilldown_on_panel.png b/docs/user/dashboard/images/drilldown_on_panel.png index 591f3280c7eca..71b83ae457062 100644 Binary files a/docs/user/dashboard/images/drilldown_on_panel.png and b/docs/user/dashboard/images/drilldown_on_panel.png differ diff --git a/docs/user/dashboard/make-dashboards-interactive.asciidoc b/docs/user/dashboard/make-dashboards-interactive.asciidoc new file mode 100644 index 0000000000000..3c2397d0241bb --- /dev/null +++ b/docs/user/dashboard/make-dashboards-interactive.asciidoc @@ -0,0 +1,241 @@ +[[role="xpack"]] +[[drilldowns]] +== Make dashboards interactive + +:keywords: administrator, analyst, concept, task, analyze, dashboard, controls, drilldowns +:description: Add interactive capabilities to your dashboard, such as controls that allow \ +you to apply dashboard-level filters, and drilldowns that allow you to navigate to other \ +dashboards and external websites. + +Add interactive capabilities to your dashboard, such as controls that allow you to apply dashboard-level filters, and drilldowns that allow you to navigate to other dashboards and external websites. + +*Controls* panels allow you to apply dashboard-level filters based on values from a list, or a range of values. + +{kib} supports two types of *Controls*: + +* *Options list* — Filters content based on one or more specified options. The dropdown menu is dynamically populated with the results of a terms aggregation. +For example, use the options list on the sample flight dashboard when you want to filter the data by origin city and destination city. + +* *Range slider* — Filters data within a specified range of numbers. The minimum and maximum values are dynamically populated with the results of a +min and max aggregation. For example, use the range slider when you want to filter the sample flight dashboard by a specific average ticket price. ++ +[role="screenshot"] +image::images/dashboard-controls.png[] + +Panels have built-in interactive capabilities that apply filters to the dashboard data. For example, when you drag a time range or click a pie slice, a filter for the time range or pie slice is applied. Drilldowns let you customize the interactive behavior while keeping the context of the interaction. + +{kib} supports two types of drilldowns: + +* *Dashboard* — Navigates you from one dashboard to another dashboard. For example, when can create a drilldown for a *Lens* panel that navigates you from a summary dashboard to a dashboard with a filter for a specific host name. + +* *URL* — Navigates you from a dashboard to an external website. For example, a website with the specific host name as a parameter. + +++++ + + +
+++++ + +Third-party developers can create drilldowns. To learn how to code drilldowns, refer to {kib-repo}blob/{branch}/x-pack/examples/ui_actions_enhanced_examples[this example plugin]. + +[float] +[[add-controls]] +=== Add Controls panels + +Add interactive dashboard-level filter panels to your dashboard. + +. On the dashboard, click *All types*, then select *Controls*. + +. Click *Options*, then configure the following options: + +* *Update {kib} filters on each change* — When selected, all interactive inputs create filters that refresh the dashboard. When unselected, + {kib} filters are created only when you click *Apply changes*. + +* *Use time filter* — When selected, the aggregations that generate the options list and time range are connected to the <>. + +* *Pin filters for all applications* — When selected, all filters created by interacting with the inputs are automatically pinned. + +. Click *Update* + +[float] +[[dashboard-drilldowns]] +=== Create dashboard drilldowns + +Dashboard drilldowns enable you to open a dashboard from another dashboard, taking the time range, filters, and other parameters with you so the context remains the same. Dashboard drilldowns help you to continue your analysis from a new perspective. + +For example, if you have a dashboard that shows the logs and metrics for multiple data centers, you can create a drilldown that navigates from the dashboard that shows multiple data centers, to a dashboard that shows a single data center or server. + +[role="screenshot"] +image:images/drilldown_on_data_table.gif[Drilldown on data table that navigates to another dashboard] + +The panels you create using the following editors support dashboard drilldowns: + +* *Lens* +* *Maps* +* *TSVB* +* *Vega* +* *Aggregation-based* area chart, data table, heat map, horitizontal bar chart, line chart, pie chart, tag cloud, and vertical bar chart +* *Timelion* + +[float] +==== Create and set up the dashboards you want to connect + +Use the <> data to create a dashboard and add panels, then set a search and filter on the *[Logs] Web traffic* dashboard. + +. Add the *Sample web logs* data. + +. Create a new dashboard, click *Add from Library*, then add the following panels: + +* *[Logs] Heatmap* +* *[Logs] Host, Visits, and Bytes Table* +* *[Logs] Total Requests and Bytes* +* *[Logs] Visitors by OS* + +. Set the <> to *Last 30 days*. + +. Save the dashboard. In the *Title* field, enter `Host Overview`. + +. Open the *[Logs] Web traffic* dashboard. + +. Create a data table. + +.. In the toolbar, click *Edit*. + +.. Click *Create visualization*. + +.. From the *Chart type* dropdown, select *Table*. + +.. From the *Available fields* list, drag and drop the following fields onto the visualization builder: + +* *agent.keyword* + +* *bytes* + +* *geo.src* + +* *ip* + +.. In the editor, remove *Count of records*, then click *Save and return*. + +. On the *[Logs] Web traffic* dashboard, set a search and filter. ++ +[%hardbreaks] +Search: `extension.keyword: ("gz" or "css" or "deb")` +Filter: `geo.src: CN` + +[float] +==== Create the drilldown + +Create a drilldown that opens the *Host Overview* dashboard from the *[Logs] Web traffic* dashboard. + +. Open the panel menu for the data table you created, then select *Create drilldown*. + +. Click *Go to dashboard*. + +.. Give the drilldown a name. For example, `My Drilldown`. + +.. From the *Choose a destination dashboard* dropdown, select *Host Overview*. + +.. To use the geo.src filter, KQL query, and time filter, select *Use filters and query from origin dashboard* and *Use date range from origin dashboard*. + +.. Click *Create drilldown*. + +. Save the dashboard. + +. In the data table panel, hover over a value, click *+*, then select `My Drilldown`. ++ +[role="screenshot"] +image::images/drilldown_on_panel.png[Drilldown on data table that navigates to another dashboard] + +[float] +[[url-drilldowns]] +=== Create URL drilldowns + +URL drilldowns enable you to navigate from a dashboard to external websites. Destination URLs can be dynamic, depending on the dashboard context or user interaction with a panel. To create URL drilldowns, you add <> to a URL template, which configures the behavior of the drilldown. + +[role="screenshot"] +image:images/url_drilldown_go_to_github.gif[Drilldown on pie chart that navigates to Github] + +Some panels support multiple interactions, also known as triggers. +The <> you use to create a <> depends on the trigger you choose. URL drilldowns support these types of triggers: + +* *Single click* — A single data point in the panel. + +* *Range selection* — A range of values in a panel. + +For example, *Single click* has `{{event.value}}` and *Range selection* has `{{event.from}}` and `{{event.to}}`. + +The panels you create using the following editors support dashboard drilldowns: + +* *Lens* +* *Maps* +* *TSVB* +* *Aggregation-based* area chart, data table, heat map, horitizontal bar chart, line chart, pie chart, tag cloud, and vertical bar chart + +[float] +==== Create a URL drilldown + +For example, if you have a dashboard that shows data from a Github repository, you can create a URL drilldown that opens Github from the dashboard panel. + +. Add the *Sample web logs* data. + +. Open the *[Logs] Web traffic* dashboard. + +. In the toolbar, click *Edit*. + +. Open the *[Logs] Visitors by OS* panel menu, then select *Create drilldown*. + +. Click *Go to URL*. + +.. Give the drilldown a name. For example, `Show on Github`. + +.. For the *Trigger*, select *Single click*. + +.. To navigate to the {kib} repository Github issues, enter the following in the *Enter URL* field: ++ +[source, bash] +---- +https://github.com/elastic/kibana/issues?q=is:issue+is:open+{{event.value}} +---- ++ +{kib} substitutes `{{event.value}}` with a value associated with the selected pie slice. + +.. Click *Create drilldown*. + +. Save the dashboard. + +. On the *[Logs] Visitors by OS* panel, click any chart slice, then select *Show on Github*. ++ +[role="screenshot"] +image:images/url_drilldown_popup.png[URL drilldown popup] + +. In the list of {kib} repository issues, verify that the slice value appears. ++ +[role="screenshot"] +image:images/url_drilldown_github.png[Github] + +[float] +[[manage-drilldowns]] +=== Manage drilldowns + +Make changes to your drilldowns, make a copy of your drilldowns for another panel, and delete drilldowns. + +. Open the panel menu that includes the drilldown, then click *Manage drilldowns*. + +. On the *Manage* tab, use the following options: + +* To change drilldowns, click *Edit* next to the drilldown you want to change, make your changes, then click *Save*. + +* To make a copy, click *Copy* next to the drilldown you want to change, enter the drilldown name, then click *Create drilldown*. + +* To delete a drilldown, select the drilldown you want to delete, then click *Delete*. + +include::url-drilldown.asciidoc[] diff --git a/examples/expressions_explorer/public/run_expressions.tsx b/examples/expressions_explorer/public/run_expressions.tsx index 05749a0e89735..a635fab7ec8ae 100644 --- a/examples/expressions_explorer/public/run_expressions.tsx +++ b/examples/expressions_explorer/public/run_expressions.tsx @@ -7,6 +7,7 @@ */ import React, { useState, useEffect, useMemo } from 'react'; +import { pluck } from 'rxjs/operators'; import { EuiCodeBlock, EuiFlexItem, @@ -35,7 +36,7 @@ interface Props { export function RunExpressionsExample({ expressions, inspector }: Props) { const [expression, updateExpression] = useState('markdown "## expressions explorer"'); - const [result, updateResult] = useState({}); + const [result, updateResult] = useState({}); const expressionChanged = (value: string) => { updateExpression(value); @@ -49,17 +50,13 @@ export function RunExpressionsExample({ expressions, inspector }: Props) { ); useEffect(() => { - const runExpression = async () => { - const execution = expressions.execute(expression, null, { - debug: true, - inspectorAdapters, - }); + const execution = expressions.execute(expression, null, { + debug: true, + inspectorAdapters, + }); + const subscription = execution.getData().pipe(pluck('result')).subscribe(updateResult); - const data: any = await execution.getData(); - updateResult(data); - }; - - runExpression(); + return () => subscription.unsubscribe(); }, [expression, expressions, inspectorAdapters]); return ( diff --git a/package.json b/package.json index 1cc379fb807d0..de7df7fea3d8d 100644 --- a/package.json +++ b/package.json @@ -93,7 +93,7 @@ "**/underscore": "^1.13.1" }, "engines": { - "node": "14.17.0", + "node": "14.17.2", "yarn": "^1.21.1" }, "dependencies": { diff --git a/packages/kbn-i18n/GUIDELINE.md b/packages/kbn-i18n/GUIDELINE.md index 437e73bb27019..806e799bd1106 100644 --- a/packages/kbn-i18n/GUIDELINE.md +++ b/packages/kbn-i18n/GUIDELINE.md @@ -19,6 +19,7 @@ Ids should end with: - ErrorMessage (if it's an error message), - LinkText (if it's `` tag), - ToggleSwitch and etc. +- `.markdown` (if it's markdown) There is one more complex case, when we have to divide a single expression into different labels. @@ -110,7 +111,7 @@ Currently, we support the following AngluarJS `i18n` tools, but they will be rem ### Naming convention The message ids chosen for message keys should always be descriptive of the string, and its role in the interface (button label, title, etc.). Think of them as long variable names. When you have to change a message id, adding a progressive number to the existing key should always be used as a last resort. -Here's a rule of id maning: +Here's a rule of id naming: `{plugin}.{area}.[{sub-area}].{element}` @@ -138,6 +139,7 @@ Here's a rule of id maning: 'kbn.management.createIndexPattern.includeSystemIndicesToggleSwitch' 'kbn.management.editIndexPattern.wrongTypeErrorMessage' 'kbn.management.editIndexPattern.scripted.table.nameDescription' + 'xpack.lens.formulaDocumentation.filterRatioDescription.markdown' ``` - For complex messages, which are divided into several parts, use the following approach: @@ -192,6 +194,7 @@ Each message id should end with a type of the message. | tooltip | `kbn.management.editIndexPattern.removeTooltip` | | error message | `kbn.management.createIndexPattern.step.invalidCharactersErrorMessage` | | toggleSwitch | `kbn.management.createIndexPattern.includeSystemIndicesToggleSwitch` | +| markdown | `xpack.lens.formulaDocumentation.filterRatioDescription.markdown` | For example: @@ -281,6 +284,27 @@ For example: /> ``` +- for markdown + ```js + import { Markdown } from '@elastic/eui'; + + + ``` + ### Variety of `values` - Variables @@ -372,6 +396,82 @@ Here is an example of message translation depending on a plural category: When `conflictFieldsLength` equals 1, the result string will be `"A field is defined as several types (string, integer, etc) across the indices that match this pattern."`. In cases when `conflictFieldsLength` has value of 2 or more, the result string - `"2 fields are defined as several types (string, integer, etc) across the indices that match this pattern."`. +### Text with markdown + +There is some support for using markdown and you can use any of the following syntax: + +#### Headers + +```md +# This is an

tag +## This is an

tag +###### This is an

tag +``` + +#### Emphasis + +```md +*This text will be italic* +_This will also be italic_ + +**This text will be bold** +__This will also be bold__ + +_You **can** combine them_ +``` + +#### Lists + ##### Unordered + +```md +* Item 1 +* Item 2 + * Item 2a + * Item 2b +``` + ##### Ordered + +```md +1. Item 1 +1. Item 2 +1. Item 3 + 1. Item 3a + 1. Item 3b +``` +#### Images + +```md +![Github Logo](/images/logo.png) +Format: ![Alt Text](url) +``` + +#### Links + +```md +http://github.com - automatic! +[GitHub](http://github.com) +``` + +#### Blockquotes + +```md +As Kanye West said: + +> We're living the future so +> the present is our past. +``` +#### Code Blocks + +```md +var a = 13; +``` + +#### Inline code + +```md +I think you should use an +`` element here instead +``` ### Splitting Splitting sentences into several keys often inadvertently presumes a grammar, a sentence structure, and such composite strings are often very difficult to translate. @@ -385,6 +485,12 @@ Splitting sentences into several keys often inadvertently presumes a grammar, a If this group of sentences is separated it’s possible that the context of the `'it'` in `'close it'` will be lost. +### Large paragraphs + +Try to avoid using large paragraphs of text. They are difficult to maintain and often need small changes when the information becomes out of date. + +If you have no other choice, you can split paragraphs into a _few_ i18n chunks. Chunks should be split at logical points to ensure they contain enough context to be intelligible on their own. + ### Unit tests #### How to test `FormattedMessage` and `i18n.translate()` components. diff --git a/src/plugins/dashboard/public/application/dashboard_app.tsx b/src/plugins/dashboard/public/application/dashboard_app.tsx index 8db6a0e8a8c7f..638b1c83e9dc6 100644 --- a/src/plugins/dashboard/public/application/dashboard_app.tsx +++ b/src/plugins/dashboard/public/application/dashboard_app.tsx @@ -40,6 +40,7 @@ export function DashboardApp({ embeddable, onAppLeave, uiSettings, + data, } = useKibana().services; const kbnUrlStateStorage = useMemo( @@ -98,6 +99,13 @@ export function DashboardApp({ ]); }, [chrome, dashboardState.title, dashboardState.viewMode, redirectTo, savedDashboardId]); + // clear search session when leaving dashboard route + useEffect(() => { + return () => { + data.search.session.clear(); + }; + }, [data.search.session]); + return ( <> {isCompleteDashboardAppState(dashboardAppState) && ( diff --git a/src/plugins/dashboard/public/application/dashboard_router.tsx b/src/plugins/dashboard/public/application/dashboard_router.tsx index e77353000ced4..cb40b30542869 100644 --- a/src/plugins/dashboard/public/application/dashboard_router.tsx +++ b/src/plugins/dashboard/public/application/dashboard_router.tsx @@ -260,6 +260,7 @@ export async function mountApp({ } render(app, element); return () => { + dataStart.search.session.clear(); unlistenParentHistory(); unmountComponentAtNode(element); appUnMounted(); diff --git a/src/plugins/dashboard/public/application/lib/build_dashboard_container.ts b/src/plugins/dashboard/public/application/lib/build_dashboard_container.ts index cb8c5ac5745e4..8b895d739e2d1 100644 --- a/src/plugins/dashboard/public/application/lib/build_dashboard_container.ts +++ b/src/plugins/dashboard/public/application/lib/build_dashboard_container.ts @@ -64,6 +64,11 @@ export const buildDashboardContainer = async ({ getLatestDashboardState, canStoreSearchSession: dashboardCapabilities.storeSearchSession, }); + + if (incomingEmbeddable?.searchSessionId) { + session.continue(incomingEmbeddable?.searchSessionId); + } + const searchSessionIdFromURL = getSearchSessionIdFromURL(history); if (searchSessionIdFromURL) { session.restore(searchSessionIdFromURL); diff --git a/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx b/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx index 5557bf25d9d85..7f72c77009cb9 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx +++ b/src/plugins/dashboard/public/application/listing/dashboard_listing.tsx @@ -87,11 +87,6 @@ export const DashboardListing = ({ }; }, [title, savedObjectsClient, redirectTo, data.query, kbnUrlStateStorage]); - // clear dangling session because they are not required here - useEffect(() => { - data.search.session.clear(); - }, [data.search.session]); - const hideWriteControls = dashboardCapabilities.hideWriteControls; const listingLimit = savedObjects.settings.getListingLimit(); const defaultFilter = title ? `"${title}"` : ''; diff --git a/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx b/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx index e5f89bd6a8e90..dab74373efef5 100644 --- a/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx +++ b/src/plugins/dashboard/public/application/top_nav/dashboard_top_nav.tsx @@ -204,10 +204,11 @@ export function DashboardTopNav({ path, state: { originatingApp: DashboardConstants.DASHBOARDS_ID, + searchSessionId: data.search.session.getSessionId(), }, }); }, - [trackUiMetric, stateTransferService] + [stateTransferService, data.search.session, trackUiMetric] ); const clearAddPanel = useCallback(() => { diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 35094fac1cc0f..66d81d058fc77 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -2783,7 +2783,7 @@ export interface WaitUntilNextSessionCompletesOptions { // src/plugins/data/public/index.ts:433:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:436:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // src/plugins/data/public/query/state_sync/connect_to_query_state.ts:34:5 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/search/session/session_service.ts:56:5 - (ae-forgotten-export) The symbol "UrlGeneratorStateMapping" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/search/session/session_service.ts:62:5 - (ae-forgotten-export) The symbol "UrlGeneratorStateMapping" needs to be exported by the entry point index.d.ts // (No @packageDocumentation comment for this package) diff --git a/src/plugins/data/public/search/session/mocks.ts b/src/plugins/data/public/search/session/mocks.ts index 18d32463864e3..dee0216530205 100644 --- a/src/plugins/data/public/search/session/mocks.ts +++ b/src/plugins/data/public/search/session/mocks.ts @@ -47,5 +47,6 @@ export function getSessionServiceMock(): jest.Mocked { isSessionStorageReady: jest.fn(() => true), getSearchSessionIndicatorUiConfig: jest.fn(() => ({ isDisabled: () => ({ disabled: false }) })), hasAccess: jest.fn(() => true), + continue: jest.fn(), }; } diff --git a/src/plugins/data/public/search/session/session_service.test.ts b/src/plugins/data/public/search/session/session_service.test.ts index 7f388a29cd454..c2c4d1540c387 100644 --- a/src/plugins/data/public/search/session/session_service.test.ts +++ b/src/plugins/data/public/search/session/session_service.test.ts @@ -98,12 +98,12 @@ describe('Session service', () => { expect(nowProvider.reset).toHaveBeenCalled(); }); - it("Can clear other apps' session", async () => { + it("Can't clear other apps' session", async () => { sessionService.start(); expect(sessionService.getSessionId()).not.toBeUndefined(); currentAppId$.next('change'); sessionService.clear(); - expect(sessionService.getSessionId()).toBeUndefined(); + expect(sessionService.getSessionId()).not.toBeUndefined(); }); it("Can start a new session in case there is other apps' stale session", async () => { @@ -161,6 +161,72 @@ describe('Session service', () => { }); }); + it('Can continue previous session from another app', async () => { + sessionService.start(); + const sessionId = sessionService.getSessionId(); + + sessionService.clear(); + currentAppId$.next('change'); + sessionService.continue(sessionId!); + + expect(sessionService.getSessionId()).toBe(sessionId); + }); + + it('Calling clear() more than once still allows previous session from another app to continue', async () => { + sessionService.start(); + const sessionId = sessionService.getSessionId(); + + sessionService.clear(); + sessionService.clear(); + + currentAppId$.next('change'); + sessionService.continue(sessionId!); + + expect(sessionService.getSessionId()).toBe(sessionId); + }); + + it('Continue drops storage configuration', () => { + sessionService.start(); + const sessionId = sessionService.getSessionId(); + + sessionService.enableStorage({ + getName: async () => 'Name', + getUrlGeneratorData: async () => ({ + urlGeneratorId: 'id', + initialState: {}, + restoreState: {}, + }), + }); + + expect(sessionService.isSessionStorageReady()).toBe(true); + + sessionService.clear(); + + sessionService.continue(sessionId!); + + expect(sessionService.isSessionStorageReady()).toBe(false); + }); + + // it might be that search requests finish after the session is cleared and before it was continued, + // to avoid "infinite loading" state after we continue the session we have to drop pending searches + it('Continue drops client side loading state', async () => { + const sessionId = sessionService.start(); + + sessionService.trackSearch({ abort: () => {} }); + expect(state$.getValue()).toBe(SearchSessionState.Loading); + + sessionService.clear(); // even allow to call clear multiple times + + expect(state$.getValue()).toBe(SearchSessionState.None); + + sessionService.continue(sessionId!); + expect(sessionService.getSessionId()).toBe(sessionId); + + // the original search was never `untracked`, + // but we still consider this a completed session until new search fire + expect(state$.getValue()).toBe(SearchSessionState.Completed); + }); + test('getSearchOptions infers isRestore & isStored from state', async () => { const sessionId = sessionService.start(); const someOtherId = 'some-other-id'; diff --git a/src/plugins/data/public/search/session/session_service.ts b/src/plugins/data/public/search/session/session_service.ts index 629d76b07d7ca..32cd620a2adb2 100644 --- a/src/plugins/data/public/search/session/session_service.ts +++ b/src/plugins/data/public/search/session/session_service.ts @@ -20,6 +20,7 @@ import { ConfigSchema } from '../../../config'; import { createSessionStateContainer, SearchSessionState, + SessionStateInternal, SessionMeta, SessionStateContainer, } from './search_session_state'; @@ -35,6 +36,11 @@ export interface TrackSearchDescriptor { abort: () => void; } +/** + * Represents a search session state in {@link SessionService} in any given moment of time + */ +export type SessionSnapshot = SessionStateInternal; + /** * Provide info about current search session to be stored in the Search Session saved object */ @@ -88,6 +94,13 @@ export class SessionService { private toastService?: ToastService; + /** + * Holds snapshot of last cleared session so that it can be continued + * Can be used to re-use a session between apps + * @private + */ + private lastSessionSnapshot?: SessionSnapshot; + constructor( initializerContext: PluginInitializerContext, getStartServices: StartServicesAccessor, @@ -128,6 +141,21 @@ export class SessionService { this.subscription.add( coreStart.application.currentAppId$.subscribe((newAppName) => { this.currentApp = newAppName; + if (!this.getSessionId()) return; + + // Apps required to clean up their sessions before unmounting + // Make sure that apps don't leave sessions open by throwing an error in DEV mode + const message = `Application '${ + this.state.get().appName + }' had an open session while navigating`; + if (initializerContext.env.mode.dev) { + coreStart.fatalErrors.add(message); + } else { + // this should never happen in prod because should be caught in dev mode + // in case this happen we don't want to throw fatal error, as most likely possible bugs are not that critical + // eslint-disable-next-line no-console + console.warn(message); + } }) ); }); @@ -158,6 +186,7 @@ export class SessionService { public destroy() { this.subscription.unsubscribe(); this.clear(); + this.lastSessionSnapshot = undefined; } /** @@ -198,7 +227,9 @@ export class SessionService { */ public start() { if (!this.currentApp) throw new Error('this.currentApp is missing'); + this.state.transitions.start({ appName: this.currentApp }); + return this.getSessionId()!; } @@ -211,10 +242,52 @@ export class SessionService { this.refreshSearchSessionSavedObject(); } + /** + * Continue previous search session + * Can be used to share a running search session between different apps, so they can reuse search cache + * + * This is different from {@link restore} as it reuses search session state and search results held in client memory instead of restoring search results from elasticsearch + * @param sessionId + */ + public continue(sessionId: string) { + if (this.lastSessionSnapshot?.sessionId === sessionId) { + this.state.set({ + ...this.lastSessionSnapshot, + // have to change a name, so that current app can cancel a session that it continues + appName: this.currentApp, + // also have to drop all pending searches which are used to derive client side state of search session indicator, + // if we weren't dropping this searches, then we would get into "infinite loading" state when continuing a session that was cleared with pending searches + // possible solution to this problem is to refactor session service to support multiple sessions + pendingSearches: [], + }); + this.lastSessionSnapshot = undefined; + } else { + // eslint-disable-next-line no-console + console.warn( + `Continue search session: last known search session id: "${this.lastSessionSnapshot?.sessionId}", but received ${sessionId}` + ); + } + } + /** * Cleans up current state */ public clear() { + // make sure apps can't clear other apps' sessions + const currentSessionApp = this.state.get().appName; + if (currentSessionApp && currentSessionApp !== this.currentApp) { + // eslint-disable-next-line no-console + console.warn( + `Skip clearing session "${this.getSessionId()}" because it belongs to a different app. current: "${ + this.currentApp + }", owner: "${currentSessionApp}"` + ); + return; + } + + if (this.getSessionId()) { + this.lastSessionSnapshot = this.state.get(); + } this.state.transitions.clear(); this.searchSessionInfoProvider = undefined; this.searchSessionIndicatorUiConfig = undefined; diff --git a/src/plugins/embeddable/public/lib/actions/edit_panel_action.ts b/src/plugins/embeddable/public/lib/actions/edit_panel_action.ts index 058fd832e15db..ea90307ef57a1 100644 --- a/src/plugins/embeddable/public/lib/actions/edit_panel_action.ts +++ b/src/plugins/embeddable/public/lib/actions/edit_panel_action.ts @@ -111,6 +111,7 @@ export class EditPanelAction implements Action { originatingApp: this.currentAppId, valueInput: byValueMode ? this.getExplicitInput({ embeddable }) : undefined, embeddableId: embeddable.id, + searchSessionId: embeddable.getInput().searchSessionId, }; return { app, path, state }; } diff --git a/src/plugins/embeddable/public/lib/state_transfer/types.ts b/src/plugins/embeddable/public/lib/state_transfer/types.ts index 5e5ef9c360a64..98cf6e70284cd 100644 --- a/src/plugins/embeddable/public/lib/state_transfer/types.ts +++ b/src/plugins/embeddable/public/lib/state_transfer/types.ts @@ -19,6 +19,12 @@ export interface EmbeddableEditorState { originatingApp: string; embeddableId?: string; valueInput?: EmbeddableInput; + + /** + * Pass current search session id when navigating to an editor, + * Editors could use it continue previous search session + */ + searchSessionId?: string; } export function isEmbeddableEditorState(state: unknown): state is EmbeddableEditorState { @@ -35,6 +41,12 @@ export interface EmbeddablePackageState { type: string; input: Optional | Optional; embeddableId?: string; + + /** + * Pass current search session id when navigating to an editor, + * Editors could use it continue previous search session + */ + searchSessionId?: string; } export function isEmbeddablePackageState(state: unknown): state is EmbeddablePackageState { diff --git a/src/plugins/embeddable/public/public.api.md b/src/plugins/embeddable/public/public.api.md index 98c48dbd848b0..a810b1f48a07c 100644 --- a/src/plugins/embeddable/public/public.api.md +++ b/src/plugins/embeddable/public/public.api.md @@ -365,6 +365,7 @@ export interface EmbeddableEditorState { embeddableId?: string; // (undocumented) originatingApp: string; + searchSessionId?: string; // (undocumented) valueInput?: EmbeddableInput; } @@ -467,6 +468,7 @@ export interface EmbeddablePackageState { embeddableId?: string; // (undocumented) input: Optional | Optional; + searchSessionId?: string; // (undocumented) type: string; } diff --git a/src/plugins/expressions/common/execution/execution.abortion.test.ts b/src/plugins/expressions/common/execution/execution.abortion.test.ts index 514086e9b19ee..798558ba7ffb6 100644 --- a/src/plugins/expressions/common/execution/execution.abortion.test.ts +++ b/src/plugins/expressions/common/execution/execution.abortion.test.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import { first } from 'rxjs/operators'; import { waitFor } from '@testing-library/react'; import { Execution } from './execution'; import { parseExpression } from '../ast'; @@ -40,9 +39,9 @@ describe('Execution abortion tests', () => { execution.start(); execution.cancel(); - const result = await execution.result.pipe(first()).toPromise(); + const result = await execution.result.toPromise(); - expect(result).toMatchObject({ + expect(result).toHaveProperty('result', { type: 'error', error: { message: 'The expression was aborted.', @@ -58,9 +57,9 @@ describe('Execution abortion tests', () => { jest.advanceTimersByTime(100); execution.cancel(); - const result = await execution.result.pipe(first()).toPromise(); + const result = await execution.result.toPromise(); - expect(result).toMatchObject({ + expect(result).toHaveProperty('result', { type: 'error', error: { message: 'The expression was aborted.', @@ -76,7 +75,7 @@ describe('Execution abortion tests', () => { execution.start(); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); execution.cancel(); @@ -136,7 +135,7 @@ describe('Execution abortion tests', () => { await waitFor(() => expect(started).toHaveBeenCalledTimes(1)); execution.cancel(); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toMatchObject({ type: 'error', error: { diff --git a/src/plugins/expressions/common/execution/execution.test.ts b/src/plugins/expressions/common/execution/execution.test.ts index feff425cc48ed..8c6f457105d42 100644 --- a/src/plugins/expressions/common/execution/execution.test.ts +++ b/src/plugins/expressions/common/execution/execution.test.ts @@ -7,7 +7,7 @@ */ import { of } from 'rxjs'; -import { first, scan } from 'rxjs/operators'; +import { scan } from 'rxjs/operators'; import { TestScheduler } from 'rxjs/testing'; import { Execution } from './execution'; import { parseExpression, ExpressionAstExpression } from '../ast'; @@ -45,7 +45,7 @@ const run = async ( ) => { const execution = createExecution(expression, context); execution.start(input); - return await execution.result.pipe(first()).toPromise(); + return await execution.result.toPromise(); }; let testScheduler: TestScheduler; @@ -84,7 +84,7 @@ describe('Execution', () => { /* eslint-enable no-console */ execution.start(123); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toBe(123); expect(spy).toHaveBeenCalledTimes(1); @@ -102,7 +102,7 @@ describe('Execution', () => { value: -1, }); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toEqual({ type: 'num', @@ -117,7 +117,7 @@ describe('Execution', () => { value: 0, }); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toEqual({ type: 'num', @@ -131,7 +131,7 @@ describe('Execution', () => { // Below 1 is cast to { type: 'num', value: 1 }. execution.start(1); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toEqual({ type: 'num', @@ -143,7 +143,7 @@ describe('Execution', () => { const execution = createExecution('add val=1'); execution.start(Promise.resolve(1)); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toEqual({ type: 'num', @@ -155,7 +155,7 @@ describe('Execution', () => { const execution = createExecution('add val=1'); execution.start(of(1)); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toEqual({ type: 'num', @@ -167,14 +167,14 @@ describe('Execution', () => { const execution = createExecution('add val=1'); testScheduler.run(({ cold, expectObservable }) => { - const input = cold(' -a--b-c-', { a: 1, b: 2, c: 3 }); + const input = cold(' -a--b-c|', { a: 1, b: 2, c: 3 }); const subscription = ' ---^---!'; - const expected = ' ---ab-c-'; + const expected = ' ---ab-c|'; expectObservable(execution.start(input), subscription).toBe(expected, { - a: { type: 'num', value: 2 }, - b: { type: 'num', value: 3 }, - c: { type: 'num', value: 4 }, + a: { partial: false, result: { type: 'num', value: 2 } }, + b: { partial: false, result: { type: 'num', value: 3 } }, + c: { partial: false, result: { type: 'num', value: 4 } }, }); }); }); @@ -187,21 +187,21 @@ describe('Execution', () => { const expected = ' -a-#'; expectObservable(execution.start(input)).toBe(expected, { - a: { type: 'num', value: 2 }, + a: { partial: false, result: { type: 'num', value: 2 } }, }); }); }); - test('does not complete when input completes', () => { + test('completes when input completes', () => { const execution = createExecution('add val=1'); testScheduler.run(({ cold, expectObservable }) => { const input = cold('-a-b|', { a: 1, b: 2 }); - const expected = ' -a-b-'; + const expected = ' -a-b|'; expectObservable(execution.start(input)).toBe(expected, { - a: { type: 'num', value: 2 }, - b: { type: 'num', value: 3 }, + a: expect.objectContaining({ result: { type: 'num', value: 2 } }), + b: expect.objectContaining({ result: { type: 'num', value: 3 } }), }); }); }); @@ -216,9 +216,9 @@ describe('Execution', () => { const input = items.pipe(scan((result, value) => [...result, value], new Array())); expectObservable(execution.start(input), subscription).toBe(expected, { - a: { type: 'num', value: 1 }, - b: { type: 'num', value: 3 }, - c: { type: 'num', value: 6 }, + a: { partial: false, result: { type: 'num', value: 1 } }, + b: { partial: false, result: { type: 'num', value: 3 } }, + c: { partial: false, result: { type: 'num', value: 6 } }, }); }); }); @@ -263,44 +263,51 @@ describe('Execution', () => { describe('execution context', () => { test('context.variables is an object', async () => { const { result } = (await run('introspectContext key="variables"')) as any; - expect(typeof result).toBe('object'); + + expect(result).toHaveProperty('result', expect.any(Object)); }); test('context.types is an object', async () => { const { result } = (await run('introspectContext key="types"')) as any; - expect(typeof result).toBe('object'); + + expect(result).toHaveProperty('result', expect.any(Object)); }); test('context.abortSignal is an object', async () => { const { result } = (await run('introspectContext key="abortSignal"')) as any; - expect(typeof result).toBe('object'); + + expect(result).toHaveProperty('result', expect.any(Object)); }); test('context.inspectorAdapters is an object', async () => { const { result } = (await run('introspectContext key="inspectorAdapters"')) as any; - expect(typeof result).toBe('object'); + + expect(result).toHaveProperty('result', expect.any(Object)); }); test('context.getKibanaRequest is a function if provided', async () => { const { result } = (await run('introspectContext key="getKibanaRequest"', { kibanaRequest: {}, })) as any; - expect(typeof result).toBe('function'); + + expect(result).toHaveProperty('result', expect.any(Function)); }); test('context.getKibanaRequest is undefined if not provided', async () => { const { result } = (await run('introspectContext key="getKibanaRequest"')) as any; - expect(typeof result).toBe('undefined'); + + expect(result).toHaveProperty('result', undefined); }); test('unknown context key is undefined', async () => { const { result } = (await run('introspectContext key="foo"')) as any; - expect(typeof result).toBe('undefined'); + + expect(result).toHaveProperty('result', undefined); }); test('can set context variables', async () => { const variables = { foo: 'bar' }; - const result = await run('var name="foo"', { variables }); + const { result } = await run('var name="foo"', { variables }); expect(result).toBe('bar'); }); }); @@ -308,10 +315,13 @@ describe('Execution', () => { describe('inspector adapters', () => { test('by default, "tables" and "requests" inspector adapters are available', async () => { const { result } = (await run('introspectContext key="inspectorAdapters"')) as any; - expect(result).toMatchObject({ - tables: expect.any(Object), - requests: expect.any(Object), - }); + expect(result).toHaveProperty( + 'result', + expect.objectContaining({ + tables: expect.any(Object), + requests: expect.any(Object), + }) + ); }); test('can set custom inspector adapters', async () => { @@ -319,7 +329,7 @@ describe('Execution', () => { const { result } = (await run('introspectContext key="inspectorAdapters"', { inspectorAdapters, })) as any; - expect(result).toBe(inspectorAdapters); + expect(result).toHaveProperty('result', inspectorAdapters); }); test('can access custom inspector adapters on Execution object', async () => { @@ -335,8 +345,7 @@ describe('Execution', () => { test('context has abortSignal object', async () => { const { result } = (await run('introspectContext key="abortSignal"')) as any; - expect(typeof result).toBe('object'); - expect((result as AbortSignal).aborted).toBe(false); + expect(result).toHaveProperty('result.aborted', false); }); }); @@ -348,7 +357,7 @@ describe('Execution', () => { value: 0, }); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toEqual({ type: 'num', @@ -357,8 +366,8 @@ describe('Execution', () => { }); test('can execute async functions', async () => { - const res = await run('sleep 10 | sleep 10'); - expect(res).toBe(null); + const { result } = await run('sleep 10 | sleep 10'); + expect(result).toBe(null); }); test('result is undefined until execution completes', async () => { @@ -374,7 +383,7 @@ describe('Execution', () => { jest.advanceTimersByTime(10); await new Promise(process.nextTick); - expect(execution.state.get().result).toBe(null); + expect(execution.state.get().result).toHaveProperty('result', null); jest.useRealTimers(); }); @@ -382,7 +391,7 @@ describe('Execution', () => { test('handles functions returning observables', () => { testScheduler.run(({ cold, expectObservable }) => { const arg = cold(' -a-b-c|', { a: 1, b: 2, c: 3 }); - const expected = ' -a-b-c-'; + const expected = ' -a-b-c|'; const observable: ExpressionFunctionDefinition<'observable', any, {}, any> = { name: 'observable', args: {}, @@ -394,14 +403,18 @@ describe('Execution', () => { const result = executor.run('observable', null, {}); - expectObservable(result).toBe(expected, { a: 1, b: 2, c: 3 }); + expectObservable(result).toBe(expected, { + a: { result: 1, partial: true }, + b: { result: 2, partial: true }, + c: { result: 3, partial: false }, + }); }); }); }); describe('when function throws', () => { test('error is reported in output object', async () => { - const result = await run('error "foobar"'); + const { result } = await run('error "foobar"'); expect(result).toMatchObject({ type: 'error', @@ -409,7 +422,7 @@ describe('Execution', () => { }); test('error message is prefixed with function name', async () => { - const result = await run('error "foobar"'); + const { result } = await run('error "foobar"'); expect(result).toMatchObject({ error: { @@ -419,7 +432,7 @@ describe('Execution', () => { }); test('returns error of the first function that throws', async () => { - const result = await run('error "foo" | error "bar"'); + const { result } = await run('error "foo" | error "bar"'); expect(result).toMatchObject({ error: { @@ -432,15 +445,18 @@ describe('Execution', () => { const execution = await createExecution('error "foo"'); execution.start(null); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toMatchObject({ type: 'error', }); expect(execution.state.get().state).toBe('result'); - expect(execution.state.get().result).toMatchObject({ - type: 'error', - }); + expect(execution.state.get().result).toHaveProperty( + 'result', + expect.objectContaining({ + type: 'error', + }) + ); }); test('does not execute remaining functions in pipeline', async () => { @@ -453,7 +469,7 @@ describe('Execution', () => { const executor = createUnitTestExecutor(); executor.registerFunction(spy); - await executor.run('error "..." | spy', null).pipe(first()).toPromise(); + await executor.run('error "..." | spy', null).toPromise(); expect(spy.fn).toHaveBeenCalledTimes(0); }); @@ -483,21 +499,21 @@ describe('Execution', () => { test('execution state is "result" when execution successfully completes', async () => { const execution = createExecution('sleep 1'); execution.start(null); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); expect(execution.state.get().state).toBe('result'); }); test('execution state is "result" when execution successfully completes - 2', async () => { const execution = createExecution('var foo'); execution.start(null); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); expect(execution.state.get().state).toBe('result'); }); }); describe('sub-expressions', () => { test('executes sub-expressions', async () => { - const result = await run('add val={add 5 | access "value"}', {}, null); + const { result } = await run('add val={add 5 | access "value"}', {}, null); expect(result).toMatchObject({ type: 'num', @@ -506,7 +522,7 @@ describe('Execution', () => { }); test('can use global variables', async () => { - const result = await run( + const { result } = await run( 'add val={var foo}', { variables: { @@ -523,7 +539,7 @@ describe('Execution', () => { }); test('can modify global variables', async () => { - const result = await run( + const { result } = await run( 'add val={var_set name=foo value=66 | var bar} | var foo', { variables: { @@ -547,18 +563,20 @@ describe('Execution', () => { const executor = createUnitTestExecutor(); executor.registerFunction(observable); - expect( - executor.run('add val={observable}', 1, {}).pipe(first()).toPromise() - ).resolves.toEqual({ - type: 'num', - value: 2, - }); + expect(executor.run('add val={observable}', 1, {}).toPromise()).resolves.toEqual( + expect.objectContaining({ + result: { + type: 'num', + value: 2, + }, + }) + ); }); test('supports observables in arguments emitting multiple values', () => { testScheduler.run(({ cold, expectObservable }) => { - const arg = cold('-a-b-c-', { a: 1, b: 2, c: 3 }); - const expected = '-a-b-c-'; + const arg = cold('-a-b-c|', { a: 1, b: 2, c: 3 }); + const expected = '-a-b-c|'; const observable = { name: 'observable', args: {}, @@ -571,18 +589,18 @@ describe('Execution', () => { const result = executor.run('add val={observable}', 1, {}); expectObservable(result).toBe(expected, { - a: { type: 'num', value: 2 }, - b: { type: 'num', value: 3 }, - c: { type: 'num', value: 4 }, + a: { partial: true, result: { type: 'num', value: 2 } }, + b: { partial: true, result: { type: 'num', value: 3 } }, + c: { partial: false, result: { type: 'num', value: 4 } }, }); }); }); test('combines multiple observables in arguments', () => { testScheduler.run(({ cold, expectObservable }) => { - const arg1 = cold('--ab-c-', { a: 0, b: 2, c: 4 }); - const arg2 = cold('-a--bc-', { a: 1, b: 3, c: 5 }); - const expected = ' --abc(de)-'; + const arg1 = cold('--ab-c---|', { a: 0, b: 2, c: 4 }); + const arg2 = cold('-a--bc---|', { a: 1, b: 3, c: 5 }); + const expected = ' --abc(de)|'; const observable1 = { name: 'observable1', args: {}, @@ -612,32 +630,11 @@ describe('Execution', () => { const result = executor.run('max val1={observable1} val2={observable2}', {}); expectObservable(result).toBe(expected, { - a: { type: 'num', value: 1 }, - b: { type: 'num', value: 2 }, - c: { type: 'num', value: 3 }, - d: { type: 'num', value: 4 }, - e: { type: 'num', value: 5 }, - }); - }); - }); - - test('does not complete when an argument completes', () => { - testScheduler.run(({ cold, expectObservable }) => { - const arg = cold('-a|', { a: 1 }); - const expected = '-a-'; - const observable = { - name: 'observable', - args: {}, - help: '', - fn: () => arg, - }; - const executor = createUnitTestExecutor(); - executor.registerFunction(observable); - - const result = executor.run('add val={observable}', 1, {}); - - expectObservable(result).toBe(expected, { - a: { type: 'num', value: 2 }, + a: { partial: true, result: { type: 'num', value: 1 } }, + b: { partial: true, result: { type: 'num', value: 2 } }, + c: { partial: true, result: { type: 'num', value: 3 } }, + d: { partial: true, result: { type: 'num', value: 4 } }, + e: { partial: false, result: { type: 'num', value: 5 } }, }); }); }); @@ -645,7 +642,7 @@ describe('Execution', () => { test('handles error in observable arguments', () => { testScheduler.run(({ cold, expectObservable }) => { const arg = cold('-a-#', { a: 1 }, new Error('some error')); - const expected = '-a-b'; + const expected = '-a-(b|)'; const observable = { name: 'observable', args: {}, @@ -658,13 +655,15 @@ describe('Execution', () => { const result = executor.run('add val={observable}', 1, {}); expectObservable(result).toBe(expected, { - a: { type: 'num', value: 2 }, - b: { - error: expect.objectContaining({ - message: '[add] > [observable] > some error', - }), - type: 'error', - }, + a: expect.objectContaining({ result: { type: 'num', value: 2 } }), + b: expect.objectContaining({ + result: { + error: expect.objectContaining({ + message: '[add] > [observable] > some error', + }), + type: 'error', + }, + }), }); }); }); @@ -685,7 +684,7 @@ describe('Execution', () => { }; const executor = createUnitTestExecutor(); executor.registerFunction(requiredArg); - const result = await executor.run('requiredArg', null, {}).pipe(first()).toPromise(); + const { result } = await executor.run('requiredArg', null, {}).toPromise(); expect(result).toMatchObject({ type: 'error', @@ -696,7 +695,7 @@ describe('Execution', () => { }); test('when required argument is missing and has alias, returns error', async () => { - const result = await run('var_set', {}); + const { result } = await run('var_set', {}); expect(result).toMatchObject({ type: 'error', @@ -711,7 +710,7 @@ describe('Execution', () => { test('can execute expression in debug mode', async () => { const execution = createExecution('add val=1 | add val=2 | add val=3', {}, true); execution.start(-1); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toEqual({ type: 'num', @@ -726,7 +725,7 @@ describe('Execution', () => { true ); execution.start(0); - const result = await execution.result.pipe(first()).toPromise(); + const { result } = await execution.result.toPromise(); expect(result).toEqual({ type: 'num', @@ -738,7 +737,7 @@ describe('Execution', () => { test('sets "success" flag on all functions to true', async () => { const execution = createExecution('add val=1 | add val=2 | add val=3', {}, true); execution.start(-1); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); for (const node of execution.state.get().ast.chain) { expect(node.debug?.success).toBe(true); @@ -748,7 +747,7 @@ describe('Execution', () => { test('stores "fn" reference to the function', async () => { const execution = createExecution('add val=1 | add val=2 | add val=3', {}, true); execution.start(-1); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); for (const node of execution.state.get().ast.chain) { expect(node.debug?.fn).toBe('add'); @@ -758,7 +757,7 @@ describe('Execution', () => { test('saves duration it took to execute each function', async () => { const execution = createExecution('add val=1 | add val=2 | add val=3', {}, true); execution.start(-1); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); for (const node of execution.state.get().ast.chain) { expect(typeof node.debug?.duration).toBe('number'); @@ -770,7 +769,7 @@ describe('Execution', () => { test('adds .debug field in expression AST on each executed function', async () => { const execution = createExecution('add val=1 | add val=2 | add val=3', {}, true); execution.start(-1); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); for (const node of execution.state.get().ast.chain) { expect(typeof node.debug).toBe('object'); @@ -781,7 +780,7 @@ describe('Execution', () => { test('stores input of each function', async () => { const execution = createExecution('add val=1 | add val=2 | add val=3', {}, true); execution.start(-1); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); const { chain } = execution.state.get().ast; @@ -799,7 +798,7 @@ describe('Execution', () => { test('stores output of each function', async () => { const execution = createExecution('add val=1 | add val=2 | add val=3', {}, true); execution.start(-1); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); const { chain } = execution.state.get().ast; @@ -824,7 +823,7 @@ describe('Execution', () => { true ); execution.start(-1); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); const { chain } = execution.state.get().ast; @@ -847,7 +846,7 @@ describe('Execution', () => { true ); execution.start(0); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); const { chain } = execution.state.get().ast.chain[0].arguments .val[0] as ExpressionAstExpression; @@ -882,7 +881,7 @@ describe('Execution', () => { params: { debug: true }, }); execution.start(0); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); const node1 = execution.state.get().ast.chain[0]; const node2 = execution.state.get().ast.chain[1]; @@ -900,7 +899,7 @@ describe('Execution', () => { params: { debug: true }, }); execution.start(0); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); const node2 = execution.state.get().ast.chain[1]; @@ -921,7 +920,7 @@ describe('Execution', () => { params: { debug: true }, }); execution.start(0); - await execution.result.pipe(first()).toPromise(); + await execution.result.toPromise(); const node2 = execution.state.get().ast.chain[1]; diff --git a/src/plugins/expressions/common/execution/execution.ts b/src/plugins/expressions/common/execution/execution.ts index b70f261ea4b20..47209c348257e 100644 --- a/src/plugins/expressions/common/execution/execution.ts +++ b/src/plugins/expressions/common/execution/execution.ts @@ -20,7 +20,7 @@ import { Observable, ReplaySubject, } from 'rxjs'; -import { catchError, finalize, map, shareReplay, switchMap, tap } from 'rxjs/operators'; +import { catchError, finalize, map, pluck, shareReplay, switchMap, tap } from 'rxjs/operators'; import { Executor } from '../executor'; import { createExecutionContainer, ExecutionContainer } from './container'; import { createError } from '../util'; @@ -45,6 +45,21 @@ import { ExpressionExecutionParams } from '../service'; import { TablesAdapter } from '../util/tables_adapter'; import { ExpressionsInspectorAdapter } from '../util/expressions_inspector_adapter'; +/** + * The result returned after an expression function execution. + */ +export interface ExecutionResult { + /** + * Partial result flag. + */ + partial: boolean; + + /** + * The expression function result. + */ + result: Output; +} + /** * AbortController is not available in Node until v15, so we * need to temporarily mock it for plugins using expressions @@ -91,7 +106,7 @@ export class Execution< /** * Dynamic state of the execution. */ - public readonly state: ExecutionContainer; + public readonly state: ExecutionContainer>; /** * Initial input of the execution. @@ -137,7 +152,7 @@ export class Execution< /** * Future that tracks result or error of this execution. */ - public readonly result: Observable; + public readonly result: Observable>; /** * Keeping track of any child executions @@ -174,7 +189,7 @@ export class Execution< this.expression = execution.expression || formatExpression(execution.ast!); const ast = execution.ast || parseExpression(this.expression); - this.state = createExecutionContainer({ + this.state = createExecutionContainer({ ...executor.state.get(), state: 'not-started', ast, @@ -201,12 +216,40 @@ export class Execution< }; this.result = this.input$.pipe( - switchMap((input) => this.race(this.invokeChain(this.state.get().ast.chain, input))), + switchMap((input) => + this.race(this.invokeChain(this.state.get().ast.chain, input)).pipe( + (source) => + new Observable>((subscriber) => { + let latest: ExecutionResult | undefined; + + subscriber.add( + source.subscribe({ + next: (result) => { + latest = { result, partial: true }; + subscriber.next(latest); + }, + error: (error) => subscriber.error(error), + complete: () => { + if (latest) { + latest.partial = false; + } + + subscriber.complete(); + }, + }) + ); + + subscriber.add(() => { + latest = undefined; + }); + }) + ) + ), catchError((error) => { if (this.abortController.signal.aborted) { this.childExecutions.forEach((childExecution) => childExecution.cancel()); - return of(createAbortErrorValue()); + return of({ result: createAbortErrorValue(), partial: false }); } return throwError(error); @@ -236,25 +279,20 @@ export class Execution< * N.B. `input` is initialized to `null` rather than `undefined` for legacy reasons, * because in legacy interpreter it was set to `null` by default. */ - public start(input: Input = null as any): Observable { + public start( + input: Input = null as any + ): Observable> { if (this.hasStarted) throw new Error('Execution already started.'); this.hasStarted = true; this.input = input; this.state.transitions.start(); if (isObservable(input)) { - // `input$` should never complete - input.subscribe( - (value) => this.input$.next(value), - (error) => this.input$.error(error) - ); + input.subscribe(this.input$); } else if (isPromise(input)) { - input.then( - (value) => this.input$.next(value), - (error) => this.input$.error(error) - ); + from(input).subscribe(this.input$); } else { - this.input$.next(input); + of(input).subscribe(this.input$); } return this.result; @@ -439,6 +477,7 @@ export class Execution< const resolveArgFns = mapValues(dealiasedArgAsts, (asts, argName) => asts.map((item) => (subInput = input) => this.interpret(item, subInput).pipe( + pluck('result'), map((output) => { if (isExpressionValueError(output)) { throw output.error; @@ -486,7 +525,7 @@ export class Execution< }); } - public interpret(ast: ExpressionAstNode, input: T): Observable { + public interpret(ast: ExpressionAstNode, input: T): Observable> { switch (getType(ast)) { case 'expression': const execution = this.execution.executor.createExecution( @@ -494,12 +533,13 @@ export class Execution< this.execution.params ); this.childExecutions.push(execution); + return execution.start(input); case 'string': case 'number': case 'null': case 'boolean': - return of(ast); + return of({ result: ast, partial: false }); default: return throwError(new Error(`Unknown AST object: ${JSON.stringify(ast)}`)); } diff --git a/src/plugins/expressions/common/execution/execution_contract.test.ts b/src/plugins/expressions/common/execution/execution_contract.test.ts index 99a5c80de3c46..de209f1dfb4a1 100644 --- a/src/plugins/expressions/common/execution/execution_contract.test.ts +++ b/src/plugins/expressions/common/execution/execution_contract.test.ts @@ -66,26 +66,23 @@ describe('ExecutionContract', () => { }); }); - test('can get error result of the expression execution', async () => { + test('can get error result of the expression execution', () => { const execution = createExecution('foo bar=123'); const contract = new ExecutionContract(execution); execution.start(); - const result = await contract.getData(); - - expect(result).toMatchObject({ - type: 'error', - }); + expect(contract.getData().toPromise()).resolves.toHaveProperty( + 'result', + expect.objectContaining({ type: 'error' }) + ); }); - test('can get result of the expression execution', async () => { + test('can get result of the expression execution', () => { const execution = createExecution('var_set name="foo" value="bar" | var name="foo"'); const contract = new ExecutionContract(execution); execution.start(); - const result = await contract.getData(); - - expect(result).toBe('bar'); + expect(contract.getData().toPromise()).resolves.toHaveProperty('result', 'bar'); }); describe('isPending', () => { diff --git a/src/plugins/expressions/common/execution/execution_contract.ts b/src/plugins/expressions/common/execution/execution_contract.ts index 3cad9cef5e09a..445ceb30b58db 100644 --- a/src/plugins/expressions/common/execution/execution_contract.ts +++ b/src/plugins/expressions/common/execution/execution_contract.ts @@ -6,9 +6,9 @@ * Side Public License, v 1. */ -import { of } from 'rxjs'; -import { catchError, take } from 'rxjs/operators'; -import { Execution } from './execution'; +import { of, Observable } from 'rxjs'; +import { catchError } from 'rxjs/operators'; +import { Execution, ExecutionResult } from './execution'; import { ExpressionValueError } from '../expression_types/specs'; import { ExpressionAstExpression } from '../ast'; @@ -39,22 +39,22 @@ export class ExecutionContract => { - return this.execution.result - .pipe( - take(1), - catchError(({ name, message, stack }) => - of({ + getData = (): Observable> => { + return this.execution.result.pipe( + catchError(({ name, message, stack }) => + of({ + partial: false, + result: { type: 'error', error: { name, message, stack, }, - } as ExpressionValueError) - ) + } as ExpressionValueError, + }) ) - .toPromise(); + ); }; /** diff --git a/src/plugins/expressions/common/executor/executor.ts b/src/plugins/expressions/common/executor/executor.ts index a307172aff973..7ca5a005991bd 100644 --- a/src/plugins/expressions/common/executor/executor.ts +++ b/src/plugins/expressions/common/executor/executor.ts @@ -13,7 +13,7 @@ import { Observable } from 'rxjs'; import { ExecutorState, ExecutorContainer } from './container'; import { createExecutorContainer } from './container'; import { AnyExpressionFunctionDefinition, ExpressionFunction } from '../expression_functions'; -import { Execution, ExecutionParams } from '../execution/execution'; +import { Execution, ExecutionParams, ExecutionResult } from '../execution/execution'; import { IRegistry } from '../types'; import { ExpressionType } from '../expression_types/expression_type'; import { AnyExpressionTypeDefinition } from '../expression_types/types'; @@ -160,7 +160,7 @@ export class Executor = Record { + ): Observable> { return this.createExecution(ast, params).start(input); } diff --git a/src/plugins/expressions/common/expression_functions/specs/tests/var_set.test.ts b/src/plugins/expressions/common/expression_functions/specs/tests/var_set.test.ts index cdcae61215fa4..1b060cde7482d 100644 --- a/src/plugins/expressions/common/expression_functions/specs/tests/var_set.test.ts +++ b/src/plugins/expressions/common/expression_functions/specs/tests/var_set.test.ts @@ -65,7 +65,7 @@ describe('expression_functions', () => { it('sets the variables', async () => { const vars = {}; - const result = await executor + const { result } = await executor .run('var_set name=test1 name=test2 value=1', 2, { variables: vars }) .pipe(first()) .toPromise(); diff --git a/src/plugins/expressions/common/service/expressions_services.test.ts b/src/plugins/expressions/common/service/expressions_services.test.ts index 8f86e81f9d1d5..db73d300e1273 100644 --- a/src/plugins/expressions/common/service/expressions_services.test.ts +++ b/src/plugins/expressions/common/service/expressions_services.test.ts @@ -114,7 +114,7 @@ describe('ExpressionsService', () => { }, }); - const result = await fork.run('__test__', null); + const { result } = await fork.run('__test__', null).toPromise(); expect(result).toBe('123'); }); diff --git a/src/plugins/expressions/common/service/expressions_services.ts b/src/plugins/expressions/common/service/expressions_services.ts index b3c0167262661..9e569c66bbe16 100644 --- a/src/plugins/expressions/common/service/expressions_services.ts +++ b/src/plugins/expressions/common/service/expressions_services.ts @@ -6,15 +6,15 @@ * Side Public License, v 1. */ -import { take } from 'rxjs/operators'; +import { Observable } from 'rxjs'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import type { KibanaRequest } from 'src/core/server'; import { Executor } from '../executor'; import { AnyExpressionRenderDefinition, ExpressionRendererRegistry } from '../expression_renderers'; import { ExpressionAstExpression } from '../ast'; -import { ExecutionContract } from '../execution/execution_contract'; -import { AnyExpressionTypeDefinition } from '../expression_types'; +import { ExecutionContract, ExecutionResult } from '../execution'; +import { AnyExpressionTypeDefinition, ExpressionValueError } from '../expression_types'; import { AnyExpressionFunctionDefinition } from '../expression_functions'; import { SavedObjectReference } from '../../../../core/types'; import { PersistableStateService, SerializableState } from '../../../kibana_utils/common'; @@ -136,7 +136,7 @@ export interface ExpressionsServiceStart { ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams - ) => Promise; + ) => Observable>; /** * Starts expression execution and immediately returns `ExecutionContract` @@ -243,7 +243,7 @@ export class ExpressionsService implements PersistableStateService this.renderers.register(definition); public readonly run: ExpressionsServiceStart['run'] = (ast, input, params) => - this.executor.run(ast, input, params).pipe(take(1)).toPromise(); + this.executor.run(ast, input, params); public readonly getFunction: ExpressionsServiceStart['getFunction'] = (name) => this.executor.getFunction(name); diff --git a/src/plugins/expressions/public/loader.test.ts b/src/plugins/expressions/public/loader.test.ts index 98adec285afd5..86477e53dc1a1 100644 --- a/src/plugins/expressions/public/loader.test.ts +++ b/src/plugins/expressions/public/loader.test.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ +import { of } from 'rxjs'; import { first, skip, toArray } from 'rxjs/operators'; import { loader, ExpressionLoader } from './loader'; import { Observable } from 'rxjs'; @@ -111,8 +112,29 @@ describe('ExpressionLoader', () => { it('emits on $data when data is available', async () => { const expressionLoader = new ExpressionLoader(element, 'var foo', { variables: { foo: 123 } }); - const response = await expressionLoader.data$.pipe(first()).toPromise(); - expect(response).toBe(123); + const { result } = await expressionLoader.data$.pipe(first()).toPromise(); + expect(result).toBe(123); + }); + + it('ignores partial results by default', async () => { + const expressionLoader = new ExpressionLoader(element, 'var foo', { + variables: { foo: of(1, 2) }, + }); + const { result, partial } = await expressionLoader.data$.pipe(first()).toPromise(); + + expect(partial).toBe(false); + expect(result).toBe(2); + }); + + it('emits partial results if enabled', async () => { + const expressionLoader = new ExpressionLoader(element, 'var foo', { + variables: { foo: of(1, 2) }, + partial: true, + }); + const { result, partial } = await expressionLoader.data$.pipe(first()).toPromise(); + + expect(partial).toBe(true); + expect(result).toBe(1); }); it('emits on loading$ on initial load and on updates', async () => { diff --git a/src/plugins/expressions/public/loader.ts b/src/plugins/expressions/public/loader.ts index 4165b8906a20e..a51ce35c68180 100644 --- a/src/plugins/expressions/public/loader.ts +++ b/src/plugins/expressions/public/loader.ts @@ -6,9 +6,10 @@ * Side Public License, v 1. */ -import { BehaviorSubject, Observable, Subject } from 'rxjs'; -import { filter, map } from 'rxjs/operators'; +import { BehaviorSubject, Observable, Subject, Subscription } from 'rxjs'; +import { filter, map, delay } from 'rxjs/operators'; import { defaults } from 'lodash'; +import { UnwrapObservable } from '@kbn/utility-types'; import { Adapters } from '../../inspector/public'; import { IExpressionLoaderParams } from './types'; import { ExpressionAstExpression } from '../common'; @@ -20,7 +21,7 @@ import { getExpressionsService } from './services'; type Data = any; export class ExpressionLoader { - data$: Observable; + data$: ReturnType; update$: ExpressionRenderHandler['update$']; render$: ExpressionRenderHandler['render$']; events$: ExpressionRenderHandler['events$']; @@ -28,10 +29,11 @@ export class ExpressionLoader { private execution: ExecutionContract | undefined; private renderHandler: ExpressionRenderHandler; - private dataSubject: Subject; + private dataSubject: Subject>; private loadingSubject: Subject; private data: Data; private params: IExpressionLoaderParams = {}; + private subscription?: Subscription; constructor( element: HTMLElement, @@ -67,8 +69,8 @@ export class ExpressionLoader { } }); - this.data$.subscribe((data) => { - this.render(data); + this.data$.subscribe(({ result }) => { + this.render(result); }); this.render$.subscribe(() => { @@ -87,27 +89,20 @@ export class ExpressionLoader { this.dataSubject.complete(); this.loadingSubject.complete(); this.renderHandler.destroy(); - if (this.execution) { - this.execution.cancel(); - } + this.cancel(); + this.subscription?.unsubscribe(); } cancel() { - if (this.execution) { - this.execution.cancel(); - } + this.execution?.cancel(); } getExpression(): string | undefined { - if (this.execution) { - return this.execution.getExpression(); - } + return this.execution?.getExpression(); } getAst(): ExpressionAstExpression | undefined { - if (this.execution) { - return this.execution.getAst(); - } + return this.execution?.getAst(); } getElement(): HTMLElement { @@ -115,27 +110,25 @@ export class ExpressionLoader { } inspect(): Adapters | undefined { - return this.execution ? (this.execution.inspect() as Adapters) : undefined; + return this.execution?.inspect() as Adapters; } - async update( - expression?: string | ExpressionAstExpression, - params?: IExpressionLoaderParams - ): Promise { + update(expression?: string | ExpressionAstExpression, params?: IExpressionLoaderParams): void { this.setParams(params); this.loadingSubject.next(true); if (expression) { - await this.loadData(expression, this.params); + this.loadData(expression, this.params); } else if (this.data) { this.render(this.data); } } - private loadData = async ( + private loadData = ( expression: string | ExpressionAstExpression, params: IExpressionLoaderParams - ): Promise => { + ) => { + this.subscription?.unsubscribe(); if (this.execution && this.execution.isPending) { this.execution.cancel(); } @@ -148,13 +141,13 @@ export class ExpressionLoader { debug: params.debug, syncColors: params.syncColors, }); - - const prevDataHandler = this.execution; - const data = await prevDataHandler.getData(); - if (this.execution !== prevDataHandler) { - return; - } - this.dataSubject.next(data); + this.subscription = this.execution + .getData() + .pipe( + delay(0), // delaying until the next tick since we execute the expression in the constructor + filter(({ partial }) => params.partial || !partial) + ) + .subscribe((value) => this.dataSubject.next(value)); }; private render(data: Data): void { @@ -184,6 +177,7 @@ export class ExpressionLoader { } this.params.syncColors = params.syncColors; this.params.debug = Boolean(params.debug); + this.params.partial = Boolean(params.partial); this.params.inspectorAdapters = (params.inspectorAdapters || this.execution?.inspect()) as Adapters; diff --git a/src/plugins/expressions/public/plugin.test.ts b/src/plugins/expressions/public/plugin.test.ts index 93353ebbb51b6..1963eb1f1b3f7 100644 --- a/src/plugins/expressions/public/plugin.test.ts +++ b/src/plugins/expressions/public/plugin.test.ts @@ -36,8 +36,10 @@ describe('ExpressionsPublicPlugin', () => { describe('.run()', () => { test('can execute simple expression', async () => { const { setup } = await expressionsPluginMock.createPlugin(); - const bar = await setup.run('var_set name="foo" value="bar" | var name="foo"', null); - expect(bar).toBe('bar'); + const { result } = await setup + .run('var_set name="foo" value="bar" | var name="foo"', null) + .toPromise(); + expect(result).toBe('bar'); }); }); }); diff --git a/src/plugins/expressions/public/public.api.md b/src/plugins/expressions/public/public.api.md index 97009ae543b97..2d9c6d94cfa6d 100644 --- a/src/plugins/expressions/public/public.api.md +++ b/src/plugins/expressions/public/public.api.md @@ -112,16 +112,17 @@ export class Execution(ast: ExpressionAstNode, input: T): Observable; + interpret(ast: ExpressionAstNode, input: T): Observable>; // (undocumented) invokeChain(chainArr: ExpressionAstFunction[], input: unknown): Observable; // (undocumented) invokeFunction(fn: ExpressionFunction, input: unknown, args: Record): Observable; // (undocumented) resolveArgs(fnDef: ExpressionFunction, input: unknown, argAsts: any): Observable; - readonly result: Observable; - start(input?: Input): Observable; - readonly state: ExecutionContainer; + readonly result: Observable>; + start(input?: Input): Observable>; + // Warning: (ae-forgotten-export) The symbol "ExecutionResult" needs to be exported by the entry point index.d.ts + readonly state: ExecutionContainer>; } // Warning: (ae-forgotten-export) The symbol "StateContainer" needs to be exported by the entry point index.d.ts @@ -155,7 +156,7 @@ export class ExecutionContract; getAst: () => ExpressionAstExpression; - getData: () => Promise; + getData: () => Observable>; getExpression: () => string; inspect: () => InspectorAdapters; // (undocumented) @@ -230,7 +231,7 @@ export class Executor = Record AnyExpressionFunctionDefinition)): void; // (undocumented) registerType(typeDefinition: AnyExpressionTypeDefinition | (() => AnyExpressionTypeDefinition)): void; - run(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams): Observable; + run(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams): Observable>; // (undocumented) readonly state: ExecutorContainer; // (undocumented) @@ -637,7 +638,7 @@ export interface ExpressionsServiceStart { getFunction: (name: string) => ReturnType; getRenderer: (name: string) => ReturnType; getType: (name: string) => ReturnType; - run: (ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams) => Promise; + run: (ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams) => Observable>; } // Warning: (ae-missing-release-tag) "ExpressionsSetup" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -907,6 +908,8 @@ export interface IExpressionLoaderParams { // // (undocumented) onRenderError?: RenderErrorHandlerFnType; + // (undocumented) + partial?: boolean; // Warning: (ae-forgotten-export) The symbol "RenderMode" needs to be exported by the entry point index.d.ts // // (undocumented) @@ -1073,7 +1076,7 @@ export interface ReactExpressionRendererProps extends IExpressionLoaderParams { // (undocumented) expression: string | ExpressionAstExpression; // (undocumented) - onData$?: (data: TData, adapters?: TInspectorAdapters) => void; + onData$?: (data: TData, adapters?: TInspectorAdapters, partial?: boolean) => void; // (undocumented) onEvent?: (event: ExpressionRendererEvent) => void; // (undocumented) diff --git a/src/plugins/expressions/public/react_expression_renderer.test.tsx b/src/plugins/expressions/public/react_expression_renderer.test.tsx index e7ae6ee45ab60..d31a4c947b09d 100644 --- a/src/plugins/expressions/public/react_expression_renderer.test.tsx +++ b/src/plugins/expressions/public/react_expression_renderer.test.tsx @@ -255,7 +255,7 @@ describe('ExpressionRenderer', () => { const dataSubject = new Subject(); const data$ = dataSubject.asObservable().pipe(share()); - const newData = {}; + const result = {}; const inspectData = {}; const onData$ = jest.fn(); @@ -275,11 +275,11 @@ describe('ExpressionRenderer', () => { expect(onData$).toHaveBeenCalledTimes(0); act(() => { - dataSubject.next(newData); + dataSubject.next({ result }); }); expect(onData$).toHaveBeenCalledTimes(1); - expect(onData$.mock.calls[0][0]).toBe(newData); + expect(onData$.mock.calls[0][0]).toBe(result); expect(onData$.mock.calls[0][1]).toBe(inspectData); }); diff --git a/src/plugins/expressions/public/react_expression_renderer.tsx b/src/plugins/expressions/public/react_expression_renderer.tsx index ce8547f132c27..719af1b39f89e 100644 --- a/src/plugins/expressions/public/react_expression_renderer.tsx +++ b/src/plugins/expressions/public/react_expression_renderer.tsx @@ -30,7 +30,11 @@ export interface ReactExpressionRendererProps extends IExpressionLoaderParams { ) => React.ReactElement | React.ReactElement[]; padding?: 'xs' | 's' | 'm' | 'l' | 'xl'; onEvent?: (event: ExpressionRendererEvent) => void; - onData$?: (data: TData, adapters?: TInspectorAdapters) => void; + onData$?: ( + data: TData, + adapters?: TInspectorAdapters, + partial?: boolean + ) => void; /** * An observable which can be used to re-run the expression without destroying the component */ @@ -135,8 +139,8 @@ export const ReactExpressionRenderer = ({ } if (onData$) { subs.push( - expressionLoaderRef.current.data$.subscribe((newData) => { - onData$(newData, expressionLoaderRef.current?.inspect()); + expressionLoaderRef.current.data$.subscribe(({ partial, result }) => { + onData$(result, expressionLoaderRef.current?.inspect(), partial); }) ); } diff --git a/src/plugins/expressions/public/types/index.ts b/src/plugins/expressions/public/types/index.ts index 947b84ec152ac..2375252e82784 100644 --- a/src/plugins/expressions/public/types/index.ts +++ b/src/plugins/expressions/public/types/index.ts @@ -48,6 +48,7 @@ export interface IExpressionLoaderParams { renderMode?: RenderMode; syncColors?: boolean; hasCompatibleActions?: ExpressionRenderHandlerParams['hasCompatibleActions']; + partial?: boolean; } export interface ExpressionRenderError extends Error { diff --git a/src/plugins/expressions/server/plugin.test.ts b/src/plugins/expressions/server/plugin.test.ts index d967f9e614678..c41cda36e7623 100644 --- a/src/plugins/expressions/server/plugin.test.ts +++ b/src/plugins/expressions/server/plugin.test.ts @@ -28,8 +28,10 @@ describe('ExpressionsServerPlugin', () => { describe('.run()', () => { test('can execute simple expression', async () => { const { setup } = await expressionsPluginMock.createPlugin(); - const bar = await setup.run('var_set name="foo" value="bar" | var name="foo"', null); - expect(bar).toBe('bar'); + const { result } = await setup + .run('var_set name="foo" value="bar" | var name="foo"', null) + .toPromise(); + expect(result).toBe('bar'); }); }); }); diff --git a/src/plugins/expressions/server/server.api.md b/src/plugins/expressions/server/server.api.md index 8d2e113e6b6ed..ec16d95ea8a3f 100644 --- a/src/plugins/expressions/server/server.api.md +++ b/src/plugins/expressions/server/server.api.md @@ -110,16 +110,17 @@ export class Execution(ast: ExpressionAstNode, input: T): Observable; + interpret(ast: ExpressionAstNode, input: T): Observable>; // (undocumented) invokeChain(chainArr: ExpressionAstFunction[], input: unknown): Observable; // (undocumented) invokeFunction(fn: ExpressionFunction, input: unknown, args: Record): Observable; // (undocumented) resolveArgs(fnDef: ExpressionFunction, input: unknown, argAsts: any): Observable; - readonly result: Observable; - start(input?: Input): Observable; - readonly state: ExecutionContainer; + readonly result: Observable>; + start(input?: Input): Observable>; + // Warning: (ae-forgotten-export) The symbol "ExecutionResult" needs to be exported by the entry point index.d.ts + readonly state: ExecutionContainer>; } // Warning: (ae-forgotten-export) The symbol "StateContainer" needs to be exported by the entry point index.d.ts @@ -212,7 +213,7 @@ export class Executor = Record AnyExpressionFunctionDefinition)): void; // (undocumented) registerType(typeDefinition: AnyExpressionTypeDefinition | (() => AnyExpressionTypeDefinition)): void; - run(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams): Observable; + run(ast: string | ExpressionAstExpression, input: Input, params?: ExpressionExecutionParams): Observable>; // (undocumented) readonly state: ExecutorContainer; // (undocumented) diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_editor_visualization.js b/src/plugins/vis_type_timeseries/public/application/components/vis_editor_visualization.js index bb264aaacbfbf..801681dbd531f 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_editor_visualization.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_editor_visualization.js @@ -10,6 +10,7 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { keys, EuiFlexGroup, EuiFlexItem, EuiButton, EuiText, EuiSwitch } from '@elastic/eui'; import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; +import { pluck } from 'rxjs/operators'; const MIN_CHART_HEIGHT = 300; @@ -55,7 +56,9 @@ class VisEditorVisualizationUI extends Component { await this._handler.render(this._visEl.current); this.props.eventEmitter.emit('embeddableRendered'); - this._subscription = this._handler.handler.data$.subscribe((data) => onDataChange(data.value)); + this._subscription = this._handler.handler.data$ + .pipe(pluck('result')) + .subscribe((data) => onDataChange(data.value)); } /** diff --git a/test/functional/page_objects/visual_builder_page.ts b/test/functional/page_objects/visual_builder_page.ts index 7f1ea64bcd979..ea11560e37b6f 100644 --- a/test/functional/page_objects/visual_builder_page.ts +++ b/test/functional/page_objects/visual_builder_page.ts @@ -447,7 +447,9 @@ export class VisualBuilderPageObject extends FtrService { const metricsIndexPatternInput = 'metricsIndexPatternInput'; if (useKibanaIndices !== undefined) { - await this.switchIndexPatternSelectionMode(useKibanaIndices); + await this.retry.try(async () => { + await this.switchIndexPatternSelectionMode(useKibanaIndices); + }); } if (useKibanaIndices === false) { diff --git a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/app/components/main.tsx b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/app/components/main.tsx index cf720657291f8..b03451bdebad2 100644 --- a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/app/components/main.tsx +++ b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/app/components/main.tsx @@ -9,7 +9,7 @@ import './main.scss'; import React from 'react'; import { EuiPage, EuiPageBody, EuiPageContent, EuiPageContentHeader } from '@elastic/eui'; -import { first } from 'rxjs/operators'; +import { first, pluck } from 'rxjs/operators'; import { IInterpreterRenderHandlers, ExpressionValue, @@ -59,7 +59,9 @@ class Main extends React.Component<{}, State> { inspectorAdapters: adapters, searchContext: initialContext as any, }) - .getData(); + .getData() + .pipe(pluck('result')) + .toPromise(); }; let lastRenderHandler: ExpressionRenderHandler; diff --git a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/server/plugin.ts b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/server/plugin.ts index 923113cc99ba8..a4903fedd22d5 100644 --- a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/server/plugin.ts +++ b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/server/plugin.ts @@ -7,6 +7,7 @@ */ import { schema } from '@kbn/config-schema'; +import { pluck } from 'rxjs/operators'; import { CoreSetup, Plugin, HttpResponsePayload } from '../../../../../src/core/server'; import { PluginStart as DataPluginStart } from '../../../../../src/plugins/data/server'; import { ExpressionsServerStart } from '../../../../../src/plugins/expressions/server'; @@ -32,13 +33,12 @@ export class TestPlugin implements Plugin { const [, { expressions }] = await core.getStartServices(); - const output = await expressions.run( - req.body.expression, - req.body.input, - { + const output = await expressions + .run(req.body.expression, req.body.input, { kibanaRequest: req, - } - ); + }) + .pipe(pluck('result')) + .toPromise(); return res.ok({ body: output }); } ); diff --git a/x-pack/plugins/apm/kibana.json b/x-pack/plugins/apm/kibana.json index 21aef379715c7..ae4510b10acd4 100644 --- a/x-pack/plugins/apm/kibana.json +++ b/x-pack/plugins/apm/kibana.json @@ -3,39 +3,34 @@ "version": "8.0.0", "kibanaVersion": "kibana", "requiredPlugins": [ - "features", "apmOss", "data", - "licensing", - "triggersActionsUi", "embeddable", + "features", + "fleet", "infra", + "licensing", "observability", - "ruleRegistry" + "ruleRegistry", + "triggersActionsUi" ], "optionalPlugins": [ - "spaces", - "cloud", - "usageCollection", - "taskManager", "actions", "alerting", - "security", - "ml", + "cloud", "home", "maps", - "fleet" + "ml", + "security", + "spaces", + "taskManager", + "usageCollection" ], "server": true, "ui": true, - "configPath": [ - "xpack", - "apm" - ], - "extraPublicDirs": [ - "public/style/variables" - ], + "configPath": ["xpack", "apm"], "requiredBundles": [ + "fleet", "home", "kibanaReact", "kibanaUtils", @@ -43,4 +38,4 @@ "ml", "observability" ] -} \ No newline at end of file +} diff --git a/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.stories.tsx b/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.stories.tsx index d069d4a11b494..16b8cc34e9752 100644 --- a/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/alerting/transaction_duration_alert_trigger/index.stories.tsx @@ -17,7 +17,7 @@ import { import { MockUrlParamsContextProvider } from '../../../context/url_params_context/mock_url_params_context_provider'; export default { - title: 'app/TransactionDurationAlertTrigger', + title: 'alerting/TransactionDurationAlertTrigger', component: TransactionDurationAlertTrigger, decorators: [ (Story: ComponentType) => { @@ -26,7 +26,7 @@ export default { http: { get: (endpoint: string) => { if (endpoint === '/api/apm/environments') { - return Promise.resolve(['production']); + return Promise.resolve({ environments: ['production'] }); } else { return Promise.resolve({ transactionTypes: ['request'], diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/ServicePage/FormRowSelect.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/ServicePage/FormRowSelect.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/ServicePage/FormRowSelect.tsx rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/ServicePage/FormRowSelect.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/ServicePage/ServicePage.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/ServicePage/ServicePage.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/ServicePage/ServicePage.tsx rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/ServicePage/ServicePage.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingFormRow.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/SettingFormRow.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingFormRow.tsx rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/SettingFormRow.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.stories.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/index.stories.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.stories.tsx rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/index.stories.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/index.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.tsx rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/AgentConfigurationCreateEdit/index.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/ConfirmDeleteModal.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/ConfirmDeleteModal.tsx rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/ConfirmDeleteModal.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/index.tsx similarity index 96% rename from x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx rename to x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/index.tsx index c098be41968dd..93ae8b270b5de 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/agent_configurations/List/index.tsx @@ -22,13 +22,12 @@ import { getOptionLabel } from '../../../../../../common/agent_configuration/all import { useApmPluginContext } from '../../../../../context/apm_plugin/use_apm_plugin_context'; import { FETCH_STATUS } from '../../../../../hooks/use_fetcher'; import { useTheme } from '../../../../../hooks/use_theme'; -import { px, units } from '../../../../../style/variables'; import { createAgentConfigurationHref, editAgentConfigurationHref, } from '../../../../shared/Links/apm/agentConfigurationLinks'; import { LoadingStatePrompt } from '../../../../shared/LoadingStatePrompt'; -import { ITableColumn, ManagedTable } from '../../../../shared/ManagedTable'; +import { ITableColumn, ManagedTable } from '../../../../shared/managed_table'; import { TimestampTooltip } from '../../../../shared/TimestampTooltip'; import { ConfirmDeleteModal } from './ConfirmDeleteModal'; @@ -125,7 +124,7 @@ export function AgentConfigurationList({ { field: 'applied_by_agent', align: 'center', - width: px(units.double), + width: theme.eui.euiSizeXL, name: '', sortable: true, render: (isApplied: boolean) => ( @@ -190,7 +189,7 @@ export function AgentConfigurationList({ ...(canSave ? [ { - width: px(units.double), + width: theme.eui.euiSizeXL, name: '', render: (config: Config) => ( ( { +function Wrapper({ children }: { children?: ReactNode }) { + return ( + + {children} + + ); +} + +describe('DeleteButton', () => { beforeAll(() => { jest.spyOn(apmApi, 'callApmApi').mockResolvedValue({}); }); + it('deletes a custom link', async () => { const onDeleteMock = jest.fn(); const { getByText } = render( - - - + , + { wrapper: Wrapper } ); + await act(async () => { fireEvent.click(getByText('Delete')); }); + expect(onDeleteMock).toHaveBeenCalledTimes(1); }); }); diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/DeleteButton.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/DeleteButton.tsx similarity index 93% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/DeleteButton.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/DeleteButton.tsx index eb6dfdd763ac4..c6547aaff0671 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/DeleteButton.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/DeleteButton.tsx @@ -9,9 +9,9 @@ import { EuiButtonEmpty } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { NotificationsStart } from 'kibana/public'; import React, { useState } from 'react'; -import { px, unit } from '../../../../../../style/variables'; import { callApmApi } from '../../../../../../services/rest/createCallApmApi'; import { useApmPluginContext } from '../../../../../../context/apm_plugin/use_apm_plugin_context'; +import { useTheme } from '../../../../../../hooks/use_theme'; interface Props { onDelete: () => void; @@ -21,6 +21,7 @@ interface Props { export function DeleteButton({ onDelete, customLinkId }: Props) { const [isDeleting, setIsDeleting] = useState(false); const { toasts } = useApmPluginContext().core.notifications; + const theme = useTheme(); return ( {i18n.translate('xpack.apm.settings.customizeUI.customLink.delete', { defaultMessage: 'Delete', diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/Documentation.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/Documentation.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/Documentation.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/Documentation.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/FiltersSection.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/FiltersSection.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/FiltersSection.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/FiltersSection.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/FlyoutFooter.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/FlyoutFooter.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/FlyoutFooter.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/FlyoutFooter.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/LinkSection.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/LinkSection.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/LinkSection.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/LinkSection.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/helper.test.ts b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.test.ts similarity index 98% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/helper.test.ts rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.test.ts index c4420f3a59c81..449968b82943f 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/helper.test.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.test.ts @@ -8,7 +8,7 @@ import { getSelectOptions, replaceTemplateVariables, -} from '../CreateEditCustomLinkFlyout/helper'; +} from '../create_edit_custom_link_flyout/helper'; import { Transaction } from '../../../../../../../typings/es_schemas/ui/transaction'; describe('Custom link helper', () => { diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/helper.ts b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/helper.ts rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper.ts diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/index.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/index.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/index.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/link_preview.stories.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.stories.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/link_preview.stories.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.stories.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/link_preview.test.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/link_preview.test.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/link_preview.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/link_preview.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/link_preview.tsx diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/saveCustomLink.ts b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/saveCustomLink.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/saveCustomLink.ts rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/saveCustomLink.ts diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/custom_link_table.tsx similarity index 95% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/custom_link_table.tsx index bb948ea665b1e..9593802407193 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/custom_link_table.tsx @@ -5,22 +5,21 @@ * 2.0. */ -import React, { useState } from 'react'; -import { i18n } from '@kbn/i18n'; import { EuiFieldSearch, EuiFlexGroup, EuiFlexItem, - EuiText, EuiSpacer, + EuiText, } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; import { isEmpty } from 'lodash'; -import { useApmPluginContext } from '../../../../../context/apm_plugin/use_apm_plugin_context'; +import React, { useState } from 'react'; import { CustomLink } from '../../../../../../common/custom_link/custom_link_types'; -import { units, px } from '../../../../../style/variables'; -import { ManagedTable } from '../../../../shared/ManagedTable'; -import { TimestampTooltip } from '../../../../shared/TimestampTooltip'; +import { useApmPluginContext } from '../../../../../context/apm_plugin/use_apm_plugin_context'; import { LoadingStatePrompt } from '../../../../shared/LoadingStatePrompt'; +import { ManagedTable } from '../../../../shared/managed_table'; +import { TimestampTooltip } from '../../../../shared/TimestampTooltip'; interface Props { items: CustomLink[]; @@ -50,7 +49,7 @@ export function CustomLinkTable({ items = [], onCustomLinkSelected }: Props) { truncateText: true, }, { - width: px(160), + width: 160, align: 'right', field: '@timestamp', name: i18n.translate( @@ -63,7 +62,7 @@ export function CustomLinkTable({ items = [], onCustomLinkSelected }: Props) { ), }, { - width: px(units.triple), + width: '48px', name: '', actions: [ ...(canSave diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.test.tsx similarity index 99% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.test.tsx index 7d119b8c406da..22fbfb04734ba 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.test.tsx @@ -22,7 +22,7 @@ import { expectTextsInDocument, expectTextsNotInDocument, } from '../../../../../utils/testHelpers'; -import * as saveCustomLink from './CreateEditCustomLinkFlyout/saveCustomLink'; +import * as saveCustomLink from './create_edit_custom_link_flyout/saveCustomLink'; const data = { customLinks: [ diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.tsx similarity index 96% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.tsx index c1315f165abdb..beea1d8276846 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/custom_link/index.tsx @@ -8,21 +8,21 @@ import { EuiFlexGroup, EuiFlexItem, - EuiTitle, - EuiText, EuiSpacer, + EuiText, + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isEmpty } from 'lodash'; import React, { useEffect, useState } from 'react'; import { INVALID_LICENSE } from '../../../../../../common/custom_link'; import { CustomLink } from '../../../../../../common/custom_link/custom_link_types'; -import { FETCH_STATUS, useFetcher } from '../../../../../hooks/use_fetcher'; import { useLicenseContext } from '../../../../../context/license/use_license_context'; +import { FETCH_STATUS, useFetcher } from '../../../../../hooks/use_fetcher'; import { LicensePrompt } from '../../../../shared/license_prompt'; import { CreateCustomLinkButton } from './CreateCustomLinkButton'; -import { CreateEditCustomLinkFlyout } from './CreateEditCustomLinkFlyout'; -import { CustomLinkTable } from './CustomLinkTable'; +import { CreateEditCustomLinkFlyout } from './create_edit_custom_link_flyout'; +import { CustomLinkTable } from './custom_link_table'; import { EmptyPrompt } from './EmptyPrompt'; export function CustomLinkOverview() { diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/index.tsx similarity index 87% rename from x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx rename to x-pack/plugins/apm/public/components/app/Settings/customize_ui/index.tsx index 9ce1f1325bb2c..9d3ee3fa47c1a 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/customize_ui/index.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { CustomLinkOverview } from './CustomLink'; +import { CustomLinkOverview } from './custom_link'; export function CustomizeUI() { return ; diff --git a/x-pack/plugins/apm/public/components/app/correlations/error_correlations.tsx b/x-pack/plugins/apm/public/components/app/correlations/error_correlations.tsx index 526aad56e743e..f0d7f8d60eb6c 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/error_correlations.tsx +++ b/x-pack/plugins/apm/public/components/app/correlations/error_correlations.tsx @@ -6,33 +6,32 @@ */ import { - ScaleType, - Chart, - LineSeries, Axis, + Chart, CurveType, + LineSeries, Position, - timeFormatter, + ScaleType, Settings, + timeFormatter, } from '@elastic/charts'; +import { EuiFlexGroup, EuiFlexItem, EuiText, EuiTitle } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; import React, { useState } from 'react'; import { useParams } from 'react-router-dom'; -import { EuiTitle, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; +import { useUiTracker } from '../../../../../observability/public'; import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLocalStorage } from '../../../hooks/useLocalStorage'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; +import { useTheme } from '../../../hooks/use_theme'; import { APIReturnType } from '../../../services/rest/createCallApmApi'; -import { px } from '../../../style/variables'; +import { ChartContainer } from '../../shared/charts/chart_container'; import { CorrelationsTable, SelectedSignificantTerm, } from './correlations_table'; -import { ChartContainer } from '../../shared/charts/chart_container'; -import { useTheme } from '../../../hooks/use_theme'; import { CustomFields } from './custom_fields'; import { useFieldNames } from './use_field_names'; -import { useLocalStorage } from '../../../hooks/useLocalStorage'; -import { useUiTracker } from '../../../../../observability/public'; type OverallErrorsApiResponse = NonNullable< APIReturnType<'GET /api/apm/correlations/errors/overall_timeseries'> @@ -221,7 +220,7 @@ function ErrorTimeseriesChart({ return ( - + theme.eui.euiSize}; `; const TransactionLinkName = euiStyled.div` - margin-left: ${px(units.half)}; + margin-left: ${({ theme }) => theme.eui.euiSizeS}; display: inline-block; vertical-align: middle; `; diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx similarity index 92% rename from x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx rename to x-pack/plugins/apm/public/components/app/error_group_details/index.tsx index 3d22c3863c100..344393d42506f 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx @@ -19,32 +19,31 @@ import React from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { useTrackPageview } from '../../../../../observability/public'; import { NOT_AVAILABLE_LABEL } from '../../../../common/i18n'; -import { useFetcher } from '../../../hooks/use_fetcher'; import { useUrlParams } from '../../../context/url_params_context/use_url_params'; -import { fontFamilyCode, fontSizes, px, units } from '../../../style/variables'; -import { DetailView } from './DetailView'; -import { ErrorDistribution } from './Distribution'; import { useErrorGroupDistributionFetcher } from '../../../hooks/use_error_group_distribution_fetcher'; +import { useFetcher } from '../../../hooks/use_fetcher'; +import { DetailView } from './detail_view'; +import { ErrorDistribution } from './Distribution'; const Titles = euiStyled.div` - margin-bottom: ${px(units.plus)}; + margin-bottom: ${({ theme }) => theme.eui.euiSizeL}; `; const Label = euiStyled.div` - margin-bottom: ${px(units.quarter)}; - font-size: ${fontSizes.small}; + margin-bottom: ${({ theme }) => theme.eui.euiSizeXS}; + font-size: ${({ theme }) => theme.eui.euiFontSizeXS}; color: ${({ theme }) => theme.eui.euiColorDarkShade}; `; const Message = euiStyled.div` - font-family: ${fontFamilyCode}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; font-weight: bold; - font-size: ${fontSizes.large}; - margin-bottom: ${px(units.half)}; + font-size: ${({ theme }) => theme.eui.euiFontSizeM}; + margin-bottom: ${({ theme }) => theme.eui.euiSizeS}; `; const Culprit = euiStyled.div` - font-family: ${fontFamilyCode}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; `; function getShortGroupId(errorGroupId?: string) { diff --git a/x-pack/plugins/apm/public/components/app/error_group_overview/List/List.test.tsx b/x-pack/plugins/apm/public/components/app/error_group_overview/List/List.test.tsx index e368230fbc77e..a2a92b7e16f8e 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_overview/List/List.test.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_overview/List/List.test.tsx @@ -13,6 +13,7 @@ import { mockMoment, toJson } from '../../../../utils/testHelpers'; import { ErrorGroupList } from './index'; import props from './__fixtures__/props.json'; import { MemoryRouter } from 'react-router-dom'; +import { EuiThemeProvider } from '../../../../../../../../src/plugins/kibana_react/common'; jest.mock('@elastic/eui/lib/services/accessibility/html_id_generator', () => { return { @@ -41,13 +42,18 @@ describe('ErrorGroupOverview -> List', () => { it('should render with data', () => { const wrapper = mount( - - - - - - - + + + + + + + + + ); expect(toJson(wrapper)).toMatchSnapshot(); diff --git a/x-pack/plugins/apm/public/components/app/error_group_overview/List/__snapshots__/List.test.tsx.snap b/x-pack/plugins/apm/public/components/app/error_group_overview/List/__snapshots__/List.test.tsx.snap index 92337a97573e4..2b85d6bb3c229 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_overview/List/__snapshots__/List.test.tsx.snap +++ b/x-pack/plugins/apm/public/components/app/error_group_overview/List/__snapshots__/List.test.tsx.snap @@ -268,7 +268,7 @@ exports[`ErrorGroupOverview -> List should render empty state 1`] = ` exports[`ErrorGroupOverview -> List should render with data 1`] = ` .c0 { - font-family: "Roboto Mono",Consolas,Menlo,Courier,monospace; + font-family: 'Roboto Mono','Consolas','Menlo','Courier',monospace; } .c2 { @@ -286,8 +286,8 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` } .c3 { - font-family: "Roboto Mono",Consolas,Menlo,Courier,monospace; - font-size: 16px; + font-family: 'Roboto Mono','Consolas','Menlo','Courier',monospace; + font-size: 18px; max-width: 100%; white-space: nowrap; overflow: hidden; @@ -295,7 +295,7 @@ exports[`ErrorGroupOverview -> List should render with data 1`] = ` } .c4 { - font-family: "Roboto Mono",Consolas,Menlo,Courier,monospace; + font-family: 'Roboto Mono','Consolas','Menlo','Courier',monospace; }
theme.eui.euiCodeFontFamily}; `; const MessageAndCulpritCell = euiStyled.div` @@ -40,13 +33,13 @@ const ErrorLink = euiStyled(ErrorOverviewLink)` `; const MessageLink = euiStyled(ErrorDetailLink)` - font-family: ${fontFamilyCode}; - font-size: ${fontSizes.large}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; + font-size: ${({ theme }) => theme.eui.euiFontSizeM}; ${truncate('100%')}; `; const Culprit = euiStyled.div` - font-family: ${fontFamilyCode}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; `; type ErrorGroupItem = APIReturnType<'GET /api/apm/services/{serviceName}/errors'>['errorGroups'][0]; @@ -86,7 +79,7 @@ function ErrorGroupList({ items, serviceName }: Props) { ), field: 'groupId', sortable: false, - width: px(unit * 6), + width: unit * 6, render: (groupId: string) => { return ( diff --git a/x-pack/plugins/apm/public/components/app/error_group_overview/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_overview/index.tsx index 886ef8412f35b..4c622758e6c8b 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_overview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_overview/index.tsx @@ -18,7 +18,7 @@ import { useTrackPageview } from '../../../../../observability/public'; import { useUrlParams } from '../../../context/url_params_context/use_url_params'; import { useErrorGroupDistributionFetcher } from '../../../hooks/use_error_group_distribution_fetcher'; import { useFetcher } from '../../../hooks/use_fetcher'; -import { ErrorDistribution } from '../ErrorGroupDetails/Distribution'; +import { ErrorDistribution } from '../error_group_details/Distribution'; import { ErrorGroupList } from './List'; interface ErrorGroupOverviewProps { diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx index e4a0ef3ef09f1..cac94885511c1 100644 --- a/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx @@ -18,8 +18,8 @@ import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { useUpgradeAssistantHref } from '../../shared/Links/kibana'; import { SearchBar } from '../../shared/search_bar'; import { NoServicesMessage } from './no_services_message'; -import { ServiceList } from './ServiceList'; -import { MLCallout } from './ServiceList/MLCallout'; +import { ServiceList } from './service_list'; +import { MLCallout } from './service_list/MLCallout'; const initialData = { items: [], diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/HealthBadge.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/HealthBadge.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/HealthBadge.tsx rename to x-pack/plugins/apm/public/components/app/service_inventory/service_list/HealthBadge.tsx diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/MLCallout.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/MLCallout.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/MLCallout.tsx rename to x-pack/plugins/apm/public/components/app/service_inventory/service_list/MLCallout.tsx diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/ServiceListMetric.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/ServiceListMetric.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/ServiceListMetric.tsx rename to x-pack/plugins/apm/public/components/app/service_inventory/service_list/ServiceListMetric.tsx diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/__fixtures__/service_api_mock_data.ts b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/__fixtures__/service_api_mock_data.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/__fixtures__/service_api_mock_data.ts rename to x-pack/plugins/apm/public/components/app/service_inventory/service_list/__fixtures__/service_api_mock_data.ts diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/index.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/index.tsx similarity index 95% rename from x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/index.tsx rename to x-pack/plugins/apm/public/components/app/service_inventory/service_list/index.tsx index 6c40639594adf..b4644068fd782 100644 --- a/x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/index.tsx @@ -5,31 +5,35 @@ * 2.0. */ -import { EuiFlexItem, EuiFlexGroup, EuiToolTip } from '@elastic/eui'; +import { + EuiFlexGroup, + EuiFlexItem, + EuiIcon, + EuiText, + EuiToolTip, +} from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import { orderBy } from 'lodash'; import React, { useMemo } from 'react'; import { ValuesType } from 'utility-types'; -import { orderBy } from 'lodash'; -import { EuiIcon } from '@elastic/eui'; -import { EuiText } from '@elastic/eui'; import { euiStyled } from '../../../../../../../../src/plugins/kibana_react/common'; +import { NOT_AVAILABLE_LABEL } from '../../../../../common/i18n'; +import { ServiceHealthStatus } from '../../../../../common/service_health_status'; import { TRANSACTION_PAGE_LOAD, TRANSACTION_REQUEST, } from '../../../../../common/transaction_types'; -import { APIReturnType } from '../../../../services/rest/createCallApmApi'; -import { ServiceHealthStatus } from '../../../../../common/service_health_status'; import { - asPercent, asMillisecondDuration, + asPercent, asTransactionRate, } from '../../../../../common/utils/formatters'; -import { NOT_AVAILABLE_LABEL } from '../../../../../common/i18n'; -import { fontSizes, px, truncate, unit } from '../../../../style/variables'; -import { ManagedTable, ITableColumn } from '../../../shared/ManagedTable'; +import { APIReturnType } from '../../../../services/rest/createCallApmApi'; +import { truncate, unit } from '../../../../utils/style'; +import { AgentIcon } from '../../../shared/agent_icon'; import { EnvironmentBadge } from '../../../shared/EnvironmentBadge'; import { ServiceOrTransactionsOverviewLink } from '../../../shared/Links/apm/service_transactions_overview_link'; -import { AgentIcon } from '../../../shared/agent_icon'; +import { ITableColumn, ManagedTable } from '../../../shared/managed_table'; import { HealthBadge } from './HealthBadge'; import { ServiceListMetric } from './ServiceListMetric'; @@ -47,7 +51,7 @@ function formatString(value?: string | null) { } const AppLink = euiStyled(ServiceOrTransactionsOverviewLink)` - font-size: ${fontSizes.large}; + font-size: ${({ theme }) => theme.eui.euiFontSizeM} ${truncate('100%')}; `; @@ -80,7 +84,7 @@ export function getServiceColumns({ name: i18n.translate('xpack.apm.servicesTable.healthColumnLabel', { defaultMessage: 'Health', }), - width: px(unit * 6), + width: unit * 6, sortable: true, render: (_, { healthStatus }) => { return ( @@ -130,7 +134,7 @@ export function getServiceColumns({ name: i18n.translate('xpack.apm.servicesTable.environmentColumnLabel', { defaultMessage: 'Environment', }), - width: px(unit * 10), + width: unit * 10, sortable: true, render: (_, { environments }) => ( @@ -144,7 +148,7 @@ export function getServiceColumns({ 'xpack.apm.servicesTable.transactionColumnLabel', { defaultMessage: 'Transaction type' } ), - width: px(unit * 10), + width: unit * 10, sortable: true, }, ] @@ -164,7 +168,7 @@ export function getServiceColumns({ /> ), align: 'left', - width: px(unit * 10), + width: unit * 10, }, { field: 'transactionsPerMinute', @@ -181,7 +185,7 @@ export function getServiceColumns({ /> ), align: 'left', - width: px(unit * 10), + width: unit * 10, }, { field: 'transactionErrorRate', @@ -204,7 +208,7 @@ export function getServiceColumns({ ); }, align: 'left', - width: px(unit * 10), + width: unit * 10, }, ]; } diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/service_list.test.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_list/service_list.test.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/service_inventory/ServiceList/service_list.test.tsx rename to x-pack/plugins/apm/public/components/app/service_inventory/service_list/service_list.test.tsx diff --git a/x-pack/plugins/apm/public/components/app/service_map/Popover/Popover.stories.tsx b/x-pack/plugins/apm/public/components/app/service_map/Popover/Popover.stories.tsx index fe3922060533a..6b7626514d03f 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Popover/Popover.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Popover/Popover.stories.tsx @@ -17,7 +17,7 @@ import { Popover } from '.'; import exampleGroupedConnectionsData from '../__stories__/example_grouped_connections.json'; export default { - title: 'app/service_map/Popover', + title: 'app/ServiceMap/Popover', component: Popover, decorators: [ (Story: ComponentType) => { diff --git a/x-pack/plugins/apm/public/components/app/service_map/Popover/ServiceStatsFetcher.tsx b/x-pack/plugins/apm/public/components/app/service_map/Popover/ServiceStatsFetcher.tsx index a71f299ab296c..3155a65b06aca 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Popover/ServiceStatsFetcher.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Popover/ServiceStatsFetcher.tsx @@ -18,7 +18,7 @@ import { ServiceNodeStats } from '../../../../../common/service_map'; import { ServiceStatsList } from './ServiceStatsList'; import { useFetcher, FETCH_STATUS } from '../../../../hooks/use_fetcher'; import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; -import { AnomalyDetection } from './AnomalyDetection'; +import { AnomalyDetection } from './anomaly_detection'; import { ServiceAnomalyStats } from '../../../../../common/anomaly_detection'; interface ServiceStatsFetcherProps { diff --git a/x-pack/plugins/apm/public/components/app/service_map/Popover/AnomalyDetection.tsx b/x-pack/plugins/apm/public/components/app/service_map/Popover/anomaly_detection.tsx similarity index 96% rename from x-pack/plugins/apm/public/components/app/service_map/Popover/AnomalyDetection.tsx rename to x-pack/plugins/apm/public/components/app/service_map/Popover/anomaly_detection.tsx index c98116a69da66..1ceb90ff838ad 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Popover/AnomalyDetection.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Popover/anomaly_detection.tsx @@ -5,30 +5,29 @@ * 2.0. */ -import { i18n } from '@kbn/i18n'; -import React from 'react'; import { EuiFlexGroup, EuiFlexItem, - EuiTitle, - EuiIconTip, EuiHealth, + EuiIconTip, + EuiTitle, } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import React from 'react'; import { euiStyled } from '../../../../../../../../src/plugins/kibana_react/common'; +import { + getSeverity, + ServiceAnomalyStats, +} from '../../../../../common/anomaly_detection'; import { getServiceHealthStatus, getServiceHealthStatusColor, } from '../../../../../common/service_health_status'; +import { TRANSACTION_REQUEST } from '../../../../../common/transaction_types'; +import { asDuration, asInteger } from '../../../../../common/utils/formatters'; import { useTheme } from '../../../../hooks/use_theme'; -import { fontSize, px } from '../../../../style/variables'; -import { asInteger, asDuration } from '../../../../../common/utils/formatters'; import { MLSingleMetricLink } from '../../../shared/Links/MachineLearningLinks/MLSingleMetricLink'; import { popoverWidth } from '../cytoscape_options'; -import { TRANSACTION_REQUEST } from '../../../../../common/transaction_types'; -import { - getSeverity, - ServiceAnomalyStats, -} from '../../../../../common/anomaly_detection'; const HealthStatusTitle = euiStyled(EuiTitle)` display: inline; @@ -47,8 +46,8 @@ const SubduedText = euiStyled.span` const EnableText = euiStyled.section` color: ${({ theme }) => theme.eui.euiTextSubduedColor}; line-height: 1.4; - font-size: ${fontSize}; - width: ${px(popoverWidth)}; + font-size: ${({ theme }) => theme.eui.euiFontSizeS}; + width: ${popoverWidth}px; `; export const ContentLine = euiStyled.section` diff --git a/x-pack/plugins/apm/public/components/app/service_map/Popover/service_stats_list.stories.tsx b/x-pack/plugins/apm/public/components/app/service_map/Popover/service_stats_list.stories.tsx index 83f0a3ea7e4b9..a8f004a7295d9 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Popover/service_stats_list.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Popover/service_stats_list.stories.tsx @@ -10,7 +10,7 @@ import { EuiThemeProvider } from '../../../../../../../../src/plugins/kibana_rea import { ServiceStatsList } from './ServiceStatsList'; export default { - title: 'app/service_map/Popover/ServiceStatsList', + title: 'app/ServiceMap/Popover/ServiceStatsList', component: ServiceStatsList, decorators: [ (Story: ComponentType) => ( diff --git a/x-pack/plugins/apm/public/components/app/service_map/__stories__/Cytoscape.stories.tsx b/x-pack/plugins/apm/public/components/app/service_map/__stories__/Cytoscape.stories.tsx index dbab10d7b93b6..8bc0d7239e9c5 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/__stories__/Cytoscape.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/__stories__/Cytoscape.stories.tsx @@ -12,7 +12,7 @@ import { Cytoscape } from '../Cytoscape'; import { Centerer } from './centerer'; export default { - title: 'app/service_map/Cytoscape', + title: 'app/ServiceMap/Cytoscape', component: Cytoscape, decorators: [ (Story: ComponentType) => ( diff --git a/x-pack/plugins/apm/public/components/app/service_map/__stories__/cytoscape_example_data.stories.tsx b/x-pack/plugins/apm/public/components/app/service_map/__stories__/cytoscape_example_data.stories.tsx index 84351d5716edb..45de632a152d4 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/__stories__/cytoscape_example_data.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/__stories__/cytoscape_example_data.stories.tsx @@ -25,7 +25,7 @@ import exampleResponseOpbeansBeats from './example_response_opbeans_beats.json'; import exampleResponseTodo from './example_response_todo.json'; import { generateServiceMapElements } from './generate_service_map_elements'; -const STORYBOOK_PATH = 'app/service_map/Cytoscape/Example data'; +const STORYBOOK_PATH = 'app/ServiceMap/Example data'; const SESSION_STORAGE_KEY = `${STORYBOOK_PATH}/pre-loaded map`; function getSessionJson() { @@ -40,7 +40,7 @@ function getHeight() { } export default { - title: 'app/service_map/Cytoscape/Example data', + title: 'app/ServiceMap/Example data', component: Cytoscape, decorators: [ (Story: ComponentType) => ( diff --git a/x-pack/plugins/apm/public/components/app/service_node_metrics/index.tsx b/x-pack/plugins/apm/public/components/app/service_node_metrics/index.tsx index a147528d42cae..07afcbc9c4682 100644 --- a/x-pack/plugins/apm/public/components/app/service_node_metrics/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_node_metrics/index.tsx @@ -20,12 +20,12 @@ import { FormattedMessage } from '@kbn/i18n/react'; import React from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { SERVICE_NODE_NAME_MISSING } from '../../../../common/service_nodes'; +import { useApmServiceContext } from '../../../context/apm_service/use_apm_service_context'; import { ChartPointerEventContextProvider } from '../../../context/chart_pointer_event/chart_pointer_event_context'; +import { useUrlParams } from '../../../context/url_params_context/use_url_params'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { useServiceMetricChartsFetcher } from '../../../hooks/use_service_metric_charts_fetcher'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; -import { useApmServiceContext } from '../../../context/apm_service/use_apm_service_context'; -import { px, truncate, unit } from '../../../style/variables'; +import { truncate, unit } from '../../../utils/style'; import { MetricsChart } from '../../shared/charts/metrics_chart'; import { ElasticDocsLink } from '../../shared/Links/ElasticDocsLink'; @@ -36,7 +36,7 @@ const INITIAL_DATA = { const Truncate = euiStyled.span` display: block; - ${truncate(px(unit * 12))} + ${truncate(unit * 12)} `; interface ServiceNodeMetricsProps { diff --git a/x-pack/plugins/apm/public/components/app/service_node_overview/index.tsx b/x-pack/plugins/apm/public/components/app/service_node_overview/index.tsx index 1a432f90f1e3a..58541e2c5501b 100644 --- a/x-pack/plugins/apm/public/components/app/service_node_overview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_node_overview/index.tsx @@ -19,16 +19,16 @@ import { } from '../../../../common/utils/formatters'; import { useUrlParams } from '../../../context/url_params_context/use_url_params'; import { useFetcher } from '../../../hooks/use_fetcher'; -import { px, truncate, unit } from '../../../style/variables'; +import { truncate, unit } from '../../../utils/style'; import { ServiceNodeMetricOverviewLink } from '../../shared/Links/apm/ServiceNodeMetricOverviewLink'; -import { ITableColumn, ManagedTable } from '../../shared/ManagedTable'; +import { ITableColumn, ManagedTable } from '../../shared/managed_table'; const INITIAL_PAGE_SIZE = 25; const INITIAL_SORT_FIELD = 'cpu'; const INITIAL_SORT_DIRECTION = 'desc'; const ServiceNodeName = euiStyled.div` - ${truncate(px(8 * unit))} + ${truncate(8 * unit)} `; interface ServiceNodeOverviewProps { diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx index b1a4d5ca5fda7..0067558865bd6 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx @@ -15,19 +15,19 @@ import { import { i18n } from '@kbn/i18n'; import { keyBy } from 'lodash'; import React from 'react'; -import { offsetPreviousPeriodCoordinates } from '../../../../../common/utils/offset_previous_period_coordinate'; -import { Coordinate } from '../../../../../typings/timeseries'; import { getNextEnvironmentUrlParam } from '../../../../../common/environment_filter_values'; import { asMillisecondDuration, asPercent, asTransactionRate, } from '../../../../../common/utils/formatters'; +import { offsetPreviousPeriodCoordinates } from '../../../../../common/utils/offset_previous_period_coordinate'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { ServiceDependencyItem } from '../../../../../server/lib/services/get_service_dependencies'; +import { Coordinate } from '../../../../../typings/timeseries'; import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; import { FETCH_STATUS, useFetcher } from '../../../../hooks/use_fetcher'; -import { px, unit } from '../../../../style/variables'; +import { unit } from '../../../../utils/style'; import { AgentIcon } from '../../../shared/agent_icon'; import { SparkPlot } from '../../../shared/charts/spark_plot'; import { ImpactBar } from '../../../shared/ImpactBar'; @@ -156,7 +156,7 @@ export function ServiceOverviewDependenciesTable({ serviceName }: Props) { defaultMessage: 'Latency (avg.)', } ), - width: px(unit * 10), + width: `${unit * 10}px`, render: (_, { latency }) => { return ( { return ( { return ( { return ( diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/get_column.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/get_column.tsx index 4ad83f7d87426..b458f6147b3f1 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/get_column.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/get_column.tsx @@ -9,12 +9,12 @@ import { EuiBasicTableColumn } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import { asInteger } from '../../../../../common/utils/formatters'; -import { px, unit } from '../../../../style/variables'; +import { APIReturnType } from '../../../../services/rest/createCallApmApi'; +import { unit } from '../../../../utils/style'; import { SparkPlot } from '../../../shared/charts/spark_plot'; import { ErrorDetailLink } from '../../../shared/Links/apm/ErrorDetailLink'; import { TimestampTooltip } from '../../../shared/TimestampTooltip'; import { TruncateWithTooltip } from '../../../shared/truncate_with_tooltip'; -import { APIReturnType } from '../../../../services/rest/createCallApmApi'; type ErrorGroupMainStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/main_statistics'>; type ErrorGroupDetailedStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/error_groups/detailed_statistics'>; @@ -61,7 +61,7 @@ export function getColumns({ render: (_, { last_seen: lastSeen }) => { return ; }, - width: px(unit * 9), + width: `${unit * 9}px`, }, { field: 'occurrences', @@ -71,7 +71,7 @@ export function getColumns({ defaultMessage: 'Occurrences', } ), - width: px(unit * 12), + width: `${unit * 12}px`, render: (_, { occurrences, group_id: errorGroupId }) => { const currentPeriodTimeseries = errorGroupDetailedStatistics?.currentPeriod?.[errorGroupId] diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/get_columns.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/get_columns.tsx index a92efff103910..f9600b9d7f418 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/get_columns.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/get_columns.tsx @@ -25,14 +25,14 @@ import { asTransactionRate, } from '../../../../../common/utils/formatters'; import { APIReturnType } from '../../../../services/rest/createCallApmApi'; -import { px, unit } from '../../../../style/variables'; +import { unit } from '../../../../utils/style'; import { SparkPlot } from '../../../shared/charts/spark_plot'; import { MetricOverviewLink } from '../../../shared/Links/apm/MetricOverviewLink'; import { ServiceNodeMetricOverviewLink } from '../../../shared/Links/apm/ServiceNodeMetricOverviewLink'; import { TruncateWithTooltip } from '../../../shared/truncate_with_tooltip'; import { getLatencyColumnLabel } from '../get_latency_column_label'; -import { InstanceActionsMenu } from './instance_actions_menu'; import { MainStatsServiceInstanceItem } from '../service_overview_instances_chart_and_table'; +import { InstanceActionsMenu } from './instance_actions_menu'; type ServiceInstanceDetailedStatistics = APIReturnType<'GET /api/apm/services/{serviceName}/service_overview_instances/detailed_statistics'>; @@ -98,7 +98,7 @@ export function getColumns({ { field: 'latency', name: getLatencyColumnLabel(latencyAggregationType), - width: px(unit * 10), + width: `${unit * 10}px`, render: (_, { serviceNodeName, latency }) => { const currentPeriodTimestamp = detailedStatsData?.currentPeriod?.[serviceNodeName]?.latency; @@ -123,7 +123,7 @@ export function getColumns({ 'xpack.apm.serviceOverview.instancesTableColumnThroughput', { defaultMessage: 'Throughput' } ), - width: px(unit * 10), + width: `${unit * 10}px`, render: (_, { serviceNodeName, throughput }) => { const currentPeriodTimestamp = detailedStatsData?.currentPeriod?.[serviceNodeName]?.throughput; @@ -149,7 +149,7 @@ export function getColumns({ 'xpack.apm.serviceOverview.instancesTableColumnErrorRate', { defaultMessage: 'Error rate' } ), - width: px(unit * 8), + width: `${unit * 8}px`, render: (_, { serviceNodeName, errorRate }) => { const currentPeriodTimestamp = detailedStatsData?.currentPeriod?.[serviceNodeName]?.errorRate; @@ -175,7 +175,7 @@ export function getColumns({ 'xpack.apm.serviceOverview.instancesTableColumnCpuUsage', { defaultMessage: 'CPU usage (avg.)' } ), - width: px(unit * 8), + width: `${unit * 8}px`, render: (_, { serviceNodeName, cpuUsage }) => { const currentPeriodTimestamp = detailedStatsData?.currentPeriod?.[serviceNodeName]?.cpuUsage; @@ -201,7 +201,7 @@ export function getColumns({ 'xpack.apm.serviceOverview.instancesTableColumnMemoryUsage', { defaultMessage: 'Memory usage (avg.)' } ), - width: px(unit * 9), + width: `${unit * 9}px`, render: (_, { serviceNodeName, memoryUsage }) => { const currentPeriodTimestamp = detailedStatsData?.currentPeriod?.[serviceNodeName]?.memoryUsage; diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_actions_menu/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_actions_menu/index.tsx index f03c2b2fc9091..a2aaa61e8a661 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_actions_menu/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/instance_actions_menu/index.tsx @@ -20,8 +20,7 @@ import { SERVICE_NODE_NAME } from '../../../../../../common/elasticsearch_fieldn import { useApmPluginContext } from '../../../../../context/apm_plugin/use_apm_plugin_context'; import { useUrlParams } from '../../../../../context/url_params_context/use_url_params'; import { FETCH_STATUS } from '../../../../../hooks/use_fetcher'; -import { px } from '../../../../../style/variables'; -import { pushNewItemToKueryBar } from '../../../../shared/KueryBar/utils'; +import { pushNewItemToKueryBar } from '../../../../shared/kuery_bar/utils'; import { useMetricOverviewHref } from '../../../../shared/Links/apm/MetricOverviewLink'; import { useServiceNodeMetricOverviewHref } from '../../../../shared/Links/apm/ServiceNodeMetricOverviewLink'; import { useInstanceDetailsFetcher } from '../use_instance_details_fetcher'; @@ -33,7 +32,7 @@ interface Props { onClose: () => void; } -const POPOVER_WIDTH = px(305); +const POPOVER_WIDTH = '305px'; export function InstanceActionsMenu({ serviceName, diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx index 35cecc49e293b..0c77051bea293 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/intance_details.tsx @@ -28,10 +28,9 @@ import { useUrlParams } from '../../../../context/url_params_context/use_url_par import { FETCH_STATUS } from '../../../../hooks/use_fetcher'; import { useTheme } from '../../../../hooks/use_theme'; import { APIReturnType } from '../../../../services/rest/createCallApmApi'; -import { pct } from '../../../../style/variables'; import { getAgentIcon } from '../../../shared/agent_icon/get_agent_icon'; import { KeyValueFilterList } from '../../../shared/key_value_filter_list'; -import { pushNewItemToKueryBar } from '../../../shared/KueryBar/utils'; +import { pushNewItemToKueryBar } from '../../../shared/kuery_bar/utils'; import { getCloudIcon, getContainerIcon } from '../../../shared/service_icons'; import { useInstanceDetailsFetcher } from './use_instance_details_fetcher'; @@ -78,7 +77,7 @@ export function InstanceDetails({ serviceName, serviceNodeName }: Props) { status === FETCH_STATUS.NOT_INITIATED ) { return ( -
+
); diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_transactions_table/get_columns.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_transactions_table/get_columns.tsx index 9ac1c7d64d8b2..2e46e23ccaa42 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_transactions_table/get_columns.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_transactions_table/get_columns.tsx @@ -16,7 +16,7 @@ import { asTransactionRate, } from '../../../../../common/utils/formatters'; import { APIReturnType } from '../../../../services/rest/createCallApmApi'; -import { px, unit } from '../../../../style/variables'; +import { unit } from '../../../../utils/style'; import { SparkPlot } from '../../../shared/charts/spark_plot'; import { ImpactBar } from '../../../shared/ImpactBar'; import { TransactionDetailLink } from '../../../shared/Links/apm/transaction_detail_link'; @@ -71,7 +71,7 @@ export function getColumns({ field: 'latency', sortable: true, name: getLatencyColumnLabel(latencyAggregationType), - width: px(unit * 10), + width: `${unit * 10}px`, render: (_, { latency, name }) => { const currentTimeseries = transactionGroupDetailedStatistics?.currentPeriod?.[name]?.latency; @@ -97,7 +97,7 @@ export function getColumns({ 'xpack.apm.serviceOverview.transactionsTableColumnThroughput', { defaultMessage: 'Throughput' } ), - width: px(unit * 10), + width: `${unit * 10}px`, render: (_, { throughput, name }) => { const currentTimeseries = transactionGroupDetailedStatistics?.currentPeriod?.[name]?.throughput; @@ -124,7 +124,7 @@ export function getColumns({ 'xpack.apm.serviceOverview.transactionsTableColumnErrorRate', { defaultMessage: 'Error rate' } ), - width: px(unit * 8), + width: `${unit * 8}px`, render: (_, { errorRate, name }) => { const currentTimeseries = transactionGroupDetailedStatistics?.currentPeriod?.[name]?.errorRate; @@ -150,7 +150,7 @@ export function getColumns({ 'xpack.apm.serviceOverview.transactionsTableColumnImpact', { defaultMessage: 'Impact' } ), - width: px(unit * 5), + width: `${unit * 5}px`, render: (_, { name }) => { const currentImpact = transactionGroupDetailedStatistics?.currentPeriod?.[name]?.impact ?? diff --git a/x-pack/plugins/apm/public/components/app/service_profiling/service_profiling_flamegraph.tsx b/x-pack/plugins/apm/public/components/app/service_profiling/service_profiling_flamegraph.tsx index 1adf58d0394c6..82ac3a04f63f1 100644 --- a/x-pack/plugins/apm/public/components/app/service_profiling/service_profiling_flamegraph.tsx +++ b/x-pack/plugins/apm/public/components/app/service_profiling/service_profiling_flamegraph.tsx @@ -13,16 +13,16 @@ import { Settings, TooltipInfo, } from '@elastic/charts'; -import { EuiInMemoryTable } from '@elastic/eui'; -import { EuiFieldText } from '@elastic/eui'; -import { EuiToolTip } from '@elastic/eui'; import { EuiCheckbox, + EuiFieldText, EuiFlexGroup, EuiFlexItem, EuiIcon, + EuiInMemoryTable, euiPaletteForTemperature, EuiText, + EuiToolTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { find, sumBy } from 'lodash'; @@ -44,7 +44,7 @@ import { } from '../../../../common/utils/formatters'; import { useFetcher } from '../../../hooks/use_fetcher'; import { useTheme } from '../../../hooks/use_theme'; -import { px, unit } from '../../../style/variables'; +import { unit } from '../../../utils/style'; const colors = euiPaletteForTemperature(100).slice(50, 85); @@ -335,7 +335,7 @@ export function ServiceProfilingFlamegraph({ /> - + formatValue(item.value, valueUnit), - width: px(unit * 6), + width: `${unit * 6}px`, }, ]} /> diff --git a/x-pack/plugins/apm/public/components/app/trace_overview/index.tsx b/x-pack/plugins/apm/public/components/app/trace_overview/index.tsx index bf60463255d64..d280b36a603ba 100644 --- a/x-pack/plugins/apm/public/components/app/trace_overview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/trace_overview/index.tsx @@ -11,7 +11,7 @@ import { useUrlParams } from '../../../context/url_params_context/use_url_params import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { APIReturnType } from '../../../services/rest/createCallApmApi'; import { SearchBar } from '../../shared/search_bar'; -import { TraceList } from './TraceList'; +import { TraceList } from './trace_list'; type TracesAPIResponse = APIReturnType<'GET /api/apm/traces'>; const DEFAULT_RESPONSE: TracesAPIResponse = { diff --git a/x-pack/plugins/apm/public/components/app/trace_overview/TraceList.tsx b/x-pack/plugins/apm/public/components/app/trace_overview/trace_list.tsx similarity index 95% rename from x-pack/plugins/apm/public/components/app/trace_overview/TraceList.tsx rename to x-pack/plugins/apm/public/components/app/trace_overview/trace_list.tsx index 774333c35b479..f1c8df553abf7 100644 --- a/x-pack/plugins/apm/public/components/app/trace_overview/TraceList.tsx +++ b/x-pack/plugins/apm/public/components/app/trace_overview/trace_list.tsx @@ -13,18 +13,18 @@ import { asMillisecondDuration, asTransactionRate, } from '../../../../common/utils/formatters'; -import { fontSizes, truncate } from '../../../style/variables'; +import { APIReturnType } from '../../../services/rest/createCallApmApi'; +import { truncate } from '../../../utils/style'; import { EmptyMessage } from '../../shared/EmptyMessage'; import { ImpactBar } from '../../shared/ImpactBar'; -import { ITableColumn, ManagedTable } from '../../shared/ManagedTable'; -import { LoadingStatePrompt } from '../../shared/LoadingStatePrompt'; import { TransactionDetailLink } from '../../shared/Links/apm/transaction_detail_link'; -import { APIReturnType } from '../../../services/rest/createCallApmApi'; +import { LoadingStatePrompt } from '../../shared/LoadingStatePrompt'; +import { ITableColumn, ManagedTable } from '../../shared/managed_table'; type TraceGroup = APIReturnType<'GET /api/apm/traces'>['items'][0]; const StyledTransactionLink = euiStyled(TransactionDetailLink)` - font-size: ${fontSizes.large}; + font-size: ${({ theme }) => theme.eui.euiFontSizeM}; ${truncate('100%')}; `; diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/Distribution/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/Distribution/index.tsx index c7dae6ce3d1d4..f59b3ddab7c05 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/Distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/Distribution/index.tsx @@ -29,7 +29,7 @@ import type { IUrlParams } from '../../../../context/url_params_context/types'; import { FETCH_STATUS } from '../../../../hooks/use_fetcher'; import { useTheme } from '../../../../hooks/use_theme'; import { APIReturnType } from '../../../../services/rest/createCallApmApi'; -import { unit } from '../../../../style/variables'; +import { unit } from '../../../../utils/style'; import { ChartContainer } from '../../../shared/charts/chart_container'; import { EmptyMessage } from '../../../shared/EmptyMessage'; import { CustomTooltip } from './custom_tooltip'; diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/HttpContext.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/HttpContext.tsx deleted file mode 100644 index 3584309ebb20c..0000000000000 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/HttpContext.tsx +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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, { Fragment } from 'react'; -import { EuiSpacer, EuiTitle } from '@elastic/eui'; -import { euiStyled } from '../../../../../../../../../../../src/plugins/kibana_react/common'; -import { - borderRadius, - fontFamilyCode, - fontSize, - px, - unit, - units, -} from '../../../../../../../style/variables'; -import { Span } from '../../../../../../../../typings/es_schemas/ui/span'; - -const ContextUrl = euiStyled.div` - padding: ${px(units.half)} ${px(unit)}; - background: ${({ theme }) => theme.eui.euiColorLightestShade}; - border-radius: ${borderRadius}; - border: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; - font-family: ${fontFamilyCode}; - font-size: ${fontSize}; -`; - -interface Props { - httpContext: NonNullable['http']; -} - -export function HttpContext({ httpContext }: Props) { - const url = httpContext?.url?.original; - - if (!url) { - return null; - } - - return ( - - -

HTTP URL

-
- - {url} - -
- ); -} diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/index.tsx index 3cac05ba2d96a..1e13e224a511a 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/index.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/index.tsx @@ -19,7 +19,7 @@ import { HeightRetainer } from '../../shared/HeightRetainer'; import { fromQuery, toQuery } from '../../shared/Links/url_helpers'; import { TransactionDistribution } from './Distribution'; import { useWaterfallFetcher } from './use_waterfall_fetcher'; -import { WaterfallWithSummmary } from './WaterfallWithSummmary'; +import { WaterfallWithSummary } from './waterfall_with_summary'; interface Sample { traceId: string; @@ -107,7 +107,7 @@ export function TransactionDetails() { - ; @@ -39,7 +39,7 @@ interface Props { traceSamples: DistributionBucket['samples']; } -export function WaterfallWithSummmary({ +export function WaterfallWithSummary({ urlParams, waterfall, exceedsMax, diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks.test.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_agent_marks.test.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks.test.ts rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_agent_marks.test.ts diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_agent_marks.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks.ts rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_agent_marks.ts diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks.test.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_error_marks.test.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks.test.ts rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_error_marks.test.ts diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_error_marks.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks.ts rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_error_marks.ts diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/index.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/index.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/index.ts rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Marks/index.ts diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/FlyoutTopLevelProperties.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/FlyoutTopLevelProperties.tsx similarity index 97% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/FlyoutTopLevelProperties.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/FlyoutTopLevelProperties.tsx index 5f4ed551597ed..0ad0fe872a840 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/FlyoutTopLevelProperties.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/FlyoutTopLevelProperties.tsx @@ -16,7 +16,7 @@ import { import { Transaction } from '../../../../../../../typings/es_schemas/ui/transaction'; import { ServiceOrTransactionsOverviewLink } from '../../../../../shared/Links/apm/service_transactions_overview_link'; import { TransactionDetailLink } from '../../../../../shared/Links/apm/transaction_detail_link'; -import { StickyProperties } from '../../../../../shared/StickyProperties'; +import { StickyProperties } from '../../../../../shared/sticky_properties'; interface Props { transaction?: Transaction; diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/ResponsiveFlyout.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/ResponsiveFlyout.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/ResponsiveFlyout.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/ResponsiveFlyout.tsx diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/DroppedSpansWarning.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/TransactionFlyout/DroppedSpansWarning.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/DroppedSpansWarning.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/TransactionFlyout/DroppedSpansWarning.tsx diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/TransactionFlyout/index.tsx similarity index 98% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/index.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/TransactionFlyout/index.tsx index 680edf880a70e..6468e6ed1e2c8 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/index.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/TransactionFlyout/index.tsx @@ -18,7 +18,7 @@ import { import { i18n } from '@kbn/i18n'; import React from 'react'; import { Transaction } from '../../../../../../../../typings/es_schemas/ui/transaction'; -import { TransactionActionMenu } from '../../../../../../shared/TransactionActionMenu/TransactionActionMenu'; +import { TransactionActionMenu } from '../../../../../../shared/transaction_action_menu/TransactionActionMenu'; import { TransactionSummary } from '../../../../../../shared/Summary/TransactionSummary'; import { FlyoutTopLevelProperties } from '../FlyoutTopLevelProperties'; import { ResponsiveFlyout } from '../ResponsiveFlyout'; diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/WaterfallFlyout.tsx similarity index 97% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/WaterfallFlyout.tsx index fddf4fcb4efc9..ec6d550affb91 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/WaterfallFlyout.tsx @@ -8,7 +8,7 @@ import { History } from 'history'; import React from 'react'; import { useHistory } from 'react-router-dom'; -import { SpanFlyout } from './SpanFlyout'; +import { SpanFlyout } from './span_flyout'; import { TransactionFlyout } from './TransactionFlyout'; import { IWaterfall } from './waterfall_helpers/waterfall_helpers'; diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/accordion_waterfall.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/accordion_waterfall.tsx similarity index 98% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/accordion_waterfall.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/accordion_waterfall.tsx index b0721791081fa..1935d373caf79 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/accordion_waterfall.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/accordion_waterfall.tsx @@ -10,7 +10,7 @@ import { isEmpty } from 'lodash'; import React, { useState } from 'react'; import { euiStyled } from '../../../../../../../../../../src/plugins/kibana_react/common'; import { Margins } from '../../../../../shared/charts/Timeline'; -import { WaterfallItem } from './WaterfallItem'; +import { WaterfallItem } from './waterfall_item'; import { IWaterfall, IWaterfallSpanOrTransaction, diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/index.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/index.tsx diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/StickySpanProperties.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/StickySpanProperties.tsx similarity index 97% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/StickySpanProperties.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/StickySpanProperties.tsx index 60d328c98a4b7..9e1174818c43b 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/StickySpanProperties.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/StickySpanProperties.tsx @@ -19,7 +19,7 @@ import { Span } from '../../../../../../../../typings/es_schemas/ui/span'; import { Transaction } from '../../../../../../../../typings/es_schemas/ui/transaction'; import { ServiceOrTransactionsOverviewLink } from '../../../../../../shared/Links/apm/service_transactions_overview_link'; import { TransactionDetailLink } from '../../../../../../shared/Links/apm/transaction_detail_link'; -import { StickyProperties } from '../../../../../../shared/StickyProperties'; +import { StickyProperties } from '../../../../../../shared/sticky_properties'; interface Props { span: Span; diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/DatabaseContext.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/database_context.tsx similarity index 76% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/DatabaseContext.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/database_context.tsx index 6fd6873cf565e..4279205743442 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/DatabaseContext.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/database_context.tsx @@ -9,39 +9,35 @@ import { EuiSpacer, EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { tint } from 'polished'; import React, { Fragment } from 'react'; +import { Light as SyntaxHighlighter } from 'react-syntax-highlighter'; import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql'; import xcode from 'react-syntax-highlighter/dist/cjs/styles/hljs/xcode'; -import { Light as SyntaxHighlighter } from 'react-syntax-highlighter'; import { euiStyled } from '../../../../../../../../../../../src/plugins/kibana_react/common'; import { Span } from '../../../../../../../../typings/es_schemas/ui/span'; -import { - borderRadius, - fontFamilyCode, - fontSize, - px, - unit, - units, -} from '../../../../../../../style/variables'; -import { TruncateHeightSection } from './TruncateHeightSection'; +import { useTheme } from '../../../../../../../hooks/use_theme'; +import { TruncateHeightSection } from './truncate_height_section'; SyntaxHighlighter.registerLanguage('sql', sql); const DatabaseStatement = euiStyled.div` - padding: ${px(units.half)} ${px(unit)}; + padding: ${({ theme }) => + `${theme.eui.paddingSizes.s} ${theme.eui.paddingSizes.m}`}; background: ${({ theme }) => tint(0.9, theme.eui.euiColorWarning)}; - border-radius: ${borderRadius}; + border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; border: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; - font-family: ${fontFamilyCode}; - font-size: ${fontSize}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; + font-size: ${({ theme }) => theme.eui.euiFontSizeS}; `; -const dbSyntaxLineHeight = unit * 1.5; - interface Props { dbContext?: NonNullable['db']; } export function DatabaseContext({ dbContext }: Props) { + const theme = useTheme(); + const dbSyntaxLineHeight = theme.eui.euiSizeL; + const previewHeight = 240; // 10 * dbSyntaxLineHeight + if (!dbContext || !dbContext.statement) { return null; } @@ -64,7 +60,7 @@ export function DatabaseContext({ dbContext }: Props) { - + theme.eui.euiSizeXS}; `; const HttpInfoContainer = euiStyled('div')` - margin-right: ${px(units.quarter)}; + margin-right: ${({ theme }) => theme.eui.euiSizeXS}; `; interface Props { diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/truncate_height_section.tsx similarity index 92% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/truncate_height_section.tsx index 181fcb91ba3e6..4c845e16348e7 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/span_flyout/truncate_height_section.tsx @@ -9,10 +9,9 @@ import { EuiIcon, EuiLink } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { Fragment, ReactNode, useEffect, useRef, useState } from 'react'; import { euiStyled } from '../../../../../../../../../../../src/plugins/kibana_react/common'; -import { px, units } from '../../../../../../../style/variables'; const ToggleButtonContainer = euiStyled.div` - margin-top: ${px(units.half)}; + margin-top: ${({ theme }) => theme.eui.euiSizeS} user-select: none; `; @@ -41,7 +40,7 @@ export function TruncateHeightSection({ children, previewHeight }: Props) { ref={contentContainerEl} style={{ overflow: 'hidden', - maxHeight: isOpen ? 'initial' : px(previewHeight), + maxHeight: isOpen ? 'initial' : previewHeight, }} > {children} diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.stories.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/sync_badge.stories.tsx similarity index 91% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.stories.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/sync_badge.stories.tsx index 8275aa1e5f156..6b52fbe2d784a 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/sync_badge.stories.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { SyncBadge, SyncBadgeProps } from './SyncBadge'; +import { SyncBadge, SyncBadgeProps } from './sync_badge'; export default { title: 'app/TransactionDetails/SyncBadge', diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/sync_badge.tsx similarity index 92% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/sync_badge.tsx index b9e4c6951fa06..cfc369fa12a26 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/sync_badge.tsx @@ -9,11 +9,10 @@ import { EuiBadge } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import { euiStyled } from '../../../../../../../../../../src/plugins/kibana_react/common'; -import { px, units } from '../../../../../../style/variables'; const SpanBadge = euiStyled(EuiBadge)` display: inline-block; - margin-right: ${px(units.quarter)}; + margin-right: ${({ theme }) => theme.eui.euiSizeXS}; `; export interface SyncBadgeProps { diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/__snapshots__/waterfall_helpers.test.ts.snap b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/__snapshots__/waterfall_helpers.test.ts.snap similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/__snapshots__/waterfall_helpers.test.ts.snap rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/__snapshots__/waterfall_helpers.test.ts.snap diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/mock_responses/spans.json b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/mock_responses/spans.json similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/mock_responses/spans.json rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/mock_responses/spans.json diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/mock_responses/transaction.json b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/mock_responses/transaction.json similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/mock_responses/transaction.json rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/mock_responses/transaction.json diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.test.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers.test.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.test.ts rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers.test.ts diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.ts rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers.ts diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_item.tsx similarity index 93% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_item.tsx index f3e1547c4b8b8..a2c2c869a079c 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/waterfall_item.tsx @@ -5,20 +5,18 @@ * 2.0. */ -import React, { ReactNode } from 'react'; - import { EuiIcon, EuiText, EuiTitle, EuiToolTip } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import React, { ReactNode } from 'react'; import { euiStyled } from '../../../../../../../../../../src/plugins/kibana_react/common'; -import { asDuration } from '../../../../../../../common/utils/formatters'; import { isRumAgentName } from '../../../../../../../common/agent_name'; -import { px, unit, units } from '../../../../../../style/variables'; -import { ErrorCount } from '../../ErrorCount'; -import { IWaterfallSpanOrTransaction } from './waterfall_helpers/waterfall_helpers'; -import { ErrorOverviewLink } from '../../../../../shared/Links/apm/ErrorOverviewLink'; import { TRACE_ID } from '../../../../../../../common/elasticsearch_fieldnames'; -import { SyncBadge } from './SyncBadge'; +import { asDuration } from '../../../../../../../common/utils/formatters'; import { Margins } from '../../../../../shared/charts/Timeline'; +import { ErrorOverviewLink } from '../../../../../shared/Links/apm/ErrorOverviewLink'; +import { ErrorCount } from '../../ErrorCount'; +import { SyncBadge } from './sync_badge'; +import { IWaterfallSpanOrTransaction } from './waterfall_helpers/waterfall_helpers'; type ItemType = 'transaction' | 'span' | 'error'; @@ -37,10 +35,10 @@ const Container = euiStyled.div` position: relative; display: block; user-select: none; - padding-top: ${px(units.half)}; - padding-bottom: ${px(units.plus)}; - margin-right: ${(props) => px(props.timelineMargins.right)}; - margin-left: ${(props) => px(props.timelineMargins.left)}; + padding-top: ${({ theme }) => theme.eui.paddingSizes.s}; + padding-bottom: ${({ theme }) => theme.eui.euiSizeM}; + margin-right: ${(props) => props.timelineMargins.right}px; + margin-left: ${(props) => props.timelineMargins.left}px; background-color: ${({ isSelected, theme }) => isSelected ? theme.eui.euiColorLightestShade : 'initial'}; cursor: pointer; @@ -53,7 +51,7 @@ const Container = euiStyled.div` const ItemBar = euiStyled.div` box-sizing: border-box; position: relative; - height: ${px(unit)}; + height: ${({ theme }) => theme.eui.euiSize}; min-width: 2px; background-color: ${(props) => props.color}; `; @@ -63,11 +61,11 @@ const ItemText = euiStyled.span` right: 0; display: flex; align-items: center; - height: ${px(units.plus)}; + height: ${({ theme }) => theme.eui.euiSizeL}; /* add margin to all direct descendants */ & > * { - margin-right: ${px(units.half)}; + margin-right: ${({ theme }) => theme.eui.euiSizeS}; white-space: nowrap; } `; diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/WaterfallContainer.stories.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/WaterfallContainer.stories.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/WaterfallContainer.stories.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/WaterfallContainer.stories.tsx diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/WaterfallLegends.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/WaterfallLegends.tsx similarity index 95% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/WaterfallLegends.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/WaterfallLegends.tsx index d6f6de2d9179b..aaa9b3e45ee22 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/WaterfallLegends.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/WaterfallLegends.tsx @@ -10,7 +10,7 @@ import { EuiFlexItem } from '@elastic/eui'; import { EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; -import { Legend } from '../../../../shared/charts/Legend'; +import { Legend } from '../../../../shared/charts/Timeline/legend'; import { IWaterfallLegend, WaterfallLegendType, diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/index.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/index.tsx rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/index.tsx diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/waterfallContainer.stories.data.ts b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfallContainer.stories.data.ts similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_details/WaterfallWithSummmary/WaterfallContainer/waterfallContainer.stories.data.ts rename to x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfallContainer.stories.data.ts diff --git a/x-pack/plugins/apm/public/components/app/transaction_overview/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_overview/index.tsx index 4f0f92cafa5e7..041c12822357c 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_overview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_overview/index.tsx @@ -24,7 +24,7 @@ import { useUrlParams } from '../../../context/url_params_context/use_url_params import { TransactionCharts } from '../../shared/charts/transaction_charts'; import { ElasticDocsLink } from '../../shared/Links/ElasticDocsLink'; import { fromQuery, toQuery } from '../../shared/Links/url_helpers'; -import { TransactionList } from './TransactionList'; +import { TransactionList } from './transaction_list'; import { useRedirect } from './useRedirect'; import { useTransactionListFetcher } from './use_transaction_list'; diff --git a/x-pack/plugins/apm/public/components/app/transaction_overview/TransactionList/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_overview/transaction_list/index.tsx similarity index 96% rename from x-pack/plugins/apm/public/components/app/transaction_overview/TransactionList/index.tsx rename to x-pack/plugins/apm/public/components/app/transaction_overview/transaction_list/index.tsx index 795a6e66f70a4..dc3bf924d6fdc 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_overview/TransactionList/index.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_overview/transaction_list/index.tsx @@ -15,9 +15,9 @@ import { asMillisecondDuration, asTransactionRate, } from '../../../../../common/utils/formatters'; -import { fontFamilyCode, truncate } from '../../../../style/variables'; +import { truncate } from '../../../../utils/style'; import { ImpactBar } from '../../../shared/ImpactBar'; -import { ITableColumn, ManagedTable } from '../../../shared/ManagedTable'; +import { ITableColumn, ManagedTable } from '../../../shared/managed_table'; import { LoadingStatePrompt } from '../../../shared/LoadingStatePrompt'; import { EmptyMessage } from '../../../shared/EmptyMessage'; import { TransactionDetailLink } from '../../../shared/Links/apm/transaction_detail_link'; @@ -27,7 +27,7 @@ type TransactionGroup = APIReturnType<'GET /api/apm/services/{serviceName}/trans // Truncate both the link and the child span (the tooltip anchor.) The link so // it doesn't overflow, and the anchor so we get the ellipsis. const TransactionNameLink = euiStyled(TransactionDetailLink)` - font-family: ${fontFamilyCode}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; white-space: nowrap; ${truncate('100%')}; diff --git a/x-pack/plugins/apm/public/components/app/transaction_overview/TransactionList/TransactionList.stories.tsx b/x-pack/plugins/apm/public/components/app/transaction_overview/transaction_list/transaction_list.stories.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/app/transaction_overview/TransactionList/TransactionList.stories.tsx rename to x-pack/plugins/apm/public/components/app/transaction_overview/transaction_list/transaction_list.stories.tsx diff --git a/x-pack/plugins/apm/public/components/fleet_integration/apm_custom_assets_extension.tsx b/x-pack/plugins/apm/public/components/fleet_integration/apm_custom_assets_extension.tsx new file mode 100644 index 0000000000000..40b902b7729d0 --- /dev/null +++ b/x-pack/plugins/apm/public/components/fleet_integration/apm_custom_assets_extension.tsx @@ -0,0 +1,36 @@ +/* + * 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 { i18n } from '@kbn/i18n'; + +import { + CustomAssetsAccordionProps, + CustomAssetsAccordion, +} from '../../../../fleet/public'; +import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; +import { ApmPluginStartDeps } from '../../plugin'; + +export function ApmCustomAssetsExtension() { + const { http } = useKibana().services; + const basePath = http?.basePath.get(); + + const views: CustomAssetsAccordionProps['views'] = [ + { + name: i18n.translate('xpack.apm.fleetIntegration.assets.name', { + defaultMessage: 'Services', + }), + url: `${basePath}/app/apm`, + description: i18n.translate( + 'xpack.apm.fleetIntegration.assets.description', + { defaultMessage: 'View application traces and service maps in APM' } + ), + }, + ]; + + return ; +} diff --git a/x-pack/plugins/apm/public/components/fleet_integration/apm_enrollment_flyout_extension.tsx b/x-pack/plugins/apm/public/components/fleet_integration/apm_enrollment_flyout_extension.tsx new file mode 100644 index 0000000000000..6b3ba6a8f05db --- /dev/null +++ b/x-pack/plugins/apm/public/components/fleet_integration/apm_enrollment_flyout_extension.tsx @@ -0,0 +1,58 @@ +/* + * 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 { EuiButton, EuiText, EuiSpacer } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; + +import { AgentEnrollmentFlyoutFinalStepExtension } from '../../../../fleet/public'; +import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; +import { ApmPluginStartDeps } from '../../plugin'; + +function StepComponent() { + const { http } = useKibana().services; + const installApmAgentLink = http?.basePath.prepend('/app/home#/tutorial/apm'); + + return ( + <> + +

+ {i18n.translate( + 'xpack.apm.fleetIntegration.enrollmentFlyout.installApmAgentDescription', + { + defaultMessage: + 'After the agent starts, you can install APM agents on your hosts to collect data from your applications and services.', + } + )} +

+
+ + + + {i18n.translate( + 'xpack.apm.fleetIntegration.enrollmentFlyout.installApmAgentButtonText', + { defaultMessage: 'Install APM Agent' } + )} + + + ); +} + +export function getApmEnrollmentFlyoutData(): Pick< + AgentEnrollmentFlyoutFinalStepExtension, + 'title' | 'Component' +> { + return { + title: i18n.translate( + 'xpack.apm.fleetIntegration.enrollmentFlyout.installApmAgentTitle', + { + defaultMessage: 'Install APM Agent', + } + ), + Component: StepComponent, + }; +} diff --git a/x-pack/plugins/apm/public/components/fleet_integration/index.ts b/x-pack/plugins/apm/public/components/fleet_integration/index.ts new file mode 100644 index 0000000000000..a676a13c3741b --- /dev/null +++ b/x-pack/plugins/apm/public/components/fleet_integration/index.ts @@ -0,0 +1,9 @@ +/* + * 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 * from './apm_enrollment_flyout_extension'; +export * from './lazy_apm_custom_assets_extension'; diff --git a/x-pack/plugins/apm/public/components/fleet_integration/lazy_apm_custom_assets_extension.tsx b/x-pack/plugins/apm/public/components/fleet_integration/lazy_apm_custom_assets_extension.tsx new file mode 100644 index 0000000000000..04f5042f3103f --- /dev/null +++ b/x-pack/plugins/apm/public/components/fleet_integration/lazy_apm_custom_assets_extension.tsx @@ -0,0 +1,18 @@ +/* + * 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 { lazy } from 'react'; + +export const LazyApmCustomAssetsExtension = lazy(async () => { + const { ApmCustomAssetsExtension } = await import( + './apm_custom_assets_extension' + ); + + return { + default: ApmCustomAssetsExtension, + }; +}); diff --git a/x-pack/plugins/apm/public/components/routing/apm_route_config.tsx b/x-pack/plugins/apm/public/components/routing/apm_route_config.tsx index 5214489c9142b..e00b7893b548e 100644 --- a/x-pack/plugins/apm/public/components/routing/apm_route_config.tsx +++ b/x-pack/plugins/apm/public/components/routing/apm_route_config.tsx @@ -11,14 +11,14 @@ import { RouteComponentProps } from 'react-router-dom'; import { getServiceNodeName } from '../../../common/service_nodes'; import { APMRouteDefinition } from '../../application/routes'; import { toQuery } from '../shared/Links/url_helpers'; -import { ErrorGroupDetails } from '../app/ErrorGroupDetails'; +import { ErrorGroupDetails } from '../app/error_group_details'; import { useApmPluginContext } from '../../context/apm_plugin/use_apm_plugin_context'; import { ServiceNodeMetrics } from '../app/service_node_metrics'; import { SettingsTemplate } from './templates/settings_template'; -import { AgentConfigurations } from '../app/Settings/AgentConfigurations'; +import { AgentConfigurations } from '../app/Settings/agent_configurations'; import { AnomalyDetection } from '../app/Settings/anomaly_detection'; import { ApmIndices } from '../app/Settings/ApmIndices'; -import { CustomizeUI } from '../app/Settings/CustomizeUI'; +import { CustomizeUI } from '../app/Settings/customize_ui'; import { Schema } from '../app/Settings/schema'; import { TraceLink } from '../app/TraceLink'; import { TransactionLink } from '../app/transaction_link'; @@ -37,7 +37,7 @@ import { TransactionOverview } from '../app/transaction_overview'; import { ServiceInventory } from '../app/service_inventory'; import { TraceOverview } from '../app/trace_overview'; import { useFetcher } from '../../hooks/use_fetcher'; -import { AgentConfigurationCreateEdit } from '../app/Settings/AgentConfigurations/AgentConfigurationCreateEdit'; +import { AgentConfigurationCreateEdit } from '../app/Settings/agent_configurations/AgentConfigurationCreateEdit'; // These component function definitions are used below with the `component` // property of the route definitions. diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/Context.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/Context.tsx index ef74894169d72..a03b0b5f2ae01 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/Context.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/Context.tsx @@ -8,14 +8,13 @@ import { size } from 'lodash'; import { tint } from 'polished'; import React from 'react'; +import { Light as SyntaxHighlighter } from 'react-syntax-highlighter'; import javascript from 'react-syntax-highlighter/dist/cjs/languages/hljs/javascript'; import python from 'react-syntax-highlighter/dist/cjs/languages/hljs/python'; import ruby from 'react-syntax-highlighter/dist/cjs/languages/hljs/ruby'; import xcode from 'react-syntax-highlighter/dist/cjs/styles/hljs/xcode'; -import { Light as SyntaxHighlighter } from 'react-syntax-highlighter'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { StackframeWithLineContext } from '../../../../typings/es_schemas/raw/fields/stackframe'; -import { borderRadius, px, unit, units } from '../../../style/variables'; SyntaxHighlighter.registerLanguage('javascript', javascript); SyntaxHighlighter.registerLanguage('python', python); @@ -23,15 +22,15 @@ SyntaxHighlighter.registerLanguage('ruby', ruby); const ContextContainer = euiStyled.div` position: relative; - border-radius: ${borderRadius}; + border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; `; -const LINE_HEIGHT = units.eighth * 9; +const LINE_HEIGHT = 18; const LineHighlight = euiStyled.div<{ lineNumber: number }>` position: absolute; width: 100%; - height: ${px(units.eighth * 9)}; - top: ${(props) => px(props.lineNumber * LINE_HEIGHT)}; + height: ${LINE_HEIGHT}px; + top: ${(props) => props.lineNumber * LINE_HEIGHT}px; pointer-events: none; background-color: ${({ theme }) => tint(0.9, theme.eui.euiColorWarning)}; `; @@ -40,7 +39,7 @@ const LineNumberContainer = euiStyled.div<{ isLibraryFrame: boolean }>` position: absolute; top: 0; left: 0; - border-radius: ${borderRadius}; + border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; background: ${({ isLibraryFrame, theme }) => isLibraryFrame ? theme.eui.euiColorEmptyShade @@ -49,29 +48,29 @@ const LineNumberContainer = euiStyled.div<{ isLibraryFrame: boolean }>` const LineNumber = euiStyled.div<{ highlight: boolean }>` position: relative; - min-width: ${px(units.eighth * 21)}; - padding-left: ${px(units.half)}; - padding-right: ${px(units.quarter)}; + min-width: 42px; + padding-left: ${({ theme }) => theme.eui.paddingSizes.s}; + padding-right: ${({ theme }) => theme.eui.paddingSizes.xs}; color: ${({ theme }) => theme.eui.euiColorMediumShade}; - line-height: ${px(unit + units.eighth)}; + line-height: ${LINE_HEIGHT}px; text-align: right; border-right: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; background-color: ${({ highlight, theme }) => highlight ? tint(0.9, theme.eui.euiColorWarning) : null}; &:last-of-type { - border-radius: 0 0 0 ${borderRadius}; + border-radius: 0 0 0 ${({ theme }) => theme.eui.euiBorderRadiusSmall}; } `; const LineContainer = euiStyled.div` overflow: auto; - margin: 0 0 0 ${px(units.eighth * 21)}; + margin: 0 0 0 42px; padding: 0; background-color: ${({ theme }) => theme.eui.euiColorEmptyShade}; &:last-of-type { - border-radius: 0 0 ${borderRadius} 0; + border-radius: 0 0 ${({ theme }) => theme.eui.euiBorderRadiusSmall} 0; } `; @@ -83,8 +82,8 @@ const Line = euiStyled.pre` border: 0; border-radius: 0; overflow: initial; - padding: 0 ${px(LINE_HEIGHT)}; - line-height: ${px(LINE_HEIGHT)}; + padding: 0 ${LINE_HEIGHT}px; + line-height: ${LINE_HEIGHT}px; `; const Code = euiStyled.code` diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/Stackframe.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/Stackframe.tsx index d361634759390..0985153c2d39e 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/Stackframe.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/Stackframe.tsx @@ -12,22 +12,16 @@ import { Stackframe as StackframeType, StackframeWithLineContext, } from '../../../../typings/es_schemas/raw/fields/stackframe'; -import { - borderRadius, - fontFamilyCode, - fontSize, -} from '../../../style/variables'; import { Context } from './Context'; -import { FrameHeading } from './FrameHeading'; +import { FrameHeading } from './frame_heading'; import { Variables } from './Variables'; -import { px, units } from '../../../style/variables'; const ContextContainer = euiStyled.div<{ isLibraryFrame: boolean }>` position: relative; - font-family: ${fontFamilyCode}; - font-size: ${fontSize}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; + font-size: ${({ theme }) => theme.eui.euiFontSizeS}; border: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; - border-radius: ${borderRadius}; + border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; background: ${({ isLibraryFrame, theme }) => isLibraryFrame ? theme.eui.euiColorEmptyShade @@ -36,7 +30,7 @@ const ContextContainer = euiStyled.div<{ isLibraryFrame: boolean }>` // Indent the non-context frames the same amount as the accordion control const NoContextFrameHeadingWrapper = euiStyled.div` - margin-left: ${px(units.unit + units.half + units.quarter)}; + margin-left: 28px; `; interface Props { diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/Variables.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/Variables.tsx index 7c09048593710..a43cd26e7f94a 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/Variables.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/Variables.tsx @@ -9,15 +9,16 @@ import { EuiAccordion } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; -import { borderRadius, px, unit, units } from '../../../style/variables'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; import { KeyValueTable } from '../KeyValueTable'; import { flattenObject } from '../../../utils/flattenObject'; const VariablesContainer = euiStyled.div` background: ${({ theme }) => theme.eui.euiColorEmptyShade}; - border-radius: 0 0 ${borderRadius} ${borderRadius}; - padding: ${px(units.half)} ${px(unit)}; + border-radius: 0 0 ${({ theme }) => + `${theme.eui.euiBorderRadiusSmall} ${theme.eui.euiBorderRadiusSmall}`}; + padding: ${({ theme }) => + `${theme.eui.paddingSizes.s} ${theme.eui.paddingSizes.m}`}; `; interface Props { diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/CauseStacktrace.test.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/cause_stacktrace.test.tsx similarity index 96% rename from x-pack/plugins/apm/public/components/shared/Stacktrace/CauseStacktrace.test.tsx rename to x-pack/plugins/apm/public/components/shared/Stacktrace/cause_stacktrace.test.tsx index a0ca8dd05b87f..cc23452127fa4 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/CauseStacktrace.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/cause_stacktrace.test.tsx @@ -5,10 +5,10 @@ * 2.0. */ -import React from 'react'; import { shallow } from 'enzyme'; -import { CauseStacktrace } from './CauseStacktrace'; +import React from 'react'; import { mountWithTheme } from '../../../utils/testHelpers'; +import { CauseStacktrace } from './cause_stacktrace'; describe('CauseStacktrace', () => { describe('render', () => { diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/CauseStacktrace.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/cause_stacktrace.tsx similarity index 94% rename from x-pack/plugins/apm/public/components/shared/Stacktrace/CauseStacktrace.tsx rename to x-pack/plugins/apm/public/components/shared/Stacktrace/cause_stacktrace.tsx index 090ba0e8e28cf..0ee4f66e2c24c 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/CauseStacktrace.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/cause_stacktrace.tsx @@ -5,17 +5,16 @@ * 2.0. */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; import { EuiAccordion, EuiTitle } from '@elastic/eui'; -import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; -import { px, unit, units } from '../../../style/variables'; +import { i18n } from '@kbn/i18n'; +import React from 'react'; import { Stacktrace } from '.'; +import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; const Accordion = euiStyled(EuiAccordion)` border-top: ${({ theme }) => theme.eui.euiBorderThin}; - margin-top: ${px(units.half)}; + margin-top: ${({ theme }) => theme.eui.euiSizeS}; `; const CausedByContainer = euiStyled('h5')` @@ -31,7 +30,7 @@ const CausedByHeading = euiStyled('span')` `; const FramesContainer = euiStyled('div')` - padding-left: ${px(unit)}; + padding-left: ${({ theme }) => theme.eui.paddingSizes.m}; `; function CausedBy({ message }: { message: string }) { diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.test.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/frame_heading.test.tsx similarity index 99% rename from x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.test.tsx rename to x-pack/plugins/apm/public/components/shared/Stacktrace/frame_heading.test.tsx index 794d88461358e..2eb3320ef3aa3 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/frame_heading.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; import { renderWithTheme } from '../../../utils/testHelpers'; -import { FrameHeading } from './FrameHeading'; +import { FrameHeading } from './frame_heading'; function getRenderedStackframeText( stackframe: Stackframe, diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/frame_heading.tsx similarity index 92% rename from x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx rename to x-pack/plugins/apm/public/components/shared/Stacktrace/frame_heading.tsx index 68b0893e1d8d3..8c9b9ae26c140 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/FrameHeading.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/frame_heading.tsx @@ -8,7 +8,6 @@ import React, { ComponentType } from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; -import { fontFamilyCode, fontSize, px, units } from '../../../style/variables'; import { CSharpFrameHeadingRenderer, DefaultFrameHeadingRenderer, @@ -21,9 +20,9 @@ import { const FileDetails = euiStyled.div` color: ${({ theme }) => theme.eui.euiColorDarkShade}; line-height: 1.5; /* matches the line-hight of the accordion container button */ - padding: ${px(units.eighth)} 0; - font-family: ${fontFamilyCode}; - font-size: ${fontSize}; + padding: 2px 0; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; + font-size: ${({ theme }) => theme.eui.euiFontSizeS}; `; const LibraryFrameFileDetail = euiStyled.span` diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/index.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/index.tsx index 19af5da30cff2..3395b22988e8c 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/index.tsx @@ -10,7 +10,7 @@ import { isEmpty, last } from 'lodash'; import React, { Fragment } from 'react'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; import { EmptyMessage } from '../../shared/EmptyMessage'; -import { LibraryStacktrace } from './LibraryStacktrace'; +import { LibraryStacktrace } from './library_stacktrace'; import { Stackframe as StackframeComponent } from './Stackframe'; interface Props { diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/LibraryStacktrace.test.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/library_stacktrace.test.tsx similarity index 95% rename from x-pack/plugins/apm/public/components/shared/Stacktrace/LibraryStacktrace.test.tsx rename to x-pack/plugins/apm/public/components/shared/Stacktrace/library_stacktrace.test.tsx index d583d4c700939..d10e6c46cd12c 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/LibraryStacktrace.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/library_stacktrace.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { renderWithTheme } from '../../../utils/testHelpers'; -import { LibraryStacktrace } from './LibraryStacktrace'; +import { LibraryStacktrace } from './library_stacktrace'; describe('LibraryStacktrace', () => { describe('render', () => { diff --git a/x-pack/plugins/apm/public/components/shared/Stacktrace/LibraryStacktrace.tsx b/x-pack/plugins/apm/public/components/shared/Stacktrace/library_stacktrace.tsx similarity index 94% rename from x-pack/plugins/apm/public/components/shared/Stacktrace/LibraryStacktrace.tsx rename to x-pack/plugins/apm/public/components/shared/Stacktrace/library_stacktrace.tsx index de417b465638f..08399d09bed86 100644 --- a/x-pack/plugins/apm/public/components/shared/Stacktrace/LibraryStacktrace.tsx +++ b/x-pack/plugins/apm/public/components/shared/Stacktrace/library_stacktrace.tsx @@ -10,11 +10,10 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { Stackframe } from '../../../../typings/es_schemas/raw/fields/stackframe'; -import { px, units } from '../../../style/variables'; import { Stackframe as StackframeComponent } from './Stackframe'; const LibraryStacktraceAccordion = euiStyled(EuiAccordion)` - margin: ${px(units.quarter)} 0; + margin: ${({ theme }) => theme.eui.euiSizeXS} 0; `; interface Props { diff --git a/x-pack/plugins/apm/public/components/shared/Summary/DurationSummaryItem.tsx b/x-pack/plugins/apm/public/components/shared/Summary/DurationSummaryItem.tsx index 1ceccc5203fb2..e0710556096c9 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/DurationSummaryItem.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/DurationSummaryItem.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; import { EuiToolTip, EuiText } from '@elastic/eui'; import { asDuration } from '../../../../common/utils/formatters'; -import { PercentOfParent } from '../../app/transaction_details/WaterfallWithSummmary/PercentOfParent'; +import { PercentOfParent } from '../../app/transaction_details/waterfall_with_summary/PercentOfParent'; interface Props { duration: number; diff --git a/x-pack/plugins/apm/public/components/shared/Summary/TransactionSummary.tsx b/x-pack/plugins/apm/public/components/shared/Summary/TransactionSummary.tsx index 8755003c89af2..6939aaf49373e 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/TransactionSummary.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/TransactionSummary.tsx @@ -10,9 +10,9 @@ import { Transaction } from '../../../../typings/es_schemas/ui/transaction'; import { Summary } from './'; import { TimestampTooltip } from '../TimestampTooltip'; import { DurationSummaryItem } from './DurationSummaryItem'; -import { ErrorCountSummaryItemBadge } from './ErrorCountSummaryItemBadge'; +import { ErrorCountSummaryItemBadge } from './error_count_summary_item_badge'; import { isRumAgentName } from '../../../../common/agent_name'; -import { HttpInfoSummaryItem } from './HttpInfoSummaryItem'; +import { HttpInfoSummaryItem } from './http_info_summary_item'; import { TransactionResultSummaryItem } from './TransactionResultSummaryItem'; import { UserAgentSummaryItem } from './UserAgentSummaryItem'; diff --git a/x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.test.tsx b/x-pack/plugins/apm/public/components/shared/Summary/error_count_summary_item_badge.test.tsx similarity index 90% rename from x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.test.tsx rename to x-pack/plugins/apm/public/components/shared/Summary/error_count_summary_item_badge.test.tsx index 9996d1ea61a76..c6b77bddbf544 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/error_count_summary_item_badge.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { ErrorCountSummaryItemBadge } from './ErrorCountSummaryItemBadge'; +import { ErrorCountSummaryItemBadge } from './error_count_summary_item_badge'; import { expectTextsInDocument, renderWithTheme, diff --git a/x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.tsx b/x-pack/plugins/apm/public/components/shared/Summary/error_count_summary_item_badge.tsx similarity index 87% rename from x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.tsx rename to x-pack/plugins/apm/public/components/shared/Summary/error_count_summary_item_badge.tsx index ec309f2f74d10..17189f1e40d94 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/ErrorCountSummaryItemBadge.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/error_count_summary_item_badge.tsx @@ -10,15 +10,13 @@ import { i18n } from '@kbn/i18n'; import { EuiBadge } from '@elastic/eui'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { useTheme } from '../../../hooks/use_theme'; -import { px } from '../../../../public/style/variables'; -import { units } from '../../../style/variables'; interface Props { count: number; } const Badge = euiStyled(EuiBadge)` - margin-top: ${px(units.eighth)}; + margin-top: 2px; `; export function ErrorCountSummaryItemBadge({ count }: Props) { diff --git a/x-pack/plugins/apm/public/components/shared/Summary/HttpInfoSummaryItem/HttpInfoSummaryItem.test.tsx b/x-pack/plugins/apm/public/components/shared/Summary/http_info_summary_item/http_info_summary_item.test.tsx similarity index 69% rename from x-pack/plugins/apm/public/components/shared/Summary/HttpInfoSummaryItem/HttpInfoSummaryItem.test.tsx rename to x-pack/plugins/apm/public/components/shared/Summary/http_info_summary_item/http_info_summary_item.test.tsx index 71d7177051b9d..3e1848af316fe 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/HttpInfoSummaryItem/HttpInfoSummaryItem.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/http_info_summary_item/http_info_summary_item.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { shallow, mount } from 'enzyme'; import { HttpInfoSummaryItem } from '.'; import * as exampleTransactions from '../__fixtures__/transactions'; +import { EuiThemeProvider } from '../../../../../../../../src/plugins/kibana_react/common'; describe('HttpInfoSummaryItem', () => { describe('render', () => { @@ -19,18 +20,24 @@ describe('HttpInfoSummaryItem', () => { it('renders', () => { expect(() => - shallow() + shallow(, { + wrappingComponent: EuiThemeProvider, + }) ).not.toThrowError(); }); it('renders empty component if no url is provided', () => { - const component = shallow(); + const component = shallow(, { + wrappingComponent: EuiThemeProvider, + }); expect(component.isEmptyRender()).toBeTruthy(); }); describe('with status code 100', () => { it('shows a success color', () => { - const wrapper = mount(); + const wrapper = mount(, { + wrappingComponent: EuiThemeProvider, + }); expect(wrapper.find('HttpStatusBadge').prop('status')).toEqual(100); }); @@ -39,7 +46,9 @@ describe('HttpInfoSummaryItem', () => { describe('with status code 200', () => { it('shows a success color', () => { const p = { ...props, status: 200 }; - const wrapper = mount(); + const wrapper = mount(, { + wrappingComponent: EuiThemeProvider, + }); expect(wrapper.find('HttpStatusBadge').prop('status')).toEqual(200); }); @@ -49,7 +58,9 @@ describe('HttpInfoSummaryItem', () => { it('shows a warning color', () => { const p = { ...props, status: 301 }; - const wrapper = mount(); + const wrapper = mount(, { + wrappingComponent: EuiThemeProvider, + }); expect(wrapper.find('HttpStatusBadge').prop('status')).toEqual(301); }); @@ -59,7 +70,9 @@ describe('HttpInfoSummaryItem', () => { it('shows a error color', () => { const p = { ...props, status: 404 }; - const wrapper = mount(); + const wrapper = mount(, { + wrappingComponent: EuiThemeProvider, + }); expect(wrapper.find('HttpStatusBadge').prop('status')).toEqual(404); }); @@ -69,7 +82,9 @@ describe('HttpInfoSummaryItem', () => { it('shows a error color', () => { const p = { ...props, status: 502 }; - const wrapper = mount(); + const wrapper = mount(, { + wrappingComponent: EuiThemeProvider, + }); expect(wrapper.find('HttpStatusBadge').prop('status')).toEqual(502); }); @@ -79,7 +94,9 @@ describe('HttpInfoSummaryItem', () => { it('shows the default color', () => { const p = { ...props, status: 700 }; - const wrapper = mount(); + const wrapper = mount(, { + wrappingComponent: EuiThemeProvider, + }); expect(wrapper.find('HttpStatusBadge').prop('status')).toEqual(700); }); diff --git a/x-pack/plugins/apm/public/components/shared/Summary/HttpInfoSummaryItem/index.tsx b/x-pack/plugins/apm/public/components/shared/Summary/http_info_summary_item/index.tsx similarity index 87% rename from x-pack/plugins/apm/public/components/shared/Summary/HttpInfoSummaryItem/index.tsx rename to x-pack/plugins/apm/public/components/shared/Summary/http_info_summary_item/index.tsx index d72f03c386226..d10d15f8240a1 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/HttpInfoSummaryItem/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/http_info_summary_item/index.tsx @@ -5,21 +5,21 @@ * 2.0. */ -import React from 'react'; -import { EuiToolTip, EuiBadge } from '@elastic/eui'; +import { EuiBadge, EuiToolTip } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import React from 'react'; import { euiStyled } from '../../../../../../../../src/plugins/kibana_react/common'; -import { units, px, truncate, unit } from '../../../../style/variables'; +import { truncate, unit } from '../../../../utils/style'; import { HttpStatusBadge } from '../HttpStatusBadge'; const HttpInfoBadge = euiStyled(EuiBadge)` - margin-right: ${px(units.quarter)}; + margin-right: ${({ theme }) => theme.eui.euiSizeXS}; `; const Url = euiStyled('span')` display: inline-block; vertical-align: bottom; - ${truncate(px(unit * 24))}; + ${truncate(unit * 24)}; `; interface HttpInfoProps { method?: string; diff --git a/x-pack/plugins/apm/public/components/shared/Summary/index.tsx b/x-pack/plugins/apm/public/components/shared/Summary/index.tsx index 395156800dceb..1880ee00f3de7 100644 --- a/x-pack/plugins/apm/public/components/shared/Summary/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/Summary/index.tsx @@ -5,10 +5,9 @@ * 2.0. */ -import React from 'react'; import { EuiFlexGrid, EuiFlexItem } from '@elastic/eui'; +import React from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; -import { px, units } from '../../../../public/style/variables'; import { Maybe } from '../../../../typings/common'; interface Props { @@ -18,7 +17,7 @@ interface Props { const Item = euiStyled(EuiFlexItem)` flex-wrap: nowrap; border-right: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; - padding-right: ${px(units.half)}; + padding-right: ${({ theme }) => theme.eui.paddingSizes.s}; flex-flow: row nowrap; line-height: 1.5; align-items: center !important; diff --git a/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.tsx b/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.tsx index 28c000310346d..b800ef41fbcac 100644 --- a/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.tsx +++ b/x-pack/plugins/apm/public/components/shared/apm_header_action_menu/anomaly_detection_setup_link.tsx @@ -17,14 +17,14 @@ import { ENVIRONMENT_ALL, getEnvironmentLabel, } from '../../../../common/environment_filter_values'; -import { getAPMHref } from '../Links/apm/APMLink'; import { useAnomalyDetectionJobsContext } from '../../../context/anomaly_detection_jobs/use_anomaly_detection_jobs_context'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; import { useLicenseContext } from '../../../context/license/use_license_context'; import { useUrlParams } from '../../../context/url_params_context/use_url_params'; import { FETCH_STATUS } from '../../../hooks/use_fetcher'; +import { useTheme } from '../../../hooks/use_theme'; import { APIReturnType } from '../../../services/rest/createCallApmApi'; -import { units } from '../../../style/variables'; +import { getAPMHref } from '../Links/apm/APMLink'; export type AnomalyDetectionApiResponse = APIReturnType<'GET /api/apm/settings/anomaly-detection/jobs'>; @@ -39,6 +39,7 @@ export function AnomalyDetectionSetupLink() { const license = useLicenseContext(); const hasValidLicense = license?.isActive && license?.hasAtLeast('platinum'); const { basePath } = core.http; + const theme = useTheme(); return ( )} - + {ANOMALY_DETECTION_LINK_LABEL} diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/__snapshots__/AgentMarker.test.tsx.snap b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/__snapshots__/agent_marker.test.tsx.snap similarity index 100% rename from x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/__snapshots__/AgentMarker.test.tsx.snap rename to x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/__snapshots__/agent_marker.test.tsx.snap diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/__snapshots__/index.test.tsx.snap b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/__snapshots__/index.test.tsx.snap index f108eb7ebf3ea..5657732eb241b 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/__snapshots__/index.test.tsx.snap @@ -4,7 +4,7 @@ exports[`Marker renders agent marker 1`] = ` @@ -25,7 +25,7 @@ exports[`Marker renders error marker 1`] = ` diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.test.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/agent_marker.test.tsx similarity index 81% rename from x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.test.tsx rename to x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/agent_marker.test.tsx index 1411a264b065e..0b7e405ae5d95 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/agent_marker.test.tsx @@ -7,9 +7,9 @@ import { shallow } from 'enzyme'; import React from 'react'; -import { AgentMarker } from './AgentMarker'; -import { AgentMark } from '../../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks'; import { EuiThemeProvider } from '../../../../../../../../../src/plugins/kibana_react/common'; +import { AgentMark } from '../../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_agent_marks'; +import { AgentMarker } from './agent_marker'; describe('AgentMarker', () => { const mark = { diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/agent_marker.tsx similarity index 80% rename from x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.tsx rename to x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/agent_marker.tsx index 3b7f0fab6c2a7..947c7a93f38b1 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/AgentMarker.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/agent_marker.tsx @@ -5,23 +5,22 @@ * 2.0. */ -import React from 'react'; import { EuiToolTip } from '@elastic/eui'; +import React from 'react'; import { euiStyled } from '../../../../../../../../../src/plugins/kibana_react/common'; import { asDuration } from '../../../../../../common/utils/formatters'; import { useTheme } from '../../../../../hooks/use_theme'; -import { px, units } from '../../../../../style/variables'; -import { Legend } from '../../Legend'; -import { AgentMark } from '../../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks'; +import { AgentMark } from '../../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_agent_marks'; +import { Legend } from '../legend'; const NameContainer = euiStyled.div` border-bottom: 1px solid ${({ theme }) => theme.eui.euiColorMediumShade}; - padding-bottom: ${px(units.half)}; + padding-bottom: ${({ theme }) => theme.eui.paddingSizes.s}; `; const TimeContainer = euiStyled.div` color: ${({ theme }) => theme.eui.euiColorMediumShade}; - padding-top: ${px(units.half)}; + padding-top: ${({ theme }) => theme.eui.paddingSizes.s}; `; interface Props { diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.test.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.test.tsx similarity index 96% rename from x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.test.tsx rename to x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.test.tsx index 36634f97a3a45..fdb97ea4fadde 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.test.tsx @@ -14,8 +14,8 @@ import { expectTextsInDocument, renderWithTheme, } from '../../../../../utils/testHelpers'; -import { ErrorMark } from '../../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks'; -import { ErrorMarker } from './ErrorMarker'; +import { ErrorMark } from '../../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_error_marks'; +import { ErrorMarker } from './error_marker'; function Wrapper({ children }: { children?: ReactNode }) { return ( diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.tsx similarity index 88% rename from x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.tsx rename to x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.tsx index 044070303d2ff..b1e902957bfd7 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/ErrorMarker.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/error_marker.tsx @@ -5,36 +5,35 @@ * 2.0. */ -import React, { useState } from 'react'; import { EuiPopover, EuiText } from '@elastic/eui'; +import React, { useState } from 'react'; import { euiStyled } from '../../../../../../../../../src/plugins/kibana_react/common'; -import { asDuration } from '../../../../../../common/utils/formatters'; -import { useTheme } from '../../../../../hooks/use_theme'; import { TRACE_ID, TRANSACTION_ID, } from '../../../../../../common/elasticsearch_fieldnames'; +import { asDuration } from '../../../../../../common/utils/formatters'; import { useUrlParams } from '../../../../../context/url_params_context/use_url_params'; -import { px, unit, units } from '../../../../../style/variables'; -import { ErrorMark } from '../../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks'; +import { useTheme } from '../../../../../hooks/use_theme'; +import { ErrorMark } from '../../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_error_marks'; import { ErrorDetailLink } from '../../../Links/apm/ErrorDetailLink'; -import { Legend, Shape } from '../../Legend'; +import { Legend, Shape } from '../legend'; interface Props { mark: ErrorMark; } const Popover = euiStyled.div` - max-width: ${px(280)}; + max-width: 280px; `; const TimeLegend = euiStyled(Legend)` - margin-bottom: ${px(unit)}; + margin-bottom: ${({ theme }) => theme.eui.euiSize}; `; const ErrorLink = euiStyled(ErrorDetailLink)` display: block; - margin: ${px(units.half)} 0 ${px(units.half)} 0; + margin: ${({ theme }) => `${theme.eui.euiSizeS} 0 ${theme.eui.euiSizeS} 0`}; overflow-wrap: break-word; `; @@ -102,7 +101,7 @@ export function ErrorMarker({ mark }: Props) { ( -
@
+
@
)} /> { it('renders agent marker', () => { diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/index.tsx index bece72b398d31..88318eb0e0c2d 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/Marker/index.tsx @@ -7,11 +7,10 @@ import React from 'react'; import { euiStyled } from '../../../../../../../../../src/plugins/kibana_react/common'; -import { px } from '../../../../../style/variables'; -import { AgentMarker } from './AgentMarker'; -import { ErrorMarker } from './ErrorMarker'; -import { AgentMark } from '../../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks'; -import { ErrorMark } from '../../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks'; +import { AgentMark } from '../../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_agent_marks'; +import { ErrorMark } from '../../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_error_marks'; +import { AgentMarker } from './agent_marker'; +import { ErrorMarker } from './error_marker'; interface Props { mark: ErrorMark | AgentMark; @@ -26,7 +25,7 @@ const MarkerContainer = euiStyled.div` export function Marker({ mark, x }: Props) { const legendWidth = 11; return ( - + {mark.type === 'errorMark' ? ( ) : ( diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/VerticalLines.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/VerticalLines.tsx index 428da80fb808a..2dcc969f661b8 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/VerticalLines.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/VerticalLines.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { VerticalGridLines, XYPlot } from 'react-vis'; import { useTheme } from '../../../../hooks/use_theme'; -import { Mark } from '../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks'; +import { Mark } from '../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks'; import { PlotValues } from './plotUtils'; interface VerticalLinesProps { diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/index.tsx index 650faa195271c..6c7cb7a067d2e 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/index.tsx @@ -8,11 +8,11 @@ import PropTypes from 'prop-types'; import React, { PureComponent, ReactNode } from 'react'; import { makeWidthFlexible } from 'react-vis'; +import { AgentMark } from '../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_agent_marks'; +import { ErrorMark } from '../../../app/transaction_details/waterfall_with_summary/waterfall_container/Marks/get_error_marks'; import { getPlotValues } from './plotUtils'; -import { TimelineAxis } from './TimelineAxis'; +import { TimelineAxis } from './timeline_axis'; import { VerticalLines } from './VerticalLines'; -import { ErrorMark } from '../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks'; -import { AgentMark } from '../../../app/transaction_details/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks'; export type Mark = AgentMark | ErrorMark; diff --git a/x-pack/plugins/apm/public/components/shared/charts/Legend/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/legend.tsx similarity index 75% rename from x-pack/plugins/apm/public/components/shared/charts/Legend/index.tsx rename to x-pack/plugins/apm/public/components/shared/charts/Timeline/legend.tsx index f81da48b760e7..c7066565f0b22 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Legend/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/legend.tsx @@ -8,7 +8,6 @@ import React from 'react'; import { euiStyled } from '../../../../../../../../src/plugins/kibana_react/common'; import { useTheme } from '../../../../hooks/use_theme'; -import { fontSizes, px, units } from '../../../../style/variables'; export enum Shape { circle = 'circle', @@ -17,7 +16,6 @@ export enum Shape { interface ContainerProps { onClick: (e: Event) => void; - fontSize?: string; clickable: boolean; disabled: boolean; } @@ -25,7 +23,7 @@ interface ContainerProps { const Container = euiStyled.div` display: flex; align-items: center; - font-size: ${(props) => props.fontSize}; + font-size: ${({ theme }) => theme.eui.euiFontSizeS}; color: ${({ theme }) => theme.eui.euiColorDarkShade}; cursor: ${(props) => (props.clickable ? 'pointer' : 'initial')}; opacity: ${(props) => (props.disabled ? 0.4 : 1)}; @@ -33,16 +31,17 @@ const Container = euiStyled.div` `; interface IndicatorProps { - radius: number; color: string; shape: Shape; withMargin: boolean; } +const radius = 11; + export const Indicator = euiStyled.span` - width: ${(props) => px(props.radius)}; - height: ${(props) => px(props.radius)}; - margin-right: ${(props) => (props.withMargin ? px(props.radius / 2) : 0)}; + width: ${radius}px; + height: ${radius}px; + margin-right: ${(props) => (props.withMargin ? `${radius / 2}px` : 0)}; background: ${(props) => props.color}; border-radius: ${(props) => { return props.shape === Shape.circle ? '100%' : '0'; @@ -53,8 +52,6 @@ interface Props { onClick?: any; text?: string; color?: string; - fontSize?: string; - radius?: number; disabled?: boolean; clickable?: boolean; shape?: Shape; @@ -65,8 +62,6 @@ export function Legend({ onClick, text, color, - fontSize = fontSizes.small, - radius = units.minus - 1, disabled = false, clickable = false, shape = Shape.circle, @@ -81,18 +76,12 @@ export function Legend({ onClick={onClick} disabled={disabled} clickable={clickable || Boolean(onClick)} - fontSize={fontSize} {...rest} > {indicator ? ( indicator() ) : ( - + )} {text} diff --git a/x-pack/plugins/apm/public/components/shared/charts/Timeline/TimelineAxis.tsx b/x-pack/plugins/apm/public/components/shared/charts/Timeline/timeline_axis.tsx similarity index 97% rename from x-pack/plugins/apm/public/components/shared/charts/Timeline/TimelineAxis.tsx rename to x-pack/plugins/apm/public/components/shared/charts/Timeline/timeline_axis.tsx index 32b78bf8818a3..cf942ebb75776 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Timeline/TimelineAxis.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/Timeline/timeline_axis.tsx @@ -5,12 +5,11 @@ * 2.0. */ -import React, { ReactNode } from 'react'; import { inRange } from 'lodash'; +import React, { ReactNode } from 'react'; import { XAxis, XYPlot } from 'react-vis'; import { getDurationFormatter } from '../../../../../common/utils/formatters'; import { useTheme } from '../../../../hooks/use_theme'; -import { px } from '../../../../style/variables'; import { Mark } from './'; import { LastTickValue } from './LastTickValue'; import { Marker } from './Marker'; @@ -59,7 +58,7 @@ export function TimelineAxis({ position: 'sticky', top: 0, borderBottom: `1px solid ${theme.eui.euiColorMediumShade}`, - height: px(margins.top), + height: margins.top, zIndex: 2, width: '100%', }} diff --git a/x-pack/plugins/apm/public/components/shared/charts/spark_plot/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/spark_plot/index.tsx index 59205ef498534..6b93fe9605e42 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/spark_plot/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/spark_plot/index.tsx @@ -5,9 +5,6 @@ * 2.0. */ -import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import React from 'react'; -import { EuiIcon } from '@elastic/eui'; import { AreaSeries, Chart, @@ -16,11 +13,13 @@ import { ScaleType, Settings, } from '@elastic/charts'; +import { EuiFlexGroup, EuiFlexItem, EuiIcon } from '@elastic/eui'; import { merge } from 'lodash'; -import { Coordinate } from '../../../../../typings/timeseries'; +import React from 'react'; import { useChartTheme } from '../../../../../../observability/public'; -import { px, unit } from '../../../../style/variables'; +import { Coordinate } from '../../../../../typings/timeseries'; import { useTheme } from '../../../../hooks/use_theme'; +import { unit } from '../../../../utils/style'; import { getComparisonChartTheme } from '../../time_comparison/get_time_range_comparison'; export type Color = @@ -73,8 +72,8 @@ export function SparkPlot({ const colorValue = theme.eui[color]; const chartSize = { - height: px(24), - width: compact ? px(unit * 3) : px(unit * 4), + height: theme.eui.euiSizeL, + width: compact ? unit * 3 : unit * 4, }; const Sparkline = hasComparisonSeries ? LineSeries : AreaSeries; diff --git a/x-pack/plugins/apm/public/components/shared/charts/timeseries_chart.tsx b/x-pack/plugins/apm/public/components/shared/charts/timeseries_chart.tsx index 9e7a3ac744ffe..9667bbd33cc73 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/timeseries_chart.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/timeseries_chart.tsx @@ -40,7 +40,7 @@ import { FETCH_STATUS } from '../../../hooks/use_fetcher'; import { useTheme } from '../../../hooks/use_theme'; import { useAnnotationsContext } from '../../../context/annotations/use_annotations_context'; import { useChartPointerEventContext } from '../../../context/chart_pointer_event/use_chart_pointer_event_context'; -import { unit } from '../../../style/variables'; +import { unit } from '../../../utils/style'; import { ChartContainer } from './chart_container'; import { onBrushEnd, isTimeseriesEmpty } from './helper/helper'; import { getLatencyChartSelector } from '../../../selectors/latency_chart_selectors'; diff --git a/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/transaction_breakdown_chart_contents.tsx b/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/transaction_breakdown_chart_contents.tsx index 436eca4781502..a68373892e78b 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/transaction_breakdown_chart_contents.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/transaction_breakdown_chart_contents.tsx @@ -34,7 +34,7 @@ import { useTheme } from '../../../../hooks/use_theme'; import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useAnnotationsContext } from '../../../../context/annotations/use_annotations_context'; import { useChartPointerEventContext } from '../../../../context/chart_pointer_event/use_chart_pointer_event_context'; -import { unit } from '../../../../style/variables'; +import { unit } from '../../../../utils/style'; import { ChartContainer } from '../../charts/chart_container'; import { isTimeseriesEmpty, onBrushEnd } from '../../charts/helper/helper'; diff --git a/x-pack/plugins/apm/public/components/shared/key_value_filter_list/index.tsx b/x-pack/plugins/apm/public/components/shared/key_value_filter_list/index.tsx index 54d8790c32d33..d28cc1646f16a 100644 --- a/x-pack/plugins/apm/public/components/shared/key_value_filter_list/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/key_value_filter_list/index.tsx @@ -19,7 +19,6 @@ import { import { i18n } from '@kbn/i18n'; import React, { Fragment } from 'react'; import styled from 'styled-components'; -import { px, units } from '../../../style/variables'; interface KeyValue { key: string; @@ -34,7 +33,8 @@ const StyledEuiAccordion = styled(EuiAccordion)` `; const StyledEuiDescriptionList = styled(EuiDescriptionList)` - margin: ${px(units.half)} ${px(units.half)} 0 ${px(units.half)}; + margin: ${({ theme }) => + `${theme.eui.euiSizeS} ${theme.eui.euiSizeS} 0 ${theme.eui.euiSizeS}`}; .descriptionList__title, .descriptionList__description { border-bottom: ${({ theme }) => theme.eui.euiBorderThin}; diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/ClickOutside.js b/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/ClickOutside.js similarity index 100% rename from x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/ClickOutside.js rename to x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/ClickOutside.js diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestion.js b/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/Suggestion.js similarity index 84% rename from x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestion.js rename to x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/Suggestion.js index 987daf67b1fc7..26b99c4e54f65 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestion.js +++ b/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/Suggestion.js @@ -9,13 +9,7 @@ import React from 'react'; import PropTypes from 'prop-types'; import { euiStyled } from '../../../../../../../../src/plugins/kibana_react/common'; import { EuiIcon } from '@elastic/eui'; -import { - fontFamilyCode, - px, - units, - fontSizes, - unit, -} from '../../../../style/variables'; +import { unit } from '../../../../utils/style'; import { tint } from 'polished'; function getIconColor(type, theme) { @@ -40,23 +34,23 @@ const Description = euiStyled.div` display: inline; span { - font-family: ${fontFamilyCode}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; color: ${({ theme }) => theme.eui.euiColorFullShade}; - padding: 0 ${px(units.quarter)}; + padding: 0 ${({ theme }) => theme.eui.paddingSizes.xs}; display: inline-block; } } `; const ListItem = euiStyled.li` - font-size: ${fontSizes.small}; - height: ${px(units.double)}; + font-size: ${({ theme }) => theme.eui.euiFontSizeXS}; + height: ${({ theme }) => theme.eui.euiSizeXL}; align-items: center; display: flex; background: ${({ selected, theme }) => selected ? theme.eui.euiColorLightestShade : 'initial'}; cursor: pointer; - border-radius: ${px(units.quarter)}; + border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; ${Description} { p span { @@ -69,19 +63,19 @@ const ListItem = euiStyled.li` `; const Icon = euiStyled.div` - flex: 0 0 ${px(units.double)}; + flex: 0 0 ${({ theme }) => theme.eui.euiSizeXL}; background: ${({ type, theme }) => tint(0.9, getIconColor(type, theme))}; color: ${({ type, theme }) => getIconColor(type, theme)}; width: 100%; height: 100%; text-align: center; - line-height: ${px(units.double)}; + line-height: ${({ theme }) => theme.eui.euiSizeXL}; `; const TextValue = euiStyled.div` - flex: 0 0 ${px(unit * 16)}; + flex: 0 0 ${unit * 16}px; color: ${({ theme }) => theme.eui.euiColorDarkestShade}; - padding: 0 ${px(units.half)}; + padding: 0 ${({ theme }) => theme.eui.paddingSizes.s}; `; function getEuiIconType(type) { diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestions.js b/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/Suggestions.js similarity index 88% rename from x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestions.js rename to x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/Suggestions.js index 405be89c6629c..386eb7e1e0d7d 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestions.js +++ b/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/Suggestions.js @@ -5,25 +5,28 @@ * 2.0. */ -import React, { Component } from 'react'; +import { isEmpty } from 'lodash'; +import { tint } from 'polished'; import PropTypes from 'prop-types'; +import React, { Component } from 'react'; import { euiStyled } from '../../../../../../../../src/plugins/kibana_react/common'; -import { isEmpty } from 'lodash'; +import { unit } from '../../../../utils/style'; import Suggestion from './Suggestion'; -import { units, px, unit } from '../../../../style/variables'; -import { tint } from 'polished'; const List = euiStyled.ul` width: 100%; border: 1px solid ${({ theme }) => theme.eui.euiColorLightShade}; - border-radius: ${px(units.quarter)}; - box-shadow: 0px ${px(units.quarter)} ${px(units.double)} - ${({ theme }) => tint(0.9, theme.eui.euiColorFullShade)}; + border-radius: ${({ theme }) => theme.eui.euiBorderRadiusSmall}; + box-shadow: 0 ${({ theme }) => + `${theme.eui.euiSizeXS} ${theme.eui.euiSizeXL} ${tint( + 0.9, + theme.eui.euiColorFullShade + )}`}; position: absolute; background: ${({ theme }) => theme.eui.euiColorEmptyShade}; z-index: 10; left: 0; - max-height: ${px(unit * 20)}; + max-height: ${unit * 20}px; overflow: scroll; `; diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/index.js b/x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/index.js similarity index 100% rename from x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/index.js rename to x-pack/plugins/apm/public/components/shared/kuery_bar/Typeahead/index.js diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/get_bool_filter.ts b/x-pack/plugins/apm/public/components/shared/kuery_bar/get_bool_filter.ts similarity index 100% rename from x-pack/plugins/apm/public/components/shared/KueryBar/get_bool_filter.ts rename to x-pack/plugins/apm/public/components/shared/kuery_bar/get_bool_filter.ts diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx b/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx rename to x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/use_processor_event.ts b/x-pack/plugins/apm/public/components/shared/kuery_bar/use_processor_event.ts similarity index 100% rename from x-pack/plugins/apm/public/components/shared/KueryBar/use_processor_event.ts rename to x-pack/plugins/apm/public/components/shared/kuery_bar/use_processor_event.ts diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/utils.ts b/x-pack/plugins/apm/public/components/shared/kuery_bar/utils.ts similarity index 100% rename from x-pack/plugins/apm/public/components/shared/KueryBar/utils.ts rename to x-pack/plugins/apm/public/components/shared/kuery_bar/utils.ts diff --git a/x-pack/plugins/apm/public/components/shared/ManagedTable/__snapshots__/ManagedTable.test.js.snap b/x-pack/plugins/apm/public/components/shared/managed_table/__snapshots__/managed_table.test.tsx.snap similarity index 90% rename from x-pack/plugins/apm/public/components/shared/ManagedTable/__snapshots__/ManagedTable.test.js.snap rename to x-pack/plugins/apm/public/components/shared/managed_table/__snapshots__/managed_table.test.tsx.snap index 655fc5a25b9ef..55e0bc0fe2431 100644 --- a/x-pack/plugins/apm/public/components/shared/ManagedTable/__snapshots__/ManagedTable.test.js.snap +++ b/x-pack/plugins/apm/public/components/shared/managed_table/__snapshots__/managed_table.test.tsx.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`ManagedTable component should render a page-full of items, with defaults 1`] = ` +exports[`ManagedTable should render a page-full of items, with defaults 1`] = ` `; -exports[`ManagedTable component should render when specifying initial values 1`] = ` +exports[`ManagedTable should render when specifying initial values 1`] = ` { field?: string; dataType?: string; align?: string; - width?: string; + width?: string | number; sortable?: boolean; render?: (value: any, item: T) => unknown; } diff --git a/x-pack/plugins/apm/public/components/shared/ManagedTable/ManagedTable.test.js b/x-pack/plugins/apm/public/components/shared/managed_table/managed_table.test.tsx similarity index 54% rename from x-pack/plugins/apm/public/components/shared/ManagedTable/ManagedTable.test.js rename to x-pack/plugins/apm/public/components/shared/managed_table/managed_table.test.tsx index ab96eba14b403..c474d98a3f0d4 100644 --- a/x-pack/plugins/apm/public/components/shared/ManagedTable/ManagedTable.test.js +++ b/x-pack/plugins/apm/public/components/shared/managed_table/managed_table.test.tsx @@ -7,39 +7,41 @@ import { shallow } from 'enzyme'; import React from 'react'; -import { UnoptimizedManagedTable } from '.'; +import { ITableColumn, UnoptimizedManagedTable } from '.'; -describe('ManagedTable component', () => { - let people; - let columns; +interface Person { + name: string; + age: number; +} - beforeEach(() => { - people = [ - { name: 'Jess', age: 29 }, - { name: 'Becky', age: 43 }, - { name: 'Thomas', age: 31 }, - ]; - columns = [ - { - field: 'name', - name: 'Name', - sortable: true, - render: (name) => `Name: ${name}`, - }, - { field: 'age', name: 'Age', render: (age) => `Age: ${age}` }, - ]; - }); +describe('ManagedTable', () => { + const people: Person[] = [ + { name: 'Jess', age: 29 }, + { name: 'Becky', age: 43 }, + { name: 'Thomas', age: 31 }, + ]; + const columns: Array> = [ + { + field: 'name', + name: 'Name', + sortable: true, + render: (name) => `Name: ${name}`, + }, + { field: 'age', name: 'Age', render: (age) => `Age: ${age}` }, + ]; it('should render a page-full of items, with defaults', () => { expect( - shallow() + shallow( + columns={columns} items={people} /> + ) ).toMatchSnapshot(); }); it('should render when specifying initial values', () => { expect( shallow( - columns={columns} items={people} initialSortField="age" diff --git a/x-pack/plugins/apm/public/components/shared/search_bar.tsx b/x-pack/plugins/apm/public/components/shared/search_bar.tsx index 74374e331ee8e..4f9e58239855d 100644 --- a/x-pack/plugins/apm/public/components/shared/search_bar.tsx +++ b/x-pack/plugins/apm/public/components/shared/search_bar.tsx @@ -19,9 +19,8 @@ import { enableInspectEsQueries } from '../../../../observability/public'; import { useApmPluginContext } from '../../context/apm_plugin/use_apm_plugin_context'; import { useKibanaUrl } from '../../hooks/useKibanaUrl'; import { useBreakPoints } from '../../hooks/use_break_points'; -import { px } from '../../style/variables'; import { DatePicker } from './DatePicker'; -import { KueryBar } from './KueryBar'; +import { KueryBar } from './kuery_bar'; import { TimeComparison } from './time_comparison'; import { TransactionTypeSelect } from './transaction_type_select'; @@ -125,7 +124,7 @@ export function SearchBar({ responsive={false} > {showTimeComparison && ( - + )} diff --git a/x-pack/plugins/apm/public/components/shared/service_icons/icon_popover.tsx b/x-pack/plugins/apm/public/components/shared/service_icons/icon_popover.tsx index 05305558564f1..695c941c61ed4 100644 --- a/x-pack/plugins/apm/public/components/shared/service_icons/icon_popover.tsx +++ b/x-pack/plugins/apm/public/components/shared/service_icons/icon_popover.tsx @@ -14,7 +14,6 @@ import { } from '@elastic/eui'; import React from 'react'; import { FETCH_STATUS } from '../../../hooks/use_fetcher'; -import { px } from '../../../style/variables'; interface IconPopoverProps { title: string; @@ -59,7 +58,7 @@ export function IconPopover({ closePopover={onClose} > {title} -
+
{isLoading ? ( ) : ( diff --git a/x-pack/plugins/apm/public/components/shared/StickyProperties/__snapshots__/StickyProperties.test.js.snap b/x-pack/plugins/apm/public/components/shared/sticky_properties/__snapshots__/sticky_properties.test.tsx.snap similarity index 100% rename from x-pack/plugins/apm/public/components/shared/StickyProperties/__snapshots__/StickyProperties.test.js.snap rename to x-pack/plugins/apm/public/components/shared/sticky_properties/__snapshots__/sticky_properties.test.tsx.snap diff --git a/x-pack/plugins/apm/public/components/shared/StickyProperties/index.tsx b/x-pack/plugins/apm/public/components/shared/sticky_properties/index.tsx similarity index 93% rename from x-pack/plugins/apm/public/components/shared/StickyProperties/index.tsx rename to x-pack/plugins/apm/public/components/shared/sticky_properties/index.tsx index ee764db516d72..49488ba09e068 100644 --- a/x-pack/plugins/apm/public/components/shared/StickyProperties/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/sticky_properties/index.tsx @@ -9,13 +9,7 @@ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { EuiToolTip } from '@elastic/eui'; import React from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; -import { - fontFamilyCode, - fontSizes, - px, - truncate, - units, -} from '../../../style/variables'; +import { truncate } from '../../../utils/style'; export interface IStickyProperty { val: JSX.Element | string | Date; @@ -26,12 +20,12 @@ export interface IStickyProperty { } const TooltipFieldName = euiStyled.span` - font-family: ${fontFamilyCode}; + font-family: ${({ theme }) => theme.eui.euiCodeFontFamily}; `; const PropertyLabel = euiStyled.div` - margin-bottom: ${px(units.half)}; - font-size: ${fontSizes.small}; + margin-bottom: ${({ theme }) => theme.eui.euiSizeS}; + font-size: ${({ theme }) => theme.eui.euiFontSizeXS}; color: ${({ theme }) => theme.eui.euiColorMediumShade}; span { diff --git a/x-pack/plugins/apm/public/components/shared/StickyProperties/StickyProperties.test.js b/x-pack/plugins/apm/public/components/shared/sticky_properties/sticky_properties.test.tsx similarity index 80% rename from x-pack/plugins/apm/public/components/shared/StickyProperties/StickyProperties.test.js rename to x-pack/plugins/apm/public/components/shared/sticky_properties/sticky_properties.test.tsx index eba70a171a1df..d29702752c159 100644 --- a/x-pack/plugins/apm/public/components/shared/StickyProperties/StickyProperties.test.js +++ b/x-pack/plugins/apm/public/components/shared/sticky_properties/sticky_properties.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { StickyProperties } from './index'; +import { StickyProperties } from '.'; import { shallow } from 'enzyme'; import { USER_ID, URL_FULL } from '../../../../common/elasticsearch_fieldnames'; import { mockMoment } from '../../../utils/testHelpers'; @@ -35,7 +35,7 @@ describe('StickyProperties', () => { { label: 'User ID', fieldName: USER_ID, - val: 1337, + val: '1337', }, ]; @@ -52,7 +52,7 @@ describe('StickyProperties', () => { { label: 'My Number', fieldName: 'myNumber', - val: 1337, + val: '1337', }, ]; @@ -66,25 +66,6 @@ describe('StickyProperties', () => { expect(wrapper).toEqual('1337'); }); - it('should not stringify booleans', () => { - const stickyProperties = [ - { - label: 'My boolean', - fieldName: 'myBoolean', - val: true, - }, - ]; - - const wrapper = shallow( - - ) - .find('PropertyValue') - .dive() - .text(); - - expect(wrapper).toEqual(''); - }); - it('should render nested components', () => { const stickyProperties = [ { diff --git a/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx b/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx index ed9d1a15cdbca..d7dfd3de2b628 100644 --- a/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx @@ -10,13 +10,12 @@ import { i18n } from '@kbn/i18n'; import moment from 'moment'; import React from 'react'; import { useHistory } from 'react-router-dom'; -import { useUiTracker } from '../../../../../observability/public'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; +import { useUiTracker } from '../../../../../observability/public'; import { getDateDifference } from '../../../../common/utils/formatters'; import { useUrlParams } from '../../../context/url_params_context/use_url_params'; -import { px, unit } from '../../../style/variables'; -import * as urlHelpers from '../../shared/Links/url_helpers'; import { useBreakPoints } from '../../../hooks/use_break_points'; +import * as urlHelpers from '../../shared/Links/url_helpers'; import { getTimeRangeComparison, TimeRangeComparisonType, @@ -28,7 +27,7 @@ const PrependContainer = euiStyled.div` align-items: center; background-color: ${({ theme }) => theme.eui.euiFormInputGroupLabelBackground}; - padding: 0 ${px(unit)}; + padding: 0 ${({ theme }) => theme.eui.paddingSizes.m}; `; function getDateFormat({ diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.test.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.test.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.test.tsx rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.test.tsx diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.tsx similarity index 98% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.tsx rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.tsx index b28b364adcf30..a4f7c2b663484 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/TransactionActionMenu.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.tsx @@ -22,7 +22,7 @@ import { Transaction } from '../../../../typings/es_schemas/ui/transaction'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; import { useLicenseContext } from '../../../context/license/use_license_context'; import { useUrlParams } from '../../../context/url_params_context/use_url_params'; -import { CustomLinkMenuSection } from './CustomLinkMenuSection'; +import { CustomLinkMenuSection } from './custom_link_menu_section'; import { getSections } from './sections'; interface Props { diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/__fixtures__/mockData.ts b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/__fixtures__/mockData.ts similarity index 100% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/__fixtures__/mockData.ts rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/__fixtures__/mockData.ts diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/__snapshots__/TransactionActionMenu.test.tsx.snap b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/__snapshots__/TransactionActionMenu.test.tsx.snap similarity index 100% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/__snapshots__/TransactionActionMenu.test.tsx.snap rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/__snapshots__/TransactionActionMenu.test.tsx.snap diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkToolbar.test.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/CustomLinkToolbar.test.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkToolbar.test.tsx rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/CustomLinkToolbar.test.tsx diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkToolbar.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/CustomLinkToolbar.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkToolbar.tsx rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/CustomLinkToolbar.tsx diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkList.test.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.test.tsx similarity index 96% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkList.test.tsx rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.test.tsx index c0c4613e033c9..e063fb36b8e9c 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkList.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.test.tsx @@ -5,15 +5,15 @@ * 2.0. */ -import React from 'react'; import { render } from '@testing-library/react'; -import { CustomLinkList } from './CustomLinkList'; +import React from 'react'; +import { CustomLink } from '../../../../../common/custom_link/custom_link_types'; +import { Transaction } from '../../../../../typings/es_schemas/ui/transaction'; import { expectTextsInDocument, expectTextsNotInDocument, } from '../../../../utils/testHelpers'; -import { Transaction } from '../../../../../typings/es_schemas/ui/transaction'; -import { CustomLink } from '../../../../../common/custom_link/custom_link_types'; +import { CustomLinkList } from './custom_link_list'; describe('CustomLinkList', () => { const customLinks = [ diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkList.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.tsx similarity index 89% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkList.tsx rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.tsx index 02d6dd436040f..7ea7cd35c443a 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/CustomLinkList.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/custom_link_list.tsx @@ -8,12 +8,12 @@ import Mustache from 'mustache'; import React from 'react'; import { - SectionLinks, SectionLink, + SectionLinks, } from '../../../../../../observability/public'; import { CustomLink } from '../../../../../common/custom_link/custom_link_types'; import { Transaction } from '../../../../../typings/es_schemas/ui/transaction'; -import { px, unit } from '../../../../style/variables'; +import { unit } from '../../../../utils/style'; export function CustomLinkList({ customLinks, @@ -23,7 +23,7 @@ export function CustomLinkList({ transaction: Transaction; }) { return ( - + {customLinks.map((link) => { const href = getHref(link, transaction); return ( diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/index.test.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.test.tsx similarity index 100% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/index.test.tsx rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.test.tsx diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/index.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.tsx similarity index 94% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/index.tsx rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.tsx index cbbf34c78c4af..bc234b88a08e4 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/CustomLinkMenuSection/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/custom_link_menu_section/index.tsx @@ -5,37 +5,36 @@ * 2.0. */ -import React, { useMemo, useState } from 'react'; import { - EuiText, + EuiButtonEmpty, EuiFlexGroup, EuiFlexItem, EuiSpacer, - EuiButtonEmpty, + EuiText, + EuiToolTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isEmpty } from 'lodash'; -import { EuiToolTip } from '@elastic/eui'; -import { NO_PERMISSION_LABEL } from '../../../../../common/custom_link'; -import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; +import React, { useMemo, useState } from 'react'; import { ActionMenuDivider, Section, SectionSubtitle, SectionTitle, } from '../../../../../../observability/public'; -import { Transaction } from '../../../../../typings/es_schemas/ui/transaction'; -import { CustomLinkList } from './CustomLinkList'; -import { CustomLinkToolbar } from './CustomLinkToolbar'; -import { FETCH_STATUS, useFetcher } from '../../../../hooks/use_fetcher'; -import { LoadingStatePrompt } from '../../LoadingStatePrompt'; -import { px } from '../../../../style/variables'; -import { CreateEditCustomLinkFlyout } from '../../../app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout'; -import { convertFiltersToQuery } from '../../../app/Settings/CustomizeUI/CustomLink/CreateEditCustomLinkFlyout/helper'; +import { NO_PERMISSION_LABEL } from '../../../../../common/custom_link'; import { CustomLink, Filter, } from '../../../../../common/custom_link/custom_link_types'; +import { Transaction } from '../../../../../typings/es_schemas/ui/transaction'; +import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; +import { FETCH_STATUS, useFetcher } from '../../../../hooks/use_fetcher'; +import { CreateEditCustomLinkFlyout } from '../../../app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout'; +import { convertFiltersToQuery } from '../../../app/Settings/customize_ui/custom_link/create_edit_custom_link_flyout/helper'; +import { LoadingStatePrompt } from '../../LoadingStatePrompt'; +import { CustomLinkToolbar } from './CustomLinkToolbar'; +import { CustomLinkList } from './custom_link_list'; const DEFAULT_LINKS_TO_SHOW = 3; @@ -165,7 +164,7 @@ function BottomSection({ return ( - + {i18n.translate('xpack.apm.customLink.empty', { defaultMessage: 'No custom links found. Set up your own custom links, e.g., a link to a specific Dashboard or external link.', diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/sections.test.ts b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/sections.test.ts similarity index 100% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/sections.test.ts rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/sections.test.ts diff --git a/x-pack/plugins/apm/public/components/shared/TransactionActionMenu/sections.ts b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/sections.ts similarity index 100% rename from x-pack/plugins/apm/public/components/shared/TransactionActionMenu/sections.ts rename to x-pack/plugins/apm/public/components/shared/transaction_action_menu/sections.ts diff --git a/x-pack/plugins/apm/public/components/shared/truncate_with_tooltip/index.tsx b/x-pack/plugins/apm/public/components/shared/truncate_with_tooltip/index.tsx index 63e0b84362073..d9268c14aa2ea 100644 --- a/x-pack/plugins/apm/public/components/shared/truncate_with_tooltip/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/truncate_with_tooltip/index.tsx @@ -8,7 +8,7 @@ import { EuiToolTip } from '@elastic/eui'; import React from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; -import { truncate } from '../../../style/variables'; +import { truncate } from '../../../utils/style'; const tooltipAnchorClassname = '_apm_truncate_tooltip_anchor_'; diff --git a/x-pack/plugins/apm/public/plugin.ts b/x-pack/plugins/apm/public/plugin.ts index 46cbc26a74d2d..0cd5009570613 100644 --- a/x-pack/plugins/apm/public/plugin.ts +++ b/x-pack/plugins/apm/public/plugin.ts @@ -22,6 +22,7 @@ import type { DataPublicPluginStart, } from '../../../../src/plugins/data/public'; import type { EmbeddableStart } from '../../../../src/plugins/embeddable/public'; +import type { FleetStart } from '../../fleet/public'; import type { HomePublicPluginSetup } from '../../../../src/plugins/home/public'; import type { PluginSetupContract as AlertingPluginPublicSetup, @@ -43,6 +44,10 @@ import type { } from '../../triggers_actions_ui/public'; import { registerApmAlerts } from './components/alerting/register_apm_alerts'; import { featureCatalogueEntry } from './featureCatalogueEntry'; +import { + getApmEnrollmentFlyoutData, + LazyApmCustomAssetsExtension, +} from './components/fleet_integration'; export type ApmPluginSetup = ReturnType; @@ -69,6 +74,7 @@ export interface ApmPluginStartDeps { ml?: MlPluginStart; triggersActionsUi: TriggersAndActionsUIPublicPluginStart; observability: ObservabilityPublicStart; + fleet: FleetStart; } export class ApmPlugin implements Plugin { @@ -303,5 +309,22 @@ export class ApmPlugin implements Plugin { return {}; } - public start(core: CoreStart, plugins: ApmPluginStartDeps) {} + public start(core: CoreStart, plugins: ApmPluginStartDeps) { + const { fleet } = plugins; + + const agentEnrollmentExtensionData = getApmEnrollmentFlyoutData(); + + fleet.registerExtension({ + package: 'apm', + view: 'agent-enrollment-flyout', + title: agentEnrollmentExtensionData.title, + Component: agentEnrollmentExtensionData.Component, + }); + + fleet.registerExtension({ + package: 'apm', + view: 'package-detail-assets', + Component: LazyApmCustomAssetsExtension, + }); + } } diff --git a/x-pack/plugins/apm/public/style/variables.ts b/x-pack/plugins/apm/public/style/variables.ts deleted file mode 100644 index 07ccf97c0dab0..0000000000000 --- a/x-pack/plugins/apm/public/style/variables.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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. - */ - -// Units -export const unit = 16; - -export const units = { - unit, - eighth: unit / 8, - quarter: unit / 4, - half: unit / 2, - minus: unit * 0.75, - plus: unit * 1.5, - double: unit * 2, - triple: unit * 3, - quadruple: unit * 4, -}; - -export function px(value: number): string { - return `${value}px`; -} - -export function pct(value: number): string { - return `${value}%`; -} - -// Styling -export const borderRadius = '4px'; - -// Fonts -export const fontFamilyCode = - '"Roboto Mono", Consolas, Menlo, Courier, monospace'; - -// Font sizes -export const fontSize = '14px'; - -export const fontSizes = { - tiny: '10px', - small: '12px', - large: '16px', - xlarge: '20px', - xxlarge: '30px', -}; - -export function truncate(width: string) { - return ` - max-width: ${width}; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - `; -} diff --git a/x-pack/plugins/apm/public/utils/style.ts b/x-pack/plugins/apm/public/utils/style.ts new file mode 100644 index 0000000000000..3c8aa5d339c6e --- /dev/null +++ b/x-pack/plugins/apm/public/utils/style.ts @@ -0,0 +1,17 @@ +/* + * 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 const unit = 16; + +export function truncate(width: string | number) { + return ` + max-width: ${typeof width === 'string' ? width : `${width}px`}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + `; +} diff --git a/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.component.tsx b/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.component.tsx index 716f757b7c25e..dd7df7059a7a4 100644 --- a/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.component.tsx +++ b/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.component.tsx @@ -13,7 +13,7 @@ import { SavedObjectFinderUi, SavedObjectMetaData, } from '../../../../../../src/plugins/saved_objects/public/'; -import { useServices } from '../../services'; +import { usePlatformService, useServices } from '../../services'; const strings = { getNoItemsText: () => @@ -33,9 +33,10 @@ export interface Props { export const AddEmbeddableFlyout: FC = ({ onSelect, availableEmbeddables, onClose }) => { const services = useServices(); - const { embeddables, platform } = services; + const platformService = usePlatformService(); + const { embeddables } = services; const { getEmbeddableFactories } = embeddables; - const { getSavedObjects, getUISettings } = platform; + const { getSavedObjects, getUISettings } = platformService; const onAddPanel = (id: string, savedObjectType: string, name: string) => { const embeddableFactories = getEmbeddableFactories(); diff --git a/x-pack/plugins/canvas/public/components/toolbar/toolbar.component.tsx b/x-pack/plugins/canvas/public/components/toolbar/toolbar.component.tsx index dca549b6b38ed..1c95e844997a0 100644 --- a/x-pack/plugins/canvas/public/components/toolbar/toolbar.component.tsx +++ b/x-pack/plugins/canvas/public/components/toolbar/toolbar.component.tsx @@ -97,7 +97,7 @@ export const Toolbar: FC = ({ {workpadName} - + ( workpad: { id: 'coolworkpad', name: 'Workpad of Cool', height: 10, width: 7 }, pageCount: 11, }} - sharingServices={{ basePath: platformService.getBasePathInterface() }} + sharingServices={{}} onExport={action('onExport')} /> )); @@ -30,7 +29,6 @@ storiesOf('components/WorkpadHeader/ShareMenu', module).add('with Reporting', () pageCount: 11, }} sharingServices={{ - basePath: platformService.getBasePathInterface(), reporting: reportingService.start, }} onExport={action('onExport')} diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/__stories__/flyout.stories.tsx b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/__stories__/flyout.stories.tsx index 4d38cc9fb88b4..d0c1eb550ea60 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/__stories__/flyout.stories.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/__stories__/flyout.stories.tsx @@ -26,17 +26,12 @@ storiesOf('components/WorkpadHeader/ShareMenu/ShareWebsiteFlyout', module) }, }) .add('default', () => ( - + )) .add('unsupported renderers', () => ( )); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/flyout.component.tsx b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/flyout.component.tsx index 5da009e050a27..be337a6dcf00c 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/flyout.component.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/flyout.component.tsx @@ -24,13 +24,42 @@ import { import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; +import { arrayBufferFetch } from '../../../../../common/lib/fetch'; +import { API_ROUTE_SHAREABLE_ZIP } from '../../../../../common/lib/constants'; +import { CanvasRenderedWorkpad } from '../../../../../shareable_runtime/types'; +import { + downloadRenderedWorkpad, + downloadRuntime, + downloadZippedRuntime, +} from '../../../../lib/download_workpad'; import { ZIP, CANVAS, HTML } from '../../../../../i18n/constants'; import { OnCloseFn } from '../share_menu.component'; import { WorkpadStep } from './workpad_step'; import { RuntimeStep } from './runtime_step'; import { SnippetsStep } from './snippets_step'; +import { useNotifyService, usePlatformService } from '../../../../services'; const strings = { + getCopyShareConfigMessage: () => + i18n.translate('xpack.canvas.workpadHeaderShareMenu.copyShareConfigMessage', { + defaultMessage: 'Copied share markup to clipboard', + }), + getShareableZipErrorTitle: (workpadName: string) => + i18n.translate('xpack.canvas.workpadHeaderShareMenu.shareWebsiteErrorTitle', { + defaultMessage: + "Failed to create {ZIP} file for '{workpadName}'. The workpad may be too large. You'll need to download the files separately.", + values: { + ZIP, + workpadName, + }, + }), + getUnknownExportErrorMessage: (type: string) => + i18n.translate('xpack.canvas.workpadHeaderShareMenu.unknownExportErrorMessage', { + defaultMessage: 'Unknown export type: {type}', + values: { + type, + }, + }), getRuntimeStepTitle: () => i18n.translate('xpack.canvas.shareWebsiteFlyout.snippetsStep.downloadRuntimeTitle', { defaultMessage: 'Download runtime', @@ -66,10 +95,9 @@ export type OnDownloadFn = (type: 'share' | 'shareRuntime' | 'shareZip') => void export type OnCopyFn = () => void; export interface Props { - onCopy: OnCopyFn; - onDownload: OnDownloadFn; onClose: OnCloseFn; unsupportedRenderers?: string[]; + renderedWorkpad: CanvasRenderedWorkpad; } const steps = (onDownload: OnDownloadFn, onCopy: OnCopyFn) => [ @@ -88,11 +116,39 @@ const steps = (onDownload: OnDownloadFn, onCopy: OnCopyFn) => [ ]; export const ShareWebsiteFlyout: FC = ({ - onCopy, - onDownload, onClose, unsupportedRenderers, + renderedWorkpad, }) => { + const notifyService = useNotifyService(); + const platformService = usePlatformService(); + const onCopy = () => { + notifyService.info(strings.getCopyShareConfigMessage()); + }; + + const onDownload = (type: 'share' | 'shareRuntime' | 'shareZip') => { + switch (type) { + case 'share': + downloadRenderedWorkpad(renderedWorkpad); + return; + case 'shareRuntime': + downloadRuntime(platformService.getBasePath()); + case 'shareZip': + const basePath = platformService.getBasePath(); + arrayBufferFetch + .post(`${basePath}${API_ROUTE_SHAREABLE_ZIP}`, JSON.stringify(renderedWorkpad)) + .then((blob) => downloadZippedRuntime(blob.data)) + .catch((err: Error) => { + notifyService.error(err, { + title: strings.getShareableZipErrorTitle(renderedWorkpad.name), + }); + }); + return; + default: + throw new Error(strings.getUnknownExportErrorMessage(type)); + } + }; + const link = ( - i18n.translate('xpack.canvas.workpadHeaderShareMenu.copyShareConfigMessage', { - defaultMessage: 'Copied share markup to clipboard', - }), - getShareableZipErrorTitle: (workpadName: string) => - i18n.translate('xpack.canvas.workpadHeaderShareMenu.shareWebsiteErrorTitle', { - defaultMessage: - "Failed to create {ZIP} file for '{workpadName}'. The workpad may be too large. You'll need to download the files separately.", - values: { - ZIP, - workpadName, - }, - }), - getUnknownExportErrorMessage: (type: string) => - i18n.translate('xpack.canvas.workpadHeaderShareMenu.unknownExportErrorMessage', { - defaultMessage: 'Unknown export type: {type}', - values: { - type, - }, - }), -}; - const getUnsupportedRenderers = (state: State) => { const renderers: string[] = []; const expressions = getRenderedWorkpadExpressions(state); @@ -86,41 +52,10 @@ export const ShareWebsiteFlyout = compose connect(mapStateToProps), withKibana, withProps( - ({ - unsupportedRenderers, + ({ unsupportedRenderers, renderedWorkpad, onClose, workpad }: Props): ComponentProps => ({ renderedWorkpad, - onClose, - workpad, - kibana, - }: Props & WithKibanaProps): ComponentProps => ({ unsupportedRenderers, onClose, - onCopy: () => { - pluginServices.getServices().notify.info(strings.getCopyShareConfigMessage()); - }, - onDownload: (type) => { - switch (type) { - case 'share': - downloadRenderedWorkpad(renderedWorkpad); - return; - case 'shareRuntime': - downloadRuntime(kibana.services.http.basePath.get()); - return; - case 'shareZip': - const basePath = kibana.services.http.basePath.get(); - arrayBufferFetch - .post(`${basePath}${API_ROUTE_SHAREABLE_ZIP}`, JSON.stringify(renderedWorkpad)) - .then((blob) => downloadZippedRuntime(blob.data)) - .catch((err: Error) => { - pluginServices.getServices().notify.error(err, { - title: strings.getShareableZipErrorTitle(workpad.name), - }); - }); - return; - default: - throw new Error(strings.getUnknownExportErrorMessage(type)); - } - }, }) ) )(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/share_menu.component.tsx b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/share_menu.component.tsx index 5ccc09bf3586b..8d150d3d36972 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/share_menu.component.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/share_menu.component.tsx @@ -9,11 +9,11 @@ import React, { FunctionComponent, useState } from 'react'; import PropTypes from 'prop-types'; import { EuiButtonEmpty, EuiContextMenu, EuiIcon } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { IBasePath } from 'kibana/public'; import { ReportingStart } from '../../../../../reporting/public'; import { PDF, JSON } from '../../../../i18n/constants'; import { flattenPanelTree } from '../../../lib/flatten_panel_tree'; +import { usePlatformService } from '../../../services'; import { ClosePopoverFn, Popover } from '../../popover'; import { ShareWebsiteFlyout } from './flyout'; import { CanvasWorkpadSharingData, getPdfJobParams } from './utils'; @@ -59,8 +59,6 @@ export interface Props { /** Canvas workpad to export as PDF **/ sharingData: CanvasWorkpadSharingData; sharingServices: { - /** BasePath dependency **/ - basePath: IBasePath; /** Reporting dependency **/ reporting?: ReportingStart; }; @@ -76,6 +74,7 @@ export const ShareMenu: FunctionComponent = ({ sharingServices: services, onExport, }) => { + const platformService = usePlatformService(); const [showFlyout, setShowFlyout] = useState(false); const onClose = () => { @@ -102,7 +101,9 @@ export const ShareMenu: FunctionComponent = ({ title: strings.getShareDownloadPDFTitle(), content: ( getPdfJobParams(sharingData, services.basePath)} + getJobParams={() => + getPdfJobParams(sharingData, platformService.getBasePathInterface()) + } layoutOption="canvas" onClose={closePopover} /> diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/share_menu.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/share_menu.ts index ef13655b66aca..f514f813599b6 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/share_menu.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/share_menu.ts @@ -41,12 +41,11 @@ export const ShareMenu = compose( withProps( ({ workpad, pageCount, services }: Props & WithServicesProps): ComponentProps => { const { - platform, reporting: { start: reporting }, } = services; return { - sharingServices: { basePath: platform.getBasePathInterface(), reporting }, + sharingServices: { reporting }, sharingData: { workpad, pageCount }, onExport: (type) => { switch (type) { diff --git a/x-pack/plugins/canvas/public/lib/custom_element_service.ts b/x-pack/plugins/canvas/public/lib/custom_element_service.ts index aa3229456ebf6..6da624bb5d3ae 100644 --- a/x-pack/plugins/canvas/public/lib/custom_element_service.ts +++ b/x-pack/plugins/canvas/public/lib/custom_element_service.ts @@ -9,10 +9,10 @@ import { AxiosPromise } from 'axios'; import { API_ROUTE_CUSTOM_ELEMENT } from '../../common/lib/constants'; import { fetch } from '../../common/lib/fetch'; import { CustomElement } from '../../types'; -import { platformService } from '../services'; +import { pluginServices } from '../services'; const getApiPath = function () { - const basePath = platformService.getService().getBasePath(); + const basePath = pluginServices.getServices().platform.getBasePath(); return `${basePath}${API_ROUTE_CUSTOM_ELEMENT}`; }; diff --git a/x-pack/plugins/canvas/public/lib/es_service.ts b/x-pack/plugins/canvas/public/lib/es_service.ts index c1a4a17970ffa..0ff6c9e5d110f 100644 --- a/x-pack/plugins/canvas/public/lib/es_service.ts +++ b/x-pack/plugins/canvas/public/lib/es_service.ts @@ -6,28 +6,29 @@ */ // TODO - clint: convert to service abstraction - import { IndexPatternAttributes } from 'src/plugins/data/public'; import { API_ROUTE } from '../../common/lib/constants'; import { fetch } from '../../common/lib/fetch'; import { ErrorStrings } from '../../i18n'; import { pluginServices } from '../services'; -import { platformService } from '../services'; const { esService: strings } = ErrorStrings; const getApiPath = function () { - const basePath = platformService.getService().getBasePath(); + const platformService = pluginServices.getServices().platform; + const basePath = platformService.getBasePath(); return basePath + API_ROUTE; }; const getSavedObjectsClient = function () { - return platformService.getService().getSavedObjectsClient(); + const platformService = pluginServices.getServices().platform; + return platformService.getSavedObjectsClient(); }; const getAdvancedSettings = function () { - return platformService.getService().getUISettings(); + const platformService = pluginServices.getServices().platform; + return platformService.getUISettings(); }; export const getFields = (index = '_all') => { diff --git a/x-pack/plugins/canvas/public/lib/fullscreen.js b/x-pack/plugins/canvas/public/lib/fullscreen.js index f3f6e029696ea..fd4e0b65785b9 100644 --- a/x-pack/plugins/canvas/public/lib/fullscreen.js +++ b/x-pack/plugins/canvas/public/lib/fullscreen.js @@ -5,21 +5,22 @@ * 2.0. */ -import { platformService } from '../services'; +import { pluginServices } from '../services'; export const fullscreenClass = 'canvas-isFullscreen'; export function setFullscreen(fullscreen, doc = document) { + const platformService = pluginServices.getServices().platform; const enabled = Boolean(fullscreen); const body = doc.querySelector('body'); const bodyClassList = body.classList; const isFullscreen = bodyClassList.contains(fullscreenClass); if (enabled && !isFullscreen) { - platformService.getService().setFullscreen(false); + platformService.setFullscreen(false); bodyClassList.add(fullscreenClass); } else if (!enabled && isFullscreen) { bodyClassList.remove(fullscreenClass); - platformService.getService().setFullscreen(true); + platformService.setFullscreen(true); } } diff --git a/x-pack/plugins/canvas/public/lib/run_interpreter.ts b/x-pack/plugins/canvas/public/lib/run_interpreter.ts index 149e90a8f6b73..d69f89566cfc9 100644 --- a/x-pack/plugins/canvas/public/lib/run_interpreter.ts +++ b/x-pack/plugins/canvas/public/lib/run_interpreter.ts @@ -6,6 +6,7 @@ */ import { fromExpression, getType } from '@kbn/interpreter/common'; +import { pluck } from 'rxjs/operators'; import { ExpressionValue, ExpressionAstExpression } from 'src/plugins/expressions/public'; import { pluginServices, expressionsService } from '../services'; @@ -21,7 +22,12 @@ export async function interpretAst( variables: Record ): Promise { const context = { variables }; - return await expressionsService.getService().execute(ast, null, context).getData(); + return await expressionsService + .getService() + .execute(ast, null, context) + .getData() + .pipe(pluck('result')) + .toPromise(); } /** @@ -43,7 +49,12 @@ export async function runInterpreter( const context = { variables }; try { - const renderable = await expressionsService.getService().execute(ast, input, context).getData(); + const renderable = await expressionsService + .getService() + .execute(ast, input, context) + .getData() + .pipe(pluck('result')) + .toPromise(); if (getType(renderable) === 'render') { return renderable; diff --git a/x-pack/plugins/canvas/public/lib/template_service.ts b/x-pack/plugins/canvas/public/lib/template_service.ts index 6a262d57672e4..d5ec467f18740 100644 --- a/x-pack/plugins/canvas/public/lib/template_service.ts +++ b/x-pack/plugins/canvas/public/lib/template_service.ts @@ -5,13 +5,16 @@ * 2.0. */ +// TODO - clint: convert to service abstraction + import { API_ROUTE_TEMPLATES } from '../../common/lib/constants'; import { fetch } from '../../common/lib/fetch'; -import { platformService } from '../services'; +import { pluginServices } from '../services'; import { CanvasTemplate } from '../../types'; const getApiPath = function () { - const basePath = platformService.getService().getBasePath(); + const platformService = pluginServices.getServices().platform; + const basePath = platformService.getBasePath(); return `${basePath}${API_ROUTE_TEMPLATES}`; }; @@ -21,6 +24,5 @@ interface ListResponse { export async function list() { const templateResponse = await fetch.get(`${getApiPath()}`); - return templateResponse.data.templates; } diff --git a/x-pack/plugins/canvas/public/lib/workpad_service.js b/x-pack/plugins/canvas/public/lib/workpad_service.js index 70aa1c3f1f816..20ad82860f1fa 100644 --- a/x-pack/plugins/canvas/public/lib/workpad_service.js +++ b/x-pack/plugins/canvas/public/lib/workpad_service.js @@ -5,6 +5,7 @@ * 2.0. */ +// TODO: clint - move to workpad service. import { API_ROUTE_WORKPAD, API_ROUTE_WORKPAD_ASSETS, @@ -12,7 +13,7 @@ import { DEFAULT_WORKPAD_CSS, } from '../../common/lib/constants'; import { fetch } from '../../common/lib/fetch'; -import { platformService } from '../services'; +import { pluginServices } from '../services'; /* Remove any top level keys from the workpad which will be rejected by validation @@ -46,17 +47,20 @@ const sanitizeWorkpad = function (workpad) { }; const getApiPath = function () { - const basePath = platformService.getService().getBasePath(); + const platformService = pluginServices.getServices().platform; + const basePath = platformService.getBasePath(); return `${basePath}${API_ROUTE_WORKPAD}`; }; const getApiPathStructures = function () { - const basePath = platformService.getService().getBasePath(); + const platformService = pluginServices.getServices().platform; + const basePath = platformService.getBasePath(); return `${basePath}${API_ROUTE_WORKPAD_STRUCTURES}`; }; const getApiPathAssets = function () { - const basePath = platformService.getService().getBasePath(); + const platformService = pluginServices.getServices().platform; + const basePath = platformService.getBasePath(); return `${basePath}${API_ROUTE_WORKPAD_ASSETS}`; }; diff --git a/x-pack/plugins/canvas/public/routes/workpad/hooks/use_fullscreen_presentation_helper.ts b/x-pack/plugins/canvas/public/routes/workpad/hooks/use_fullscreen_presentation_helper.ts index ab26625038bc5..9021c6d6c2753 100644 --- a/x-pack/plugins/canvas/public/routes/workpad/hooks/use_fullscreen_presentation_helper.ts +++ b/x-pack/plugins/canvas/public/routes/workpad/hooks/use_fullscreen_presentation_helper.ts @@ -5,15 +5,14 @@ * 2.0. */ import { useContext, useEffect } from 'react'; -import { useServices } from '../../../services'; +import { usePlatformService } from '../../../services'; import { WorkpadRoutingContext } from '..'; const fullscreenClass = 'canvas-isFullscreen'; export const useFullscreenPresentationHelper = () => { const { isFullscreen } = useContext(WorkpadRoutingContext); - const services = useServices(); - const { setFullscreen } = services.platform; + const { setFullscreen } = usePlatformService(); useEffect(() => { const body = document.querySelector('body'); diff --git a/x-pack/plugins/canvas/public/routes/workpad/workpad_presentation_helper.tsx b/x-pack/plugins/canvas/public/routes/workpad/workpad_presentation_helper.tsx index ccb38cd1a1e0f..bdf84de7a47bd 100644 --- a/x-pack/plugins/canvas/public/routes/workpad/workpad_presentation_helper.tsx +++ b/x-pack/plugins/canvas/public/routes/workpad/workpad_presentation_helper.tsx @@ -14,21 +14,21 @@ import { getWorkpad } from '../../state/selectors/workpad'; import { useFullscreenPresentationHelper } from './hooks/use_fullscreen_presentation_helper'; import { useAutoplayHelper } from './hooks/use_autoplay_helper'; import { useRefreshHelper } from './hooks/use_refresh_helper'; -import { useServices } from '../../services'; +import { usePlatformService } from '../../services'; export const WorkpadPresentationHelper: FC = ({ children }) => { - const services = useServices(); + const platformService = usePlatformService(); const workpad = useSelector(getWorkpad); useFullscreenPresentationHelper(); useAutoplayHelper(); useRefreshHelper(); useEffect(() => { - services.platform.setBreadcrumbs([ + platformService.setBreadcrumbs([ getBaseBreadcrumb(), getWorkpadBreadcrumb({ name: workpad.name }), ]); - }, [workpad.name, workpad.id, services.platform]); + }, [workpad.name, workpad.id, platformService]); useEffect(() => { setDocTitle(workpad.name); diff --git a/x-pack/plugins/canvas/public/services/index.ts b/x-pack/plugins/canvas/public/services/index.ts index 83a54a8a673a1..0aaef4ef280f0 100644 --- a/x-pack/plugins/canvas/public/services/index.ts +++ b/x-pack/plugins/canvas/public/services/index.ts @@ -10,13 +10,16 @@ export * from './legacy'; import { PluginServices } from '../../../../../src/plugins/presentation_util/public'; import { CanvasWorkpadService } from './workpad'; import { CanvasNotifyService } from './notify'; +import { CanvasPlatformService } from './platform'; export interface CanvasPluginServices { workpad: CanvasWorkpadService; notify: CanvasNotifyService; + platform: CanvasPlatformService; } export const pluginServices = new PluginServices(); export const useWorkpadService = () => (() => pluginServices.getHooks().workpad.useService())(); export const useNotifyService = () => (() => pluginServices.getHooks().notify.useService())(); +export const usePlatformService = () => (() => pluginServices.getHooks().platform.useService())(); diff --git a/x-pack/plugins/canvas/public/services/kibana/index.ts b/x-pack/plugins/canvas/public/services/kibana/index.ts index 7bb2be3f77e27..bb0095a3c525c 100644 --- a/x-pack/plugins/canvas/public/services/kibana/index.ts +++ b/x-pack/plugins/canvas/public/services/kibana/index.ts @@ -14,11 +14,13 @@ import { import { workpadServiceFactory } from './workpad'; import { notifyServiceFactory } from './notify'; +import { platformServiceFactory } from './platform'; import { CanvasPluginServices } from '..'; import { CanvasStartDeps } from '../../plugin'; export { workpadServiceFactory } from './workpad'; export { notifyServiceFactory } from './notify'; +export { platformServiceFactory } from './platform'; export const pluginServiceProviders: PluginServiceProviders< CanvasPluginServices, @@ -26,6 +28,7 @@ export const pluginServiceProviders: PluginServiceProviders< > = { workpad: new PluginServiceProvider(workpadServiceFactory), notify: new PluginServiceProvider(notifyServiceFactory), + platform: new PluginServiceProvider(platformServiceFactory), }; export const pluginServiceRegistry = new PluginServiceRegistry< diff --git a/x-pack/plugins/canvas/public/services/legacy/platform.ts b/x-pack/plugins/canvas/public/services/kibana/platform.ts similarity index 54% rename from x-pack/plugins/canvas/public/services/legacy/platform.ts rename to x-pack/plugins/canvas/public/services/kibana/platform.ts index b867622f5d302..79eae8d8081bb 100644 --- a/x-pack/plugins/canvas/public/services/legacy/platform.ts +++ b/x-pack/plugins/canvas/public/services/kibana/platform.ts @@ -5,38 +5,17 @@ * 2.0. */ -import { - SavedObjectsStart, - SavedObjectsClientContract, - IUiSettingsClient, - ChromeBreadcrumb, - IBasePath, - ChromeStart, -} from '../../../../../../src/core/public'; -import { CanvasServiceFactory } from '.'; +import { KibanaPluginServiceFactory } from '../../../../../../src/plugins/presentation_util/public'; -export interface PlatformService { - getBasePath: () => string; - getBasePathInterface: () => IBasePath; - getDocLinkVersion: () => string; - getElasticWebsiteUrl: () => string; - getHasWriteAccess: () => boolean; - getUISetting: (key: string, defaultValue?: any) => any; - setBreadcrumbs: (newBreadcrumbs: ChromeBreadcrumb[]) => void; - setRecentlyAccessed: (link: string, label: string, id: string) => void; - setFullscreen: ChromeStart['setIsVisible']; +import { CanvasStartDeps } from '../../plugin'; +import { CanvasPlatformService } from '../platform'; - // TODO: these should go away. We want thin accessors, not entire objects. - // Entire objects are hard to mock, and hide our dependency on the external service. - getSavedObjects: () => SavedObjectsStart; - getSavedObjectsClient: () => SavedObjectsClientContract; - getUISettings: () => IUiSettingsClient; -} +export type CanvaPlatformServiceFactory = KibanaPluginServiceFactory< + CanvasPlatformService, + CanvasStartDeps +>; -export const platformServiceFactory: CanvasServiceFactory = ( - _coreSetup, - coreStart -) => { +export const platformServiceFactory: CanvaPlatformServiceFactory = ({ coreStart }) => { return { getBasePath: coreStart.http.basePath.get, getBasePathInterface: () => coreStart.http.basePath, diff --git a/x-pack/plugins/canvas/public/services/legacy/context.tsx b/x-pack/plugins/canvas/public/services/legacy/context.tsx index dd2e45740f041..2f472afd7d3c1 100644 --- a/x-pack/plugins/canvas/public/services/legacy/context.tsx +++ b/x-pack/plugins/canvas/public/services/legacy/context.tsx @@ -22,7 +22,6 @@ export interface WithServicesProps { const defaultContextValue = { embeddables: {}, expressions: {}, - platform: {}, navLink: {}, search: {}, }; @@ -30,7 +29,6 @@ const defaultContextValue = { const context = createContext(defaultContextValue as CanvasServices); export const useServices = () => useContext(context); -export const usePlatformService = () => useServices().platform; export const useEmbeddablesService = () => useServices().embeddables; export const useExpressionsService = () => useServices().expressions; export const useNavLinkService = () => useServices().navLink; @@ -50,7 +48,6 @@ export const LegacyServicesProvider: FC<{ const value = { embeddables: specifiedProviders.embeddables.getService(), expressions: specifiedProviders.expressions.getService(), - platform: specifiedProviders.platform.getService(), navLink: specifiedProviders.navLink.getService(), search: specifiedProviders.search.getService(), reporting: specifiedProviders.reporting.getService(), diff --git a/x-pack/plugins/canvas/public/services/legacy/index.ts b/x-pack/plugins/canvas/public/services/legacy/index.ts index 763fd657ad800..01f252c8eb0d6 100644 --- a/x-pack/plugins/canvas/public/services/legacy/index.ts +++ b/x-pack/plugins/canvas/public/services/legacy/index.ts @@ -8,7 +8,6 @@ import { BehaviorSubject } from 'rxjs'; import { CoreSetup, CoreStart, AppUpdater } from '../../../../../../src/core/public'; import { CanvasSetupDeps, CanvasStartDeps } from '../../plugin'; -import { platformServiceFactory } from './platform'; import { navLinkServiceFactory } from './nav_link'; import { embeddablesServiceFactory } from './embeddables'; import { expressionsServiceFactory } from './expressions'; @@ -17,7 +16,6 @@ import { labsServiceFactory } from './labs'; import { reportingServiceFactory } from './reporting'; export { SearchService } from './search'; -export { PlatformService } from './platform'; export { NavLinkService } from './nav_link'; export { EmbeddablesService } from './embeddables'; export { ExpressionsService } from '../../../../../../src/plugins/expressions/common'; @@ -77,7 +75,6 @@ export type ServiceFromProvider

= P extends CanvasServiceProvider ? export const services = { embeddables: new CanvasServiceProvider(embeddablesServiceFactory), expressions: new CanvasServiceProvider(expressionsServiceFactory), - platform: new CanvasServiceProvider(platformServiceFactory), navLink: new CanvasServiceProvider(navLinkServiceFactory), search: new CanvasServiceProvider(searchServiceFactory), reporting: new CanvasServiceProvider(reportingServiceFactory), @@ -89,7 +86,6 @@ export type CanvasServiceProviders = typeof services; export interface CanvasServices { embeddables: ServiceFromProvider; expressions: ServiceFromProvider; - platform: ServiceFromProvider; navLink: ServiceFromProvider; search: ServiceFromProvider; reporting: ServiceFromProvider; @@ -116,7 +112,6 @@ export const stopServices = () => { export const { embeddables: embeddableService, - platform: platformService, navLink: navLinkService, expressions: expressionsService, search: searchService, diff --git a/x-pack/plugins/canvas/public/services/legacy/stubs/index.ts b/x-pack/plugins/canvas/public/services/legacy/stubs/index.ts index cebefdd7682cc..9857e27d8a3cf 100644 --- a/x-pack/plugins/canvas/public/services/legacy/stubs/index.ts +++ b/x-pack/plugins/canvas/public/services/legacy/stubs/index.ts @@ -11,7 +11,6 @@ import { expressionsService } from './expressions'; import { reportingService } from './reporting'; import { navLinkService } from './nav_link'; import { labsService } from './labs'; -import { platformService } from './platform'; import { searchService } from './search'; export const stubs: CanvasServices = { @@ -19,7 +18,6 @@ export const stubs: CanvasServices = { expressions: expressionsService, reporting: reportingService, navLink: navLinkService, - platform: platformService, search: searchService, labs: labsService, }; diff --git a/x-pack/plugins/canvas/public/services/platform.ts b/x-pack/plugins/canvas/public/services/platform.ts new file mode 100644 index 0000000000000..7a452d809a614 --- /dev/null +++ b/x-pack/plugins/canvas/public/services/platform.ts @@ -0,0 +1,33 @@ +/* + * 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 { + SavedObjectsStart, + SavedObjectsClientContract, + IUiSettingsClient, + ChromeBreadcrumb, + IBasePath, + ChromeStart, +} from '../../../../../src/core/public'; + +export interface CanvasPlatformService { + getBasePath: () => string; + getBasePathInterface: () => IBasePath; + getDocLinkVersion: () => string; + getElasticWebsiteUrl: () => string; + getHasWriteAccess: () => boolean; + getUISetting: (key: string, defaultValue?: any) => any; + setBreadcrumbs: (newBreadcrumbs: ChromeBreadcrumb[]) => void; + setRecentlyAccessed: (link: string, label: string, id: string) => void; + setFullscreen: ChromeStart['setIsVisible']; + + // TODO: these should go away. We want thin accessors, not entire objects. + // Entire objects are hard to mock, and hide our dependency on the external service. + getSavedObjects: () => SavedObjectsStart; + getSavedObjectsClient: () => SavedObjectsClientContract; + getUISettings: () => IUiSettingsClient; +} diff --git a/x-pack/plugins/canvas/public/services/stubs/index.ts b/x-pack/plugins/canvas/public/services/stubs/index.ts index 5c3440cc4cdbc..1aa05647f7e9e 100644 --- a/x-pack/plugins/canvas/public/services/stubs/index.ts +++ b/x-pack/plugins/canvas/public/services/stubs/index.ts @@ -16,13 +16,16 @@ import { import { CanvasPluginServices } from '..'; import { workpadServiceFactory } from './workpad'; import { notifyServiceFactory } from './notify'; +import { platformServiceFactory } from './platform'; export { workpadServiceFactory } from './workpad'; export { notifyServiceFactory } from './notify'; +export { platformServiceFactory } from './platform'; export const pluginServiceProviders: PluginServiceProviders = { workpad: new PluginServiceProvider(workpadServiceFactory), notify: new PluginServiceProvider(notifyServiceFactory), + platform: new PluginServiceProvider(platformServiceFactory), }; export const pluginServiceRegistry = new PluginServiceRegistry( diff --git a/x-pack/plugins/canvas/public/services/legacy/stubs/platform.ts b/x-pack/plugins/canvas/public/services/stubs/platform.ts similarity index 72% rename from x-pack/plugins/canvas/public/services/legacy/stubs/platform.ts rename to x-pack/plugins/canvas/public/services/stubs/platform.ts index 5776a1d0d6983..181d355df8a1c 100644 --- a/x-pack/plugins/canvas/public/services/legacy/stubs/platform.ts +++ b/x-pack/plugins/canvas/public/services/stubs/platform.ts @@ -5,7 +5,11 @@ * 2.0. */ -import { PlatformService } from '../platform'; +import { PluginServiceFactory } from '../../../../../../src/plugins/presentation_util/public'; + +import { CanvasPlatformService } from '../platform'; + +type CanvasPlatformServiceFactory = PluginServiceFactory; const noop = (..._args: any[]): any => {}; @@ -15,7 +19,7 @@ const uiSettings: Record = { const getUISetting = (setting: string) => uiSettings[setting]; -export const platformService: PlatformService = { +export const platformServiceFactory: CanvasPlatformServiceFactory = () => ({ getBasePath: () => '/base/path', getBasePathInterface: noop, getDocLinkVersion: () => 'dockLinkVersion', @@ -28,4 +32,4 @@ export const platformService: PlatformService = { getSavedObjectsClient: noop, getUISettings: noop, setFullscreen: noop, -}; +}); diff --git a/x-pack/plugins/canvas/public/state/initial_state.js b/x-pack/plugins/canvas/public/state/initial_state.js index e4909bdb95081..c652cc573abe9 100644 --- a/x-pack/plugins/canvas/public/state/initial_state.js +++ b/x-pack/plugins/canvas/public/state/initial_state.js @@ -6,11 +6,12 @@ */ import { get } from 'lodash'; -import { platformService } from '../services'; +import { pluginServices } from '../services'; import { getDefaultWorkpad } from './defaults'; export const getInitialState = (path) => { - const { getHasWriteAccess } = platformService.getService(); + const platformService = pluginServices.getServices().platform; + const { getHasWriteAccess } = platformService; const state = { app: {}, // Kibana stuff in here diff --git a/x-pack/plugins/canvas/public/state/reducers/workpad.js b/x-pack/plugins/canvas/public/state/reducers/workpad.js index acd371e9490fb..ebde0106f9c01 100644 --- a/x-pack/plugins/canvas/public/state/reducers/workpad.js +++ b/x-pack/plugins/canvas/public/state/reducers/workpad.js @@ -6,7 +6,7 @@ */ import { handleActions } from 'redux-actions'; -import { platformService } from '../../services'; +import { pluginServices } from '../../services'; import { getDefaultWorkpad } from '../defaults'; import { setWorkpad, @@ -24,9 +24,13 @@ import { APP_ROUTE_WORKPAD } from '../../../common/lib/constants'; export const workpadReducer = handleActions( { [setWorkpad]: (workpadState, { payload }) => { - platformService - .getService() - .setRecentlyAccessed(`${APP_ROUTE_WORKPAD}/${payload.id}`, payload.name, payload.id); + pluginServices + .getServices() + .platform.setRecentlyAccessed( + `${APP_ROUTE_WORKPAD}/${payload.id}`, + payload.name, + payload.id + ); return payload; }, @@ -39,9 +43,13 @@ export const workpadReducer = handleActions( }, [setName]: (workpadState, { payload }) => { - platformService - .getService() - .setRecentlyAccessed(`${APP_ROUTE_WORKPAD}/${workpadState.id}`, payload, workpadState.id); + pluginServices + .getServices() + .platform.setRecentlyAccessed( + `${APP_ROUTE_WORKPAD}/${workpadState.id}`, + payload, + workpadState.id + ); return { ...workpadState, name: payload }; }, diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/handle_api_errors.ts b/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/handle_api_errors.ts index 11003d0fcc171..1b5dab0839663 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/handle_api_errors.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/handle_api_errors.ts @@ -5,6 +5,8 @@ * 2.0. */ +import { i18n } from '@kbn/i18n'; + import { HttpResponse } from 'src/core/public'; import { FlashMessagesLogic } from './flash_messages_logic'; @@ -31,12 +33,17 @@ interface Options { isQueued?: boolean; } +export const defaultErrorMessage = i18n.translate( + 'xpack.enterpriseSearch.shared.flashMessages.defaultErrorMessage', + { + defaultMessage: 'An unexpected error occurred', + } +); + /** * Converts API/HTTP errors into user-facing Flash Messages */ export const flashAPIErrors = (error: HttpResponse, { isQueued }: Options = {}) => { - const defaultErrorMessage = 'An unexpected error occurred'; - const errorFlashMessages: IFlashMessage[] = Array.isArray(error?.body?.attributes?.errors) ? error.body!.attributes.errors.map((message) => ({ type: 'error', message })) : [{ type: 'error', message: error?.body?.message || defaultErrorMessage }]; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts index fd1a574b3438f..3e8322145dad6 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts @@ -27,6 +27,7 @@ const spyScrollTo = jest.fn(); Object.defineProperty(global.window, 'scrollTo', { value: spyScrollTo }); import { ADD, UPDATE } from '../../../../../shared/constants/operations'; +import { defaultErrorMessage } from '../../../../../shared/flash_messages/handle_api_errors'; import { SchemaType } from '../../../../../shared/schema/types'; import { AppLogic } from '../../../../app_logic'; @@ -390,13 +391,25 @@ describe('SchemaLogic', () => { expect(onSchemaSetSuccessSpy).toHaveBeenCalledWith(serverResponse); }); - it('handles error', async () => { + it('handles error with message', async () => { + const onSchemaSetFormErrorsSpy = jest.spyOn(SchemaLogic.actions, 'onSchemaSetFormErrors'); + // We expect body.message to be a string[] when it is present + http.post.mockReturnValue(Promise.reject({ body: { message: ['this is an error'] } })); + SchemaLogic.actions.setServerField(schema, ADD); + await nextTick(); + + expect(onSchemaSetFormErrorsSpy).toHaveBeenCalledWith(['this is an error']); + expect(spyScrollTo).toHaveBeenCalledWith(0, 0); + }); + + it('handles error with no message', async () => { const onSchemaSetFormErrorsSpy = jest.spyOn(SchemaLogic.actions, 'onSchemaSetFormErrors'); - http.post.mockReturnValue(Promise.reject({ message: 'this is an error' })); + http.post.mockReturnValue(Promise.reject()); SchemaLogic.actions.setServerField(schema, ADD); await nextTick(); - expect(onSchemaSetFormErrorsSpy).toHaveBeenCalledWith('this is an error'); + expect(onSchemaSetFormErrorsSpy).toHaveBeenCalledWith([defaultErrorMessage]); + expect(spyScrollTo).toHaveBeenCalledWith(0, 0); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts index b2c329f0544fd..7af074d412a60 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts @@ -17,6 +17,7 @@ import { setErrorMessage, clearFlashMessages, } from '../../../../../shared/flash_messages'; +import { defaultErrorMessage } from '../../../../../shared/flash_messages/handle_api_errors'; import { HttpLogic } from '../../../../../shared/http'; import { IndexJob, @@ -349,7 +350,9 @@ export const SchemaLogic = kea>({ } catch (e) { window.scrollTo(0, 0); if (isAdding) { - actions.onSchemaSetFormErrors(e?.message); + // We expect body.message to be a string[] for actions.onSchemaSetFormErrors + const message: string[] = e?.body?.message || [defaultErrorMessage]; + actions.onSchemaSetFormErrors(message); } else { flashAPIErrors(e); } diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx index 1363af573b86d..5075398d2d6b0 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx @@ -425,7 +425,7 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { [params, updatePackageInfo, agentPolicy, updateAgentPolicy, queryParamsPolicyId] ); - const ExtensionView = useUIExtension(packagePolicy.package?.name ?? '', 'package-policy-create'); + const extensionView = useUIExtension(packagePolicy.package?.name ?? '', 'package-policy-create'); const stepConfigurePackagePolicy = useMemo( () => @@ -444,7 +444,7 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { /> {/* Only show the out-of-box configuration step if a UI extension is NOT registered */} - {!ExtensionView && ( + {!extensionView && ( { )} {/* If an Agent Policy and a package has been selected, then show UI extension (if any) */} - {ExtensionView && packagePolicy.policy_id && packagePolicy.package?.name && ( + {extensionView && packagePolicy.policy_id && packagePolicy.package?.name && ( - + )} @@ -474,7 +477,7 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { validationResults, formState, integrationInfo?.name, - ExtensionView, + extensionView, handleExtensionViewOnChange, ] ); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx index fb3603aaef7f4..b07d76dc6bd8e 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx @@ -338,7 +338,7 @@ export const EditPackagePolicyForm = memo<{ packageInfo, }; - const ExtensionView = useUIExtension(packagePolicy.package?.name ?? '', 'package-policy-edit'); + const extensionView = useUIExtension(packagePolicy.package?.name ?? '', 'package-policy-edit'); const configurePackage = useMemo( () => @@ -354,7 +354,7 @@ export const EditPackagePolicyForm = memo<{ /> {/* Only show the out-of-box configuration step if a UI extension is NOT registered */} - {!ExtensionView && ( + {!extensionView && ( )} - {ExtensionView && + {extensionView && packagePolicy.policy_id && packagePolicy.package?.name && originalPackagePolicy && ( - = { dashboard: 'Dashboard', @@ -36,6 +36,7 @@ export const AssetTitleMap: Record = { lens: 'Lens', security_rule: 'Security Rule', ml_module: 'ML Module', + view: 'Views', }; export const ServiceTitleMap: Record = { diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/assets.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/assets.tsx index e6dce1bc51367..6d075faeef308 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/assets.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/assets.tsx @@ -10,12 +10,17 @@ import { Redirect } from 'react-router-dom'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiFlexGroup, EuiFlexItem, EuiTitle, EuiSpacer } from '@elastic/eui'; -import { Loading, Error } from '../../../../../components'; +import { Loading, Error, ExtensionWrapper } from '../../../../../components'; import type { PackageInfo } from '../../../../../types'; import { InstallStatus } from '../../../../../types'; -import { useGetPackageInstallStatus, useLink, useStartServices } from '../../../../../hooks'; +import { + useGetPackageInstallStatus, + useLink, + useStartServices, + useUIExtension, +} from '../../../../../hooks'; import type { AssetSavedObject } from './types'; import { allowedAssetTypes } from './constants'; @@ -27,9 +32,12 @@ interface AssetsPanelProps { export const AssetsPage = ({ packageInfo }: AssetsPanelProps) => { const { name, version } = packageInfo; + const pkgkey = `${name}-${version}`; + const { savedObjects: { client: savedObjectsClient }, } = useStartServices(); + const customAssetsExtension = useUIExtension(packageInfo.name, 'package-detail-assets'); const { getPath } = useLink(); const getPackageInstallStatus = useGetPackageInstallStatus(); @@ -76,13 +84,7 @@ export const AssetsPage = ({ packageInfo }: AssetsPanelProps) => { // if they arrive at this page and the package is not installed, send them to overview // this happens if they arrive with a direct url or they uninstall while on this tab if (packageInstallStatus.status !== InstallStatus.installed) { - return ( - - ); + return ; } let content: JSX.Element | Array; @@ -102,31 +104,49 @@ export const AssetsPage = ({ packageInfo }: AssetsPanelProps) => { /> ); } else if (assetSavedObjects === undefined) { - content = ( - -

- -

- - ); + if (customAssetsExtension) { + // If a UI extension for custom asset entries is defined, render the custom component here depisite + // there being no saved objects found + content = ( + + + + ); + } else { + content = ( + +

+ +

+
+ ); + } } else { - content = allowedAssetTypes.map((assetType) => { - const sectionAssetSavedObjects = assetSavedObjects.filter((so) => so.type === assetType); + content = [ + ...allowedAssetTypes.map((assetType) => { + const sectionAssetSavedObjects = assetSavedObjects.filter((so) => so.type === assetType); - if (!sectionAssetSavedObjects.length) { - return null; - } + if (!sectionAssetSavedObjects.length) { + return null; + } - return ( - <> - - - - ); - }); + return ( + <> + + + + ); + }), + // Ensure we add any custom assets provided via UI extension to the end of the list of other assets + customAssetsExtension ? ( + + + + ) : null, + ]; } return ( diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/assets_accordion.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/assets_accordion.tsx index 12d4a0014b976..91c6b68c66221 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/assets_accordion.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/assets_accordion.tsx @@ -55,6 +55,11 @@ export const AssetsAccordion: FunctionComponent = ({ savedObjects, type } {savedObjects.map(({ id, attributes: { title, description } }, idx) => { + // Ignore custom asset views + if (type === 'view') { + return; + } + const pathToObjectInApp = getHrefToObjectInKibanaApp({ http, id, diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/types.ts b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/types.ts index 21efd1cd562e8..26a6729be3623 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/types.ts +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/assets/types.ts @@ -17,4 +17,4 @@ export type AllowedAssetTypes = [ KibanaAssetType.visualization ]; -export type AllowedAssetType = AllowedAssetTypes[number]; +export type AllowedAssetType = AllowedAssetTypes[number] | 'view'; diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/custom/custom.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/custom/custom.tsx index ef8d21236c670..b59804cea1733 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/custom/custom.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/custom/custom.tsx @@ -18,16 +18,16 @@ interface Props { } export const CustomViewPage: React.FC = memo(({ packageInfo }) => { - const CustomView = useUIExtension(packageInfo.name, 'package-detail-custom'); + const customViewExtension = useUIExtension(packageInfo.name, 'package-detail-custom'); const { getPath } = useLink(); const pkgkey = useMemo(() => pkgKeyFromPackageInfo(packageInfo), [packageInfo]); - return CustomView ? ( + return customViewExtension ? ( - + diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.test.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.test.tsx index 04253994d3875..f436c248abd3c 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.test.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.test.tsx @@ -113,7 +113,7 @@ describe('when on integration detail', () => { }); }); - describe('and a custom UI extension is registered', () => { + describe('and a custom tab UI extension is registered', () => { // Because React Lazy components are loaded async (Promise), we setup this "watcher" Promise // that is `resolved` once the lazy components actually renders. let lazyComponentWasRendered: Promise; @@ -136,7 +136,7 @@ describe('when on integration detail', () => { testRenderer.startInterface.registerExtension({ package: 'nginx', view: 'package-detail-custom', - component: CustomComponent, + Component: CustomComponent, }); render(); @@ -162,6 +162,53 @@ describe('when on integration detail', () => { }); }); + describe('and a custom assets UI extension is registered', () => { + let lazyComponentWasRendered: Promise; + + beforeEach(() => { + let setWasRendered: () => void; + lazyComponentWasRendered = new Promise((resolve) => { + setWasRendered = resolve; + }); + + const CustomComponent = lazy(async () => { + return { + default: memo(() => { + setWasRendered(); + return
hello
; + }), + }; + }); + + testRenderer.startInterface.registerExtension({ + package: 'nginx', + view: 'package-detail-assets', + Component: CustomComponent, + }); + + render(); + }); + + afterEach(() => { + // @ts-ignore + lazyComponentWasRendered = undefined; + }); + + it('should display "assets" tab in navigation', () => { + expect(renderResult.getByTestId('tab-assets')); + }); + + it('should display custom assets when tab is clicked', async () => { + act(() => { + testRenderer.history.push( + pagePathGetters.integration_details_assets({ pkgkey: 'nginx-0.3.7' })[1] + ); + }); + await lazyComponentWasRendered; + expect(renderResult.getByTestId('custom-hello')); + }); + }); + describe('and the Add integration button is clicked', () => { beforeEach(() => render()); diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx index 2102c5055503b..21a139ad11baa 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx @@ -101,6 +101,8 @@ export function Detail() { const setPackageInstallStatus = useSetPackageInstallStatus(); const getPackageInstallStatus = useGetPackageInstallStatus(); + const CustomAssets = useUIExtension(packageInfo?.name ?? '', 'package-detail-assets'); + const packageInstallStatus = useMemo(() => { if (packageInfo === null || !packageInfo.name) { return undefined; @@ -418,7 +420,7 @@ export function Detail() { }); } - if (packageInstallStatus === InstallStatus.installed && packageInfo.assets) { + if (packageInstallStatus === InstallStatus.installed && (packageInfo.assets || CustomAssets)) { tabs.push({ id: 'assets', name: ( @@ -471,7 +473,7 @@ export function Detail() { } return tabs; - }, [packageInfo, panel, getHref, integration, packageInstallStatus, showCustomTab]); + }, [packageInfo, panel, getHref, integration, packageInstallStatus, showCustomTab, CustomAssets]); return ( ) => { setPagination({ @@ -98,35 +105,46 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps [setPagination] ); - const renderViewDataStepContent = useCallback( - () => ( - <> - - - {i18n.translate( - 'xpack.fleet.epm.agentEnrollment.viewDataDescription.pleaseNoteLabel', - { defaultMessage: 'Please note' } - )} - - ), - }} - /> - - - - {i18n.translate('xpack.fleet.epm.agentEnrollment.viewDataAssetsLabel', { - defaultMessage: 'View assets', - })} - - - ), - [name, version, getHref] - ); + const viewDataStep = useMemo(() => { + if (agentEnrollmentFlyoutExtension) { + return { + title: agentEnrollmentFlyoutExtension.title, + children: , + }; + } + + return { + title: i18n.translate('xpack.fleet.agentEnrollment.stepViewDataTitle', { + defaultMessage: 'View your data', + }), + children: ( + <> + + + {i18n.translate( + 'xpack.fleet.epm.agentEnrollment.viewDataDescription.pleaseNoteLabel', + { defaultMessage: 'Please note' } + )} + + ), + }} + /> + + + + {i18n.translate('xpack.fleet.epm.agentEnrollment.viewDataAssetsLabel', { + defaultMessage: 'View assets', + })} + + + ), + }; + }, [name, version, getHref, agentEnrollmentFlyoutExtension]); const columns: Array> = useMemo( () => [ @@ -230,13 +248,13 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps ); }, }, ], - [renderViewDataStepContent] + [viewDataStep] ); const noItemsMessage = useMemo(() => { @@ -292,7 +310,7 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps data?.items.find(({ agentPolicy }) => agentPolicy.id === flyoutOpenForPolicyId) ?.agentPolicy } - viewDataStepContent={renderViewDataStepContent()} + viewDataStep={viewDataStep} /> )} diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/agent_enrollment_flyout.test.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/agent_enrollment_flyout.test.tsx index f6d62d45a4e56..f68b1b878c51c 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/agent_enrollment_flyout.test.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/agent_enrollment_flyout.test.tsx @@ -21,7 +21,7 @@ import { FleetStatusProvider, ConfigContext } from '../../hooks'; import { useFleetServerInstructions } from '../../applications/fleet/sections/agents/agent_requirements_page/components'; -import { AgentEnrollmentKeySelectionStep, AgentPolicySelectionStep, ViewDataStep } from './steps'; +import { AgentEnrollmentKeySelectionStep, AgentPolicySelectionStep } from './steps'; import type { Props } from '.'; import { AgentEnrollmentFlyout } from '.'; @@ -129,24 +129,26 @@ describe('', () => { }); }); - describe('"View data" extension point', () => { - it('calls the "View data" step when UI extension is provided', async () => { + // Skipped due to implementation details in the step components. See https://github.com/elastic/kibana/issues/103894 + describe.skip('"View data" extension point', () => { + it('shows the "View data" step when UI extension is provided', async () => { jest.clearAllMocks(); await act(async () => { testBed = await setup({ agentPolicies: [], onClose: jest.fn(), - viewDataStepContent:
, + viewDataStep: { title: 'View Data', children:
}, }); testBed.component.update(); }); const { exists, actions } = testBed; expect(exists('agentEnrollmentFlyout')).toBe(true); - expect(ViewDataStep).toHaveBeenCalled(); + expect(exists('view-data-step')).toBe(true); jest.clearAllMocks(); actions.goToStandaloneTab(); - expect(ViewDataStep).not.toHaveBeenCalled(); + expect(exists('agentEnrollmentFlyout')).toBe(true); + expect(exists('view-data-step')).toBe(false); }); it('does not call the "View data" step when UI extension is not provided', async () => { @@ -155,17 +157,17 @@ describe('', () => { testBed = await setup({ agentPolicies: [], onClose: jest.fn(), - viewDataStepContent: undefined, + viewDataStep: undefined, }); testBed.component.update(); }); const { exists, actions } = testBed; expect(exists('agentEnrollmentFlyout')).toBe(true); - expect(ViewDataStep).not.toHaveBeenCalled(); + expect(exists('view-data-step')).toBe(false); jest.clearAllMocks(); actions.goToStandaloneTab(); - expect(ViewDataStep).not.toHaveBeenCalled(); + expect(exists('view-data-step')).toBe(false); }); }); }); diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx index 08d78154941e9..9b82b2a80b5e1 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/index.tsx @@ -45,7 +45,7 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ onClose, agentPolicy, agentPolicies, - viewDataStepContent, + viewDataStep, defaultMode = 'managed', }) => { const [mode, setMode] = useState(defaultMode); @@ -119,14 +119,10 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ ) : ( - + )} diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx index c739725b79739..61f86335cd7f9 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/managed_instructions.tsx @@ -23,12 +23,7 @@ import { } from '../../applications/fleet/sections/agents/agent_requirements_page/components'; import { FleetServerRequirementPage } from '../../applications/fleet/sections/agents/agent_requirements_page'; -import { - DownloadStep, - AgentPolicySelectionStep, - AgentEnrollmentKeySelectionStep, - ViewDataStep, -} from './steps'; +import { DownloadStep, AgentPolicySelectionStep, AgentEnrollmentKeySelectionStep } from './steps'; import type { BaseProps } from './types'; type Props = BaseProps; @@ -61,7 +56,7 @@ const FleetServerMissingRequirements = () => { }; export const ManagedInstructions = React.memo( - ({ agentPolicy, agentPolicies, viewDataStepContent }) => { + ({ agentPolicy, agentPolicies, viewDataStep }) => { const fleetStatus = useFleetStatus(); const [selectedApiKeyId, setSelectedAPIKeyId] = useState(); @@ -118,8 +113,8 @@ export const ManagedInstructions = React.memo( }); } - if (viewDataStepContent) { - baseSteps.push(ViewDataStep(viewDataStepContent)); + if (viewDataStep) { + baseSteps.push({ 'data-test-subj': 'view-data-step', ...viewDataStep }); } return baseSteps; @@ -127,12 +122,12 @@ export const ManagedInstructions = React.memo( agentPolicy, selectedApiKeyId, setSelectedAPIKeyId, - viewDataStepContent, agentPolicies, apiKey.data, fleetServerSteps, isFleetServerPolicySelected, settings.data?.item?.fleet_server_hosts, + viewDataStep, ]); return ( diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx index f77cba754e909..8eeb5fac4b0df 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/steps.tsx @@ -144,16 +144,3 @@ export const AgentEnrollmentKeySelectionStep = ({ ), }; }; - -/** - * Send users to assets installed by the package in Kibana so they can - * view their data. - */ -export const ViewDataStep = (content: JSX.Element) => { - return { - title: i18n.translate('xpack.fleet.agentEnrollment.stepViewDataTitle', { - defaultMessage: 'View your data', - }), - children: content, - }; -}; diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/types.ts b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/types.ts index e0c5b040a61fb..9ee514c634655 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/types.ts +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/types.ts @@ -5,6 +5,8 @@ * 2.0. */ +import type { EuiStepProps } from '@elastic/eui'; + import type { AgentPolicy } from '../../types'; export interface BaseProps { @@ -24,5 +26,5 @@ export interface BaseProps { * There is a step in the agent enrollment process that allows users to see the data from an integration represented in the UI * in some way. This is an area for consumers to render a button and text explaining how data can be viewed. */ - viewDataStepContent?: JSX.Element; + viewDataStep?: EuiStepProps; } diff --git a/x-pack/plugins/fleet/public/components/custom_assets_accordion.tsx b/x-pack/plugins/fleet/public/components/custom_assets_accordion.tsx new file mode 100644 index 0000000000000..f4dd3a7deaaab --- /dev/null +++ b/x-pack/plugins/fleet/public/components/custom_assets_accordion.tsx @@ -0,0 +1,86 @@ +/* + * 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 type { FunctionComponent } from 'react'; +import { + EuiAccordion, + EuiFlexGroup, + EuiFlexItem, + EuiText, + EuiNotificationBadge, + EuiSpacer, + EuiSplitPanel, + EuiLink, + EuiHorizontalRule, +} from '@elastic/eui'; + +import { AssetTitleMap } from '../applications/integrations/sections/epm/constants'; +import { useStartServices } from '../hooks'; +import { RedirectAppLinks } from '../../../../../src/plugins/kibana_react/public'; + +export interface CustomAssetsAccordionProps { + views: Array<{ + name: string; + url: string; + description: string; + }>; + initialIsOpen?: boolean; +} + +export const CustomAssetsAccordion: FunctionComponent = ({ + views, + initialIsOpen = false, +}) => { + const { application } = useStartServices(); + + return ( + + + +

{AssetTitleMap.view}

+
+
+ + +

{views.length}

+
+
+ + } + id="custom-assets" + > + <> + + + {views.map((view, index) => ( + <> + + +

+ + {view.name} + +

+
+ + + +

{view.description}

+
+
+ {index + 1 < views.length && } + + ))} +
+ +
+ ); +}; diff --git a/x-pack/plugins/fleet/public/components/package_policy_actions_menu.tsx b/x-pack/plugins/fleet/public/components/package_policy_actions_menu.tsx index 1f64de27fce39..9743135d5f1c1 100644 --- a/x-pack/plugins/fleet/public/components/package_policy_actions_menu.tsx +++ b/x-pack/plugins/fleet/public/components/package_policy_actions_menu.tsx @@ -7,6 +7,7 @@ import React, { useMemo, useState } from 'react'; import { EuiContextMenuItem, EuiPortal } from '@elastic/eui'; +import type { EuiStepProps } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import type { AgentPolicy, PackagePolicy } from '../types'; @@ -21,8 +22,8 @@ import { PackagePolicyDeleteProvider } from './package_policy_delete_provider'; export const PackagePolicyActionsMenu: React.FunctionComponent<{ agentPolicy: AgentPolicy; packagePolicy: PackagePolicy; - viewDataStepContent?: JSX.Element; -}> = ({ agentPolicy, packagePolicy, viewDataStepContent }) => { + viewDataStep?: EuiStepProps; +}> = ({ agentPolicy, packagePolicy, viewDataStep }) => { const [isEnrollmentFlyoutOpen, setIsEnrollmentFlyoutOpen] = useState(false); const { getHref } = useLink(); const hasWriteCapabilities = useCapabilities().write; @@ -106,7 +107,7 @@ export const PackagePolicyActionsMenu: React.FunctionComponent<{ diff --git a/x-pack/plugins/fleet/public/constants/index.ts b/x-pack/plugins/fleet/public/constants/index.ts index a7cc2726eace1..a0e88bc58726a 100644 --- a/x-pack/plugins/fleet/public/constants/index.ts +++ b/x-pack/plugins/fleet/public/constants/index.ts @@ -24,3 +24,5 @@ export { export * from './page_paths'; export const INDEX_NAME = '.kibana'; + +export const CUSTOM_LOGS_INTEGRATION_NAME = 'log'; diff --git a/x-pack/plugins/fleet/public/custom_logs_assets_extension.tsx b/x-pack/plugins/fleet/public/custom_logs_assets_extension.tsx new file mode 100644 index 0000000000000..4090c4520bf2a --- /dev/null +++ b/x-pack/plugins/fleet/public/custom_logs_assets_extension.tsx @@ -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. + */ + +import React from 'react'; +import { i18n } from '@kbn/i18n'; + +import { CustomAssetsAccordion } from './components/custom_assets_accordion'; +import type { CustomAssetsAccordionProps } from './components/custom_assets_accordion'; +import { useStartServices } from './hooks'; +import type { PackageAssetsComponent } from './types'; + +export const CustomLogsAssetsExtension: PackageAssetsComponent = () => { + const { http } = useStartServices(); + const logStreamUrl = http.basePath.prepend('/app/logs/stream'); + + const views: CustomAssetsAccordionProps['views'] = [ + { + name: i18n.translate('xpack.fleet.assets.customLogs.name', { defaultMessage: 'Logs' }), + url: logStreamUrl, + description: i18n.translate('xpack.fleet.assets.customLogs.description', { + defaultMessage: 'View Custom logs data in Logs app', + }), + }, + ]; + + return ; +}; diff --git a/x-pack/plugins/fleet/public/hooks/use_ui_extension.ts b/x-pack/plugins/fleet/public/hooks/use_ui_extension.ts index 3880a08a7ec03..93e316be241cb 100644 --- a/x-pack/plugins/fleet/public/hooks/use_ui_extension.ts +++ b/x-pack/plugins/fleet/public/hooks/use_ui_extension.ts @@ -20,7 +20,7 @@ type NarrowExtensionPoint( packageName: UIExtensionPoint['package'], view: V -): NarrowExtensionPoint['component'] | undefined => { +): NarrowExtensionPoint | undefined => { const registeredExtensions = useContext(UIExtensionsContext); if (!registeredExtensions) { @@ -32,6 +32,6 @@ export const useUIExtension = (async () => { + return { + default: CustomLogsAssetsExtension, + }; +}); diff --git a/x-pack/plugins/fleet/public/plugin.ts b/x-pack/plugins/fleet/public/plugin.ts index c092d5914637c..9b3aefa488f7b 100644 --- a/x-pack/plugins/fleet/public/plugin.ts +++ b/x-pack/plugins/fleet/public/plugin.ts @@ -32,7 +32,7 @@ import type { CheckPermissionsResponse, PostIngestSetupResponse } from '../commo import type { FleetConfigType } from '../common/types'; -import { FLEET_BASE_PATH } from './constants'; +import { CUSTOM_LOGS_INTEGRATION_NAME, FLEET_BASE_PATH } from './constants'; import { licenseService } from './hooks'; import { setHttpClient } from './hooks/use_request'; import { createPackageSearchProvider } from './search_provider'; @@ -43,6 +43,7 @@ import { } from './components/home_integration'; import { createExtensionRegistrationCallback } from './services/ui_extensions'; import type { UIExtensionRegistrationCallback, UIExtensionsStorage } from './types'; +import { LazyCustomLogsAssetsExtension } from './lazy_custom_logs_assets_extension'; export { FleetConfigType } from '../common/types'; @@ -204,6 +205,13 @@ export class FleetPlugin implements Plugin; + const registerExtension = createExtensionRegistrationCallback(this.extensions); + + registerExtension({ + package: CUSTOM_LOGS_INTEGRATION_NAME, + view: 'package-detail-assets', + Component: LazyCustomLogsAssetsExtension, + }); return { isInitialized: () => { @@ -229,8 +237,7 @@ export class FleetPlugin implements Plugin { register({ view: 'package-policy-edit', package: 'endpoint', - component: LazyCustomView, + Component: LazyCustomView, }); expect(storage.endpoint['package-policy-edit']).toEqual({ view: 'package-policy-edit', package: 'endpoint', - component: LazyCustomView, + Component: LazyCustomView, }); }); @@ -57,21 +57,21 @@ describe('UI Extension services', () => { register({ view: 'package-policy-edit', package: 'endpoint', - component: LazyCustomView, + Component: LazyCustomView, }); expect(() => { register({ view: 'package-policy-edit', package: 'endpoint', - component: LazyCustomView2, + Component: LazyCustomView2, }); }).toThrow(); expect(storage.endpoint['package-policy-edit']).toEqual({ view: 'package-policy-edit', package: 'endpoint', - component: LazyCustomView, + Component: LazyCustomView, }); }); }); diff --git a/x-pack/plugins/fleet/public/types/ui_extensions.ts b/x-pack/plugins/fleet/public/types/ui_extensions.ts index c79b676a26b33..bc692fe1caa7d 100644 --- a/x-pack/plugins/fleet/public/types/ui_extensions.ts +++ b/x-pack/plugins/fleet/public/types/ui_extensions.ts @@ -5,6 +5,7 @@ * 2.0. */ +import type { EuiStepProps } from '@elastic/eui'; import type { ComponentType, LazyExoticComponent } from 'react'; import type { NewPackagePolicy, PackageInfo, PackagePolicy } from './index'; @@ -48,7 +49,7 @@ export interface PackagePolicyEditExtensionComponentProps { export interface PackagePolicyEditExtension { package: string; view: 'package-policy-edit'; - component: LazyExoticComponent; + Component: LazyExoticComponent; } /** @@ -76,7 +77,7 @@ export interface PackagePolicyCreateExtensionComponentProps { export interface PackagePolicyCreateExtension { package: string; view: 'package-policy-create'; - component: LazyExoticComponent; + Component: LazyExoticComponent; } /** @@ -94,11 +95,32 @@ export interface PackageCustomExtensionComponentProps { export interface PackageCustomExtension { package: string; view: 'package-detail-custom'; - component: LazyExoticComponent; + Component: LazyExoticComponent; +} + +/** + * UI Component Extension for displaying custom views under the Assets tab for a given Integration + */ +export type PackageAssetsComponent = ComponentType<{}>; + +/** Extension point registration contract for Integration details Assets view */ +export interface PackageAssetsExtension { + package: string; + view: 'package-detail-assets'; + Component: LazyExoticComponent; +} + +export interface AgentEnrollmentFlyoutFinalStepExtension { + package: string; + view: 'agent-enrollment-flyout'; + title: EuiStepProps['title']; + Component: ComponentType<{}>; } /** Fleet UI Extension Point */ export type UIExtensionPoint = | PackagePolicyEditExtension | PackageCustomExtension - | PackagePolicyCreateExtension; + | PackagePolicyCreateExtension + | PackageAssetsExtension + | AgentEnrollmentFlyoutFinalStepExtension; diff --git a/x-pack/plugins/index_management/server/lib/fetch_indices.ts b/x-pack/plugins/index_management/server/lib/fetch_indices.ts index a6f499ede9038..b83843f0c615d 100644 --- a/x-pack/plugins/index_management/server/lib/fetch_indices.ts +++ b/x-pack/plugins/index_management/server/lib/fetch_indices.ts @@ -76,26 +76,33 @@ async function fetchIndicesCall( query: catQuery, }); - // The two responses should be equal in the number of indices returned - return catHits.map((hit) => { + // System indices may show up in _cat APIs, as these APIs are primarily used for troubleshooting + // For now, we filter them out and only return index information for the indices we have + // In the future, we should migrate away from using cat APIs (https://github.com/elastic/kibana/issues/57286) + return catHits.reduce((decoratedIndices, hit) => { const index = indices[hit.index]; - const aliases = Object.keys(index.aliases); - return { - health: hit.health, - status: hit.status, - name: hit.index, - uuid: hit.uuid, - primary: hit.pri, - replica: hit.rep, - documents: hit['docs.count'], - size: hit['store.size'], - isFrozen: hit.sth === 'true', // sth value coming back as a string from ES - aliases: aliases.length ? aliases : 'none', - hidden: index.settings.index.hidden === 'true', - data_stream: index.data_stream, - }; - }); + if (typeof index !== 'undefined') { + const aliases = Object.keys(index.aliases); + + decoratedIndices.push({ + health: hit.health, + status: hit.status, + name: hit.index, + uuid: hit.uuid, + primary: hit.pri, + replica: hit.rep, + documents: hit['docs.count'], + size: hit['store.size'], + isFrozen: hit.sth === 'true', // sth value coming back as a string from ES + aliases: aliases.length ? aliases : 'none', + hidden: index.settings.index.hidden === 'true', + data_stream: index.data_stream, + }); + } + + return decoratedIndices; + }, [] as Index[]); } export const fetchIndices = async ( diff --git a/x-pack/plugins/lens/public/app_plugin/mounter.tsx b/x-pack/plugins/lens/public/app_plugin/mounter.tsx index 1fd12460ba3b6..12522402116c9 100644 --- a/x-pack/plugins/lens/public/app_plugin/mounter.tsx +++ b/x-pack/plugins/lens/public/app_plugin/mounter.tsx @@ -161,6 +161,7 @@ export async function mountApp( embeddableId: isCopied ? undefined : embeddableEditorIncomingState.embeddableId, type: LENS_EMBEDDABLE_TYPE, input, + searchSessionId: data.search.session.getSessionId(), }, }); } else { @@ -178,6 +179,10 @@ export async function mountApp( if (!initialContext) { data.query.filterManager.setAppFilters([]); } + + if (embeddableEditorIncomingState?.searchSessionId) { + data.search.session.continue(embeddableEditorIncomingState.searchSessionId); + } const { datasourceMap, visualizationMap } = instance; const initialDatasourceId = getInitialDatasourceId(datasourceMap); @@ -298,6 +303,7 @@ export async function mountApp( params.element ); return () => { + data.search.session.clear(); unmountComponentAtNode(params.element); unlistenParentHistory(); lensStore.dispatch(navigateAway()); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/counter_rate.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/counter_rate.tsx index 3f539b18896c4..e6cba7ac9dce0 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/counter_rate.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/counter_rate.tsx @@ -126,7 +126,7 @@ export const counterRateOperation: OperationDefinition< signature: i18n.translate('xpack.lens.indexPattern.counterRate.signature', { defaultMessage: 'metric: number', }), - description: i18n.translate('xpack.lens.indexPattern.counterRate.documentation', { + description: i18n.translate('xpack.lens.indexPattern.counterRate.documentation.markdown', { defaultMessage: ` Calculates the rate of an ever increasing counter. This function will only yield helpful results on counter metric fields which contain a measurement of some kind monotonically growing over time. If the value does get smaller, it will interpret this as a counter reset. To get most precise results, \`counter_rate\` should be calculated on the \`max\` of a field. diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/cumulative_sum.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/cumulative_sum.tsx index 0bdef4cc7678d..9c8437140f793 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/cumulative_sum.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/cumulative_sum.tsx @@ -122,7 +122,7 @@ export const cumulativeSumOperation: OperationDefinition< signature: i18n.translate('xpack.lens.indexPattern.cumulative_sum.signature', { defaultMessage: 'metric: number', }), - description: i18n.translate('xpack.lens.indexPattern.cumulativeSum.documentation', { + description: i18n.translate('xpack.lens.indexPattern.cumulativeSum.documentation.markdown', { defaultMessage: ` Calculates the cumulative sum of a metric over time, adding all previous values of a series to each value. To use this function, you need to configure a date histogram dimension as well. diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/differences.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/differences.tsx index 857b719b0f411..8890390378d21 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/differences.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/differences.tsx @@ -114,7 +114,7 @@ export const derivativeOperation: OperationDefinition< signature: i18n.translate('xpack.lens.indexPattern.differences.signature', { defaultMessage: 'metric: number', }), - description: i18n.translate('xpack.lens.indexPattern.differences.documentation', { + description: i18n.translate('xpack.lens.indexPattern.differences.documentation.markdown', { defaultMessage: ` Calculates the difference to the last value of a metric over time. To use this function, you need to configure a date histogram dimension as well. Differences requires the data to be sequential. If your data is empty when using differences, try increasing the date histogram interval. diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/moving_average.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/moving_average.tsx index aea203c70a928..72e14cc2ea016 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/moving_average.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/moving_average.tsx @@ -137,7 +137,7 @@ export const movingAverageOperation: OperationDefinition< signature: i18n.translate('xpack.lens.indexPattern.moving_average.signature', { defaultMessage: 'metric: number, [window]: number', }), - description: i18n.translate('xpack.lens.indexPattern.movingAverage.documentation', { + description: i18n.translate('xpack.lens.indexPattern.movingAverage.documentation.markdown', { defaultMessage: ` Calculates the moving average of a metric over time, averaging the last n-th values to calculate the current value. To use this function, you need to configure a date histogram dimension as well. The default window value is {defaultValue}. diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/overall_metric.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/overall_metric.tsx index 21ec5387b3853..4250811e11452 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/overall_metric.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/overall_metric.tsx @@ -115,7 +115,7 @@ export const overallSumOperation = buildOverallMetricOperation ), }, @@ -102,8 +105,10 @@ count(kql='response.status_code > 400') / count() }), description: ( ), }, @@ -126,8 +132,10 @@ percentile(system.network.in.bytes, percentile=99, shift='1w') }), description: ( ), }, @@ -372,9 +381,8 @@ sum(products.base_price) / overall_sum(sum(products.base_price)) }} > >({ signature: i18n.translate('xpack.lens.indexPattern.metric.signature', { defaultMessage: 'field: string', }), - description: i18n.translate('xpack.lens.indexPattern.metric.documentation', { + description: i18n.translate('xpack.lens.indexPattern.metric.documentation.markdown', { defaultMessage: ` Returns the {metric} of a field. This function only works for number fields. diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.tsx index bdc4743e4f56d..9c9f7e8b66a1f 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/percentile.tsx @@ -220,7 +220,7 @@ export const percentileOperation: OperationDefinition { minLon: 95, }, buffer: { - maxLat: 21.94305, - maxLon: 112.5, + maxLat: 11.1784, + maxLon: 101.25, minLat: 0, minLon: 90, }, @@ -158,10 +158,10 @@ describe('map_actions', () => { minLon: 85, }, buffer: { - maxLat: 7.71099, - maxLon: 92.8125, - minLat: -2.81137, - minLon: 82.26563, + maxLat: 5.26601, + maxLon: 90.35156, + minLat: -0.35156, + minLon: 84.72656, }, }, type: 'MAP_EXTENT_CHANGED', @@ -190,10 +190,10 @@ describe('map_actions', () => { minLon: 96, }, buffer: { - maxLat: 13.58192, - maxLon: 103.53516, - minLat: 3.33795, - minLon: 93.33984, + maxLat: 11.0059, + maxLon: 101.07422, + minLat: 5.96575, + minLon: 95.97656, }, }, type: 'MAP_EXTENT_CHANGED', diff --git a/x-pack/plugins/maps/public/actions/map_actions.ts b/x-pack/plugins/maps/public/actions/map_actions.ts index a1c7e2f7b453c..af8d6cc6bedc3 100644 --- a/x-pack/plugins/maps/public/actions/map_actions.ts +++ b/x-pack/plugins/maps/public/actions/map_actions.ts @@ -60,7 +60,6 @@ import { Timeslice, } from '../../common/descriptor_types'; import { INITIAL_LOCATION } from '../../common/constants'; -import { scaleBounds } from '../../common/elasticsearch_util'; import { cleanTooltipStateForLayer } from './tooltip_actions'; import { VectorLayer } from '../classes/layers/vector_layer'; import { SET_DRAW_MODE } from './ui_actions'; @@ -167,9 +166,8 @@ export function mapExtentChanged(mapExtentState: MapExtentState) { } if (!doesBufferContainExtent || currentZoom !== newZoom) { - const expandedExtent = scaleBounds(extent, 0.5); // snap to the smallest tile-bounds, to avoid jitter in the bounds - dataFilters.buffer = expandToTileBoundaries(expandedExtent, Math.ceil(newZoom)); + dataFilters.buffer = expandToTileBoundaries(extent, Math.ceil(newZoom)); } } diff --git a/x-pack/plugins/osquery/public/plugin.ts b/x-pack/plugins/osquery/public/plugin.ts index d1e7154fb0dc0..abdea2df3b2b5 100644 --- a/x-pack/plugins/osquery/public/plugin.ts +++ b/x-pack/plugins/osquery/public/plugin.ts @@ -58,7 +58,7 @@ export function toggleOsqueryPlugin( registerExtension({ package: OSQUERY_INTEGRATION_NAME, view: 'package-detail-custom', - component: LazyOsqueryManagedCustomButtonExtension, + Component: LazyOsqueryManagedCustomButtonExtension, }); } @@ -146,13 +146,13 @@ export class OsqueryPlugin implements Plugin { }); it('Selected renderer can be disabled with one click', () => { + // Ensure these elements are visible before continuing since sometimes it takes a second for the modal to show up + // and it gives the click handlers a bit of time to be initialized as well to reduce chances of flake but you still + // have to use pipe() below as an additional measure. cy.get(TIMELINE_ROW_RENDERERS_DISABLE_ALL_BTN).should('exist'); - cy.get(TIMELINE_ROW_RENDERERS_DISABLE_ALL_BTN) - .pipe(($el) => $el.trigger('click')) - .should('not.be.visible'); + cy.get(TIMELINE_ROW_RENDERERS_MODAL_ITEMS_CHECKBOX).should('be.checked'); + + // Keep clicking on the disable all button until the first element of all the elements are no longer checked. + // In cases where the click handler is not present on the page just yet, this will cause the button to be clicked + // multiple times until it sees that the click took effect. You could go through the whole list but I just check + // for the first to be unchecked and then assume the click was successful + cy.root() + .pipe(($el) => { + $el.find(TIMELINE_ROW_RENDERERS_DISABLE_ALL_BTN).trigger('click'); + return $el.find(TIMELINE_ROW_RENDERERS_MODAL_ITEMS_CHECKBOX).first(); + }) + .should('not.be.checked'); cy.intercept('PATCH', '/api/timeline').as('updateTimeline'); cy.wait('@updateTimeline').its('response.statusCode').should('eq', 200); diff --git a/x-pack/plugins/security_solution/public/app/deep_links/index.ts b/x-pack/plugins/security_solution/public/app/deep_links/index.ts index cbaa789d47489..affed45908fdd 100644 --- a/x-pack/plugins/security_solution/public/app/deep_links/index.ts +++ b/x-pack/plugins/security_solution/public/app/deep_links/index.ts @@ -165,7 +165,7 @@ const nestedDeepLinks: SecurityDeepLinks = { navLinkStatus: AppNavLinkStatus.hidden, keywords: [ i18n.translate('xpack.securitySolution.search.exceptions', { - defaultMessage: 'Exceptions', + defaultMessage: 'Exception list', }), ], searchable: true, @@ -299,14 +299,14 @@ const nestedDeepLinks: SecurityDeepLinks = { { id: SecurityPageName.trustedApps, title: i18n.translate('xpack.securitySolution.search.administration.trustedApps', { - defaultMessage: 'Trusted Applications', + defaultMessage: 'Trusted applications', }), path: TRUSTED_APPS_PATH, }, { id: SecurityPageName.eventFilters, title: i18n.translate('xpack.securitySolution.search.administration.eventFilters', { - defaultMessage: 'Event Filters', + defaultMessage: 'Event filters', }), path: EVENT_FILTERS_PATH, }, diff --git a/x-pack/plugins/security_solution/public/app/translations.ts b/x-pack/plugins/security_solution/public/app/translations.ts index edbab928a5c69..847a9114d94bd 100644 --- a/x-pack/plugins/security_solution/public/app/translations.ts +++ b/x-pack/plugins/security_solution/public/app/translations.ts @@ -24,7 +24,7 @@ export const RULES = i18n.translate('xpack.securitySolution.navigation.rules', { }); export const EXCEPTIONS = i18n.translate('xpack.securitySolution.navigation.exceptions', { - defaultMessage: 'Exceptions', + defaultMessage: 'Exception list', }); export const ALERTS = i18n.translate('xpack.securitySolution.navigation.alerts', { @@ -48,13 +48,13 @@ export const ENDPOINTS = i18n.translate('xpack.securitySolution.search.administr export const TRUSTED_APPLICATIONS = i18n.translate( 'xpack.securitySolution.search.administration.trustedApps', { - defaultMessage: 'Trusted Applications', + defaultMessage: 'Trusted applications', } ); export const EVENT_FILTERS = i18n.translate( 'xpack.securitySolution.search.administration.eventFilters', { - defaultMessage: 'Event Filters', + defaultMessage: 'Event filters', } ); diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx index d07cdd81aa5f4..9afaaef61b17a 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx +++ b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx @@ -104,7 +104,7 @@ const EventDetailsComponent: React.FC = ({ setSelectedTabId, ]); - const eventFields = useMemo(() => getEnrichmentFields(data ?? []), [data]); + const eventFields = useMemo(() => getEnrichmentFields(data), [data]); const existingEnrichments = useMemo( () => isAlert @@ -242,7 +242,7 @@ const EventDetailsComponent: React.FC = ({ ); }, [summaryTab, threatIntelTab, tableTab, jsonTab]); - const selectedTab = useMemo(() => tabs.find((tab) => tab.id === selectedTabId), [ + const selectedTab = useMemo(() => tabs.find((tab) => tab.id === selectedTabId) ?? tabs[0], [ tabs, selectedTabId, ]); diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/index.test.tsx index 7e211a2e95152..47ffb20c21d5a 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/navigation/use_security_solution_navigation/index.test.tsx @@ -139,7 +139,7 @@ describe('useSecuritySolutionNavigation', () => { "href": "securitySolution/exceptions?query=(language:kuery,query:'host.name:%22security-solution-es%22')&sourcerer=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'2020-07-07T08:20:18.966Z',fromStr:now-24h,kind:relative,to:'2020-07-08T08:20:18.966Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2020-07-07T08:20:18.966Z',fromStr:now-24h,kind:relative,to:'2020-07-08T08:20:18.966Z',toStr:now)))", "id": "exceptions", "isSelected": false, - "name": "Exceptions", + "name": "Exception list", "onClick": [Function], }, ], @@ -207,7 +207,7 @@ describe('useSecuritySolutionNavigation', () => { "href": "securitySolution/trusted_apps", "id": "trusted_apps", "isSelected": false, - "name": "Trusted Applications", + "name": "Trusted applications", "onClick": [Function], }, Object { @@ -217,7 +217,7 @@ describe('useSecuritySolutionNavigation', () => { "href": "securitySolution/event_filters", "id": "event_filters", "isSelected": false, - "name": "Event Filters", + "name": "Event filters", "onClick": [Function], }, ], diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_custom_assets_extension.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_custom_assets_extension.tsx new file mode 100644 index 0000000000000..781aa880d1483 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_custom_assets_extension.tsx @@ -0,0 +1,34 @@ +/* + * 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 { i18n } from '@kbn/i18n'; + +import { useKibana } from '../../../../../common/lib/kibana'; +import { APP_PATH } from '../../../../../../common/constants'; +import { + CustomAssetsAccordionProps, + CustomAssetsAccordion, + PackageAssetsComponent, +} from '../../../../../../../fleet/public'; + +export const EndpointCustomAssetsExtension: PackageAssetsComponent = () => { + const { http } = useKibana().services; + const views: CustomAssetsAccordionProps['views'] = [ + { + name: i18n.translate('xpack.securitySolution.fleetIntegration.assets.name', { + defaultMessage: 'Hosts', + }), + url: http.basePath.prepend(`${APP_PATH}/administration/endpoints`), + description: i18n.translate('xpack.securitySolution.fleetIntegration.assets.description', { + defaultMessage: 'View endpoints in Security app', + }), + }, + ]; + + return ; +}; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/lazy_endpoint_custom_assets_extension.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/lazy_endpoint_custom_assets_extension.tsx new file mode 100644 index 0000000000000..05187d64a12e7 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/lazy_endpoint_custom_assets_extension.tsx @@ -0,0 +1,16 @@ +/* + * 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 { lazy } from 'react'; + +export const LazyEndpointCustomAssetsExtension = lazy(async () => { + const { EndpointCustomAssetsExtension } = await import('./endpoint_custom_assets_extension'); + + return { + default: EndpointCustomAssetsExtension, + }; +}); diff --git a/x-pack/plugins/security_solution/public/plugin.tsx b/x-pack/plugins/security_solution/public/plugin.tsx index 1bf3edf1605d8..137fef1641501 100644 --- a/x-pack/plugins/security_solution/public/plugin.tsx +++ b/x-pack/plugins/security_solution/public/plugin.tsx @@ -60,6 +60,7 @@ import { LazyEndpointPolicyCreateExtension } from './management/pages/policy/vie import { getLazyEndpointPackageCustomExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_package_custom_extension'; import { parseExperimentalConfigValue } from '../common/experimental_features'; import type { TimelineState } from '../../timelines/public'; +import { LazyEndpointCustomAssetsExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_custom_assets_extension'; export class Plugin implements IPlugin { private kibanaVersion: string; @@ -199,19 +200,25 @@ export class Plugin implements IPlugin( { + const { SyntheticsCustomAssetsExtension } = await import('./synthetics_custom_assets_extension'); + + return { + default: SyntheticsCustomAssetsExtension, + }; +}); diff --git a/x-pack/plugins/uptime/public/components/fleet_package/synthetics_custom_assets_extension.tsx b/x-pack/plugins/uptime/public/components/fleet_package/synthetics_custom_assets_extension.tsx new file mode 100644 index 0000000000000..7eda6efa20530 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/fleet_package/synthetics_custom_assets_extension.tsx @@ -0,0 +1,35 @@ +/* + * 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 { i18n } from '@kbn/i18n'; + +import { + PackageAssetsComponent, + CustomAssetsAccordionProps, + CustomAssetsAccordion, +} from '../../../../fleet/public'; +import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; +import { ClientPluginsStart } from '../../apps/plugin'; +import { PLUGIN } from '../../../common/constants/plugin'; + +export const SyntheticsCustomAssetsExtension: PackageAssetsComponent = () => { + const { http } = useKibana().services; + const views: CustomAssetsAccordionProps['views'] = [ + { + name: i18n.translate('xpack.uptime.fleetIntegration.assets.name', { + defaultMessage: 'Monitors', + }), + url: http?.basePath.prepend(`/app/${PLUGIN.ID}`) ?? '', + description: i18n.translate('xpack.uptime.fleetIntegration.assets.description', { + defaultMessage: 'View monitors in Uptime', + }), + }, + ]; + + return ; +}; diff --git a/x-pack/plugins/uptime/public/components/monitor/monitor_title.tsx b/x-pack/plugins/uptime/public/components/monitor/monitor_title.tsx index 8cb1c49cbd974..2112af0653669 100644 --- a/x-pack/plugins/uptime/public/components/monitor/monitor_title.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/monitor_title.tsx @@ -89,17 +89,9 @@ export const MonitorPageTitle: React.FC = () => { return ( <> - - - -

{nameOrId}

-
- -
- - - -
+ +

{nameOrId}

+
@@ -126,6 +118,7 @@ export const MonitorPageTitle: React.FC = () => { )} + ); }; diff --git a/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_bar.test.ts b/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_bar.test.ts new file mode 100644 index 0000000000000..82e7dfd2d0ced --- /dev/null +++ b/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_bar.test.ts @@ -0,0 +1,32 @@ +/* + * 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 { renderMonitorType } from './status_bar'; + +describe('StatusBar component', () => { + describe('renderMonitorType', () => { + it('handles http type', () => { + expect(renderMonitorType('http')).toBe('HTTP'); + }); + + it('handles tcp type', () => { + expect(renderMonitorType('tcp')).toBe('TCP'); + }); + + it('handles icmp type', () => { + expect(renderMonitorType('icmp')).toBe('ICMP'); + }); + + it('handles browser type', () => { + expect(renderMonitorType('browser')).toBe('Browser'); + }); + + it('returns empty string for `undefined`', () => { + expect(renderMonitorType(undefined)).toBe(''); + }); + }); +}); diff --git a/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_bar.tsx b/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_bar.tsx index 18049a9de5c5c..e8374d3792bfe 100644 --- a/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_bar.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/status_details/status_bar/status_bar.tsx @@ -15,6 +15,7 @@ import { EuiDescriptionListDescription, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; import { MonitorSSLCertificate } from './ssl_certificate'; import * as labels from '../translations'; import { StatusByLocations } from './status_by_location'; @@ -40,6 +41,29 @@ export const MonListDescription = styled(EuiDescriptionListDescription)` } `; +export const renderMonitorType = (type: string | undefined) => { + switch (type) { + case 'http': + return i18n.translate('xpack.uptime.monitorDetails.statusBar.pingType.http', { + defaultMessage: 'HTTP', + }); + case 'tcp': + return i18n.translate('xpack.uptime.monitorDetails.statusBar.pingType.tcp', { + defaultMessage: 'TCP', + }); + case 'icmp': + return i18n.translate('xpack.uptime.monitorDetails.statusBar.pingType.icmp', { + defaultMessage: 'ICMP', + }); + case 'browser': + return i18n.translate('xpack.uptime.monitorDetails.statusBar.pingType.browser', { + defaultMessage: 'Browser', + }); + default: + return ''; + } +}; + export const MonitorStatusBar: React.FC = () => { const { monitorId, monitorStatus, monitorLocations = {} } = useStatusBar(); @@ -77,7 +101,7 @@ export const MonitorStatusBar: React.FC = () => { <> {labels.typeLabel} - {monitorStatus.monitor.type} + {renderMonitorType(monitorStatus?.monitor?.type)} )} diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/__snapshots__/monitor_list.test.tsx.snap b/x-pack/plugins/uptime/public/components/overview/monitor_list/__snapshots__/monitor_list.test.tsx.snap index 8ecadcf19f4ef..a4fcb141d454b 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/__snapshots__/monitor_list.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/__snapshots__/monitor_list.test.tsx.snap @@ -1299,28 +1299,37 @@ exports[`MonitorList component renders the monitor list 1`] = ` class="euiPopover__anchor" >
- + +
+
@@ -1552,28 +1561,37 @@ exports[`MonitorList component renders the monitor list 1`] = ` class="euiPopover__anchor" >
- + +
+
diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/define_connectors.test.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/define_connectors.test.tsx new file mode 100644 index 0000000000000..aa257177970a1 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/define_connectors.test.tsx @@ -0,0 +1,44 @@ +/* + * 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 { DefineAlertConnectors } from './define_connectors'; +import { screen } from '@testing-library/react'; +import { fireEvent } from '@testing-library/dom'; +import { ENABLE_STATUS_ALERT } from './translations'; +import { render } from '../../../../lib/helper/rtl_helpers'; + +describe('EnableAlertComponent', () => { + it('does not showHelpText or render popover when showHelpText and renderPopOver are false', () => { + render(); + expect(screen.getByTestId('uptimeDisplayDefineConnector')).toBeInTheDocument(); + expect(screen.queryByText(ENABLE_STATUS_ALERT)).not.toBeInTheDocument(); + expect(screen.queryByText(/Define a default connector/)).not.toBeInTheDocument(); + + fireEvent.click(screen.getByTestId('uptimeDisplayDefineConnector')); + + expect(screen.queryByTestId('uptimeSettingsDefineConnector')).not.toBeInTheDocument(); + }); + + it('shows label when showLabel is true', () => { + render(); + expect(screen.getByText(ENABLE_STATUS_ALERT)).toBeInTheDocument(); + }); + + it('shows helpText when showHelpText is true', () => { + render(); + expect(screen.getByText(/Define a default connector/)).toBeInTheDocument(); + }); + + it('renders popover on click when showPopover is true', () => { + render(); + + fireEvent.click(screen.getByTestId('uptimeDisplayDefineConnector')); + + expect(screen.getByTestId('uptimeSettingsDefineConnector')).toBeInTheDocument(); + }); +}); diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/define_connectors.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/define_connectors.tsx index 956e18f3d7cc3..dcc70c16e920b 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/define_connectors.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/define_connectors.tsx @@ -6,41 +6,72 @@ */ import React, { useState } from 'react'; -import { EuiPopover, EuiSwitch, EuiText } from '@elastic/eui'; -import { useRouteMatch } from 'react-router-dom'; -import { i18n } from '@kbn/i18n'; +import { EuiSwitch, EuiPopover, EuiText, EuiFormRow } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { ReactRouterEuiLink } from '../../../common/react_router_helpers'; -import { MONITOR_ROUTE, SETTINGS_ROUTE } from '../../../../../common/constants'; +import { SETTINGS_ROUTE } from '../../../../../common/constants'; import { ENABLE_STATUS_ALERT } from './translations'; -const SETTINGS_LINK_TEXT = i18n.translate('xpack.uptime.page_header.defineConnector', { - defaultMessage: 'Define a default connector', -}); +interface Props { + showPopover?: boolean; + showHelpText?: boolean; + showLabel?: boolean; +} -export const DefineAlertConnectors = () => { +export const DefineAlertConnectors = ({ + showPopover = false, + showHelpText = false, + showLabel = false, +}: Props) => { const [isPopoverOpen, setIsPopoverOpen] = useState(false); const onButtonClick = () => setIsPopoverOpen((val) => !val); const closePopover = () => setIsPopoverOpen(false); - const isMonitorPage = useRouteMatch(MONITOR_ROUTE); - return ( + <> + + + + ), + }} + /> + ) : undefined + } + > + {}} + checked={false} + compressed={true} + disabled={!showPopover} + data-test-subj={'uptimeDisplayDefineConnector'} + /> + + } - isOpen={isPopoverOpen} + isOpen={showPopover ? isPopoverOpen : false} closePopover={closePopover} > @@ -48,10 +79,13 @@ export const DefineAlertConnectors = () => { to={SETTINGS_ROUTE + '?focusConnectorField=true'} data-test-subj={'uptimeSettingsLink'} > - {SETTINGS_LINK_TEXT} + {' '} diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/enable_alert.test.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/enable_alert.test.tsx index 427985839ba89..53ba1b8ed57eb 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/enable_alert.test.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/enable_alert.test.tsx @@ -18,7 +18,7 @@ import { AlertsResult } from '../../../../state/actions/types'; describe('EnableAlertComponent', () => { it('it displays define connectors when there is none', () => { - const { getByTestId, getByLabelText, getByText } = render( + const { getByTestId, getByLabelText, getByText, getByRole } = render( { fireEvent.click(getByTestId('uptimeDisplayDefineConnector')); - expect(getByTestId('uptimeSettingsLink')).toHaveAttribute( + expect(getByRole('link', { name: 'Define a default connector' })).toHaveAttribute( 'href', '/settings?focusConnectorField=true' ); - expect(getByText('to receive status alerts.')); + expect(getByText(/Define a default connector/)); + expect(getByText(/to receive status alerts./)); }); it('does not displays define connectors when there is connector', () => { diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/enable_alert.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/enable_alert.tsx index f0f7c4d91c4f5..9db6c3b4b0acb 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/enable_alert.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/enable_alert.tsx @@ -125,6 +125,10 @@ export const EnableMonitorAlert = ({ monitorId, selectedMonitor }: Props) => { ) : ( - + ); }; diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/translations.ts b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/translations.ts index eadf8febebcf2..ce6708abf9ade 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/translations.ts +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/columns/translations.ts @@ -8,11 +8,11 @@ import { i18n } from '@kbn/i18n'; export const ENABLE_STATUS_ALERT = i18n.translate('xpack.uptime.monitorList.enableDownAlert', { - defaultMessage: 'Enable rule', + defaultMessage: 'Enable status alerts', }); export const DISABLE_STATUS_ALERT = i18n.translate('xpack.uptime.monitorList.disableDownAlert', { - defaultMessage: 'Disable rule', + defaultMessage: 'Disable status alerts', }); export const EXPAND_TAGS_LABEL = i18n.translate('xpack.uptime.monitorList.tags.expand', { diff --git a/x-pack/test/api_integration/apis/management/index_management/indices.js b/x-pack/test/api_integration/apis/management/index_management/indices.js index d0e17476530b7..25b1ef97d3087 100644 --- a/x-pack/test/api_integration/apis/management/index_management/indices.js +++ b/x-pack/test/api_integration/apis/management/index_management/indices.js @@ -177,12 +177,19 @@ export default function ({ getService }) { }); }); - // FLAKY: https://github.com/elastic/kibana/issues/64473 - describe.skip('list', function () { + describe('list', function () { this.tags(['skipCloud']); it('should list all the indices with the expected properties and data enrichers', async function () { - const { body } = await list().expect(200); + // Create an index that we can assert against + await createIndex('test_index'); + + // Verify indices request + const { body: indices } = await list().expect(200); + + // Find the "test_index" created to verify expected keys + const indexCreated = indices.find((index) => index.name === 'test_index'); + const expectedKeys = [ 'health', 'hidden', @@ -203,7 +210,8 @@ export default function ({ getService }) { // We need to sort the keys before comparing then, because race conditions // can cause enrichers to register in non-deterministic order. const sortedExpectedKeys = expectedKeys.sort(); - const sortedReceivedKeys = Object.keys(body[0]).sort(); + const sortedReceivedKeys = Object.keys(indexCreated).sort(); + expect(sortedReceivedKeys).to.eql(sortedExpectedKeys); }); }); diff --git a/x-pack/test/functional/apps/maps/blended_vector_layer.js b/x-pack/test/functional/apps/maps/blended_vector_layer.js index 3cc7d8e07d623..67e6d7f93a4cd 100644 --- a/x-pack/test/functional/apps/maps/blended_vector_layer.js +++ b/x-pack/test/functional/apps/maps/blended_vector_layer.js @@ -29,7 +29,7 @@ export default function ({ getPageObjects, getService }) { it('should request documents when zoomed to smaller regions showing less data', async () => { const { rawResponse: response } = await PageObjects.maps.getResponse(); // Allow a range of hits to account for variances in browser window size. - expect(response.hits.hits.length).to.be.within(35, 45); + expect(response.hits.hits.length).to.be.within(5, 12); }); it('should request clusters when zoomed to larger regions showing lots of data', async () => { diff --git a/x-pack/test/functional/apps/maps/documents_source/search_hits.js b/x-pack/test/functional/apps/maps/documents_source/search_hits.js index 4da36a44cff08..de2233fdf791d 100644 --- a/x-pack/test/functional/apps/maps/documents_source/search_hits.js +++ b/x-pack/test/functional/apps/maps/documents_source/search_hits.js @@ -53,7 +53,7 @@ export default function ({ getPageObjects, getService }) { describe('inspector', () => { it('should register elasticsearch request in inspector', async () => { const hits = await PageObjects.maps.getHits(); - expect(hits).to.equal('6'); + expect(hits).to.equal('5'); }); }); @@ -74,7 +74,7 @@ export default function ({ getPageObjects, getService }) { const requestStats = await inspector.getTableData(); const hits = PageObjects.maps.getInspectorStatRowHit(requestStats, 'Hits'); await inspector.close(); - expect(hits).to.equal('3'); + expect(hits).to.equal('2'); }); it('should re-fetch query when "refresh" is clicked', async () => { diff --git a/x-pack/test/functional/apps/maps/es_geo_grid_source.js b/x-pack/test/functional/apps/maps/es_geo_grid_source.js index 27949ca720e34..26eabafef7d1f 100644 --- a/x-pack/test/functional/apps/maps/es_geo_grid_source.js +++ b/x-pack/test/functional/apps/maps/es_geo_grid_source.js @@ -59,9 +59,9 @@ export default function ({ getPageObjects, getService }) { }); it('should not rerequest when zoom changes do not cause geotile_grid precision to change', async () => { - await PageObjects.maps.setView(DATA_CENTER_LAT, DATA_CENTER_LON, 1.2); + await PageObjects.maps.setView(DATA_CENTER_LAT, DATA_CENTER_LON, 1.4); const beforeSameZoom = await getRequestTimestamp(); - await PageObjects.maps.setView(DATA_CENTER_LAT, DATA_CENTER_LON, 1.8); + await PageObjects.maps.setView(DATA_CENTER_LAT, DATA_CENTER_LON, 1.6); const afterTimestamp = await getRequestTimestamp(); expect(afterTimestamp).to.equal(beforeSameZoom); }); diff --git a/x-pack/test/functional/apps/maps/layer_visibility.js b/x-pack/test/functional/apps/maps/layer_visibility.js index 52cfa44923f63..cf6051cde8be7 100644 --- a/x-pack/test/functional/apps/maps/layer_visibility.js +++ b/x-pack/test/functional/apps/maps/layer_visibility.js @@ -32,7 +32,7 @@ export default function ({ getPageObjects, getService }) { it('should fetch layer data when layer is made visible', async () => { await PageObjects.maps.toggleLayerVisibility('logstash'); const hits = await PageObjects.maps.getHits(); - expect(hits).to.equal('6'); + expect(hits).to.equal('5'); }); }); } diff --git a/x-pack/test/functional/apps/maps/saved_object_management.js b/x-pack/test/functional/apps/maps/saved_object_management.js index bdc9011ec2cba..3392e418bd987 100644 --- a/x-pack/test/functional/apps/maps/saved_object_management.js +++ b/x-pack/test/functional/apps/maps/saved_object_management.js @@ -82,7 +82,7 @@ export default function ({ getPageObjects, getService }) { const requestStats = await inspector.getTableData(); const hits = PageObjects.maps.getInspectorStatRowHit(requestStats, 'Hits'); await inspector.close(); - expect(hits).to.equal('2'); + expect(hits).to.equal('1'); }); it('should override query stored with map when query is provided in app state', async () => { @@ -130,7 +130,7 @@ export default function ({ getPageObjects, getService }) { const requestStats = await inspector.getTableData(); const hits = PageObjects.maps.getInspectorStatRowHit(requestStats, 'Hits'); await inspector.close(); - expect(hits).to.equal('2'); + expect(hits).to.equal('1'); }); }); }); diff --git a/x-pack/test/functional/apps/timelion/feature_controls/timelion_security.ts b/x-pack/test/functional/apps/timelion/feature_controls/timelion_security.ts index e83eabfb05f44..ff6103f16e494 100644 --- a/x-pack/test/functional/apps/timelion/feature_controls/timelion_security.ts +++ b/x-pack/test/functional/apps/timelion/feature_controls/timelion_security.ts @@ -11,6 +11,7 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; export default function ({ getPageObjects, getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const security = getService('security'); + const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects([ 'common', 'error', @@ -24,10 +25,19 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { describe('feature controls security', () => { before(async () => { - await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/timelion/feature_controls'); + await kibanaServer.importExport.load( + 'x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json' + ); await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/logstash_functional'); }); + after(async () => { + await kibanaServer.importExport.unload( + 'x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json' + ); + await esArchiver.unload('x-pack/test/functional/es_archives/logstash_functional'); + }); + describe('global timelion all privileges', () => { before(async () => { await security.role.create('global_timelion_all_role', { diff --git a/x-pack/test/functional/apps/timelion/feature_controls/timelion_spaces.ts b/x-pack/test/functional/apps/timelion/feature_controls/timelion_spaces.ts index 91c357f37085e..a1dea695fce86 100644 --- a/x-pack/test/functional/apps/timelion/feature_controls/timelion_spaces.ts +++ b/x-pack/test/functional/apps/timelion/feature_controls/timelion_spaces.ts @@ -13,6 +13,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const spacesService = getService('spaces'); const PageObjects = getPageObjects(['common', 'timelion', 'security', 'spaceSelector']); const appsMenu = getService('appsMenu'); + const kibanaServer = getService('kibanaServer'); describe('timelion', () => { before(async () => { @@ -23,29 +24,44 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { before(async () => { // we need to load the following in every situation as deleting // a space deletes all of the associated saved objects - await esArchiver.load('x-pack/test/functional/es_archives/timelion/feature_controls'); + // await esArchiver.load('x-pack/test/functional/es_archives/timelion/feature_controls'); + await kibanaServer.importExport.load( + 'x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json' + ); + await spacesService.create({ id: 'custom_space', name: 'custom_space', disabledFeatures: [], }); + + await kibanaServer.importExport.load( + 'x-pack/test/functional/fixtures/kbn_archiver/timelion/timelion_custom_space.json', + { space: 'custom_space' } + ); }); after(async () => { await spacesService.delete('custom_space'); - await esArchiver.unload('x-pack/test/functional/es_archives/timelion/feature_controls'); + await kibanaServer.importExport.unload( + 'x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json' + ); }); it('shows timelion navlink', async () => { await PageObjects.common.navigateToApp('home', { basePath: '/s/custom_space', }); + const navLinks = (await appsMenu.readLinks()).map((link) => link.text); expect(navLinks).to.contain('Timelion'); }); it(`allows a timelion sheet to be created`, async () => { - await PageObjects.common.navigateToApp('timelion'); + await PageObjects.common.navigateToApp('timelion', { + basePath: '/s/custom_space', + }); + await PageObjects.timelion.saveTimelionSheet(); }); }); @@ -54,17 +70,29 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { before(async () => { // we need to load the following in every situation as deleting // a space deletes all of the associated saved objects - await esArchiver.load('x-pack/test/functional/es_archives/timelion/feature_controls'); + // await esArchiver.load('x-pack/test/functional/es_archives/timelion/feature_controls'); + + await kibanaServer.importExport.load( + 'x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json' + ); + await spacesService.create({ id: 'custom_space', name: 'custom_space', disabledFeatures: ['timelion'], }); + + await kibanaServer.importExport.load( + 'x-pack/test/functional/fixtures/kbn_archiver/timelion/timelion_custom_space.json', + { space: 'custom_space' } + ); }); after(async () => { await spacesService.delete('custom_space'); - await esArchiver.unload('x-pack/test/functional/es_archives/timelion/feature_controls'); + await kibanaServer.importExport.unload( + 'x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json' + ); }); it(`doesn't show timelion navlink`, async () => { diff --git a/x-pack/test/functional/apps/uptime/synthetics_integration.ts b/x-pack/test/functional/apps/uptime/synthetics_integration.ts index a4740de8e9a2b..c4996299f0d43 100644 --- a/x-pack/test/functional/apps/uptime/synthetics_integration.ts +++ b/x-pack/test/functional/apps/uptime/synthetics_integration.ts @@ -253,7 +253,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { ]); }); - it.skip('allows configuring http advanced options', async () => { + it('allows configuring http advanced options', async () => { // This test ensures that updates made to the Synthetics Policy are carried all the way through // to the generated Agent Policy that is dispatch down to the Elastic Agent. const config = generateHTTPConfig('http://elastic.co'); diff --git a/x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json b/x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json new file mode 100644 index 0000000000000..323dbb67d54b8 --- /dev/null +++ b/x-pack/test/functional/fixtures/kbn_archiver/timelion/feature_controls.json @@ -0,0 +1,52 @@ +{ + "attributes": { + "buildNum": 9007199254740991, + "defaultIndex": "logstash-*" + }, + "coreMigrationVersion": "7.14.0", + "id": "7.0.0", + "migrationVersion": { + "config": "7.13.0" + }, + "references": [], + "type": "config", + "updated_at": "2019-01-22T19:32:02.235Z", + "version": "WzQsMl0=" +} + +{ + "attributes": { + "description": "", + "hits": 0, + "timelion_chart_height": 275, + "timelion_columns": 2, + "timelion_interval": "auto", + "timelion_rows": 2, + "timelion_sheet": [ + ".es(*)" + ], + "title": "i-exist", + "version": 1 + }, + "coreMigrationVersion": "7.14.0", + "id": "i-exist", + "references": [], + "type": "timelion-sheet", + "version": "WzYsMl0=" +} + +{ + "attributes": { + "fields": "[{\"name\":\"@message\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"@message.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"@tags\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"@tags.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"@timestamp\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"_id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"_index\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"_score\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"_source\",\"type\":\"_source\",\"count\":0,\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"_type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"agent\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"agent.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"bytes\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"clientip\",\"type\":\"ip\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"extension\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"extension.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.coordinates\",\"type\":\"geo_point\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.dest\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.src\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.srcdest\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"headings\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"headings.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"host\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"host.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"id\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"index\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"index.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"ip\",\"type\":\"ip\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"links\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"links.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"machine.os\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"machine.os.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"machine.ram\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"memory\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"meta.char\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"meta.related\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"meta.user.firstname\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"meta.user.lastname\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"phpmemory\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"referer\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:modified_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:published_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:section\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.article:section.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:tag\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.article:tag.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:description\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:description.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image:height\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image:height.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image:width\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image:width.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:site_name\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:site_name.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:title\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:title.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:type.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:card\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:card.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:description\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:description.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:image\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:image.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:site\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:site.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:title\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:title.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"request\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"request.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"response\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"response.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"spaces\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"spaces.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"utc_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"xss\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"xss.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"kilobytes\",\"type\":\"number\",\"count\":0,\"scripted\":true,\"script\":\"doc['bytes'].value / 1000\",\"lang\":\"painless\",\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"machine os raw\",\"type\":\"string\",\"count\":0,\"scripted\":true,\"script\":\"doc['machine.os.raw'].value\",\"lang\":\"painless\",\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false}]", + "timeFieldName": "@timestamp", + "title": "logstash-*" + }, + "coreMigrationVersion": "7.14.0", + "id": "logstash-*", + "migrationVersion": { + "index-pattern": "7.11.0" + }, + "references": [], + "type": "index-pattern", + "version": "WzUsMl0=" +} \ No newline at end of file diff --git a/x-pack/test/functional/fixtures/kbn_archiver/timelion/timelion_custom_space.json b/x-pack/test/functional/fixtures/kbn_archiver/timelion/timelion_custom_space.json new file mode 100644 index 0000000000000..f27149f9d7eb6 --- /dev/null +++ b/x-pack/test/functional/fixtures/kbn_archiver/timelion/timelion_custom_space.json @@ -0,0 +1,20 @@ +{ + "attributes": { + "description": "", + "hits": 0, + "timelion_chart_height": 275, + "timelion_columns": 2, + "timelion_interval": "auto", + "timelion_rows": 2, + "timelion_sheet": [ + ".es(*).label('custom space sheet')" + ], + "title": "i-exist", + "version": 1 + }, + "coreMigrationVersion": "7.14.0", + "id": "i-exist", + "references": [], + "type": "timelion-sheet", + "version": "WzcsMl0=" +} \ No newline at end of file diff --git a/x-pack/test/functional/page_objects/synthetics_integration_page.ts b/x-pack/test/functional/page_objects/synthetics_integration_page.ts index 56a67d9e6fbd4..3321234a345e4 100644 --- a/x-pack/test/functional/page_objects/synthetics_integration_page.ts +++ b/x-pack/test/functional/page_objects/synthetics_integration_page.ts @@ -86,7 +86,7 @@ export function SyntheticsIntegrationPageProvider({ * @params {value} the value of the input */ async fillTextInputByTestSubj(testSubj: string, value: string) { - const field = await testSubjects.find(testSubj, 5000); + const field = await testSubjects.find(testSubj); await field.scrollIntoViewIfNecessary({ bottomOffset: fixedFooterHeight }); await field.click(); await field.clearValue(); @@ -118,7 +118,7 @@ export function SyntheticsIntegrationPageProvider({ */ async findHTTPAdvancedOptionsAccordion() { await this.ensureIsOnPackagePage(); - const accordion = await testSubjects.find('syntheticsHTTPAdvancedFieldsAccordion', 5000); + const accordion = await testSubjects.find('syntheticsHTTPAdvancedFieldsAccordion'); return accordion; }, diff --git a/x-pack/test/search_sessions_integration/config.ts b/x-pack/test/search_sessions_integration/config.ts index 1e2d648712098..9dc542038a48a 100644 --- a/x-pack/test/search_sessions_integration/config.ts +++ b/x-pack/test/search_sessions_integration/config.ts @@ -22,6 +22,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { testFiles: [ resolve(__dirname, './tests/apps/dashboard/async_search'), + resolve(__dirname, './tests/apps/dashboard/session_sharing'), resolve(__dirname, './tests/apps/discover'), resolve(__dirname, './tests/apps/lens'), resolve(__dirname, './tests/apps/management/search_sessions'), diff --git a/x-pack/test/search_sessions_integration/tests/apps/dashboard/session_sharing/index.ts b/x-pack/test/search_sessions_integration/tests/apps/dashboard/session_sharing/index.ts new file mode 100644 index 0000000000000..d06d5d5ebd6ab --- /dev/null +++ b/x-pack/test/search_sessions_integration/tests/apps/dashboard/session_sharing/index.ts @@ -0,0 +1,26 @@ +/* + * 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 { FtrProviderContext } from '../../../../ftr_provider_context'; + +export default function ({ loadTestFile, getService, getPageObjects }: FtrProviderContext) { + const kibanaServer = getService('kibanaServer'); + const esArchiver = getService('esArchiver'); + const PageObjects = getPageObjects(['common']); + + describe('Search session sharing', function () { + this.tags('ciGroup3'); + + before(async () => { + await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/logstash_functional'); + await kibanaServer.uiSettings.replace({ defaultIndex: 'logstash-*' }); + await PageObjects.common.navigateToApp('dashboard'); + }); + + loadTestFile(require.resolve('./lens')); + }); +} diff --git a/x-pack/test/search_sessions_integration/tests/apps/dashboard/session_sharing/lens.ts b/x-pack/test/search_sessions_integration/tests/apps/dashboard/session_sharing/lens.ts new file mode 100644 index 0000000000000..b6dfc29bb1c6b --- /dev/null +++ b/x-pack/test/search_sessions_integration/tests/apps/dashboard/session_sharing/lens.ts @@ -0,0 +1,71 @@ +/* + * 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 expect from '@kbn/expect'; +import { FtrProviderContext } from '../../../../ftr_provider_context'; + +export default function ({ getService, getPageObjects }: FtrProviderContext) { + const esArchiver = getService('esArchiver'); + const dashboardPanelActions = getService('dashboardPanelActions'); + const dashboardAddPanel = getService('dashboardAddPanel'); + const find = getService('find'); + const testSubjects = getService('testSubjects'); + const PageObjects = getPageObjects(['header', 'common', 'dashboard', 'timePicker', 'lens']); + + // Dashboard shares a search session with lens when navigating to and from by value lens to hit search cache + // https://github.com/elastic/kibana/issues/99310 + describe('Search session sharing with lens', () => { + before(async () => { + await esArchiver.loadIfNeeded('x-pack/test/functional/es_archives/lens/basic'); + await PageObjects.common.navigateToApp('dashboard'); + await PageObjects.dashboard.preserveCrossAppState(); + }); + + after(async () => { + await esArchiver.unload('x-pack/test/functional/es_archives/lens/basic'); + }); + + // NOTE: This test doesn't check if the cache was actually hit, but just checks if the same search session id is used + // so it doesn't give the 100% confidence that cache-hit improvement works https://github.com/elastic/kibana/issues/99310 + // but if it fails, we for sure know it doesn't work + it("should share search session with by value lens and don't share with by reference", async () => { + // Add a by ref lens panel to a new dashboard + const lensTitle = 'Artistpreviouslyknownaslens'; + await PageObjects.dashboard.clickNewDashboard(); + await dashboardAddPanel.clickOpenAddPanel(); + await dashboardAddPanel.filterEmbeddableNames(lensTitle); + await find.clickByButtonText(lensTitle); + await dashboardAddPanel.closeAddPanel(); + await PageObjects.lens.goToTimeRange(); + await PageObjects.dashboard.waitForRenderComplete(); + + // Navigating to lens and back should create a new session + const byRefSessionId = await dashboardPanelActions.getSearchSessionIdByTitle(lensTitle); + await dashboardPanelActions.openContextMenu(); + await dashboardPanelActions.clickEdit(); + await PageObjects.lens.saveAndReturn(); + await PageObjects.dashboard.waitForRenderComplete(); + const newByRefSessionId = await dashboardPanelActions.getSearchSessionIdByTitle(lensTitle); + + expect(byRefSessionId).not.to.eql(newByRefSessionId); + + // Convert to by-value + const byRefPanel = await testSubjects.find('embeddablePanelHeading-' + lensTitle); + await dashboardPanelActions.unlinkFromLibary(byRefPanel); + await PageObjects.dashboard.waitForRenderComplete(); + const byValueSessionId = await dashboardPanelActions.getSearchSessionIdByTitle(lensTitle); + + // Navigating to lens and back should keep the session + await dashboardPanelActions.openContextMenu(); + await dashboardPanelActions.clickEdit(); + await PageObjects.lens.saveAndReturn(); + await PageObjects.dashboard.waitForRenderComplete(); + const newByValueSessionId = await dashboardPanelActions.getSearchSessionIdByTitle(lensTitle); + expect(byValueSessionId).to.eql(newByValueSessionId); + }); + }); +}