Initial support for units

This commit is contained in:
Daniel Dunn
2025-04-02 19:42:13 -06:00
parent 42d84dbfa0
commit 6b27595a89
2 changed files with 45 additions and 24 deletions

View File

@@ -1,11 +1,14 @@
import React, { useState, useEffect } from 'react';
import { TextField, Grid } from '@mui/material';
import { Grid, TextField } from '@mui/material';
import TextFieldWithDesc from '@components/options/TextFieldWithDesc';
import Autocomplete from '@mui/material/Autocomplete';
import Qty from 'js-quantities';
import { parse } from 'path';
import { b } from 'vitest/dist/suite-IbNSsUWN.js';
export default function NumericInputWithUnit(props: {
value: { value: number; unit: string };
onChange: (value: { value: number; unit: string }) => void;
onOwnChange: (value: { value: number; unit: string }, ...baseProps) => void;
}) {
const [inputValue, setInputValue] = useState(props.value.value);
const [unit, setUnit] = useState(props.value.unit);
@@ -26,13 +29,13 @@ export default function NumericInputWithUnit(props: {
setUnit(props.value.unit);
}, [props.value]);
const handleValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = parseFloat(event.target.value) || 0;
const handleValueChange = (val: { value: number; unit: string }) => {
const newValue = val.value;
setInputValue(newValue);
if (props.onChange) {
if (props.onOwnChange) {
try {
const qty = Qty(newValue, unit).to('meters');
props.onChange({ unit: 'meters', value: qty.scalar });
const qty = Qty(newValue, unit).to(val.unit);
props.onOwnChange({ unit: val.unit, value: qty.scalar });
} catch (error) {
console.error('Conversion error', error);
}
@@ -48,16 +51,28 @@ export default function NumericInputWithUnit(props: {
} catch (error) {
console.error('Unit conversion error', error);
}
if (props.onOwnChange) {
try {
const qty = Qty(inputValue, unit).to(newUnit);
props.onOwnChange({ unit: newUnit, value: qty.scalar });
} catch (error) {
console.error('Conversion error', error);
}
}
};
return (
<Grid container spacing={2} alignItems="center">
<Grid item xs={6}>
<TextField
<TextFieldWithDesc
{...props.baseProps}
type="number"
fullWidth
value={inputValue}
onChange={handleValueChange}
onOwnChange={(value) =>
handleValueChange({ value: parseFloat(value), unit: unit })
}
label="Value"
/>
</Grid>
@@ -65,8 +80,8 @@ export default function NumericInputWithUnit(props: {
<Autocomplete
options={unitOptions}
value={unit}
onChange={() => {
handleUnitChange(unit);
onChange={(event, newValue) => {
handleUnitChange(newValue || '');
}}
renderInput={(params) => (
<TextField {...params} label="Unit" fullWidth />