UNPKG

@grafana/ui

Version:
89 lines (86 loc) 2.38 kB
import { jsx } from 'react/jsx-runtime'; import { cx, css } from '@emotion/css'; import { useRef, useState } from 'react'; import { useClickAway } from 'react-use'; import { useStyles2 } from '../../themes/ThemeContext.mjs'; import { measureText } from '../../utils/measureText.mjs'; import { InlineLabel } from '../Forms/InlineLabel.mjs'; import { getSegmentStyles } from './styles.mjs'; import { useExpandableLabel } from './useExpandableLabel.mjs'; "use strict"; const FONT_SIZE = 14; function SegmentInput({ value: initialValue, onChange, Component, className, placeholder, inputPlaceholder, disabled, autofocus = false, onExpandedChange, ...rest }) { const ref = useRef(null); const [value, setValue] = useState(initialValue); const [inputWidth, setInputWidth] = useState(measureText((initialValue || "").toString(), FONT_SIZE).width); const [Label, , expanded, setExpanded] = useExpandableLabel(autofocus, onExpandedChange); const styles = useStyles2(getSegmentStyles); useClickAway(ref, () => { setExpanded(false); onChange(value); }); if (!expanded) { return /* @__PURE__ */ jsx( Label, { disabled, Component: Component || /* @__PURE__ */ jsx( InlineLabel, { className: cx( styles.segment, { [styles.queryPlaceholder]: placeholder !== void 0 && !value, [styles.disabled]: disabled }, className ), children: initialValue || placeholder } ) } ); } const inputWidthStyle = css({ width: `${Math.max(inputWidth + 20, 32)}px` }); return /* @__PURE__ */ jsx( "input", { ...rest, ref, autoFocus: true, className: cx(`gf-form gf-form-input`, inputWidthStyle), value, placeholder: inputPlaceholder, onChange: (item) => { const { width } = measureText(item.target.value, FONT_SIZE); setInputWidth(width); setValue(item.target.value); }, onBlur: () => { setExpanded(false); onChange(value); }, onKeyDown: (e) => { if ([13, 27].includes(e.keyCode)) { setExpanded(false); onChange(value); } } } ); } export { SegmentInput }; //# sourceMappingURL=SegmentInput.mjs.map