UNPKG

@etsoo/materialui

Version:

TypeScript Material-UI Implementation

65 lines (64 loc) 2.63 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import ArrowRightAltIcon from "@mui/icons-material/ArrowRightAlt"; import { useDimensions } from "@etsoo/react"; import React from "react"; import { DateUtils, DomUtils } from "@etsoo/shared"; import { InputField } from "./InputField"; import InputAdornment from "@mui/material/InputAdornment"; import Input from "@mui/material/Input"; /** * TwoField Input * @param props Props * @returns Component */ export function TwoFieldInput(props) { // Destruct const { name, inputProps, type = inputProps?.inputMode, values, onValuesChange, onChange, onInput, ...rest } = props; // Local values const localValues = values == null ? [null, null] : Array.isArray(values) ? values : [values, null]; // Ref const valueRef = React.useRef(localValues); // Watch container const { dimensions } = useDimensions(1, (target, rect) => { const width = (rect.width - 64) / 2; const inputs = target.querySelectorAll("input"); inputs[0].style.width = `${width}px`; inputs[1].parentElement.style.width = `${width}px`; }, 0); // Handle change const handleChange = (event) => { const value = DomUtils.getInputValue(event.target); const index = event.target.name.endsWith("-start") ? 0 : 1; valueRef.current[index] = value; if (onValuesChange) { if (onValuesChange(valueRef.current) === false) return; } if (onChange) onChange(event); }; const formatValue = (v, type) => { if (v == null) return ""; if (typeof v === "number") return v; if (type === "date" || type === "datetime-local") return DateUtils.formatForInput(v, type); return v; }; React.useEffect(() => { valueRef.current = localValues; }, [localValues]); // Layout return (_jsx(InputField, { name: `${name}-start`, type: type, value: formatValue(localValues[0], type), ref: dimensions[0][0], inputProps: inputProps, InputProps: { endAdornment: (_jsxs(InputAdornment, { position: "end", sx: { display: "flex", alignItems: "center", gap: 1 }, children: [_jsx(ArrowRightAltIcon, {}), _jsx(Input, { type: type, name: `${name}-end`, value: formatValue(localValues[1], type), disableUnderline: true, onInput: onInput, onChange: handleChange, inputProps: inputProps })] })) }, onInput: onInput, onChange: handleChange, ...rest })); }