Functional Weave
Code in Rust

react.form.address-fields@1.0.0

impl/typescript.tsx

4,322 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 } from "react";
import { addressFormat, validateAddress, type Address, type AddressError, type AddressFormat } from "./form_address.ts";  ← from form.address ^1.0.0 · built alongside by fune
import { Fieldset } from "./react_form_fieldset.ts";  ← from react.form.fieldset ^1.0.0 · built alongside by fune
import { Select } from "./react_form_select.ts";  ← from react.form.select ^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 { AddressFieldsProps } from "./react_form_address_fields_types.ts";

type Line = "line1" | "line2" | "town" | "region" | "postcode";

const EMPTY: Address = { line1: "", line2: null, town: "", region: null, postcode: null, country: "GB" };

// A country not in the list (or none chosen yet) still gets a usable form:
// the international labels, with the postcode optional.
function formatFor(country: string): AddressFormat {
  try {
    return addressFormat(country);
  } catch {
    return { country, name: country, uk: false, postcodeLabel: "Postal code", postcodeRequired: false, postcodeExample: null, regionLabel: "Region" };
  }
}

/**
 * The GOV.UK address pattern: several text inputs under one legend, each with
 * its own label and the autocomplete token that lets a browser fill it
 * (WCAG 1.3.5). For GB (and the Crown Dependencies) it is the UK form:
 * address lines, town or city, county and postcode. For anywhere else the
 * labels are that country's (ZIP code and State for the US), the postcode is
 * optional where the country has none, and a country select is shown when
 * countries are given. Errors come from validateAddress, field by field, the
 * same check a server makes of the submitted address.
 */
export function AddressFields(props: AddressFieldsProps): JSX.Element {
  const auto = useId();
  const { legend, hint, value, defaultValue, onChange, onBlur, errors, showErrors, countries, isPageHeading, disabled, className } = props;
  const id = props.id ?? auto;
  const name = props.name ?? id;
  const [own, setOwn] = useState<Address>(value ?? defaultValue ?? EMPTY);
  const current = value ?? own;
  const format = formatFor(current.country);
  const shown: readonly AddressError[] = errors ?? (showErrors ? validateAddress(current).errors : []);
  const message = (field: string) => shown.find((e) => e.field === field)?.message;

  function change(field: Line | "country", text: string): void {
    const next: Address = { ...current, [field]: text };
    setOwn(next);
    onChange?.(next);
  }

  const optional = (label: string) => `${label} (optional)`;
  const line = (field: Line, label: string, autoComplete: string, width?: string) => {
    const text = current[field];
    return (
      <TextField
        id={`${id}-${field}`}
        name={`${name}-${field}`}
        label={label}
        error={message(field)}
        value={value ? (text ?? "") : undefined}
        defaultValue={value ? undefined : (text ?? "")}
        onChange={(next) => change(field, next)}
        onBlur={onBlur}
        autoComplete={autoComplete}
        spellCheck={field === "postcode" ? false : undefined}
        disabled={disabled}
        className={width}
      />
    );
  };

  return (
    <Fieldset id={id} legend={legend} hint={hint} isPageHeading={isPageHeading} className={className ? `fune-address ${className}` : "fune-address"}>
      {line("line1", "Address line 1", "address-line1")}
      {line("line2", optional("Address line 2"), "address-line2")}
      {line("town", "Town or city", "address-level2", "fune-field--width-20")}
      {line("region", optional(format.regionLabel), "address-level1", "fune-field--width-20")}
      {line("postcode", format.postcodeRequired ? format.postcodeLabel : optional(format.postcodeLabel), "postal-code", "fune-field--width-10")}
      {countries ? (
        <Select
          id={`${id}-country`}
          name={`${name}-country`}
          label="Country"
          options={countries}
          placeholder="Choose a country"
          error={message("country")}
          value={value ? current.country : undefined}
          defaultValue={value ? undefined : current.country}
          onChange={(next) => change("country", next)}
          onBlur={onBlur}
          autoComplete="country"
          disabled={disabled}
        />
      ) : (
        <input type="hidden" name={`${name}-country`} value={current.country} readOnly />
      )}
    </Fieldset>
  );
}