Functional Weave
Code in Rust

react.form.money-field@1.0.0

impl/typescript.tsx

2,261 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

"use client";

import { useId, useState, type JSX, type ReactNode } from "react";
import { moneyInputFormat, parseMoneyInput } from "./form_money_input.ts";  ← from form.money-input ^1.0.0 · built alongside by fune
import { TextField } from "./react_form_text_field.ts";  ← from react.form.text-field ^1.0.0 · built alongside by fune
import type { MoneyFieldProps } from "./react_form_money_field_types.ts";

function present(node: ReactNode): boolean {
  return node !== null && node !== undefined && node !== false && node !== "";
}

/**
 * The GOV.UK text input with a currency prefix (or suffix, for currencies
 * written after the amount), a decimal keyboard and no spell check. What is
 * typed stays text: parseMoneyInput reads it as integer minor units for the
 * currency, the way the locale writes numbers, and checks the rules, so the
 * server can read the same text to the same Money. The symbol is aria-hidden,
 * as GOV.UK does, so the label has to say the currency.
 */
export function MoneyField(props: MoneyFieldProps): JSX.Element {
  const auto = useId();
  const { label, currency, locale, rules, hint, showError, error, value, defaultValue, onChange, onBlur, autoComplete, disabled, className } = props;
  const id = props.id ?? auto;
  const [own, setOwn] = useState<string>(defaultValue ?? "");
  const current = value ?? own;
  // Both throw for an unknown currency or locale: a bug in the page, not
  // something the person typed.
  const format = moneyInputFormat(currency, locale);
  const check = parseMoneyInput(current, currency, locale, rules);
  const shown: ReactNode = present(error) ? error : showError && !check.valid ? check.message : null;
  return (
    <TextField
      id={id}
      name={props.name ?? id}
      label={label}
      hint={hint}
      error={shown}
      value={value}
      defaultValue={value === undefined ? defaultValue : undefined}
      onChange={(text) => {
        setOwn(text);
        onChange?.(text);
      }}
      onBlur={onBlur}
      inputMode="decimal"
      spellCheck={false}
      autoComplete={autoComplete}
      prefix={format.symbolBefore ? format.symbol : undefined}
      suffix={format.symbolBefore ? undefined : format.symbol}
      required={rules.required || undefined}
      disabled={disabled}
      className={className ? `fune-money-field ${className}` : "fune-money-field"}
    />
  );
}