import { css } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { usePrevious } from 'react-use'; import { VariableSuggestion } from '@grafana/data'; import { DataSourcePicker } from '@grafana/runtime'; import { Button, DataLinkInput, stylesFactory, LegacyForms } from '@grafana/ui'; import { DerivedFieldConfig } from '../types'; const { Switch, FormField } = LegacyForms; const getStyles = stylesFactory(() => ({ row: css` display: flex; align-items: baseline; `, nameField: css` flex: 2; `, regexField: css` flex: 3; `, urlField: css` flex: 1; `, urlDisplayLabelField: css` flex: 1; `, })); type Props = { value: DerivedFieldConfig; onChange: (value: DerivedFieldConfig) => void; onDelete: () => void; suggestions: VariableSuggestion[]; className?: string; }; export const DerivedField = (props: Props) => { const { value, onChange, onDelete, suggestions, className } = props; const styles = getStyles(); const [showInternalLink, setShowInternalLink] = useState(!!value.datasourceUid); const previousUid = usePrevious(value.datasourceUid); // Force internal link visibility change if uid changed outside of this component. useEffect(() => { if (!previousUid && value.datasourceUid && !showInternalLink) { setShowInternalLink(true); } if (previousUid && !value.datasourceUid && showInternalLink) { setShowInternalLink(false); } }, [previousUid, value.datasourceUid, showInternalLink]); const handleChange = (field: keyof typeof value) => (event: React.ChangeEvent) => { onChange({ ...value, [field]: event.currentTarget.value, }); }; return (
onChange({ ...value, url: newValue, }) } suggestions={suggestions} /> } className={styles.urlField} />
{ if (showInternalLink) { onChange({ ...value, datasourceUid: undefined, }); } setShowInternalLink(!showInternalLink); }} /> {showInternalLink && ( onChange({ ...value, datasourceUid: ds.uid, }) } current={value.datasourceUid} /> )}
); };