import { css } from '@emotion/css'; import { Dispatch, SetStateAction, useEffect, useState } from 'react'; import * as React from 'react'; import { usePrevious } from 'react-use'; import { DataSourceInstanceSettings, VariableSuggestion } from '@grafana/data'; import { DataSourcePicker } from '@grafana/runtime'; import { Button, DataLinkInput, InlineField, InlineSwitch, InlineFieldRow, InlineLabel, Input, useStyles2, } from '@grafana/ui'; import { DataLinkConfig } from '../types'; interface Props { value: DataLinkConfig; onChange: (value: DataLinkConfig) => void; onDelete: () => void; suggestions: VariableSuggestion[]; className?: string; } export const DataLink = (props: Props) => { const { value, onChange, onDelete, suggestions, className } = props; const styles = useStyles2(getStyles); const [showInternalLink, setShowInternalLink] = useInternalLink(value.datasourceUid); const handleChange = (field: keyof typeof value) => (event: React.ChangeEvent) => { onChange({ ...value, [field]: event.currentTarget.value, }); }; return (
{showInternalLink ? 'Query' : 'URL'} onChange({ ...value, url: newValue, }) } suggestions={suggestions} />
{ if (showInternalLink) { onChange({ ...value, datasourceUid: undefined, }); } setShowInternalLink(!showInternalLink); }} /> {showInternalLink && ( { onChange({ ...value, datasourceUid: ds.uid, }); }} current={value.datasourceUid} /> )}
); }; function useInternalLink(datasourceUid?: string): [boolean, Dispatch>] { const [showInternalLink, setShowInternalLink] = useState(!!datasourceUid); const previousUid = usePrevious(datasourceUid); // Force internal link visibility change if uid changed outside of this component. useEffect(() => { if (!previousUid && datasourceUid && !showInternalLink) { setShowInternalLink(true); } if (previousUid && !datasourceUid && showInternalLink) { setShowInternalLink(false); } }, [previousUid, datasourceUid, showInternalLink]); return [showInternalLink, setShowInternalLink]; } const getStyles = () => ({ firstRow: css({ display: 'flex', }), nameField: css({ flex: 2, }), regexField: css({ flex: 3, }), row: css({ display: 'flex', alignItems: 'baseline', }), urlField: css({ display: 'flex', flex: 1, }), urlDisplayLabelField: css({ flex: 1, }), });