|
| 1 | +/* |
| 2 | + * Copyright OpenSearch Contributors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +import React, { useCallback, useState } from 'react'; |
| 7 | +import { EuiForm, EuiFormRow, EuiButton, EuiFieldText } from '@elastic/eui'; |
| 8 | +import { i18n } from '@osd/i18n'; |
| 9 | +import { render, unmountComponentAtNode } from 'react-dom'; |
| 10 | +import { ExpressionRenderDefinition } from '../../../../../src/plugins/expressions/public'; |
| 11 | + |
| 12 | +export interface QuickFormRenderValue { |
| 13 | + label: string; |
| 14 | + buttonLabel: string; |
| 15 | +} |
| 16 | + |
| 17 | +export const quickFormRenderer: ExpressionRenderDefinition<QuickFormRenderValue> = { |
| 18 | + name: 'quick-form-renderer', |
| 19 | + displayName: i18n.translate('expressionsExample.form.render.help', { |
| 20 | + defaultMessage: 'Render a simple input form', |
| 21 | + }), |
| 22 | + reuseDomNode: true, |
| 23 | + render: (domNode, config, handlers) => { |
| 24 | + handlers.onDestroy(() => { |
| 25 | + unmountComponentAtNode(domNode); |
| 26 | + }); |
| 27 | + |
| 28 | + render( |
| 29 | + <QuickForm |
| 30 | + {...config} |
| 31 | + onSubmit={(value) => |
| 32 | + handlers.event({ |
| 33 | + data: value, |
| 34 | + }) |
| 35 | + } |
| 36 | + />, |
| 37 | + domNode, |
| 38 | + handlers.done |
| 39 | + ); |
| 40 | + }, |
| 41 | +}; |
| 42 | + |
| 43 | +interface QuickFormProps extends QuickFormRenderValue { |
| 44 | + onSubmit: Function; |
| 45 | +} |
| 46 | + |
| 47 | +const QuickForm = ({ onSubmit, buttonLabel, label }: QuickFormProps) => { |
| 48 | + const [value, setValue] = useState(''); |
| 49 | + const handleClick = useCallback(() => { |
| 50 | + onSubmit(value); |
| 51 | + }, [onSubmit, value]); |
| 52 | + |
| 53 | + return ( |
| 54 | + <EuiForm> |
| 55 | + <EuiFormRow label={label}> |
| 56 | + <EuiFieldText value={value} onChange={(e) => setValue(e.target.value)} /> |
| 57 | + </EuiFormRow> |
| 58 | + <EuiButton onClick={handleClick}>{buttonLabel}</EuiButton> |
| 59 | + </EuiForm> |
| 60 | + ); |
| 61 | +}; |
0 commit comments