Skip to content

Commit

Permalink
[D&D] Enable basic embeddable panels
Browse files Browse the repository at this point in the history
- add embeddable, embeddable component, embeddable factory
- update `toExpression` to allow passing services
- register embeddable factory in plugin setup

fixes #1908
  • Loading branch information
joshuarrrr committed Jul 18, 2022
1 parent fbce578 commit f327247
Show file tree
Hide file tree
Showing 9 changed files with 436 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/plugins/saved_objects_management/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ You'll notice that when clicking on the "Inspect" button from the saved objects

### Registering

Ideally, we'd allow plugins to self-register their `savedObjectLoader` and (declare a dependency on this plugin). However, as currently implemented, any plugins that want this plugin to handle their inpect routes need to be added as optional dependencies and registered here.
Ideally, we'd allow plugins to self-register their `savedObjectLoader` and (declare a dependency on this plugin). However, as currently implemented, any plugins that want this plugin to handle their inspect routes need to be added as optional dependencies and registered here.

1. Add your plugin to the `optionalPlugins` array in `./opensearch_dashboards.json`
2. Update the `StartDependencies` interface of this plugin to include the public plugin start type
Expand Down
7 changes: 7 additions & 0 deletions src/plugins/wizard/public/embeddable/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

export * from './wizard_embeddable';
export * from './wizard_embeddable_factory';
133 changes: 133 additions & 0 deletions src/plugins/wizard/public/embeddable/wizard_component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import React, { useEffect, useState } from 'react';
import {
EuiFlexItem,
EuiFlexGroup,
EuiText,
EuiAvatar,
EuiFlexGrid,
EuiCodeBlock,
} from '@elastic/eui';

import { withEmbeddableSubscription } from '../../../embeddable/public';
import { WizardEmbeddable, WizardInput, WizardOutput } from './wizard_embeddable';
import { validateSchemaState } from '../application/utils/validate_schema_state';

interface Props {
embeddable: WizardEmbeddable;
input: WizardInput;
output: WizardOutput;
}

function wrapSearchTerms(task?: string, search?: string) {
if (!search) return task;
if (!task) return task;
const parts = task.split(new RegExp(`(${search})`, 'g'));
return parts.map((part, i) =>
part === search ? (
<span key={i} style={{ backgroundColor: 'yellow' }}>
{part}
</span>
) : (
part
)
);
}

function WizardEmbeddableComponentInner({
embeddable,
input: { search },
output: { savedAttributes },
}: Props) {
const { ReactExpressionRenderer, toasts, types, indexPatterns, aggs } = embeddable;
const [expression, setExpression] = useState<string>();
const { title, description, visualizationState, styleState } = savedAttributes || {};

useEffect(() => {
const { visualizationState: visualization, styleState: style } = savedAttributes || {};
if (savedAttributes === undefined || visualization === undefined || style === undefined) {
return;
}

const rootState = {
visualization: JSON.parse(visualization),
style: JSON.parse(style),
};

const visualizationType = types.get(rootState.visualization?.activeVisualization?.name ?? '');
if (!visualizationType) {
throw new Error(`Invalid visualization type ${visualizationType}`);
}
const { toExpression, ui } = visualizationType;

async function loadExpression() {
const schemas = ui.containerConfig.data.schemas;
const [valid, errorMsg] = validateSchemaState(schemas, rootState);

if (!valid) {
if (errorMsg) {
toasts.addWarning(errorMsg);
}
setExpression(undefined);
return;
}
const exp = await toExpression(rootState, indexPatterns, aggs);
setExpression(exp);
}

if (savedAttributes !== undefined) {
loadExpression();
}
}, [aggs, indexPatterns, savedAttributes, toasts, types]);

// TODO: add correct loading and error states, remove debugging mode
return (
<>
{expression ? (
<EuiFlexItem>
<ReactExpressionRenderer expression={expression} />
</EuiFlexItem>
) : (
<EuiFlexGroup>
<EuiFlexItem grow={false}>
<EuiAvatar name={title || description || ''} size="l" />
</EuiFlexItem>
<EuiFlexItem>
<EuiFlexGrid columns={1}>
<EuiFlexItem>
<EuiText data-test-subj="wizardEmbeddableTitle">
<h3>{wrapSearchTerms(title || '', search)}</h3>
</EuiText>
</EuiFlexItem>
<EuiFlexItem>
<EuiText data-test-subj="wizardEmbeddableDescription">
{wrapSearchTerms(description, search)}
</EuiText>
</EuiFlexItem>
<EuiFlexItem>
<EuiCodeBlock data-test-subj="wizardEmbeddableDescription">
{wrapSearchTerms(visualizationState, search)}
</EuiCodeBlock>
</EuiFlexItem>
<EuiFlexItem>
<EuiCodeBlock data-test-subj="wizardEmbeddableDescription">
{wrapSearchTerms(styleState, search)}
</EuiCodeBlock>
</EuiFlexItem>
</EuiFlexGrid>
</EuiFlexItem>
</EuiFlexGroup>
)}
</>
);
}

export const WizardEmbeddableComponent = withEmbeddableSubscription<
WizardInput,
WizardOutput,
WizardEmbeddable
>(WizardEmbeddableComponentInner);
160 changes: 160 additions & 0 deletions src/plugins/wizard/public/embeddable/wizard_embeddable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import React from 'react';
import ReactDOM from 'react-dom';
import { Subscription } from 'rxjs';

import { WizardSavedObjectAttributes } from '../../common';
import {
Embeddable,
EmbeddableOutput,
IContainer,
SavedObjectEmbeddableInput,
} from '../../../embeddable/public';
import { IToasts, SavedObjectsClientContract } from '../../../../core/public';
import { WizardEmbeddableComponent } from './wizard_component';
import { ReactExpressionRendererType } from '../../../expressions/public';
import { TypeServiceStart } from '../services/type_service';
import { DataPublicPluginStart } from '../../../data/public';

export const WIZARD_EMBEDDABLE = 'WIZARD_EMBEDDABLE';

// TODO: remove search, hasMatch or update as appropriate
export interface WizardInput extends SavedObjectEmbeddableInput {
/**
* Optional search string which will be used to highlight search terms as
* well as calculate `output.hasMatch`.
*/
search?: string;
}

export interface WizardOutput extends EmbeddableOutput {
/**
* Should be true if input.search is defined and the task or title contain
* search as a substring.
*/
hasMatch: boolean;
/**
* Will contain the saved object attributes of the Wizard Saved Object that matches
* `input.savedObjectId`. If the id is invalid, this may be undefined.
*/
savedAttributes?: WizardSavedObjectAttributes;
}

/**
* Returns whether any attributes contain the search string. If search is empty, true is returned. If
* there are no savedAttributes, false is returned.
* @param search - the search string
* @param savedAttributes - the saved object attributes for the saved object with id `input.savedObjectId`
*/
function getHasMatch(search?: string, savedAttributes?: WizardSavedObjectAttributes): boolean {
if (!search) return true;
if (!savedAttributes) return false;
return Boolean(
(savedAttributes.description && savedAttributes.description.match(search)) ||
(savedAttributes.title && savedAttributes.title.match(search))
);
}

export class WizardEmbeddable extends Embeddable<WizardInput, WizardOutput> {
public readonly type = WIZARD_EMBEDDABLE;
private subscription: Subscription;
private node?: HTMLElement;
private savedObjectsClient: SavedObjectsClientContract;
public ReactExpressionRenderer: ReactExpressionRendererType;
public toasts: IToasts;
public types: TypeServiceStart;
public indexPatterns: DataPublicPluginStart['indexPatterns'];
public aggs: DataPublicPluginStart['search']['aggs'];
private savedObjectId?: string;

constructor(
initialInput: WizardInput,
{
parent,
savedObjectsClient,
data,
ReactExpressionRenderer,
toasts,
types,
}: {
parent?: IContainer;
data: DataPublicPluginStart;
savedObjectsClient: SavedObjectsClientContract;
ReactExpressionRenderer: ReactExpressionRendererType;
toasts: IToasts;
types: TypeServiceStart;
}
) {
// TODO: can default title come from saved object?
super(initialInput, { defaultTitle: 'wizard', hasMatch: false }, parent);
this.savedObjectsClient = savedObjectsClient;
this.ReactExpressionRenderer = ReactExpressionRenderer;
this.toasts = toasts;
this.types = types;
this.indexPatterns = data.indexPatterns;
this.aggs = data.search.aggs;

this.subscription = this.getInput$().subscribe(async () => {
// There is a little more work today for this embeddable because it has
// more output it needs to update in response to input state changes.
let savedAttributes: WizardSavedObjectAttributes | undefined;

// Since this is an expensive task, we save a local copy of the previous
// savedObjectId locally and only retrieve the new saved object if the id
// actually changed.
if (this.savedObjectId !== this.input.savedObjectId) {
this.savedObjectId = this.input.savedObjectId;
const wizardSavedObject = await this.savedObjectsClient.get<WizardSavedObjectAttributes>(
'wizard',
this.input.savedObjectId
);
savedAttributes = wizardSavedObject?.attributes;
}

// The search string might have changed as well so we need to make sure we recalculate
// hasMatch.
this.updateOutput({
hasMatch: getHasMatch(this.input.search, savedAttributes),
savedAttributes,
title: savedAttributes?.title,
});
});
}

public render(node: HTMLElement) {
if (this.node) {
ReactDOM.unmountComponentAtNode(this.node);
}
this.node = node;
ReactDOM.render(<WizardEmbeddableComponent embeddable={this} />, node);
}

/**
* Lets re-sync our saved object to make sure it's up to date!
*/
public async reload() {
this.savedObjectId = this.input.savedObjectId;
const wizardSavedObject = await this.savedObjectsClient.get<WizardSavedObjectAttributes>(
'wizard',
this.input.savedObjectId
);
const savedAttributes = wizardSavedObject?.attributes;
this.updateOutput({
hasMatch: getHasMatch(this.input.search, savedAttributes),
savedAttributes,
title: wizardSavedObject?.attributes?.title,
});
}

public destroy() {
super.destroy();
this.subscription.unsubscribe();
if (this.node) {
ReactDOM.unmountComponentAtNode(this.node);
}
}
}
Loading

0 comments on commit f327247

Please sign in to comment.