From f6752965b73d760059d7292944c5b30ac4d3ce13 Mon Sep 17 00:00:00 2001 From: psychedelicious <4822129+psychedelicious@users.noreply.github.com> Date: Sat, 15 Jul 2023 01:04:33 +1000 Subject: [PATCH] fix(ui): allow decimals in number inputs still some jank but eh --- .../src/common/components/IAINumberInput.tsx | 2 +- .../fields/NumberInputFieldComponent.tsx | 36 ++++++++++++++++--- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/invokeai/frontend/web/src/common/components/IAINumberInput.tsx b/invokeai/frontend/web/src/common/components/IAINumberInput.tsx index 8f675cc148..de3b44564a 100644 --- a/invokeai/frontend/web/src/common/components/IAINumberInput.tsx +++ b/invokeai/frontend/web/src/common/components/IAINumberInput.tsx @@ -28,7 +28,7 @@ import { useState, } from 'react'; -const numberStringRegex = /^-?(0\.)?\.?$/; +export const numberStringRegex = /^-?(0\.)?\.?$/; interface Props extends Omit { label?: string; diff --git a/invokeai/frontend/web/src/features/nodes/components/fields/NumberInputFieldComponent.tsx b/invokeai/frontend/web/src/features/nodes/components/fields/NumberInputFieldComponent.tsx index f5df8989f5..50d69a6496 100644 --- a/invokeai/frontend/web/src/features/nodes/components/fields/NumberInputFieldComponent.tsx +++ b/invokeai/frontend/web/src/features/nodes/components/fields/NumberInputFieldComponent.tsx @@ -6,6 +6,7 @@ import { NumberInputStepper, } from '@chakra-ui/react'; import { useAppDispatch } from 'app/store/storeHooks'; +import { numberStringRegex } from 'common/components/IAINumberInput'; import { fieldValueChanged } from 'features/nodes/store/nodesSlice'; import { FloatInputFieldTemplate, @@ -13,7 +14,7 @@ import { IntegerInputFieldTemplate, IntegerInputFieldValue, } from 'features/nodes/types/types'; -import { memo } from 'react'; +import { memo, useEffect, useState } from 'react'; import { FieldComponentProps } from './types'; const NumberInputFieldComponent = ( @@ -23,17 +24,42 @@ const NumberInputFieldComponent = ( > ) => { const { nodeId, field } = props; - const dispatch = useAppDispatch(); + const [valueAsString, setValueAsString] = useState( + String(field.value) + ); - const handleValueChanged = (_: string, value: number) => { - dispatch(fieldValueChanged({ nodeId, fieldName: field.name, value })); + const handleValueChanged = (v: string) => { + setValueAsString(v); + // This allows negatives and decimals e.g. '-123', `.5`, `-0.2`, etc. + if (!v.match(numberStringRegex)) { + // Cast the value to number. Floor it if it should be an integer. + dispatch( + fieldValueChanged({ + nodeId, + fieldName: field.name, + value: + props.template.type === 'integer' + ? Math.floor(Number(v)) + : Number(v), + }) + ); + } }; + useEffect(() => { + if ( + !valueAsString.match(numberStringRegex) && + field.value !== Number(valueAsString) + ) { + setValueAsString(String(field.value)); + } + }, [field.value, valueAsString]); + return (