From ceb8af712cd09e54f7c0d8e31bec12ff6630bd5f Mon Sep 17 00:00:00 2001 From: Brecht Cloetens Date: Mon, 19 Dec 2022 22:18:28 +0100 Subject: [PATCH] Fixes #236 --- changelog.md | 2 ++ packages/input.number/src/NumberInput.tsx | 24 ++++++++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/changelog.md b/changelog.md index 38ade3569..0303dfe5e 100644 --- a/changelog.md +++ b/changelog.md @@ -2,6 +2,8 @@ ## [Unreleased] +- Fixed an issue with the initialValue property of the number field. It is now possible to empty the field while editting when an initialValue was set. The initialValue will only be set at first render when the value is undefined or when leaving the required field with an empty value. Leaving an optional empty number field will not add the initialValue. + ## [0.3.1] - Fix the `@alinea/preview/remix` preview hook diff --git a/packages/input.number/src/NumberInput.tsx b/packages/input.number/src/NumberInput.tsx index 0a9bd141f..dfda4206a 100644 --- a/packages/input.number/src/NumberInput.tsx +++ b/packages/input.number/src/NumberInput.tsx @@ -1,8 +1,10 @@ import {InputLabel, InputState, useInput} from '@alinea/editor' -import {fromModule} from '@alinea/ui' + import {IcRoundNumbers} from '@alinea/ui/icons/IcRoundNumbers' import {NumberField} from './NumberField' import css from './NumberInput.module.scss' +import {fromModule} from '@alinea/ui' +import {useState} from 'react' const styles = fromModule(css) @@ -14,7 +16,8 @@ export type NumberInputProps = { export function NumberInput({state, field}: NumberInputProps) { const {inline, help, optional, initialValue, width, minValue, maxValue} = field.options - const [value = initialValue, setValue] = useInput(state) + const [value, setValue] = useInput(state) + const [defined, setDefined] = useState(typeof value === undefined) return ( + value={ + String(value ?? '') || (!defined ? String(initialValue ?? '') : '') + } + onChange={e => { setValue( e.currentTarget.value === '' ? undefined! : Number(e.currentTarget.value) ) - } + if (!defined) setDefined(true) + }} + onBlur={e => { + if ( + !optional && + value === undefined && + typeof initialValue !== 'undefined' + ) + setValue(initialValue) + }} min={minValue} max={maxValue} />