/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ import React, { forwardRef, useCallback, useImperativeHandle, useMemo, useRef } from "react"; import { EuiAccordion, EuiAccordionProps, EuiSpacer, EuiFormRowProps } from "@elastic/eui"; import SwitchableEditor, { SwitchableEditorProps, ISwitchableEditorRef } from "../SwitchableEditor"; import CustomFormRow, { CustomFormRowProps } from "../CustomFormRow"; import "./index.scss"; export interface IAdvancedSettingsProps { rowProps?: Omit; accordionProps?: EuiAccordionProps; value?: T; onChange?: (totalValue: T) => void; renderProps?: ( options: Pick>, "value" | "onChange"> & { ref: React.Ref } ) => React.ReactChild; editorProps?: Partial & { ref?: React.Ref; formatValue?: (val: Record) => Record; }; } export interface IAdvancedSettingsRef { validate: () => Promise; setValue: (val: any) => void; } function AdvancedSettings(props: IAdvancedSettingsProps, ref: React.Ref) { const { value, renderProps, editorProps } = props; const propsRef = useRef>(props); const editorRef = useRef(null); propsRef.current = props; const onChangeInRenderProps = useCallback( (val: string) => { let parsedValue = JSON.parse(val); if (editorProps?.formatValue) { parsedValue = editorProps.formatValue(parsedValue); } editorRef.current?.setValue(JSON.stringify(parsedValue, null, 2)); propsRef.current.onChange && propsRef.current.onChange(parsedValue); }, [props.onChange] ); const accordionId = useMemo(() => { return props.accordionProps?.id || `${Date.now()}-${Math.floor(Math.random() * 100)}`; }, [props.accordionProps?.id]); useImperativeHandle(ref, () => ({ validate: () => { if (editorRef.current) { return editorRef.current.validate(); } return Promise.resolve(""); }, setValue: (val) => { editorRef.current?.setValue(JSON.stringify(val || {}, null, 2)); }, })); return ( {renderProps ? ( (renderProps({ value: propsRef.current.value || ({} as T), onChange: (val) => { if (propsRef.current?.onChange) { propsRef.current?.onChange(val); } }, ref: editorRef, }) as any) ) : ( )} ); } export default forwardRef(AdvancedSettings) as ( props: IAdvancedSettingsProps & { ref?: React.Ref } ) => ReturnType;