/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ import { EuiCodeBlock, EuiFormLabel, EuiSpacer, EuiCodeEditor, EuiPanel, EuiForm, EuiFormRow, EuiFieldText, EuiTitle, EuiProgress, EuiCallOut, } from '@elastic/eui'; import { i18n } from '@osd/i18n'; import { FormattedMessage } from '@osd/i18n/react'; import React, { useEffect, useMemo, useState } from 'react'; import { ReactExpressionRenderer } from '../../../../src/plugins/expressions/public'; import { useOpenSearchDashboards } from '../../../../src/plugins/opensearch_dashboards_react/public'; import { PersistedState } from '../../../../src/plugins/visualizations/public'; import { ExpressionsExampleServices } from '../types'; interface Props { title: string; defaultInput?: string; defaultExpression: string; renderType?: boolean; } export function PlaygroundSection({ title, defaultExpression, defaultInput = '10', renderType = false, }: Props) { const { services: { expressions }, } = useOpenSearchDashboards(); const [loading, setLoading] = useState(false); const [input, setInput] = useState(defaultInput); const [expression, setExpression] = useState(defaultExpression); const [result, setResult] = useState(''); // Visualizations require the uiState to persist even when the expression changes const uiState = useMemo(() => new PersistedState(), []); useEffect(() => { let isMounted = true; if (renderType) return; try { setLoading(true); const execution = expressions.execute(expression, input); execution.getData().then((data: any) => { if (!isMounted) return; const value = data?.type === 'error' ? `Error: ${data?.error?.message ?? 'Something went wrong'}` : data; const parsedValue = typeof value === 'object' ? JSON.stringify(value, null, 2) : value; setLoading(false); setResult(parsedValue); }); } catch (error) { setLoading(false); setResult(String(error)); } return () => { isMounted = false; }; }, [expressions, input, expression, renderType]); return ( <>

{title}

{/* Rendered the input field only for non renderable expressions */} {!renderType && ( <> setInput(e.target.value)} /> )} setExpression(value)} /> {renderType ? ( <> ) : ( {loading && } {result} )}
); }