/ client / src / components / numberField.tsx
numberField.tsx
 1  import { NumberFieldProps } from "@refinedev/antd/dist/components/fields/types";
 2  import { Typography } from "antd";
 3  
 4  const { Text } = Typography;
 5  
 6  function toLocaleStringSupportsOptions() {
 7    return !!(typeof Intl == "object" && Intl && typeof Intl.NumberFormat == "function");
 8  }
 9  
10  type Props = NumberFieldProps & {
11    unit: string;
12  };
13  
14  /**
15   * This field is used to display a number formatted according to the browser locale, right aligned. and uses {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl `Intl`} to display date format.
16   *
17   * @see {@link https://refine.dev/docs/ui-frameworks/antd/components/fields/number} for more details.
18   */
19  export const NumberFieldUnit = ({ value, locale, options, unit }: Props) => {
20    const number = Number(value);
21  
22    return (
23      <Text>
24        {toLocaleStringSupportsOptions() ? number.toLocaleString(locale, options) : number} {unit}
25      </Text>
26    );
27  };
28  
29  /**
30   * Like a {@link NumberFieldUnit} but for a range of numbers.
31   * @param props
32   * @returns
33   */
34  export function NumberFieldUnitRange(props: {
35    value: (number | null)[] | undefined;
36    unit?: string;
37    options?: Intl.NumberFormatOptions;
38  }) {
39    const { value, unit, options } = props;
40  
41    if (value === undefined) {
42      console.warn("NumberFieldUnitRange received undefined value");
43      return <></>;
44    }
45  
46    if (!Array.isArray(value) || value.length !== 2) {
47      console.warn("NumberFieldUnitRange received invalid value", value);
48      return <></>;
49    }
50  
51    const [min, max] = value;
52  
53    return (
54      <>
55        {min === null ? <></> : <NumberFieldUnit value={min} unit={unit ?? ""} options={options} />}
56        {" \u2013 "}
57        {max === null ? <></> : <NumberFieldUnit value={max} unit={unit ?? ""} options={options} />}
58      </>
59    );
60  }