diff --git a/apps/website/pages/components/amount-input/code.tsx b/apps/website/pages/components/amount-input/code.tsx new file mode 100644 index 000000000..f6668e2a8 --- /dev/null +++ b/apps/website/pages/components/amount-input/code.tsx @@ -0,0 +1,17 @@ +import Head from "next/head"; +import type { ReactElement } from "react"; +import AmountInputPageLayout from "screens/components/amount-input/AmountInputPageLayout"; +import AmountInputCodePage from "screens/components/amount-input/code/AmountInputCodePage"; + +const Code = () => ( + <> + + Amount input code — Halstack Design System + + + +); + +Code.getLayout = (page: ReactElement) => {page}; + +export default Code; diff --git a/apps/website/pages/components/amount-input/index.tsx b/apps/website/pages/components/amount-input/index.tsx new file mode 100644 index 000000000..c3ba93aa3 --- /dev/null +++ b/apps/website/pages/components/amount-input/index.tsx @@ -0,0 +1,17 @@ +import Head from "next/head"; +import type { ReactElement } from "react"; +import AmountInputOverviewPage from "screens/components/amount-input/overview/AmountInputOverviewPage"; +import AmountInputPageLayout from "screens/components/amount-input/AmountInputPageLayout"; + +const Index = () => ( + <> + + Amount input — Halstack Design System + + + +); + +Index.getLayout = (page: ReactElement) => {page}; + +export default Index; diff --git a/apps/website/screens/common/componentsList.json b/apps/website/screens/common/componentsList.json index c3693bbc3..054c44f9f 100644 --- a/apps/website/screens/common/componentsList.json +++ b/apps/website/screens/common/componentsList.json @@ -123,6 +123,12 @@ "label": "Forms", "icon": "assignment", "links": [ + { + "label": "Amount input", + "path": "/components/amount-input", + "status": "experimental", + "icon": "universal_currency_alt" + }, { "label": "Button", "path": "/components/button", diff --git a/apps/website/screens/components/amount-input/AmountInputPageLayout.tsx b/apps/website/screens/components/amount-input/AmountInputPageLayout.tsx new file mode 100644 index 000000000..136d66793 --- /dev/null +++ b/apps/website/screens/components/amount-input/AmountInputPageLayout.tsx @@ -0,0 +1,30 @@ +import { DxcParagraph, DxcFlex } from "@dxc-technology/halstack-react"; +import PageHeading from "@/common/PageHeading"; +import TabsPageHeading from "@/common/TabsPageLayout"; +import ComponentHeading from "@/common/ComponentHeading"; +import { ReactNode } from "react"; + +const AmountInputPageHeading = ({ children }: { children: ReactNode }) => { + const tabs = [ + { label: "Overview", path: "/components/amount-input" }, + { label: "Code", path: "/components/amount-input/code" }, + ]; + + return ( + + + + + + Amount inputs are fields specifically designed to capture and display{" "} + monetary or amount-based numeric values in a structured, readable, and accessible format. + + + + + {children} + + ); +}; + +export default AmountInputPageHeading; diff --git a/apps/website/screens/components/amount-input/code/AmountInputCodePage.tsx b/apps/website/screens/components/amount-input/code/AmountInputCodePage.tsx new file mode 100644 index 000000000..37fa1e093 --- /dev/null +++ b/apps/website/screens/components/amount-input/code/AmountInputCodePage.tsx @@ -0,0 +1,310 @@ +import { DxcFlex, DxcLink, DxcTable } from "@dxc-technology/halstack-react"; +import QuickNavContainer from "@/common/QuickNavContainer"; +import DocFooter from "@/common/DocFooter"; +import Code, { TableCode, ExtendedTableCode } from "@/common/Code"; +import controlled from "./examples/controlled"; +import Example from "@/common/example/Example"; +import currency from "./examples/currency"; +import unit from "./examples/unit"; +import Link from "next/link"; + +const configTypeString = `{ + thousandSeparator?: string; + decimalSeparator?: string; + symbolPosition?: 'before' | 'after'; +} & ( + | { + currencyConfig?: { + currency: string; + currencyDisplay?: 'code' | + 'symbol' | + 'narrowSymbol' | + 'name'; + currencySign?: 'standard' | 'accounting'; + }; + unitsConfig?: never; + } + | { + currencyConfig?: never; + unitsConfig?: { + unit: string; + unitDisplay?: 'short' | 'long' | 'narrow'; + }; + } +)`; + +const sections = [ + { + title: "Props", + content: ( + + + + Name + Type + Description + Default + + + + + alignment + + 'left' | 'right' + + Sets the alignment inside the input. + - + + + ariaLabel + + string + + + Specifies a string to be used as the name for the textInput element when no label is + provided. + + - + + + clearable + + boolean + + If true, the input will have an action to clear the entered value. + - + + + config + + {configTypeString} + + + Configuration for the amount input, including currency or units, and formatting options such as thousand + and decimal separators and the position of the currency symbol. currencyConfig and{" "} + unitsConfig are mutually exclusive. To better understand the allowed values for currencies + and units, please refer to the{" "} + + respective documentation. + + + - + + + defaultValue + + string + + Initial value of the input, only when it is uncontrolled. + - + + + disabled + + boolean + + If true, the component will be disabled. + - + + + error + + string + + + If it is a defined value and also a truthy string, the component will change its appearance, showing the + error below the input component. If the defined value is an empty string, it will reserve a space below + the component for a future error, but it would not change its look. In case of being undefined or null, + both the appearance and the space for the error message would not be modified. + + - + + + helperText + + string + + Helper text to be placed above the input. + - + + + label + + string + + + Text to be placed above the input. This label will be used as the aria-label attribute of the list of + suggestions. + + - + + + maxValue + + number + + Specifies the maximum value allowed in the input. + - + + + minValue + + number + + Specifies the minimum value allowed in the input. + - + + + name + + string + + Name attribute of the input element. + - + + + numberOfDecimals + + number + + + Specifies the number of decimal places allowed in the input. By default it is set to 3 or the permitted + amount by the currency. + + - + + + numberOfIntegers + + number + + Specifies the number of integer places allowed in the input. + - + + + onBlur + + {"(val: { value: string; error?: string }) => void"} + + + This function will be called when the input element loses the focus. An object including the input value + and the error (if the value entered is not valid) will be passed to this function. If there is no error,{" "} + error will not be defined. + + - + + + onChange + + {"(val: { value: string; error?: string }) => void"} + + + This function will be called when the user types within the input element of the component. An object + including the current value and the error (if the value entered is not valid) will be passed to this + function. If there is no error, error will not be defined. + + - + + + optional + + boolean + + + If true, the input will be optional, showing '(Optional)' next to the label. Otherwise, the field will be + considered required and an error will be passed as a parameter to the onBlur and{" "} + onChange functions when it has not been filled. + + - + + + placeholder + + string + + Text to be put as placeholder of the input. + - + + + readOnly + + boolean + + + If true, the component will not be mutable, meaning the user can not edit the control. In addition, the + clear action will not be displayed even if the flag is set to true. + + - + + + ref + + {"React.Ref"} + + Ref to the input element. + - + + + size + + 'small' | 'medium' | 'large' | 'fillParent' + + Size of the component. + - + + + tabIndex + + number + + + Value of the tabindex attribute. + + - + + + value + + string + + + Value of the input. If undefined, the component will be uncontrolled and the value will be managed + internally by the component. + + - + + + + ), + }, + { + title: "Examples", + subSections: [ + { + title: "Controlled", + content: , + }, + { + title: "Currency", + content: , + }, + { + title: "Unit", + content: , + }, + ], + }, +]; + +const AmountInputCodePage = () => ( + + + + +); + +export default AmountInputCodePage; diff --git a/apps/website/screens/components/amount-input/code/examples/controlled.tsx b/apps/website/screens/components/amount-input/code/examples/controlled.tsx new file mode 100644 index 000000000..59a1f1d7e --- /dev/null +++ b/apps/website/screens/components/amount-input/code/examples/controlled.tsx @@ -0,0 +1,24 @@ +import { DxcAmountInput, DxcInset } from "@dxc-technology/halstack-react"; +import { useState } from "react"; + +const code = `() => { + const [value, setValue] = useState(""); + + return ( + + setValue(value)} + /> + + ); +}`; + +const scope = { + DxcAmountInput, + DxcInset, + useState, +}; + +export default { code, scope }; diff --git a/apps/website/screens/components/amount-input/code/examples/currency.tsx b/apps/website/screens/components/amount-input/code/examples/currency.tsx new file mode 100644 index 000000000..b5b289ec0 --- /dev/null +++ b/apps/website/screens/components/amount-input/code/examples/currency.tsx @@ -0,0 +1,27 @@ +import { DxcAmountInput, DxcInset } from "@dxc-technology/halstack-react"; +import { useState } from "react"; + +const code = `() => { + const config = { + currencyConfig: { + currency: "USD", + }, + }; + + return ( + + + + ); +}`; + +const scope = { + DxcAmountInput, + DxcInset, + useState, +}; + +export default { code, scope }; diff --git a/apps/website/screens/components/amount-input/code/examples/unit.tsx b/apps/website/screens/components/amount-input/code/examples/unit.tsx new file mode 100644 index 000000000..c7b318a5e --- /dev/null +++ b/apps/website/screens/components/amount-input/code/examples/unit.tsx @@ -0,0 +1,28 @@ +import { DxcAmountInput, DxcInset } from "@dxc-technology/halstack-react"; +import { useState } from "react"; + +const code = `() => { + const config = { + unitsConfig: { + unit: "kilogram", + unitDisplay: "short", + }, + }; + + return ( + + + + ); +}`; + +const scope = { + DxcAmountInput, + DxcInset, + useState, +}; + +export default { code, scope }; diff --git a/apps/website/screens/components/amount-input/overview/AmountInputOverviewPage.tsx b/apps/website/screens/components/amount-input/overview/AmountInputOverviewPage.tsx new file mode 100644 index 000000000..b1b07d904 --- /dev/null +++ b/apps/website/screens/components/amount-input/overview/AmountInputOverviewPage.tsx @@ -0,0 +1,334 @@ +import { DxcParagraph, DxcBulletedList, DxcFlex, DxcTable } from "@dxc-technology/halstack-react"; +import QuickNavContainer from "@/common/QuickNavContainer"; +import DocFooter from "@/common/DocFooter"; +import Image from "@/common/Image"; +import anatomy from "./images/amount_input_anatomy.png"; +import Code from "@/common/Code"; + +const sections = [ + { + title: "Introduction", + content: ( + <> + + Distinct from the standard number input, the amount input is optimized for values where{" "} + numeric formatting is required (ex. currency, financial values, percentages, and + measurements). It can present values using grouping, decimal separators, and symbols to provide contextual + information to users. + + + This makes the component particularly useful for financial forms, payments, budgets, transactions, quotations, + and other experiences where users enter financial or values requiring specific units and formatting. + + + ), + }, + { + title: "Anatomy", + content: ( + <> + Amount input anatomy + + + Label (Optional): a descriptive text that identifies the amount users are expected + to enter. Labels should be concise and should communicate the purpose of the value rather than its + formatting. + + + Optional indicator (Optional): indicates that providing an amount is not required. + + + Helper text (Optional): provides additional information about the expected amount, + currency, restrictions, or other requirements. + + + Container: the visual wrapper for the input. It establishes the interactive area and + communicates states such as hover, focus, error, disabled, and read-only. + + + Placeholder/Value: provides an example or hint before a value is entered. The value + represents the number provided by the user and can be automatically formatted based on currency, percentage, + or unit settings. + + + + ), + }, + { + title: "Form inputs", + content: ( + <> + + Form inputs allow users to enter or select data. Choosing an input that matches the type of information being + collected helps improve task completion and data accuracy. + + + Amount input should be used when the numeric information being collected has value and formatting-specific + presentation requirements. For numeric data where rigid formatting is unnecessary, use the more general number + input instead. + + + ), + subSections: [ + { + title: "Shared input characteristics", + content: ( + <> + Amount input shares the common characteristics of other Halstack form inputs: + + + Placeholder: provides a hint or example of the expected value. + + + Helper text: provides instructions or additional information about the expected amount. + + + Optional label: communicates that entering a value is not mandatory. + + + + ), + }, + { + title: "Common input states", + content: ( + <> + Most inputs can also present standard interactive or informative states: + + + Disabled: this state prevents users from interacting with the field. It's typically + used when a value is not applicable or editable under certain conditions or roles. + + + Error: when a user enters invalid or incomplete data, the input shows an error state, + often accompanied by a helpful message to guide corrections. + + + Read-only: the input is visible, focusable, and hoverable, but not editable. This is + ideal for fields with auto-calculated values. Unlike disabled fields, read-only inputs can still be + submitted with the form and are part of the form data. + + + + ), + }, + ], + }, + { + title: "Using amount inputs", + content: ( + + Amount inputs should be used whenever users need to enter monetary values or other numeric values where{" "} + amount formatting and readability are important. + + ), + subSections: [ + { + title: "Amount Input vs Number Input vs Text Input", + content: ( + <> + + + Use amount input when the value represents an amount and requires currency-specific, + percentage, or measurement unit formatting. + + + Use number input for discrete, countable quantities like Item counts, guests, age, or + ratings where the numeric value itself is calculated or compared. + + + Use text input for general numeric values that need more flexibility or a combination + of numbers and letters. These can include location information like address, contact number, and zip + code. + + + + + + Need + Component + + + + + Address, phone number, zip code + Text Input + + + Quantities that Increment/decrement with a defined step (ex. age, object count, ratings) + Number Input + + + Currency or locale-formatted values + Amount Input + + + + Price, cost, payment or financial amounts that require specific digits, separators, decimals, or + formatting + + Amount Input + + + Quantities with units (percent, weight, distance, volume) + Amount Input + + + + + ), + }, + ], + }, + { + title: "Formatting", + content: ( + <> + + Users should be able to type an amount directly into the field using familiar numeric input conventions. + + + The component should distinguish between a user's editing state and the{" "} + formatted representation of the final value. This prevents formatting from interfering + unnecessarily while users are entering or correcting an amount. + + For example, a user typing: +
+ 1234567.89 +
+ may ultimately see: +
+ 1,234,567.89 +
+ after the value has been accepted and formatted. + Common use cases and corresponding amount input formatting examples: + + + + Use case + Example + + + + + Currency + + $ 2,532.50 +
+ 123.456,79 €
+ -3,500.00 US dollars + + + + Units + + 1,000 km +
+ 58.2 litres + + + + Percentage + + 97.999 % +
+ 2.5% + + + + Digit grouping and separators + + R$ 1.250.500,75 +
+ 1 250 500,75 € +
+ ₹12,50,500.75 + + + + Decimal values + + 0.00075 +
+ 9.81 + + + +
+ + ), + }, + { + title: "Best practices", + subSections: [ + { + title: "General", + content: ( + + + Always use clear labels: describe what the amount represents rather than relying on its + formatting or currency symbol alone. + + + Make currency clear: when the value represents money, users should be able to determine + which currency applies without relying on context elsewhere on the page. + + + Use helper text when necessary: explain constraints, expected values, or other + requirements that cannot be inferred from the label. + + + Indicate optional fields: use the standard Halstack optional indicator when entering an + amount is not mandatory. + + + ), + }, + { + title: "Formatting", + content: ( + + + Format for readability, not decoration: thousand/grouping separators are especially + useful for large values making them easier to read. Alignment also plays a significant role in improving + the readability of multiple values, particularly those with fixed decimal digits. + + + Consider locale carefully and communicate it clearly with users: Decimal and grouping + separators differ between locales. For example, 1,234.56 and 1.234,56 can + represent the same amount under different conventions. + + + ), + }, + { + title: "Validation", + content: ( + + + Provide useful validation messages: explain why an amount is invalid and, where possible, + what users need to do to correct it. + + + Explain constraints in human-readable terms: for example, prefer “Enter an amount between + $100 and $1,000” over a generic “Invalid value.” + + + Preserve user input when displaying an error: so users can correct the value rather than + entering it again. + + + ), + }, + ], + }, +]; + +const AmountInputOverviewPage = () => ( + + + + +); + +export default AmountInputOverviewPage; diff --git a/apps/website/screens/components/amount-input/overview/images/amount_input_anatomy.png b/apps/website/screens/components/amount-input/overview/images/amount_input_anatomy.png new file mode 100644 index 000000000..1c40273a4 Binary files /dev/null and b/apps/website/screens/components/amount-input/overview/images/amount_input_anatomy.png differ diff --git a/apps/website/screens/guidelines/localization/LocalizationPage.tsx b/apps/website/screens/guidelines/localization/LocalizationPage.tsx index a546d8564..fce7cf9b1 100644 --- a/apps/website/screens/guidelines/localization/LocalizationPage.tsx +++ b/apps/website/screens/guidelines/localization/LocalizationPage.tsx @@ -167,6 +167,40 @@ const sections = [ ), }, + { + title: "amountInput", + content: ( + + + + Label Name + Default value + Details + + + + + + valueGreaterThanOrEqualToErrorMessage + + + Value must be greater than or equal to value. + + It is a function that receives one parameter (value) and returns the text with that parameter. + + + + valueLessThanOrEqualToErrorMessage + + + Value must be less than or equal to value. + + It is a function that receives one parameter (value) and returns the text with that parameter. + + + + ), + }, { title: "calendar", content: ( diff --git a/apps/website/screens/guidelines/localization/examples/localization.tsx b/apps/website/screens/guidelines/localization/examples/localization.tsx index 9475e15ca..accd24bc7 100644 --- a/apps/website/screens/guidelines/localization/examples/localization.tsx +++ b/apps/website/screens/guidelines/localization/examples/localization.tsx @@ -1,4 +1,11 @@ -import { DxcDateInput, DxcTimeInput, HalstackProvider, DxcInset, DxcFlex } from "@dxc-technology/halstack-react"; +import { + DxcAmountInput, + DxcDateInput, + DxcTimeInput, + HalstackProvider, + DxcInset, + DxcFlex, +} from "@dxc-technology/halstack-react"; const code = `() => { @@ -21,6 +28,15 @@ const labels = { label="Time" optional /> + @@ -31,6 +47,7 @@ const scope = { DxcFlex, DxcTimeInput, DxcDateInput, + DxcAmountInput, HalstackProvider, DxcInset, }; diff --git a/apps/website/screens/theme-generator/componentsRegistry.tsx b/apps/website/screens/theme-generator/componentsRegistry.tsx index b4a740a2a..dbca20fe2 100644 --- a/apps/website/screens/theme-generator/componentsRegistry.tsx +++ b/apps/website/screens/theme-generator/componentsRegistry.tsx @@ -1,6 +1,7 @@ import { AccordionPreview, AlertPreview, + AmountInputPreview, AvatarPreview, BadgePreview, BreadcrumbsPreview, @@ -43,6 +44,7 @@ import { ApplicationPreview, DashboardPreview, FormPreview } from "./previews/ex export const componentsRegistry = { "/components/accordion": AccordionPreview, + "/components/amount-input": AmountInputPreview, "/components/avatar": AvatarPreview, "/components/divider": DividerPreview, "/components/wizard": WizardPreview, diff --git a/apps/website/screens/theme-generator/previews/components/AmountInputPreview.tsx b/apps/website/screens/theme-generator/previews/components/AmountInputPreview.tsx new file mode 100644 index 000000000..bddcd915d --- /dev/null +++ b/apps/website/screens/theme-generator/previews/components/AmountInputPreview.tsx @@ -0,0 +1,11 @@ +import { DxcFlex, DxcAmountInput } from "@dxc-technology/halstack-react"; +const AmountInputPreview = () => { + return ( + + + + + ); +}; + +export default AmountInputPreview; diff --git a/apps/website/screens/theme-generator/previews/components/index.ts b/apps/website/screens/theme-generator/previews/components/index.ts index 871a93b95..258f1172c 100644 --- a/apps/website/screens/theme-generator/previews/components/index.ts +++ b/apps/website/screens/theme-generator/previews/components/index.ts @@ -1,5 +1,6 @@ export { default as AccordionPreview } from "./AccordionPreview"; export { default as AlertPreview } from "./AlertPreview"; +export { default as AmountInputPreview } from "./AmountInputPreview"; export { default as AvatarPreview } from "./AvatarPreview"; export { default as BadgePreview } from "./BadgePreview"; export { default as BreadcrumbsPreview } from "./BreadcrumbsPreview"; diff --git a/packages/lib/src/amount-input/AmountInput.stories.tsx b/packages/lib/src/amount-input/AmountInput.stories.tsx new file mode 100644 index 000000000..e22f8d0dd --- /dev/null +++ b/packages/lib/src/amount-input/AmountInput.stories.tsx @@ -0,0 +1,176 @@ +import { Meta, StoryObj } from "@storybook/react-vite"; +import type { CurrencyConfigType, UnitsConfigType } from "./types"; +import ExampleContainer from "../../.storybook/components/ExampleContainer"; +import Title from "../../.storybook/components/Title"; +import DxcAmountInput from "./AmountInput"; +import { HalstackProvider } from "../HalstackContext"; + +export default { + title: "Amount Input", + component: DxcAmountInput, +} satisfies Meta; + +const currencyConfig = { + currency: "CNY", + currencyDisplay: "symbol", + currencySign: "accounting", +} as CurrencyConfigType; + +const unitsConfig = { + unit: "kilometer", + unitDisplay: "short", +} as UnitsConfigType; + +const Examples = () => { + return ( + <> + + + + + + ); +}; + +const LocalizationExamples = () => { + return ( + <> + + + + + { + console.log({ value, error }); + }} + clearable + /> + + + ); +}; + +const AmountInput = () => { + return ( + <> + + + + <DxcAmountInput ariaLabel="Amount" /> + </ExampleContainer> + <ExampleContainer> + <Title title="With label and placeholder" theme="light" level={4} /> + <DxcAmountInput label="Amount" placeholder="Enter an amount" /> + </ExampleContainer> + <ExampleContainer> + <Title title="Helper text, optional, value and clearable" theme="light" level={4} /> + <DxcAmountInput label="Amount" helperText="Enter an amount" optional defaultValue="1234.56" clearable /> + </ExampleContainer> + <ExampleContainer> + <Title title="Disabled with placeholder" theme="light" level={4} /> + <DxcAmountInput label="Disabled amount" disabled placeholder="Enter an amount" /> + </ExampleContainer> + <ExampleContainer> + <Title title="Disabled with value" theme="light" level={4} /> + <DxcAmountInput label="Disabled amount" helperText="Help message" disabled optional defaultValue="1234.56" /> + </ExampleContainer> + <ExampleContainer> + <Title title="Read only" theme="light" level={4} /> + <DxcAmountInput label="Amount" helperText="Help message" readOnly optional defaultValue="1234.56" /> + </ExampleContainer> + <ExampleContainer> + <Title title="Invalid" theme="light" level={4} /> + <DxcAmountInput label="Amount" helperText="Help message" error="Error message." defaultValue="1234.56" /> + </ExampleContainer> + <ExampleContainer pseudoState="pseudo-hover"> + <Title title="Hovered" theme="light" level={4} /> + <Examples /> + <DxcAmountInput label="Amount" helperText="Help message" error="Error message." defaultValue="1234.56" /> + </ExampleContainer> + <ExampleContainer pseudoState="pseudo-active"> + <Title title="Active" theme="light" level={4} /> + <Examples /> + </ExampleContainer> + <ExampleContainer pseudoState="pseudo-focus"> + <Title title="Focused" theme="light" level={4} /> + <Examples /> + </ExampleContainer> + <ExampleContainer> + <Title title="Configuration" theme="light" level={2} /> + <DxcAmountInput label="Distance" defaultValue="1231234.56" config={{ unitsConfig }} /> + <DxcAmountInput label="Currency" defaultValue="1231234.56" config={{ currencyConfig }} /> + <DxcAmountInput + label="Custom separators" + defaultValue="1231234.56" + config={{ decimalSeparator: "@", thousandSeparator: "#" }} + /> + <DxcAmountInput alignment="right" label="Distance" defaultValue="1231234.56" config={{ unitsConfig }} /> + <DxcAmountInput alignment="right" label="Currency" defaultValue="1231234.56" config={{ currencyConfig }} /> + <DxcAmountInput + alignment="right" + label="Custom separators" + defaultValue="1231234.56" + config={{ decimalSeparator: "@", thousandSeparator: "#" }} + /> + </ExampleContainer> + <ExampleContainer> + <HalstackProvider localeTag="nl-NL"> + <Title title="nl-NL locale" theme="light" level={3} /> + <LocalizationExamples /> + </HalstackProvider> + <HalstackProvider localeTag="fr-FR"> + <Title title="fr-FR locale" theme="light" level={3} /> + <LocalizationExamples /> + </HalstackProvider> + </ExampleContainer> + <Title title="Sizes" theme="light" level={2} /> + <ExampleContainer> + <Title title="Small size" theme="light" level={4} /> + <DxcAmountInput label="Small" size="small" /> + </ExampleContainer> + <ExampleContainer> + <Title title="Medium size" theme="light" level={4} /> + <DxcAmountInput label="Medium" size="medium" /> + </ExampleContainer> + <ExampleContainer> + <Title title="Large size" theme="light" level={4} /> + <DxcAmountInput label="Large" size="large" /> + </ExampleContainer> + <ExampleContainer> + <Title title="Fill parent size" theme="light" level={4} /> + <DxcAmountInput label="Fill parent" size="fillParent" /> + </ExampleContainer> + </HalstackProvider> + </> + ); +}; + +type Story = StoryObj<typeof AmountInput>; + +export const Chromatic: Story = { + render: AmountInput, +}; diff --git a/packages/lib/src/amount-input/AmountInput.test.tsx b/packages/lib/src/amount-input/AmountInput.test.tsx new file mode 100644 index 000000000..c485e6e32 --- /dev/null +++ b/packages/lib/src/amount-input/AmountInput.test.tsx @@ -0,0 +1,86 @@ +import { fireEvent, render } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { HalstackProvider } from "../HalstackContext"; +import MockDOMRect from "../../test/mocks/domRectMock"; +import AmountInput from "./AmountInput"; + +global.DOMRect = MockDOMRect; +global.ResizeObserver = jest.fn().mockImplementation(() => ({ + observe: jest.fn(), + unobserve: jest.fn(), + disconnect: jest.fn(), +})); + +describe("Amount input component", () => { + test("renders its label, helper text, and placeholder", () => { + const { getByLabelText, getByText } = render( + <AmountInput label="Amount" helperText="Enter an amount" placeholder="Amount placeholder" /> + ); + const input = getByLabelText("Amount") as HTMLInputElement; + + expect(getByText("Enter an amount")).toBeTruthy(); + expect(input.placeholder).toBe("Amount placeholder"); + }); + + test("formats a default value as currency", () => { + const { getByLabelText } = render( + <HalstackProvider localeTag="en-US"> + <AmountInput label="Amount" defaultValue="1234.5" config={{ currencyConfig: { currency: "USD" } }} /> + </HalstackProvider> + ); + + expect((getByLabelText("Amount") as HTMLInputElement).value).toBe("$1,234.50"); + }); + + test("sanitizes input and formats the value on blur", async () => { + const user = userEvent.setup(); + const onChange = jest.fn(); + const onBlur = jest.fn(); + const { getByLabelText } = render( + <HalstackProvider localeTag="en-US"> + <AmountInput label="Amount" onChange={onChange} onBlur={onBlur} /> + </HalstackProvider> + ); + const input = getByLabelText("Amount") as HTMLInputElement; + + await user.type(input, "1234.5"); + expect(onChange).toHaveBeenLastCalledWith({ value: "1234.5", error: undefined }); + expect(input.value).toBe("1234.5"); + + fireEvent.blur(input); + expect(onBlur).toHaveBeenLastCalledWith({ value: "1,234.5", error: undefined }); + expect(input.value).toBe("1,234.5"); + }); + + test("limits integer digits without counting the negative sign", async () => { + const user = userEvent.setup(); + const onChange = jest.fn(); + const { getByLabelText } = render(<AmountInput label="Amount" numberOfIntegers={3} onChange={onChange} />); + const input = getByLabelText("Amount") as HTMLInputElement; + + await user.type(input, "-1234"); + + expect(onChange).toHaveBeenLastCalledWith({ value: "-123", error: undefined }); + expect(input.value).toBe("-123"); + + fireEvent.change(input, { target: { value: "-1234.56" } }); + expect(onChange).toHaveBeenLastCalledWith({ value: "-123.56", error: undefined }); + expect(input.value).toBe("-123.56"); + }); + + test("reports an error when the value exceeds the maximum", async () => { + const user = userEvent.setup(); + const onChange = jest.fn(); + const { getByLabelText } = render( + <HalstackProvider localeTag="en-US"> + <AmountInput label="Amount" maxValue={10} onChange={onChange} /> + </HalstackProvider> + ); + + await user.type(getByLabelText("Amount"), "121234.34"); + expect(onChange).toHaveBeenLastCalledWith({ + value: "121234.34", + error: "Value must be less than or equal to 10.", + }); + }); +}); diff --git a/packages/lib/src/amount-input/AmountInput.tsx b/packages/lib/src/amount-input/AmountInput.tsx new file mode 100644 index 000000000..b63d06359 --- /dev/null +++ b/packages/lib/src/amount-input/AmountInput.tsx @@ -0,0 +1,117 @@ +import { HalstackLanguageContext } from "../HalstackContext"; +import TextInput from "../text-input/TextInput"; +import { AmountInputProps } from "./types"; +import { use, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { sanitizeAmount, formatString, getErrorMessage } from "./utils"; + +const AmountInput = ({ + alignment, + ariaLabel, + clearable, + config, + defaultValue, + disabled, + error, + helperText, + label, + maxValue, + minValue, + name, + numberOfDecimals, + numberOfIntegers, + onChange, + onBlur, + optional, + placeholder, + readOnly, + ref, + size, + tabIndex, + value, +}: AmountInputProps) => { + const languageContext = use(HalstackLanguageContext); + const translatedLabels = languageContext.labels; + const locale = languageContext.locale ? languageContext.locale : undefined; + const [internalValue, setInternalValue] = useState(defaultValue ?? ""); + const [isFocused, setIsFocused] = useState(false); + const isControlled = useRef(value !== undefined); + const numberValue = isControlled.current ? (value ?? "") : internalValue; + const inputRef = useRef<HTMLInputElement | null>(null); + const setInputRef = useCallback( + (element: HTMLInputElement | null) => { + inputRef.current = element; + if (typeof ref === "function") { + const cleanup = ref(element); + if (typeof cleanup === "function") { + return () => { + inputRef.current = null; + cleanup(); + }; + } + } else if (ref) { + ref.current = element; + } + }, + [ref] + ); + const displayValue = useMemo(() => { + if (numberValue === undefined || numberValue === "") return undefined; + if (config) { + return formatString(numberValue, locale, config); + } + return new Intl.NumberFormat(locale).format(parseFloat(numberValue)); + }, [numberValue, config, locale]); + + const handleBlur = (event: { value: string; error?: string }) => { + setIsFocused(false); + const errorMessage = getErrorMessage(event.value, translatedLabels.amountInput, maxValue, minValue); + onBlur?.({ value: formatString(event.value, locale, config), error: errorMessage || event.error }); + }; + + const handleChange = (event: { value: string; error?: string }) => { + const sanitizedValue = sanitizeAmount(event.value, numberOfDecimals, numberOfIntegers); + if (!isControlled.current) { + setInternalValue(sanitizedValue); + } + const errorMessage = getErrorMessage(sanitizedValue, translatedLabels.amountInput, maxValue, minValue); + onChange?.({ value: sanitizedValue, error: errorMessage || event.error }); + }; + + useEffect(() => { + const inputElement = inputRef.current?.querySelector("input"); + const handleFocus = () => { + if (!readOnly) setIsFocused(true); + }; + if (inputElement) { + inputElement.addEventListener("focus", handleFocus); + return () => { + inputElement.removeEventListener("focus", handleFocus); + }; + } + }, [readOnly]); + + return ( + <TextInput + alignment={alignment} + ariaLabel={ariaLabel} + autocomplete="off" + clearable={clearable} + disabled={disabled} + error={error} + helperText={helperText} + label={label} + name={name} + onChange={handleChange} + onBlur={handleBlur} + optional={optional} + placeholder={placeholder} + readOnly={readOnly} + ref={setInputRef} + size={size} + tabIndex={tabIndex} + value={isFocused ? (numberValue?.toString() ?? "") : displayValue} + /> + ); +}; + +export default AmountInput; diff --git a/packages/lib/src/amount-input/types.ts b/packages/lib/src/amount-input/types.ts new file mode 100644 index 000000000..f6d9299ec --- /dev/null +++ b/packages/lib/src/amount-input/types.ts @@ -0,0 +1,142 @@ +import { PrettifyTypes } from "../common/types"; + +export type CurrencyConfigType = { + currency: string; + currencyDisplay?: "code" | "symbol" | "narrowSymbol" | "name"; + currencySign?: "standard" | "accounting"; +}; + +export type UnitsConfigType = { + unit: string; + unitDisplay?: "short" | "long" | "narrow"; +}; + +export type ConfigType = PrettifyTypes< + { + thousandSeparator?: string; + decimalSeparator?: string; + symbolPosition?: "before" | "after"; + } & ( + | { currencyConfig?: CurrencyConfigType; unitsConfig?: never } + | { currencyConfig?: never; unitsConfig?: UnitsConfigType } + ) +>; + +export type AmountInputProps = { + /** + * Sets the alignment inside the input. + */ + alignment?: "left" | "right"; + /** + * Specifies a string to be used as the name for the textInput element when no `label` is provided. + */ + ariaLabel?: string; + /** + * If true, the input will have an action to clear the entered value. + */ + clearable?: boolean; + /** + * Configuration for the amount input, including currency and units. + * This includes settings for currency, units, and formatting options like thousand and decimal separators, as well as the position of the currency symbol. + */ + config?: ConfigType; + /** + * Initial value of the input, only when it is uncontrolled. + */ + defaultValue?: string; + /** + * If true, the component will be disabled. + */ + disabled?: boolean; + /** + * If it is a defined value and also a truthy string, the component will + * change its appearance, showing the error below the input component. If + * the defined value is an empty string, it will reserve a space below + * the component for a future error, but it would not change its look. In + * case of being undefined or null, both the appearance and the space for + * the error message would not be modified. + */ + error?: string; + /** + * Helper text to be placed above the input. + */ + helperText?: string; + /** + * Text to be placed above the input. This label will be used as the aria-label attribute of the list of suggestions. + */ + label?: string; + /** + * Specifies the maximum value allowed in the input. + */ + maxValue?: number; + /** + * Specifies the minimum value allowed in the input. + */ + minValue?: number; + /** + * Name attribute of the input element. + */ + name?: string; + /** + * Specifies the number of decimal places allowed in the input. + */ + numberOfDecimals?: number; + /** + * Specifies the number of integer places allowed in the input. + */ + numberOfIntegers?: number; + /** + * This function will be called when the user types within the input + * element of the component. An object including the current value and + * the error (if the value entered is not valid) will be passed to this + * function. If there is no error, error will not be defined. + */ + onChange?: (val: { value: string; error?: string }) => void; + /** + * This function will be called when the input element loses the focus. + * An object including the input value and the error (if the value + * entered is not valid) will be passed to this function. If there is no error, + * error will not be defined. + */ + onBlur?: (val: { value: string; error?: string }) => void; + /** + * If true, the input will be optional, showing '(Optional)' + * next to the label. Otherwise, the field will be considered required and an error will be + * passed as a parameter to the OnBlur and onChange functions when it has + * not been filled. + */ + optional?: boolean; + /** + * Text to be put as placeholder of the input. + */ + placeholder?: string; + /** + * If true, the component will not be mutable, meaning the user can not edit the control. + * In addition, the clear action will not be displayed even if the flag is set to true + * and the custom action will not execute its onClick event. + */ + readOnly?: boolean; + /** + * Ref to the input element. + */ + ref?: React.Ref<HTMLInputElement>; + /** + * Size of the component. + */ + size?: "small" | "medium" | "large" | "fillParent"; + /** + * Value of the tabindex attribute. + */ + tabIndex?: number; + /** + * Value of the input. If undefined, the component will be uncontrolled and the value will be managed internally by the component. + */ + value?: string; +}; + +/** + * Reference to the component. + */ +export type RefType = HTMLDivElement; + +export type { AmountInputProps as default }; diff --git a/packages/lib/src/amount-input/utils.ts b/packages/lib/src/amount-input/utils.ts new file mode 100644 index 000000000..6f2a18ccb --- /dev/null +++ b/packages/lib/src/amount-input/utils.ts @@ -0,0 +1,125 @@ +import { ConfigType } from "./types"; + +/** + * Sanitizes the input amount string by removing thousand separators, replacing the decimal separator with a dot, and limiting the number of decimals. + */ +export const sanitizeAmount = ( + value: string | undefined, + numberOfDecimals?: number, + numberOfIntegers?: number +): string => { + if (!value) return ""; + const isNegativeAccounting = value.includes("(") && value.includes(")"); + value = value.replace(/[^\d.-]/g, ""); + if (value.startsWith("-")) { + value = "-" + value.slice(1).replace(/-/g, ""); + } else { + value = value.replace(/-/g, ""); + } + const decimalSeparatorCount = (value.match(new RegExp(`\\.`, "g")) || []).length; + if (decimalSeparatorCount > 1) { + const firstIndex = value.indexOf("."); + value = value.slice(0, firstIndex + 1) + value.slice(firstIndex + 1).replace(new RegExp(`\\.`, "g"), ""); + } + + if (numberOfDecimals !== undefined && numberOfDecimals >= 0) { + const [integerPart, decimalPart] = value.split("."); + if (decimalPart) { + value = `${integerPart}.${decimalPart.slice(0, numberOfDecimals)}`; + } + } + if (numberOfIntegers !== undefined && numberOfIntegers >= 0) { + const [integerPart, decimalPart] = value.split("."); + if (integerPart) { + const sign = integerPart.startsWith("-") ? "-" : ""; + const digits = sign ? integerPart.slice(1) : integerPart; + value = `${sign}${digits.slice(0, numberOfIntegers)}${decimalPart ? `.${decimalPart}` : ""}`; + } + } + return isNegativeAccounting && value ? `-${value}` : value; +}; + +export const formatString = (value: string, locale: string | undefined, config?: ConfigType): string => { + let formatter = new Intl.NumberFormat(locale); + if (config?.currencyConfig && config.currencyConfig.currency) { + formatter = new Intl.NumberFormat(locale, { + style: "currency", + currency: config.currencyConfig.currency, + currencyDisplay: config.currencyConfig.currencyDisplay || "symbol", + currencySign: config.currencyConfig.currencySign || "standard", + }); + } + if (config?.unitsConfig && config.unitsConfig.unit) { + formatter = new Intl.NumberFormat(locale, { + style: "unit", + unit: config.unitsConfig.unit, + unitDisplay: config.unitsConfig.unitDisplay || "short", + }); + } + let formattedParts = formatter.formatToParts(parseFloat(value)); + + if ( + config?.symbolPosition === "before" && + formattedParts.some((part) => part.type === "currency" || part.type === "unit") + ) { + let symbolIndex = formattedParts.findIndex((part) => part.type === "currency" || part.type === "unit"); + if (symbolIndex > 0) { + if (formattedParts[symbolIndex - 1]?.type === "literal") { + const [literalPart] = formattedParts.splice(symbolIndex - 1, 1); + if (literalPart) formattedParts.unshift(literalPart); + // symbolIndex--; + } + const [symbolPart] = formattedParts.splice(symbolIndex, 1); + if (symbolPart) formattedParts.unshift(symbolPart); + } + } else if ( + config?.symbolPosition === "after" && + formattedParts.some((part) => part.type === "currency" || part.type === "unit") + ) { + let symbolIndex = formattedParts.findIndex((part) => part.type === "currency" || part.type === "unit"); + if (symbolIndex < formattedParts.length - 1) { + if (formattedParts[symbolIndex + 1]?.type === "literal") { + const [literalPart] = formattedParts.splice(symbolIndex + 1, 1); + if (literalPart) formattedParts.push(literalPart); + } + const [symbolPart] = formattedParts.splice(symbolIndex, 1); + if (symbolPart) formattedParts.push(symbolPart); + } + } + + return formattedParts + .map((part) => { + if (part.type === "decimal" && config?.decimalSeparator) return config.decimalSeparator; + if (part.type === "group" && config?.thousandSeparator) return config.thousandSeparator; + return part.value; + }) + .join(""); +}; + +export const getDefaultConfigBasedOnLocale = (locale: string | undefined, config?: ConfigType) => { + const number = 1234.56; + let formatter = new Intl.NumberFormat(locale); + const decimalSeparator = + config?.decimalSeparator || formatter.formatToParts(number).find((part) => part.type === "decimal")?.value || "."; + const thousandSeparator = + config?.thousandSeparator || formatter.formatToParts(number).find((part) => part.type === "group")?.value || ","; + return { decimalSeparator, thousandSeparator }; +}; + +export const getErrorMessage = ( + value: string, + amountLabels: { + valueGreaterThanOrEqualToErrorMessage: (value: number) => string; + valueLessThanOrEqualToErrorMessage: (value: number) => string; + }, + maxValue?: number, + minValue?: number +) => { + if (maxValue !== undefined && parseFloat(value) > maxValue) { + return amountLabels.valueLessThanOrEqualToErrorMessage(maxValue); + } + if (minValue !== undefined && parseFloat(value) < minValue) { + return amountLabels.valueGreaterThanOrEqualToErrorMessage(minValue); + } + return undefined; +}; diff --git a/packages/lib/src/common/variables.ts b/packages/lib/src/common/variables.ts index 98a2caf42..64e16868b 100644 --- a/packages/lib/src/common/variables.ts +++ b/packages/lib/src/common/variables.ts @@ -19,15 +19,19 @@ export const responsiveSizes = { }; export const defaultTranslatedComponentLabels = { - applicationLayout: { - visibilityToggleTitle: "Toggle sidenav visibility", - }, alert: { previousMessageActionTitle: "Previous message", nextMessageActionTitle: "Next message", closeAlertActionTitle: "Close alert", closeMessageActionTitle: "Close message", }, + applicationLayout: { + visibilityToggleTitle: "Toggle sidenav visibility", + }, + amountInput: { + valueGreaterThanOrEqualToErrorMessage: (value: number) => `Value must be greater than or equal to ${value}.`, + valueLessThanOrEqualToErrorMessage: (value: number) => `Value must be less than or equal to ${value}.`, + }, calendar: { daysShort: ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: [ diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 0fbf48b89..3d577db35 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -3,6 +3,7 @@ import "./styles/variables.css"; export { default as DxcAccordion } from "./accordion/Accordion"; export { default as DxcAlert } from "./alert/Alert"; +export { default as DxcAmountInput } from "./amount-input/AmountInput"; export { default as DxcApplicationLayout } from "./layout/ApplicationLayout"; export { default as DxcAvatar } from "./avatar/Avatar"; export { default as DxcBadge } from "./badge/Badge"; @@ -79,6 +80,11 @@ export type { AlertAction as DxcAlertAction, AlertMessage as DxcAlertMessage, } from "./alert/types"; +export type { + AmountInputProps as DxcAmountInputProps, + CurrencyConfigType as DxcCurrencyConfigType, + UnitsConfigType as DxcUnitsConfigType, +} from "./amount-input/types"; export type { ApplicationLayoutProps as DxcAppLayoutProps, AppLayoutMainProps as DxcAppLayoutMainProps,