Skip to content

Commit 1247c8e

Browse files
committed
fix(widgets): normalize regional decimal keypad separators in numeric and currency inputs
1 parent f00a5cd commit 1247c8e

2 files changed

Lines changed: 241 additions & 6 deletions

File tree

‎app/client/src/widgets/BaseInputWidget/component/index.test.tsx‎

Lines changed: 90 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import React from "react";
2-
import { render } from "@testing-library/react";
2+
import { fireEvent, render } from "@testing-library/react";
33
import "@testing-library/jest-dom/extend-expect";
4-
import BaseInputComponent, { type BaseInputComponentProps } from "./index";
4+
import BaseInputComponent, {
5+
normalizeNumericInputValue,
6+
type BaseInputComponentProps,
7+
} from "./index";
58
import { ThemeProvider } from "styled-components";
69
import { lightTheme } from "selectors/themeSelectors";
710

@@ -62,4 +65,89 @@ describe("BaseInputComponent TestCases", () => {
6265

6366
expect(inputElement).toHaveAttribute("inputmode", "decimal");
6467
});
68+
69+
test("3. Numeric input normalizes alternate decimal separator on change and allows it on keyPress", () => {
70+
const onValueChange = jest.fn();
71+
const { container } = renderBaseInputComponent({
72+
inputType: "CURRENCY",
73+
inputHTMLType: "NUMBER",
74+
shouldUseLocale: true,
75+
value: "12",
76+
onValueChange,
77+
});
78+
79+
const inputElement = container.querySelector("input")!;
80+
const commaEventNotCancelled = fireEvent.keyPress(inputElement, {
81+
key: ",",
82+
charCode: 44,
83+
});
84+
85+
expect(commaEventNotCancelled).toBe(true);
86+
87+
const alphaEventNotCancelled = fireEvent.keyPress(inputElement, {
88+
key: "a",
89+
charCode: 97,
90+
});
91+
92+
expect(alphaEventNotCancelled).toBe(false);
93+
94+
fireEvent.change(inputElement, { target: { value: "12,34" } });
95+
96+
expect(onValueChange).toHaveBeenCalledWith("12.34");
97+
});
98+
99+
test("4. Currency input with comma locale accepts dot keypad input and normalizes to comma", () => {
100+
const languagesSpy = jest
101+
.spyOn(window.navigator, "languages", "get")
102+
.mockReturnValue(["de-DE"]);
103+
const onValueChange = jest.fn();
104+
105+
try {
106+
const { container } = renderBaseInputComponent({
107+
inputType: "CURRENCY",
108+
inputHTMLType: "NUMBER",
109+
shouldUseLocale: true,
110+
value: "12",
111+
onValueChange,
112+
});
113+
114+
const inputElement = container.querySelector("input")!;
115+
const dotEventNotCancelled = fireEvent.keyPress(inputElement, {
116+
key: ".",
117+
charCode: 46,
118+
});
119+
120+
expect(dotEventNotCancelled).toBe(true);
121+
122+
fireEvent.change(inputElement, { target: { value: "12.34" } });
123+
124+
expect(onValueChange).toHaveBeenCalledWith("12,34");
125+
} finally {
126+
languagesSpy.mockRestore();
127+
}
128+
});
129+
});
130+
131+
describe("normalizeNumericInputValue", () => {
132+
it("maps a single alternate comma separator to dot when dot is expected", () => {
133+
expect(normalizeNumericInputValue("12,", ".", "en-US")).toBe("12.");
134+
expect(normalizeNumericInputValue("12,34", ".", "en-US")).toBe("12.34");
135+
expect(normalizeNumericInputValue("12.3,", ".", "en-US")).toBe("12.3");
136+
expect(normalizeNumericInputValue("1,234.56", ".", "en-US")).toBe(
137+
"1234.56",
138+
);
139+
expect(normalizeNumericInputValue("1,234,567", ".", "en-US")).toBe(
140+
"1234567",
141+
);
142+
expect(normalizeNumericInputValue("12abc,5", ".", "en-US")).toBe("12.5");
143+
});
144+
145+
it("maps a single alternate dot separator to comma when comma is expected", () => {
146+
expect(normalizeNumericInputValue("12.", ",", "de-DE")).toBe("12,");
147+
expect(normalizeNumericInputValue("12.34", ",", "de-DE")).toBe("12,34");
148+
expect(normalizeNumericInputValue("12,3.", ",", "de-DE")).toBe("12,3");
149+
expect(normalizeNumericInputValue("1.234,56", ",", "de-DE")).toBe(
150+
"1234,56",
151+
);
152+
});
65153
});

‎app/client/src/widgets/BaseInputWidget/component/index.tsx‎

Lines changed: 151 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import { Icon } from "@design-system/widgets-old";
2626
import type { InputType } from "widgets/InputWidget/constants";
2727
import { getBaseWidgetClassName } from "constants/componentClassNameConstants";
2828
import { LabelPosition } from "components/constants";
29-
import { lightenColor } from "widgets/WidgetUtils";
29+
import { getLocaleDecimalSeperator, lightenColor } from "widgets/WidgetUtils";
3030
import LabelWithTooltip, {
3131
labelLayoutStyles,
3232
LABEL_CONTAINER_CLASS,
@@ -424,6 +424,82 @@ export const isNumberInputType = (inputHTMLType: InputHTMLType = "TEXT") => {
424424
return inputHTMLType === "NUMBER";
425425
};
426426

427+
const getExpectedDecimalSeparator = (shouldUseLocale?: boolean): string => {
428+
if (!shouldUseLocale) {
429+
return ".";
430+
}
431+
432+
return getLocaleDecimalSeperator() || ".";
433+
};
434+
435+
const getAllowedNumericChars = (
436+
expectedDecimalSeparator: string,
437+
locale?: string,
438+
): Set<string> => {
439+
const allowed = new Set<string>([
440+
"e",
441+
"E",
442+
"+",
443+
"-",
444+
expectedDecimalSeparator,
445+
]);
446+
447+
for (let digit = 0; digit <= 9; digit++) {
448+
allowed.add(String(digit));
449+
450+
if (locale) {
451+
allowed.add(digit.toLocaleString(locale));
452+
}
453+
}
454+
455+
return allowed;
456+
};
457+
458+
/**
459+
* Normalizes alternate decimal separators (`.` / `,`) typed by regional mobile
460+
* keypads to `expectedDecimalSeparator` and strips non-numeric characters.
461+
*/
462+
export const normalizeNumericInputValue = (
463+
value: string,
464+
expectedDecimalSeparator: string,
465+
locale?: string,
466+
): string => {
467+
if (!value) {
468+
return value;
469+
}
470+
471+
// Convert full-width digits (e.g. Japanese IME) to ASCII, matching Blueprint's NumericInput.
472+
let normalized = value.replace(/[\uFF10-\uFF19]/g, (ch) =>
473+
String.fromCharCode(ch.charCodeAt(0) - 0xfee0),
474+
);
475+
476+
if (!normalized.includes(expectedDecimalSeparator)) {
477+
const alternates = [".", ","].filter(
478+
(sep) => sep !== expectedDecimalSeparator && normalized.includes(sep),
479+
);
480+
481+
if (alternates.length === 1) {
482+
const alt = alternates[0];
483+
const firstIdx = normalized.indexOf(alt);
484+
485+
// Only treat a single alternate separator as a decimal point (multiple occurrences are thousand separators).
486+
if (firstIdx !== -1 && normalized.indexOf(alt, firstIdx + 1) === -1) {
487+
normalized =
488+
normalized.slice(0, firstIdx) +
489+
expectedDecimalSeparator +
490+
normalized.slice(firstIdx + 1);
491+
}
492+
}
493+
}
494+
495+
const allowed = getAllowedNumericChars(expectedDecimalSeparator, locale);
496+
497+
return normalized
498+
.split("")
499+
.filter((ch) => allowed.has(ch))
500+
.join("");
501+
};
502+
427503
class BaseInputComponent extends React.Component<
428504
BaseInputComponentProps,
429505
InputComponentState
@@ -483,8 +559,35 @@ class BaseInputComponent extends React.Component<
483559
this.props.onValueChange(event.target.value);
484560
};
485561

486-
onNumberChange = (valueAsNum: number, valueAsString: string) => {
487-
this.props.onValueChange(valueAsString);
562+
onNumberChange = (
563+
valueAsNum: number,
564+
valueAsString: string,
565+
inputElement?: HTMLInputElement | null,
566+
) => {
567+
let nextValue = valueAsString;
568+
569+
if (this.props.allowNumericCharactersOnly !== false) {
570+
const locale = this.props.shouldUseLocale ? getLocale() : undefined;
571+
const expectedDecimalSeparator = getExpectedDecimalSeparator(
572+
this.props.shouldUseLocale,
573+
);
574+
575+
nextValue = normalizeNumericInputValue(
576+
valueAsString,
577+
expectedDecimalSeparator,
578+
locale,
579+
);
580+
581+
if (
582+
inputElement &&
583+
nextValue !== valueAsString &&
584+
nextValue === (this.props.value ?? "")
585+
) {
586+
inputElement.value = nextValue;
587+
}
588+
}
589+
590+
this.props.onValueChange(nextValue);
488591
};
489592

490593
getType(inputType: InputHTMLType = "TEXT") {
@@ -518,6 +621,49 @@ class BaseInputComponent extends React.Component<
518621
}
519622
};
520623

624+
onNumericKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
625+
if (this.props.allowNumericCharactersOnly !== false) {
626+
const { key } = e;
627+
628+
if (
629+
key != null &&
630+
!e.ctrlKey &&
631+
!e.altKey &&
632+
!e.metaKey &&
633+
key.length === 1
634+
) {
635+
const locale = this.props.shouldUseLocale ? getLocale() : undefined;
636+
const expectedDecimalSeparator = getExpectedDecimalSeparator(
637+
this.props.shouldUseLocale,
638+
);
639+
const allowed = getAllowedNumericChars(
640+
expectedDecimalSeparator,
641+
locale,
642+
);
643+
const isAlternateSeparator =
644+
(key === "." || key === ",") && key !== expectedDecimalSeparator;
645+
646+
if (!allowed.has(key) && !isAlternateSeparator) {
647+
e.preventDefault();
648+
649+
return;
650+
}
651+
652+
if (isAlternateSeparator) {
653+
const currentVal = e.currentTarget.value ?? "";
654+
const start = e.currentTarget.selectionStart ?? currentVal.length;
655+
const end = e.currentTarget.selectionEnd ?? start;
656+
const unselectedVal =
657+
currentVal.slice(0, start) + currentVal.slice(end);
658+
659+
if (unselectedVal.includes(expectedDecimalSeparator)) {
660+
e.preventDefault();
661+
}
662+
}
663+
}
664+
}
665+
};
666+
521667
onKeyUp = (
522668
e:
523669
| React.KeyboardEvent<HTMLTextAreaElement>
@@ -542,7 +688,7 @@ class BaseInputComponent extends React.Component<
542688

543689
return (
544690
<StyledNumericInput
545-
allowNumericCharactersOnly
691+
allowNumericCharactersOnly={false}
546692
autoFocus={this.props.autoFocus}
547693
buttonPosition={this.props.buttonPosition}
548694
className={
@@ -564,6 +710,7 @@ class BaseInputComponent extends React.Component<
564710
onBlur={() => this.setFocusState(false)}
565711
onFocus={() => this.setFocusState(true)}
566712
onKeyDown={this.onKeyDown}
713+
onKeyPress={this.onNumericKeyPress}
567714
onKeyUp={this.onKeyUp}
568715
onValueChange={this.onNumberChange}
569716
placeholder={this.props.placeholder}

0 commit comments

Comments
 (0)