UNPKG

@grafana/ui

Version:
87 lines (84 loc) 2.57 kB
import { jsxs, Fragment, jsx } from 'react/jsx-runtime'; import { cx, css } from '@emotion/css'; import { useState, useCallback } from 'react'; import { v4 } from 'uuid'; import { selectors } from '@grafana/e2e-selectors'; import { t } from '@grafana/i18n'; import { useStyles2 } from '../../themes/ThemeContext.mjs'; import { getFocusStyles } from '../../themes/mixins.mjs'; import { trimFileName } from '../../utils/file.mjs'; import { getButtonStyles } from '../Button/Button.mjs'; import { Icon } from '../Icon/Icon.mjs'; const FileUpload = ({ onFileUpload, className, children = "Upload file", accept = "*", size = "md", showFileName }) => { const style = useStyles2(getStyles(size)); const [fileName, setFileName] = useState(""); const id = v4(); const onChange = useCallback( (event) => { var _a, _b, _c; const file = (_b = (_a = event.currentTarget) == null ? void 0 : _a.files) == null ? void 0 : _b[0]; if (file) { setFileName((_c = file.name) != null ? _c : ""); } onFileUpload(event); }, [onFileUpload] ); return /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx( "input", { type: "file", id, className: style.fileUpload, onChange, multiple: false, accept, "data-testid": selectors.components.FileUpload.inputField } ), /* @__PURE__ */ jsxs("label", { htmlFor: id, className: cx(style.labelWrapper, className), children: [ /* @__PURE__ */ jsx(Icon, { name: "upload", className: style.icon }), children ] }), showFileName && fileName && /* @__PURE__ */ jsx( "span", { "aria-label": t("grafana-ui.file-upload.file-name", "File name"), className: style.fileName, "data-testid": selectors.components.FileUpload.fileNameSpan, children: trimFileName(fileName) } ) ] }); }; const getStyles = (size) => (theme) => { const buttonStyles = getButtonStyles({ theme, variant: "primary", size, iconOnly: false }); const focusStyle = getFocusStyles(theme); return { fileUpload: css({ height: "0.1px", opacity: "0", overflow: "hidden", position: "absolute", width: "0.1px", zIndex: -1, "&:focus + label": focusStyle, "&:focus-visible + label": focusStyle }), labelWrapper: buttonStyles.button, icon: buttonStyles.icon, fileName: css({ marginLeft: theme.spacing(0.5) }) }; }; export { FileUpload }; //# sourceMappingURL=FileUpload.mjs.map