feat: autofill all fields on enter details and countryselector clean up

This commit is contained in:
Simon Emanuelsson
2025-05-06 08:43:15 +02:00
parent 81c2afe570
commit 4d41d4fd92
9 changed files with 290 additions and 33 deletions

View File

@@ -10,17 +10,9 @@ export default function AutoFillDetector() {
} = useFormContext()
useEffect(() => {
const dirtyFieldKeys = Object.keys(dirtyFields)
const touchedFieldKeys = Object.keys(touchedFields)
const hasDirtyUnTouchedFields = dirtyFieldKeys.some(
(field) => !touchedFieldKeys.includes(field)
)
const subscription = watch((_, field) => {
if (!field.type) {
if (isDirty && hasDirtyUnTouchedFields) {
trigger(field.name)
trigger("countryCode")
}
if (field.name && dirtyFields[field.name] && !touchedFields[field.name]) {
trigger(field.name)
}
})

View File

@@ -112,6 +112,7 @@ export default function Details({ user }: DetailsProps) {
})}
</Footnote>
<Input
autoComplete="given-name"
label={intl.formatMessage({
defaultMessage: "First name",
})}
@@ -121,6 +122,7 @@ export default function Details({ user }: DetailsProps) {
registerOptions={{ required: true, onBlur: updateDetailsStore }}
/>
<Input
autoComplete="family-name"
label={intl.formatMessage({
defaultMessage: "Last name",
})}
@@ -139,6 +141,7 @@ export default function Details({ user }: DetailsProps) {
registerOptions={{ required: true, onBlur: updateDetailsStore }}
/>
<Input
autoComplete="email"
className={styles.fullWidth}
label={intl.formatMessage({
defaultMessage: "Email address",

View File

@@ -0,0 +1,158 @@
.select {
background-color: var(--Surface-UI-Fill-Default);
border: 1px solid var(--Border-Interactive-Default);
border-radius: var(--Corner-radius-md);
position: relative;
&[data-required] .label::after {
content: " *";
}
&[data-open] {
.chevron {
rotate: -90deg;
}
}
&[data-focused] {
border-color: var(--Border-Interactive-Focus);
.button,
.input {
outline: none;
}
.input {
min-height: 18px;
}
.label {
color: var(--Text-Interactive-Focus);
}
}
&[data-disabled] {
.inner {
background-color: var(--Surface-Primary-Disabled);
color: var(--Text-Interactive-Disabled);
}
.button,
.input,
.label {
color: var(--Text-Interactive-Disabled);
}
}
&[data-invalid] {
border-color: var(--Border-Interactive-Error);
}
}
.inner {
align-items: center;
box-sizing: border-box;
display: flex;
gap: var(--Space-x1);
height: 56px;
padding: var(--Space-x15);
width: 100%;
}
.displayText {
cursor: text;
display: flex;
gap: calc(var(--Space-x05) / 2);
flex: 1;
flex-direction: column;
height: 100%;
justify-content: center;
position: relative;
}
.label {
color: var(--Text-Interactive-Placeholder);
transition: font-size 150ms ease;
white-space: nowrap;
&.labelValue {
display: none;
}
&.labelEmpty {
display: none;
}
}
.inner:has(input:placeholder-shown, input[data-focused="true"], input:valid)
.labelValue {
display: initial;
}
.inner:has(input[value=""]:not([data-focused="true"])) .labelEmpty {
display: initial;
}
.input {
background: none;
border: 0;
height: 0;
min-height: 0;
padding: 0;
transition: min-height 150ms ease;
width: 100%;
&[value]:not([value=""]) {
min-height: 18px;
}
}
.button {
background: none;
border: 0;
padding: 0;
}
.chevron {
rotate: 90deg;
}
.popover {
background-color: var(--Surface-Primary-Default);
border-radius: var(--Corner-radius-md);
box-shadow: 0 0 14px 6px rgb(0 0 0 / 10%);
display: inline-flex;
flex-direction: column;
gap: var(--Space-x1);
min-width: 280px;
outline: none;
overflow: auto;
padding: var(--Space-x2);
scrollbar-color: var(--Icon-Interactive-Disabled);
scrollbar-width: thin;
}
.listBox {
display: flex;
flex-direction: column;
gap: var(--Space-x1);
outline: none;
}
.listBoxItem {
align-items: center;
border-radius: var(--Corner-radius-md);
color: var(--Text-Default);
display: flex;
gap: var(--Space-x1);
padding: var(--Space-x1) var(--Space-x1) var(--Space-x1) var(--Space-x15);
&[data-focused] {
outline: none;
}
&[data-focused],
&[data-hovered] {
background-color: var(--Surface-Primary-Hover);
}
}

View File

@@ -1,6 +1,7 @@
import type { RegisterOptions } from "react-hook-form"
export type CountryProps = {
autoComplete?: string
className?: string
label: string
name?: string

View File

@@ -1,11 +1,21 @@
"use client"
import { useMemo, useState } from "react"
import { useFilter } from "react-aria-components"
import { useController, useFormContext } from "react-hook-form"
import { type SyntheticEvent, useMemo, useState } from "react"
import {
Button,
ComboBox,
Input,
Label,
ListBox,
ListBoxItem,
Popover,
useFilter,
} from "react-aria-components"
import { useController } from "react-hook-form"
import { useIntl } from "react-intl"
import { Select } from "@scandic-hotels/design-system/Select"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { countries } from "@/constants/countries"
@@ -13,9 +23,14 @@ import useLang from "@/hooks/useLang"
import ErrorMessage from "../ErrorMessage"
import styles from "./country.module.css"
import type { CountryProps } from "./country"
const prioCountryCode = ["DE", "DK", "FI", "NO", "SE"]
export default function CountrySelect({
autoComplete = "country-name",
className = "",
label,
name = "country",
@@ -27,42 +42,124 @@ export default function CountrySelect({
const { startsWith } = useFilter({ sensitivity: "base" })
const [filterValue, setFilterValue] = useState("")
const { control, setValue } = useFormContext()
const { field, formState, fieldState } = useController({
control,
name,
rules: registerOptions,
})
const items = useMemo(() => {
const collator = new Intl.Collator(lang)
return countries
.map((country) => ({
function mapCountry(country: (typeof countries)[number]) {
return {
value: country.code,
label:
intl.formatDisplayName(country.code, { type: "region" }) ||
country.name,
}))
}
}
const collator = new Intl.Collator(lang)
const prioCountries = countries
.filter((c) => prioCountryCode.includes(c.code))
.map(mapCountry)
.filter((item) => startsWith(item.label, filterValue))
.sort((a, b) => collator.compare(a.label, b.label))
const restCountries = countries
.filter((c) => !prioCountryCode.includes(c.code))
.map(mapCountry)
.filter((item) => startsWith(item.label, filterValue))
.sort((a, b) => collator.compare(a.label, b.label))
return [...prioCountries, ...restCountries]
}, [filterValue, intl, lang, startsWith])
function handleOnInput(evt: SyntheticEvent<HTMLInputElement>) {
setFilterValue(evt.currentTarget.value)
const isAutoCompleteEvent = !("inputType" in evt.nativeEvent)
if (isAutoCompleteEvent) {
const { value } = evt.currentTarget
const cc = countries.find((c) => c.name === value || c.code === value)
if (cc) {
field.onChange(cc.code)
}
}
}
return (
<div className={className}>
<Select
label={label}
items={items}
enableFiltering
isRequired={Boolean(registerOptions?.required)}
isInvalid={fieldState.invalid}
name={field.name}
onBlur={field.onBlur}
onSelectionChange={(country) => setValue(name, country ?? "")}
selectedKey={field.value}
<ComboBox
aria-label={label}
className={styles.select}
data-testid={name}
isReadOnly={readOnly}
onInputChange={setFilterValue}
/>
isRequired={Boolean(registerOptions?.required)}
isInvalid={fieldState.invalid}
name={name}
onBlur={field.onBlur}
onSelectionChange={(c) => field.onChange(c ?? "")}
selectedKey={field.value}
>
<Label className={styles.inner}>
<div className={styles.displayText}>
<Typography variant="Label/xsRegular">
<span className={`${styles.label} ${styles.labelValue}`}>
{label}
</span>
</Typography>
<Typography variant="Body/Paragraph/mdRegular">
<span className={`${styles.label} ${styles.labelEmpty}`}>
{label}
</span>
</Typography>
<Typography variant="Body/Paragraph/mdRegular">
<Input
autoComplete={autoComplete}
className={styles.input}
onInput={handleOnInput}
ref={field.ref}
/>
</Typography>
</div>
<Button className={styles.button}>
<MaterialIcon
aria-hidden="true"
className={styles.chevron}
color="Icon/Default"
icon="chevron_right"
size={24}
/>
</Button>
</Label>
<Popover
className={styles.popover}
crossOffset={-8}
offset={22}
shouldFlip={false}
>
<ListBox className={styles.listBox}>
{items.map((item) => (
<ListBoxItem
className={styles.listBoxItem}
key={item.value}
id={item.value}
textValue={item.label}
>
{({ isSelected }) => (
<Typography
variant={
isSelected
? "Body/Paragraph/mdBold"
: "Body/Paragraph/mdRegular"
}
>
<span>{item.label}</span>
</Typography>
)}
</ListBoxItem>
))}
</ListBox>
</Popover>
</ComboBox>
<ErrorMessage errors={formState.errors} name={name} />
</div>
)

View File

@@ -19,6 +19,7 @@ import type { InputProps } from "./input"
const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
{
"aria-label": ariaLabel,
autoComplete,
className = "",
disabled = false,
helpText = "",
@@ -65,6 +66,7 @@ const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
{...field}
ref={ref}
aria-labelledby={field.name}
autoComplete={autoComplete}
id={field.name}
label={label}
maxLength={maxLength}

View File

@@ -141,6 +141,7 @@ export default function Phone({
>
<AriaInputWithLabel
{...field}
autoComplete="tel-national"
id={field.name}
label={label}
onChange={handleChange}

View File

@@ -27,6 +27,7 @@ export function SelectFilter({
onSelectionChange = () => undefined,
onFocus = () => undefined,
onBlur = () => undefined,
autoComplete,
...props
}: SelectFilterProps) {
const [focus, setFocus] = useState(false)
@@ -73,7 +74,7 @@ export function SelectFilter({
<span className={styles.label}>{label}</span>
</Typography>
<Typography variant="Body/Paragraph/mdRegular">
<Input className={styles.input} />
<Input className={styles.input} autoComplete={autoComplete} />
</Typography>
</span>
<Button className={styles.button}>

View File

@@ -10,6 +10,7 @@ interface Item extends Record<string, unknown> {
}
export interface SelectProps extends ComponentProps<typeof Select> {
autoComplete?: string
icon?: MaterialIconProps['icon']
itemIcon?: MaterialIconProps['icon']
items: Item[]
@@ -24,6 +25,7 @@ export interface SelectItemProps extends ComponentProps<typeof ListBoxItem> {
}
export interface SelectFilterProps extends ComponentProps<typeof ComboBox> {
autoComplete?: string
icon?: MaterialIconProps['icon']
itemIcon?: MaterialIconProps['icon']
items: Item[]