diff --git a/.sass-lint.yml b/.sass-lint.yml index 9c64c1e5eea56..dd7bc0576692b 100644 --- a/.sass-lint.yml +++ b/.sass-lint.yml @@ -7,6 +7,7 @@ files: - 'x-pack/legacy/plugins/rollup/**/*.s+(a|c)ss' - 'x-pack/legacy/plugins/security/**/*.s+(a|c)ss' - 'x-pack/legacy/plugins/canvas/**/*.s+(a|c)ss' + - 'x-pack/plugins/triggers_actions_ui/**/*.s+(a|c)ss' ignore: - 'x-pack/legacy/plugins/canvas/shareable_runtime/**/*.s+(a|c)ss' - 'x-pack/legacy/plugins/lens/**/*.s+(a|c)ss' diff --git a/docs/api/dashboard/export-dashboard.asciidoc b/docs/api/dashboard/export-dashboard.asciidoc index 7858b69d44c79..36c551dee84fc 100644 --- a/docs/api/dashboard/export-dashboard.asciidoc +++ b/docs/api/dashboard/export-dashboard.asciidoc @@ -9,7 +9,7 @@ experimental[] Export dashboards and corresponding saved objects. [[dashboard-api-export-request]] ==== Request -`GET /api/kibana/dashboards/export` +`GET :/api/kibana/dashboards/export` [[dashboard-api-export-params]] ==== Query parameters @@ -20,9 +20,9 @@ experimental[] Export dashboards and corresponding saved objects. [[dashboard-api-export-response-body]] ==== Response body -`objects`:: +`objects`:: (array) A top level property that includes the saved objects. The order of the objects is not guaranteed. Use the exact response body as the request body for the corresponding <>. - + [[dashboard-api-export-codes]] ==== Response code @@ -33,10 +33,10 @@ experimental[] Export dashboards and corresponding saved objects. [[dashboard-api-export-example]] ==== Example -[source,js] +[source,sh] -------------------------------------------------- -GET api/kibana/dashboards/export?dashboard=942dcef0-b2cd-11e8-ad8e-85441f0c2e5c <1> +$ curl -X GET "localhost:5601/api/kibana/dashboards/export?dashboard=942dcef0-b2cd-11e8-ad8e-85441f0c2e5c" <1> -------------------------------------------------- // KIBANA -<1> The dashboard ID is `942dcef0-b2cd-11e8-ad8e-85441f0c2e5c`. \ No newline at end of file +<1> The dashboard ID is `942dcef0-b2cd-11e8-ad8e-85441f0c2e5c`. diff --git a/docs/api/dashboard/import-dashboard.asciidoc b/docs/api/dashboard/import-dashboard.asciidoc index 14817719ec7ee..320859f78c617 100644 --- a/docs/api/dashboard/import-dashboard.asciidoc +++ b/docs/api/dashboard/import-dashboard.asciidoc @@ -9,7 +9,7 @@ experimental[] Import dashboards and corresponding saved objects. [[dashboard-api-import-request]] ==== Request -`POST /api/kibana/dashboards/import` +`POST :/api/kibana/dashboards/import` [[dashboard-api-import-params]] ==== Query parameters @@ -40,9 +40,9 @@ Use the complete response body from the <:/api/features` [float] [[features-api-get-codes]] @@ -23,7 +23,7 @@ experimental[] Retrieves all {kib} features. Features are used by spaces and sec The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "id": "discover", diff --git a/docs/api/logstash-configuration-management.asciidoc b/docs/api/logstash-configuration-management.asciidoc index fbb45095c214b..621b6c61dad8a 100644 --- a/docs/api/logstash-configuration-management.asciidoc +++ b/docs/api/logstash-configuration-management.asciidoc @@ -2,9 +2,9 @@ [[logstash-configuration-management-api]] == Logstash configuration management APIs -Programmatically integrate with the Logstash configuration management feature. +Programmatically integrate with Logstash configuration management. -WARNING: Do not directly access the `.logstash` index. The structure of the `.logstash` index is subject to change, which could cause your integration to break. Instead, use the Logstash configuration management APIs. +WARNING: Do not directly access the `.logstash` index. The structure of the `.logstash` index is subject to change, which could cause your integration to break. Instead, use the Logstash configuration management APIs. The following Logstash configuration management APIs are available: @@ -20,5 +20,3 @@ include::logstash-configuration-management/delete-pipeline.asciidoc[] include::logstash-configuration-management/list-pipeline.asciidoc[] include::logstash-configuration-management/create-logstash.asciidoc[] include::logstash-configuration-management/retrieve-pipeline.asciidoc[] - - diff --git a/docs/api/logstash-configuration-management/create-logstash.asciidoc b/docs/api/logstash-configuration-management/create-logstash.asciidoc index 38e0ee12a0ebf..d6ad27fe44603 100644 --- a/docs/api/logstash-configuration-management/create-logstash.asciidoc +++ b/docs/api/logstash-configuration-management/create-logstash.asciidoc @@ -9,7 +9,7 @@ experimental[] Create a centrally-managed Logstash pipeline, or update an existi [[logstash-configuration-management-api-create-request]] ==== Request -`PUT /api/logstash/pipeline/` +`PUT :/api/logstash/pipeline/` [[logstash-configuration-management-api-create-params]] ==== Path parameters @@ -39,9 +39,9 @@ experimental[] Create a centrally-managed Logstash pipeline, or update an existi [[logstash-configuration-management-api-create-example]] ==== Example -[source,js] +[source,sh] -------------------------------------------------- -PUT api/logstash/pipeline/hello-world +$ curl -X PUT "localhost:5601/api/logstash/pipeline/hello-world" { "pipeline": "input { stdin {} } output { stdout {} }", "settings": { diff --git a/docs/api/logstash-configuration-management/delete-pipeline.asciidoc b/docs/api/logstash-configuration-management/delete-pipeline.asciidoc index 15d44034b46fe..e982619ee17f4 100644 --- a/docs/api/logstash-configuration-management/delete-pipeline.asciidoc +++ b/docs/api/logstash-configuration-management/delete-pipeline.asciidoc @@ -9,7 +9,7 @@ experimental[] Delete a centrally-managed Logstash pipeline. [[logstash-configuration-management-api-delete-request]] ==== Request -`DELETE /api/logstash/pipeline/` +`DELETE :/api/logstash/pipeline/` [[logstash-configuration-management-api-delete-params]] ==== Path parameters @@ -26,9 +26,8 @@ experimental[] Delete a centrally-managed Logstash pipeline. [[logstash-configuration-management-api-delete-example]] ==== Example -[source,js] +[source,sh] -------------------------------------------------- -DELETE api/logstash/pipeline/hello-world +$ curl -X DELETE "localhost:5601/api/logstash/pipeline/hello-world" -------------------------------------------------- // KIBANA - diff --git a/docs/api/logstash-configuration-management/list-pipeline.asciidoc b/docs/api/logstash-configuration-management/list-pipeline.asciidoc index 7140c35d89853..d875ea3d95b78 100644 --- a/docs/api/logstash-configuration-management/list-pipeline.asciidoc +++ b/docs/api/logstash-configuration-management/list-pipeline.asciidoc @@ -9,14 +9,14 @@ experimental[] List all centrally-managed Logstash pipelines. [[logstash-configuration-management-api-list-request]] ==== Request -`GET /api/logstash/pipelines` +`GET :/api/logstash/pipelines` [[logstash-configuration-management-api-list-example]] ==== Example The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "pipelines": [ @@ -35,4 +35,4 @@ The API returns the following: } -------------------------------------------------- -<1> The `username` property appears when security is enabled, and depends on when the pipeline was created or last updated. \ No newline at end of file +<1> The `username` property appears when security is enabled, and depends on when the pipeline was created or last updated. diff --git a/docs/api/logstash-configuration-management/retrieve-pipeline.asciidoc b/docs/api/logstash-configuration-management/retrieve-pipeline.asciidoc index 93a1ec3aa1da5..1eb380b71c62a 100644 --- a/docs/api/logstash-configuration-management/retrieve-pipeline.asciidoc +++ b/docs/api/logstash-configuration-management/retrieve-pipeline.asciidoc @@ -9,20 +9,20 @@ experimental[] Retrieve a centrally-managed Logstash pipeline. [[logstash-configuration-management-api-retrieve-request]] ==== Request -`GET /api/logstash/pipeline/` +`GET :/api/logstash/pipeline/` [[logstash-configuration-management-api-retrieve-path-params]] ==== Path parameters `id`:: (Required, string) The pipeline ID. - + [[logstash-configuration-management-api-retrieve-example]] ==== Example The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "id": "hello-world", @@ -33,4 +33,4 @@ The API returns the following: "queue.type": "persistent" } } --------------------------------------------------- \ No newline at end of file +-------------------------------------------------- diff --git a/docs/api/role-management.asciidoc b/docs/api/role-management.asciidoc index 482d1a9b3cdd3..4c4620a23943a 100644 --- a/docs/api/role-management.asciidoc +++ b/docs/api/role-management.asciidoc @@ -2,9 +2,9 @@ [[role-management-api]] == {kib} role management APIs -Manage the roles that grant <>. +Manage the roles that grant <>. -WARNING: Do not use the {ref}/security-api.html#security-role-apis[{es} role management APIs] to manage {kib} roles. +WARNING: Do not use the {ref}/security-api.html#security-role-apis[{es} role management APIs] to manage {kib} roles. The following {kib} role management APIs are available: diff --git a/docs/api/role-management/delete.asciidoc b/docs/api/role-management/delete.asciidoc index acf2e4a3e3f1f..530e1e252ef8f 100644 --- a/docs/api/role-management/delete.asciidoc +++ b/docs/api/role-management/delete.asciidoc @@ -4,26 +4,23 @@ Delete role ++++ -Delete a {kib} role. - -experimental["The underlying mechanism of enforcing role-based access control is stable, but the APIs for managing the roles are experimental."] +experimental[] Delete a {kib} role. [[role-management-api-delete-prereqs]] -==== Prerequisite +==== Prerequisite To use the delete role API, you must have the `manage_security` cluster privilege. [[role-management-api-delete-request-body]] ==== Request -`DELETE /api/security/role/my_admin_role` +`DELETE :/api/security/role/my_admin_role` [[role-management-api-delete-response-codes]] ==== Response codes `204`:: Indicates a successful call. - + `404`:: - Indicates an unsuccessful call. - \ No newline at end of file + Indicates an unsuccessful call. diff --git a/docs/api/role-management/get-all.asciidoc b/docs/api/role-management/get-all.asciidoc index 4a3dbd7734d3a..888bf0c8a137c 100644 --- a/docs/api/role-management/get-all.asciidoc +++ b/docs/api/role-management/get-all.asciidoc @@ -4,32 +4,30 @@ Get all roles ++++ -Retrieve all {kib} roles. - -experimental["The underlying mechanism of enforcing role-based access control is stable, but the APIs for managing the roles are experimental."] +experimental[] Retrieve all {kib} roles. [[role-management-api-get-prereqs]] -==== Prerequisite +==== Prerequisite To use the get role API, you must have the `manage_security` cluster privilege. [[role-management-api-retrieve-all-request-body]] ==== Request -`GET /api/security/role` +`GET :/api/security/role` [[role-management-api-retrieve-all-response-codes]] ==== Response code -`200`:: +`200`:: Indicates a successful call. - + [[role-management-api-retrieve-all-example]] ==== Example The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- [ { @@ -77,4 +75,4 @@ The API returns the following: "kibana": [ ] } ] --------------------------------------------------- \ No newline at end of file +-------------------------------------------------- diff --git a/docs/api/role-management/get.asciidoc b/docs/api/role-management/get.asciidoc index 44423b01abe5b..d1e9d1e6afa83 100644 --- a/docs/api/role-management/get.asciidoc +++ b/docs/api/role-management/get.asciidoc @@ -4,32 +4,30 @@ Get specific role ++++ -Retrieve a specific role. - -experimental["The underlying mechanism of enforcing role-based access control is stable, but the APIs for managing the roles are experimental."] +experimental[] Retrieve a specific role. [[role-management-specific-api-get-prereqs]] -==== Prerequisite +==== Prerequisite To use the get specific role API, you must have the `manage_security` cluster privilege. [[role-management-specific-api-retrieve-all-request-body]] ===== Request -`GET /api/security/role/my_restricted_kibana_role` +`GET :/api/security/role/my_restricted_kibana_role` [[role-management-specific-api-retrieve-all-response-codes]] ==== Response code -`200`:: +`200`:: Indicates a successful call. - + [[role-management-specific-api-retrieve-all-example]] ===== Example The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "name": "my_restricted_kibana_role", diff --git a/docs/api/role-management/put.asciidoc b/docs/api/role-management/put.asciidoc index a00fedf7e7ac4..59e6bc8d37eec 100644 --- a/docs/api/role-management/put.asciidoc +++ b/docs/api/role-management/put.asciidoc @@ -4,15 +4,13 @@ Create or update role ++++ -Create a new {kib} role, or update the attributes of an existing role. {kib} roles are stored in the +experimental[] Create a new {kib} role, or update the attributes of an existing role. {kib} roles are stored in the {es} native realm. -experimental["The underlying mechanism of enforcing role-based access control is stable, but the APIs for managing the roles are experimental."] - [[role-management-api-put-request]] ==== Request -`PUT /api/security/role/my_kibana_role` +`PUT :/api/security/role/my_kibana_role` [[role-management-api-put-prereqs]] ==== Prerequisite @@ -22,45 +20,45 @@ To use the create or update role API, you must have the `manage_security` cluste [[role-management-api-response-body]] ==== Request body -`metadata`:: +`metadata`:: (Optional, object) In the `metadata` object, keys that begin with `_` are reserved for system usage. -`elasticsearch`:: - (Optional, object) {es} cluster and index privileges. Valid keys include +`elasticsearch`:: + (Optional, object) {es} cluster and index privileges. Valid keys include `cluster`, `indices`, and `run_as`. For more information, see {ref}/defining-roles.html[Defining roles]. -`kibana`:: +`kibana`:: (list) Objects that specify the <> for the role: -`base` ::: +`base` ::: (Optional, list) A base privilege. When specified, the base must be `["all"]` or `["read"]`. When the `base` privilege is specified, you are unable to use the `feature` section. "all" grants read/write access to all {kib} features for the specified spaces. "read" grants read-only access to all {kib} features for the specified spaces. -`feature` ::: +`feature` ::: (object) Contains privileges for specific features. When the `feature` privileges are specified, you are unable to use the `base` section. To retrieve a list of available features, use the <>. -`spaces` ::: +`spaces` ::: (list) The spaces to apply the privileges to. To grant access to all spaces, set to `["*"]`, or omit the value. [[role-management-api-put-response-codes]] ==== Response code -`204`:: +`204`:: Indicates a successful call. ===== Examples Grant access to various features in all spaces: -[source,js] +[source,sh] -------------------------------------------------- -PUT /api/security/role/my_kibana_role +$ curl -X PUT "localhost:5601/api/security/role/my_kibana_role" { "metadata" : { "version" : 1 @@ -127,9 +125,9 @@ PUT /api/security/role/my_kibana_role Grant dashboard-only access to only the Marketing space: -[source,js] +[source,sh] -------------------------------------------------- -PUT /api/security/role/my_kibana_role +$ curl -X PUT "localhost:5601/api/security/role/my_kibana_role" { "metadata" : { "version" : 1 @@ -155,9 +153,9 @@ PUT /api/security/role/my_kibana_role Grant full access to all features in the Default space: -[source,js] +[source,sh] -------------------------------------------------- -PUT /api/security/role/my_kibana_role +$ curl -X PUT "localhost:5601/api/security/role/my_kibana_role" { "metadata" : { "version" : 1 @@ -182,9 +180,9 @@ PUT /api/security/role/my_kibana_role Grant different access to different spaces: -[source,js] +[source,sh] -------------------------------------------------- -PUT /api/security/role/my_kibana_role +$ curl -X PUT "localhost:5601/api/security/role/my_kibana_role" { "metadata" : { "version" : 1 @@ -216,11 +214,11 @@ PUT /api/security/role/my_kibana_role -------------------------------------------------- // KIBANA -Grant access to {kib} and Elasticsearch: +Grant access to {kib} and {es}: -[source,js] +[source,sh] -------------------------------------------------- -PUT /api/security/role/my_kibana_role +$ curl -X PUT "localhost:5601/api/security/role/my_kibana_role" { "metadata" : { "version" : 1 diff --git a/docs/api/saved-objects/bulk_create.asciidoc b/docs/api/saved-objects/bulk_create.asciidoc index d649684bc30f2..9daba224b317c 100644 --- a/docs/api/saved-objects/bulk_create.asciidoc +++ b/docs/api/saved-objects/bulk_create.asciidoc @@ -9,9 +9,9 @@ experimental[] Create multiple {kib} saved objects. [[saved-objects-api-bulk-create-request]] ==== Request -`POST /api/saved_objects/_bulk_create` +`POST :/api/saved_objects/_bulk_create` -`POST /s//api/saved_objects/_bulk_create` +`POST :/s//api/saved_objects/_bulk_create` [[saved-objects-api-bulk-create-path-params]] @@ -63,9 +63,9 @@ Saved objects that are unable to persist are replaced with an error object. Create an index pattern with the `my-pattern` ID, and a dashboard with the `my-dashboard` ID: -[source,js] +[source,sh] -------------------------------------------------- -POST api/saved_objects/_bulk_create +$ curl -X POST "localhost:5601/api/saved_objects/_bulk_create" [ { "type": "index-pattern", @@ -87,7 +87,7 @@ POST api/saved_objects/_bulk_create The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "saved_objects": [ diff --git a/docs/api/saved-objects/bulk_get.asciidoc b/docs/api/saved-objects/bulk_get.asciidoc index 3ef5823716d79..a6fdeb69ba925 100644 --- a/docs/api/saved-objects/bulk_get.asciidoc +++ b/docs/api/saved-objects/bulk_get.asciidoc @@ -9,9 +9,9 @@ experimental[] Retrieve multiple {kib} saved objects by ID. [[saved-objects-api-bulk-get-request]] ==== Request -`POST /api/saved_objects/_bulk_get` +`POST :/api/saved_objects/_bulk_get` -`POST /s//api/saved_objects/_bulk_get` +`POST :/s//api/saved_objects/_bulk_get` [[saved-objects-api-bulk-get-path-params]] ==== Path parameters @@ -50,9 +50,9 @@ Saved objects that are unable to persist are replaced with an error object. Retrieve an index pattern with the `my-pattern` ID, and a dashboard with the `my-dashboard` ID: -[source,js] +[source,sh] -------------------------------------------------- -POST api/saved_objects/_bulk_get +$ curl -X POST "localhost:5601/api/saved_objects/_bulk_get" [ { "type": "index-pattern", @@ -68,7 +68,7 @@ POST api/saved_objects/_bulk_get The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "saved_objects": [ diff --git a/docs/api/saved-objects/create.asciidoc b/docs/api/saved-objects/create.asciidoc index 634c71bb4eefe..dc010c80fd012 100644 --- a/docs/api/saved-objects/create.asciidoc +++ b/docs/api/saved-objects/create.asciidoc @@ -9,11 +9,11 @@ experimental[] Create {kib} saved objects. [[saved-objects-api-create-request]] ==== Request -`POST /api/saved_objects/` + +`POST :/api/saved_objects/` + -`POST /api/saved_objects//` +`POST :/api/saved_objects//` -`POST /s//saved_objects/` +`POST :/s//saved_objects/` [[saved-objects-api-create-path-params]] ==== Path parameters @@ -55,9 +55,9 @@ any data that you send to the API is properly formed. [[saved-objects-api-create-example]] ==== Example -[source,js] +[source,sh] -------------------------------------------------- -POST api/saved_objects/index-pattern/my-pattern +$ curl -X POST "localhost:5601/api/saved_objects/index-pattern/my-pattern" { "attributes": { "title": "my-pattern-*" @@ -68,7 +68,7 @@ POST api/saved_objects/index-pattern/my-pattern The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "id": "my-pattern", <1> diff --git a/docs/api/saved-objects/delete.asciidoc b/docs/api/saved-objects/delete.asciidoc index c34f9b67dfd22..65c955e15d360 100644 --- a/docs/api/saved-objects/delete.asciidoc +++ b/docs/api/saved-objects/delete.asciidoc @@ -4,16 +4,16 @@ Delete object ++++ -experimental[] Remove {kib} saved objects. +experimental[] Remove {kib} saved objects. WARNING: Once you delete a saved object, _it cannot be recovered_. [[saved-objects-api-delete-request]] ==== Request -`DELETE /api/saved_objects//` +`DELETE :/api/saved_objects//` -`DELETE /s//api/saved_objects//` +`DELETE :/s//api/saved_objects//` [[saved-objects-api-delete-path-params]] ==== Path parameters @@ -33,12 +33,12 @@ WARNING: Once you delete a saved object, _it cannot be recovered_. `200`:: Indicates a successful call. -==== Examples +==== Example Delete an index pattern object with the `my-pattern` ID: -[source,js] +[source,sh] -------------------------------------------------- -DELETE api/saved_objects/index-pattern/my-pattern +$ curl -X DELETE "localhost:5601/api/saved_objects/index-pattern/my-pattern" -------------------------------------------------- // KIBANA diff --git a/docs/api/saved-objects/export.asciidoc b/docs/api/saved-objects/export.asciidoc index 1b4f50dda2ddb..e8c762b9543a1 100644 --- a/docs/api/saved-objects/export.asciidoc +++ b/docs/api/saved-objects/export.asciidoc @@ -9,9 +9,9 @@ experimental[] Retrieve sets of saved objects that you want to import into {kib} [[saved-objects-api-export-request]] ==== Request -`POST /api/saved_objects/_export` +`POST :/api/saved_objects/_export` -`POST /s//api/saved_objects/_export` +`POST :/s//api/saved_objects/_export` [[saved-objects-api-export-path-params]] ==== Path parameters @@ -39,7 +39,7 @@ TIP: You must include `type` or `objects` in the request body. [[saved-objects-api-export-request-response-body]] ==== Response body -The format of the response body is newline delimited JSON. Each exported object is exported as a valid JSON record and separated by the newline character '\n'. +The format of the response body is newline delimited JSON. Each exported object is exported as a valid JSON record and separated by the newline character '\n'. When `excludeExportDetails=false` (the default) we append an export result details record at the end of the file after all the saved object records. The export result details object has the following format: @@ -66,9 +66,9 @@ When `excludeExportDetails=false` (the default) we append an export result detai Export all index pattern saved objects: -[source,js] +[source,sh] -------------------------------------------------- -POST api/saved_objects/_export +$ curl -X POST "localhost:5601/api/saved_objects/_export" { "type": "index-pattern" } @@ -77,9 +77,9 @@ POST api/saved_objects/_export Export all index pattern saved objects and exclude the export summary from the stream: -[source,js] +[source,sh] -------------------------------------------------- -POST api/saved_objects/_export +$ curl -X POST "localhost:5601/api/saved_objects/_export" { "type": "index-pattern", "excludeExportDetails": true @@ -89,9 +89,9 @@ POST api/saved_objects/_export Export a specific saved object: -[source,js] +[source,sh] -------------------------------------------------- -POST api/saved_objects/_export +$ curl -X POST "localhost:5601/api/saved_objects/_export" { "objects": [ { @@ -105,9 +105,9 @@ POST api/saved_objects/_export Export a specific saved object and it's related objects : -[source,js] +[source,sh] -------------------------------------------------- -POST api/saved_objects/_export +$ curl -X POST "localhost:5601/api/saved_objects/_export" { "objects": [ { diff --git a/docs/api/saved-objects/find.asciidoc b/docs/api/saved-objects/find.asciidoc index 955c50922fde7..93e60be5d4923 100644 --- a/docs/api/saved-objects/find.asciidoc +++ b/docs/api/saved-objects/find.asciidoc @@ -9,9 +9,9 @@ experimental[] Retrieve a paginated set of {kib} saved objects by various condit [[saved-objects-api-find-request]] ==== Request -`GET /api/saved_objects/_find` +`GET :/api/saved_objects/_find` -`GET /s//api/saved_objects/_find` +`GET :/s//api/saved_objects/_find` [[saved-objects-api-find-path-params]] ==== Path parameters @@ -67,15 +67,15 @@ change. Use the find API for traditional paginated results, but avoid using it t Find index patterns with titles that start with `my`: -[source,js] +[source,sh] -------------------------------------------------- -GET api/saved_objects/_find?type=index-pattern&search_fields=title&search=my* +$ curl -X GET "localhost:5601/api/saved_objects/_find?type=index-pattern&search_fields=title&search=my*" -------------------------------------------------- // KIBANA The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "total": 1, @@ -95,8 +95,8 @@ The API returns the following: For parameters that accept multiple values (e.g. `fields`), repeat the query parameter for each value: -[source,js] +[source,sh] -------------------------------------------------- -GET api/saved_objects/_find?fields=id&fields=title +$ curl -X GET "localhost:5601/api/saved_objects/_find?fields=id&fields=title" -------------------------------------------------- // KIBANA diff --git a/docs/api/saved-objects/get.asciidoc b/docs/api/saved-objects/get.asciidoc index 29f8ef67e0a83..86b86795b534f 100644 --- a/docs/api/saved-objects/get.asciidoc +++ b/docs/api/saved-objects/get.asciidoc @@ -9,9 +9,9 @@ experimental[] Retrieve a single {kib} saved object by ID. [[saved-objects-api-get-request]] ==== Request -`GET /api/saved_objects//` +`GET :/api/saved_objects//` -`GET /s//api/saved_objects//` +`GET :/s//api/saved_objects//` [[saved-objects-api-get-params]] ==== Path parameters @@ -37,15 +37,15 @@ experimental[] Retrieve a single {kib} saved object by ID. Retrieve the index pattern object with the `my-pattern` ID: -[source,js] +[source,sh] -------------------------------------------------- -GET api/saved_objects/index-pattern/my-pattern +$ curl -X GET "localhost:5601/api/saved_objects/index-pattern/my-pattern" -------------------------------------------------- // KIBANA The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "id": "my-pattern", @@ -57,17 +57,17 @@ The API returns the following: } -------------------------------------------------- -The following example retrieves a dashboard object in the `testspace` by id. +Retrieve a dashboard object in the `testspace` by ID: -[source,js] +[source,sh] -------------------------------------------------- -GET /s/testspace/api/saved_objects/dashboard/7adfa750-4c81-11e8-b3d7-01146121b73d +$ curl -X GET "localhost:5601/s/testspace/api/saved_objects/dashboard/7adfa750-4c81-11e8-b3d7-01146121b73d" -------------------------------------------------- // KIBANA The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "id": "7adfa750-4c81-11e8-b3d7-01146121b73d", diff --git a/docs/api/saved-objects/import.asciidoc b/docs/api/saved-objects/import.asciidoc index 1a380830ed21a..b3e4c48696a17 100644 --- a/docs/api/saved-objects/import.asciidoc +++ b/docs/api/saved-objects/import.asciidoc @@ -9,9 +9,9 @@ experimental[] Create sets of {kib} saved objects from a file created by the exp [[saved-objects-api-import-request]] ==== Request -`POST /api/saved_objects/_import` +`POST :/api/saved_objects/_import` -`POST /s//api/saved_objects/_import` +`POST :/s//api/saved_objects/_import` [[saved-objects-api-import-path-params]] ==== Path parameters @@ -55,14 +55,15 @@ The request body must include the multipart/form-data type. Import an index pattern and dashboard: -[source,js] +[source,sh] -------------------------------------------------- $ curl -X POST "localhost:5601/api/saved_objects/_import" -H "kbn-xsrf: true" --form file=@file.ndjson -------------------------------------------------- +// KIBANA The `file.ndjson` file contains the following: -[source,js] +[source,sh] -------------------------------------------------- {"type":"index-pattern","id":"my-pattern","attributes":{"title":"my-pattern-*"}} {"type":"dashboard","id":"my-dashboard","attributes":{"title":"Look at my dashboard"}} @@ -70,7 +71,7 @@ The `file.ndjson` file contains the following: The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "success": true, @@ -80,14 +81,15 @@ The API returns the following: Import an index pattern and dashboard that includes a conflict on the index pattern: -[source,js] +[source,sh] -------------------------------------------------- $ curl -X POST "localhost:5601/api/saved_objects/_import" -H "kbn-xsrf: true" --form file=@file.ndjson -------------------------------------------------- +// KIBANA The `file.ndjson` file contains the following: -[source,js] +[source,sh] -------------------------------------------------- {"type":"index-pattern","id":"my-pattern","attributes":{"title":"my-pattern-*"}} {"type":"dashboard","id":"my-dashboard","attributes":{"title":"Look at my dashboard"}} @@ -95,7 +97,7 @@ The `file.ndjson` file contains the following: The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "success": false, @@ -115,14 +117,15 @@ The API returns the following: Import a visualization and dashboard with an index pattern for the visualization reference that doesn't exist: -[source,js] +[source,sh] -------------------------------------------------- $ curl -X POST "localhost:5601/api/saved_objects/_import" -H "kbn-xsrf: true" --form file=@file.ndjson -------------------------------------------------- +// KIBANA The `file.ndjson` file contains the following: -[source,js] +[source,sh] -------------------------------------------------- {"type":"visualization","id":"my-vis","attributes":{"title":"my-vis"},"references":[{"name":"ref_0","type":"index-pattern","id":"my-pattern-*"}]} {"type":"dashboard","id":"my-dashboard","attributes":{"title":"Look at my dashboard"},"references":[{"name":"ref_0","type":"visualization","id":"my-vis"}]} @@ -130,7 +133,7 @@ The `file.ndjson` file contains the following: The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- "success": false, "successCount": 0, diff --git a/docs/api/saved-objects/resolve_import_errors.asciidoc b/docs/api/saved-objects/resolve_import_errors.asciidoc index b64e5deb361b2..ec03917390d36 100644 --- a/docs/api/saved-objects/resolve_import_errors.asciidoc +++ b/docs/api/saved-objects/resolve_import_errors.asciidoc @@ -17,9 +17,9 @@ To resolve errors, you can: [[saved-objects-api-resolve-import-errors-request]] ==== Request -`POST /api/saved_objects/_resolve_import_errors` +`POST :/api/saved_objects/_resolve_import_errors` -`POST /s//api/saved_objects/_resolve_import_errors` +`POST :/s//api/saved_objects/_resolve_import_errors` [[saved-objects-api-resolve-import-errors-path-params]] ==== Path parameters @@ -61,21 +61,22 @@ The request body must include the multipart/form-data type. Retry a dashboard import: -[source,js] +[source,sh] -------------------------------------------------- $ curl -X POST "localhost:5601/api/saved_objects/_resolve_import_errors" -H "kbn-xsrf: true" --form file=@file.ndjson --form retries='[{"type":"dashboard","id":"my-dashboard"}]' -------------------------------------------------- +// KIBANA The `file.ndjson` file contains the following: -[source,js] +[source,sh] -------------------------------------------------- {"type":"dashboard","id":"my-dashboard","attributes":{"title":"Look at my dashboard"}} -------------------------------------------------- The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "success": true, @@ -85,14 +86,15 @@ The API returns the following: Resolve errors for a dashboard and overwrite the existing saved object: -[source,js] +[source,sh] -------------------------------------------------- $ curl -X POST "localhost:5601/api/saved_objects/_resolve_import_errors" -H "kbn-xsrf: true" --form file=@file.ndjson --form retries='[{"type":"dashboard","id":"my-dashboard","overwrite":true}]' -------------------------------------------------- +// KIBANA The `file.ndjson` file contains the following: -[source,js] +[source,sh] -------------------------------------------------- {"type":"index-pattern","id":"my-pattern","attributes":{"title":"my-pattern-*"}} {"type":"dashboard","id":"my-dashboard","attributes":{"title":"Look at my dashboard"}} @@ -100,7 +102,7 @@ The `file.ndjson` file contains the following: The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "success": true, @@ -110,21 +112,22 @@ The API returns the following: Resolve errors for a visualization by replacing the index pattern with another: -[source,js] +[source,sh] -------------------------------------------------- $ curl -X POST "localhost:5601/api/saved_objects/_resolve_import_errors" -H "kbn-xsrf: true" --form file=@file.ndjson --form retries='[{"type":"visualization","id":"my-vis","replaceReferences":[{"type":"index-pattern","from":"missing","to":"existing"}]}]' -------------------------------------------------- +// KIBANA The `file.ndjson` file contains the following: -[source,js] +[source,sh] -------------------------------------------------- {"type":"visualization","id":"my-vis","attributes":{"title":"Look at my visualization"},"references":[{"name":"ref_0","type":"index-pattern","id":"missing"}]} -------------------------------------------------- The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "success": true, diff --git a/docs/api/saved-objects/update.asciidoc b/docs/api/saved-objects/update.asciidoc index 99a9bd4ad15bb..62f4104debc77 100644 --- a/docs/api/saved-objects/update.asciidoc +++ b/docs/api/saved-objects/update.asciidoc @@ -9,9 +9,9 @@ experimental[] Update the attributes for existing {kib} saved objects. [[saved-objects-api-update-request]] ==== Request -`PUT /api/saved_objects//` +`PUT :/api/saved_objects//` -`PUT /s//api/saved_objects//` +`PUT :/s//api/saved_objects//` [[saved-objects-api-update-path-params]] ==== Path parameters @@ -47,9 +47,9 @@ WARNING: When you update, attributes are not validated, which allows you to pass Update an existing index pattern object,`my-pattern`, with a different title: -[source,js] +[source,sh] -------------------------------------------------- -PUT api/saved_objects/index-pattern/my-pattern +$ curl -X PUT "localhost:5601/api/saved_objects/index-pattern/my-pattern" { "attributes": { "title": "some-other-pattern-*" @@ -60,7 +60,7 @@ PUT api/saved_objects/index-pattern/my-pattern The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "id": "my-pattern", diff --git a/docs/api/spaces-management/copy_saved_objects.asciidoc b/docs/api/spaces-management/copy_saved_objects.asciidoc index c07b5f35efe09..e23a137485b2d 100644 --- a/docs/api/spaces-management/copy_saved_objects.asciidoc +++ b/docs/api/spaces-management/copy_saved_objects.asciidoc @@ -5,225 +5,75 @@ Copy saved objects to space ++++ -experimental["The underlying Spaces concepts are stable, but the APIs for managing Spaces are experimental."] - -//// -Use the appropriate heading levels for your book. -Add anchors for each section. -FYI: The section titles use attributes in case those terms change. -//// - -[[spaces-api-copy-saved-objects-request]] -==== {api-request-title} -//// -This section show the basic endpoint, without the body or optional parameters. -Variables should use <...> syntax. -If an API supports both PUT and POST, include both here. -//// - -`POST /api/spaces/_copy_saved_objects` - -`POST /s//api/spaces/_copy_saved_objects` - - -//// -[[spaces-api-copy-saved-objects-prereqs]] -==== {api-prereq-title} -//// -//// -Optional list of prerequisites. - -For example: - -* A snapshot of an index created in 5.x can be restored to 6.x. You must... -* If the {es} {security-features} are enabled, you must have `write`, `monitor`, -and `manage_follow_index` index privileges... -//// - - -[[spaces-api-copy-saved-objects-desc]] -==== {api-description-title} - -Copy saved objects between spaces. +experimental[] Copy saved objects between spaces. It also allows you to automatically copy related objects, so when you copy a `dashboard`, this can automatically copy over the associated visualizations, index patterns, and saved searches, as required. -You can request to overwrite any objects that already exist in the target space if they share an ID, or you can use the +You can request to overwrite any objects that already exist in the target space if they share an ID, or you can use the <> to do this on a per-object basis. -//// -Add a more detailed description the context. -Link to related APIs if appropriate. +[[spaces-api-copy-saved-objects-request]] +==== {api-request-title} -Guidelines for parameter documentation -*************************************** -* Use a definition list. -* End each definition with a period. -* Include whether the parameter is Optional or Required and the data type. -* Include default values as the last sentence of the first paragraph. -* Include a range of valid values, if applicable. -* If the parameter requires a specific delimiter for multiple values, say so. -* If the parameter supports wildcards, ditto. -* For large or nested objects, consider linking to a separate definition list. -*************************************** -//// +`POST :/api/spaces/_copy_saved_objects` +`POST :/s//api/spaces/_copy_saved_objects` [[spaces-api-copy-saved-objects-path-params]] ==== {api-path-parms-title} -//// -A list of all the parameters within the path of the endpoint (before the query string (?)). -For example: -``:: -(Required, string) Name of the follower index -//// `space_id`:: -(Optional, string) Identifies the source space from which saved objects will be copied. If `space_id` is not specified in the URL, the default space is used. - -//// -[[spaces-api-copy-saved-objects-params]] -==== {api-query-parms-title} -//// -//// -A list of the parameters in the query string of the endpoint (after the ?). - -For example: -`wait_for_active_shards`:: -(Optional, integer) Specifies the number of shards to wait on being active before -responding. A shard must be restored from the leader index being active. -Restoring a follower shard requires transferring all the remote Lucene segment -files to the follower index. The default is `0`, which means waiting on none of -the shards to be active. -//// +(Optional, string) The ID of the space that contains the saved objects you want to copy. When `space_id` is unspecified in the URL, the default space is used. [[spaces-api-copy-saved-objects-request-body]] ==== {api-request-body-title} -//// -A list of the properties you can specify in the body of the request. -For example: -`remote_cluster`:: -(Required, string) The <> that contains -the leader index. +`spaces`:: + (Required, string array) The IDs of the spaces where you want to copy the specified objects. -`leader_index`:: -(Required, string) The name of the index in the leader cluster to follow. -//// -`spaces` :: - (Required, string array) The ids of the spaces the specified object(s) will be copied into. - -`objects` :: +`objects`:: (Required, object array) The saved objects to copy. - `type` ::: + `type`::: (Required, string) The saved object type. - `id` ::: - (Required, string) The saved object id. + `id`::: + (Required, string) The saved object ID. -`includeReferences` :: +`includeReferences`:: (Optional, boolean) When set to `true`, all saved objects related to the specified saved objects will also be copied into the target spaces. The default value is `false`. -`overwrite` :: - (Optional, boolean) When set to `true`, all conflicts will be automatically overidden. If a saved object with a matching `type` and `id` exists in the target space, then that version will be replaced with the version from the source space. The default value is `false`. +`overwrite`:: + (Optional, boolean) When set to `true`, all conflicts are automatically overidden. When a saved object with a matching `type` and `id` exists in the target space, that version is replaced with the version from the source space. The default value is `false`. [[spaces-api-copy-saved-objects-response-body]] ==== {api-response-body-title} -//// -Response body is only required for detailed responses. - -For example: -`auto_follow_stats`:: - (object) An object representing stats for the auto-follow coordinator. This - object consists of the following fields: - -`auto_follow_stats.number_of_successful_follow_indices`::: - (long) the number of indices that the auto-follow coordinator successfully - followed -... - -//// ``:: - (object) Specifies the dynamic keys that are included in the response. An object describing the result of the copy operation for this particular space. + (object) An object that describes the result of the copy operation for the space. Includes the dynamic keys in the response. `success`::: - (boolean) Indicates if the copy operation was successful. Note that some objects may have been copied even if this is set to `false`. Consult the `successCount` and `errors` properties of the response for additional information. + (boolean) The copy operation was successful. When set to `false`, some objects may have been copied. For additional information, refer to the `successCount` and `errors` properties. `successCount`::: - (number) The number of objects that were successfully copied. + (number) The number of objects that successfully copied. `errors`::: - (Optional, array) Collection of any errors that were encountered during the copy operation. If any errors are reported, then the `success` flag will be set to `false`. + (Optional, array) The errors that occurred during the copy operation. When errors are reported, the `success` flag is set to `false`.v `id`:::: - (string) The saved object id which failed to copy. + (string) The saved object ID that failed to copy. `type`:::: - (string) The type of saved object which failed to copy. + (string) The type of saved object that failed to copy. `error`:::: - (object) The error which caused the copy operation to fail. + (object) The error that caused the copy operation to fail. `type`::::: - (string) Indicates the type of error. May be one of: `conflict`, `unsupported_type`, `missing_references`, `unknown`. Errors marked as `conflict` may be resolved by using the <>. - -//// -[[spaces-api-copy-saved-objects-response-codes]] -==== {api-response-codes-title} -//// -//// -Response codes are only required when needed to understand the response body. - -For example: -`200`:: -Indicates all listed indices or index aliases exist. - - `404`:: -Indicates one or more listed indices or index aliases **do not** exist. -//// - + (string) The type of error. For example, `unsupported_type`, `missing_references`, or `unknown`. Errors marked as `conflict` may be resolved by using the <>. [[spaces-api-copy-saved-objects-example]] ==== {api-examples-title} -//// -Optional brief example. -Use an 'Examples' heading if you include multiple examples. +Copy a dashboard with the `my-dashboard` ID, including all references from the `default` space to the `marketing` and `sales` spaces: -[source,js] +[source,sh] ---- -PUT /follower_index/_ccr/follow?wait_for_active_shards=1 -{ - "remote_cluster" : "remote_cluster", - "leader_index" : "leader_index", - "max_read_request_operation_count" : 1024, - "max_outstanding_read_requests" : 16, - "max_read_request_size" : "1024k", - "max_write_request_operation_count" : 32768, - "max_write_request_size" : "16k", - "max_outstanding_write_requests" : 8, - "max_write_buffer_count" : 512, - "max_write_buffer_size" : "512k", - "max_retry_delay" : "10s", - "read_poll_timeout" : "30s" -} ----- -// CONSOLE -// TEST[setup:remote_cluster_and_leader_index] - -The API returns the following result: - -[source,js] ----- -{ - "follow_index_created" : true, - "follow_index_shards_acked" : true, - "index_following_started" : true -} ----- -// TESTRESPONSE -//// - -The following example attempts to copy a dashboard with id `my-dashboard`, including all references from the `default` space to the `marketing` and `sales` spaces. The `marketing` space succeeds, while the `sales` space fails due to a conflict on the underlying index pattern: - -[source,js] ----- -POST /api/spaces/_copy_saved_objects +$ curl -X POST "localhost:5601/api/spaces/_copy_saved_objects" { "objects": [{ "type": "dashboard", @@ -235,9 +85,9 @@ POST /api/spaces/_copy_saved_objects ---- // KIBANA -The API returns the following result: +The API returns the following: -[source,js] +[source,sh] ---- { "marketing": { @@ -258,11 +108,13 @@ The API returns the following result: } ---- -The following example successfully copies a visualization with id `my-viz` from the `marketing` space to the `default` space: +The `marketing` space succeeds, but the `sales` space fails due to a conflict in the index pattern. + +Copy a visualization with the `my-viz` ID from the `marketing` space to the `default` space: -[source,js] +[source,sh] ---- -POST /s/marketing/api/spaces/_copy_saved_objects +$ curl -X POST "localhost:5601/s/marketing/api/spaces/_copy_saved_objects" { "objects": [{ "type": "visualization", @@ -273,9 +125,9 @@ POST /s/marketing/api/spaces/_copy_saved_objects ---- // KIBANA -The API returns the following result: +The API returns the following: -[source,js] +[source,sh] ---- { "default": { diff --git a/docs/api/spaces-management/delete.asciidoc b/docs/api/spaces-management/delete.asciidoc index c66307ea3070f..5b4db78c056dd 100644 --- a/docs/api/spaces-management/delete.asciidoc +++ b/docs/api/spaces-management/delete.asciidoc @@ -4,22 +4,20 @@ Delete space ++++ -Delete a {kib} space. +experimental[] Delete a {kib} space. -experimental["The underlying Spaces concepts are stable, but the APIs for managing Spaces are experimental."] - -WARNING: When you delete a space, all saved objects that belong to the space are automatically deleted, which is permanent and cannot be undone. +WARNING: When you delete a space, all saved objects that belong to the space are automatically deleted, which is permanent and cannot be undone. [[spaces-api-delete-request]] ==== Request -`DELETE /api/spaces/space/marketing` +`DELETE :/api/spaces/space/marketing` [[spaces-api-delete-errors-codes]] ==== Response codes -`204`:: +`204`:: Indicates a successful call. - + `404`:: Indicates that the request failed. diff --git a/docs/api/spaces-management/get.asciidoc b/docs/api/spaces-management/get.asciidoc index 49119d7602b20..48245b7786604 100644 --- a/docs/api/spaces-management/get.asciidoc +++ b/docs/api/spaces-management/get.asciidoc @@ -4,14 +4,12 @@ Get space ++++ -Retrieve a specified {kib} space. - -experimental["The underlying Spaces concepts are stable, but the APIs for managing Spaces are experimental."] +experimental[] Retrieve a specified {kib} space. [[spaces-api-get-request]] ==== Request -`GET /api/spaces/space/marketing` +`GET :/api/spaces/space/marketing` [[spaces-api-get-response-codes]] ==== Response code @@ -24,7 +22,7 @@ experimental["The underlying Spaces concepts are stable, but the APIs for managi The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "id": "marketing", @@ -35,4 +33,4 @@ The API returns the following: "disabledFeatures": [], "imageUrl": "" } --------------------------------------------------- \ No newline at end of file +-------------------------------------------------- diff --git a/docs/api/spaces-management/get_all.asciidoc b/docs/api/spaces-management/get_all.asciidoc index f7fb92baa165f..8f7ba86f332de 100644 --- a/docs/api/spaces-management/get_all.asciidoc +++ b/docs/api/spaces-management/get_all.asciidoc @@ -4,14 +4,12 @@ Get all spaces ++++ -Retrieve all {kib} spaces. - -experimental["The underlying Spaces concepts are stable, but the APIs for managing Spaces are experimental."] +experimental[] Retrieve all {kib} spaces. [[spaces-api-get-all-request]] ==== Request -`GET /api/spaces/space` +`GET :/api/spaces/space` [[spaces-api-get-all-response-codes]] ==== Response code @@ -24,7 +22,7 @@ experimental["The underlying Spaces concepts are stable, but the APIs for managi The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- [ { diff --git a/docs/api/spaces-management/post.asciidoc b/docs/api/spaces-management/post.asciidoc index 4d4627e98899e..b96fbe6364c34 100644 --- a/docs/api/spaces-management/post.asciidoc +++ b/docs/api/spaces-management/post.asciidoc @@ -4,14 +4,12 @@ Create space ++++ -Create a {kib} space. - -experimental["The underlying Spaces concepts are stable, but the APIs for managing Spaces are experimental."] +experimental[] Create a {kib} space. [[spaces-api-post-request]] ==== Request -`POST /api/spaces/space` +`POST :/api/spaces/space` [[spaces-api-post-request-body]] ==== Request body @@ -29,13 +27,13 @@ experimental["The underlying Spaces concepts are stable, but the APIs for managi (Optional, string array) The list of disabled features for the space. To get a list of available feature IDs, use the <>. `initials`:: - (Optional, string) Specifies the initials shown in the space avatar. By default, the initials are automatically generated from the space name. Initials must be 1 or 2 characters. + (Optional, string) The initials shown in the space avatar. By default, the initials are automatically generated from the space name. Initials must be 1 or 2 characters. `color`:: - (Optional, string) Specifies the hexadecimal color code used in the space avatar. By default, the color is automatically generated from the space name. + (Optional, string) The hexadecimal color code used in the space avatar. By default, the color is automatically generated from the space name. `imageUrl`:: - (Optional, string) Specifies the data-url encoded image to display in the space avatar. If specified, `initials` will not be displayed, and the `color` will be visible as the background color for transparent images. + (Optional, string) The data-URL encoded image to display in the space avatar. If specified, `initials` will not be displayed, and the `color` will be visible as the background color for transparent images. For best results, your image should be 64x64. Images will not be optimized by this API call, so care should be taken when using custom images. [[spaces-api-post-response-codes]] @@ -47,9 +45,9 @@ experimental["The underlying Spaces concepts are stable, but the APIs for managi [[spaces-api-post-example]] ==== Example -[source,js] +[source,sh] -------------------------------------------------- -POST /api/spaces/space +$ curl -X POST "localhost:5601/api/spaces/space" { "id": "marketing", "name": "Marketing", diff --git a/docs/api/spaces-management/put.asciidoc b/docs/api/spaces-management/put.asciidoc index 586818707c76f..f405d57975a70 100644 --- a/docs/api/spaces-management/put.asciidoc +++ b/docs/api/spaces-management/put.asciidoc @@ -4,37 +4,35 @@ Update space ++++ -Update an existing {kib} space. - -experimental["The underlying Spaces concepts are stable, but the APIs for managing Spaces are experimental."] +experimental[] Update an existing {kib} space. [[spaces-api-put-api-request]] ==== Request -`PUT /api/spaces/space/` +`PUT :/api/spaces/space/` [[spaces-api-put-request-body]] ==== Request body -`id`:: +`id`:: (Required, string) The space ID that is part of the {kib} URL when inside the space. You are unable to change the ID with the update operation. -`name`:: +`name`:: (Required, string) The display name for the space. -`description`:: +`description`:: (Optional, string) The description for the space. -`disabledFeatures`:: +`disabledFeatures`:: (Optional, string array) The list of disabled features for the space. To get a list of available feature IDs, use the <>. -`initials`:: +`initials`:: (Optional, string) Specifies the initials shown in the space avatar. By default, the initials are automatically generated from the space name. Initials must be 1 or 2 characters. -`color`:: +`color`:: (Optional, string) Specifies the hexadecimal color code used in the space avatar. By default, the color is automatically generated from the space name. -`imageUrl`:: +`imageUrl`:: (Optional, string) Specifies the data-url encoded image to display in the space avatar. If specified, `initials` will not be displayed, and the `color` will be visible as the background color for transparent images. For best results, your image should be 64x64. Images will not be optimized by this API call, so care should be taken when using custom images. @@ -43,13 +41,13 @@ experimental["The underlying Spaces concepts are stable, but the APIs for managi `200`:: Indicates a successful call. - + [[sample-api-example]] ==== Example -[source,js] +[source,sh] -------------------------------------------------- -PUT /api/spaces/space/marketing +$ curl -X PUT "localhost:5601/api/spaces/space/marketing" { "id": "marketing", "name": "Marketing", diff --git a/docs/api/spaces-management/resolve_copy_saved_objects_conflicts.asciidoc b/docs/api/spaces-management/resolve_copy_saved_objects_conflicts.asciidoc index 7b52125599c05..8e874bb9f94e5 100644 --- a/docs/api/spaces-management/resolve_copy_saved_objects_conflicts.asciidoc +++ b/docs/api/spaces-management/resolve_copy_saved_objects_conflicts.asciidoc @@ -5,227 +5,80 @@ Resolve copy to space conflicts ++++ -Overwrite specific saved objects that were returned as errors from the <>. - -experimental["The underlying Spaces concepts are stable, but the APIs for managing Spaces are experimental."] - -//// -Use the appropriate heading levels for your book. -Add anchors for each section. -FYI: The section titles use attributes in case those terms change. -//// +experimental[] Overwrite saved objects that are returned as errors from the <>. [[spaces-api-resolve-copy-saved-objects-conflicts-request]] ==== {api-request-title} -//// -This section show the basic endpoint, without the body or optional parameters. -Variables should use <...> syntax. -If an API supports both PUT and POST, include both here. -//// - -`POST /api/spaces/_resolve_copy_saved_objects_errors` - -`POST /s//api/spaces/_resolve_copy_saved_objects_errors` +`POST :/api/spaces/_resolve_copy_saved_objects_errors` +`POST :/s//api/spaces/_resolve_copy_saved_objects_errors` [[spaces-api-resolve-copy-saved-objects-conflicts-prereqs]] ==== {api-prereq-title} -//// -Optional list of prerequisites. - -For example: - -* A snapshot of an index created in 5.x can be restored to 6.x. You must... -* If the {es} {security-features} are enabled, you must have `write`, `monitor`, -and `manage_follow_index` index privileges... -//// -* Executed the <>, which returned one or more `conflict` errors that you wish to resolve. - -//// -[[spaces-api-resolve-copy-saved-objects-conflicts-desc]] -==== {api-description-title} - -Allows saved objects to be selectively overridden in the target spaces. -//// - -//// -Add a more detailed description the context. -Link to related APIs if appropriate. - -Guidelines for parameter documentation -*************************************** -* Use a definition list. -* End each definition with a period. -* Include whether the parameter is Optional or Required and the data type. -* Include default values as the last sentence of the first paragraph. -* Include a range of valid values, if applicable. -* If the parameter requires a specific delimiter for multiple values, say so. -* If the parameter supports wildcards, ditto. -* For large or nested objects, consider linking to a separate definition list. -*************************************** -//// +Execute the <>, which returns the errors for you to resolve. [[spaces-api-resolve-copy-saved-objects-conflicts-path-params]] ==== {api-path-parms-title} -//// -A list of all the parameters within the path of the endpoint (before the query string (?)). -For example: -``:: -(Required, string) Name of the follower index -//// `space_id`:: -(Optional, string) Identifies the source space from which saved objects will be copied. If `space_id` is not specified in the URL, the default space is used. Must be the same value that was used during the failed <> operation. - -//// -[[spaces-api-resolve-copy-saved-objects-conflicts-request-params]] -==== {api-query-parms-title} -//// -//// -A list of the parameters in the query string of the endpoint (after the ?). - -For example: -`wait_for_active_shards`:: -(Optional, integer) Specifies the number of shards to wait on being active before -responding. A shard must be restored from the leader index being active. -Restoring a follower shard requires transferring all the remote Lucene segment -files to the follower index. The default is `0`, which means waiting on none of -the shards to be active. -//// +(Optional, string) The ID of the space that contains the saved objects you want to copy. When `space_id` is unspecified in the URL, the default space is used. The `space_id` must be the same value used during the failed <> operation. [[spaces-api-resolve-copy-saved-objects-conflicts-request-body]] ==== {api-request-body-title} -//// -A list of the properties you can specify in the body of the request. - -For example: -`remote_cluster`:: -(Required, string) The <> that contains -the leader index. -`leader_index`:: -(Required, string) The name of the index in the leader cluster to follow. -//// -`objects` :: - (Required, object array) The saved objects to copy. Must be the same value that was used during the failed <> operation. - `type` ::: +`objects`:: + (Required, object array) The saved objects to copy. The `objects` must be the same values used during the failed <> operation. + `type`::: (Required, string) The saved object type. - `id` ::: - (Required, string) The saved object id. + `id`::: + (Required, string) The saved object ID. -`includeReferences` :: - (Optional, boolean) When set to `true`, all saved objects related to the specified saved objects will also be copied into the target spaces. You must set this to the same value that you used when executing the <>. The default value is `false`. +`includeReferences`:: + (Optional, boolean) When set to `true`, all saved objects related to the specified saved objects are copied into the target spaces. The `includeReferences` must be the same values used during the failed <> operation. The default value is `false`. `retries`:: - (Required, object) The retry operations to attempt. Object keys represent the target space ids. - `` ::: - (Required, array) The the conflicts to resolve for the indicated ``. - `type` :::: + (Required, object) The retry operations to attempt. Object keys represent the target space IDs. + ``::: + (Required, array) The errors to resolve for the specified ``. + `type`:::: (Required, string) The saved object type. - `id` :::: - (Required, string) The saved object id. - `overwrite` :::: - (Required, boolean) when set to `true`, the saved object from the source space (desigated by the <>) will overwrite the the conflicting object in the destination space. When `false`, this does nothing. + `id`:::: + (Required, string) The saved object ID. + `overwrite`:::: + (Required, boolean) When set to `true`, the saved object from the source space (desigated by the <>) overwrites the conflicting object in the destination space. When set to `false`, this does nothing. [[spaces-api-resolve-copy-saved-objects-conflicts-response-body]] ==== {api-response-body-title} -//// -Response body is only required for detailed responses. - -For example: -`auto_follow_stats`:: - (object) An object representing stats for the auto-follow coordinator. This - object consists of the following fields: - -`auto_follow_stats.number_of_successful_follow_indices`::: - (long) the number of indices that the auto-follow coordinator successfully - followed -... - -//// ``:: - (object) Specifies the dynamic keys that are included in the response. An object describing the result of the copy operation for this particular space. + (object) An object that describes the result of the copy operation for the space. Includes the dynamic keys in the response. `success`::: - (boolean) Indicates if the copy operation was successful. Note that some objects may have been copied even if this is set to `false`. Consult the `successCount` and `errors` properties of the response for additional information. + (boolean) The copy operation was successful. When set to `false`, some objects may have been copied. For additional information, refer to the `successCount` and `errors` properties. `successCount`::: - (number) The number of objects that were successfully copied. + (number) The number of objects that successfully copied. `errors`::: - (Optional, array) Collection of any errors that were encountered during the copy operation. If any errors are reported, then the `success` flag will be set to `false`. + (Optional, array) The errors that occurred during the copy operation. When errors are reported, the `success` flag is set to `false`. `id`:::: - (string) The saved object id which failed to copy. + (string) The saved object ID that failed to copy. `type`:::: - (string) The type of saved object which failed to copy. + (string) The type of saved object that failed to copy. `error`:::: - (object) The error which caused the copy operation to fail. + (object) The error that caused the copy operation to fail. `type`::::: - (string) Indicates the type of error. May be one of: `unsupported_type`, `missing_references`, `unknown`. - -//// -[[spaces-api-resolve-copy-saved-objects-conflicts-response-codes]] -==== {api-response-codes-title} -//// -//// -Response codes are only required when needed to understand the response body. - -For example: -`200`:: -Indicates all listed indices or index aliases exist. - - `404`:: -Indicates one or more listed indices or index aliases **do not** exist. -//// + (string) The type of error. For example, `unsupported_type`, `missing_references`, or `unknown`. [[spaces-api-resolve-copy-saved-objects-conflicts-example]] ==== {api-examples-title} -//// -Optional brief example. -Use an 'Examples' heading if you include multiple examples. - - -[source,js] ----- -PUT /follower_index/_ccr/follow?wait_for_active_shards=1 -{ - "remote_cluster" : "remote_cluster", - "leader_index" : "leader_index", - "max_read_request_operation_count" : 1024, - "max_outstanding_read_requests" : 16, - "max_read_request_size" : "1024k", - "max_write_request_operation_count" : 32768, - "max_write_request_size" : "16k", - "max_outstanding_write_requests" : 8, - "max_write_buffer_count" : 512, - "max_write_buffer_size" : "512k", - "max_retry_delay" : "10s", - "read_poll_timeout" : "30s" -} ----- -// CONSOLE -// TEST[setup:remote_cluster_and_leader_index] - -The API returns the following result: - -[source,js] ----- -{ - "follow_index_created" : true, - "follow_index_shards_acked" : true, - "index_following_started" : true -} ----- -// TESTRESPONSE -//// -The following example overwrites an index pattern in the marketing space, and a visualization in the sales space. +Overwrite an index pattern in the `marketing` space, and a visualization in the `sales` space: -[source,js] +[source,sh] ---- -POST api/spaces/_resolve_copy_saved_objects_errors +$ curl -X POST "localhost:5601/api/spaces/_resolve_copy_saved_objects_errors" { "objects": [{ "type": "dashboard", @@ -248,9 +101,9 @@ POST api/spaces/_resolve_copy_saved_objects_errors ---- // KIBANA -The API returns the following result: +The API returns the following: -[source,js] +[source,sh] ---- { "marketing": { diff --git a/docs/api/upgrade-assistant.asciidoc b/docs/api/upgrade-assistant.asciidoc index 3e9c416b292cf..15d87fbd0dc9d 100644 --- a/docs/api/upgrade-assistant.asciidoc +++ b/docs/api/upgrade-assistant.asciidoc @@ -2,7 +2,7 @@ [[upgrade-assistant-api]] == Upgrade assistant APIs -Check the upgrade status of your Elasticsearch cluster and reindex indices that were created in the previous major version. The assistant helps you prepare for the next major version of Elasticsearch. +Check the upgrade status of your {es} cluster and reindex indices that were created in the previous major version. The assistant helps you prepare for the next major version of {es}. The following upgrade assistant APIs are available: @@ -16,7 +16,7 @@ The following upgrade assistant APIs are available: * <> to check the status of the reindex operation -* <> to cancel reindexes that are waiting for the Elasticsearch reindex task to complete +* <> to cancel reindexes that are waiting for the {es} reindex task to complete include::upgrade-assistant/status.asciidoc[] include::upgrade-assistant/reindexing.asciidoc[] diff --git a/docs/api/upgrade-assistant/cancel_reindex.asciidoc b/docs/api/upgrade-assistant/cancel_reindex.asciidoc index d31894cd06a05..04ab3bdde35fc 100644 --- a/docs/api/upgrade-assistant/cancel_reindex.asciidoc +++ b/docs/api/upgrade-assistant/cancel_reindex.asciidoc @@ -4,14 +4,14 @@ Cancel reindex ++++ -experimental["The underlying Upgrade Assistant concepts are stable, but the APIs for managing Upgrade Assistant are experimental."] +experimental[] Cancel reindexes that are waiting for the {es} reindex task to complete. For example, `lastCompletedStep` set to `40`. Cancel reindexes that are waiting for the Elasticsearch reindex task to complete. For example, `lastCompletedStep` set to `40`. [[cancel-reindex-request]] ==== Request -`POST /api/upgrade_assistant/reindex/myIndex/cancel` +`POST :/api/upgrade_assistant/reindex/myIndex/cancel` [[cancel-reindex-response-codes]] ==== Response codes @@ -24,7 +24,7 @@ Cancel reindexes that are waiting for the Elasticsearch reindex task to complete The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "acknowledged": true diff --git a/docs/api/upgrade-assistant/check_reindex_status.asciidoc b/docs/api/upgrade-assistant/check_reindex_status.asciidoc index c422e5764c69f..00801f201d1e1 100644 --- a/docs/api/upgrade-assistant/check_reindex_status.asciidoc +++ b/docs/api/upgrade-assistant/check_reindex_status.asciidoc @@ -4,27 +4,27 @@ Check reindex status ++++ -experimental["The underlying Upgrade Assistant concepts are stable, but the APIs for managing Upgrade Assistant are experimental."] +experimental[] Check the status of the reindex operation. Check the status of the reindex operation. [[check-reindex-status-request]] ==== Request -`GET /api/upgrade_assistant/reindex/myIndex` +`GET :/api/upgrade_assistant/reindex/myIndex` [[check-reindex-status-response-codes]] ==== Response codes `200`:: Indicates a successful call. - + [[check-reindex-status-example]] ==== Example The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "reindexOp": { @@ -53,59 +53,58 @@ The API returns the following: [[status-code]] ==== Status codes -`0`:: +`0`:: In progress -`1`:: +`1`:: Completed -`2`:: +`2`:: Failed - -`3`:: + +`3`:: Paused NOTE: If the {kib} node that started the reindex is shutdown or restarted, the reindex goes into a paused state after some time. To resume the reindex, you must submit a new POST request to the `/api/upgrade_assistant/reindex/` endpoint. -`4`:: +`4`:: Cancelled [[step-code]] ==== Step codes -`0`:: +`0`:: The reindex operation has been created in Kibana. - -`10`:: + +`10`:: The index group services stopped. Only applies to some system indices. - -`20`:: - The index is set to `readonly`. - -`30`:: + +`20`:: + The index is set to `readonly`. + +`30`:: The new destination index has been created. - -`40`:: + +`40`:: The reindex task in Elasticsearch has started. - -`50`:: + +`50`:: The reindex task in Elasticsearch has completed. - -`60`:: + +`60`:: Aliases were created to point to the new index, and the old index has been deleted. - -`70`:: + +`70`:: The index group services have resumed. Only applies to some system indices. [[warning-code]] ==== Warning codes -`0`:: +`0`:: Specifies to remove the `_all` meta field. - -`1`:: + +`1`:: Specifies to convert any coerced boolean values in the source document. For example, `yes`, `1`, and `off`. - -`2`:: - Specifies to convert documents to support Elastic Common Schema. Only applies to APM indices created in 6.x. +`2`:: + Specifies to convert documents to support Elastic Common Schema. Only applies to APM indices created in 6.x. diff --git a/docs/api/upgrade-assistant/reindexing.asciidoc b/docs/api/upgrade-assistant/reindexing.asciidoc index 51e7b917b67ac..ce5670822e5ad 100644 --- a/docs/api/upgrade-assistant/reindexing.asciidoc +++ b/docs/api/upgrade-assistant/reindexing.asciidoc @@ -4,14 +4,14 @@ Start or resume reindex ++++ -experimental["The underlying Upgrade Assistant concepts are stable, but the APIs for managing Upgrade Assistant are experimental."] +experimental[] Start a new reindex or resume a paused reindex. Start a new reindex or resume a paused reindex. [[start-resume-reindex-request]] ==== Request -`POST /api/upgrade_assistant/reindex/myIndex` +`POST :/api/upgrade_assistant/reindex/myIndex` [[start-resume-reindex-codes]] ==== Response code @@ -24,7 +24,7 @@ Start a new reindex or resume a paused reindex. The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "indexName": ".ml-state", @@ -37,9 +37,9 @@ The API returns the following: } -------------------------------------------------- -<1> Name of the new index that is being created. -<2> Current status of the reindex. For details, see <>. -<3> Last successfully completed step of the reindex. For details, see <> table. -<4> Task ID of the reindex task in Elasticsearch. Only present if reindexing has started. -<5> Percentage of how far the reindexing task in Elasticsearch has progressed, in decimal from from 0 to 1. -<6> Error that caused the reindex to fail, if it failed. +<1> The name of the new index. +<2> The reindex status. For more information, refer to <>. +<3> The last successfully completed step of the reindex. For more information, refer to <>. +<4> The task ID of the reindex task in {es}. Appears when the reindexing starts. +<5> The progress of the reindexing task in {es}. Appears in decimal form, from 0 to 1. +<6> The error that caused the reindex to fail, if it failed. diff --git a/docs/api/upgrade-assistant/status.asciidoc b/docs/api/upgrade-assistant/status.asciidoc index b087a66fa3bcd..42030061c4289 100644 --- a/docs/api/upgrade-assistant/status.asciidoc +++ b/docs/api/upgrade-assistant/status.asciidoc @@ -4,14 +4,14 @@ Upgrade readiness status ++++ -experimental["The underlying Upgrade Assistant concepts are stable, but the APIs for managing Upgrade Assistant are experimental."] +experimental[] Check the status of your cluster. Check the status of your cluster. [[upgrade-assistant-api-status-request]] ==== Request -`GET /api/upgrade_assistant/status` +`GET :/api/upgrade_assistant/status` [[upgrade-assistant-api-status-response-codes]] ==== Response codes @@ -24,7 +24,7 @@ Check the status of your cluster. The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "readyForUpgrade": false, diff --git a/docs/api/url-shortening.asciidoc b/docs/api/url-shortening.asciidoc index 8bc701a3d5d12..a62529e11a9ba 100644 --- a/docs/api/url-shortening.asciidoc +++ b/docs/api/url-shortening.asciidoc @@ -12,18 +12,18 @@ Short URLs are designed to make sharing {kib} URLs easier. [[url-shortening-api-request]] ==== Request -`POST /api/shorten_url` +`POST :/api/shorten_url` [[url-shortening-api-request-body]] ==== Request body `url`:: - (Required, string) The {kib} URL that you want to shorten, Relative to `/app/kibana`. + (Required, string) The {kib} URL that you want to shorten, relative to `/app/kibana`. [[url-shortening-api-response-body]] ==== Response body -urlId:: A top level property that contains the shortened URL token for the provided request body. +urlId:: A top-level property that contains the shortened URL token for the provided request body. [[url-shortening-api-codes]] ==== Response code @@ -31,21 +31,21 @@ urlId:: A top level property that contains the shortened URL token for the provi `200`:: Indicates a successful call. -[[url-shortening-api-example]] +[[url-shortening-api-example]] ==== Example -[source,js] +[source,sh] -------------------------------------------------- -POST api/shorten_url +$ curl -X POST "localhost:5601/api/shorten_url" { "url": "/app/kibana#/dashboard?_g=()&_a=(description:'',filters:!(),fullScreenMode:!f,options:(hidePanelTitles:!f,useMargins:!t),panels:!((embeddableConfig:(),gridData:(h:15,i:'1',w:24,x:0,y:0),id:'8f4d0c00-4c86-11e8-b3d7-01146121b73d',panelIndex:'1',type:visualization,version:'7.0.0-alpha1')),query:(language:lucene,query:''),timeRestore:!f,title:'New%20Dashboard',viewMode:edit)" } -------------------------------------------------- // KIBANA -The API returns the following result: +The API returns the following: -[source,js] +[source,sh] -------------------------------------------------- { "urlId": "f73b295ff92718b26bc94edac766d8e3" diff --git a/docs/api/using-api.asciidoc b/docs/api/using-api.asciidoc index 37c5315025dc4..aba65f2e921c2 100644 --- a/docs/api/using-api.asciidoc +++ b/docs/api/using-api.asciidoc @@ -33,6 +33,7 @@ For example, the following `curl` command exports a dashboard: -- curl -X POST -u $USER:$PASSWORD "localhost:5601/api/kibana/dashboards/export?dashboard=942dcef0-b2cd-11e8-ad8e-85441f0c2e5c" -- +// KIBANA [float] [[api-request-headers]] @@ -43,14 +44,14 @@ For all APIs, you must use a request header. The {kib} APIs support the `kbn-xsr `kbn-xsrf: true`:: By default, you must use `kbn-xsrf` for all API calls, except in the following scenarios: -* The API endpoint uses the `GET` or `HEAD` methods +* The API endpoint uses the `GET` or `HEAD` operations * The path is whitelisted using the <> setting * XSRF protections are disabled using the `server.xsrf.disableProtection` setting `Content-Type: application/json`:: - Applicable only when you send a payload in the API request. {kib} API requests and responses use JSON. Typically, if you include the `kbn-xsrf` header, you must also include the `Content-Type` header. + Applicable only when you send a payload in the API request. {kib} API requests and responses use JSON. Typically, if you include the `kbn-xsrf` header, you must also include the `Content-Type` header. Request header example: diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.filterbar.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.filterbar.md index 016adffd0d7f4..6d8862323792a 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.filterbar.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.filterbar.md @@ -7,7 +7,7 @@ Signature: ```typescript -FilterBar: React.ComponentClass, any> & { +FilterBar: React.ComponentClass, any> & { WrappedComponent: React.ComponentType; } ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md index 58690300b3bd6..d0d4cc491e142 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md @@ -7,5 +7,5 @@ Signature: ```typescript -QueryStringInput: React.FC> +QueryStringInput: React.FC> ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchbar.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchbar.md index 5cdf938a9e47f..a0b879673e553 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchbar.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchbar.md @@ -7,7 +7,7 @@ Signature: ```typescript -SearchBar: React.ComponentClass, "query" | "isLoading" | "indexPatterns" | "filters" | "onQueryChange" | "customSubmitButton" | "screenTitle" | "dataTestSubj" | "showQueryBar" | "showQueryInput" | "showFilterBar" | "showDatePicker" | "showAutoRefreshOnly" | "isRefreshPaused" | "refreshInterval" | "dateRangeFrom" | "dateRangeTo" | "showSaveQuery" | "savedQuery" | "onQuerySubmit" | "onSaved" | "onSavedQueryUpdated" | "onClearSavedQuery" | "onRefresh" | "timeHistory" | "onFiltersUpdated" | "onRefreshChange">, any> & { - WrappedComponent: React.ComponentType & ReactIntl.InjectedIntlProps>; +SearchBar: React.ComponentClass, "query" | "isLoading" | "filters" | "indexPatterns" | "refreshInterval" | "screenTitle" | "dataTestSubj" | "customSubmitButton" | "showQueryBar" | "showQueryInput" | "showFilterBar" | "showDatePicker" | "showAutoRefreshOnly" | "isRefreshPaused" | "dateRangeFrom" | "dateRangeTo" | "showSaveQuery" | "savedQuery" | "onQueryChange" | "onQuerySubmit" | "onSaved" | "onSavedQueryUpdated" | "onClearSavedQuery" | "onRefresh" | "timeHistory" | "onFiltersUpdated" | "onRefreshChange">, any> & { + WrappedComponent: React.ComponentType & ReactIntl.InjectedIntlProps>; } ``` diff --git a/examples/alerting_example/public/components/view_alert.tsx b/examples/alerting_example/public/components/view_alert.tsx index c1b65eb92edc5..e418ed91096eb 100644 --- a/examples/alerting_example/public/components/view_alert.tsx +++ b/examples/alerting_example/public/components/view_alert.tsx @@ -32,7 +32,11 @@ import { import { withRouter, RouteComponentProps } from 'react-router-dom'; import { CoreStart } from 'kibana/public'; import { isEmpty } from 'lodash'; -import { Alert, AlertTaskState } from '../../../../x-pack/plugins/alerting/common'; +import { + Alert, + AlertTaskState, + BASE_ALERT_API_PATH, +} from '../../../../x-pack/plugins/alerting/common'; import { ALERTING_EXAMPLE_APP_ID } from '../../common/constants'; type Props = RouteComponentProps & { @@ -45,10 +49,10 @@ export const ViewAlertPage = withRouter(({ http, id }: Props) => { useEffect(() => { if (!alert) { - http.get(`/api/alert/${id}`).then(setAlert); + http.get(`${BASE_ALERT_API_PATH}/${id}`).then(setAlert); } if (!alertState) { - http.get(`/api/alert/${id}/state`).then(setAlertState); + http.get(`${BASE_ALERT_API_PATH}/${id}/state`).then(setAlertState); } }, [alert, alertState, http, id]); diff --git a/examples/alerting_example/public/components/view_astros_alert.tsx b/examples/alerting_example/public/components/view_astros_alert.tsx index db93d8f54924d..296269180dd7b 100644 --- a/examples/alerting_example/public/components/view_astros_alert.tsx +++ b/examples/alerting_example/public/components/view_astros_alert.tsx @@ -34,7 +34,11 @@ import { import { withRouter, RouteComponentProps } from 'react-router-dom'; import { CoreStart } from 'kibana/public'; import { isEmpty } from 'lodash'; -import { Alert, AlertTaskState } from '../../../../x-pack/plugins/alerting/common'; +import { + Alert, + AlertTaskState, + BASE_ALERT_API_PATH, +} from '../../../../x-pack/plugins/alerting/common'; import { ALERTING_EXAMPLE_APP_ID } from '../../common/constants'; type Props = RouteComponentProps & { @@ -51,10 +55,10 @@ export const ViewPeopleInSpaceAlertPage = withRouter(({ http, id }: Props) => { useEffect(() => { if (!alert) { - http.get(`/api/alert/${id}`).then(setAlert); + http.get(`${BASE_ALERT_API_PATH}/${id}`).then(setAlert); } if (!alertState) { - http.get(`/api/alert/${id}/state`).then(setAlertState); + http.get(`${BASE_ALERT_API_PATH}/${id}/state`).then(setAlertState); } }, [alert, alertState, http, id]); diff --git a/package.json b/package.json index 70d064fa2a8eb..3421bf938cd80 100644 --- a/package.json +++ b/package.json @@ -118,10 +118,10 @@ "@babel/core": "^7.5.5", "@babel/register": "^7.7.0", "@elastic/apm-rum": "^4.6.0", - "@elastic/charts": "^17.1.1", + "@elastic/charts": "^18.1.0", "@elastic/datemath": "5.0.2", "@elastic/ems-client": "7.7.0", - "@elastic/eui": "20.0.2", + "@elastic/eui": "21.0.1", "@elastic/filesaver": "1.1.2", "@elastic/good": "8.1.1-kibana2", "@elastic/numeral": "2.4.0", diff --git a/packages/kbn-ui-shared-deps/package.json b/packages/kbn-ui-shared-deps/package.json index 65fd837ad17c2..1e9ceb42433f0 100644 --- a/packages/kbn-ui-shared-deps/package.json +++ b/packages/kbn-ui-shared-deps/package.json @@ -9,9 +9,9 @@ "kbn:watch": "node scripts/build --watch" }, "devDependencies": { - "@elastic/charts": "^17.1.1", + "@elastic/charts": "^18.1.0", "abortcontroller-polyfill": "^1.4.0", - "@elastic/eui": "20.0.2", + "@elastic/eui": "21.0.1", "@kbn/babel-preset": "1.0.0", "@kbn/dev-utils": "1.0.0", "@kbn/i18n": "1.0.0", diff --git a/src/core/public/integrations/moment/moment_service.test.mocks.ts b/src/core/public/integrations/moment/moment_service.test.mocks.ts index 2fa013a6bf132..bb13232157b78 100644 --- a/src/core/public/integrations/moment/moment_service.test.mocks.ts +++ b/src/core/public/integrations/moment/moment_service.test.mocks.ts @@ -21,6 +21,9 @@ export const momentMock = { locale: jest.fn(() => 'default-locale'), tz: { setDefault: jest.fn(), + zone: jest.fn( + z => [{ name: 'tz1' }, { name: 'tz2' }, { name: 'tz3' }].find(f => z === f.name) || null + ), }, weekdays: jest.fn(() => ['dow1', 'dow2', 'dow3']), updateLocale: jest.fn(), diff --git a/src/core/public/integrations/moment/moment_service.test.ts b/src/core/public/integrations/moment/moment_service.test.ts index c9b4479f2f163..bc48ba2a85f63 100644 --- a/src/core/public/integrations/moment/moment_service.test.ts +++ b/src/core/public/integrations/moment/moment_service.test.ts @@ -47,6 +47,26 @@ describe('MomentService', () => { expect(momentMock.updateLocale).toHaveBeenCalledWith('default-locale', { week: { dow: 0 } }); }); + it('does not set unknkown zone', async () => { + const tz$ = new BehaviorSubject('timezone/undefined'); + const uiSettings = uiSettingsServiceMock.createSetupContract(); + uiSettings.get$.mockReturnValueOnce(tz$); + + service.start({ uiSettings }); + await flushPromises(); + expect(momentMock.tz.setDefault).not.toHaveBeenCalled(); + }); + + it('sets timezone when a zone is defined', async () => { + const tz$ = new BehaviorSubject('tz3'); + const uiSettings = uiSettingsServiceMock.createSetupContract(); + uiSettings.get$.mockReturnValueOnce(tz$); + + service.start({ uiSettings }); + await flushPromises(); + expect(momentMock.tz.setDefault).toHaveBeenCalledWith('tz3'); + }); + test('updates moment config', async () => { const tz$ = new BehaviorSubject('tz1'); const dow$ = new BehaviorSubject('dow1'); diff --git a/src/core/public/integrations/moment/moment_service.ts b/src/core/public/integrations/moment/moment_service.ts index 65f2bdea02933..69cc29231d6e4 100644 --- a/src/core/public/integrations/moment/moment_service.ts +++ b/src/core/public/integrations/moment/moment_service.ts @@ -35,7 +35,10 @@ export class MomentService implements CoreService { public async setup() {} public async start({ uiSettings }: StartDeps) { - const setDefaultTimezone = (tz: string) => moment.tz.setDefault(tz); + const setDefaultTimezone = (tz: string) => { + const zone = moment.tz.zone(tz); + if (zone) moment.tz.setDefault(zone.name); + }; const setStartDayOfWeek = (day: string) => { const dow = moment.weekdays().indexOf(day); moment.updateLocale(moment.locale(), { week: { dow } } as any); diff --git a/src/dev/jest/config.js b/src/dev/jest/config.js index 8078c32b10646..a941735c7840e 100644 --- a/src/dev/jest/config.js +++ b/src/dev/jest/config.js @@ -49,8 +49,6 @@ export default { '!packages/kbn-ui-framework/src/services/**/*/index.js', 'src/legacy/core_plugins/**/*.{js,jsx,ts,tsx}', '!src/legacy/core_plugins/**/{__test__,__snapshots__}/**/*', - 'src/legacy/ui/public/{agg_types,vis}/**/*.{ts,tsx}', - '!src/legacy/ui/public/{agg_types,vis}/**/*.d.ts', ], moduleNameMapper: { '@elastic/eui$': '/node_modules/@elastic/eui/test-env', diff --git a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_state.test.ts b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_state.test.ts index 60ea14dad19e1..08ccc1e0d1e89 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_state.test.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/np_ready/dashboard_state.test.ts @@ -25,13 +25,6 @@ import { InputTimeRange, TimefilterContract, TimeRange } from 'src/plugins/data/ import { ViewMode } from 'src/plugins/embeddable/public'; import { createKbnUrlStateStorage } from 'src/plugins/kibana_utils/public'; -jest.mock('ui/agg_types', () => ({ - aggTypes: { - metrics: [], - buckets: [], - }, -})); - describe('DashboardState', function() { let dashboardState: DashboardStateManager; const savedDashboard = getSavedDashboardMock(); diff --git a/src/legacy/core_plugins/kibana/public/discover/kibana_services.ts b/src/legacy/core_plugins/kibana/public/discover/kibana_services.ts index 725e94f16e2e8..cf76a9355e384 100644 --- a/src/legacy/core_plugins/kibana/public/discover/kibana_services.ts +++ b/src/legacy/core_plugins/kibana/public/discover/kibana_services.ts @@ -53,7 +53,6 @@ export { wrapInI18nContext } from 'ui/i18n'; import { search } from '../../../../../plugins/data/public'; export const { getRequestInspectorStats, getResponseInspectorStats, tabifyAggResponse } = search; // @ts-ignore -export { intervalOptions } from 'ui/agg_types'; // @ts-ignore export { timezoneProvider } from 'ui/vis/lib/timezone'; export { diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/histogram.tsx b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/histogram.tsx index 8db3c77ba0f47..107c30ec5e688 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/histogram.tsx +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/histogram.tsx @@ -38,6 +38,7 @@ import { TooltipValue, TooltipType, ElementClickListener, + XYChartElementEvent, } from '@elastic/charts'; import { i18n } from '@kbn/i18n'; @@ -140,7 +141,7 @@ export class DiscoverHistogram extends Component ([elementData]) => { - const startRange = elementData[0].x; + const startRange = (elementData as XYChartElementEvent)[0].x; const range = { from: startRange, diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js index 2857f8720d8dc..e45ab2a7d7675 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js +++ b/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js @@ -44,7 +44,6 @@ import { getRequestInspectorStats, getResponseInspectorStats, getServices, - intervalOptions, unhashUrl, subscribeWithScope, tabifyAggResponse, @@ -76,6 +75,7 @@ import { connectToQueryState, syncQueryStateWithUrl, getDefaultQuery, + search, } from '../../../../../../../plugins/data/public'; import { getIndexPatternId } from '../helpers/get_index_pattern_id'; import { addFatalError } from '../../../../../../../plugins/kibana_legacy/public'; @@ -285,7 +285,7 @@ function discoverController( mode: 'absolute', }); }; - $scope.intervalOptions = intervalOptions; + $scope.intervalOptions = search.aggs.intervalOptions; $scope.minimumVisibleRows = 50; $scope.fetchStatus = fetchStatuses.UNINITIALIZED; $scope.showSaveQuery = uiCapabilities.discover.saveQuery; diff --git a/src/legacy/core_plugins/kibana/public/kibana.js b/src/legacy/core_plugins/kibana/public/kibana.js index 04eaf2cbe2679..df6b08ef76556 100644 --- a/src/legacy/core_plugins/kibana/public/kibana.js +++ b/src/legacy/core_plugins/kibana/public/kibana.js @@ -48,7 +48,6 @@ import './dashboard/legacy'; import './management'; import './dev_tools'; import 'ui/agg_response'; -import 'ui/agg_types'; import { showAppRedirectNotification } from '../../../../plugins/kibana_legacy/public'; import 'leaflet'; import { localApplicationService } from './local_application_service'; diff --git a/src/legacy/core_plugins/region_map/public/region_map_type.js b/src/legacy/core_plugins/region_map/public/region_map_type.js index a03fbe4b291e2..9a1a76362e094 100644 --- a/src/legacy/core_plugins/region_map/public/region_map_type.js +++ b/src/legacy/core_plugins/region_map/public/region_map_type.js @@ -18,12 +18,12 @@ */ import React from 'react'; import { i18n } from '@kbn/i18n'; -import { Schemas } from 'ui/agg_types'; import { mapToLayerWithId } from './util'; import { createRegionMapVisualization } from './region_map_visualization'; import { Status } from '../../visualizations/public'; import { RegionMapOptions } from './components/region_map_options'; import { truncatedColorSchemas } from '../../../../plugins/charts/public'; +import { Schemas } from '../../vis_default_editor/public'; // TODO: reference to TILE_MAP plugin should be removed import { ORIGIN } from '../../tile_map/common/origin'; diff --git a/src/legacy/core_plugins/telemetry/server/collection_manager.ts b/src/legacy/core_plugins/telemetry/server/collection_manager.ts index 715ca56e290a2..ebac4bede85bb 100644 --- a/src/legacy/core_plugins/telemetry/server/collection_manager.ts +++ b/src/legacy/core_plugins/telemetry/server/collection_manager.ts @@ -20,6 +20,7 @@ import { encryptTelemetry } from './collectors'; import { CallCluster } from '../../elasticsearch'; import { UsageCollectionSetup } from '../../../../plugins/usage_collection/server'; +import { Cluster } from '../../elasticsearch'; import { ESLicense } from './telemetry_collection/get_local_license'; export type EncryptedStatsGetterConfig = { unencrypted: false } & { @@ -70,7 +71,7 @@ export type LicenseGetter = ( interface CollectionConfig { title: string; priority: number; - esCluster: string; + esCluster: string | Cluster; statsGetter: StatsGetter; clusterDetailsGetter: ClusterDetailsGetter; licenseGetter: LicenseGetter; @@ -79,7 +80,7 @@ interface Collection { statsGetter: StatsGetter; licenseGetter: LicenseGetter; clusterDetailsGetter: ClusterDetailsGetter; - esCluster: string; + esCluster: string | Cluster; title: string; } @@ -135,9 +136,10 @@ export class TelemetryCollectionManager { ): Promise => { const { start, end } = config; const server = config.unencrypted ? config.req.server : config.server; - const { callWithRequest, callWithInternalUser } = server.plugins.elasticsearch.getCluster( - collection.esCluster - ); + const { callWithRequest, callWithInternalUser } = + typeof collection.esCluster === 'string' + ? server.plugins.elasticsearch.getCluster(collection.esCluster) + : collection.esCluster; const callCluster = config.unencrypted ? (...args: any[]) => callWithRequest(config.req, ...args) : callWithInternalUser; diff --git a/src/legacy/core_plugins/tile_map/public/tile_map_type.js b/src/legacy/core_plugins/tile_map/public/tile_map_type.js index 544b63abe82c7..0809bf6ecbab6 100644 --- a/src/legacy/core_plugins/tile_map/public/tile_map_type.js +++ b/src/legacy/core_plugins/tile_map/public/tile_map_type.js @@ -21,8 +21,8 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; import { convertToGeoJson } from 'ui/vis/map/convert_to_geojson'; -import { Schemas } from 'ui/agg_types'; +import { Schemas } from '../../vis_default_editor/public'; import { Status } from '../../visualizations/public'; import { createTileMapVisualization } from './tile_map_visualization'; import { TileMapOptions } from './components/tile_map_options'; diff --git a/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js b/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js index 111db0a83ffc4..fb54c36df27d7 100644 --- a/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js +++ b/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js @@ -21,287 +21,295 @@ import _ from 'lodash'; import rison from 'rison-node'; import { uiModules } from 'ui/modules'; import 'ui/directives/input_focus'; -import 'ui/directives/paginate'; import savedObjectFinderTemplate from './saved_object_finder.html'; import { savedSheetLoader } from '../services/saved_sheets'; import { keyMap } from 'ui/directives/key_map'; +import { + PaginateControlsDirectiveProvider, + PaginateDirectiveProvider, +} from '../../../../../plugins/kibana_legacy/public'; const module = uiModules.get('kibana'); -module.directive('savedObjectFinder', function($location, kbnUrl, Private, config) { - return { - restrict: 'E', - scope: { - type: '@', - // optional make-url attr, sets the userMakeUrl in our scope - userMakeUrl: '=?makeUrl', - // optional on-choose attr, sets the userOnChoose in our scope - userOnChoose: '=?onChoose', - // optional useLocalManagement attr, removes link to management section - useLocalManagement: '=?useLocalManagement', - /** - * @type {function} - an optional function. If supplied an `Add new X` button is shown - * and this function is called when clicked. - */ - onAddNew: '=', - /** - * @{type} boolean - set this to true, if you don't want the search box above the - * table to automatically gain focus once loaded - */ - disableAutoFocus: '=', - }, - template: savedObjectFinderTemplate, - controllerAs: 'finder', - controller: function($scope, $element) { - const self = this; - - // the text input element - const $input = $element.find('input[ng-model=filter]'); - - // The number of items to show in the list - $scope.perPage = config.get('savedObjects:perPage'); - - // the list that will hold the suggestions - const $list = $element.find('ul'); - - // the current filter string, used to check that returned results are still useful - let currentFilter = $scope.filter; - - // the most recently entered search/filter - let prevSearch; - - // the list of hits, used to render display - self.hits = []; - - self.service = savedSheetLoader; - self.properties = self.service.loaderProperties; - - filterResults(); - - /** - * Boolean that keeps track of whether hits are sorted ascending (true) - * or descending (false) by title - * @type {Boolean} - */ - self.isAscending = true; - - /** - * Sorts saved object finder hits either ascending or descending - * @param {Array} hits Array of saved finder object hits - * @return {Array} Array sorted either ascending or descending - */ - self.sortHits = function(hits) { - self.isAscending = !self.isAscending; - self.hits = self.isAscending ? _.sortBy(hits, 'title') : _.sortBy(hits, 'title').reverse(); - }; - - /** - * Passed the hit objects and will determine if the - * hit should have a url in the UI, returns it if so - * @return {string|null} - the url or nothing - */ - self.makeUrl = function(hit) { - if ($scope.userMakeUrl) { - return $scope.userMakeUrl(hit); - } - - if (!$scope.userOnChoose) { - return hit.url; - } +module + .directive('paginate', PaginateDirectiveProvider) + .directive('paginateControls', PaginateControlsDirectiveProvider) + .directive('savedObjectFinder', function($location, kbnUrl, Private, config) { + return { + restrict: 'E', + scope: { + type: '@', + // optional make-url attr, sets the userMakeUrl in our scope + userMakeUrl: '=?makeUrl', + // optional on-choose attr, sets the userOnChoose in our scope + userOnChoose: '=?onChoose', + // optional useLocalManagement attr, removes link to management section + useLocalManagement: '=?useLocalManagement', + /** + * @type {function} - an optional function. If supplied an `Add new X` button is shown + * and this function is called when clicked. + */ + onAddNew: '=', + /** + * @{type} boolean - set this to true, if you don't want the search box above the + * table to automatically gain focus once loaded + */ + disableAutoFocus: '=', + }, + template: savedObjectFinderTemplate, + controllerAs: 'finder', + controller: function($scope, $element) { + const self = this; + + // the text input element + const $input = $element.find('input[ng-model=filter]'); + + // The number of items to show in the list + $scope.perPage = config.get('savedObjects:perPage'); + + // the list that will hold the suggestions + const $list = $element.find('ul'); + + // the current filter string, used to check that returned results are still useful + let currentFilter = $scope.filter; + + // the most recently entered search/filter + let prevSearch; + + // the list of hits, used to render display + self.hits = []; + + self.service = savedSheetLoader; + self.properties = self.service.loaderProperties; - return '#'; - }; + filterResults(); - self.preventClick = function($event) { - $event.preventDefault(); - }; + /** + * Boolean that keeps track of whether hits are sorted ascending (true) + * or descending (false) by title + * @type {Boolean} + */ + self.isAscending = true; + + /** + * Sorts saved object finder hits either ascending or descending + * @param {Array} hits Array of saved finder object hits + * @return {Array} Array sorted either ascending or descending + */ + self.sortHits = function(hits) { + self.isAscending = !self.isAscending; + self.hits = self.isAscending + ? _.sortBy(hits, 'title') + : _.sortBy(hits, 'title').reverse(); + }; + + /** + * Passed the hit objects and will determine if the + * hit should have a url in the UI, returns it if so + * @return {string|null} - the url or nothing + */ + self.makeUrl = function(hit) { + if ($scope.userMakeUrl) { + return $scope.userMakeUrl(hit); + } - /** - * Called when a hit object is clicked, can override the - * url behavior if necessary. - */ - self.onChoose = function(hit, $event) { - if ($scope.userOnChoose) { - $scope.userOnChoose(hit, $event); - } + if (!$scope.userOnChoose) { + return hit.url; + } - const url = self.makeUrl(hit); - if (!url || url === '#' || url.charAt(0) !== '#') return; + return '#'; + }; - $event.preventDefault(); + self.preventClick = function($event) { + $event.preventDefault(); + }; - // we want the '/path', not '#/path' - kbnUrl.change(url.substr(1)); - }; + /** + * Called when a hit object is clicked, can override the + * url behavior if necessary. + */ + self.onChoose = function(hit, $event) { + if ($scope.userOnChoose) { + $scope.userOnChoose(hit, $event); + } - $scope.$watch('filter', function(newFilter) { - // ensure that the currentFilter changes from undefined to '' - // which triggers - currentFilter = newFilter || ''; - filterResults(); - }); - - $scope.pageFirstItem = 0; - $scope.pageLastItem = 0; - $scope.onPageChanged = page => { - $scope.pageFirstItem = page.firstItem; - $scope.pageLastItem = page.lastItem; - }; - - //manages the state of the keyboard selector - self.selector = { - enabled: false, - index: -1, - }; - - self.getLabel = function() { - return _.words(self.properties.nouns) - .map(_.capitalize) - .join(' '); - }; - - //key handler for the filter text box - self.filterKeyDown = function($event) { - switch (keyMap[$event.keyCode]) { - case 'enter': - if (self.hitCount !== 1) return; - - const hit = self.hits[0]; - if (!hit) return; - - self.onChoose(hit, $event); - $event.preventDefault(); - break; - } - }; + const url = self.makeUrl(hit); + if (!url || url === '#' || url.charAt(0) !== '#') return; - //key handler for the list items - self.hitKeyDown = function($event, page, paginate) { - switch (keyMap[$event.keyCode]) { - case 'tab': - if (!self.selector.enabled) break; + $event.preventDefault(); - self.selector.index = -1; - self.selector.enabled = false; + // we want the '/path', not '#/path' + kbnUrl.change(url.substr(1)); + }; - //if the user types shift-tab return to the textbox - //if the user types tab, set the focus to the currently selected hit. - if ($event.shiftKey) { - $input.focus(); - } else { - $list.find('li.active a').focus(); - } + $scope.$watch('filter', function(newFilter) { + // ensure that the currentFilter changes from undefined to '' + // which triggers + currentFilter = newFilter || ''; + filterResults(); + }); - $event.preventDefault(); - break; - case 'down': - if (!self.selector.enabled) break; + $scope.pageFirstItem = 0; + $scope.pageLastItem = 0; + $scope.onPageChanged = page => { + $scope.pageFirstItem = page.firstItem; + $scope.pageLastItem = page.lastItem; + }; + + //manages the state of the keyboard selector + self.selector = { + enabled: false, + index: -1, + }; + + self.getLabel = function() { + return _.words(self.properties.nouns) + .map(_.capitalize) + .join(' '); + }; + + //key handler for the filter text box + self.filterKeyDown = function($event) { + switch (keyMap[$event.keyCode]) { + case 'enter': + if (self.hitCount !== 1) return; + + const hit = self.hits[0]; + if (!hit) return; + + self.onChoose(hit, $event); + $event.preventDefault(); + break; + } + }; + + //key handler for the list items + self.hitKeyDown = function($event, page, paginate) { + switch (keyMap[$event.keyCode]) { + case 'tab': + if (!self.selector.enabled) break; + + self.selector.index = -1; + self.selector.enabled = false; + + //if the user types shift-tab return to the textbox + //if the user types tab, set the focus to the currently selected hit. + if ($event.shiftKey) { + $input.focus(); + } else { + $list.find('li.active a').focus(); + } + + $event.preventDefault(); + break; + case 'down': + if (!self.selector.enabled) break; + + if (self.selector.index + 1 < page.length) { + self.selector.index += 1; + } + $event.preventDefault(); + break; + case 'up': + if (!self.selector.enabled) break; + + if (self.selector.index > 0) { + self.selector.index -= 1; + } + $event.preventDefault(); + break; + case 'right': + if (!self.selector.enabled) break; + + if (page.number < page.count) { + paginate.goToPage(page.number + 1); + self.selector.index = 0; + selectTopHit(); + } + $event.preventDefault(); + break; + case 'left': + if (!self.selector.enabled) break; + + if (page.number > 1) { + paginate.goToPage(page.number - 1); + self.selector.index = 0; + selectTopHit(); + } + $event.preventDefault(); + break; + case 'escape': + if (!self.selector.enabled) break; - if (self.selector.index + 1 < page.length) { - self.selector.index += 1; - } - $event.preventDefault(); - break; - case 'up': - if (!self.selector.enabled) break; + $input.focus(); + $event.preventDefault(); + break; + case 'enter': + if (!self.selector.enabled) break; + + const hitIndex = (page.number - 1) * paginate.perPage + self.selector.index; + const hit = self.hits[hitIndex]; + if (!hit) break; + + self.onChoose(hit, $event); + $event.preventDefault(); + break; + case 'shift': + break; + default: + $input.focus(); + break; + } + }; + + self.hitBlur = function() { + self.selector.index = -1; + self.selector.enabled = false; + }; + + self.manageObjects = function(type) { + $location.url('/management/kibana/objects?_a=' + rison.encode({ tab: type })); + }; + + self.hitCountNoun = function() { + return (self.hitCount === 1 ? self.properties.noun : self.properties.nouns).toLowerCase(); + }; + + function selectTopHit() { + setTimeout(function() { + //triggering a focus event kicks off a new angular digest cycle. + $list.find('a:first').focus(); + }, 0); + } - if (self.selector.index > 0) { - self.selector.index -= 1; - } - $event.preventDefault(); - break; - case 'right': - if (!self.selector.enabled) break; - - if (page.number < page.count) { - paginate.goToPage(page.number + 1); - self.selector.index = 0; - selectTopHit(); - } - $event.preventDefault(); - break; - case 'left': - if (!self.selector.enabled) break; - - if (page.number > 1) { - paginate.goToPage(page.number - 1); - self.selector.index = 0; - selectTopHit(); + function filterResults() { + if (!self.service) return; + if (!self.properties) return; + + // track the filter that we use for this search, + // but ensure that we don't search for the same + // thing twice. This is called from multiple places + // and needs to be smart about when it actually searches + const filter = currentFilter; + if (prevSearch === filter) return; + + prevSearch = filter; + + const isLabsEnabled = config.get('visualize:enableLabs'); + self.service.find(filter).then(function(hits) { + hits.hits = hits.hits.filter( + hit => isLabsEnabled || _.get(hit, 'type.stage') !== 'experimental' + ); + hits.total = hits.hits.length; + + // ensure that we don't display old results + // as we can't really cancel requests + if (currentFilter === filter) { + self.hitCount = hits.total; + self.hits = _.sortBy(hits.hits, 'title'); } - $event.preventDefault(); - break; - case 'escape': - if (!self.selector.enabled) break; - - $input.focus(); - $event.preventDefault(); - break; - case 'enter': - if (!self.selector.enabled) break; - - const hitIndex = (page.number - 1) * paginate.perPage + self.selector.index; - const hit = self.hits[hitIndex]; - if (!hit) break; - - self.onChoose(hit, $event); - $event.preventDefault(); - break; - case 'shift': - break; - default: - $input.focus(); - break; + }); } - }; - - self.hitBlur = function() { - self.selector.index = -1; - self.selector.enabled = false; - }; - - self.manageObjects = function(type) { - $location.url('/management/kibana/objects?_a=' + rison.encode({ tab: type })); - }; - - self.hitCountNoun = function() { - return (self.hitCount === 1 ? self.properties.noun : self.properties.nouns).toLowerCase(); - }; - - function selectTopHit() { - setTimeout(function() { - //triggering a focus event kicks off a new angular digest cycle. - $list.find('a:first').focus(); - }, 0); - } - - function filterResults() { - if (!self.service) return; - if (!self.properties) return; - - // track the filter that we use for this search, - // but ensure that we don't search for the same - // thing twice. This is called from multiple places - // and needs to be smart about when it actually searches - const filter = currentFilter; - if (prevSearch === filter) return; - - prevSearch = filter; - - const isLabsEnabled = config.get('visualize:enableLabs'); - self.service.find(filter).then(function(hits) { - hits.hits = hits.hits.filter( - hit => isLabsEnabled || _.get(hit, 'type.stage') !== 'experimental' - ); - hits.total = hits.hits.length; - - // ensure that we don't display old results - // as we can't really cancel requests - if (currentFilter === filter) { - self.hitCount = hits.total; - self.hits = _.sortBy(hits.hits, 'title'); - } - }); - } - }, - }; -}); + }, + }; + }); diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/__snapshots__/agg.test.tsx.snap b/src/legacy/core_plugins/vis_default_editor/public/components/__snapshots__/agg.test.tsx.snap index ba5f2ae975cbe..5200fee45d6b3 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/__snapshots__/agg.test.tsx.snap +++ b/src/legacy/core_plugins/vis_default_editor/public/components/__snapshots__/agg.test.tsx.snap @@ -3,6 +3,7 @@ exports[`DefaultEditorAgg component should init with the default set of props 1`] = ` diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/__snapshots__/agg_params.test.tsx.snap b/src/legacy/core_plugins/vis_default_editor/public/components/__snapshots__/agg_params.test.tsx.snap deleted file mode 100644 index 028d0b8016693..0000000000000 --- a/src/legacy/core_plugins/vis_default_editor/public/components/__snapshots__/agg_params.test.tsx.snap +++ /dev/null @@ -1,70 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`DefaultEditorAggParams component should init with the default set of params 1`] = ` - - - - - - - - - -`; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg.test.tsx index 22e0ebb3d30dc..7e715be25bff3 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg.test.tsx @@ -21,17 +21,14 @@ import React from 'react'; import { mount, shallow } from 'enzyme'; import { act } from 'react-dom/test-utils'; -import { IndexPattern } from 'src/plugins/data/public'; +import { IndexPattern, IAggType, AggGroupNames } from 'src/plugins/data/public'; import { VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { IAggType, AggGroupNames } from '../legacy_imports'; import { DefaultEditorAgg, DefaultEditorAggProps } from './agg'; import { DefaultEditorAggParams } from './agg_params'; import { AGGS_ACTION_KEYS } from './agg_group_state'; import { Schema } from '../schemas'; -jest.mock('ui/new_platform'); - jest.mock('./agg_params', () => ({ DefaultEditorAggParams: () => null, })); diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg.tsx index 30ccd4f0b6cae..2a45273207623 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg.tsx @@ -28,7 +28,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { IAggConfig } from '../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { DefaultEditorAggParams } from './agg_params'; import { DefaultEditorAggCommonProps } from './agg_common_props'; import { AGGS_ACTION_KEYS, AggsAction } from './agg_group_state'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_add.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg_add.tsx index 24cb83498d4d0..9df4ea58e0f07 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_add.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_add.tsx @@ -29,7 +29,7 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -import { IAggConfig, AggGroupNames } from '../legacy_imports'; +import { IAggConfig, AggGroupNames } from '../../../../../plugins/data/public'; import { Schema } from '../schemas'; interface DefaultEditorAggAddProps { diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_common_props.ts b/src/legacy/core_plugins/vis_default_editor/public/components/agg_common_props.ts index 1a97cc5c4d967..ec92f511b6eee 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_common_props.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_common_props.ts @@ -18,7 +18,7 @@ */ import { VisState, VisParams } from 'src/legacy/core_plugins/visualizations/public'; -import { IAggType, IAggConfig, IAggGroupNames } from '../legacy_imports'; +import { IAggType, IAggConfig, IAggGroupNames } from 'src/plugins/data/public'; import { Schema } from '../schemas'; type AggId = IAggConfig['id']; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group.test.tsx index ec467480539ab..63f5e696c99f4 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group.test.tsx @@ -21,7 +21,7 @@ import React from 'react'; import { mount, shallow } from 'enzyme'; import { act } from 'react-dom/test-utils'; import { VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { IAggConfigs, IAggConfig } from '../legacy_imports'; +import { IAggConfigs, IAggConfig } from 'src/plugins/data/public'; import { DefaultEditorAggGroup, DefaultEditorAggGroupProps } from './agg_group'; import { DefaultEditorAgg } from './agg'; import { DefaultEditorAggAdd } from './agg_add'; @@ -36,17 +36,6 @@ jest.mock('@elastic/eui', () => ({ EuiPanel: 'eui-panel', })); -jest.mock('../legacy_imports', () => ({ - aggGroupNamesMap: () => ({ - metrics: 'Metrics', - buckets: 'Buckets', - }), - AggGroupNames: { - Metrics: 'metrics', - Buckets: 'buckets', - }, -})); - jest.mock('./agg', () => ({ DefaultEditorAgg: () =>
, })); diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group.tsx index a15a98d4983ce..600612f2cf9d8 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group.tsx @@ -30,7 +30,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { IAggConfig, aggGroupNamesMap, AggGroupNames } from '../legacy_imports'; +import { AggGroupNames, search, IAggConfig } from '../../../../../plugins/data/public'; import { DefaultEditorAgg } from './agg'; import { DefaultEditorAggAdd } from './agg_add'; import { AddSchema, ReorderAggs, DefaultEditorAggCommonProps } from './agg_common_props'; @@ -68,7 +68,7 @@ function DefaultEditorAggGroup({ setTouched, setValidity, }: DefaultEditorAggGroupProps) { - const groupNameLabel = (aggGroupNamesMap() as any)[groupName]; + const groupNameLabel = (search.aggs.aggGroupNamesMap() as any)[groupName]; // e.g. buckets can have no aggs const schemaNames = getSchemasByGroup(schemas, groupName).map(s => s.name); const group: IAggConfig[] = useMemo( diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_helper.test.ts b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_helper.test.ts index aebece29e7ae6..3693f1b1e3091 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_helper.test.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_helper.test.ts @@ -17,7 +17,7 @@ * under the License. */ -import { IAggConfig } from '../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { isAggRemovable, calcAggIsTooLow, diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_helper.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_helper.tsx index 0a8c5c3077ada..9a4cca940baea 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_helper.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_helper.tsx @@ -18,7 +18,7 @@ */ import { findIndex, isEmpty } from 'lodash'; -import { IAggConfig } from '../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { AggsState } from './agg_group_state'; import { Schema, getSchemaByName } from '../schemas'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_state.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_state.tsx index d022297ae72b3..bfd5bec339b1f 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_state.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_group_state.tsx @@ -17,7 +17,7 @@ * under the License. */ -import { IAggConfig } from '../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; export enum AGGS_ACTION_KEYS { TOUCHED = 'aggsTouched', diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_param_props.ts b/src/legacy/core_plugins/vis_default_editor/public/components/agg_param_props.ts index cdc5a4c8f8a77..7c2852798b403 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_param_props.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_param_props.ts @@ -17,9 +17,8 @@ * under the License. */ -import { IndexPatternField } from 'src/plugins/data/public'; +import { IAggConfig, AggParam, IndexPatternField } from 'src/plugins/data/public'; import { VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { IAggConfig, AggParam } from '../legacy_imports'; import { ComboBoxGroupedOptions } from '../utils'; import { EditorConfig } from './utils'; import { Schema } from '../schemas'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params.test.tsx index d2821566fcb37..cd6486b6a1532 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params.test.tsx @@ -18,12 +18,16 @@ */ import React from 'react'; -import { mount, shallow } from 'enzyme'; +import { mount } from 'enzyme'; import { VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { IndexPattern } from 'src/plugins/data/public'; -import { DefaultEditorAggParams, DefaultEditorAggParamsProps } from './agg_params'; -import { IAggConfig, AggGroupNames } from '../legacy_imports'; +import { IndexPattern, IAggConfig, AggGroupNames } from 'src/plugins/data/public'; +import { + DefaultEditorAggParams as PureDefaultEditorAggParams, + DefaultEditorAggParamsProps, +} from './agg_params'; +import { KibanaContextProvider } from '../../../../../plugins/kibana_react/public'; +import { dataPluginMock } from '../../../../../plugins/data/public/mocks'; const mockEditorConfig = { useNormalizedEsInterval: { hidden: false, fixedValue: false }, @@ -34,8 +38,12 @@ const mockEditorConfig = { timeBase: '1m', }, }; +const DefaultEditorAggParams = (props: DefaultEditorAggParamsProps) => ( + + + +); -jest.mock('ui/new_platform'); jest.mock('./utils', () => ({ getEditorConfig: jest.fn(() => mockEditorConfig), })); @@ -109,12 +117,6 @@ describe('DefaultEditorAggParams component', () => { }; }); - it('should init with the default set of params', () => { - const comp = shallow(); - - expect(comp).toMatchSnapshot(); - }); - it('should reset the validity to true when destroyed', () => { const comp = mount(); diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params.tsx index 510c21af95da1..b1555b76500d0 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params.tsx @@ -22,8 +22,7 @@ import { EuiForm, EuiAccordion, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import useUnmount from 'react-use/lib/useUnmount'; -import { IndexPattern } from 'src/plugins/data/public'; -import { IAggConfig, AggGroupNames } from '../legacy_imports'; +import { IAggConfig, IndexPattern, AggGroupNames } from '../../../../../plugins/data/public'; import { DefaultEditorAggSelect } from './agg_select'; import { DefaultEditorAggParam } from './agg_param'; @@ -41,6 +40,8 @@ import { import { DefaultEditorCommonProps } from './agg_common_props'; import { EditorParamConfig, TimeIntervalParam, FixedParam, getEditorConfig } from './utils'; import { Schema, getSchemaByName } from '../schemas'; +import { useKibana } from '../../../../../plugins/kibana_react/public'; +import { VisDefaultEditorKibanaServices } from '../types'; const FIXED_VALUE_PROP = 'fixedValue'; const DEFAULT_PROP = 'default'; @@ -83,18 +84,24 @@ function DefaultEditorAggParams({ allowedAggs = [], hideCustomLabel = false, }: DefaultEditorAggParamsProps) { - const schema = getSchemaByName(schemas, agg.schema); - const { title } = schema; - const aggFilter = [...allowedAggs, ...(schema.aggFilter || [])]; + const schema = useMemo(() => getSchemaByName(schemas, agg.schema), [agg.schema, schemas]); + const aggFilter = useMemo(() => [...allowedAggs, ...(schema.aggFilter || [])], [ + allowedAggs, + schema.aggFilter, + ]); + const { services } = useKibana(); + const aggTypes = useMemo(() => services.data.search.aggs.types.getAll(), [ + services.data.search.aggs.types, + ]); const groupedAggTypeOptions = useMemo( - () => getAggTypeOptions(agg, indexPattern, groupName, aggFilter), - [agg, indexPattern, groupName, aggFilter] + () => getAggTypeOptions(aggTypes, agg, indexPattern, groupName, aggFilter), + [aggTypes, agg, indexPattern, groupName, aggFilter] ); const error = aggIsTooLow ? i18n.translate('visDefaultEditor.aggParams.errors.aggWrongRunOrderErrorMessage', { defaultMessage: '"{schema}" aggs must run before all other buckets!', - values: { schema: title }, + values: { schema: schema.title }, }) : ''; const aggTypeName = agg.type?.name; @@ -105,8 +112,20 @@ function DefaultEditorAggParams({ fieldName, ]); const params = useMemo( - () => getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas, hideCustomLabel }), - [agg, editorConfig, metricAggs, state, schemas, hideCustomLabel] + () => + getAggParamsToRender( + { agg, editorConfig, metricAggs, state, schemas, hideCustomLabel }, + services.data.search.__LEGACY.aggTypeFieldFilters + ), + [ + agg, + editorConfig, + metricAggs, + state, + schemas, + hideCustomLabel, + services.data.search.__LEGACY.aggTypeFieldFilters, + ] ); const allParams = [...params.basic, ...params.advanced]; const [paramsState, onChangeParamsState] = useReducer( diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_helper.test.ts b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_helper.test.ts index 047467750794b..f2ebbdc87a60a 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_helper.test.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_helper.test.ts @@ -17,9 +17,15 @@ * under the License. */ -import { IndexPattern } from 'src/plugins/data/public'; +import { + AggGroupNames, + BUCKET_TYPES, + IAggConfig, + IAggType, + IndexPattern, + IndexPatternField, +} from 'src/plugins/data/public'; import { VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { IAggConfig, IAggType, AggGroupNames, BUCKET_TYPES } from '../legacy_imports'; import { getAggParamsToRender, getAggTypeOptions, @@ -33,7 +39,11 @@ jest.mock('../utils', () => ({ groupAndSortBy: jest.fn(() => ['indexedFields']), })); -jest.mock('ui/new_platform'); +const mockFilter: any = { + filter(fields: IndexPatternField[]): IndexPatternField[] { + return fields; + }, +}; describe('DefaultEditorAggParams helpers', () => { describe('getAggParamsToRender', () => { @@ -62,14 +72,20 @@ describe('DefaultEditorAggParams helpers', () => { }, schema: 'metric', } as IAggConfig; - const params = getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas }); + const params = getAggParamsToRender( + { agg, editorConfig, metricAggs, state, schemas }, + mockFilter + ); expect(params).toEqual(emptyParams); }); it('should not create any param if there is no agg type', () => { agg = { schema: 'metric' } as IAggConfig; - const params = getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas }); + const params = getAggParamsToRender( + { agg, editorConfig, metricAggs, state, schemas }, + mockFilter + ); expect(params).toEqual(emptyParams); }); @@ -85,7 +101,10 @@ describe('DefaultEditorAggParams helpers', () => { hidden: true, }, }; - const params = getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas }); + const params = getAggParamsToRender( + { agg, editorConfig, metricAggs, state, schemas }, + mockFilter + ); expect(params).toEqual(emptyParams); }); @@ -97,7 +116,10 @@ describe('DefaultEditorAggParams helpers', () => { }, schema: 'metric2', } as any) as IAggConfig; - const params = getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas }); + const params = getAggParamsToRender( + { agg, editorConfig, metricAggs, state, schemas }, + mockFilter + ); expect(params).toEqual(emptyParams); }); @@ -136,7 +158,10 @@ describe('DefaultEditorAggParams helpers', () => { field: 'field', }, } as any) as IAggConfig; - const params = getAggParamsToRender({ agg, editorConfig, metricAggs, state, schemas }); + const params = getAggParamsToRender( + { agg, editorConfig, metricAggs, state, schemas }, + mockFilter + ); expect(params).toEqual({ basic: [ @@ -172,7 +197,13 @@ describe('DefaultEditorAggParams helpers', () => { describe('getAggTypeOptions', () => { it('should return agg type options grouped by subtype', () => { const indexPattern = {} as IndexPattern; - const aggs = getAggTypeOptions({} as IAggConfig, indexPattern, 'metrics', []); + const aggs = getAggTypeOptions( + { metrics: [] }, + {} as IAggConfig, + indexPattern, + 'metrics', + [] + ); expect(aggs).toEqual(['indexedFields']); }); diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_helper.ts b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_helper.ts index 520ff6ffc5ff5..e07bf81697579 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_helper.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_helper.ts @@ -19,23 +19,23 @@ import { get, isEmpty } from 'lodash'; -import { IndexPattern, IndexPatternField } from 'src/plugins/data/public'; -import { VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { groupAndSortBy, ComboBoxGroupedOptions } from '../utils'; -import { AggTypeState, AggParamsState } from './agg_params_state'; -import { AggParamEditorProps } from './agg_param_props'; -import { aggParamsMap } from './agg_params_map'; import { - aggTypeFilters, - aggTypeFieldFilters, - aggTypes, + AggTypeFieldFilters, IAggConfig, AggParam, IFieldParamType, IAggType, -} from '../legacy_imports'; + IndexPattern, + IndexPatternField, +} from 'src/plugins/data/public'; +import { VisState } from 'src/legacy/core_plugins/visualizations/public'; +import { groupAndSortBy, ComboBoxGroupedOptions } from '../utils'; +import { AggTypeState, AggParamsState } from './agg_params_state'; +import { AggParamEditorProps } from './agg_param_props'; +import { aggParamsMap } from './agg_params_map'; import { EditorConfig } from './utils'; import { Schema, getSchemaByName } from '../schemas'; +import { search } from '../../../../../plugins/data/public'; interface ParamInstanceBase { agg: IAggConfig; @@ -53,14 +53,10 @@ export interface ParamInstance extends ParamInstanceBase { value: unknown; } -function getAggParamsToRender({ - agg, - editorConfig, - metricAggs, - state, - schemas, - hideCustomLabel, -}: ParamInstanceBase) { +function getAggParamsToRender( + { agg, editorConfig, metricAggs, state, schemas, hideCustomLabel }: ParamInstanceBase, + aggTypeFieldFilters: AggTypeFieldFilters +) { const params = { basic: [] as ParamInstance[], advanced: [] as ParamInstance[], @@ -136,13 +132,14 @@ function getAggParamsToRender({ } function getAggTypeOptions( + aggTypes: any, agg: IAggConfig, indexPattern: IndexPattern, groupName: string, allowedAggs: string[] ): ComboBoxGroupedOptions { - const aggTypeOptions = aggTypeFilters.filter( - (aggTypes as any)[groupName], + const aggTypeOptions = search.aggs.aggTypeFilters.filter( + aggTypes[groupName], indexPattern, agg, allowedAggs diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_map.ts b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_map.ts index 7caa775dd4fa4..4517313b6fd6e 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_map.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_params_map.ts @@ -22,11 +22,12 @@ import { AggGroupNames, BUCKET_TYPES, METRIC_TYPES, - siblingPipelineType, - parentPipelineType, -} from '../legacy_imports'; + search, +} from '../../../../../plugins/data/public'; import { wrapWithInlineComp } from './controls/utils'; +const { siblingPipelineType, parentPipelineType } = search.aggs; + const buckets = { [BUCKET_TYPES.DATE_HISTOGRAM]: { scaleMetricValues: controls.ScaleMetricsParamEditor, diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/agg_select.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/agg_select.tsx index 4d969a2d8ec6c..7ee432946f3c8 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/agg_select.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/agg_select.tsx @@ -23,9 +23,8 @@ import { EuiComboBox, EuiComboBoxOptionOption, EuiFormRow, EuiLink, EuiText } fr import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { IndexPattern } from 'src/plugins/data/public'; +import { IAggType, IndexPattern } from 'src/plugins/data/public'; import { useKibana } from '../../../../../plugins/kibana_react/public'; -import { IAggType } from '../legacy_imports'; import { ComboBoxGroupedOptions } from '../utils'; import { AGG_TYPE_ACTION_KEYS, AggTypeAction } from './agg_params_state'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/agg_control_props.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/agg_control_props.tsx index 7f04b851902de..98540d3414f2d 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/agg_control_props.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/agg_control_props.tsx @@ -18,7 +18,7 @@ */ import { VisParams } from 'src/legacy/core_plugins/visualizations/public'; -import { IAggConfig } from '../../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { DefaultEditorAggCommonProps } from '../agg_common_props'; export interface AggControlProps { diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/agg_utils.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/agg_utils.test.tsx index 0b847e3747b30..0c1e93bc1e646 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/agg_utils.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/agg_utils.test.tsx @@ -20,7 +20,7 @@ import React, { FunctionComponent } from 'react'; import { mount, ReactWrapper } from 'enzyme'; -import { IAggConfig } from '../../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { safeMakeLabel, useAvailableOptions, diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/components/mask_list.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/components/mask_list.tsx index 625b09b05d28f..f6edecbbcbd70 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/components/mask_list.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/components/mask_list.tsx @@ -22,7 +22,7 @@ import { EuiFieldText, EuiFlexItem } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { InputList, InputListConfig, InputObject, InputModel, InputItem } from './input_list'; -import { CidrMask } from '../../../legacy_imports'; +import { search } from '../../../../../../../plugins/data/public'; const EMPTY_STRING = ''; @@ -47,7 +47,7 @@ function MaskList({ showValidation, onBlur, ...rest }: MaskListProps) { defaultValue: { mask: { model: '0.0.0.0/1', value: '0.0.0.0/1', isInvalid: false }, }, - validateClass: CidrMask, + validateClass: search.aggs.CidrMask, getModelValue: (item: MaskObject = {}) => ({ mask: { model: item.mask || EMPTY_STRING, diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/field.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/field.test.tsx index 186738d0f551c..1043431475494 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/field.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/field.test.tsx @@ -22,11 +22,10 @@ import { act } from 'react-dom/test-utils'; import { mount, shallow, ReactWrapper } from 'enzyme'; import { EuiComboBoxProps, EuiComboBox } from '@elastic/eui'; -import { IndexPatternField } from 'src/plugins/data/public'; +import { IAggConfig, IndexPatternField } from 'src/plugins/data/public'; import { VisState } from 'src/legacy/core_plugins/visualizations/public'; import { ComboBoxGroupedOptions } from '../../utils'; import { FieldParamEditor, FieldParamEditorProps } from './field'; -import { IAggConfig } from '../../legacy_imports'; function callComboBoxOnChange(comp: ReactWrapper, value: any = []) { const comboBoxProps = comp.find(EuiComboBox).props() as EuiComboBoxProps; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/field.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/field.tsx index 0ec00ab6f20f0..59642ae4c25f7 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/field.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/field.tsx @@ -23,8 +23,7 @@ import React, { useEffect, useState, useCallback } from 'react'; import { EuiComboBox, EuiComboBoxOptionOption, EuiFormRow } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { IndexPatternField } from 'src/plugins/data/public'; -import { AggParam, IAggConfig, IFieldParamType } from '../../legacy_imports'; +import { AggParam, IAggConfig, IFieldParamType, IndexPatternField } from 'src/plugins/data/public'; import { formatListAsProse, parseCommaSeparatedList, useValidation } from './utils'; import { AggParamEditorProps } from '../agg_param_props'; import { ComboBoxGroupedOptions } from '../../utils'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/filter.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/filter.tsx index 3622b27bad403..e2e7c2895093e 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/filter.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/filter.tsx @@ -21,8 +21,7 @@ import React, { useState } from 'react'; import { EuiForm, EuiButtonIcon, EuiFieldText, EuiFormRow, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { Query, QueryStringInput } from '../../../../../../plugins/data/public'; -import { IAggConfig } from '../../legacy_imports'; +import { IAggConfig, Query, QueryStringInput } from '../../../../../../plugins/data/public'; interface FilterRowProps { id: string; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/has_extended_bounds.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/has_extended_bounds.tsx index 416f925da8c1e..90b7cb03b7a5b 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/has_extended_bounds.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/has_extended_bounds.tsx @@ -20,10 +20,12 @@ import React, { useEffect } from 'react'; import { i18n } from '@kbn/i18n'; +import { search } from '../../../../../../plugins/data/public'; import { SwitchParamEditor } from './switch'; -import { isType } from '../../legacy_imports'; import { AggParamEditorProps } from '../agg_param_props'; +const { isType } = search.aggs; + function HasExtendedBoundsParamEditor(props: AggParamEditorProps) { useEffect(() => { props.setValue(props.value && props.agg.params.min_doc_count); diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/metric_agg.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/metric_agg.test.tsx index cf7af1aa5cb3a..c53e7a8beb831 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/metric_agg.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/metric_agg.test.tsx @@ -20,7 +20,7 @@ import React from 'react'; import { mount, shallow } from 'enzyme'; -import { IAggConfig } from '../../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { DEFAULT_OPTIONS, aggFilter, MetricAggParamEditor } from './metric_agg'; jest.mock('./utils', () => ({ diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/missing_bucket.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/missing_bucket.tsx index 8d22ab283f3a1..7010f0d53e569 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/missing_bucket.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/missing_bucket.tsx @@ -21,11 +21,11 @@ import React, { useEffect } from 'react'; import { i18n } from '@kbn/i18n'; import { SwitchParamEditor } from './switch'; -import { isStringType } from '../../legacy_imports'; +import { search } from '../../../../../../plugins/data/public'; import { AggParamEditorProps } from '../agg_param_props'; function MissingBucketParamEditor(props: AggParamEditorProps) { - const fieldTypeIsNotString = !isStringType(props.agg); + const fieldTypeIsNotString = !search.aggs.isStringType(props.agg); useEffect(() => { if (fieldTypeIsNotString) { diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/order.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/order.tsx index f40143251e46a..8f63662d928c1 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/order.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/order.tsx @@ -21,7 +21,7 @@ import React, { useEffect } from 'react'; import { EuiFormRow, EuiSelect } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { OptionedValueProp, OptionedParamEditorProps } from '../../legacy_imports'; +import { OptionedValueProp, OptionedParamEditorProps } from 'src/plugins/data/public'; import { AggParamEditorProps } from '../agg_param_props'; function OrderParamEditor({ diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_agg.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_agg.test.tsx index 01f5ed9b6a2f1..4c843791153b0 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_agg.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_agg.test.tsx @@ -21,8 +21,6 @@ import React from 'react'; import { mount } from 'enzyme'; import { OrderByParamEditor } from './order_by'; -jest.mock('ui/new_platform'); - describe('OrderAggParamEditor component', () => { let setValue: jest.Mock; let setValidity: jest.Mock; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_agg.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_agg.tsx index 8c020c668b3c6..41672bc192fab 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_agg.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_agg.tsx @@ -20,7 +20,7 @@ import React, { useEffect } from 'react'; import { EuiSpacer } from '@elastic/eui'; -import { AggParamType, IAggConfig, AggGroupNames } from '../../legacy_imports'; +import { AggParamType, IAggConfig, AggGroupNames } from '../../../../../../plugins/data/public'; import { useSubAggParamsHandlers } from './utils'; import { AggParamEditorProps } from '../agg_param_props'; import { DefaultEditorAggParams } from '../agg_params'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_by.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_by.tsx index c0391358ec6e2..9f1aaa54a8ca3 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_by.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/order_by.tsx @@ -28,8 +28,9 @@ import { useValidation, } from './utils'; import { AggParamEditorProps } from '../agg_param_props'; -import { termsAggFilter } from '../../legacy_imports'; +import { search } from '../../../../../../plugins/data/public'; +const { termsAggFilter } = search.aggs; const DEFAULT_VALUE = '_key'; const DEFAULT_OPTIONS = [ { diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/percentiles.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/percentiles.test.tsx index 0eaf9bcc987c1..76eb12af8c4e2 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/percentiles.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/percentiles.test.tsx @@ -19,7 +19,7 @@ import React from 'react'; import { AggParamEditorProps } from '../agg_param_props'; -import { IAggConfig } from '../../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { VisState } from 'src/legacy/core_plugins/visualizations/public'; import { mount } from 'enzyme'; import { PercentilesEditor } from './percentiles'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/sub_agg.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/sub_agg.tsx index 5bc94bd4af226..c9f53a68b3e83 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/sub_agg.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/sub_agg.tsx @@ -20,7 +20,7 @@ import React, { useEffect } from 'react'; import { EuiSpacer } from '@elastic/eui'; -import { AggParamType, IAggConfig, AggGroupNames } from '../../legacy_imports'; +import { AggParamType, IAggConfig, AggGroupNames } from '../../../../../../plugins/data/public'; import { useSubAggParamsHandlers } from './utils'; import { AggParamEditorProps } from '../agg_param_props'; import { DefaultEditorAggParams } from '../agg_params'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/sub_metric.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/sub_metric.tsx index 9d48b1c964a27..ead3f8bb00623 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/sub_metric.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/sub_metric.tsx @@ -21,7 +21,7 @@ import React, { useEffect } from 'react'; import { EuiFormLabel, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { AggParamType, IAggConfig, AggGroupNames } from '../../legacy_imports'; +import { AggParamType, IAggConfig, AggGroupNames } from '../../../../../../plugins/data/public'; import { useSubAggParamsHandlers } from './utils'; import { AggParamEditorProps } from '../agg_param_props'; import { DefaultEditorAggParams } from '../agg_params'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/test_utils.ts b/src/legacy/core_plugins/vis_default_editor/public/components/controls/test_utils.ts index 8a21114999cd6..b816e61cce355 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/test_utils.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/test_utils.ts @@ -18,7 +18,7 @@ */ import { VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { IAggConfig, AggParam } from '../../legacy_imports'; +import { IAggConfig, AggParam } from 'src/plugins/data/public'; import { EditorConfig } from '../utils'; export const aggParamCommonPropsMock = { diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/time_interval.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/time_interval.tsx index ee3666b2ed441..de0059f5467ad 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/time_interval.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/time_interval.tsx @@ -23,7 +23,7 @@ import { EuiFormRow, EuiIconTip, EuiComboBox, EuiComboBoxOptionOption } from '@e import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { isValidInterval, AggParamOption } from '../../legacy_imports'; +import { search, AggParamOption } from '../../../../../../plugins/data/public'; import { AggParamEditorProps } from '../agg_param_props'; interface ComboBoxOption extends EuiComboBoxOptionOption { @@ -59,7 +59,7 @@ function TimeIntervalParamEditor({ if (value) { definedOption = find(options, { key: value }); selectedOptions = definedOption ? [definedOption] : [{ label: value, key: 'custom' }]; - isValid = !!(definedOption || isValidInterval(value, timeBase)); + isValid = !!(definedOption || search.aggs.isValidInterval(value, timeBase)); } const interval = get(agg, 'buckets.getInterval') && (agg as any).buckets.getInterval(); @@ -100,7 +100,7 @@ function TimeIntervalParamEditor({ const normalizedCustomValue = customValue.trim(); setValue(normalizedCustomValue); - if (normalizedCustomValue && isValidInterval(normalizedCustomValue, timeBase)) { + if (normalizedCustomValue && search.aggs.isValidInterval(normalizedCustomValue, timeBase)) { agg.write(); } }; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/top_aggregate.test.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/top_aggregate.test.tsx index 4ce0712040bd5..74dab1a3b551a 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/top_aggregate.test.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/top_aggregate.test.tsx @@ -25,7 +25,7 @@ import { TopAggregateParamEditorProps, } from './top_aggregate'; import { aggParamCommonPropsMock } from './test_utils'; -import { IAggConfig } from '../../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; describe('TopAggregateParamEditor', () => { let agg: IAggConfig; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/top_aggregate.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/controls/top_aggregate.tsx index 346dfc0156f07..bab20d18c8fc0 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/top_aggregate.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/top_aggregate.tsx @@ -28,7 +28,7 @@ import { OptionedValueProp, OptionedParamEditorProps, OptionedParamType, -} from '../../legacy_imports'; +} from 'src/plugins/data/public'; import { AggParamEditorProps } from '../agg_param_props'; export interface AggregateValueProp extends OptionedValueProp { diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/utils/agg_utils.ts b/src/legacy/core_plugins/vis_default_editor/public/components/controls/utils/agg_utils.ts index 8aeae488942cd..f4c0814748ebc 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/utils/agg_utils.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/utils/agg_utils.ts @@ -20,7 +20,7 @@ import { useEffect, useCallback, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; -import { IAggConfig } from '../../../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; type AggFilter = string[]; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/controls/utils/use_handlers.ts b/src/legacy/core_plugins/vis_default_editor/public/components/controls/utils/use_handlers.ts index c7816d5a9d305..4dadef79b1204 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/controls/utils/use_handlers.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/controls/utils/use_handlers.ts @@ -19,7 +19,7 @@ import { useCallback } from 'react'; -import { IAggConfig, AggParamType } from '../../../legacy_imports'; +import { IAggConfig, AggParamType } from 'src/plugins/data/public'; type SetValue = (value?: IAggConfig) => void; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/data_tab.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/data_tab.tsx index 1c1f9d57d8b90..6f92c27e90ec1 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/data_tab.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/data_tab.tsx @@ -23,11 +23,11 @@ import { EuiSpacer } from '@elastic/eui'; import { VisState } from 'src/legacy/core_plugins/visualizations/public'; import { - IAggConfig, AggGroupNames, - parentPipelineType, + IAggConfig, IMetricAggType, -} from '../../legacy_imports'; + search, +} from '../../../../../../plugins/data/public'; import { DefaultEditorAggGroup } from '../agg_group'; import { EditorAction, @@ -67,7 +67,7 @@ function DefaultEditorDataTab({ () => findLast( metricAggs, - ({ type }: { type: IMetricAggType }) => type.subtype === parentPipelineType + ({ type }: { type: IMetricAggType }) => type.subtype === search.aggs.parentPipelineType ), [metricAggs] ); diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/sidebar.tsx b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/sidebar.tsx index 1efd8dae8178b..2508ef3a55537 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/sidebar.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/sidebar.tsx @@ -23,7 +23,6 @@ import { i18n } from '@kbn/i18n'; import { keyCodes, EuiButtonIcon, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { Vis } from 'src/legacy/core_plugins/visualizations/public'; -import { AggGroupNames } from '../../legacy_imports'; import { DefaultEditorNavBar, OptionTab } from './navbar'; import { DefaultEditorControls } from './controls'; import { setStateParamValue, useEditorReducer, useEditorFormState, discardChanges } from './state'; @@ -31,6 +30,7 @@ import { DefaultEditorAggCommonProps } from '../agg_common_props'; import { SidebarTitle } from './sidebar_title'; import { PersistedState } from '../../../../../../plugins/visualizations/public'; import { SavedSearch } from '../../../../../../plugins/discover/public'; +import { AggGroupNames } from '../../../../../../plugins/data/public'; import { getSchemasByGroup } from '../../schemas'; interface DefaultEditorSideBarProps { diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/actions.ts b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/actions.ts index f9915bedc8878..e3577218b7e25 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/actions.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/actions.ts @@ -18,7 +18,7 @@ */ import { Vis, VisParams } from 'src/legacy/core_plugins/visualizations/public'; -import { IAggConfig } from '../../../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { EditorStateActionTypes } from './constants'; import { Schema } from '../../../schemas'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/index.ts b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/index.ts index df5ba3f6121c7..6383ac866dcfc 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/index.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/index.ts @@ -21,15 +21,22 @@ import { useEffect, useReducer, useCallback } from 'react'; import { isEqual } from 'lodash'; import { Vis, VisState, VisParams } from 'src/legacy/core_plugins/visualizations/public'; -import { editorStateReducer, initEditorState } from './reducers'; +import { createEditorStateReducer, initEditorState } from './reducers'; import { EditorStateActionTypes } from './constants'; import { EditorAction, updateStateParams } from './actions'; +import { useKibana } from '../../../../../../../plugins/kibana_react/public'; +import { VisDefaultEditorKibanaServices } from '../../../types'; export * from './editor_form_state'; export * from './actions'; export function useEditorReducer(vis: Vis): [VisState, React.Dispatch] { - const [state, dispatch] = useReducer(editorStateReducer, vis, initEditorState); + const { services } = useKibana(); + const [state, dispatch] = useReducer( + createEditorStateReducer(services.data.search), + vis, + initEditorState + ); useEffect(() => { const handleVisUpdate = (params: VisParams) => { diff --git a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts index 73675e75cbe36..67220fd9fd91b 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/components/sidebar/state/reducers.ts @@ -20,7 +20,7 @@ import { cloneDeep } from 'lodash'; import { Vis, VisState } from 'src/legacy/core_plugins/visualizations/public'; -import { createAggConfigs, AggGroupNames } from '../../../legacy_imports'; +import { AggGroupNames, DataPublicPluginStart } from '../../../../../../../plugins/data/public'; import { EditorStateActionTypes } from './constants'; import { getEnabledMetricAggsCount } from '../../agg_group_helper'; import { EditorAction } from './actions'; @@ -29,7 +29,9 @@ function initEditorState(vis: Vis) { return vis.copyCurrentState(true); } -function editorStateReducer(state: VisState, action: EditorAction): VisState { +const createEditorStateReducer = ({ + aggs: { createAggConfigs }, +}: DataPublicPluginStart['search']) => (state: VisState, action: EditorAction): VisState => { switch (action.type) { case EditorStateActionTypes.ADD_NEW_AGG: { const { schema } = action.payload; @@ -181,6 +183,6 @@ function editorStateReducer(state: VisState, action: EditorAction): VisState { }; } } -} +}; -export { editorStateReducer, initEditorState }; +export { createEditorStateReducer, initEditorState }; diff --git a/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts b/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts deleted file mode 100644 index 50028d8c970f4..0000000000000 --- a/src/legacy/core_plugins/vis_default_editor/public/legacy_imports.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* `ui/agg_types` dependencies */ -export { BUCKET_TYPES, METRIC_TYPES } from '../../../../plugins/data/public'; -export { - AggGroupNames, - aggGroupNamesMap, - AggParam, - AggParamType, - AggType, - aggTypes, - createAggConfigs, - FieldParamType, - IAggConfig, - IAggConfigs, - IAggGroupNames, - IAggType, - IFieldParamType, - termsAggFilter, -} from 'ui/agg_types'; -export { aggTypeFilters, propFilter } from 'ui/agg_types'; -export { aggTypeFieldFilters } from 'ui/agg_types'; -export { MetricAggType, IMetricAggType } from 'ui/agg_types'; -export { parentPipelineType } from 'ui/agg_types'; -export { siblingPipelineType } from 'ui/agg_types'; -export { isType, isStringType } from 'ui/agg_types'; -export { OptionedValueProp, OptionedParamEditorProps, OptionedParamType } from 'ui/agg_types'; -export { isValidInterval } from 'ui/agg_types'; -export { AggParamOption } from 'ui/agg_types'; -export { CidrMask } from 'ui/agg_types'; diff --git a/src/legacy/core_plugins/vis_default_editor/public/types.ts b/src/legacy/core_plugins/vis_default_editor/public/types.ts new file mode 100644 index 0000000000000..22fc24005994d --- /dev/null +++ b/src/legacy/core_plugins/vis_default_editor/public/types.ts @@ -0,0 +1,24 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { DataPublicPluginStart } from 'src/plugins/data/public'; + +export interface VisDefaultEditorKibanaServices { + data: DataPublicPluginStart; +} diff --git a/src/legacy/core_plugins/vis_default_editor/public/utils.test.ts b/src/legacy/core_plugins/vis_default_editor/public/utils.test.ts index b050979b7b338..f3912450ba670 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/utils.test.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/utils.test.ts @@ -18,9 +18,7 @@ */ import { groupAndSortBy } from './utils'; -import { AggGroupNames } from './legacy_imports'; - -jest.mock('ui/new_platform'); +import { AggGroupNames } from 'src/plugins/data/public'; const aggs = [ { diff --git a/src/legacy/core_plugins/vis_default_editor/public/vis_options_props.tsx b/src/legacy/core_plugins/vis_default_editor/public/vis_options_props.tsx index 18fbba1b039b5..2e8f20946c73a 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/vis_options_props.tsx +++ b/src/legacy/core_plugins/vis_default_editor/public/vis_options_props.tsx @@ -17,8 +17,8 @@ * under the License. */ +import { IAggConfigs } from 'src/plugins/data/public'; import { PersistedState } from '../../../../plugins/visualizations/public'; -import { IAggConfigs } from './legacy_imports'; import { Vis } from '../../visualizations/public'; export interface VisOptionsProps { diff --git a/src/legacy/core_plugins/vis_default_editor/public/vis_type_agg_filter.ts b/src/legacy/core_plugins/vis_default_editor/public/vis_type_agg_filter.ts index fcb06f73513b0..3ff212c43e6e8 100644 --- a/src/legacy/core_plugins/vis_default_editor/public/vis_type_agg_filter.ts +++ b/src/legacy/core_plugins/vis_default_editor/public/vis_type_agg_filter.ts @@ -16,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ -import { IndexPattern } from 'src/plugins/data/public'; -import { IAggType, IAggConfig, aggTypeFilters, propFilter } from './legacy_imports'; +import { IAggType, IAggConfig, IndexPattern, search } from '../../../../plugins/data/public'; +const { aggTypeFilters, propFilter } = search.aggs; const filterByName = propFilter('name'); /** diff --git a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts index b769030a04fb1..cd7a8e740d85d 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/legacy_imports.ts @@ -18,4 +18,3 @@ */ export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; -export { AggGroupNames, Schemas } from 'ui/agg_types'; diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.test.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.test.ts index 3bddc94929cf5..22c32895d6803 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.test.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_fn.test.ts @@ -23,21 +23,8 @@ import { functionWrapper } from '../../../../plugins/expressions/common/expressi jest.mock('ui/new_platform'); -jest.mock('../../vis_default_editor/public/legacy_imports', () => ({ - propFilter: jest.fn(), - AggGroupNames: { - Buckets: 'buckets', - Metrics: 'metrics', - }, - aggTypeFilters: { - addFilter: jest.fn(), - }, - BUCKET_TYPES: { - DATE_HISTOGRAM: 'date_histogram', - }, - METRIC_TYPES: { - TOP_HITS: 'top_hits', - }, +jest.mock('../../vis_default_editor/public', () => ({ + Schemas: class {}, })); describe('interpreter/functions#metric', () => { diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts index 5813465cc3f00..cce5864aa50a1 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.test.ts @@ -36,21 +36,8 @@ import { createMetricVisTypeDefinition } from './metric_vis_type'; jest.mock('ui/new_platform'); -jest.mock('../../vis_default_editor/public/legacy_imports', () => ({ - propFilter: jest.fn(), - AggGroupNames: { - Buckets: 'buckets', - Metrics: 'metrics', - }, - aggTypeFilters: { - addFilter: jest.fn(), - }, - BUCKET_TYPES: { - DATE_HISTOGRAM: 'date_histogram', - }, - METRIC_TYPES: { - TOP_HITS: 'top_hits', - }, +jest.mock('../../vis_default_editor/public', () => ({ + Schemas: class {}, })); describe('metric_vis - createMetricVisTypeDefinition', () => { diff --git a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts index 0b8d9b17659f4..f29164f7e540d 100644 --- a/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts +++ b/src/legacy/core_plugins/vis_type_metric/public/metric_vis_type.ts @@ -22,8 +22,9 @@ import { i18n } from '@kbn/i18n'; import { MetricVisComponent } from './components/metric_vis_component'; import { MetricVisOptions } from './components/metric_vis_options'; import { ColorModes } from '../../vis_type_vislib/public'; -import { Schemas, AggGroupNames } from './legacy_imports'; import { ColorSchemas, colorSchemas } from '../../../../plugins/charts/public'; +import { AggGroupNames } from '../../../../plugins/data/public'; +import { Schemas } from '../../vis_default_editor/public'; export const createMetricVisTypeDefinition = () => ({ name: 'metric', diff --git a/src/legacy/core_plugins/vis_type_table/public/agg_table/__tests__/agg_table.js b/src/legacy/core_plugins/vis_type_table/public/agg_table/__tests__/agg_table.js index 91581923b05cb..8edef2ea16353 100644 --- a/src/legacy/core_plugins/vis_type_table/public/agg_table/__tests__/agg_table.js +++ b/src/legacy/core_plugins/vis_type_table/public/agg_table/__tests__/agg_table.js @@ -27,7 +27,8 @@ import { oneTermOneHistogramBucketWithTwoMetricsOneTopHitOneDerivative, } from 'fixtures/fake_hierarchical_data'; import sinon from 'sinon'; -import { tabifyAggResponse, npStart } from '../../legacy_imports'; +import { npStart } from '../../legacy_imports'; +import { search } from '../../../../../../plugins/data/public'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; import { round } from 'lodash'; import { tableVisTypeDefinition } from '../../table_vis_type'; @@ -39,6 +40,8 @@ import { getAngularModule } from '../../get_inner_angular'; import { initTableVisLegacyModule } from '../../table_vis_legacy_module'; import { tableVisResponseHandler } from '../../table_vis_response_handler'; +const { tabifyAggResponse } = search; + describe('Table Vis - AggTable Directive', function() { let $rootScope; let $compile; diff --git a/src/legacy/core_plugins/vis_type_table/public/agg_table/__tests__/agg_table_group.js b/src/legacy/core_plugins/vis_type_table/public/agg_table/__tests__/agg_table_group.js index 4d62551dcf396..89900d2144030 100644 --- a/src/legacy/core_plugins/vis_type_table/public/agg_table/__tests__/agg_table_group.js +++ b/src/legacy/core_plugins/vis_type_table/public/agg_table/__tests__/agg_table_group.js @@ -21,13 +21,16 @@ import $ from 'jquery'; import ngMock from 'ng_mock'; import expect from '@kbn/expect'; import { metricOnly, threeTermBuckets } from 'fixtures/fake_hierarchical_data'; -import { tabifyAggResponse, npStart } from '../../legacy_imports'; +import { npStart } from '../../legacy_imports'; +import { search } from '../../../../../../plugins/data/public'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; import { getAngularModule } from '../../get_inner_angular'; import { initTableVisLegacyModule } from '../../table_vis_legacy_module'; import { tableVisResponseHandler } from '../../table_vis_response_handler'; import { start as visualizationsStart } from '../../../../visualizations/public/np_ready/public/legacy'; +const { tabifyAggResponse } = search; + describe('Table Vis - AggTableGroup Directive', function() { let $rootScope; let $compile; diff --git a/src/legacy/core_plugins/vis_type_table/public/components/table_vis_options.tsx b/src/legacy/core_plugins/vis_type_table/public/components/table_vis_options.tsx index 8cc0ca2456867..30a9526273166 100644 --- a/src/legacy/core_plugins/vis_type_table/public/components/table_vis_options.tsx +++ b/src/legacy/core_plugins/vis_type_table/public/components/table_vis_options.tsx @@ -24,11 +24,13 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { VisOptionsProps } from 'src/legacy/core_plugins/vis_default_editor/public'; -import { tabifyGetColumns } from '../legacy_imports'; +import { search } from '../../../../../plugins/data/public'; import { NumberInputOption, SwitchOption, SelectOption } from '../../../vis_type_vislib/public'; import { TableVisParams } from '../types'; import { totalAggregations } from './utils'; +const { tabifyGetColumns } = search; + function TableOptions({ aggs, stateParams, diff --git a/src/legacy/core_plugins/vis_type_table/public/get_inner_angular.ts b/src/legacy/core_plugins/vis_type_table/public/get_inner_angular.ts index 6fb5658d8e815..6208e358b4184 100644 --- a/src/legacy/core_plugins/vis_type_table/public/get_inner_angular.ts +++ b/src/legacy/core_plugins/vis_type_table/public/get_inner_angular.ts @@ -25,14 +25,14 @@ import 'angular-recursion'; import { i18nDirective, i18nFilter, I18nProvider } from '@kbn/i18n/angular'; import { CoreStart, LegacyCoreStart, IUiSettingsClient } from 'kibana/public'; import { - PrivateProvider, + initAngularBootstrap, PaginateDirectiveProvider, PaginateControlsDirectiveProvider, + PrivateProvider, watchMultiDecorator, KbnAccessibleClickProvider, configureAppAngularModule, -} from './legacy_imports'; -import { initAngularBootstrap } from '../../../../plugins/kibana_legacy/public'; +} from '../../../../plugins/kibana_legacy/public'; initAngularBootstrap(); diff --git a/src/legacy/core_plugins/vis_type_table/public/legacy_imports.ts b/src/legacy/core_plugins/vis_type_table/public/legacy_imports.ts index 7b584f8069338..287b6c172ffd9 100644 --- a/src/legacy/core_plugins/vis_type_table/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_type_table/public/legacy_imports.ts @@ -19,16 +19,3 @@ export { npSetup, npStart } from 'ui/new_platform'; export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; -export { IAggConfig, AggGroupNames, Schemas } from 'ui/agg_types'; -// @ts-ignore -export { PaginateDirectiveProvider } from 'ui/directives/paginate'; -// @ts-ignore -export { PaginateControlsDirectiveProvider } from 'ui/directives/paginate'; -import { search } from '../../../../plugins/data/public'; -export const { tabifyAggResponse, tabifyGetColumns } = search; -export { - configureAppAngularModule, - KbnAccessibleClickProvider, - PrivateProvider, - watchMultiDecorator, -} from '../../../../plugins/kibana_legacy/public'; diff --git a/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts b/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts index 6d4e94c6292a6..327a47093f535 100644 --- a/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts +++ b/src/legacy/core_plugins/vis_type_table/public/table_vis_controller.test.ts @@ -34,8 +34,13 @@ import { stubFields } from '../../../../plugins/data/public/stubs'; import { tableVisResponseHandler } from './table_vis_response_handler'; import { coreMock } from '../../../../core/public/mocks'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { createAggConfigs } from 'ui/agg_types'; -import { tabifyAggResponse, IAggConfig } from './legacy_imports'; +import { npStart } from './legacy_imports'; +import { IAggConfig, search } from '../../../../plugins/data/public'; + +// should be mocked once get rid of 'ui/new_platform' legacy imports +const { createAggConfigs } = npStart.plugins.data.search.aggs; + +const { tabifyAggResponse } = search; jest.mock('ui/new_platform'); jest.mock('../../../../plugins/kibana_legacy/public/angular/angular_config', () => ({ diff --git a/src/legacy/core_plugins/vis_type_table/public/table_vis_type.ts b/src/legacy/core_plugins/vis_type_table/public/table_vis_type.ts index 970bf1ba7ce64..e70b09904253f 100644 --- a/src/legacy/core_plugins/vis_type_table/public/table_vis_type.ts +++ b/src/legacy/core_plugins/vis_type_table/public/table_vis_type.ts @@ -18,7 +18,8 @@ */ import { i18n } from '@kbn/i18n'; -import { AggGroupNames, Schemas } from './legacy_imports'; +import { AggGroupNames } from '../../../../plugins/data/public'; +import { Schemas } from '../../vis_default_editor/public'; import { Vis } from '../../visualizations/public'; import { tableVisResponseHandler } from './table_vis_response_handler'; // @ts-ignore diff --git a/src/legacy/core_plugins/vis_type_tagcloud/public/legacy_imports.ts b/src/legacy/core_plugins/vis_type_tagcloud/public/legacy_imports.ts index 0d76bc5d8b68b..cd7a8e740d85d 100644 --- a/src/legacy/core_plugins/vis_type_tagcloud/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_type_tagcloud/public/legacy_imports.ts @@ -17,5 +17,4 @@ * under the License. */ -export { Schemas } from 'ui/agg_types'; export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; diff --git a/src/legacy/core_plugins/vis_type_tagcloud/public/tag_cloud_type.ts b/src/legacy/core_plugins/vis_type_tagcloud/public/tag_cloud_type.ts index 34d15287169c0..9a522fe6e648e 100644 --- a/src/legacy/core_plugins/vis_type_tagcloud/public/tag_cloud_type.ts +++ b/src/legacy/core_plugins/vis_type_tagcloud/public/tag_cloud_type.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; -import { Schemas } from './legacy_imports'; +import { Schemas } from '../../vis_default_editor/public'; import { Status } from '../../visualizations/public'; import { TagCloudOptions } from './components/tag_cloud_options'; diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/__snapshots__/area_decorator.test.js.snap b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/__snapshots__/area_decorator.test.js.snap index 56504ca11ca39..6506b838ff288 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/__snapshots__/area_decorator.test.js.snap +++ b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/__snapshots__/area_decorator.test.js.snap @@ -22,12 +22,8 @@ exports[`src/legacy/core_plugins/metrics/public/visualizations/views/timeseries/ }, } } + color="rgb(0, 156, 224)" curve={9} - customSeriesColors={ - Array [ - "rgb(0, 156, 224)", - ] - } data={ Array [ Array [ diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/__snapshots__/bar_decorator.test.js.snap b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/__snapshots__/bar_decorator.test.js.snap index 6317973cef536..c337c0dc77a2f 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/__snapshots__/bar_decorator.test.js.snap +++ b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/__snapshots__/bar_decorator.test.js.snap @@ -15,11 +15,7 @@ exports[`src/legacy/core_plugins/metrics/public/visualizations/views/timeseries/ }, } } - customSeriesColors={ - Array [ - "rgb(0, 156, 224)", - ] - } + color="rgb(0, 156, 224)" data={ Array [ Array [ diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/area_decorator.js b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/area_decorator.js index 411c0813cad7c..923024ff690a4 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/area_decorator.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/area_decorator.js @@ -43,7 +43,6 @@ export function AreaSeriesDecorator({ }) { const id = seriesId; const groupId = seriesGroupId; - const customSeriesColors = [color]; const areaSeriesStyle = getAreaStyles({ points, lines, color }); const seriesSettings = { @@ -51,7 +50,7 @@ export function AreaSeriesDecorator({ name, groupId, data, - customSeriesColors, + color, hideInLegend, xAccessor: X_ACCESSOR_INDEX, yAccessors: Y_ACCESSOR_INDEXES, diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/bar_decorator.js b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/bar_decorator.js index 9cc8931b48d9f..6d2cd7b8dd935 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/bar_decorator.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/decorators/bar_decorator.js @@ -42,7 +42,6 @@ export function BarSeriesDecorator({ }) { const id = seriesId; const groupId = seriesGroupId; - const customSeriesColors = [color]; const barSeriesStyle = getBarStyles(bars, color); const seriesSettings = { @@ -50,7 +49,7 @@ export function BarSeriesDecorator({ name, groupId, data, - customSeriesColors, + color, hideInLegend, xAccessor: X_ACCESSOR_INDEX, yAccessors: Y_ACCESSOR_INDEXES, diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/index.js b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/index.js index 75554a476bdea..5673f560214c7 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/index.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/visualizations/views/timeseries/index.js @@ -99,6 +99,7 @@ export const TimeSeries = ({ @@ -226,6 +227,7 @@ exports[`ValueAxesPanel component should init with the default set of props 1`] diff --git a/src/legacy/core_plugins/vis_type_vislib/public/components/options/metrics_axes/__snapshots__/value_axis_options.test.tsx.snap b/src/legacy/core_plugins/vis_type_vislib/public/components/options/metrics_axes/__snapshots__/value_axis_options.test.tsx.snap index 00e1b1cce5ea8..b89d193c7c751 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/components/options/metrics_axes/__snapshots__/value_axis_options.test.tsx.snap +++ b/src/legacy/core_plugins/vis_type_vislib/public/components/options/metrics_axes/__snapshots__/value_axis_options.test.tsx.snap @@ -118,6 +118,7 @@ exports[`ValueAxisOptions component should init with the default set of props 1` /> ({ SeriesPanel: () => 'SeriesPanel', })); diff --git a/src/legacy/core_plugins/vis_type_vislib/public/components/options/metrics_axes/index.tsx b/src/legacy/core_plugins/vis_type_vislib/public/components/options/metrics_axes/index.tsx index 82b64e4185ed2..a6f4a967d9c76 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/components/options/metrics_axes/index.tsx +++ b/src/legacy/core_plugins/vis_type_vislib/public/components/options/metrics_axes/index.tsx @@ -21,7 +21,7 @@ import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { cloneDeep, uniq, get } from 'lodash'; import { EuiSpacer } from '@elastic/eui'; -import { IAggConfig } from '../../../legacy_imports'; +import { IAggConfig } from 'src/plugins/data/public'; import { BasicVislibParams, ValueAxis, SeriesParam, Axis } from '../../../types'; import { ValidationVisOptionsProps } from '../../common'; import { SeriesPanel } from './series_panel'; diff --git a/src/legacy/core_plugins/vis_type_vislib/public/gauge.ts b/src/legacy/core_plugins/vis_type_vislib/public/gauge.ts index c78925d5316b0..4610bd37db5f1 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/gauge.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/gauge.ts @@ -19,8 +19,8 @@ import { i18n } from '@kbn/i18n'; -import { RangeValues } from '../../vis_default_editor/public'; -import { Schemas, AggGroupNames } from './legacy_imports'; +import { RangeValues, Schemas } from '../../vis_default_editor/public'; +import { AggGroupNames } from '../../../../plugins/data/public'; import { GaugeOptions } from './components/options'; import { getGaugeCollections, Alignments, ColorModes, GaugeTypes } from './utils/collections'; import { createVislibVisController } from './vis_controller'; diff --git a/src/legacy/core_plugins/vis_type_vislib/public/goal.ts b/src/legacy/core_plugins/vis_type_vislib/public/goal.ts index d2fdb9543d827..c918128d01f11 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/goal.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/goal.ts @@ -19,12 +19,13 @@ import { i18n } from '@kbn/i18n'; -import { Schemas, AggGroupNames } from './legacy_imports'; import { GaugeOptions } from './components/options'; import { getGaugeCollections, GaugeTypes, ColorModes } from './utils/collections'; import { createVislibVisController } from './vis_controller'; import { VisTypeVislibDependencies } from './plugin'; import { ColorSchemas } from '../../../../plugins/charts/public'; +import { AggGroupNames } from '../../../../plugins/data/public'; +import { Schemas } from '../../vis_default_editor/public'; export const createGoalVisTypeDefinition = (deps: VisTypeVislibDependencies) => ({ name: 'goal', diff --git a/src/legacy/core_plugins/vis_type_vislib/public/heatmap.ts b/src/legacy/core_plugins/vis_type_vislib/public/heatmap.ts index c8ce335f09e78..39a583f3c9641 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/heatmap.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/heatmap.ts @@ -19,8 +19,8 @@ import { i18n } from '@kbn/i18n'; -import { RangeValues } from '../../vis_default_editor/public'; -import { Schemas, AggGroupNames } from './legacy_imports'; +import { RangeValues, Schemas } from '../../vis_default_editor/public'; +import { AggGroupNames } from '../../../../plugins/data/public'; import { AxisTypes, getHeatmapCollections, Positions, ScaleTypes } from './utils/collections'; import { HeatmapOptions } from './components/options'; import { createVislibVisController } from './vis_controller'; diff --git a/src/legacy/core_plugins/vis_type_vislib/public/histogram.ts b/src/legacy/core_plugins/vis_type_vislib/public/histogram.ts index 7b9b008481c40..15ef369e5150e 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/histogram.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/histogram.ts @@ -23,8 +23,8 @@ import { palettes } from '@elastic/eui/lib/services'; // @ts-ignore import { euiPaletteColorBlind } from '@elastic/eui/lib/services'; -import { Schemas, AggGroupNames } from './legacy_imports'; - +import { AggGroupNames } from '../../../../plugins/data/public'; +import { Schemas } from '../../vis_default_editor/public'; import { Positions, ChartTypes, diff --git a/src/legacy/core_plugins/vis_type_vislib/public/horizontal_bar.ts b/src/legacy/core_plugins/vis_type_vislib/public/horizontal_bar.ts index eca26b4f55f60..8b5811628855c 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/horizontal_bar.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/horizontal_bar.ts @@ -23,8 +23,8 @@ import { palettes } from '@elastic/eui/lib/services'; // @ts-ignore import { euiPaletteColorBlind } from '@elastic/eui/lib/services'; -import { Schemas, AggGroupNames } from './legacy_imports'; - +import { AggGroupNames } from '../../../../plugins/data/public'; +import { Schemas } from '../../vis_default_editor/public'; import { Positions, ChartTypes, diff --git a/src/legacy/core_plugins/vis_type_vislib/public/legacy_imports.ts b/src/legacy/core_plugins/vis_type_vislib/public/legacy_imports.ts index 343fda44340d1..2b177bff98d56 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/legacy_imports.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/legacy_imports.ts @@ -19,7 +19,6 @@ import { npStart } from 'ui/new_platform'; export const { createFiltersFromEvent } = npStart.plugins.data.actions; -export { AggType, AggGroupNames, IAggConfig, IAggType, Schemas } from 'ui/agg_types'; export { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; import { search } from '../../../../plugins/data/public'; export const { tabifyAggResponse, tabifyGetColumns } = search; diff --git a/src/legacy/core_plugins/vis_type_vislib/public/line.ts b/src/legacy/core_plugins/vis_type_vislib/public/line.ts index 7aaad52ed8841..ac4cda869fe29 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/line.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/line.ts @@ -23,7 +23,8 @@ import { palettes } from '@elastic/eui/lib/services'; // @ts-ignore import { euiPaletteColorBlind } from '@elastic/eui/lib/services'; -import { Schemas, AggGroupNames } from './legacy_imports'; +import { AggGroupNames } from '../../../../plugins/data/public'; +import { Schemas } from '../../vis_default_editor/public'; import { Positions, ChartTypes, diff --git a/src/legacy/core_plugins/vis_type_vislib/public/pie.ts b/src/legacy/core_plugins/vis_type_vislib/public/pie.ts index b56dba659ffc8..0f1bd93f5b5bd 100644 --- a/src/legacy/core_plugins/vis_type_vislib/public/pie.ts +++ b/src/legacy/core_plugins/vis_type_vislib/public/pie.ts @@ -19,7 +19,8 @@ import { i18n } from '@kbn/i18n'; -import { Schemas, AggGroupNames } from './legacy_imports'; +import { AggGroupNames } from '../../../../plugins/data/public'; +import { Schemas } from '../../vis_default_editor/public'; import { PieOptions } from './components/options'; import { getPositions, Positions } from './utils/collections'; import { createVislibVisController } from './vis_controller'; diff --git a/src/legacy/server/status/constants.js b/src/legacy/server/status/constants.js index d16e46008acc8..3bb23749bae87 100644 --- a/src/legacy/server/status/constants.js +++ b/src/legacy/server/status/constants.js @@ -17,4 +17,4 @@ * under the License. */ -export const KIBANA_STATS_TYPE = 'kibana_stats'; // kibana stats per 5s intervals +export const KIBANA_STATS_TYPE = 'oss_kibana_stats'; // kibana stats per 5s intervals diff --git a/src/legacy/ui/public/agg_types/index.ts b/src/legacy/ui/public/agg_types/index.ts deleted file mode 100644 index 75c2cd4317872..0000000000000 --- a/src/legacy/ui/public/agg_types/index.ts +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * Nothing to see here! - * - * Agg Types have moved to the new platform, and are being - * re-exported from ui/agg_types for backwards compatibility. - */ - -import { npStart } from 'ui/new_platform'; - -// runtime contracts -const { types } = npStart.plugins.data.search.aggs; -export const aggTypes = types.getAll(); -export const { createAggConfigs } = npStart.plugins.data.search.aggs; -export const { - AggConfig, - AggType, - aggTypeFieldFilters, - FieldParamType, - MetricAggType, - parentPipelineAggHelper, - siblingPipelineAggHelper, -} = npStart.plugins.data.search.__LEGACY; - -// types -export { - AggGroupNames, - AggParam, - AggParamOption, - AggParamType, - AggTypeFieldFilters, - AggTypeFilters, - BUCKET_TYPES, - DateRangeKey, - IAggConfig, - IAggConfigs, - IAggGroupNames, - IAggType, - IFieldParamType, - IMetricAggType, - IpRangeKey, - METRIC_TYPES, - OptionedParamEditorProps, - OptionedParamType, - OptionedValueProp, -} from '../../../../plugins/data/public'; - -// static code -import { search } from '../../../../plugins/data/public'; -export const { - aggGroupNamesMap, - aggTypeFilters, - CidrMask, - convertDateRangeToString, - convertIPRangeToString, - intervalOptions, - isDateHistogramBucketAggConfig, - isStringType, - isType, - isValidInterval, - parentPipelineType, - propFilter, - siblingPipelineType, - termsAggFilter, -} = search.aggs; - -export { ISchemas, Schemas, Schema } from '../../../core_plugins/vis_default_editor/public/schemas'; diff --git a/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx b/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx index 39312c9340ff9..97abdcb10016d 100644 --- a/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx +++ b/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx @@ -19,14 +19,7 @@ import React, { Component } from 'react'; import { Subscription } from 'rxjs'; -import { - Comparators, - EuiFlexGroup, - EuiFlexItem, - EuiSpacer, - // @ts-ignore - Query, -} from '@elastic/eui'; +import { Comparators, EuiFlexGroup, EuiFlexItem, EuiSpacer, Query } from '@elastic/eui'; import { useParams } from 'react-router-dom'; import { CallOuts } from './components/call_outs'; @@ -38,7 +31,7 @@ import { ComponentRegistry } from '../'; import { getAriaName, toEditableConfig, DEFAULT_CATEGORY } from './lib'; -import { FieldSetting, IQuery, SettingsChanges } from './types'; +import { FieldSetting, SettingsChanges } from './types'; interface AdvancedSettingsProps { enableSaving: boolean; @@ -54,7 +47,7 @@ interface AdvancedSettingsComponentProps extends AdvancedSettingsProps { interface AdvancedSettingsState { footerQueryMatched: boolean; - query: IQuery; + query: Query; filteredSettings: Record; } @@ -156,7 +149,7 @@ export class AdvancedSettingsComponent extends Component< }, {}); } - onQueryChange = ({ query }: { query: IQuery }) => { + onQueryChange = ({ query }: { query: Query }) => { this.setState({ query, filteredSettings: this.mapSettings(Query.execute(query, this.settings)), diff --git a/src/plugins/advanced_settings/public/management_app/components/search/search.tsx b/src/plugins/advanced_settings/public/management_app/components/search/search.tsx index 51402296a44a2..74e4894a27a6d 100644 --- a/src/plugins/advanced_settings/public/management_app/components/search/search.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/search/search.tsx @@ -19,19 +19,14 @@ import React, { Fragment, PureComponent } from 'react'; import { i18n } from '@kbn/i18n'; -import { - // @ts-ignore - EuiSearchBar, - EuiFormErrorText, -} from '@elastic/eui'; -import { IQuery } from '../../types'; +import { EuiSearchBar, EuiFormErrorText, Query } from '@elastic/eui'; import { getCategoryName } from '../../lib'; interface SearchProps { categories: string[]; - query: IQuery; - onQueryChange: ({ query }: { query: IQuery }) => void; + query: Query; + onQueryChange: ({ query }: { query: Query }) => void; } export class Search extends PureComponent { @@ -53,7 +48,7 @@ export class Search extends PureComponent { parseErrorMessage: null, }; - onChange = ({ query, error }: { query: IQuery; error: { message: string } }) => { + onChange = ({ query, error }: { query: Query | null; error: { message: string } | null }) => { if (error) { this.setState({ isSearchTextValid: false, @@ -66,7 +61,7 @@ export class Search extends PureComponent { isSearchTextValid: true, parseErrorMessage: null, }); - this.props.onQueryChange({ query }); + this.props.onQueryChange({ query: query! }); }; render() { @@ -82,12 +77,12 @@ export class Search extends PureComponent { const filters = [ { - type: 'field_value_selection', + type: 'field_value_selection' as const, field: 'category', name: i18n.translate('advancedSettings.categorySearchLabel', { defaultMessage: 'Category', }), - multiSelect: 'or', + multiSelect: 'or' as const, options: this.categories, }, ]; diff --git a/src/plugins/advanced_settings/public/management_app/types.ts b/src/plugins/advanced_settings/public/management_app/types.ts index ee9b9b0535b79..6e243926f7d7d 100644 --- a/src/plugins/advanced_settings/public/management_app/types.ts +++ b/src/plugins/advanced_settings/public/management_app/types.ts @@ -54,9 +54,3 @@ export interface FieldState { isInvalid?: boolean; error?: string | null; } - -export interface IQuery { - ast: any; // incomplete - text: string; - syntax: any; // incomplete -} diff --git a/src/plugins/data/common/field_formats/utils/serialize.ts b/src/plugins/data/common/field_formats/utils/serialize.ts index 9931f55c30a9e..1092c90d19451 100644 --- a/src/plugins/data/common/field_formats/utils/serialize.ts +++ b/src/plugins/data/common/field_formats/utils/serialize.ts @@ -17,7 +17,7 @@ * under the License. */ -import { IAggConfig } from '../../../../../legacy/ui/public/agg_types'; +import { IAggConfig } from 'src/plugins/data/public'; import { SerializedFieldFormat } from '../../../../expressions/common/types'; export const serializeFieldFormat = (agg: IAggConfig): SerializedFieldFormat => { diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 07d8d302bc18c..dad3a8e639bc5 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -513,7 +513,7 @@ export interface Filter { // Warning: (ae-missing-release-tag) "FilterBar" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export const FilterBar: React.ComponentClass, any> & { +export const FilterBar: React.ComponentClass, any> & { WrappedComponent: React.ComponentType; }; @@ -1322,7 +1322,7 @@ export interface QueryState { // Warning: (ae-missing-release-tag) "QueryStringInput" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export const QueryStringInput: React.FC>; +export const QueryStringInput: React.FC>; // @public (undocumented) export type QuerySuggestion = QuerySuggestionBasic | QuerySuggestionField; @@ -1531,8 +1531,8 @@ export const search: { // Warning: (ae-missing-release-tag) "SearchBar" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export const SearchBar: React.ComponentClass, "query" | "isLoading" | "indexPatterns" | "filters" | "onQueryChange" | "customSubmitButton" | "screenTitle" | "dataTestSubj" | "showQueryBar" | "showQueryInput" | "showFilterBar" | "showDatePicker" | "showAutoRefreshOnly" | "isRefreshPaused" | "refreshInterval" | "dateRangeFrom" | "dateRangeTo" | "showSaveQuery" | "savedQuery" | "onQuerySubmit" | "onSaved" | "onSavedQueryUpdated" | "onClearSavedQuery" | "onRefresh" | "timeHistory" | "onFiltersUpdated" | "onRefreshChange">, any> & { - WrappedComponent: React.ComponentType & ReactIntl.InjectedIntlProps>; +export const SearchBar: React.ComponentClass, "query" | "isLoading" | "filters" | "indexPatterns" | "refreshInterval" | "screenTitle" | "dataTestSubj" | "customSubmitButton" | "showQueryBar" | "showQueryInput" | "showFilterBar" | "showDatePicker" | "showAutoRefreshOnly" | "isRefreshPaused" | "dateRangeFrom" | "dateRangeTo" | "showSaveQuery" | "savedQuery" | "onQueryChange" | "onQuerySubmit" | "onSaved" | "onSavedQueryUpdated" | "onClearSavedQuery" | "onRefresh" | "timeHistory" | "onFiltersUpdated" | "onRefreshChange">, any> & { + WrappedComponent: React.ComponentType & ReactIntl.InjectedIntlProps>; }; // Warning: (ae-forgotten-export) The symbol "SearchBarOwnProps" needs to be exported by the entry point index.d.ts diff --git a/src/plugins/kibana_legacy/public/index.ts b/src/plugins/kibana_legacy/public/index.ts index 18f01854de259..75e81b0505747 100644 --- a/src/plugins/kibana_legacy/public/index.ts +++ b/src/plugins/kibana_legacy/public/index.ts @@ -27,6 +27,7 @@ export * from './plugin'; export { kbnBaseUrl } from '../common/kbn_base_url'; export { initAngularBootstrap } from './angular_bootstrap'; +export { PaginateDirectiveProvider, PaginateControlsDirectiveProvider } from './paginate/paginate'; export * from './angular'; export * from './notify'; export * from './utils'; diff --git a/src/plugins/kibana_legacy/public/paginate/paginate.d.ts b/src/plugins/kibana_legacy/public/paginate/paginate.d.ts new file mode 100644 index 0000000000000..a40b869b2ccbb --- /dev/null +++ b/src/plugins/kibana_legacy/public/paginate/paginate.d.ts @@ -0,0 +1,21 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export function PaginateDirectiveProvider($parse: any, $compile: any): any; +export function PaginateControlsDirectiveProvider(): any; diff --git a/src/legacy/ui/public/directives/paginate.js b/src/plugins/kibana_legacy/public/paginate/paginate.js similarity index 93% rename from src/legacy/ui/public/directives/paginate.js rename to src/plugins/kibana_legacy/public/paginate/paginate.js index 802aaaf453751..f7e623cdabd86 100644 --- a/src/legacy/ui/public/directives/paginate.js +++ b/src/plugins/kibana_legacy/public/paginate/paginate.js @@ -19,8 +19,7 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; -import { uiModules } from '../modules'; -import paginateControlsTemplate from './partials/paginate_controls.html'; +import paginateControlsTemplate from './paginate_controls.html'; export function PaginateDirectiveProvider($parse, $compile) { return { @@ -61,12 +60,9 @@ export function PaginateDirectiveProvider($parse, $compile) { controller: function($scope, $document) { const self = this; const ALL = 0; - const allSizeTitle = i18n.translate( - 'common.ui.directives.paginate.size.allDropDownOptionLabel', - { - defaultMessage: 'All', - } - ); + const allSizeTitle = i18n.translate('kibana_legacy.paginate.size.allDropDownOptionLabel', { + defaultMessage: 'All', + }); self.sizeOptions = [ { title: '10', value: 10 }, @@ -229,8 +225,3 @@ export function PaginateControlsDirectiveProvider() { template: paginateControlsTemplate, }; } - -uiModules - .get('kibana') - .directive('paginate', PaginateDirectiveProvider) - .directive('paginateControls', PaginateControlsDirectiveProvider); diff --git a/src/legacy/ui/public/directives/partials/paginate_controls.html b/src/plugins/kibana_legacy/public/paginate/paginate_controls.html similarity index 96% rename from src/legacy/ui/public/directives/partials/paginate_controls.html rename to src/plugins/kibana_legacy/public/paginate/paginate_controls.html index c40021507c233..a553bc2231720 100644 --- a/src/legacy/ui/public/directives/partials/paginate_controls.html +++ b/src/plugins/kibana_legacy/public/paginate/paginate_controls.html @@ -3,7 +3,7 @@ ng-if="linkToTop" ng-click="paginate.goToTop()" data-test-subj="paginateControlsLinkToTop" - i18n-id="common.ui.paginateControls.scrollTopButtonLabel" + i18n-id="kibana_legacy.paginate.controls.scrollTopButtonLabel" i18n-default-message="Scroll to top" > @@ -86,7 +86,7 @@
-
-
- - -
-
- -
-
-
-
- -`; - -exports[`Storyshots renderers/TimeFilter/components/DatetimeCalendar invalid date 1`] = ` -
-
-
- -
-
- - -
-
- -
-
-
-
-
-`; - -exports[`Storyshots renderers/TimeFilter/components/DatetimeCalendar with max date 1`] = ` -
-
-
- -
-
- - -
-
- -
-
-
-
-
-`; - -exports[`Storyshots renderers/TimeFilter/components/DatetimeCalendar with min date 1`] = ` -
-
-
- -
-
- - -
-
- -
-
-
-
-
-`; - -exports[`Storyshots renderers/TimeFilter/components/DatetimeCalendar with start and end date 1`] = ` -
-
-
- -
-
- - -
-
- -
-
-
-
-
-`; - -exports[`Storyshots renderers/TimeFilter/components/DatetimeCalendar with value 1`] = ` -
-
-
- -
-
- - -
-
- -
-
-
-
-
-`; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/__examples__/datetime_calendar.stories.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/__examples__/datetime_calendar.stories.tsx deleted file mode 100644 index 19004e6fdcc5a..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/__examples__/datetime_calendar.stories.tsx +++ /dev/null @@ -1,55 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { action } from '@storybook/addon-actions'; -import { storiesOf } from '@storybook/react'; -import moment from 'moment'; -import React from 'react'; -import { DatetimeCalendar } from '..'; - -const startDate = moment.utc('2019-06-27'); -const endDate = moment.utc('2019-07-04'); - -storiesOf('renderers/TimeFilter/components/DatetimeCalendar', module) - .add('default', () => ( - - )) - .add('with value', () => ( - - )) - .add('with start and end date', () => ( - - )) - .add('with min date', () => ( - - )) - .add('with max date', () => ( - - )) - .add('invalid date', () => ( - - )); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/datetime_calendar.scss b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/datetime_calendar.scss deleted file mode 100644 index 6133b9184d1c5..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/datetime_calendar.scss +++ /dev/null @@ -1,6 +0,0 @@ -.canvasDateTimeCal { - display: inline-grid; - height: 100%; - border: $euiBorderThin; - grid-template-rows: $euiSizeXL 1fr; -} diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/datetime_calendar.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/datetime_calendar.tsx deleted file mode 100644 index 8c189682c959c..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_calendar/datetime_calendar.tsx +++ /dev/null @@ -1,65 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { FunctionComponent } from 'react'; -import PropTypes from 'prop-types'; -import { Moment } from 'moment'; -import { momentObj } from 'react-moment-proptypes'; -import { EuiDatePicker } from '@elastic/eui'; -import { DatetimeInput } from '../datetime_input'; - -export interface Props { - /** Selected date (Moment date object) */ - value?: Moment; - /** Function invoked when a date is selected from the datepicker */ - onSelect: (date: Moment | null) => void; - /** Function invoked when the date text input changes */ - onValueChange: (moment: Moment) => void; // Called with a moment - /** Start date of selected date range (Moment date object) */ - startDate?: Moment; - /** End date of selected date range (Moment date object) */ - endDate?: Moment; - /** Earliest selectable date (Moment date object) */ - minDate?: Moment; - /** Latest selectable date (Moment date object) */ - maxDate?: Moment; -} - -export const DatetimeCalendar: FunctionComponent = ({ - value, - onValueChange, - onSelect, - startDate, - endDate, - minDate, - maxDate, -}) => ( -
- - -
-); - -DatetimeCalendar.propTypes = { - value: PropTypes.oneOfType([momentObj, PropTypes.object]), // Handle both valid and invalid moment objects - onSelect: PropTypes.func.isRequired, - onValueChange: PropTypes.func.isRequired, // Called with a moment - startDate: momentObj, - endDate: momentObj, - minDate: momentObj, - maxDate: momentObj, -}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/__examples__/__snapshots__/datetime_input.stories.storyshot b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/__examples__/__snapshots__/datetime_input.stories.storyshot deleted file mode 100644 index 1bda4b5246991..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/__examples__/__snapshots__/datetime_input.stories.storyshot +++ /dev/null @@ -1,67 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Storyshots renderers/TimeFilter/components/DatetimeInput default 1`] = ` -
-
- -
-
-`; - -exports[`Storyshots renderers/TimeFilter/components/DatetimeInput invalid date 1`] = ` -
-
- -
-
-`; - -exports[`Storyshots renderers/TimeFilter/components/DatetimeInput with date 1`] = ` -
-
- -
-
-`; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/__examples__/datetime_input.stories.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/__examples__/datetime_input.stories.tsx deleted file mode 100644 index 060f04da88f99..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/__examples__/datetime_input.stories.tsx +++ /dev/null @@ -1,20 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { action } from '@storybook/addon-actions'; -import { storiesOf } from '@storybook/react'; -import moment from 'moment'; -import React from 'react'; -import { DatetimeInput } from '..'; - -storiesOf('renderers/TimeFilter/components/DatetimeInput', module) - .add('default', () => ) - .add('with date', () => ( - - )) - .add('invalid date', () => ( - - )); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/datetime_input.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/datetime_input.tsx deleted file mode 100644 index 32bdcde5ddda0..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/datetime_input.tsx +++ /dev/null @@ -1,60 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { FunctionComponent, ChangeEvent } from 'react'; -import PropTypes from 'prop-types'; -import { EuiFieldText } from '@elastic/eui'; -import moment, { Moment } from 'moment'; - -export interface Props { - /** Selected string value of input */ - strValue: string; - /** Function invoked with string when input is changed */ - setStrValue: (value: string) => void; - /** Function invoked with moment when input is changed with valid datetime */ - setMoment: (value: Moment) => void; - /** Boolean denotes whether current input value is valid date */ - valid: boolean; - /** Function invoked with value validity when input is changed */ - setValid: (valid: boolean) => void; -} - -export const DatetimeInput: FunctionComponent = ({ - strValue, - setStrValue, - setMoment, - valid, - setValid, -}) => { - function check(e: ChangeEvent) { - const parsed = moment(e.target.value, 'YYYY-MM-DD HH:mm:ss', true); - if (parsed.isValid()) { - setMoment(parsed); - setValid(true); - } else { - setValid(false); - } - setStrValue(e.target.value); - } - - return ( - - ); -}; - -DatetimeInput.propTypes = { - setMoment: PropTypes.func, - strValue: PropTypes.string, - setStrValue: PropTypes.func, - valid: PropTypes.bool, - setValid: PropTypes.func, -}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/index.ts b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/index.ts deleted file mode 100644 index ff0e52580b421..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_input/index.ts +++ /dev/null @@ -1,40 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { Moment } from 'moment'; -import { compose, withState, lifecycle } from 'recompose'; -import { DatetimeInput as Component, Props as ComponentProps } from './datetime_input'; - -export interface Props { - /** Input value (Moment date object) */ - moment?: Moment; - /** Function to invoke when the input changes */ - setMoment: (m: Moment) => void; -} - -export const DatetimeInput = compose( - withState('valid', 'setValid', () => true), - withState('strValue', 'setStrValue', ({ moment }) => - moment ? moment.format('YYYY-MM-DD HH:mm:ss') : '' - ), - lifecycle({ - componentDidUpdate(prevProps) { - const prevMoment = prevProps.moment; - - // If we don't have a current moment, do nothing - if (!this.props.moment) return; - - // If we previously had a moment and it's the same as the current moment, do nothing - if (prevMoment && prevMoment.isSame(this.props.moment)) { - return; - } - - // Set the string value of the current moment and mark as valid - this.props.setStrValue(this.props.moment.format('YYYY-MM-DD HH:mm:ss')); - this.props.setValid(true); - }, - }) -)(Component); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/__examples__/__snapshots__/datetime_quick_list.stories.storyshot b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/__examples__/__snapshots__/datetime_quick_list.stories.storyshot deleted file mode 100644 index b3ec64fa55a07..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/__examples__/__snapshots__/datetime_quick_list.stories.storyshot +++ /dev/null @@ -1,249 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Storyshots renderers/TimeFilter/components/DatetimeQuickList with children 1`] = ` -
- - - - - - - - -
-`; - -exports[`Storyshots renderers/TimeFilter/components/DatetimeQuickList with start and end dates 1`] = ` -
- - - - - - - -
-`; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/__examples__/datetime_quick_list.stories.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/__examples__/datetime_quick_list.stories.tsx deleted file mode 100644 index 68ef3cf1300bc..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/__examples__/datetime_quick_list.stories.tsx +++ /dev/null @@ -1,21 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { EuiButtonEmpty } from '@elastic/eui'; -import { action } from '@storybook/addon-actions'; -import { storiesOf } from '@storybook/react'; -import React from 'react'; -import { DatetimeQuickList } from '..'; - -storiesOf('renderers/TimeFilter/components/DatetimeQuickList', module) - .add('with start and end dates', () => ( - - )) - .add('with children', () => ( - - Apply - - )); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/datetime_quick_list.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/datetime_quick_list.tsx deleted file mode 100644 index 9d5a3893dbcb8..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_quick_list/datetime_quick_list.tsx +++ /dev/null @@ -1,60 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { ReactNode, FunctionComponent } from 'react'; -import PropTypes from 'prop-types'; -import { EuiButton, EuiButtonEmpty } from '@elastic/eui'; -import 'react-datetime/css/react-datetime.css'; -import { UnitStrings } from '../../../../../i18n/units'; - -const { quickRanges: strings } = UnitStrings; - -interface Props { - /** Initial start date string */ - from: string; - /** Initial end date string */ - to: string; - - /** Function invoked when a date range is clicked */ - onSelect: (from: string, to: string) => void; - - /** Nodes to display under the date range buttons */ - children?: ReactNode; -} - -const quickRanges = [ - { from: 'now/d', to: 'now', display: strings.getTodayLabel() }, - { from: 'now-24h', to: 'now', display: strings.getLast24HoursLabel() }, - { from: 'now-7d', to: 'now', display: strings.getLast7DaysLabel() }, - { from: 'now-14d', to: 'now', display: strings.getLast2WeeksLabel() }, - { from: 'now-30d', to: 'now', display: strings.getLast30DaysLabel() }, - { from: 'now-90d', to: 'now', display: strings.getLast90DaysLabel() }, - { from: 'now-1y', to: 'now', display: strings.getLast1YearLabel() }, -]; - -export const DatetimeQuickList: FunctionComponent = ({ from, to, onSelect, children }) => ( -
- {quickRanges.map((range, i) => - from === range.from && to === range.to ? ( - onSelect(range.from, range.to)}> - {range.display} - - ) : ( - onSelect(range.from, range.to)}> - {range.display} - - ) - )} - {children} -
-); - -DatetimeQuickList.propTypes = { - from: PropTypes.string.isRequired, - to: PropTypes.string.isRequired, - onSelect: PropTypes.func.isRequired, - children: PropTypes.node, -}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/__examples__/__snapshots__/datetime_range_absolute.stories.storyshot b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/__examples__/__snapshots__/datetime_range_absolute.stories.storyshot deleted file mode 100644 index 7bf08c3d6f24e..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/__examples__/__snapshots__/datetime_range_absolute.stories.storyshot +++ /dev/null @@ -1,122 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Storyshots renderers/TimeFilter/components/DatetimeRangeAbsolute default 1`] = ` -
-
-
-
-
- -
-
- - -
-
- -
-
-
-
-
-
-
-
-
-
- -
-
- - -
-
- -
-
-
-
-
-
-
-`; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/__examples__/datetime_range_absolute.stories.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/__examples__/datetime_range_absolute.stories.tsx deleted file mode 100644 index 01d2fe49e29e8..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/__examples__/datetime_range_absolute.stories.tsx +++ /dev/null @@ -1,18 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { action } from '@storybook/addon-actions'; -import { storiesOf } from '@storybook/react'; -import moment from 'moment'; -import React from 'react'; -import { DatetimeRangeAbsolute } from '..'; - -const startDate = moment.utc('2019-06-21'); -const endDate = moment.utc('2019-07-05'); - -storiesOf('renderers/TimeFilter/components/DatetimeRangeAbsolute', module).add('default', () => ( - -)); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.scss b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.scss deleted file mode 100644 index 706bd90ad1edf..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.scss +++ /dev/null @@ -1,7 +0,0 @@ -.canvasDateTimeRangeAbsolute { - display: flex; - - > div:not(:last-child) { - margin-right: $euiSizeS; - } -} diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.tsx deleted file mode 100644 index ddd755b4a12f4..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.tsx +++ /dev/null @@ -1,74 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { FunctionComponent } from 'react'; -import PropTypes from 'prop-types'; -import { Moment } from 'moment'; -import { momentObj } from 'react-moment-proptypes'; -import { DatetimeCalendar } from '../datetime_calendar'; - -interface Props { - /** Optional initial start date moment */ - from?: Moment; - /** Optional initial end date moment */ - to?: Moment; - - /** Function invoked when a date is selected from the datetime calendar */ - onSelect: (from?: Moment, to?: Moment) => void; -} - -export const DatetimeRangeAbsolute: FunctionComponent = ({ from, to, onSelect }) => ( -
-
- onSelect(val, to)} - onSelect={val => { - if (!val || !from) { - return; - } - - // sets the time to start of day if only the date was selected - if (from.format('hh:mm:ss a') === val.format('hh:mm:ss a')) { - onSelect(val.startOf('day'), to); - } else { - onSelect(val, to); - } - }} - /> -
-
- onSelect(from, val)} - onSelect={val => { - if (!val || !to) { - return; - } - - // set the time to end of day if only the date was selected - if (to.format('hh:mm:ss a') === val.format('hh:mm:ss a')) { - onSelect(from, val.endOf('day')); - } else { - onSelect(from, val); - } - }} - /> -
-
-); - -DatetimeRangeAbsolute.propTypes = { - from: momentObj, - to: momentObj, - onSelect: PropTypes.func.isRequired, -}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/index.ts b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/index.ts deleted file mode 100644 index c6e5a77ca8af8..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/index.ts +++ /dev/null @@ -1,7 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -export { DatetimeRangeAbsolute } from './datetime_range_absolute'; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/index.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/index.tsx new file mode 100644 index 0000000000000..e2e9358bf99c6 --- /dev/null +++ b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/index.tsx @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { AdvancedSettings } from '../../../../public/lib/kibana_advanced_settings'; +import { TimeFilter as Component, Props } from './time_filter'; + +export const TimeFilter = (props: Props) => { + const customQuickRanges = (AdvancedSettings.get('timepicker:quickRanges') || []).map( + ({ from, to, display }: { from: string; to: string; display: string }) => ({ + start: from, + end: to, + label: display, + }) + ); + + const customDateFormat = AdvancedSettings.get('dateFormat'); + + return ( + + ); +}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/__examples__/__snapshots__/pretty_duration.stories.storyshot b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/__examples__/__snapshots__/pretty_duration.stories.storyshot deleted file mode 100644 index 3730cfb5f4e5c..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/__examples__/__snapshots__/pretty_duration.stories.storyshot +++ /dev/null @@ -1,13 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Storyshots renderers/TimeFilter/components/PrettyDuration with absolute dates 1`] = ` - - ~ 5 months ago to ~ 4 months ago - -`; - -exports[`Storyshots renderers/TimeFilter/components/PrettyDuration with relative dates 1`] = ` - - Last 7 days - -`; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/__examples__/pretty_duration.stories.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/__examples__/pretty_duration.stories.tsx deleted file mode 100644 index 951776f8a9558..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/__examples__/pretty_duration.stories.tsx +++ /dev/null @@ -1,13 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { storiesOf } from '@storybook/react'; -import React from 'react'; -import { PrettyDuration } from '..'; - -storiesOf('renderers/TimeFilter/components/PrettyDuration', module) - .add('with relative dates', () => ) - .add('with absolute dates', () => ); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/format_duration.ts b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/format_duration.ts deleted file mode 100644 index b713eb4d7cd5e..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/format_duration.ts +++ /dev/null @@ -1,59 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import dateMath from '@elastic/datemath'; -import moment, { Moment } from 'moment'; -import { quickRanges, QuickRange } from './quick_ranges'; -import { timeUnits, TimeUnit } from '../../../../../../common/lib/time_units'; - -const lookupByRange: { [key: string]: QuickRange } = {}; -quickRanges.forEach(frame => { - lookupByRange[`${frame.from} to ${frame.to}`] = frame; -}); - -function formatTime(time: string | Moment, roundUp = false) { - if (moment.isMoment(time)) { - return time.format('lll'); - } else { - if (time === 'now') { - return 'now'; - } else { - const tryParse = dateMath.parse(time, { roundUp }); - return moment.isMoment(tryParse) ? '~ ' + tryParse.fromNow() : time; - } - } -} - -function cantLookup(from: string, to: string) { - return `${formatTime(from)} to ${formatTime(to)}`; -} - -export function formatDuration(from: string, to: string) { - // If both parts are date math, try to look up a reasonable string - if (from && to && !moment.isMoment(from) && !moment.isMoment(to)) { - const tryLookup = lookupByRange[`${from.toString()} to ${to.toString()}`]; - if (tryLookup) { - return tryLookup.display; - } else { - const fromParts = from.toString().split('-'); - if (to.toString() === 'now' && fromParts[0] === 'now' && fromParts[1]) { - const rounded = fromParts[1].split('/'); - let text = `Last ${rounded[0]}`; - if (rounded[1]) { - const unit = rounded[1] as TimeUnit; - text = `${text} rounded to the ${timeUnits[unit]}`; - } - - return text; - } else { - return cantLookup(from, to); - } - } - // If at least one part is a moment, try to make pretty strings by parsing date math - } else { - return cantLookup(from, to); - } -} diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/quick_ranges.ts b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/quick_ranges.ts deleted file mode 100644 index 1c436d3630b53..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/lib/quick_ranges.ts +++ /dev/null @@ -1,53 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { UnitStrings } from '../../../../../../i18n/units'; - -export interface QuickRange { - /** Start date string of range */ - from: string; - /** Start date string of range */ - to: string; - /** Display name describing date range */ - display: string; -} - -const { quickRanges: strings } = UnitStrings; - -export const quickRanges: QuickRange[] = [ - { from: 'now/d', to: 'now/d', display: strings.getTodayLabel() }, - { from: 'now/w', to: 'now/w', display: strings.getThisWeekLabel() }, - { from: 'now/M', to: 'now/M', display: strings.getThisMonthLabel() }, - { from: 'now/y', to: 'now/y', display: strings.getThisYearLabel() }, - { from: 'now/d', to: 'now', display: strings.getTheDaySoFarLabel() }, - { from: 'now/w', to: 'now', display: strings.getWeekToDateLabel() }, - { from: 'now/M', to: 'now', display: strings.getMonthToDateLabel() }, - { from: 'now/y', to: 'now', display: strings.getYearToDateLabel() }, - - { from: 'now-1d/d', to: 'now-1d/d', display: strings.getYesterdayLabel() }, - { from: 'now-2d/d', to: 'now-2d/d', display: strings.getDayBeforeYesterdayLabel() }, - { from: 'now-7d/d', to: 'now-7d/d', display: strings.getThisDayLastWeek() }, - { from: 'now-1w/w', to: 'now-1w/w', display: strings.getPreviousWeekLabel() }, - { from: 'now-1M/M', to: 'now-1M/M', display: strings.getPreviousMonthLabel() }, - { from: 'now-1y/y', to: 'now-1y/y', display: strings.getPreviousYearLabel() }, - - { from: 'now-15m', to: 'now', display: strings.getLast15MinutesLabel() }, - { from: 'now-30m', to: 'now', display: strings.getLast30MinutesLabel() }, - { from: 'now-1h', to: 'now', display: strings.getLast1HourLabel() }, - { from: 'now-4h', to: 'now', display: strings.getLast4HoursLabel() }, - { from: 'now-12h', to: 'now', display: strings.getLast12HoursLabel() }, - { from: 'now-24h', to: 'now', display: strings.getLast24HoursLabel() }, - { from: 'now-7d', to: 'now', display: strings.getLast7DaysLabel() }, - { from: 'now-14d', to: 'now', display: strings.getLast2WeeksLabel() }, - - { from: 'now-30d', to: 'now', display: strings.getLast30DaysLabel() }, - { from: 'now-60d', to: 'now', display: strings.getLast60DaysLabel() }, - { from: 'now-90d', to: 'now', display: strings.getLast90DaysLabel() }, - { from: 'now-6M', to: 'now', display: strings.getLast6MonthsLabel() }, - { from: 'now-1y', to: 'now', display: strings.getLast1YearLabel() }, - { from: 'now-2y', to: 'now', display: strings.getLast2YearsLabel() }, - { from: 'now-5y', to: 'now', display: strings.getLast5YearsLabel() }, -]; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/pretty_duration.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/pretty_duration.tsx deleted file mode 100644 index f1b65c586ff0c..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/pretty_duration.tsx +++ /dev/null @@ -1,25 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { FunctionComponent } from 'react'; -import PropTypes from 'prop-types'; -import { formatDuration } from './lib/format_duration'; - -interface Props { - /** Initial start date string */ - from: string; - /** Initial end date string */ - to: string; -} - -export const PrettyDuration: FunctionComponent = ({ from, to }) => ( - {formatDuration(from, to)} -); - -PrettyDuration.propTypes = { - from: PropTypes.string.isRequired, - to: PropTypes.string.isRequired, -}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter.tsx new file mode 100644 index 0000000000000..8d28287b32066 --- /dev/null +++ b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter.tsx @@ -0,0 +1,87 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { EuiSuperDatePicker, OnTimeChangeProps, EuiSuperDatePickerCommonRange } from '@elastic/eui'; +import React from 'react'; +import PropTypes from 'prop-types'; +import { get } from 'lodash'; +import { fromExpression } from '@kbn/interpreter/common'; +import { UnitStrings } from '../../../../i18n/units'; + +const { quickRanges: strings } = UnitStrings; + +const defaultQuickRanges: EuiSuperDatePickerCommonRange[] = [ + { start: 'now-1d/d', end: 'now-1d/d', label: strings.getYesterdayLabel() }, + { start: 'now/d', end: 'now', label: strings.getTodayLabel() }, + { start: 'now-24h', end: 'now', label: strings.getLast24HoursLabel() }, + { start: 'now-7d', end: 'now', label: strings.getLast7DaysLabel() }, + { start: 'now-14d', end: 'now', label: strings.getLast2WeeksLabel() }, + { start: 'now-30d', end: 'now', label: strings.getLast30DaysLabel() }, + { start: 'now-90d', end: 'now', label: strings.getLast90DaysLabel() }, + { start: 'now-1y', end: 'now', label: strings.getLast1YearLabel() }, +]; + +export interface FilterMeta { + /** Name of datetime column to be filtered */ + column: string; + /** Start date string of filtered date range */ + start: string; + /** End date string of filtered date range */ + end: string; +} + +function getFilterMeta(filter: string): FilterMeta { + const ast = fromExpression(filter); + const column = get(ast, 'chain[0].arguments.column[0]'); + const start = get(ast, 'chain[0].arguments.from[0]'); + const end = get(ast, 'chain[0].arguments.to[0]'); + return { column, start, end }; +} + +export interface Props { + /** Initial value of the filter */ + filter: string; + /** Function invoked when the filter changes */ + commit: (filter: string) => void; + /** Elastic datemath format string */ + dateFormat?: string; + /** Array of time ranges */ + commonlyUsedRanges?: EuiSuperDatePickerCommonRange[]; +} + +export const TimeFilter = ({ filter, commit, dateFormat, commonlyUsedRanges = [] }: Props) => { + const setFilter = (column: string) => ({ start, end }: OnTimeChangeProps) => { + commit(`timefilter from="${start}" to=${end} column=${column}`); + }; + + const { column, start, end } = getFilterMeta(filter); + + return ( +
+ +
+ ); +}; + +TimeFilter.propTypes = { + filter: PropTypes.string.isRequired, + commit: PropTypes.func.isRequired, // Canvas filter + dateFormat: PropTypes.string, + commonlyUsedRanges: PropTypes.arrayOf( + PropTypes.shape({ + start: PropTypes.string.isRequired, + end: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + }) + ), +}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/__examples__/__snapshots__/time_filter.examples.storyshot b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/__examples__/__snapshots__/time_filter.examples.storyshot deleted file mode 100644 index 9c070dded5810..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/__examples__/__snapshots__/time_filter.examples.storyshot +++ /dev/null @@ -1,283 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Storyshots renderers/TimeFilter compact mode 1`] = ` -
-
- -
-
-`; - -exports[`Storyshots renderers/TimeFilter default 1`] = ` -
-
-
-
-
-
- -
-
- - -
-
- -
-
-
-
-
-
-
-
-
-
- -
-
- - -
-
- -
-
-
-
-
-
-
-
- - - - - - - - -
-
-`; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/__examples__/time_filter.examples.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/__examples__/time_filter.examples.tsx deleted file mode 100644 index b6b94bf3e4a05..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/__examples__/time_filter.examples.tsx +++ /dev/null @@ -1,25 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { action } from '@storybook/addon-actions'; -import { storiesOf } from '@storybook/react'; -import React from 'react'; -import { TimeFilter } from '..'; - -storiesOf('renderers/TimeFilter', module) - .add('default', () => ( - - )) - .add('compact mode', () => ( - - )); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/index.ts b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/index.ts deleted file mode 100644 index cdea7d6591592..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/index.ts +++ /dev/null @@ -1,7 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -export { TimeFilter } from './time_filter'; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/time_filter.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/time_filter.tsx deleted file mode 100644 index cbe9793c806e1..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_filter/time_filter.tsx +++ /dev/null @@ -1,58 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import PropTypes from 'prop-types'; -import { get } from 'lodash'; -import { fromExpression } from '@kbn/interpreter/common'; -import { TimePicker } from '../time_picker'; -import { TimePickerPopover } from '../time_picker_popover'; - -export interface FilterMeta { - /** Name of datetime column to be filtered */ - column: string; - /** Start date string of filtered date range */ - from: string; - /** End date string of filtered date range */ - to: string; -} - -function getFilterMeta(filter: string): FilterMeta { - const ast = fromExpression(filter); - const column = get(ast, 'chain[0].arguments.column[0]'); - const from = get(ast, 'chain[0].arguments.from[0]'); - const to = get(ast, 'chain[0].arguments.to[0]'); - return { column, from, to }; -} - -export interface Props { - /** Initial value of the filter */ - filter: string; - /** Function invoked when the filter changes */ - commit: (filter: string) => void; - /** Determines if compact or full-sized time picker is displayed */ - compact?: boolean; -} - -export const TimeFilter = ({ filter, commit, compact }: Props) => { - const setFilter = (column: string) => (from: string, to: string) => { - commit(`timefilter from="${from}" to=${to} column=${column}`); - }; - - const { column, from, to } = getFilterMeta(filter); - - if (compact) { - return ; - } else { - return ; - } -}; - -TimeFilter.propTypes = { - filter: PropTypes.string.isRequired, - commit: PropTypes.func.isRequired, // Canvas filter - compact: PropTypes.bool, -}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/__examples__/__snapshots__/time_picker.stories.storyshot b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/__examples__/__snapshots__/time_picker.stories.storyshot deleted file mode 100644 index 49ea8ccc5889e..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/__examples__/__snapshots__/time_picker.stories.storyshot +++ /dev/null @@ -1,256 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Storyshots renderers/TimeFilter/components/TimePicker default 1`] = ` -
-
-
-
-
-
- -
-
- - -
-
- -
-
-
-
-
-
-
-
-
-
- -
-
- - -
-
- -
-
-
-
-
-
-
-
- - - - - - - - -
-
-`; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/__examples__/time_picker.stories.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/__examples__/time_picker.stories.tsx deleted file mode 100644 index e34d2d5f58561..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/__examples__/time_picker.stories.tsx +++ /dev/null @@ -1,18 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { action } from '@storybook/addon-actions'; -import { storiesOf } from '@storybook/react'; -import moment from 'moment'; -import React from 'react'; -import { TimePicker } from '..'; - -const startDate = moment.utc('2018-04-04').toISOString(); -const endDate = moment.utc('2019-04-04').toISOString(); - -storiesOf('renderers/TimeFilter/components/TimePicker', module).add('default', () => ( - -)); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/index.ts b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/index.ts deleted file mode 100644 index a220bd5eebc21..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/index.ts +++ /dev/null @@ -1,7 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -export { TimePicker } from './time_picker'; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/time_picker.scss b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/time_picker.scss deleted file mode 100644 index 889db1fc8165d..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/time_picker.scss +++ /dev/null @@ -1,7 +0,0 @@ -.canvasTimePicker { - display: flex; - - > div:not(:last-child) { - margin-right: $euiSizeS; - } -} diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/time_picker.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/time_picker.tsx deleted file mode 100644 index 599b15524ddda..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker/time_picker.tsx +++ /dev/null @@ -1,99 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Component } from 'react'; -import PropTypes from 'prop-types'; -import dateMath from '@elastic/datemath'; -import { EuiButton } from '@elastic/eui'; -import moment from 'moment'; -import { DatetimeQuickList } from '../datetime_quick_list'; -import { DatetimeRangeAbsolute } from '../datetime_range_absolute'; -import { ComponentStrings } from '../../../../../i18n/components'; - -const { TimePicker: strings } = ComponentStrings; - -export interface Props { - /** Start date string */ - from: string; - /** End date string */ - to: string; - /** Function invoked when date range is changed */ - onSelect: (from: string, to: string) => void; -} - -export interface State { - range: { - /** Start date string of selected date range */ - from: string; - /** End date string of selected date range */ - to: string; - }; - /** Boolean denoting whether selected date range has been applied */ - isDirty: boolean; -} - -export class TimePicker extends Component { - static propTypes = { - from: PropTypes.string.isRequired, - to: PropTypes.string.isRequired, - onSelect: PropTypes.func.isRequired, - }; - - state = { - range: { from: this.props.from, to: this.props.to }, - isDirty: false, - }; - - componentDidUpdate(prevProps: Props) { - const { to, from } = this.props; - - if (prevProps.from !== from || prevProps.to !== to) { - this.setState({ - range: { from, to }, - isDirty: false, - }); - } - } - - _absoluteSelect = (from?: moment.Moment, to?: moment.Moment) => { - if (from && to) { - this.setState({ - range: { from: moment(from).toISOString(), to: moment(to).toISOString() }, - isDirty: true, - }); - } - }; - - render() { - const { onSelect } = this.props; - const { range, isDirty } = this.state; - const { from, to } = range; - - return ( -
- - - { - this.setState({ isDirty: false }); - onSelect(from, to); - }} - > - {strings.getApplyButtonLabel()} - - -
- ); - } -} diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/__examples__/__snapshots__/time_picker_popover.examples.storyshot b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/__examples__/__snapshots__/time_picker_popover.examples.storyshot deleted file mode 100644 index 7e2474dbfb79c..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/__examples__/__snapshots__/time_picker_popover.examples.storyshot +++ /dev/null @@ -1,28 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Storyshots renderers/TimeFilter/components/TimePickerPopover default 1`] = ` -
-
- -
-
-`; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/__examples__/time_picker_popover.examples.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/__examples__/time_picker_popover.examples.tsx deleted file mode 100644 index 7555de1336b3e..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/__examples__/time_picker_popover.examples.tsx +++ /dev/null @@ -1,18 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { action } from '@storybook/addon-actions'; -import { storiesOf } from '@storybook/react'; -import moment from 'moment'; -import React from 'react'; -import { TimePickerPopover } from '..'; - -const startDate = moment.utc('2019-05-04').toISOString(); -const endDate = moment.utc('2019-06-04').toISOString(); - -storiesOf('renderers/TimeFilter/components/TimePickerPopover', module).add('default', () => ( - -)); diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/index.ts b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/index.ts deleted file mode 100644 index 482580ea2e367..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/index.ts +++ /dev/null @@ -1,7 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -export { TimePickerPopover } from './time_picker_popover'; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/time_picker_popover.scss b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/time_picker_popover.scss deleted file mode 100644 index 1703c2c721dc0..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/time_picker_popover.scss +++ /dev/null @@ -1,19 +0,0 @@ -.canvasTimePickerPopover { - width: 100%; - - .canvasTimePickerPopover__button { - width: 100%; - padding: $euiSizeXS; - border: $euiBorderThin; - border-radius: $euiBorderRadius; - background-color: $euiColorEmptyShade; - - &:hover { - background-color: $euiColorLightestShade; - } - } - - .canvasTimePickerPopover__anchor { - width: 100%; - } -} diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/time_picker_popover.tsx b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/time_picker_popover.tsx deleted file mode 100644 index 8f6061b688319..0000000000000 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/time_picker_popover/time_picker_popover.tsx +++ /dev/null @@ -1,63 +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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { FunctionComponent, MouseEvent } from 'react'; -import PropTypes from 'prop-types'; -// @ts-ignore untyped local -import { Popover } from '../../../../../public/components/popover'; -import { PrettyDuration } from '../pretty_duration'; -import { formatDuration } from '../pretty_duration/lib/format_duration'; -import { TimePicker } from '../time_picker'; - -export interface Props { - /** Start date string */ - from: string; - /** End date string */ - to: string; - /** Function invoked when date range is changed */ - onSelect: (from: string, to: string) => void; -} - -export const TimePickerPopover: FunctionComponent = ({ from, to, onSelect }) => { - const button = (handleClick: (event: MouseEvent) => void) => ( - - ); - - return ( - - {({ closePopover }) => ( - { - onSelect(...args); - closePopover(); - }} - /> - )} - - ); -}; - -TimePickerPopover.propTypes = { - from: PropTypes.string.isRequired, - to: PropTypes.string.isRequired, - onSelect: PropTypes.func.isRequired, -}; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/index.js b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/index.js index 7fd6e81752b3c..cbc514e218d74 100644 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/index.js +++ b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/index.js @@ -9,7 +9,7 @@ import React from 'react'; import { toExpression } from '@kbn/interpreter/common'; import { syncFilterExpression } from '../../../public/lib/sync_filter_expression'; import { RendererStrings } from '../../../i18n'; -import { TimeFilter } from './components/time_filter'; +import { TimeFilter } from './components'; const { timeFilter: strings } = RendererStrings; diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/time_filter.scss b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/time_filter.scss new file mode 100644 index 0000000000000..442332697f318 --- /dev/null +++ b/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/time_filter.scss @@ -0,0 +1,11 @@ +.canvasTimeFilter .euiSuperDatePicker__flexWrapper { + width: 100%; + + &.euiFlexGroup--gutterSmall { + margin: 0; + + > .euiFlexItem { + margin: 0; + } + } +} \ No newline at end of file diff --git a/x-pack/legacy/plugins/canvas/i18n/units.ts b/x-pack/legacy/plugins/canvas/i18n/units.ts index 04b1fec9b1f8a..a105031e7edf7 100644 --- a/x-pack/legacy/plugins/canvas/i18n/units.ts +++ b/x-pack/legacy/plugins/canvas/i18n/units.ts @@ -72,6 +72,10 @@ export const UnitStrings = { }), }, quickRanges: { + getYesterdayLabel: () => + i18n.translate('xpack.canvas.units.quickRange.yesterday', { + defaultMessage: 'Yesterday', + }), getTodayLabel: () => i18n.translate('xpack.canvas.units.quickRange.today', { defaultMessage: 'Today', @@ -100,93 +104,5 @@ export const UnitStrings = { i18n.translate('xpack.canvas.units.quickRange.last1Year', { defaultMessage: 'Last 1 year', }), - getThisWeekLabel: () => - i18n.translate('xpack.canvas.units.quickRange.thisWeek', { - defaultMessage: 'This week', - }), - getThisMonthLabel: () => - i18n.translate('xpack.canvas.units.quickRange.thisMonth', { - defaultMessage: 'This month', - }), - getThisYearLabel: () => - i18n.translate('xpack.canvas.units.quickRange.thisYear', { - defaultMessage: 'This year', - }), - getTheDaySoFarLabel: () => - i18n.translate('xpack.canvas.units.quickRange.theDaySoFar', { - defaultMessage: 'The day so far', - }), - getWeekToDateLabel: () => - i18n.translate('xpack.canvas.units.quickRange.weekToDate', { - defaultMessage: 'Week to date', - }), - getMonthToDateLabel: () => - i18n.translate('xpack.canvas.units.quickRange.monthToDate', { - defaultMessage: 'Month to date', - }), - getYearToDateLabel: () => - i18n.translate('xpack.canvas.units.quickRange.yearToDate', { - defaultMessage: 'Year to date', - }), - getYesterdayLabel: () => - i18n.translate('xpack.canvas.units.quickRange.yesterday', { - defaultMessage: 'Yesterday', - }), - getDayBeforeYesterdayLabel: () => - i18n.translate('xpack.canvas.units.quickRange.dayBeforeYesterday', { - defaultMessage: 'Day before yesterday', - }), - getThisDayLastWeek: () => - i18n.translate('xpack.canvas.units.quickRange.thisDayLastWeek', { - defaultMessage: 'This day last week', - }), - getPreviousWeekLabel: () => - i18n.translate('xpack.canvas.units.quickRange.previousWeek', { - defaultMessage: 'Previous week', - }), - getPreviousMonthLabel: () => - i18n.translate('xpack.canvas.units.quickRange.previousMonth', { - defaultMessage: 'Previous month', - }), - getPreviousYearLabel: () => - i18n.translate('xpack.canvas.units.quickRange.previousYear', { - defaultMessage: 'Previous year', - }), - getLast15MinutesLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last15Minutes', { - defaultMessage: 'Last 15 minutes', - }), - getLast30MinutesLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last30Minutes', { - defaultMessage: 'Last 30 minutes', - }), - getLast1HourLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last1Hour', { - defaultMessage: 'Last 1 hour', - }), - getLast4HoursLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last4Hours', { - defaultMessage: 'Last 4 hours', - }), - getLast12HoursLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last12Hours', { - defaultMessage: 'Last 12 hours', - }), - getLast60DaysLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last60Days', { - defaultMessage: 'Last 60 days', - }), - getLast6MonthsLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last6Months', { - defaultMessage: 'Last 6 months', - }), - getLast2YearsLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last2Years', { - defaultMessage: 'Last 2 years', - }), - getLast5YearsLabel: () => - i18n.translate('xpack.canvas.units.quickRange.last5Years', { - defaultMessage: 'Last 5 years', - }), }, }; diff --git a/x-pack/legacy/plugins/canvas/public/components/custom_element_modal/__examples__/__snapshots__/custom_element_modal.examples.storyshot b/x-pack/legacy/plugins/canvas/public/components/custom_element_modal/__examples__/__snapshots__/custom_element_modal.examples.storyshot index 61ffc33cd9dde..eb82d1b63fdc2 100644 --- a/x-pack/legacy/plugins/canvas/public/components/custom_element_modal/__examples__/__snapshots__/custom_element_modal.examples.storyshot +++ b/x-pack/legacy/plugins/canvas/public/components/custom_element_modal/__examples__/__snapshots__/custom_element_modal.examples.storyshot @@ -193,6 +193,7 @@ Array [ >
@@ -1384,26 +1345,21 @@ Array [
-
-
- - - +

+ Name +

@@ -1462,27 +1418,22 @@ Array [
-
-
+
-
- - - +

+ Connection mode +

@@ -1665,27 +1616,22 @@ Array [
-
-
+
-
- - - +

+ Make remote cluster optional +

@@ -1762,7 +1708,7 @@ Array [
-
+
,
{ private renderDeleteButton = () => { const { selectedJobs } = this.state; - if (selectedJobs.length === 0) return null; + if (selectedJobs.length === 0) return undefined; const performDelete = async () => { for (const record of selectedJobs) { diff --git a/x-pack/plugins/transform/public/app/sections/transform_management/components/transform_list/common.ts b/x-pack/plugins/transform/public/app/sections/transform_management/components/transform_list/common.ts index a6d69dd655c0c..f42c9afb7ed00 100644 --- a/x-pack/plugins/transform/public/app/sections/transform_management/components/transform_list/common.ts +++ b/x-pack/plugins/transform/public/app/sections/transform_management/components/transform_list/common.ts @@ -4,18 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -export interface Clause { - type: string; - value: string; - match: string; -} +import { Query, Ast } from '@elastic/eui'; -export interface Query { - ast: { - clauses: Clause[]; - }; - text: string; - syntax: any; -} +export { Query }; +export type Clause = Parameters[0]; + +type ExtractClauseType = T extends (x: any) => x is infer Type ? Type : never; +export type TermClause = ExtractClauseType; +export type FieldClause = ExtractClauseType; +export type Value = Parameters[0]; export type ItemIdToExpandedRowMap = Record; diff --git a/x-pack/plugins/transform/public/app/sections/transform_management/components/transform_list/transform_list.tsx b/x-pack/plugins/transform/public/app/sections/transform_management/components/transform_list/transform_list.tsx index 3393aada8b69d..6736a79d62a3f 100644 --- a/x-pack/plugins/transform/public/app/sections/transform_management/components/transform_list/transform_list.tsx +++ b/x-pack/plugins/transform/public/app/sections/transform_management/components/transform_list/transform_list.tsx @@ -18,6 +18,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiInMemoryTable, + EuiSearchBarProps, EuiPopover, EuiTitle, } from '@elastic/eui'; @@ -39,7 +40,7 @@ import { DeleteAction } from './action_delete'; import { StartAction } from './action_start'; import { StopAction } from './action_stop'; -import { ItemIdToExpandedRowMap, Query, Clause } from './common'; +import { ItemIdToExpandedRowMap, Clause, TermClause, FieldClause, Value } from './common'; import { getColumns } from './columns'; import { ExpandedRow } from './expanded_row'; @@ -56,7 +57,7 @@ function getItemIdToExpandedRowMap( }, {} as ItemIdToExpandedRowMap); } -function stringMatch(str: string | undefined, substr: string) { +function stringMatch(str: string | undefined, substr: any) { return ( typeof str === 'string' && typeof substr === 'string' && @@ -104,7 +105,10 @@ export const TransformList: FC = ({ !capabilities.canPreviewTransform || !capabilities.canStartStopTransform; - const onQueryChange = ({ query, error }: { query: Query; error: any }) => { + const onQueryChange = ({ + query, + error, + }: Parameters>[0]) => { if (error) { setSearchError(error.message); } else { @@ -114,7 +118,7 @@ export const TransformList: FC = ({ } if (clauses.length > 0) { setFilterActive(true); - filterTransforms(clauses); + filterTransforms(clauses as Array); } else { setFilterActive(false); } @@ -122,7 +126,7 @@ export const TransformList: FC = ({ } }; - const filterTransforms = (clauses: Clause[]) => { + const filterTransforms = (clauses: Array) => { setIsLoading(true); // keep count of the number of matches we make as we're looping over the clauses // we only want to return transforms which match all clauses, i.e. each search term is ANDed @@ -161,7 +165,7 @@ export const TransformList: FC = ({ // filter other clauses, i.e. the mode and status filters if (Array.isArray(c.value)) { // the status value is an array of string(s) e.g. ['failed', 'stopped'] - ts = transforms.filter(transform => c.value.includes(transform.stats.state)); + ts = transforms.filter(transform => (c.value as Value[]).includes(transform.stats.state)); } else { ts = transforms.filter(transform => transform.mode === c.value); } diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 95fa13c028c30..bec3ffd147964 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -77,7 +77,6 @@ }, "messages": { "common.ui.aggResponse.allDocsTitle": "すべてのドキュメント", - "common.ui.directives.paginate.size.allDropDownOptionLabel": "すべて", "common.ui.errorAutoCreateIndex.breadcrumbs.errorText": "エラー", "common.ui.errorAutoCreateIndex.errorDescription": "Elasticsearch クラスターの {autoCreateIndexActionConfig} 設定が原因で、Kibana が保存されたオブジェクトを格納するインデックスを自動的に作成できないようです。Kibana は、保存されたオブジェクトインデックスが適切なマッピング/スキーマを使用し Kibana から Elasticsearch へのポーリングの回数を減らすための最適な手段であるため、この Elasticsearch の機能を使用します。", "common.ui.errorAutoCreateIndex.errorDisclaimer": "申し訳ございませんが、この問題が解決されるまで Kibana で何も保存することができません。", @@ -245,8 +244,6 @@ "common.ui.flotCharts.thuLabel": "木", "common.ui.flotCharts.tueLabel": "火", "common.ui.flotCharts.wedLabel": "水", - "common.ui.paginateControls.pageSizeLabel": "ページサイズ", - "common.ui.paginateControls.scrollTopButtonLabel": "最上部に移動", "common.ui.scriptingLanguages.errorFetchingToastDescription": "Elasticsearch から利用可能なスクリプト言語の取得中にエラーが発生しました", "common.ui.stateManagement.unableToParseUrlErrorMessage": "URL をパースできません", "common.ui.stateManagement.unableToRestoreUrlErrorMessage": "URL を完全に復元できません。共有機能を使用していることを確認してください。", @@ -1543,6 +1540,9 @@ "kibana_legacy.notify.toaster.errorMessage": "错误:{errorMessage}\n {errorStack}", "kibana_legacy.notify.toaster.errorStatusMessage": "错误 {errStatus} {errStatusText}:{errMessage}", "kibana_legacy.notify.toaster.unavailableServerErrorMessage": "HTTP 请求无法连接。请检查 Kibana 服务器是否正在运行以及您的浏览器是否具有有效的连接,或请联系您的系统管理员。", + "kibana_legacy.paginate.controls.pageSizeLabel": "ページサイズ", + "kibana_legacy.paginate.controls.scrollTopButtonLabel": "最上部に移動", + "kibana_legacy.paginate.size.allDropDownOptionLabel": "すべて", "home.addData.apm.addApmButtonLabel": "APM を追加", "home.addData.apm.nameDescription": "APM は、集約内から自動的に詳細なパフォーマンスメトリックやエラーを集めます。", "home.addData.apm.nameTitle": "APM", @@ -5140,34 +5140,13 @@ "xpack.canvas.uis.views.timefilter.args.filterGroupLabel": "選択されたグループ名をエレメントのフィルター関数に適用してこのフィルターをターゲットにする", "xpack.canvas.uis.views.timefilter.args.filterGroupTitle": "フィルターグループ名", "xpack.canvas.uis.views.timefilterTitle": "時間フィルター", - "xpack.canvas.units.quickRange.dayBeforeYesterday": "一昨日", - "xpack.canvas.units.quickRange.last12Hours": "過去 12 時間", - "xpack.canvas.units.quickRange.last15Minutes": "過去 15 分間", - "xpack.canvas.units.quickRange.last1Hour": "過去 1 時間", "xpack.canvas.units.quickRange.last1Year": "過去 1 年間", "xpack.canvas.units.quickRange.last24Hours": "過去 24 時間", "xpack.canvas.units.quickRange.last2Weeks": "過去 2 週間", - "xpack.canvas.units.quickRange.last2Years": "過去 2 年間", "xpack.canvas.units.quickRange.last30Days": "過去 30 日間", - "xpack.canvas.units.quickRange.last30Minutes": "過去 30 分間", - "xpack.canvas.units.quickRange.last4Hours": "過去 4 時間", - "xpack.canvas.units.quickRange.last5Years": "過去 5 年間", - "xpack.canvas.units.quickRange.last60Days": "過去 60 日間", - "xpack.canvas.units.quickRange.last6Months": "過去 6 か月間", "xpack.canvas.units.quickRange.last7Days": "過去 7 日間", "xpack.canvas.units.quickRange.last90Days": "過去 90 日間", - "xpack.canvas.units.quickRange.monthToDate": "月初めから今日まで", - "xpack.canvas.units.quickRange.previousMonth": "先月", - "xpack.canvas.units.quickRange.previousWeek": "先週", - "xpack.canvas.units.quickRange.previousYear": "昨年", - "xpack.canvas.units.quickRange.theDaySoFar": "本日現在まで", - "xpack.canvas.units.quickRange.thisDayLastWeek": "先週のこの曜日", - "xpack.canvas.units.quickRange.thisMonth": "今月", - "xpack.canvas.units.quickRange.thisWeek": "今週", - "xpack.canvas.units.quickRange.thisYear": "今年", "xpack.canvas.units.quickRange.today": "今日", - "xpack.canvas.units.quickRange.weekToDate": "週初めから今日まで", - "xpack.canvas.units.quickRange.yearToDate": "年度の頭から今日まで", "xpack.canvas.units.quickRange.yesterday": "昨日", "xpack.canvas.units.time.days": "{days, plural, one {# 日} other {# 日}}", "xpack.canvas.units.time.hours": "{hours, plural, one {# 時間} other {# 時間}}", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 9f9b5cc442b9a..f472247232cb8 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -77,7 +77,6 @@ }, "messages": { "common.ui.aggResponse.allDocsTitle": "所有文档", - "common.ui.directives.paginate.size.allDropDownOptionLabel": "全部", "common.ui.errorAutoCreateIndex.breadcrumbs.errorText": "错误", "common.ui.errorAutoCreateIndex.errorDescription": "似乎 Elasticsearch 集群的 {autoCreateIndexActionConfig} 设置使 Kibana 无法自动创建用于存储已保存对象的索引。Kibana 将使用此 Elasticsearch 功能,因为这是确保已保存对象索引使用正确映射/架构的最好方式,而且其允许 Kibana 较少地轮询 Elasticsearch。", "common.ui.errorAutoCreateIndex.errorDisclaimer": "但是,只有解决了此问题后,您才能在 Kibana 保存内容。", @@ -245,8 +244,6 @@ "common.ui.flotCharts.thuLabel": "周四", "common.ui.flotCharts.tueLabel": "周二", "common.ui.flotCharts.wedLabel": "周三", - "common.ui.paginateControls.pageSizeLabel": "页面大小", - "common.ui.paginateControls.scrollTopButtonLabel": "滚动至顶部", "common.ui.scriptingLanguages.errorFetchingToastDescription": "从 Elasticsearch 获取可用的脚本语言时出错", "common.ui.stateManagement.unableToParseUrlErrorMessage": "无法解析 URL", "common.ui.stateManagement.unableToRestoreUrlErrorMessage": "无法完整还原 URL,确保使用共享功能。", @@ -1544,6 +1541,9 @@ "kibana_legacy.notify.toaster.errorMessage": "错误:{errorMessage}\n {errorStack}", "kibana_legacy.notify.toaster.errorStatusMessage": "错误 {errStatus} {errStatusText}:{errMessage}", "kibana_legacy.notify.toaster.unavailableServerErrorMessage": "HTTP 请求无法连接。请检查 Kibana 服务器是否正在运行以及您的浏览器是否具有有效的连接,或请联系您的系统管理员。", + "kibana_legacy.paginate.controls.pageSizeLabel": "页面大小", + "kibana_legacy.paginate.controls.scrollTopButtonLabel": "滚动至顶部", + "kibana_legacy.paginate.size.allDropDownOptionLabel": "全部", "home.addData.apm.addApmButtonLabel": "添加 APM", "home.addData.apm.nameDescription": "APM 自动从您的应用程序内收集深入全面的性能指标和错误。", "home.addData.apm.nameTitle": "APM", @@ -5140,34 +5140,13 @@ "xpack.canvas.uis.views.timefilter.args.filterGroupLabel": "将选定组名称应用到元素的筛选函数,以定位该筛选", "xpack.canvas.uis.views.timefilter.args.filterGroupTitle": "筛选组名称", "xpack.canvas.uis.views.timefilterTitle": "时间筛选", - "xpack.canvas.units.quickRange.dayBeforeYesterday": "前天", - "xpack.canvas.units.quickRange.last12Hours": "过去 12 小时", - "xpack.canvas.units.quickRange.last15Minutes": "过去 15 分钟", - "xpack.canvas.units.quickRange.last1Hour": "过去 1 小时", "xpack.canvas.units.quickRange.last1Year": "过去 1 年", "xpack.canvas.units.quickRange.last24Hours": "过去 24 小时", "xpack.canvas.units.quickRange.last2Weeks": "过去 2 周", - "xpack.canvas.units.quickRange.last2Years": "过去 2 年", "xpack.canvas.units.quickRange.last30Days": "过去 30 天", - "xpack.canvas.units.quickRange.last30Minutes": "过去 30 分钟", - "xpack.canvas.units.quickRange.last4Hours": "过去 4 小时", - "xpack.canvas.units.quickRange.last5Years": "过去 5 年", - "xpack.canvas.units.quickRange.last60Days": "过去 60 天", - "xpack.canvas.units.quickRange.last6Months": "过去 6 个月", "xpack.canvas.units.quickRange.last7Days": "过去 7 天", "xpack.canvas.units.quickRange.last90Days": "过去 90 天", - "xpack.canvas.units.quickRange.monthToDate": "本月迄今为止", - "xpack.canvas.units.quickRange.previousMonth": "上一月", - "xpack.canvas.units.quickRange.previousWeek": "上一周", - "xpack.canvas.units.quickRange.previousYear": "上一年", - "xpack.canvas.units.quickRange.theDaySoFar": "今天迄今为止", - "xpack.canvas.units.quickRange.thisDayLastWeek": "上周本日", - "xpack.canvas.units.quickRange.thisMonth": "本月", - "xpack.canvas.units.quickRange.thisWeek": "本周", - "xpack.canvas.units.quickRange.thisYear": "本年", "xpack.canvas.units.quickRange.today": "今日", - "xpack.canvas.units.quickRange.weekToDate": "本周迄今为止", - "xpack.canvas.units.quickRange.yearToDate": "本年迄今为止", "xpack.canvas.units.quickRange.yesterday": "昨天", "xpack.canvas.units.time.days": "{days, plural, one {# 天} other {# 天}}", "xpack.canvas.units.time.hours": "{hours, plural, one {# 小时} other {# 小时}}", diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_alert_types/threshold/expression.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_alert_types/threshold/expression.tsx index 728418bf3c336..fa26e8b11bfec 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_alert_types/threshold/expression.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_alert_types/threshold/expression.tsx @@ -399,8 +399,8 @@ export const IndexThresholdAlertTypeExpression: React.FunctionComponent setAlertParams('timeWindowSize', selectedWindowSize) diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_alert_types/threshold/visualization.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_alert_types/threshold/visualization.tsx index 0bcaa83127468..ef08ac9a9d0de 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_alert_types/threshold/visualization.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_alert_types/threshold/visualization.tsx @@ -7,11 +7,10 @@ import React, { Fragment, useEffect, useState } from 'react'; import { IUiSettingsClient, HttpSetup } from 'kibana/public'; import { i18n } from '@kbn/i18n'; +import { interval } from 'rxjs'; import { AnnotationDomainTypes, Axis, - getAxisId, - getSpecId, Chart, LineAnnotation, LineSeries, @@ -21,7 +20,14 @@ import { niceTimeFormatter, } from '@elastic/charts'; import moment from 'moment-timezone'; -import { EuiCallOut, EuiLoadingChart, EuiSpacer, EuiEmptyPrompt, EuiText } from '@elastic/eui'; +import { + EuiCallOut, + EuiLoadingChart, + EuiSpacer, + EuiEmptyPrompt, + EuiText, + EuiLoadingSpinner, +} from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { getThresholdAlertVisualizationData } from '../../../../common/lib/index_threshold_api'; import { AggregationType, Comparator } from '../../../../common/types'; @@ -59,7 +65,7 @@ const getTimezone = (uiSettings: IUiSettingsClient) => { return tzOffset; }; -const getDomain = (alertInterval: string) => { +const getDomain = (alertInterval: string, startAt: Date) => { const VISUALIZE_INTERVALS = 30; let intervalMillis: number; @@ -69,10 +75,9 @@ const getDomain = (alertInterval: string) => { intervalMillis = 1000 * 60; // default to one minute if not parseable } - const now = Date.now(); return { - min: now - intervalMillis * VISUALIZE_INTERVALS, - max: now, + min: startAt.getTime() - intervalMillis * VISUALIZE_INTERVALS, + max: startAt.getTime(), }; }; @@ -84,6 +89,15 @@ interface Props { [key: string]: Comparator; }; alertsContext: AlertsContextValue; + refreshRateInMilliseconds?: number; +} + +const DEFAULT_REFRESH_RATE = 5000; + +enum LoadingStateType { + FirstLoad, + Refresh, + Idle, } type MetricResult = [number, number]; // [epochMillis, value] @@ -93,6 +107,7 @@ export const ThresholdVisualization: React.FunctionComponent = ({ aggregationTypes, comparators, alertsContext, + refreshRateInMilliseconds = DEFAULT_REFRESH_RATE, }) => { const { index, @@ -109,14 +124,25 @@ export const ThresholdVisualization: React.FunctionComponent = ({ } = alertParams; const { http, toastNotifications, charts, uiSettings, dataFieldsFormats } = alertsContext; - const [isLoading, setIsLoading] = useState(false); + const [loadingState, setLoadingState] = useState(null); const [error, setError] = useState(undefined); const [visualizationData, setVisualizationData] = useState>(); + const [startVisualizationAt, setStartVisualizationAt] = useState(new Date()); + + useEffect(() => { + const source = interval(refreshRateInMilliseconds); + const subscription = source.subscribe((val: number) => { + setStartVisualizationAt(new Date()); + }); + return () => { + subscription.unsubscribe(); + }; + }, [refreshRateInMilliseconds]); useEffect(() => { (async () => { try { - setIsLoading(true); + setLoadingState(loadingState ? LoadingStateType.Refresh : LoadingStateType.FirstLoad); setVisualizationData( await getVisualizationData(alertWithoutActions, visualizeOptions, http) ); @@ -131,7 +157,7 @@ export const ThresholdVisualization: React.FunctionComponent = ({ } setError(e); } finally { - setIsLoading(false); + setLoadingState(LoadingStateType.Idle); } })(); /* eslint-disable react-hooks/exhaustive-deps */ @@ -147,6 +173,7 @@ export const ThresholdVisualization: React.FunctionComponent = ({ timeWindowUnit, groupBy, threshold, + startVisualizationAt, ]); /* eslint-enable react-hooks/exhaustive-deps */ @@ -155,7 +182,7 @@ export const ThresholdVisualization: React.FunctionComponent = ({ } const chartsTheme = charts.theme.useChartsTheme(); - const domain = getDomain(alertInterval); + const domain = getDomain(alertInterval, startVisualizationAt); const visualizeOptions = { rangeFrom: new Date(domain.min).toISOString(), rangeTo: new Date(domain.max).toISOString(), @@ -165,7 +192,7 @@ export const ThresholdVisualization: React.FunctionComponent = ({ // Fetching visualization data is independent of alert actions const alertWithoutActions = { ...alertParams, actions: [], type: 'threshold' }; - if (isLoading) { + if (loadingState === LoadingStateType.FirstLoad) { return ( } @@ -224,32 +251,33 @@ export const ThresholdVisualization: React.FunctionComponent = ({ const dateFormatter = niceTimeFormatter([domain.min, domain.max]); const aggLabel = aggregationTypes[aggType].text; return ( -
+
+ {loadingState === LoadingStateType.Refresh ? ( + + ) : ( + + )} {alertVisualizationDataKeys.length ? ( - + {alertVisualizationDataKeys.map((key: string) => { return ( { id: 'test', name: 'Test', enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', }, ]; http.get.mockResolvedValueOnce(resolvedValue); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/action_type_compare.test.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/action_type_compare.test.ts new file mode 100644 index 0000000000000..9ce50cf47560a --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/action_type_compare.test.ts @@ -0,0 +1,74 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ActionType } from '../../types'; +import { actionTypeCompare } from './action_type_compare'; + +test('should sort enabled action types first', async () => { + const actionTypes: ActionType[] = [ + { + id: '1', + minimumLicenseRequired: 'basic', + name: 'first', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + }, + { + id: '2', + minimumLicenseRequired: 'gold', + name: 'second', + enabled: false, + enabledInConfig: true, + enabledInLicense: false, + }, + { + id: '3', + minimumLicenseRequired: 'basic', + name: 'third', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + }, + ]; + const result = [...actionTypes].sort(actionTypeCompare); + expect(result[0]).toEqual(actionTypes[0]); + expect(result[1]).toEqual(actionTypes[2]); + expect(result[2]).toEqual(actionTypes[1]); +}); + +test('should sort by name when all enabled', async () => { + const actionTypes: ActionType[] = [ + { + id: '1', + minimumLicenseRequired: 'basic', + name: 'third', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + }, + { + id: '2', + minimumLicenseRequired: 'basic', + name: 'first', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + }, + { + id: '3', + minimumLicenseRequired: 'basic', + name: 'second', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + }, + ]; + const result = [...actionTypes].sort(actionTypeCompare); + expect(result[0]).toEqual(actionTypes[1]); + expect(result[1]).toEqual(actionTypes[2]); + expect(result[2]).toEqual(actionTypes[0]); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/action_type_compare.ts b/x-pack/plugins/triggers_actions_ui/public/application/lib/action_type_compare.ts new file mode 100644 index 0000000000000..d18cb21b3a0fe --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/action_type_compare.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ActionType } from '../../types'; + +export function actionTypeCompare(a: ActionType, b: ActionType) { + if (a.enabled === true && b.enabled === false) { + return -1; + } + if (a.enabled === false && b.enabled === true) { + return 1; + } + return a.name.localeCompare(b.name); +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.scss b/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.scss new file mode 100644 index 0000000000000..32ab1bd7b1821 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.scss @@ -0,0 +1,9 @@ +.actCheckActionTypeEnabled__disabledActionWarningCard { + background-color: $euiColorLightestShade; +} + +.actAccordionActionForm { + .euiCard { + box-shadow: none; + } +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.test.tsx new file mode 100644 index 0000000000000..eb51bb8ac5098 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.test.tsx @@ -0,0 +1,88 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ActionType } from '../../types'; +import { checkActionTypeEnabled } from './check_action_type_enabled'; + +test(`returns isEnabled:true when action type isn't provided`, async () => { + expect(checkActionTypeEnabled()).toMatchInlineSnapshot(` + Object { + "isEnabled": true, + } + `); +}); + +test('returns isEnabled:true when action type is enabled', async () => { + const actionType: ActionType = { + id: '1', + minimumLicenseRequired: 'basic', + name: 'my action', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + }; + expect(checkActionTypeEnabled(actionType)).toMatchInlineSnapshot(` + Object { + "isEnabled": true, + } + `); +}); + +test('returns isEnabled:false when action type is disabled by license', async () => { + const actionType: ActionType = { + id: '1', + minimumLicenseRequired: 'basic', + name: 'my action', + enabled: false, + enabledInConfig: true, + enabledInLicense: false, + }; + expect(checkActionTypeEnabled(actionType)).toMatchInlineSnapshot(` + Object { + "isEnabled": false, + "message": "This connector is disabled because it requires a basic license.", + "messageCard": + + + + , + } + `); +}); + +test('returns isEnabled:false when action type is disabled by config', async () => { + const actionType: ActionType = { + id: '1', + minimumLicenseRequired: 'basic', + name: 'my action', + enabled: false, + enabledInConfig: false, + enabledInLicense: true, + }; + expect(checkActionTypeEnabled(actionType)).toMatchInlineSnapshot(` + Object { + "isEnabled": false, + "message": "This connector is disabled by the Kibana configuration.", + "messageCard": , + } + `); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.tsx b/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.tsx new file mode 100644 index 0000000000000..7691c3741468c --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/lib/check_action_type_enabled.tsx @@ -0,0 +1,93 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiCard, EuiLink } from '@elastic/eui'; +import { ActionType } from '../../types'; +import { VIEW_LICENSE_OPTIONS_LINK } from '../../common/constants'; +import './check_action_type_enabled.scss'; + +export interface IsEnabledResult { + isEnabled: true; +} +export interface IsDisabledResult { + isEnabled: false; + message: string; + messageCard: JSX.Element; +} + +export function checkActionTypeEnabled( + actionType?: ActionType +): IsEnabledResult | IsDisabledResult { + if (actionType?.enabledInLicense === false) { + return { + isEnabled: false, + message: i18n.translate( + 'xpack.triggersActionsUI.checkActionTypeEnabled.actionTypeDisabledByLicenseMessage', + { + defaultMessage: + 'This connector is disabled because it requires a {minimumLicenseRequired} license.', + values: { + minimumLicenseRequired: actionType.minimumLicenseRequired, + }, + } + ), + messageCard: ( + + + + } + /> + ), + }; + } + + if (actionType?.enabledInConfig === false) { + return { + isEnabled: false, + message: i18n.translate( + 'xpack.triggersActionsUI.checkActionTypeEnabled.actionTypeDisabledByConfigMessage', + { defaultMessage: 'This connector is disabled by the Kibana configuration.' } + ), + messageCard: ( + + ), + }; + } + + return { isEnabled: true }; +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.test.tsx index caed0caefe109..89d37c4d00a11 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.test.tsx @@ -39,6 +39,36 @@ describe('action_form', () => { actionParamsFields: null, }; + const disabledByConfigActionType = { + id: 'disabled-by-config', + iconClass: 'test', + selectMessage: 'test', + validateConnector: (): ValidationResult => { + return { errors: {} }; + }, + validateParams: (): ValidationResult => { + const validationResult = { errors: {} }; + return validationResult; + }, + actionConnectorFields: null, + actionParamsFields: null, + }; + + const disabledByLicenseActionType = { + id: 'disabled-by-license', + iconClass: 'test', + selectMessage: 'test', + validateConnector: (): ValidationResult => { + return { errors: {} }; + }, + validateParams: (): ValidationResult => { + const validationResult = { errors: {} }; + return validationResult; + }, + actionConnectorFields: null, + actionParamsFields: null, + }; + describe('action_form in alert', () => { let wrapper: ReactWrapper; @@ -49,7 +79,11 @@ describe('action_form', () => { http: mockes.http, actionTypeRegistry: actionTypeRegistry as any, }; - actionTypeRegistry.list.mockReturnValue([actionType]); + actionTypeRegistry.list.mockReturnValue([ + actionType, + disabledByConfigActionType, + disabledByLicenseActionType, + ]); actionTypeRegistry.has.mockReturnValue(true); const initialAlert = ({ @@ -92,8 +126,38 @@ describe('action_form', () => { actionTypeRegistry={deps!.actionTypeRegistry} defaultActionMessage={'Alert [{{ctx.metadata.name}}] has exceeded the threshold'} actionTypes={[ - { id: actionType.id, name: 'Test', enabled: true }, - { id: '.index', name: 'Index', enabled: true }, + { + id: actionType.id, + name: 'Test', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', + }, + { + id: '.index', + name: 'Index', + enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', + }, + { + id: 'disabled-by-config', + name: 'Disabled by config', + enabled: false, + enabledInConfig: false, + enabledInLicense: true, + minimumLicenseRequired: 'gold', + }, + { + id: 'disabled-by-license', + name: 'Disabled by license', + enabled: false, + enabledInConfig: true, + enabledInLicense: false, + minimumLicenseRequired: 'gold', + }, ]} toastNotifications={deps!.toastNotifications} /> @@ -112,6 +176,32 @@ describe('action_form', () => { `[data-test-subj="${actionType.id}-ActionTypeSelectOption"]` ); expect(actionOption.exists()).toBeTruthy(); + expect( + wrapper + .find(`EuiToolTip [data-test-subj="${actionType.id}-ActionTypeSelectOption"]`) + .exists() + ).toBeFalsy(); + }); + + it(`doesn't render action types disabled by config`, async () => { + await setup(); + const actionOption = wrapper.find( + `[data-test-subj="disabled-by-config-ActionTypeSelectOption"]` + ); + expect(actionOption.exists()).toBeFalsy(); + }); + + it('renders action types disabled by license', async () => { + await setup(); + const actionOption = wrapper.find( + `[data-test-subj="disabled-by-license-ActionTypeSelectOption"]` + ); + expect(actionOption.exists()).toBeTruthy(); + expect( + wrapper + .find('EuiToolTip [data-test-subj="disabled-by-license-ActionTypeSelectOption"]') + .exists() + ).toBeTruthy(); }); }); }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx index 64be161fc90b3..4dcbfeaaf1d3a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx @@ -21,6 +21,9 @@ import { EuiButtonIcon, EuiEmptyPrompt, EuiButtonEmpty, + EuiToolTip, + EuiIconTip, + EuiLink, } from '@elastic/eui'; import { HttpSetup, ToastsApi } from 'kibana/public'; import { loadActionTypes, loadAllActions } from '../../lib/action_connector_api'; @@ -35,6 +38,9 @@ import { import { SectionLoading } from '../../components/section_loading'; import { ConnectorAddModal } from './connector_add_modal'; import { TypeRegistry } from '../../type_registry'; +import { actionTypeCompare } from '../../lib/action_type_compare'; +import { checkActionTypeEnabled } from '../../lib/check_action_type_enabled'; +import { VIEW_LICENSE_OPTIONS_LINK } from '../../../common/constants'; interface ActionAccordionFormProps { actions: AlertAction[]; @@ -51,6 +57,7 @@ interface ActionAccordionFormProps { actionTypes?: ActionType[]; messageVariables?: string[]; defaultActionMessage?: string; + setHasActionsDisabled?: (value: boolean) => void; } interface ActiveActionConnectorState { @@ -70,6 +77,7 @@ export const ActionForm = ({ messageVariables, defaultActionMessage, toastNotifications, + setHasActionsDisabled, }: ActionAccordionFormProps) => { const [addModalVisible, setAddModalVisibility] = useState(false); const [activeActionItem, setActiveActionItem] = useState( @@ -91,6 +99,10 @@ export const ActionForm = ({ index[actionTypeItem.id] = actionTypeItem; } setActionTypesIndex(index); + const hasActionsDisabled = actions.some(action => !index[action.actionTypeId].enabled); + if (setHasActionsDisabled) { + setHasActionsDisabled(hasActionsDisabled); + } } catch (e) { if (toastNotifications) { toastNotifications.addDanger({ @@ -127,19 +139,6 @@ export const ActionForm = ({ }); } } - - const actionsErrors = actions.reduce( - (acc: Record, alertAction: AlertAction) => { - const actionType = actionTypeRegistry.get(alertAction.actionTypeId); - if (!actionType) { - return { ...acc }; - } - const actionValidationErrors = actionType.validateParams(alertAction.params); - return { ...acc, [alertAction.id]: actionValidationErrors }; - }, - {} - ) as Record; - const getSelectedOptions = (actionItemId: string) => { const val = connectors.find(connector => connector.id === actionItemId); if (!val) { @@ -157,17 +156,16 @@ export const ActionForm = ({ const getActionTypeForm = ( actionItem: AlertAction, actionConnector: ActionConnector, + actionParamsErrors: { + errors: IErrorObject; + }, index: number ) => { const optionsList = connectors .filter( connectorItem => connectorItem.actionTypeId === actionItem.actionTypeId && - (connectorItem.id === actionItem.id || - !actions.find( - (existingAction: AlertAction) => - existingAction.id === connectorItem.id && existingAction.group === actionItem.group - )) + connectorItem.id === actionItem.id ) .map(({ name, id }) => ({ label: name, @@ -177,62 +175,12 @@ export const ActionForm = ({ const actionTypeRegistered = actionTypeRegistry.get(actionConnector.actionTypeId); if (!actionTypeRegistered || actionItem.group !== defaultActionGroupId) return null; const ParamsFieldsComponent = actionTypeRegistered.actionParamsFields; - const actionParamsErrors: { errors: IErrorObject } = - Object.keys(actionsErrors).length > 0 ? actionsErrors[actionItem.id] : { errors: {} }; + const checkEnabledResult = checkActionTypeEnabled( + actionTypesIndex && actionTypesIndex[actionConnector.actionTypeId] + ); - return ( - - - - - - -
- -
-
-
- - } - extraAction={ - { - const updatedActions = actions.filter( - (item: AlertAction) => item.id !== actionItem.id - ); - setAlertProperty(updatedActions); - setIsAddActionPanelOpen( - updatedActions.filter((item: AlertAction) => item.id !== actionItem.id).length === 0 - ); - setActiveActionItem(undefined); - }} - /> - } - paddingSize="l" - > + const accordionContent = checkEnabledResult.isEnabled ? ( + ) : null} + + ) : ( + checkEnabledResult.messageCard + ); + + return ( + + + + + + +
+ + + + + + {checkEnabledResult.isEnabled === false && ( + + + + )} + + +
+
+
+ + } + extraAction={ + { + const updatedActions = actions.filter((_item: AlertAction, i: number) => i !== index); + setAlertProperty(updatedActions); + setIsAddActionPanelOpen( + updatedActions.filter((item: AlertAction) => item.id !== actionItem.id).length === 0 + ); + setActiveActionItem(undefined); + }} + /> + } + paddingSize="l" + > + {accordionContent}
); }; @@ -302,8 +328,8 @@ export const ActionForm = ({ initialIsOpen={true} key={index} id={index.toString()} - className="euiAccordionForm" - buttonContentClassName="euiAccordionForm__button" + className="actAccordionActionForm" + buttonContentClassName="actAccordionActionForm__button" data-test-subj={`alertActionAccordion-${defaultActionGroupId}`} buttonContent={ @@ -329,7 +355,7 @@ export const ActionForm = ({ { - const updatedActions = actions.filter( - (item: AlertAction) => item.id !== actionItem.id - ); + const updatedActions = actions.filter((_item: AlertAction, i: number) => i !== index); setAlertProperty(updatedActions); setIsAddActionPanelOpen( updatedActions.filter((item: AlertAction) => item.id !== actionItem.id).length === 0 @@ -397,24 +421,16 @@ export const ActionForm = ({ const actionTypeConnectors = connectors.filter( field => field.actionTypeId === actionTypeModel.id ); - let freeConnectors; if (actionTypeConnectors.length > 0) { - // Should we allow adding multiple actions to the same connector under the alert? - freeConnectors = actionTypeConnectors.filter( - (actionConnector: ActionConnector) => - !actions.find((actionItem: AlertAction) => actionItem.id === actionConnector.id) - ); - if (freeConnectors.length > 0) { - actions.push({ - id: '', - actionTypeId: actionTypeModel.id, - group: defaultActionGroupId, - params: {}, - }); - setActionIdByIndex(freeConnectors[0].id, actions.length - 1); - } + actions.push({ + id: '', + actionTypeId: actionTypeModel.id, + group: defaultActionGroupId, + params: {}, + }); + setActionIdByIndex(actionTypeConnectors[0].id, actions.length - 1); } - if (actionTypeConnectors.length === 0 || !freeConnectors || freeConnectors.length === 0) { + if (actionTypeConnectors.length === 0) { // if no connectors exists or all connectors is already assigned an action under current alert // set actionType as id to be able to create new connector within the alert form actions.push({ @@ -427,20 +443,46 @@ export const ActionForm = ({ } } - const actionTypeNodes = actionTypesIndex - ? actionTypeRegistry.list().map(function(item, index) { - return actionTypesIndex[item.id] ? ( + let actionTypeNodes: JSX.Element[] | null = null; + let hasDisabledByLicenseActionTypes = false; + if (actionTypesIndex) { + actionTypeNodes = actionTypeRegistry + .list() + .filter( + item => actionTypesIndex[item.id] && actionTypesIndex[item.id].enabledInConfig === true + ) + .sort((a, b) => actionTypeCompare(actionTypesIndex[a.id], actionTypesIndex[b.id])) + .map(function(item, index) { + const actionType = actionTypesIndex[item.id]; + const checkEnabledResult = checkActionTypeEnabled(actionTypesIndex[item.id]); + if (!actionType.enabledInLicense) { + hasDisabledByLicenseActionTypes = true; + } + + const keyPadItem = ( addActionType(item)} > - ) : null; - }) - : null; + ); + + return ( + + {checkEnabledResult.isEnabled && keyPadItem} + {checkEnabledResult.isEnabled === false && ( + + {keyPadItem} + + )} + + ); + }); + } return ( @@ -450,7 +492,12 @@ export const ActionForm = ({ if (!actionConnector) { return getAddConnectorsForm(actionItem, index); } - return getActionTypeForm(actionItem, actionConnector, index); + + const actionErrors: { errors: IErrorObject } = actionTypeRegistry + .get(actionItem.actionTypeId) + ?.validateParams(actionItem.params); + + return getActionTypeForm(actionItem, actionConnector, actionErrors, index); })} {isAddActionPanelOpen === false ? ( @@ -467,14 +514,36 @@ export const ActionForm = ({ ) : null} {isAddActionPanelOpen ? ( - -
- -
-
+ + + +
+ +
+
+
+ {hasDisabledByLicenseActionTypes && ( + + +
+ + + +
+
+
+ )} +
{isLoadingActionTypes ? ( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.test.tsx index 4f098165033e7..84d5269337b9e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.test.tsx @@ -77,6 +77,9 @@ describe('connector_add_flyout', () => { id: actionType.id, enabled: true, name: 'Test', + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', }, ]} /> @@ -85,4 +88,107 @@ describe('connector_add_flyout', () => { expect(wrapper.find('[data-test-subj="my-action-type-card"]').exists()).toBeTruthy(); }); + + it(`doesn't renders action types that are disabled via config`, () => { + const onActionTypeChange = jest.fn(); + const actionType = { + id: 'my-action-type', + iconClass: 'test', + selectMessage: 'test', + validateConnector: (): ValidationResult => { + return { errors: {} }; + }, + validateParams: (): ValidationResult => { + const validationResult = { errors: {} }; + return validationResult; + }, + actionConnectorFields: null, + actionParamsFields: null, + }; + actionTypeRegistry.get.mockReturnValueOnce(actionType); + + const wrapper = mountWithIntl( + { + return new Promise(() => {}); + }, + }} + > + + + ); + + expect(wrapper.find('[data-test-subj="my-action-type-card"]').exists()).toBeFalsy(); + }); + + it(`renders action types as disabled when disabled by license`, () => { + const onActionTypeChange = jest.fn(); + const actionType = { + id: 'my-action-type', + iconClass: 'test', + selectMessage: 'test', + validateConnector: (): ValidationResult => { + return { errors: {} }; + }, + validateParams: (): ValidationResult => { + const validationResult = { errors: {} }; + return validationResult; + }, + actionConnectorFields: null, + actionParamsFields: null, + }; + actionTypeRegistry.get.mockReturnValueOnce(actionType); + + const wrapper = mountWithIntl( + { + return new Promise(() => {}); + }, + }} + > + + + ); + + const element = wrapper.find('[data-test-subj="my-action-type-card"]'); + expect(element.exists()).toBeTruthy(); + expect(element.first().prop('betaBadgeLabel')).toEqual('Upgrade'); + expect(element.first().prop('betaBadgeTooltipContent')).toEqual( + 'This connector is disabled because it requires a gold license.' + ); + }); }); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.tsx index a63665a68fb6b..2dd5e413faf9c 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_type_menu.tsx @@ -4,18 +4,25 @@ * you may not use this file except in compliance with the Elastic License. */ import React, { useEffect, useState } from 'react'; -import { EuiFlexItem, EuiCard, EuiIcon, EuiFlexGrid } from '@elastic/eui'; +import { EuiFlexItem, EuiCard, EuiIcon, EuiFlexGrid, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ActionType, ActionTypeIndex } from '../../../types'; import { loadActionTypes } from '../../lib/action_connector_api'; import { useActionsConnectorsContext } from '../../context/actions_connectors_context'; +import { actionTypeCompare } from '../../lib/action_type_compare'; +import { checkActionTypeEnabled } from '../../lib/check_action_type_enabled'; interface Props { onActionTypeChange: (actionType: ActionType) => void; actionTypes?: ActionType[]; + setHasActionsDisabledByLicense?: (value: boolean) => void; } -export const ActionTypeMenu = ({ onActionTypeChange, actionTypes }: Props) => { +export const ActionTypeMenu = ({ + onActionTypeChange, + actionTypes, + setHasActionsDisabledByLicense, +}: Props) => { const { http, toastNotifications, actionTypeRegistry } = useActionsConnectorsContext(); const [actionTypesIndex, setActionTypesIndex] = useState(undefined); @@ -28,6 +35,12 @@ export const ActionTypeMenu = ({ onActionTypeChange, actionTypes }: Props) => { index[actionTypeItem.id] = actionTypeItem; } setActionTypesIndex(index); + if (setHasActionsDisabledByLicense) { + const hasActionsDisabledByLicense = availableActionTypes.some( + action => !index[action.id].enabledInLicense + ); + setHasActionsDisabledByLicense(hasActionsDisabledByLicense); + } } catch (e) { if (toastNotifications) { toastNotifications.addDanger({ @@ -43,33 +56,54 @@ export const ActionTypeMenu = ({ onActionTypeChange, actionTypes }: Props) => { }, []); const registeredActionTypes = Object.entries(actionTypesIndex ?? []) - .filter(([index]) => actionTypeRegistry.has(index)) - .map(([index, actionType]) => { - const actionTypeModel = actionTypeRegistry.get(index); + .filter(([id, details]) => actionTypeRegistry.has(id) && details.enabledInConfig === true) + .map(([id, actionType]) => { + const actionTypeModel = actionTypeRegistry.get(id); return { iconClass: actionTypeModel ? actionTypeModel.iconClass : '', selectMessage: actionTypeModel ? actionTypeModel.selectMessage : '', actionType, name: actionType.name, - typeName: index.replace('.', ''), + typeName: id.replace('.', ''), }; }); const cardNodes = registeredActionTypes - .sort((a, b) => a.name.localeCompare(b.name)) + .sort((a, b) => actionTypeCompare(a.actionType, b.actionType)) .map((item, index) => { - return ( - - } - title={item.name} - description={item.selectMessage} - onClick={() => onActionTypeChange(item.actionType)} - /> - + const checkEnabledResult = checkActionTypeEnabled(item.actionType); + const card = ( + } + title={item.name} + description={item.selectMessage} + isDisabled={!checkEnabledResult.isEnabled} + onClick={() => onActionTypeChange(item.actionType)} + betaBadgeLabel={ + checkEnabledResult.isEnabled + ? undefined + : i18n.translate( + 'xpack.triggersActionsUI.sections.actionsConnectorsList.upgradeBadge', + { defaultMessage: 'Upgrade' } + ) + } + betaBadgeTooltipContent={ + checkEnabledResult.isEnabled ? undefined : checkEnabledResult.message + } + /> ); + + return {card}; }); - return {cardNodes}; + return ( +
+ + + {cardNodes} + +
+ ); }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.test.tsx index cf0edbe422495..c25cae832006a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.test.tsx @@ -79,6 +79,9 @@ describe('connector_add_flyout', () => { id: actionType.id, enabled: true, name: 'Test', + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', }, ]} /> diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.tsx index 9aea2419ec619..665eeca43acb4 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_flyout.tsx @@ -18,6 +18,9 @@ import { EuiButton, EuiFlyoutBody, EuiBetaBadge, + EuiCallOut, + EuiLink, + EuiSpacer, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ActionTypeMenu } from './action_type_menu'; @@ -27,6 +30,7 @@ import { connectorReducer } from './connector_reducer'; import { hasSaveActionsCapability } from '../../lib/capabilities'; import { createActionConnector } from '../../lib/action_connector_api'; import { useActionsConnectorsContext } from '../../context/actions_connectors_context'; +import { VIEW_LICENSE_OPTIONS_LINK } from '../../../common/constants'; export interface ConnectorAddFlyoutProps { addFlyoutVisible: boolean; @@ -48,6 +52,7 @@ export const ConnectorAddFlyout = ({ reloadConnectors, } = useActionsConnectorsContext(); const [actionType, setActionType] = useState(undefined); + const [hasActionsDisabledByLicense, setHasActionsDisabledByLicense] = useState(false); // hooks const initialConnector = { @@ -86,7 +91,11 @@ export const ConnectorAddFlyout = ({ let actionTypeModel; if (!actionType) { currentForm = ( - + ); } else { actionTypeModel = actionTypeRegistry.get(actionType.id); @@ -204,7 +213,11 @@ export const ConnectorAddFlyout = ({
- {currentForm} + + {currentForm} + @@ -252,3 +265,24 @@ export const ConnectorAddFlyout = ({ ); }; + +const upgradeYourLicenseCallOut = ( + + + + + + + +); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.scss b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.scss index f8fa882cd617d..7f56c220db4bb 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.scss +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.scss @@ -1,3 +1,7 @@ .actConnectorModal { z-index: 9000; } + +.euiComboBoxOptionsList { + z-index: 9001; +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.test.tsx index 31d801bb340f3..d2e3739c1cd22 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/connector_add_modal.test.tsx @@ -8,7 +8,7 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { coreMock } from '../../../../../../../src/core/public/mocks'; import { ConnectorAddModal } from './connector_add_modal'; import { actionTypeRegistryMock } from '../../action_type_registry.mock'; -import { ValidationResult } from '../../../types'; +import { ValidationResult, ActionType } from '../../../types'; import { ActionsConnectorsContextValue } from '../../context/actions_connectors_context'; const actionTypeRegistry = actionTypeRegistryMock.create(); @@ -54,10 +54,13 @@ describe('connector_add_modal', () => { actionTypeRegistry.get.mockReturnValueOnce(actionTypeModel); actionTypeRegistry.has.mockReturnValue(true); - const actionType = { + const actionType: ActionType = { id: 'my-action-type', name: 'test', enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', }; const wrapper = deps diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.scss b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.scss index 7a824aaeaa8d8..3d65b8a799b1b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.scss +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.scss @@ -1,3 +1,15 @@ .actConnectorsList__logo + .actConnectorsList__logo { margin-left: $euiSize; } + +.actConnectorsList__tableRowDisabled { + background-color: $euiColorLightestShade; + + .actConnectorsList__tableCellDisabled { + color: $euiColorDarkShade; + } + + .euiLink + .euiIcon { + margin-left: $euiSizeXS; + } +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx index 9187836d52462..9331fe1704694 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx @@ -136,10 +136,12 @@ describe('actions_connectors_list component with items', () => { { id: 'test', name: 'Test', + enabled: true, }, { id: 'test2', name: 'Test2', + enabled: true, }, ]); @@ -375,6 +377,117 @@ describe('actions_connectors_list with show only capability', () => { }); }); +describe('actions_connectors_list component with disabled items', () => { + let wrapper: ReactWrapper; + + beforeAll(async () => { + const { loadAllActions, loadActionTypes } = jest.requireMock( + '../../../lib/action_connector_api' + ); + loadAllActions.mockResolvedValueOnce({ + page: 1, + perPage: 10000, + total: 2, + data: [ + { + id: '1', + actionTypeId: 'test', + description: 'My test', + referencedByCount: 1, + config: {}, + }, + { + id: '2', + actionTypeId: 'test2', + description: 'My test 2', + referencedByCount: 1, + config: {}, + }, + ], + }); + loadActionTypes.mockResolvedValueOnce([ + { + id: 'test', + name: 'Test', + enabled: false, + enabledInConfig: false, + enabledInLicense: true, + }, + { + id: 'test2', + name: 'Test2', + enabled: false, + enabledInConfig: true, + enabledInLicense: false, + }, + ]); + + const mockes = coreMock.createSetup(); + const [ + { + chrome, + docLinks, + application: { capabilities, navigateToApp }, + }, + ] = await mockes.getStartServices(); + const deps = { + chrome, + docLinks, + dataPlugin: dataPluginMock.createStartContract(), + charts: chartPluginMock.createStartContract(), + toastNotifications: mockes.notifications.toasts, + injectedMetadata: mockes.injectedMetadata, + http: mockes.http, + uiSettings: mockes.uiSettings, + navigateToApp, + capabilities: { + ...capabilities, + siem: { + 'actions:show': true, + 'actions:save': true, + 'actions:delete': true, + }, + }, + setBreadcrumbs: jest.fn(), + actionTypeRegistry: { + get() { + return null; + }, + } as any, + alertTypeRegistry: {} as any, + }; + + await act(async () => { + wrapper = mountWithIntl( + + + + ); + }); + + await waitForRender(wrapper); + + expect(loadAllActions).toHaveBeenCalled(); + }); + + it('renders table of connectors', () => { + expect(wrapper.find('EuiInMemoryTable')).toHaveLength(1); + expect(wrapper.find('EuiTableRow')).toHaveLength(2); + expect( + wrapper + .find('EuiTableRow') + .at(0) + .prop('className') + ).toEqual('actConnectorsList__tableRowDisabled'); + expect( + wrapper + .find('EuiTableRow') + .at(1) + .prop('className') + ).toEqual('actConnectorsList__tableRowDisabled'); + }); +}); + async function waitForRender(wrapper: ReactWrapper) { await Promise.resolve(); await Promise.resolve(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.tsx index 9444b31a8b78f..c023f9087d70e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.tsx @@ -15,17 +15,19 @@ import { EuiTitle, EuiLink, EuiLoadingSpinner, + EuiIconTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { useAppDependencies } from '../../../app_context'; import { loadAllActions, loadActionTypes } from '../../../lib/action_connector_api'; -import { ActionConnector, ActionConnectorTableItem, ActionTypeIndex } from '../../../../types'; import { ConnectorAddFlyout, ConnectorEditFlyout } from '../../action_connector_form'; import { hasDeleteActionsCapability, hasSaveActionsCapability } from '../../../lib/capabilities'; import { DeleteConnectorsModal } from '../../../components/delete_connectors_modal'; import { ActionsConnectorsContextProvider } from '../../../context/actions_connectors_context'; +import { checkActionTypeEnabled } from '../../../lib/check_action_type_enabled'; import './actions_connectors_list.scss'; +import { ActionConnector, ActionConnectorTableItem, ActionTypeIndex } from '../../../../types'; export const ActionsConnectorsList: React.FunctionComponent = () => { const { http, toastNotifications, capabilities, actionTypeRegistry } = useAppDependencies(); @@ -139,11 +141,33 @@ export const ActionsConnectorsList: React.FunctionComponent = () => { sortable: false, truncateText: true, render: (value: string, item: ActionConnectorTableItem) => { - return ( - editItem(item)} key={item.id}> + const checkEnabledResult = checkActionTypeEnabled( + actionTypesIndex && actionTypesIndex[item.actionTypeId] + ); + + const link = ( + editItem(item)} + key={item.id} + disabled={actionTypesIndex ? !actionTypesIndex[item.actionTypeId].enabled : true} + > {value} ); + + return checkEnabledResult.isEnabled ? ( + link + ) : ( + + {link} + + + ); }, }, { @@ -211,11 +235,19 @@ export const ActionsConnectorsList: React.FunctionComponent = () => { sorting={true} itemId="id" columns={actionsTableColumns} - rowProps={() => ({ + rowProps={(item: ActionConnectorTableItem) => ({ + className: + !actionTypesIndex || !actionTypesIndex[item.actionTypeId].enabled + ? 'actConnectorsList__tableRowDisabled' + : '', 'data-test-subj': 'connectors-row', })} - cellProps={() => ({ + cellProps={(item: ActionConnectorTableItem) => ({ 'data-test-subj': 'cell', + className: + !actionTypesIndex || !actionTypesIndex[item.actionTypeId].enabled + ? 'actConnectorsList__tableCellDisabled' + : '', })} data-test-subj="actionsTable" pagination={true} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.test.tsx index 92b3e4eb9679f..f025b0396f04d 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/alert_details.test.tsx @@ -124,6 +124,9 @@ describe('alert_details', () => { id: '.server-log', name: 'Server log', enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', }, ]; @@ -173,11 +176,17 @@ describe('alert_details', () => { id: '.server-log', name: 'Server log', enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', }, { id: '.email', name: 'Send email', enabled: true, + enabledInConfig: true, + enabledInLicense: true, + minimumLicenseRequired: 'basic', }, ]; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/view_in_app.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/view_in_app.test.tsx index 18825d58aa055..e7f92a0976b06 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/view_in_app.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_details/components/view_in_app.test.tsx @@ -35,7 +35,7 @@ jest.mock('../../../lib/capabilities', () => ({ hasSaveAlertsCapability: jest.fn(() => true), })); -describe('alert_details', () => { +describe('view in app', () => { describe('link to the app that created the alert', () => { it('is disabled when there is no navigation', async () => { const alert = mockAlert(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_add.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_add.tsx index 2ab59a9d10ab9..4e6d63e97ec45 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_add.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_add.tsx @@ -82,25 +82,18 @@ export const AlertAdd = ({ } as IErrorObject; const hasErrors = !!Object.keys(errors).find(errorKey => errors[errorKey].length >= 1); - const actionsErrors = alert.actions.reduce( - (acc: Record, alertAction: AlertAction) => { - const actionType = actionTypeRegistry.get(alertAction.actionTypeId); - if (!actionType) { - return { ...acc }; - } - const actionValidationErrors = actionType.validateParams(alertAction.params); - return { ...acc, [alertAction.id]: actionValidationErrors }; - }, - {} - ) as Record; + const actionsErrors: Array<{ + errors: IErrorObject; + }> = alert.actions.map((alertAction: AlertAction) => + actionTypeRegistry.get(alertAction.actionTypeId)?.validateParams(alertAction.params) + ); - const hasActionErrors = !!Object.entries(actionsErrors) - .map(([, actionErrors]) => actionErrors) - .find((actionErrors: { errors: IErrorObject }) => { - return !!Object.keys(actionErrors.errors).find( - errorKey => actionErrors.errors[errorKey].length >= 1 - ); - }); + const hasActionErrors = + actionsErrors.find( + (errorObj: { errors: IErrorObject }) => + errorObj && + !!Object.keys(errorObj.errors).find(errorKey => errorObj.errors[errorKey].length >= 1) + ) !== undefined; async function onSaveAlert(): Promise { try { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_edit.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_edit.tsx index ac3951cfa98de..3feceb42e6ddc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_edit.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_edit.tsx @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import React, { useCallback, useReducer, useState } from 'react'; +import React, { Fragment, useCallback, useReducer, useState } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiTitle, @@ -17,6 +17,8 @@ import { EuiFlyoutBody, EuiPortal, EuiBetaBadge, + EuiCallOut, + EuiSpacer, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { useAlertsContext } from '../../context/alerts_context'; @@ -38,6 +40,7 @@ export const AlertEdit = ({ }: AlertEditProps) => { const [{ alert }, dispatch] = useReducer(alertReducer, { alert: initialAlert }); const [isSaving, setIsSaving] = useState(false); + const [hasActionsDisabled, setHasActionsDisabled] = useState(false); const { reloadAlerts, @@ -63,25 +66,18 @@ export const AlertEdit = ({ } as IErrorObject; const hasErrors = !!Object.keys(errors).find(errorKey => errors[errorKey].length >= 1); - const actionsErrors = alert.actions.reduce( - (acc: Record, alertAction: AlertAction) => { - const actionType = actionTypeRegistry.get(alertAction.actionTypeId); - if (!actionType) { - return { ...acc }; - } - const actionValidationErrors = actionType.validateParams(alertAction.params); - return { ...acc, [alertAction.id]: actionValidationErrors }; - }, - {} - ) as Record; + const actionsErrors: Array<{ + errors: IErrorObject; + }> = alert.actions.map((alertAction: AlertAction) => + actionTypeRegistry.get(alertAction.actionTypeId)?.validateParams(alertAction.params) + ); - const hasActionErrors = !!Object.entries(actionsErrors) - .map(([, actionErrors]) => actionErrors) - .find((actionErrors: { errors: IErrorObject }) => { - return !!Object.keys(actionErrors.errors).find( - errorKey => actionErrors.errors[errorKey].length >= 1 - ); - }); + const hasActionErrors = + actionsErrors.find( + (errorObj: { errors: IErrorObject }) => + errorObj && + !!Object.keys(errorObj.errors).find(errorKey => errorObj.errors[errorKey].length >= 1) + ) !== undefined; async function onSaveAlert(): Promise { try { @@ -141,7 +137,27 @@ export const AlertEdit = ({ - + {hasActionsDisabled && ( + + + + + )} + diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.test.tsx index b31be7ecb9a79..b87aaacb3ec0e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.test.tsx @@ -86,7 +86,7 @@ describe('alert_form', () => { uiSettings: deps!.uiSettings, }} > - {}} errors={{ name: [] }} /> + {}} errors={{ name: [], interval: [] }} /> ); @@ -165,7 +165,7 @@ describe('alert_form', () => { uiSettings: deps!.uiSettings, }} > - {}} errors={{ name: [] }} /> + {}} errors={{ name: [], interval: [] }} /> ); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.tsx index 1fa620c5394a1..c6346ba002a7f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alert_form/alert_form.tsx @@ -24,6 +24,10 @@ import { EuiButtonIcon, EuiHorizontalRule, } from '@elastic/eui'; +import { + getDurationNumberInItsUnit, + getDurationUnitValue, +} from '../../../../../alerting/common/parse_duration'; import { loadAlertTypes } from '../../lib/alert_api'; import { actionVariablesFromAlertType } from '../../lib/action_variables'; import { AlertReducerAction } from './alert_reducer'; @@ -48,7 +52,7 @@ export function validateBaseProperties(alertObject: Alert) { }) ); } - if (!alertObject.schedule.interval) { + if (alertObject.schedule.interval.length < 2) { errors.interval.push( i18n.translate('xpack.triggersActionsUI.sections.alertForm.error.requiredIntervalText', { defaultMessage: 'Check interval is required.', @@ -70,9 +74,16 @@ interface AlertFormProps { dispatch: React.Dispatch; errors: IErrorObject; canChangeTrigger?: boolean; // to hide Change trigger button + setHasActionsDisabled?: (value: boolean) => void; } -export const AlertForm = ({ alert, canChangeTrigger = true, dispatch, errors }: AlertFormProps) => { +export const AlertForm = ({ + alert, + canChangeTrigger = true, + dispatch, + errors, + setHasActionsDisabled, +}: AlertFormProps) => { const alertsContext = useAlertsContext(); const { http, toastNotifications, alertTypeRegistry, actionTypeRegistry } = alertsContext; @@ -81,17 +92,17 @@ export const AlertForm = ({ alert, canChangeTrigger = true, dispatch, errors }: ); const [alertTypesIndex, setAlertTypesIndex] = useState(undefined); - const [alertInterval, setAlertInterval] = useState( - alert.schedule.interval ? parseInt(alert.schedule.interval.replace(/^[A-Za-z]+$/, ''), 0) : 1 + const [alertInterval, setAlertInterval] = useState( + alert.schedule.interval ? getDurationNumberInItsUnit(alert.schedule.interval) : undefined ); const [alertIntervalUnit, setAlertIntervalUnit] = useState( - alert.schedule.interval ? alert.schedule.interval.replace(alertInterval.toString(), '') : 'm' + alert.schedule.interval ? getDurationUnitValue(alert.schedule.interval) : 'm' ); const [alertThrottle, setAlertThrottle] = useState( - alert.throttle ? parseInt(alert.throttle.replace(/^[A-Za-z]+$/, ''), 0) : null + alert.throttle ? getDurationNumberInItsUnit(alert.throttle) : null ); const [alertThrottleUnit, setAlertThrottleUnit] = useState( - alert.throttle ? alert.throttle.replace((alertThrottle ?? '').toString(), '') : 'm' + alert.throttle ? getDurationUnitValue(alert.throttle) : 'm' ); const [defaultActionGroupId, setDefaultActionGroupId] = useState(undefined); @@ -214,6 +225,7 @@ export const AlertForm = ({ alert, canChangeTrigger = true, dispatch, errors }: {defaultActionGroupId ? ( av.name) @@ -344,19 +356,27 @@ export const AlertForm = ({ alert, canChangeTrigger = true, dispatch, errors }: - + 0} + error={errors.interval} + > 0} compressed - value={alertInterval} + value={alertInterval || ''} name="interval" data-test-subj="intervalInput" onChange={e => { - const interval = e.target.value !== '' ? parseInt(e.target.value, 10) : null; - setAlertInterval(interval ?? 1); + const interval = + e.target.value !== '' ? parseInt(e.target.value, 10) : undefined; + setAlertInterval(interval); setScheduleProperty('interval', `${e.target.value}${alertIntervalUnit}`); }} /> @@ -366,7 +386,7 @@ export const AlertForm = ({ alert, canChangeTrigger = true, dispatch, errors }: fullWidth compressed value={alertIntervalUnit} - options={getTimeOptions(alertInterval)} + options={getTimeOptions(alertInterval ?? 1)} onChange={e => { setAlertIntervalUnit(e.target.value); setScheduleProperty('interval', `${alertInterval}${e.target.value}`); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.tsx index 4bcfef78abd71..18e79a1d93a10 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.tsx @@ -21,6 +21,7 @@ import { } from '@elastic/eui'; import { useHistory } from 'react-router-dom'; +import { isEmpty } from 'lodash'; import { AlertsContextProvider } from '../../../context/alerts_context'; import { useAppDependencies } from '../../../app_context'; import { ActionType, Alert, AlertTableItem, AlertTypeIndex, Pagination } from '../../../../types'; @@ -216,31 +217,25 @@ export const AlertsList: React.FunctionComponent = () => { 'data-test-subj': 'alertsTableCell-interval', }, { - field: '', name: '', width: '50px', - actions: canSave - ? [ - { - render: (item: AlertTableItem) => { - return alertTypeRegistry.has(item.alertTypeId) ? ( - editItem(item)} - > - - - ) : ( - <> - ); - }, - }, - ] - : [], + render(item: AlertTableItem) { + if (!canSave || !alertTypeRegistry.has(item.alertTypeId)) { + return; + } + return ( + editItem(item)} + > + + + ); + }, }, { name: '', @@ -417,15 +412,24 @@ export const AlertsList: React.FunctionComponent = () => {
); + const loadedItems = convertAlertsToTableItems(alertsState.data, alertTypesState.data); + + const isFilterApplied = !( + isEmpty(searchText) && + isEmpty(typesFilter) && + isEmpty(actionTypesFilter) + ); + return (
- {convertAlertsToTableItems(alertsState.data, alertTypesState.data).length !== 0 && table} - {convertAlertsToTableItems(alertsState.data, alertTypesState.data).length === 0 && - !alertTypesState.isLoading && - !alertsState.isLoading && - emptyPrompt} - {(alertTypesState.isLoading || alertsState.isLoading) && } + {loadedItems.length || isFilterApplied ? ( + table + ) : alertTypesState.isLoading || alertsState.isLoading ? ( + + ) : ( + emptyPrompt + )} { } /** - * Returns an object type, null if not registered + * Returns an object type, throw error if not registered */ public get(id: string): T { if (!this.has(id)) { diff --git a/x-pack/plugins/triggers_actions_ui/public/common/constants/index.ts b/x-pack/plugins/triggers_actions_ui/public/common/constants/index.ts index 816dc894ab9ec..a2a1657a1f4cc 100644 --- a/x-pack/plugins/triggers_actions_ui/public/common/constants/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/common/constants/index.ts @@ -7,3 +7,5 @@ export { COMPARATORS, builtInComparators } from './comparators'; export { AGGREGATION_TYPES, builtInAggregationTypes } from './aggregation_types'; export { builtInGroupByTypes } from './group_by_types'; + +export const VIEW_LICENSE_OPTIONS_LINK = 'https://www.elastic.co/subscriptions'; diff --git a/x-pack/plugins/triggers_actions_ui/public/common/expression_items/for_the_last.test.tsx b/x-pack/plugins/triggers_actions_ui/public/common/expression_items/for_the_last.test.tsx index 6ae3056001c8f..e66bb1e7b4b9a 100644 --- a/x-pack/plugins/triggers_actions_ui/public/common/expression_items/for_the_last.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/common/expression_items/for_the_last.test.tsx @@ -36,7 +36,7 @@ describe('for the last expression', () => { /> ); wrapper.simulate('click'); - expect(wrapper.find('[value=1]').length > 0).toBeTruthy(); + expect(wrapper.find('[value=""]').length > 0).toBeTruthy(); expect(wrapper.find('[value="s"]').length > 0).toBeTruthy(); expect( wrapper.contains( diff --git a/x-pack/plugins/triggers_actions_ui/public/common/expression_items/for_the_last.tsx b/x-pack/plugins/triggers_actions_ui/public/common/expression_items/for_the_last.tsx index 844551de3171d..673391dd9cbad 100644 --- a/x-pack/plugins/triggers_actions_ui/public/common/expression_items/for_the_last.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/common/expression_items/for_the_last.tsx @@ -25,7 +25,7 @@ interface ForLastExpressionProps { timeWindowSize?: number; timeWindowUnit?: string; errors: { [key: string]: string[] }; - onChangeWindowSize: (selectedWindowSize: number | '') => void; + onChangeWindowSize: (selectedWindowSize: number | undefined) => void; onChangeWindowUnit: (selectedWindowUnit: string) => void; popupPosition?: | 'upCenter' @@ -43,7 +43,7 @@ interface ForLastExpressionProps { } export const ForLastExpression = ({ - timeWindowSize = 1, + timeWindowSize, timeWindowUnit = 's', errors, onChangeWindowSize, @@ -64,7 +64,7 @@ export const ForLastExpression = ({ )} value={`${timeWindowSize} ${getTimeUnitLabel( timeWindowUnit as TIME_UNITS, - timeWindowSize.toString() + (timeWindowSize ?? '').toString() )}`} isActive={alertDurationPopoverOpen} onClick={() => { @@ -97,11 +97,11 @@ export const ForLastExpression = ({ 0 && timeWindowSize !== undefined} - min={1} - value={timeWindowSize} + min={0} + value={timeWindowSize || ''} onChange={e => { const { value } = e.target; - const timeWindowSizeVal = value !== '' ? parseInt(value, 10) : value; + const timeWindowSizeVal = value !== '' ? parseInt(value, 10) : undefined; onChangeWindowSize(timeWindowSizeVal); }} /> @@ -114,7 +114,7 @@ export const ForLastExpression = ({ onChange={e => { onChangeWindowUnit(e.target.value); }} - options={getTimeOptions(timeWindowSize)} + options={getTimeOptions(timeWindowSize ?? 1)} /> diff --git a/x-pack/plugins/triggers_actions_ui/public/index.ts b/x-pack/plugins/triggers_actions_ui/public/index.ts index 668a8802d1461..342401c4778d8 100644 --- a/x-pack/plugins/triggers_actions_ui/public/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/index.ts @@ -11,7 +11,7 @@ export { AlertsContextProvider } from './application/context/alerts_context'; export { ActionsConnectorsContextProvider } from './application/context/actions_connectors_context'; export { AlertAdd } from './application/sections/alert_form'; export { ActionForm } from './application/sections/action_connector_form'; -export { AlertAction, Alert, AlertTypeModel } from './types'; +export { AlertAction, Alert, AlertTypeModel, ActionType } from './types'; export { ConnectorAddFlyout, ConnectorEditFlyout, diff --git a/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx index 96f1669d8f0e3..ec88a8c6d4cff 100644 --- a/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx @@ -215,6 +215,7 @@ export const WatchVisualization = () => { theme={[customTheme(), chartsTheme]} xDomain={domain} showLegend={!!watch.termField} + showLegendExtra legendPosition={Position.Bottom} /> { box: { incremental: true, }, - toolsLeft: selection.length && ( - { - setWatchesToDelete(selection.map((selected: any) => selected.id)); - }} - color="danger" - > - {selection.length > 1 ? ( - - ) : ( - - )} - - ), + toolsLeft: + selection.length > 0 ? ( + { + setWatchesToDelete(selection.map((selected: any) => selected.id)); + }} + color="danger" + > + {selection.length > 1 ? ( + + ) : ( + + )} + + ) : ( + undefined + ), toolsRight: createWatchContextMenu, }; diff --git a/x-pack/scripts/functional_tests.js b/x-pack/scripts/functional_tests.js index c1f8047c8a5cc..06ee0b91c8a5d 100644 --- a/x-pack/scripts/functional_tests.js +++ b/x-pack/scripts/functional_tests.js @@ -13,6 +13,7 @@ const onlyNotInCoverageTests = [ require.resolve('../test/functional/config_security_basic.js'), require.resolve('../test/api_integration/config_security_basic.js'), require.resolve('../test/api_integration/config.js'), + require.resolve('../test/alerting_api_integration/basic/config.ts'), require.resolve('../test/alerting_api_integration/spaces_only/config.ts'), require.resolve('../test/alerting_api_integration/security_and_spaces/config.ts'), require.resolve('../test/detection_engine_api_integration/security_and_spaces/config.ts'), diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/index.ts b/x-pack/test/alerting_api_integration/basic/config.ts similarity index 53% rename from x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/index.ts rename to x-pack/test/alerting_api_integration/basic/config.ts index a35a4aba66487..f9c248ec3d56f 100644 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/pretty_duration/index.ts +++ b/x-pack/test/alerting_api_integration/basic/config.ts @@ -4,7 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pure } from 'recompose'; -import { PrettyDuration as Component } from './pretty_duration'; +import { createTestConfig } from '../common/config'; -export const PrettyDuration = pure(Component); +// eslint-disable-next-line import/no-default-export +export default createTestConfig('basic', { + disabledPlugins: [], + license: 'basic', + ssl: true, +}); diff --git a/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/email.ts b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/email.ts new file mode 100644 index 0000000000000..f22fe0e3bc1e7 --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/email.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function emailTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + + describe('create email action', () => { + it('should return 403 when creating an email action', async () => { + await supertest + .post('/api/action') + .set('kbn-xsrf', 'foo') + .send({ + name: 'An email action', + actionTypeId: '.email', + config: { + service: '__json', + from: 'bob@example.com', + }, + secrets: { + user: 'bob', + password: 'supersecret', + }, + }) + .expect(403, { + statusCode: 403, + error: 'Forbidden', + message: + 'Action type .email is disabled because your basic license does not support it. Please upgrade your license.', + }); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/es_index.ts b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/es_index.ts new file mode 100644 index 0000000000000..ec07f6ff44df6 --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/es_index.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function indexTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + + describe('index action', () => { + it('should return 200 when creating an index action', async () => { + // create action with no config + await supertest + .post('/api/action') + .set('kbn-xsrf', 'foo') + .send({ + name: 'An index action', + actionTypeId: '.index', + config: { + index: 'foo', + }, + secrets: {}, + }) + .expect(200); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/pagerduty.ts b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/pagerduty.ts new file mode 100644 index 0000000000000..e261cf15d05ae --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/pagerduty.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function pagerdutyTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + + describe('pagerduty action', () => { + it('should return 403 when creating a pagerduty action', async () => { + await supertest + .post('/api/action') + .set('kbn-xsrf', 'foo') + .send({ + name: 'A pagerduty action', + actionTypeId: '.pagerduty', + config: { + apiUrl: 'http://localhost', + }, + secrets: { + routingKey: 'pager-duty-routing-key', + }, + }) + .expect(403, { + statusCode: 403, + error: 'Forbidden', + message: + 'Action type .pagerduty is disabled because your basic license does not support it. Please upgrade your license.', + }); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/server_log.ts b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/server_log.ts new file mode 100644 index 0000000000000..686f4a0086fa0 --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/server_log.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function serverLogTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const esArchiver = getService('esArchiver'); + + describe('server-log action', () => { + after(() => esArchiver.unload('empty_kibana')); + + it('should return 200 when creating a server-log action', async () => { + await supertest + .post('/api/action') + .set('kbn-xsrf', 'foo') + .send({ + name: 'A server.log action', + actionTypeId: '.server-log', + }) + .expect(200); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/servicenow.ts b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/servicenow.ts new file mode 100644 index 0000000000000..a7551ad7e2fad --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/servicenow.ts @@ -0,0 +1,83 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; + +import { + getExternalServiceSimulatorPath, + ExternalServiceSimulator, +} from '../../../../common/fixtures/plugins/actions'; + +// node ../scripts/functional_test_runner.js --grep "Actions.servicenddd" --config=test/alerting_api_integration/security_and_spaces/config.ts + +const mapping = [ + { + source: 'title', + target: 'description', + actionType: 'nothing', + }, + { + source: 'description', + target: 'short_description', + actionType: 'nothing', + }, + { + source: 'comments', + target: 'comments', + actionType: 'nothing', + }, +]; + +// eslint-disable-next-line import/no-default-export +export default function servicenowTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const kibanaServer = getService('kibanaServer'); + const mockServiceNow = { + config: { + apiUrl: 'www.servicenowisinkibanaactions.com', + casesConfiguration: { mapping: [...mapping] }, + }, + secrets: { + password: 'elastic', + username: 'changeme', + }, + params: { + comments: 'hello cool service now incident', + short_description: 'this is a cool service now incident', + }, + }; + describe('servicenow', () => { + let servicenowSimulatorURL: string = ''; + + // need to wait for kibanaServer to settle ... + before(() => { + servicenowSimulatorURL = kibanaServer.resolveUrl( + getExternalServiceSimulatorPath(ExternalServiceSimulator.SERVICENOW) + ); + }); + + it('should return 403 when creating a servicenow action', async () => { + await supertest + .post('/api/action') + .set('kbn-xsrf', 'foo') + .send({ + name: 'A servicenow action', + actionTypeId: '.servicenow', + config: { + apiUrl: servicenowSimulatorURL, + casesConfiguration: { ...mockServiceNow.config.casesConfiguration }, + }, + secrets: mockServiceNow.secrets, + }) + .expect(403, { + statusCode: 403, + error: 'Forbidden', + message: + 'Action type .servicenow is disabled because your basic license does not support it. Please upgrade your license.', + }); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/slack.ts b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/slack.ts new file mode 100644 index 0000000000000..46258e41d5d69 --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/slack.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; + +import { + getExternalServiceSimulatorPath, + ExternalServiceSimulator, +} from '../../../../common/fixtures/plugins/actions'; + +// eslint-disable-next-line import/no-default-export +export default function slackTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const kibanaServer = getService('kibanaServer'); + + describe('slack action', () => { + let slackSimulatorURL: string = ''; + + // need to wait for kibanaServer to settle ... + before(() => { + slackSimulatorURL = kibanaServer.resolveUrl( + getExternalServiceSimulatorPath(ExternalServiceSimulator.SLACK) + ); + }); + + it('should return 403 when creating a slack action', async () => { + await supertest + .post('/api/action') + .set('kbn-xsrf', 'foo') + .send({ + name: 'A slack action', + actionTypeId: '.slack', + secrets: { + webhookUrl: slackSimulatorURL, + }, + }) + .expect(403, { + statusCode: 403, + error: 'Forbidden', + message: + 'Action type .slack is disabled because your basic license does not support it. Please upgrade your license.', + }); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/webhook.ts b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/webhook.ts new file mode 100644 index 0000000000000..338610e9243a4 --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/actions/builtin_action_types/webhook.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../../common/ftr_provider_context'; +import { + getExternalServiceSimulatorPath, + ExternalServiceSimulator, +} from '../../../../common/fixtures/plugins/actions'; + +// eslint-disable-next-line import/no-default-export +export default function webhookTest({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const kibanaServer = getService('kibanaServer'); + + describe('webhook action', () => { + let webhookSimulatorURL: string = ''; + + // need to wait for kibanaServer to settle ... + before(() => { + webhookSimulatorURL = kibanaServer.resolveUrl( + getExternalServiceSimulatorPath(ExternalServiceSimulator.WEBHOOK) + ); + }); + + it('should return 403 when creating a webhook action', async () => { + await supertest + .post('/api/action') + .set('kbn-xsrf', 'test') + .send({ + name: 'A generic Webhook action', + actionTypeId: '.webhook', + secrets: { + user: 'username', + password: 'mypassphrase', + }, + config: { + url: webhookSimulatorURL, + }, + }) + .expect(403, { + statusCode: 403, + error: 'Forbidden', + message: + 'Action type .webhook is disabled because your basic license does not support it. Please upgrade your license.', + }); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/basic/tests/actions/index.ts b/x-pack/test/alerting_api_integration/basic/tests/actions/index.ts new file mode 100644 index 0000000000000..1788a12afebf2 --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/actions/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../../common/ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function actionsTests({ loadTestFile }: FtrProviderContext) { + describe('Actions', () => { + loadTestFile(require.resolve('./builtin_action_types/email')); + loadTestFile(require.resolve('./builtin_action_types/es_index')); + loadTestFile(require.resolve('./builtin_action_types/pagerduty')); + loadTestFile(require.resolve('./builtin_action_types/server_log')); + loadTestFile(require.resolve('./builtin_action_types/servicenow')); + loadTestFile(require.resolve('./builtin_action_types/slack')); + loadTestFile(require.resolve('./builtin_action_types/webhook')); + }); +} diff --git a/x-pack/test/alerting_api_integration/basic/tests/index.ts b/x-pack/test/alerting_api_integration/basic/tests/index.ts new file mode 100644 index 0000000000000..2aa5ddee11047 --- /dev/null +++ b/x-pack/test/alerting_api_integration/basic/tests/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { FtrProviderContext } from '../../common/ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function alertingApiIntegrationTests({ + loadTestFile, + getService, +}: FtrProviderContext) { + describe('alerting api integration basic license', function() { + this.tags('ciGroup3'); + + loadTestFile(require.resolve('./actions')); + }); +} diff --git a/x-pack/test/alerting_api_integration/common/config.ts b/x-pack/test/alerting_api_integration/common/config.ts index eb03aafc03d08..5fb1afa7d584f 100644 --- a/x-pack/test/alerting_api_integration/common/config.ts +++ b/x-pack/test/alerting_api_integration/common/config.ts @@ -62,7 +62,8 @@ export function createTestConfig(name: string, options: CreateTestConfigOptions) ssl, serverArgs: [ `xpack.license.self_generated.type=${license}`, - `xpack.security.enabled=${!disabledPlugins.includes('security') && license === 'trial'}`, + `xpack.security.enabled=${!disabledPlugins.includes('security') && + ['trial', 'basic'].includes(license)}`, ], }, kbnTestServer: { diff --git a/x-pack/test/alerting_api_integration/common/fixtures/plugins/actions/index.ts b/x-pack/test/alerting_api_integration/common/fixtures/plugins/actions/index.ts index aeec07aba906c..acd14e8a2bf7b 100644 --- a/x-pack/test/alerting_api_integration/common/fixtures/plugins/actions/index.ts +++ b/x-pack/test/alerting_api_integration/common/fixtures/plugins/actions/index.ts @@ -43,6 +43,7 @@ export default function(kibana: any) { const notEnabledActionType: ActionType = { id: 'test.not-enabled', name: 'Test: Not Enabled', + minimumLicenseRequired: 'gold', async executor() { return { status: 'ok', actionId: '' }; }, diff --git a/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts/index.ts b/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts/index.ts index 58f7a49720007..9b4a2d14de9ea 100644 --- a/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts/index.ts +++ b/x-pack/test/alerting_api_integration/common/fixtures/plugins/alerts/index.ts @@ -42,6 +42,7 @@ export default function(kibana: any) { const noopActionType: ActionType = { id: 'test.noop', name: 'Test: Noop', + minimumLicenseRequired: 'gold', async executor() { return { status: 'ok', actionId: '' }; }, @@ -49,6 +50,7 @@ export default function(kibana: any) { const indexRecordActionType: ActionType = { id: 'test.index-record', name: 'Test: Index Record', + minimumLicenseRequired: 'gold', validate: { params: schema.object({ index: schema.string(), @@ -80,6 +82,7 @@ export default function(kibana: any) { const failingActionType: ActionType = { id: 'test.failing', name: 'Test: Failing', + minimumLicenseRequired: 'gold', validate: { params: schema.object({ index: schema.string(), @@ -104,6 +107,7 @@ export default function(kibana: any) { const rateLimitedActionType: ActionType = { id: 'test.rate-limit', name: 'Test: Rate Limit', + minimumLicenseRequired: 'gold', maxAttempts: 2, validate: { params: schema.object({ @@ -133,6 +137,7 @@ export default function(kibana: any) { const authorizationActionType: ActionType = { id: 'test.authorization', name: 'Test: Authorization', + minimumLicenseRequired: 'gold', validate: { params: schema.object({ callClusterAuthorizationIndex: schema.string(), diff --git a/x-pack/test/alerting_api_integration/common/lib/es_test_index_tool.ts b/x-pack/test/alerting_api_integration/common/lib/es_test_index_tool.ts index 999a8686e0ee7..14a91325d1cc1 100644 --- a/x-pack/test/alerting_api_integration/common/lib/es_test_index_tool.ts +++ b/x-pack/test/alerting_api_integration/common/lib/es_test_index_tool.ts @@ -41,6 +41,10 @@ export class ESTestIndexTool { type: 'date', format: 'strict_date_time', }, + date_epoch_millis: { + type: 'date', + format: 'epoch_millis', + }, testedValue: { type: 'long', }, diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/create.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/create.ts index 1ce9a6ba3a040..43a3861491467 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/create.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/create.ts @@ -205,10 +205,10 @@ export default function createActionTests({ getService }: FtrProviderContext) { break; case 'superuser at space1': case 'space_1_all at space1': - expect(response.statusCode).to.eql(400); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 400, - error: 'Bad Request', + statusCode: 403, + error: 'Forbidden', message: 'action type "test.not-enabled" is not enabled in the Kibana config xpack.actions.enabledActionTypes', }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/config.ts b/x-pack/test/alerting_api_integration/spaces_only/config.ts index 44603cc95e5e0..c79c26ef68752 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/config.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/config.ts @@ -7,4 +7,4 @@ import { createTestConfig } from '../common/config'; // eslint-disable-next-line import/no-default-export -export default createTestConfig('spaces_only', { disabledPlugins: ['security'], license: 'basic' }); +export default createTestConfig('spaces_only', { disabledPlugins: ['security'], license: 'trial' }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/actions/type_not_enabled.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/actions/type_not_enabled.ts index 7193a80b94498..1388108806c0f 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/actions/type_not_enabled.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/actions/type_not_enabled.ts @@ -29,10 +29,10 @@ export default function typeNotEnabledTests({ getService }: FtrProviderContext) actionTypeId: DISABLED_ACTION_TYPE, }); - expect(response.statusCode).to.eql(400); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - statusCode: 400, - error: 'Bad Request', + statusCode: 403, + error: 'Forbidden', message: 'action type "test.not-enabled" is not enabled in the Kibana config xpack.actions.enabledActionTypes', }); @@ -46,11 +46,10 @@ export default function typeNotEnabledTests({ getService }: FtrProviderContext) params: {}, }); - expect(response.statusCode).to.eql(200); + expect(response.statusCode).to.eql(403); expect(response.body).to.eql({ - status: 'error', - retry: false, - actionId: PREWRITTEN_ACTION_ID, + statusCode: 403, + error: 'Forbidden', message: 'action type "test.not-enabled" is not enabled in the Kibana config xpack.actions.enabledActionTypes', }); @@ -76,12 +75,12 @@ export default function typeNotEnabledTests({ getService }: FtrProviderContext) name: 'an action created before test.not-enabled was disabled (updated)', }); - expect(responseUpdate.statusCode).to.eql(200); + expect(responseUpdate.statusCode).to.eql(403); expect(responseUpdate.body).to.eql({ - actionTypeId: 'test.not-enabled', - config: {}, - id: 'uuid-actionId', - name: 'an action created before test.not-enabled was disabled (updated)', + statusCode: 403, + error: 'Forbidden', + message: + 'action type "test.not-enabled" is not enabled in the Kibana config xpack.actions.enabledActionTypes', }); const response = await supertest.get(`/api/action/${PREWRITTEN_ACTION_ID}`); @@ -90,7 +89,7 @@ export default function typeNotEnabledTests({ getService }: FtrProviderContext) actionTypeId: 'test.not-enabled', config: {}, id: 'uuid-actionId', - name: 'an action created before test.not-enabled was disabled (updated)', + name: 'an action created before test.not-enabled was disabled', }); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/alert.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/alert.ts index 13f3a4971183c..87acbcf99d383 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/alert.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/alert.ts @@ -172,12 +172,14 @@ export default function alertTests({ getService }: FtrProviderContext) { // create some more documents in the first group createEsDocumentsInGroups(1); + // this never fires because of bad fields error await createAlert({ name: 'never fire', + timeField: 'source', // bad field for time aggType: 'avg', - aggField: 'testedValue', + aggField: 'source', // bad field for agg groupBy: 'all', - thresholdComparator: '<', + thresholdComparator: '>', threshold: [0], }); @@ -303,6 +305,7 @@ export default function alertTests({ getService }: FtrProviderContext) { name: string; aggType: string; aggField?: string; + timeField?: string; groupBy: 'all' | 'top'; termField?: string; termSize?: number; @@ -347,7 +350,7 @@ export default function alertTests({ getService }: FtrProviderContext) { actions: [action], params: { index: ES_TEST_INDEX_NAME, - timeField: 'date', + timeField: params.timeField || 'date', aggType: params.aggType, aggField: params.aggField, groupBy: params.groupBy, diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/create_test_data.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/create_test_data.ts index 21f73ac9b9833..1a83f34f0fdfb 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/create_test_data.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/create_test_data.ts @@ -53,6 +53,7 @@ async function createEsDocument(es: any, epochMillis: number, testedValue: numbe source: DOCUMENT_SOURCE, reference: DOCUMENT_REFERENCE, date: new Date(epochMillis).toISOString(), + date_epoch_millis: epochMillis, testedValue, group, }; diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/fields_endpoint.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/fields_endpoint.ts index fa7aed2c035b9..c6f8f6d1b80b1 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/fields_endpoint.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/fields_endpoint.ts @@ -139,6 +139,12 @@ export default function fieldsEndpointTests({ getService }: FtrProviderContext) expect(field.name).to.eql('updated_at'); expect(field.type).to.eql('date'); }); + + // TODO: the pattern '*a:b,c:d*' throws an exception in dev, but not ci! + it('should handle no_such_remote_cluster', async () => { + const result = await runQueryExpect({ indexPatterns: ['*a:b,c:d*'] }, 200); + expect(result.fields.length).to.be(0); + }); }); function getFieldNamed(fields: any[], fieldName: string): any | undefined { diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/indices_endpoint.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/indices_endpoint.ts index 6908398deb57b..72484fa70f9cc 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/indices_endpoint.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/indices_endpoint.ts @@ -105,6 +105,12 @@ export default function indicesEndpointTests({ getService }: FtrProviderContext) expect(result.indices).to.be.an('array'); expect(result.indices.includes('.kibana')).to.be(true); }); + + // TODO: the pattern '*a:b,c:d*' throws an exception in dev, but not ci! + it('should handle no_such_remote_cluster', async () => { + const result = await runQueryExpect({ pattern: '*a:b,c:d*' }, 200); + expect(result.indices.length).to.be(0); + }); }); async function runQueryExpect(requestBody: any, status: number): Promise { diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/time_series_query_endpoint.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/time_series_query_endpoint.ts index c9b488da5dec5..932ffe3a7ce14 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/time_series_query_endpoint.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/builtin_alert_types/index_threshold/time_series_query_endpoint.ts @@ -273,6 +273,32 @@ export default function timeSeriesQueryEndpointTests({ getService }: FtrProvider }; expect(await runQueryExpect(query, 400)).eql(expected); }); + + it('should handle epoch_millis time field', async () => { + const query = getQueryBody({ + dateStart: START_DATE, + dateEnd: START_DATE, + timeField: 'date_epoch_millis', + }); + const expected = { + results: [{ group: 'all documents', metrics: [[START_DATE, 6]] }], + }; + expect(await runQueryExpect(query, 200)).eql(expected); + }); + + it('should handle ES errors', async () => { + const query = getQueryBody({ + dateStart: START_DATE, + dateEnd: START_DATE, + timeField: 'source', // bad field for time + aggType: 'avg', + aggField: 'source', // bad field for agg + }); + const expected = { + results: [], + }; + expect(await runQueryExpect(query, 200)).eql(expected); + }); }); async function runQueryExpect(requestBody: TimeSeriesQuery, status: number): Promise { diff --git a/x-pack/test/api_integration/apis/fleet/agents/services.ts b/x-pack/test/api_integration/apis/fleet/agents/services.ts index 9946135568e36..8b58c381eaf02 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/services.ts +++ b/x-pack/test/api_integration/apis/fleet/agents/services.ts @@ -39,10 +39,6 @@ export function setupIngest({ getService }: FtrProviderContext) { .send(); await getService('supertest') .post(`/api/ingest_manager/fleet/setup`) - .set('kbn-xsrf', 'xxx') - .send({ - admin_username: 'elastic', - admin_password: 'changeme', - }); + .set('kbn-xsrf', 'xxx'); }); } diff --git a/x-pack/test/api_integration/apis/fleet/index.js b/x-pack/test/api_integration/apis/fleet/index.js index 547bbb8c7c6ee..289af867a10f8 100644 --- a/x-pack/test/api_integration/apis/fleet/index.js +++ b/x-pack/test/api_integration/apis/fleet/index.js @@ -16,5 +16,6 @@ export default function loadTests({ loadTestFile }) { loadTestFile(require.resolve('./enrollment_api_keys/crud')); loadTestFile(require.resolve('./install')); loadTestFile(require.resolve('./agents/actions')); + loadTestFile(require.resolve('./setup')); }); } diff --git a/x-pack/test/api_integration/apis/fleet/setup.ts b/x-pack/test/api_integration/apis/fleet/setup.ts new file mode 100644 index 0000000000000..2284d067331b3 --- /dev/null +++ b/x-pack/test/api_integration/apis/fleet/setup.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; + +export default function({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + const es = getService('es'); + + describe('fleet_setup', () => { + before(async () => { + try { + await es.security.deleteUser({ + username: 'fleet_enroll', + }); + } catch (e) { + if (e.meta?.statusCode !== 404) { + throw e; + } + } + try { + await es.security.deleteRole({ + name: 'fleet_enroll', + }); + } catch (e) { + if (e.meta?.statusCode !== 404) { + throw e; + } + } + }); + + it('should create a fleet_enroll user and role', async () => { + const { body: apiResponse } = await supertest + .post(`/api/ingest_manager/fleet/setup`) + .set('kbn-xsrf', 'xxxx') + .expect(200); + + expect(apiResponse.isInitialized).to.be(true); + + const { body: userResponse } = await es.security.getUser({ + username: 'fleet_enroll', + }); + + expect(userResponse).to.have.key('fleet_enroll'); + expect(userResponse.fleet_enroll.roles).to.eql(['fleet_enroll']); + + const { body: roleResponse } = await es.security.getRole({ + name: 'fleet_enroll', + }); + expect(roleResponse).to.have.key('fleet_enroll'); + expect(roleResponse.fleet_enroll).to.eql({ + cluster: ['monitor', 'manage_api_key'], + indices: [ + { + names: ['logs-*', 'metrics-*', 'events-*'], + privileges: ['write', 'create_index'], + allow_restricted_indices: false, + }, + ], + applications: [], + run_as: [], + metadata: {}, + transient_metadata: { enabled: true }, + }); + }); + }); +} diff --git a/x-pack/test/api_integration/apis/monitoring/common/mappings_exist.js b/x-pack/test/api_integration/apis/monitoring/common/mappings_exist.js index 73b3f5f97c6fa..d5a72fa0ae3c8 100644 --- a/x-pack/test/api_integration/apis/monitoring/common/mappings_exist.js +++ b/x-pack/test/api_integration/apis/monitoring/common/mappings_exist.js @@ -6,11 +6,11 @@ import expect from '@kbn/expect'; import { get } from 'lodash'; -import * as esMetrics from '../../../../../legacy/plugins/monitoring/server/lib/metrics/elasticsearch/metrics'; -import * as kibanaMetrics from '../../../../../legacy/plugins/monitoring/server/lib/metrics/kibana/metrics'; -import * as logstashMetrics from '../../../../../legacy/plugins/monitoring/server/lib/metrics/logstash/metrics'; -import * as beatsMetrics from '../../../../../legacy/plugins/monitoring/server/lib/metrics/beats/metrics'; -import * as apmMetrics from '../../../../../legacy/plugins/monitoring/server/lib/metrics/apm/metrics'; +import * as esMetrics from '../../../../../plugins/monitoring/server/lib/metrics/elasticsearch/metrics'; +import * as kibanaMetrics from '../../../../../plugins/monitoring/server/lib/metrics/kibana/metrics'; +import * as logstashMetrics from '../../../../../plugins/monitoring/server/lib/metrics/logstash/metrics'; +import * as beatsMetrics from '../../../../../plugins/monitoring/server/lib/metrics/beats/metrics'; +import * as apmMetrics from '../../../../../plugins/monitoring/server/lib/metrics/apm/metrics'; export default function({ getService }) { const es = getService('legacyEs'); diff --git a/x-pack/test/functional/apps/endpoint/policy_details.ts b/x-pack/test/functional/apps/endpoint/policy_details.ts index 39b6e7a9f4fb7..f251dcd93014e 100644 --- a/x-pack/test/functional/apps/endpoint/policy_details.ts +++ b/x-pack/test/functional/apps/endpoint/policy_details.ts @@ -10,7 +10,8 @@ export default function({ getPageObjects, getService }: FtrProviderContext) { const pageObjects = getPageObjects(['common', 'endpoint']); const testSubjects = getService('testSubjects'); - describe('Endpoint Policy Details', function() { + // Skipped until we can figure out how to load data for Ingest + describe.skip('Endpoint Policy Details', function() { this.tags(['ciGroup7']); it('loads the Policy Details Page', async () => { diff --git a/x-pack/test/functional/apps/endpoint/policy_list.ts b/x-pack/test/functional/apps/endpoint/policy_list.ts index 382963bc2b0c7..c54eafdd8b787 100644 --- a/x-pack/test/functional/apps/endpoint/policy_list.ts +++ b/x-pack/test/functional/apps/endpoint/policy_list.ts @@ -10,8 +10,8 @@ export default function({ getPageObjects, getService }: FtrProviderContext) { const pageObjects = getPageObjects(['common', 'endpoint']); const testSubjects = getService('testSubjects'); - // FLAKY: https://github.com/elastic/kibana/issues/57946 - describe('Endpoint Policy List', function() { + // FIXME: Skipped until we can figure out how to load data for Ingest + describe.skip('Endpoint Policy List', function() { this.tags(['ciGroup7']); before(async () => { await pageObjects.common.navigateToUrlWithBrowserHistory('endpoint', '/policy'); diff --git a/x-pack/test/functional/apps/lens/smokescreen.ts b/x-pack/test/functional/apps/lens/smokescreen.ts index 317bb0b27e972..5768e51ae5f9f 100644 --- a/x-pack/test/functional/apps/lens/smokescreen.ts +++ b/x-pack/test/functional/apps/lens/smokescreen.ts @@ -9,7 +9,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects, ...rest }: FtrProviderContext) { +export default function({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects([ 'header', 'common', @@ -89,6 +89,17 @@ export default function({ getService, getPageObjects, ...rest }: FtrProviderCont field: 'bytes', }); + await PageObjects.lens.configureDimension({ + dimension: + '[data-test-subj="lnsXY_splitDimensionPanel"] [data-test-subj="lns-empty-dimension"]', + operation: 'terms', + field: '@message.raw', + }); + + await PageObjects.lens.switchToVisualization('lnsChartSwitchPopover_lnsDatatable'); + await PageObjects.lens.removeDimension('lnsDatatable_column'); + await PageObjects.lens.switchToVisualization('lnsChartSwitchPopover_bar_stacked'); + await PageObjects.lens.configureDimension({ dimension: '[data-test-subj="lnsXY_splitDimensionPanel"] [data-test-subj="lns-empty-dimension"]', diff --git a/x-pack/test/functional/page_objects/gis_page.js b/x-pack/test/functional/page_objects/gis_page.js index 8d0c649d75dd6..1d0e231d7dc54 100644 --- a/x-pack/test/functional/page_objects/gis_page.js +++ b/x-pack/test/functional/page_objects/gis_page.js @@ -451,7 +451,7 @@ export function GisPageProvider({ getService, getPageObjects }) { async getCodeBlockParsedJson(dataTestSubjName) { log.debug(`Get parsed code block for ${dataTestSubjName}`); - const indexRespCodeBlock = await find.byCssSelector(`[data-test-subj="${dataTestSubjName}"]`); + const indexRespCodeBlock = await testSubjects.find(`${dataTestSubjName}`); const indexRespJson = await indexRespCodeBlock.getAttribute('innerText'); return JSON.parse(indexRespJson); } diff --git a/x-pack/test/functional/page_objects/lens_page.ts b/x-pack/test/functional/page_objects/lens_page.ts index 480814cb02781..1bf637c50b0ba 100644 --- a/x-pack/test/functional/page_objects/lens_page.ts +++ b/x-pack/test/functional/page_objects/lens_page.ts @@ -103,8 +103,8 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont /** * Changes the specified dimension to the specified operation and (optinally) field. * - * @param opts.from - the text of the dimension being changed - * @param opts.to - the desired operation for the dimension + * @param opts.dimension - the selector of the dimension being changed + * @param opts.operation - the desired operation ID for the dimension * @param opts.field - the desired field for the dimension */ async configureDimension(opts: { dimension: string; operation?: string; field?: string }) { @@ -123,6 +123,15 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont } }, + /** + * Removes the dimension matching a specific test subject + */ + async removeDimension(dimensionTestSubj: string) { + await find.clickByCssSelector( + `[data-test-subj="${dimensionTestSubj}"] [data-test-subj="indexPattern-dimensionPopover-remove"]` + ); + }, + /** * Save the current Lens visualization. */ diff --git a/x-pack/test/functional/page_objects/rollup_page.js b/x-pack/test/functional/page_objects/rollup_page.js index 1514693defecb..b6bc60df6f7cd 100644 --- a/x-pack/test/functional/page_objects/rollup_page.js +++ b/x-pack/test/functional/page_objects/rollup_page.js @@ -111,28 +111,18 @@ export function RollupPageProvider({ getService, getPageObjects }) { async getJobList() { const jobs = await testSubjects.findAll('jobTableRow'); return mapAsync(jobs, async job => { - const jobNameElement = await job.findByCssSelector('[data-test-subj="jobTableCell-id"]'); - const jobStatusElement = await job.findByCssSelector( - '[data-test-subj="jobTableCell-status"]' + const jobNameElement = await job.findByTestSubject('jobTableCell-id'); + const jobStatusElement = await job.findByTestSubject('jobTableCell-status'); + const jobIndexPatternElement = await job.findByTestSubject('jobTableCell-indexPattern'); + const jobRollUpIndexPatternElement = await job.findByTestSubject( + 'jobTableCell-rollupIndex' ); - const jobIndexPatternElement = await job.findByCssSelector( - '[data-test-subj="jobTableCell-indexPattern"]' - ); - const jobRollUpIndexPatternElement = await job.findByCssSelector( - '[data-test-subj="jobTableCell-rollupIndex"]' - ); - const jobDelayElement = await job.findByCssSelector( - '[data-test-subj="jobTableCell-rollupDelay"]' - ); - const jobIntervalElement = await job.findByCssSelector( - '[data-test-subj="jobTableCell-dateHistogramInterval"]' - ); - const jobGroupElement = await job.findByCssSelector( - '[data-test-subj="jobTableCell-groups"]' - ); - const jobMetricsElement = await job.findByCssSelector( - '[data-test-subj="jobTableCell-metrics"]' + const jobDelayElement = await job.findByTestSubject('jobTableCell-rollupDelay'); + const jobIntervalElement = await job.findByTestSubject( + 'jobTableCell-dateHistogramInterval' ); + const jobGroupElement = await job.findByTestSubject('jobTableCell-groups'); + const jobMetricsElement = await job.findByTestSubject('jobTableCell-metrics'); return { jobName: await jobNameElement.getVisibleText(), diff --git a/x-pack/test/functional/page_objects/security_page.js b/x-pack/test/functional/page_objects/security_page.js index 4b097b916573d..b399327012a77 100644 --- a/x-pack/test/functional/page_objects/security_page.js +++ b/x-pack/test/functional/page_objects/security_page.js @@ -229,13 +229,12 @@ export function SecurityPageProvider({ getService, getPageObjects }) { async getElasticsearchUsers() { const users = await testSubjects.findAll('userRow'); return mapAsync(users, async user => { - const fullnameElement = await user.findByCssSelector('[data-test-subj="userRowFullName"]'); - const usernameElement = await user.findByCssSelector('[data-test-subj="userRowUserName"]'); - const emailElement = await user.findByCssSelector('[data-test-subj="userRowEmail"]'); - const rolesElement = await user.findByCssSelector('[data-test-subj="userRowRoles"]'); - // findAllByCssSelector is substantially faster than `find.descendantExistsByCssSelector for negative cases - const isUserReserved = - (await user.findAllByCssSelector('span[data-test-subj="userReserved"]', 1)).length > 0; + const fullnameElement = await user.findByTestSubject('userRowFullName'); + const usernameElement = await user.findByTestSubject('userRowUserName'); + const emailElement = await user.findByTestSubject('userRowEmail'); + const rolesElement = await user.findByTestSubject('userRowRoles'); + // findAll is substantially faster than `find.descendantExistsByCssSelector for negative cases + const isUserReserved = (await user.findAllByTestSubject('userReserved', 1)).length > 0; return { username: await usernameElement.getVisibleText(), @@ -251,15 +250,11 @@ export function SecurityPageProvider({ getService, getPageObjects }) { const users = await testSubjects.findAll('roleRow'); return mapAsync(users, async role => { const [rolename, reserved, deprecated] = await Promise.all([ - role.findByCssSelector('[data-test-subj="roleRowName"]').then(el => el.getVisibleText()), - // findAllByCssSelector is substantially faster than `find.descendantExistsByCssSelector for negative cases - role - .findAllByCssSelector('span[data-test-subj="roleReserved"]', 1) - .then(el => el.length > 0), - // findAllByCssSelector is substantially faster than `find.descendantExistsByCssSelector for negative cases - role - .findAllByCssSelector('span[data-test-subj="roleDeprecated"]', 1) - .then(el => el.length > 0), + role.findByTestSubject('roleRowName').then(el => el.getVisibleText()), + // findAll is substantially faster than `find.descendantExistsByCssSelector for negative cases + role.findAllByTestSubject('roleReserved', 1).then(el => el.length > 0), + // findAll is substantially faster than `find.descendantExistsByCssSelector for negative cases + role.findAllByTestSubject('roleDeprecated', 1).then(el => el.length > 0), ]); return { diff --git a/x-pack/test/functional/page_objects/snapshot_restore_page.ts b/x-pack/test/functional/page_objects/snapshot_restore_page.ts index 1c8ba9f633111..841345e3727f1 100644 --- a/x-pack/test/functional/page_objects/snapshot_restore_page.ts +++ b/x-pack/test/functional/page_objects/snapshot_restore_page.ts @@ -28,21 +28,15 @@ export function SnapshotRestorePageProvider({ getService }: FtrProviderContext) }, async getRepoList() { const table = await testSubjects.find('repositoryTable'); - const rows = await table.findAllByCssSelector('[data-test-subj="row"]'); + const rows = await table.findAllByTestSubject('row'); return await Promise.all( rows.map(async row => { return { - repoName: await ( - await row.findByCssSelector('[data-test-subj="Name_cell"]') - ).getVisibleText(), - repoLink: await ( - await row.findByCssSelector('[data-test-subj="Name_cell"]') - ).findByCssSelector('a'), - repoType: await ( - await row.findByCssSelector('[data-test-subj="Type_cell"]') - ).getVisibleText(), - repoEdit: await row.findByCssSelector('[data-test-subj="editRepositoryButton"]'), - repoDelete: await row.findByCssSelector('[data-test-subj="deleteRepositoryButton"]'), + repoName: await (await row.findByTestSubject('Name_cell')).getVisibleText(), + repoLink: await (await row.findByTestSubject('Name_cell')).findByCssSelector('a'), + repoType: await (await row.findByTestSubject('Type_cell')).getVisibleText(), + repoEdit: await row.findByTestSubject('editRepositoryButton'), + repoDelete: await row.findByTestSubject('deleteRepositoryButton'), }; }) ); diff --git a/x-pack/test/functional/services/machine_learning/data_frame_analytics.ts b/x-pack/test/functional/services/machine_learning/data_frame_analytics.ts index eed7db48af460..bada1d42b564a 100644 --- a/x-pack/test/functional/services/machine_learning/data_frame_analytics.ts +++ b/x-pack/test/functional/services/machine_learning/data_frame_analytics.ts @@ -7,7 +7,7 @@ import { FtrProviderContext } from '../../ftr_provider_context'; import { MlApi } from './api'; -import { DATA_FRAME_TASK_STATE } from '../../../../plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/common'; +import { DATA_FRAME_TASK_STATE } from '../../../../plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/data_frame_task_state'; export function MachineLearningDataFrameAnalyticsProvider( { getService }: FtrProviderContext, diff --git a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/alerts.ts b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/alerts.ts index 79448fa535370..b4dd3bb5baa51 100644 --- a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/alerts.ts +++ b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/alerts.ts @@ -63,7 +63,6 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await fieldOptions[1].click(); // need this two out of popup clicks to close them await nameInput.click(); - await testSubjects.click('intervalInput'); await testSubjects.click('.slack-ActionTypeSelectOption'); await testSubjects.click('createActionConnectorButton'); @@ -84,7 +83,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await testSubjects.click('slackAddVariableButton'); const variableMenuButton = await testSubjects.find('variableMenuButton-0'); await variableMenuButton.click(); - await find.clickByCssSelector('[data-test-subj="saveAlertButton"]'); + await testSubjects.click('saveAlertButton'); const toastTitle = await pageObjects.common.closeToast(); expect(toastTitle).to.eql(`Saved '${alertName}'`); await pageObjects.triggersActionsUI.searchAlerts(alertName); @@ -241,6 +240,13 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { ]); }); + it('should display an empty list when search removes all alerts', async () => { + await pageObjects.common.navigateToApp('triggersActions'); + await pageObjects.triggersActionsUI.searchAlerts(`An Alert That For Sure Doesn't Exist!`); + + expect(await pageObjects.triggersActionsUI.isAlertsListDisplayed()).to.eql(true); + }); + it('should disable single alert', async () => { const createdAlert = await createAlert(); await pageObjects.common.navigateToApp('triggersActions'); @@ -333,10 +339,8 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await testSubjects.click('collapsedItemActions'); await testSubjects.click('deleteAlert'); - const emptyPrompt = await find.byCssSelector( - '[data-test-subj="createFirstAlertEmptyPrompt"]' - ); - expect(await emptyPrompt.elementHasClass('euiEmptyPrompt')).to.be(true); + + expect(await pageObjects.triggersActionsUI.isAnEmptyAlertsListDisplayed()).to.be(true); }); it('should mute all selection', async () => { @@ -446,10 +450,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { await testSubjects.click('deleteAll'); - const emptyPrompt = await find.byCssSelector( - '[data-test-subj="createFirstAlertEmptyPrompt"]' - ); - expect(await emptyPrompt.elementHasClass('euiEmptyPrompt')).to.be(true); + expect(await pageObjects.triggersActionsUI.isAnEmptyAlertsListDisplayed()).to.be(true); }); }); }; diff --git a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts index 64655e5b45a2b..145b536a26f61 100644 --- a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts +++ b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts @@ -148,9 +148,10 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); }); - describe.skip('View In App', function() { + describe('View In App', function() { const testRunUuid = uuid.v4(); - before(async () => { + + beforeEach(async () => { await pageObjects.common.navigateToApp('triggersActions'); }); @@ -170,10 +171,30 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { expect(await pageObjects.alertDetailsUI.isViewInAppEnabled()).to.be(true); - await pageObjects.alertDetailsUI.clickViewInAppEnabled(); + await pageObjects.alertDetailsUI.clickViewInApp(); expect(await pageObjects.alertDetailsUI.getNoOpAppTitle()).to.be(`View Alert ${alert.id}`); }); + + it('renders a disabled alert details view in app button', async () => { + const alert = await alerting.alerts.createAlwaysFiringWithActions( + `test-alert-disabled-nav`, + [] + ); + + // refresh to see alert + await browser.refresh(); + + await pageObjects.header.waitUntilLoadingHasFinished(); + + // Verify content + await testSubjects.existOrFail('alertsList'); + + // click on first alert + await pageObjects.triggersActionsUI.clickOnAlertInAlertsList(alert.name); + + expect(await pageObjects.alertDetailsUI.isViewInAppDisabled()).to.be(true); + }); }); describe('Alert Instances', function() { diff --git a/x-pack/test/functional_with_es_ssl/page_objects/alert_details.ts b/x-pack/test/functional_with_es_ssl/page_objects/alert_details.ts index 03f0056670311..48ad59586f793 100644 --- a/x-pack/test/functional_with_es_ssl/page_objects/alert_details.ts +++ b/x-pack/test/functional_with_es_ssl/page_objects/alert_details.ts @@ -102,15 +102,28 @@ export function AlertDetailsPageProvider({ getService }: FtrProviderContext) { const nextButton = await testSubjects.find(`pagination-button-next`); nextButton.click(); }, + async isViewInAppDisabled() { + await retry.try(async () => { + const viewInAppButton = await testSubjects.find(`alertDetails-viewInApp`); + expect(await viewInAppButton.getAttribute('disabled')).to.eql('true'); + }); + return true; + }, async isViewInAppEnabled() { - const viewInAppButton = await testSubjects.find(`alertDetails-viewInApp`); - return (await viewInAppButton.getAttribute('disabled')) !== 'disabled'; + await retry.try(async () => { + const viewInAppButton = await testSubjects.find(`alertDetails-viewInApp`); + expect(await viewInAppButton.getAttribute('disabled')).to.not.eql('true'); + }); + return true; }, - async clickViewInAppEnabled() { - const viewInAppButton = await testSubjects.find(`alertDetails-viewInApp`); - return viewInAppButton.click(); + async clickViewInApp() { + return await testSubjects.click('alertDetails-viewInApp'); }, async getNoOpAppTitle() { + await retry.try(async () => { + const title = await testSubjects.find('noop-title'); + expect(title.isDisplayed()).to.eql(true); + }); return await testSubjects.getVisibleText('noop-title'); }, }; diff --git a/x-pack/test/functional_with_es_ssl/page_objects/triggers_actions_ui_page.ts b/x-pack/test/functional_with_es_ssl/page_objects/triggers_actions_ui_page.ts index 91c7fe1f97d12..6c41c2cab801e 100644 --- a/x-pack/test/functional_with_es_ssl/page_objects/triggers_actions_ui_page.ts +++ b/x-pack/test/functional_with_es_ssl/page_objects/triggers_actions_ui_page.ts @@ -19,14 +19,14 @@ export function TriggersActionsPageProvider({ getService }: FtrProviderContext) return await testSubjects.getVisibleText('appTitle'); }, async clickCreateFirstConnectorButton() { - const createBtn = await find.byCssSelector('[data-test-subj="createFirstActionButton"]'); + const createBtn = await testSubjects.find('createFirstActionButton'); const createBtnIsVisible = await createBtn.isDisplayed(); if (createBtnIsVisible) { await createBtn.click(); } }, async clickCreateConnectorButton() { - const createBtn = await find.byCssSelector('[data-test-subj="createActionButton"]'); + const createBtn = await testSubjects.find('createActionButton'); const createBtnIsVisible = await createBtn.isDisplayed(); if (createBtnIsVisible) { await createBtn.click(); @@ -102,6 +102,23 @@ export function TriggersActionsPageProvider({ getService }: FtrProviderContext) }; }); }, + async isAlertsListDisplayed() { + const table = await find.byCssSelector('[data-test-subj="alertsList"] table'); + return table.isDisplayed(); + }, + async isAnEmptyAlertsListDisplayed() { + await retry.try(async () => { + const table = await find.byCssSelector('[data-test-subj="alertsList"] table'); + const $ = await table.parseDomContent(); + const rows = $.findTestSubjects('alert-row').toArray(); + expect(rows.length).not.to.eql(0); + const emptyRow = await find.byCssSelector( + '[data-test-subj="alertsList"] table .euiTableRow' + ); + expect(await emptyRow.getVisibleText()).not.to.eql('No items found'); + }); + return true; + }, async clickOnAlertInAlertsList(name: string) { await this.searchAlerts(name); await find.clickDisplayedByCssSelector(`[data-test-subj="alertsList"] [title="${name}"]`); diff --git a/x-pack/typings/@elastic/eui/index.d.ts b/x-pack/typings/@elastic/eui/index.d.ts index ea7a81fa986ce..7306f1f1af138 100644 --- a/x-pack/typings/@elastic/eui/index.d.ts +++ b/x-pack/typings/@elastic/eui/index.d.ts @@ -6,10 +6,6 @@ // TODO: Remove once typescript definitions are in EUI -declare module '@elastic/eui' { - export const Query: any; -} - declare module '@elastic/eui/lib/services' { export const RIGHT_ALIGNMENT: any; } diff --git a/yarn.lock b/yarn.lock index b18bc67413cda..e2b8082877cd2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1880,12 +1880,11 @@ dependencies: "@elastic/apm-rum-core" "^4.7.0" -"@elastic/charts@^17.1.1": - version "17.1.1" - resolved "https://registry.yarnpkg.com/@elastic/charts/-/charts-17.1.1.tgz#28df3d1be445aa4951fac59dec0831760a1ea034" - integrity sha512-zI3ZHy51tqlsEenDbHFWlL6qbDMvrQXeuV+UFleILtVcfI0r4Lk7DtSbx4GQlHcBuVvvAk1MRdYKNGA0IYWP6w== +"@elastic/charts@^18.1.0": + version "18.1.0" + resolved "https://registry.yarnpkg.com/@elastic/charts/-/charts-18.1.0.tgz#ee98b3e7680239d79807c09f0ee6efa6c1afa84b" + integrity sha512-cUobkGiKHPKHNytxsO7sSJyH6fOcAsZvcxAfnJPBn143P2d5oEsjSJmJTqu0z/obCs2v476Xlg6POVGainUj1Q== dependencies: - "@types/d3-shape" "^1.3.1" classnames "^2.2.6" d3-array "^1.2.4" d3-collection "^1.0.7" @@ -1952,10 +1951,10 @@ tabbable "^1.1.0" uuid "^3.1.0" -"@elastic/eui@20.0.2": - version "20.0.2" - resolved "https://registry.yarnpkg.com/@elastic/eui/-/eui-20.0.2.tgz#c64b16fef15da6aa9e627d45cdd372f1fc676359" - integrity sha512-8TtazI7RO1zJH4Qkl6TZKvAxaFG9F8BEdwyGmbGhyvXOJbkvttRzoaEg9jSQpKr+z7w2vsjGNbza/fEAE41HOA== +"@elastic/eui@21.0.1": + version "21.0.1" + resolved "https://registry.yarnpkg.com/@elastic/eui/-/eui-21.0.1.tgz#7cf6846ed88032aebd72f75255298df2fbe26554" + integrity sha512-Hf8ZGRI265qpOKwnnqhZkaMQvali+Xg6FAaNZSskkpXvdLhwGtUGC4YU7HW2vb7svq6IpNUuz+5XWrMLLzVY9w== dependencies: "@types/chroma-js" "^1.4.3" "@types/enzyme" "^3.1.13" @@ -5037,14 +5036,7 @@ dependencies: "@types/react" "*" -"@types/react-dom@*": - version "16.9.4" - resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-16.9.4.tgz#0b58df09a60961dcb77f62d4f1832427513420df" - integrity sha512-fya9xteU/n90tda0s+FtN5Ym4tbgxpq/hb/Af24dvs6uYnYn+fspaxw5USlw0R8apDNwxsqumdRoCoKitckQqw== - dependencies: - "@types/react" "*" - -"@types/react-dom@^16.9.5": +"@types/react-dom@*", "@types/react-dom@^16.9.5": version "16.9.5" resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-16.9.5.tgz#5de610b04a35d07ffd8f44edad93a71032d9aaa7" integrity sha512-BX6RQ8s9D+2/gDhxrj8OW+YD4R+8hj7FEM/OJHGNR0KipE1h1mSsf39YeyC81qafkq+N3rU3h3RFbLSwE5VqUg== @@ -5159,9 +5151,9 @@ "@types/react" "*" "@types/react@*", "@types/react@^16.8.23", "@types/react@^16.9.19": - version "16.9.19" - resolved "https://registry.yarnpkg.com/@types/react/-/react-16.9.19.tgz#c842aa83ea490007d29938146ff2e4d9e4360c40" - integrity sha512-LJV97//H+zqKWMms0kvxaKYJDG05U2TtQB3chRLF8MPNs+MQh/H1aGlyDUxjaHvu08EAGerdX2z4LTBc7ns77A== + version "16.9.23" + resolved "https://registry.yarnpkg.com/@types/react/-/react-16.9.23.tgz#1a66c6d468ba11a8943ad958a8cb3e737568271c" + integrity sha512-SsGVT4E7L2wLN3tPYLiF20hmZTPGuzaayVunfgXzUn1x4uHVsKH6QDJQ/TdpHqwsTLd4CwrmQ2vOgxN7gE24gw== dependencies: "@types/prop-types" "*" csstype "^2.2.0"