All files / src/components/form ChoiceField.tsx

100% Statements 17/17
100% Branches 22/22
100% Functions 7/7
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122                                                                          1728x 1185x   5960x   5960x 1728x 1185x 1185x 1185x     1185x   1185x                                                     3354x 3354x               32x 32x                                                                  
// One choice from a few options, as a row of toggle buttons (Design canvas:
// the room count on "Uusi asunto"), bound to a TanStack Form field. Errors
// are reason codes, shown under the group like TextField's.
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import FormHelperText from '@mui/material/FormHelperText'
import Typography from '@mui/material/Typography'
import { useSelector, type AnyFieldApi } from '@tanstack/react-form'
import { reasonText, type Reason } from '#/lib/reasons'
import { colors, radii } from '#/theme/tokens'
import { firstReason } from './reason'
 
export interface Choice<T> {
  value: T
  label: string
}
 
interface Props<T> {
  field: AnyFieldApi
  label: string
  choices: readonly Choice<T>[]
  /** An error from outside the form's validators, e.g. a server's. */
  reason?: Reason | undefined
  /** One choice per row, for long labels or many choices. */
  stacked?: boolean
  /** Chips that wrap onto more rows, for many short choices. */
  wrap?: boolean
}
 
export function ChoiceField<T extends string | number>({
  field,
  label,
  choices,
  reason,
  stacked = false,
  wrap = false,
}: Props<T>) {
  const errors = useSelector(field.store, (s): unknown[] => s.meta.errors)
  const submitted = useSelector(
    field.form.store,
    (s) => s.submissionAttempts > 0,
  )
  const submitting = useSelector(field.form.store, (s) => s.isSubmitting)
  const value = useSelector(field.store, (s): unknown => s.value)
  const name = String(field.name)
  const labelId = `${name}-label`
  const helperId = `${name}-helper-text`
 
  // A choice can't be half-made, so errors show only after submitting.
  const shown = reason ?? (submitted ? firstReason(errors) : undefined)
 
  return (
    <Box
      role="group"
      aria-labelledby={labelId}
      aria-describedby={shown === undefined ? undefined : helperId}
      sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}
    >
      <Typography
        id={labelId}
        variant="body2"
        component="span"
        sx={{ fontWeight: 800, color: 'text.secondary' }}
      >
        {label}
      </Typography>
      <Box
        sx={
          wrap
            ? { display: 'flex', flexWrap: 'wrap', gap: 0.75 }
            : {
                display: 'grid',
                gridTemplateColumns: `repeat(${String(stacked ? 1 : choices.length)}, minmax(0, 1fr))`,
                gap: 0.75,
              }
        }
      >
        {choices.map((choice) => {
          const pressed = choice.value === value
          return (
            <Button
              key={choice.value}
              type="button"
              variant="outlined"
              aria-pressed={pressed}
              disabled={submitting}
              onClick={() => {
                field.handleChange(choice.value)
                field.handleBlur()
              }}
              // The theme's outlined button, with the pressed one in plum.
              sx={{
                minWidth: 0,
                paddingInline: wrap ? 2 : 1,
                borderRadius: wrap ? 999 : `${String(radii.input)}px`,
                fontSize: 14,
                fontWeight: 800,
                ...(shown === undefined ? {} : { borderColor: 'error.main' }),
                ...(pressed
                  ? {
                      bgcolor: 'primary.main',
                      borderColor: 'primary.main',
                      color: 'primary.contrastText',
                      '&:hover': { bgcolor: 'primary.main' },
                    }
                  : { '&:hover': { bgcolor: colors.sand } }),
              }}
            >
              {choice.label}
            </Button>
          )
        })}
      </Box>
      {shown !== undefined && (
        <FormHelperText id={helperId} error sx={{ mx: '14px' }}>
          {reasonText(shown).text}
        </FormHelperText>
      )}
    </Box>
  )
}