diff --git a/sites/shared/components/sets/measie-input.mjs b/sites/shared/components/sets/measie-input.mjs index 3a23db0ccee..dfc832c3a7d 100644 --- a/sites/shared/components/sets/measie-input.mjs +++ b/sites/shared/components/sets/measie-input.mjs @@ -1,8 +1,9 @@ import { isDegreeMeasurement } from 'config/measurements.mjs' -import { measurementAsMm, formatMm } from 'shared/utils.mjs' +import { measurementAsMm, formatMm, measurementAsUnits } from 'shared/utils.mjs' import { Collapse } from 'shared/components/collapse.mjs' import { PlusIcon, EditIcon } from 'shared/components/icons.mjs' -import { useState } from 'react' +import { NumberInput } from 'shared/components/workbench/menus/shared/inputs.mjs' +import { useState, useCallback } from 'react' export const ns = ['account'] const Mval = ({ m, val = false, imperial = false, className = '' }) => @@ -100,35 +101,35 @@ export const MeasieInput = ({ stopLoading = () => null, }) => { const isDegree = isDegreeMeasurement(m) - const factor = isDegree ? 1 : mset.imperial ? 25.4 : 10 + const units = mset.imperial ? 'imperial' : 'metric' + const [val, setVal] = useState(() => { + const measie = mset.measies?.[m] + if (!measie) return '' + if (isDegree) return measie + return measurementAsUnits(measie, units) + }) - const isValValid = (val) => - typeof val === 'undefined' || val === '' ? null : val != false && !isNaN(val) - const isValid = (newVal) => (typeof newVal === 'undefined' ? isValValid(val) : isValValid(newVal)) - - const [val, setVal] = useState(mset.measies?.[m] / factor || '') - const [valid, setValid] = useState(isValid(mset.measies?.[m] / factor || '')) + const [valid, setValid] = useState(null) // Update onChange - const update = (evt) => { - setVal(evt.target.value) + const update = useCallback( + (validVal, rawVal) => { + setValid(validVal) + setVal(validVal || rawVal) - const useVal = isDegree - ? evt.target.value - : measurementAsMm(evt.target.value, mset.imperial ? 'imperial' : 'metric') - const validUpdate = isValid(useVal) - setValid(validUpdate) - - if (validUpdate && typeof onUpdate === 'function') { - onUpdate(m, useVal) - } - } + if (validVal && typeof onUpdate === 'function') { + const useVal = isDegree ? validVal : measurementAsMm(validVal, units) + onUpdate(m, useVal) + } + }, + [isDegree, setValid, setVal, onUpdate, units, m] + ) const save = async () => { // FIXME startLoading() const measies = {} - measies[m] = val * factor + measies[m] = isDegree ? val : measurementAsMm(val, units) const result = await backend.updateSet(mset.id, { measies }) if (result.success) { refresh() @@ -137,7 +138,7 @@ export const MeasieInput = ({ stopLoading() } - const fraction = (i, base) => update({ target: { value: Math.floor(val) + i / base } }) + const fraction = (i, base) => update(Math.floor(('' + val).split(/[\s.]/)[0]) + i / base) if (!m) return null @@ -147,48 +148,41 @@ export const MeasieInput = ({