Skip to content

Commit

Permalink
feat: improve number fields behavior when formatted with a unit (#379)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuafcole authored May 2, 2024
1 parent e486f7f commit 9be4b9f
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions packages/core/src/number-field/number-field-root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,15 @@ export function NumberFieldRoot<T extends ValidComponent = "div">(
? numberParser().parse(value ?? "")
: Number(value ?? "");

const isValidPartialValue = (value: string | number | undefined) =>
local.format && typeof value !== "number"
? numberParser().isValidPartialNumber(
value ?? "",
mergedProps.minValue,
mergedProps.maxValue,
)
: !Number.isNaN(Number(value));

const [value, setValue] = createControllableSignal({
value: () => local.value,
defaultValue: () => local.defaultValue ?? local.rawValue,
Expand Down Expand Up @@ -259,17 +268,26 @@ export function NumberFieldRoot<T extends ValidComponent = "div">(
}

const target = e.target as HTMLInputElement;
// cache the cursor position in case we need to update the input's value.
const cursorPosition = target.selectionStart;

if (e.inputType !== "insertText" || isAllowedInput(e.data || "")) {
setValue(target.value);
if (isValidPartialValue(target.value)) {
if (e.inputType !== "insertText" || isAllowedInput(e.data || "")) {
setValue(target.value);
}
}

// Unlike in React, inputs `value` can be out of sync with our value state.
// even if an input is controlled (ex: `<input value="foo" />`,
// typing on the input will change its internal `value`.
//
// To prevent this, we need to force the input `value` to be in sync with the text field value state.
target.value = String(value() ?? "");
const v = value();
if (v !== target.value) {
target.value = String(v ?? "");
target.selectionStart = cursorPosition;
target.selectionEnd = cursorPosition;
}
};

const context: NumberFieldContextValue = {
Expand Down

0 comments on commit 9be4b9f

Please sign in to comment.