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

[Lens] Implement deep linking and embedding #84416

Merged
merged 16 commits into from
Jan 12, 2021
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 5 additions & 0 deletions x-pack/examples/embedded_lens_example/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"@typescript-eslint/consistent-type-definitions": 0
}
}
5 changes: 5 additions & 0 deletions x-pack/examples/embedded_lens_example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Embedded Lens examples

To run this example plugin, use the command `yarn start --run-examples`.

TODO
15 changes: 15 additions & 0 deletions x-pack/examples/embedded_lens_example/kibana.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"id": "embeddedLensExample",
"version": "0.0.1",
"kibanaVersion": "kibana",
"configPath": ["embedded_lens_example"],
"server": false,
"ui": true,
"requiredPlugins": [
"lens",
"data",
"developerExamples"
Copy link
Member

Choose a reason for hiding this comment

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

Hey @flash1293! For this example plugin, can we add a dependency on features to illustrate that you'll need to grant access to the lens saved object type in order to properly embed when security is enabled?

I'm happy to help draft this change if you'd like help with it

Copy link
Contributor Author

@flash1293 flash1293 Dec 22, 2020

Choose a reason for hiding this comment

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

@legrego Happy to include this - but I'm not sure how it should look like.

This example is not working with saved objects directly, but it does link into the Lens editor. So I guess the right integration would be to check whether there there are at least visualize read permissions via ui capabilities and otherwise disable the button, right?

Copy link
Member

Choose a reason for hiding this comment

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

This example is not working with saved objects directly, but it does link into the Lens editor. So I guess the right integration would be to check whether there there are at least visualize read permissions via ui capabilities and otherwise disable the button, right?

Ah, so this doesn't allow you to view existing visualizations, or save new ones? If that's the case, then you shouldn't need any capabilities checks

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As discussed offline, I will introduce a third method on the contract which can be used by consumers to determine whether it's possible to link to Lens or not.

],
"optionalPlugins": [],
"requiredBundles": []
}
14 changes: 14 additions & 0 deletions x-pack/examples/embedded_lens_example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "embedded_lens_example",
"version": "1.0.0",
"main": "target/examples/embedded_lens_example",
"kibana": {
"version": "kibana",
"templateVersion": "1.0.0"
},
"license": "Apache-2.0",
"scripts": {
"kbn": "node ../../../scripts/kbn.js",
"build": "rm -rf './target' && ../../../node_modules/.bin/tsc"
}
}
146 changes: 146 additions & 0 deletions x-pack/examples/embedded_lens_example/public/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*
* 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, { useState } from 'react';
import {
EuiButton,
EuiPage,
EuiPageBody,
EuiPageContent,
EuiPageContentBody,
EuiPageHeader,
EuiPageHeaderSection,
EuiTitle,
} from '@elastic/eui';
import { CoreStart } from 'kibana/public';
import { LensProps } from '../../../plugins/lens/public';
import { StartDependencies } from './plugin';

function getLensAttributes(defaultIndex: string, color: string): LensProps['attributes'] {
return {
visualizationType: 'lnsXY',
title: '',
references: [
{
id: defaultIndex,
name: 'indexpattern-datasource-current-indexpattern',
type: 'index-pattern',
},
{
id: defaultIndex,
name: 'indexpattern-datasource-layer-layer1',
type: 'index-pattern',
},
],
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm a bit worried about the references parameter of our saved object. Seems easy for an app to provide the wrong information.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I thought about a builder function of some sort abstracting away these things, but didn't want to overdo it for the first experimental release.

Do you have something simple in mind we could add here? IMHO we can wait for consumers to see in which direction we should drive this API.

Copy link
Contributor

Choose a reason for hiding this comment

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

I was also expecting some kind of builder, but I agree that we should iterate on it. For now I'm assuming that users will copy+paste the JSON from a saved object.

state: {
datasourceStates: {
indexpattern: {
layers: {
layer1: {
columnOrder: ['col1', 'col2'],
columns: {
col2: {
dataType: 'number',
isBucketed: false,
label: 'Count of records',
operationType: 'count',
scale: 'ratio',
sourceField: 'Records',
},
col1: {
dataType: 'date',
isBucketed: true,
label: '@timestamp',
operationType: 'date_histogram',
params: { interval: 'auto' },
scale: 'interval',
sourceField: '@timestamp',
},
},
},
},
},
},
filters: [],
query: { language: 'kuery', query: '' },
visualization: {
axisTitlesVisibilitySettings: { x: true, yLeft: true, yRight: true },
fittingFunction: 'None',
gridlinesVisibilitySettings: { x: true, yLeft: true, yRight: true },
layers: [
{
accessors: ['col2'],
layerId: 'layer1',
seriesType: 'bar_stacked',
xAccessor: 'col1',
yConfig: [{ forAccessor: 'col2', color }],
},
],
legend: { isVisible: true, position: 'right' },
preferredSeriesType: 'bar_stacked',
tickLabelsVisibilitySettings: { x: true, yLeft: true, yRight: true },
valueLabels: 'hide',
},
},
};
}

export const App = (props: { core: CoreStart; plugins: StartDependencies }) => {
const [color, setColor] = useState('green');
const LensComponent = props.plugins.lens.EmbeddableComponent;
return (
<EuiPage>
<EuiPageBody style={{ maxWidth: 1200, margin: '0 auto' }}>
<EuiPageHeader>
<EuiPageHeaderSection>
<EuiTitle size="l">
<h1>Embedded Lens vis</h1>
</EuiTitle>
</EuiPageHeaderSection>
</EuiPageHeader>
<EuiPageContent>
<EuiPageContentBody style={{ maxWidth: 800, margin: '0 auto' }}>
<EuiButton
onClick={() => {
// eslint-disable-next-line no-bitwise
const newColor = '#' + ((Math.random() * 0xffffff) << 0).toString(16);
setColor(newColor);
}}
>
Change color
</EuiButton>
<EuiButton
onClick={() => {
props.plugins.lens.navigateToPrefilledEditor({
id: '',
timeRange: {
from: 'now-5d',
to: 'now',
},
attributes: getLensAttributes(props.core.uiSettings.get('defaultIndex'), color),
});
// eslint-disable-next-line no-bitwise
const newColor = '#' + ((Math.random() * 0xffffff) << 0).toString(16);
setColor(newColor);
}}
>
Edit
</EuiButton>
<LensComponent
id=""
height={500}
timeRange={{
from: 'now-5d',
to: 'now',
}}
attributes={getLensAttributes(props.core.uiSettings.get('defaultIndex'), color)}
/>
</EuiPageContentBody>
</EuiPageContent>
</EuiPageBody>
</EuiPage>
);
};
9 changes: 9 additions & 0 deletions x-pack/examples/embedded_lens_example/public/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;
* you may not use this file except in compliance with the Elastic License.
*/

import { EmbeddedLensExamplePlugin } from './plugin';

export const plugin = () => new EmbeddedLensExamplePlugin();
25 changes: 25 additions & 0 deletions x-pack/examples/embedded_lens_example/public/mount.tsx
Original file line number Diff line number Diff line change
@@ -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 * as React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { CoreSetup, AppMountParameters } from 'kibana/public';
import { StartDependencies } from './plugin';

export const mount = (coreSetup: CoreSetup<StartDependencies>) => async ({
element,
}: AppMountParameters) => {
const [core, plugins] = await coreSetup.getStartServices();
const { App } = await import('./app');

const deps = {
core,
plugins,
};
const reactElement = <App {...deps} />;
render(reactElement, element);
return () => unmountComponentAtNode(element);
};
52 changes: 52 additions & 0 deletions x-pack/examples/embedded_lens_example/public/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { Plugin, CoreSetup, AppNavLinkStatus } from '../../../../src/core/public';
import { DataPublicPluginStart } from '../../../../src/plugins/data/public';
import { LensPublicStart } from '../../../plugins/lens/public';
import { DeveloperExamplesSetup } from '../../../../examples/developer_examples/public';
import { mount } from './mount';

export interface SetupDependencies {
developerExamples: DeveloperExamplesSetup;
}

export interface StartDependencies {
data: DataPublicPluginStart;
lens: LensPublicStart;
}

export class EmbeddedLensExamplePlugin
implements Plugin<void, void, SetupDependencies, StartDependencies> {
public setup(core: CoreSetup<StartDependencies>, { developerExamples }: SetupDependencies) {
core.application.register({
id: 'embedded_lens_example',
title: 'Embedded Lens example',
navLinkStatus: AppNavLinkStatus.hidden,
mount: mount(core),
});

developerExamples.register({
appId: 'embedded_lens_example',
title: 'Embedded Lens',
description: 'Examples of how to use Lens in other apps.',
links: [
{
label: 'README',
href:
'https://github.com/elastic/kibana/tree/master/x-pack/examples/embedded_lens_example',
iconType: 'logoGithub',
size: 's',
target: '_blank',
},
],
});
}

public start() {}

public stop() {}
}
21 changes: 21 additions & 0 deletions x-pack/examples/embedded_lens_example/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./target",
"skipLibCheck": true
},
"include": [
"index.ts",
"public/**/*.ts",
"public/**/*.tsx",
"server/**/*.ts",
"../../typings/**/*"
],
"exclude": [],
"references": [
{ "path": "../../../src/core/tsconfig.json" },
{ "path": "../../../src/plugins/kibana_utils/tsconfig.json" },
{ "path": "../../../src/plugins/kibana_react/tsconfig.json" },
{ "path": "../../../src/plugins/share/tsconfig.json" }
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* 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, { useRef, MutableRefObject, useEffect } from 'react';
import { RenderMode } from 'src/plugins/expressions';
import { PaletteOutput } from 'src/plugins/charts/public';
import { TimeRange } from 'src/plugins/data/public';
import { LensEmbeddableDeps, LensEmbeddableInput } from './embeddable';
import { Embeddable } from './embeddable';
import { Document } from '../../persistence';
import { IndexPatternPersistedState } from '../../indexpattern_datasource/types';
import { XYState } from '../../xy_visualization/types';
import { PieVisualizationState } from '../../pie_visualization/types';
import { DatatableVisualizationState } from '../../datatable_visualization/visualization';
import { State as MetricState } from '../../metric_visualization/types';

type LensAttributes<TVisType, TVisState> = Omit<
Document,
'savedObjectId' | 'type' | 'state' | 'visualizationType'
> & {
visualizationType: TVisType;
state: Omit<Document['state'], 'datasourceStates' | 'visualization'> & {
datasourceStates: {
indexpattern: IndexPatternPersistedState;
};
visualization: TVisState;
};
};

export type LensProps = Omit<LensEmbeddableInput, 'attributes'> & {
palette?: PaletteOutput;
renderMode?: RenderMode;
timeRange?: TimeRange;
height: number;
attributes:
| LensAttributes<'lnsXY', XYState>
| LensAttributes<'lnsPie', PieVisualizationState>
| LensAttributes<'lnsDatatable', DatatableVisualizationState>
| LensAttributes<'lnsMetric', MetricState>;
};

function LensComponent({
props: { timeRange, height, ...props },
deps,
}: {
props: LensProps;
deps: LensEmbeddableDeps;
}) {
const elementRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
const embeddableRef: MutableRefObject<Embeddable | null> = useRef(null);

useEffect(() => {
(async () => {
if (elementRef.current && embeddableRef.current) {
if (timeRange) {
embeddableRef.current.onContainerStateChanged({ ...props, timeRange });
}
await embeddableRef.current.initializeSavedVis(props);
embeddableRef.current.render(elementRef.current);
}
})();
// TODO do not re-render too often
}, [props, timeRange]);

return (
<div
style={{ height }}
ref={(newElement) => {
if (newElement) {
if (!embeddableRef.current) {
embeddableRef.current = new Embeddable(deps, props);
}
if (timeRange) {
embeddableRef.current.onContainerStateChanged({ ...props, timeRange });
}
if (elementRef.current !== newElement) {
embeddableRef.current!.render(newElement);
}
elementRef.current = newElement;
}
}}
/>
);
}

// eslint-disable-next-line import/no-default-export
export { LensComponent as default };
Loading