Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[Canvas] Adds expression registration example plugin #101611

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 37 additions & 28 deletions dev_docs/tutorials/expressions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ tags: ['kibana', 'onboarding', 'dev', 'architecture']

## Expressions service

Expression service exposes a registry of reusable functions primary used for fetching and transposing data and a registry of renderer functions that can render data into a DOM element.
Adding functions is easy and so is reusing them. An expression is a chain of functions with provided arguments, which given a single input translates to a single output.
Expression service exposes a registry of reusable functions primary used for fetching and transposing data and a registry of renderer functions that can render data into a DOM element.
Adding functions is easy and so is reusing them. An expression is a chain of functions with provided arguments, which given a single input translates to a single output.
Each expression is representable by a human friendly string which a user can type.

### creating expressions
Expand All @@ -19,13 +19,12 @@ Here is a very simple expression string:

essql 'select column1, column2 from myindex' | mapColumn name=column3 fn='{ column1 + 3 }' | table


It consists of 3 functions:

- essql which runs given sql query against elasticsearch and returns the results
- `mapColumn`, which computes a new column from existing ones;
- `table`, which prepares the data for rendering in a tabular format.
- essql which runs given sql query against elasticsearch and returns the results
- `mapColumn`, which computes a new column from existing ones;
- `table`, which prepares the data for rendering in a tabular format.

The same expression could also be constructed in the code:

```ts
Expand Down Expand Up @@ -54,21 +53,23 @@ const result = await executionContract.getData();
```

<DocCallOut title="Server Side Search">
Check the full spec of execute function [here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.md)
Check the full spec of execute function
[here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.execution.md)
</DocCallOut>

In addition, on the browser side, there are two additional ways to run expressions and render the results.

#### React expression renderer component

This is the easiest way to get expressions rendered inside your application.
This is the easiest way to get expressions rendered inside your application.

```ts
<ReactExpressionRenderer expression={expression} />
```

<DocCallOut title="Server Side Search">
Check the full spec of ReactExpressionRenderer component props [here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.md)
Check the full spec of ReactExpressionRenderer component props
[here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.reactexpressionrendererprops.md)
</DocCallOut>

#### Expression loader
Expand All @@ -80,7 +81,8 @@ const handler = loader(domElement, expression, params);
```

<DocCallOut title="Server Side Search">
Check the full spec of expression loader params [here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.md)
Check the full spec of expression loader params
[here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.iexpressionloaderparams.md)
</DocCallOut>

### Creating new expression functions
Expand All @@ -89,21 +91,22 @@ Creating a new expression function is easy, just call `registerFunction` method

```ts
const functionDefinition = {
name: 'clog',
args: {},
help: 'Outputs the context to the console',
fn: (input: unknown) => {
// eslint-disable-next-line no-console
console.log(input);
return input;
},
name: 'clog',
args: {},
help: 'Outputs the context to the console',
fn: (input: unknown) => {
// eslint-disable-next-line no-console
console.log(input);
return input;
},
};

expressions.registerFunction(functionDefinition);
```

<DocCallOut title="Server Side Search">
Check the full interface of ExpressionFuntionDefinition [here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionfunctiondefinition.md)
Check the full interface of ExpressionFuntionDefinition
[here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionfunctiondefinition.md)
</DocCallOut>

### Creating new expression renderers
Expand All @@ -112,18 +115,24 @@ Adding new renderers is just as easy as adding functions:

```ts
const rendererDefinition = {
name: 'debug',
help: 'Outputs the context to the dom element',
render: (domElement, input, handlers) => {
// eslint-disable-next-line no-console
domElement.innerText = JSON.strinfigy(input);
handlers.done();
},
name: 'debug',
help: 'Outputs the context to the dom element',
render: (domElement, input, handlers) => {
// eslint-disable-next-line no-console
domElement.innerText = JSON.strinfigy(input);
handlers.done();
},
};

expressions.registerRenderer(rendererDefinition);
```

<DocCallOut title="Server Side Search">
Check the full interface of ExpressionRendererDefinition [here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionrenderdefinition.md)
Make sure you call `handlers.done` once the rendering should be shown. The React component and the
Loader depend on this method being called to switch out of the loading state
</DocCallOut>

<DocCallOut title="Server Side Search">
Check the full interface of ExpressionRendererDefinition
[here](https://github.com/elastic/kibana/blob/master/docs/development/plugins/expressions/public/kibana-plugin-plugins-expressions-public.expressionrenderdefinition.md)
</DocCallOut>
31 changes: 31 additions & 0 deletions examples/expression_registration_example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Expression Registration Example

This plugin is intended to serve as an example of how to create a plugin to register functions and renderers to the expressions plugin. It registers a `demofunction` function and a `demo` type renderer to the `expressions` plugin and displays a simple expression that makes use of them. This should be a good starting point for anyone building a new plugin to add functionality to the `expressions` plugin.

Plugins that are made exclusively to add to expressions should be prefixed with `expression`. Examples `expression_shape`, `expression_reveal_image`


## Porting from Canvas

When porting existing functions and renderers from Canvas, here are some key things to watch out for

#### Prefer React Components
Some of the existing Canvas renderers do a lot of manual DOM manipulation. We prefer all of that logic be encapsulated in a React component, which is much easier to test via Jest and Storybook

#### ESLint
Some of the Canvas functions and renderers were built outside of our existing eslint config, so expect there to be ESLint errors (filenames not snake cased, etc) as they are moved over. These should be relatively simple to fix.

#### Handlers
Canvas has extended the IInterpreterRenderHandlers interface to add additional handlers that we pass to our renderes. This is going to prevent reuse across applications. Any use of these extended methods should be changed to use the `event` method that is a part of IInterpreterRenderHandlers.

```
// Non-standard handler
handlers.resize({height: 100, width: 150});

// Should become
handlers.event('resize', {height: 100, width: 150});
Copy link
Member

Choose a reason for hiding this comment

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

maybe it makes sense to provide more details here or link to this issue: #74644

for example the resize most likely shouldn't be an event, but should be handled internally ... unless we want to let the outside world know that a resize happened. but in most cases we only want to do some rerendering so that can be done completely internally.

some others are much simpler, for example onDestroy needs to be replaced with destroy, no need for event

```




16 changes: 16 additions & 0 deletions examples/expression_registration_example/common/i18n/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { i18n } from '@kbn/i18n';

export const RendererStrings = {
getLabelText: () =>
i18n.translate('expressionRegistrationExample.labelMessage', {
defaultMessage: 'Here is the input text',
}),
};
9 changes: 9 additions & 0 deletions examples/expression_registration_example/common/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

export * from './i18n';
11 changes: 11 additions & 0 deletions examples/expression_registration_example/kibana.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"id": "vistypeDemo",
"version": "0.0.1",
"kibanaVersion": "kibana",
"server": false,
"ui": true,
"requiredPlugins": ["expressions", "developerExamples"],
"optionalPlugins": [],
"extraPublicDirs": [],
"requiredBundles": []
}
37 changes: 37 additions & 0 deletions examples/expression_registration_example/public/demo_renderer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import React, { FC } from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import type { ExpressionRenderDefinition } from '../../../src/plugins/expressions/public';
import { RendererStrings } from '../common';
import { DemoRenderValue } from './expression_functions/demo_function';

interface Props {
text: string;
color: string;
}

export const DemoComponent: FC<Props> = ({ text, color }) => (
<div style={{ color }}>
{RendererStrings.getLabelText()}: {text}
</div>
);

export const DemoRenderer: ExpressionRenderDefinition<DemoRenderValue> = {
name: 'demo',
displayName: 'demo renderer',
reuseDomNode: true,
render: async (domNode, { text, color }, handlers) => {
handlers.onDestroy(() => unmountComponentAtNode(domNode));

render(<DemoComponent text={text} color={color} />, domNode);

handlers.done();
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import type {
ExpressionFunctionDefinition,
Render,
} from '../../../../src/plugins/expressions/public';

export interface Arguments {
inputText: string;
inputColor?: string;
}

export interface DemoRenderValue {
text: string;
color: string;
}

export const demoFunction = (): ExpressionFunctionDefinition<
'demofunction',
null,
Arguments,
Render<DemoRenderValue>
> => ({
name: 'demofunction',
help: 'This is a demo function',
type: 'render',
args: {
inputText: {
types: ['string'],
help: 'This is the text to be displayed',
required: true,
},
inputColor: {
types: ['string'],
help: 'This is the color the text should be',
required: false,
},
},
fn: (input, args) => {
return {
type: 'render',
as: 'demo',
value: {
text: args.inputText,
color: args.inputColor || 'inherit',
},
};
},
});
11 changes: 11 additions & 0 deletions examples/expression_registration_example/public/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { VisTypeDemoPlugin } from './plugin';

export const plugin = () => new VisTypeDemoPlugin();
Loading