UNPKG

@blocklet/payment-react

Version:

Reusable react components for payment kit v2

113 lines (112 loc) 3.31 kB
import { Fragment, jsx, jsxs } from "react/jsx-runtime"; import { useImperativeHandle, useRef } from "react"; import { Box, InputAdornment, TextField, Typography, Stack, useMediaQuery, useTheme } from "@mui/material"; import get from "lodash/get"; import { Controller, useFormContext } from "react-hook-form"; import FormLabel from "./label.js"; function FormInputError({ error }) { return /* @__PURE__ */ jsx(InputAdornment, { position: "end", children: /* @__PURE__ */ jsx(Typography, { component: "span", color: "error", children: error }) }); } export default function FormInput({ ref = void 0, name, label = "", placeholder = "", rules = {}, errorPosition = "bottom", wrapperStyle = {}, inputProps = {}, required = false, tooltip = "", description = "", layout = "vertical", slotProps, ...rest }) { const { control, formState } = useFormContext(); const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down("sm")); const inputRef = useRef(null); useImperativeHandle(ref, () => { return inputRef.current; }); const error = get(formState.errors, name)?.message; const isHorizontal = layout === "horizontal" && !isMobile; const mergedSlotProps = { htmlInput: { ...inputProps, ...slotProps?.htmlInput }, input: Object.assign( rest.InputProps || {}, slotProps?.input || {}, errorPosition === "right" && error ? { endAdornment: /* @__PURE__ */ jsx(FormInputError, { error }) } : {} ) }; const renderLabel = () => { if (!label) return null; return /* @__PURE__ */ jsx( FormLabel, { required, tooltip, description, boxSx: isHorizontal ? { width: "fit-content", whiteSpace: "nowrap", minWidth: "fit-content" } : void 0, children: label } ); }; return /* @__PURE__ */ jsx( Controller, { name, control, rules, render: ({ field }) => /* @__PURE__ */ jsx(Box, { sx: { width: "100%", ...wrapperStyle }, children: isHorizontal ? /* @__PURE__ */ jsxs( Stack, { direction: "row", spacing: 2, sx: { alignItems: "center", justifyContent: "space-between" }, children: [ renderLabel(), /* @__PURE__ */ jsx( TextField, { fullWidth: false, error: !!error, helperText: errorPosition === "bottom" && error ? error : "", placeholder, size: "small", ...field, ...rest, inputRef, slotProps: mergedSlotProps, sx: { flex: 1, ...rest.sx } } ) ] } ) : /* @__PURE__ */ jsxs(Fragment, { children: [ renderLabel(), /* @__PURE__ */ jsx( TextField, { fullWidth: true, error: !!error, helperText: errorPosition === "bottom" && error ? error : "", placeholder, size: "small", ...field, ...rest, inputRef, slotProps: mergedSlotProps } ) ] }) }) } ); }