@graphcommerce/address-autocomplete 10.1.0-canary.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @graphcommerce/address-autocomplete
2
+
3
+ ## 10.1.0-canary.42
4
+
5
+ ### Minor Changes
6
+
7
+ - [#2653](https://github.com/graphcommerce-org/graphcommerce/pull/2653) [`18ef8ef`](https://github.com/graphcommerce-org/graphcommerce/commit/18ef8ef45d244aa480508db9377f4fa83e651734) - Adds Google Places address autocomplete to customer and checkout address forms. Selected addresses populate GraphCommerce address fields and Magento regions, with automatic fallback to manual entry when Google Maps is unavailable. ([@hsngdz](https://github.com/hsngdz))
@@ -0,0 +1,6 @@
1
+ extend input GraphCommerceConfig {
2
+ """
3
+ Google Maps API key for address autocomplete. This is required for the address autocomplete to work.
4
+ """
5
+ googleMapsApiKey: String
6
+ }
package/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # @graphcommerce/address-autocomplete
2
+
3
+ Adds Google Places address autocomplete to GraphCommerce customer and checkout
4
+ address forms.
5
+
6
+ When a customer selects an address, the package fills the street, house number,
7
+ addition, postcode, city, country, and Magento region fields. If Google Maps is
8
+ not configured or cannot be loaded, the standard manual street field remains
9
+ available.
10
+
11
+ ## Installation
12
+
13
+ Install the package using the same version as the other GraphCommerce packages
14
+ in your project:
15
+
16
+ ```bash
17
+ yarn add @graphcommerce/address-autocomplete
18
+ ```
19
+
20
+ Run code generation after installing the package:
21
+
22
+ ```bash
23
+ yarn codegen
24
+ ```
25
+
26
+ The package uses the GraphCommerce plugin system, so no component overrides are
27
+ required.
28
+
29
+ Google Maps is loaded directly with the official `@googlemaps/js-api-loader`.
30
+
31
+ ## Google Maps setup
32
+
33
+ Create a Google Maps API key with the Places API (New) enabled. Restrict the key
34
+ to the domains where the storefront is hosted.
35
+
36
+ Add the key to `graphcommerce.config.ts`:
37
+
38
+ ```ts
39
+ import type { GraphCommerceConfig } from '@graphcommerce/next-config'
40
+
41
+ const config: Partial<GraphCommerceConfig> = {
42
+ googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY,
43
+ }
44
+
45
+ export default config
46
+ ```
47
+
48
+ Restart code generation and the development server after changing the
49
+ configuration.
50
+
51
+ See [Config.graphqls](./Config.graphqls) for the available configuration fields.
52
+
53
+ ## Behavior
54
+
55
+ The plugin replaces the standard `AddressStreet` field only when
56
+ `googleMapsApiKey` is configured. It:
57
+
58
+ - loads the Google Maps Places library directly with
59
+ `@googlemaps/js-api-loader`;
60
+ - requests predictions through the Places API (New) `AutocompleteSuggestion`
61
+ interface;
62
+ - starts searching after three characters and debounces requests by 250 ms;
63
+ - limits suggestions to addresses;
64
+ - uses the browser's preferred language for suggestions;
65
+ - keeps the GraphCommerce `TextFieldElement` and renders predictions in a custom
66
+ Material UI popper;
67
+ - supports mouse and keyboard selection with the required combobox attributes;
68
+ - displays the required Google Maps attribution with the predictions;
69
+ - groups prediction and place-detail requests into autocomplete sessions;
70
+ - retrieves the selected address through `Place.fetchFields()`;
71
+ - maps Google address components to GraphCommerce address fields;
72
+ - splits a street-number suffix into the addition field when Google does not
73
+ provide a separate subpremise, for example `221B` becomes house number `221`
74
+ and addition `B`;
75
+ - resolves the Google region to the corresponding Magento region ID;
76
+ - preserves the standard field styling and validation behavior;
77
+ - suppresses browser address autofill from competing with Google suggestions;
78
+ and
79
+ - falls back to the original manual field if the API is unavailable.
80
+
81
+ ## Public API
82
+
83
+ The main package export provides:
84
+
85
+ - `AddressAutocomplete` — Google-assisted street field with a required fallback;
86
+ - `formatAddress` — converts Google address components to a normalized address;
87
+ - `addressValues` — converts a normalized address to form values; and
88
+ - `findRegionId` — matches a Google region to a Magento region ID.
89
+
90
+ The GraphCommerce plugin is available from:
91
+
92
+ ```ts
93
+ @graphcommerce/address-autocomplete/plugins/AddAddressAutocompleteAddressFields
94
+ ```
95
+
96
+ It is discovered automatically during code generation and normally does not need
97
+ to be imported directly.
98
+
99
+ ## Troubleshooting
100
+
101
+ ### Suggestions are not displayed
102
+
103
+ Check that:
104
+
105
+ - the global `googleMapsApiKey` is configured;
106
+ - the Places API (New) is enabled for the Google Cloud project;
107
+ - the API key allows the storefront domain; and
108
+ - billing is enabled for the Google Cloud project.
109
+
110
+ The manual street field is displayed when the key is missing or the Google Maps
111
+ script cannot be loaded. Loading and request errors are logged to the browser
112
+ console without showing an error message to the customer.
113
+
114
+ ### Google Maps attribution
115
+
116
+ The suggestions popper displays Google Maps content without an accompanying
117
+ Google Map. The `Google Maps` attribution shown with the predictions is
118
+ therefore required and should not be removed, hidden, or translated.
119
+
120
+ ### A selected region is not filled
121
+
122
+ The package matches regions by country, region code, and normalized region name.
123
+ Verify that the region exists in Magento and that its code or name corresponds
124
+ to the value returned by Google.
@@ -0,0 +1,292 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import { act } from 'react'
4
+ import type { Root } from 'react-dom/client'
5
+ import { createRoot } from 'react-dom/client'
6
+ import { AddressAutocomplete } from './AddressAutocomplete'
7
+
8
+ const { loaderOptions } = vi.hoisted(() => ({
9
+ loaderOptions: [] as unknown[],
10
+ }))
11
+ const { fetchAutocompleteSuggestions, importLibrary, setValue } = vi.hoisted(() => ({
12
+ fetchAutocompleteSuggestions: vi.fn(),
13
+ importLibrary: vi.fn(),
14
+ setValue: vi.fn(),
15
+ }))
16
+
17
+ vi.mock('@graphcommerce/ecommerce-ui', () => ({
18
+ TextFieldElement: ({
19
+ inputProps,
20
+ inputRef,
21
+ name,
22
+ onChange,
23
+ onFocus,
24
+ onKeyDown,
25
+ variant,
26
+ }: {
27
+ inputProps?: React.InputHTMLAttributes<HTMLInputElement>
28
+ inputRef?: React.Ref<HTMLInputElement>
29
+ name: string
30
+ onChange?: React.ChangeEventHandler<HTMLInputElement>
31
+ onFocus?: React.FocusEventHandler<HTMLInputElement>
32
+ onKeyDown?: React.KeyboardEventHandler<HTMLInputElement>
33
+ variant: string
34
+ }) => (
35
+ <input
36
+ ref={inputRef}
37
+ aria-label='Street'
38
+ data-variant={variant}
39
+ name={name}
40
+ onChange={onChange}
41
+ onFocus={onFocus}
42
+ onKeyDown={onKeyDown}
43
+ {...inputProps}
44
+ />
45
+ ),
46
+ }))
47
+
48
+ vi.mock('@graphcommerce/graphql', () => ({
49
+ useQuery: () => ({ data: undefined }),
50
+ }))
51
+
52
+ vi.mock('@graphcommerce/magento-customer', () => ({
53
+ useAddressFieldsForm: () => ({
54
+ control: {},
55
+ getValues: () => '',
56
+ name: {
57
+ street: 'street',
58
+ houseNumber: 'houseNumber',
59
+ addition: 'addition',
60
+ postcode: 'postcode',
61
+ city: 'city',
62
+ countryCode: 'countryCode',
63
+ regionId: 'regionId',
64
+ },
65
+ readOnly: false,
66
+ required: { street: true },
67
+ setValue,
68
+ }),
69
+ }))
70
+
71
+ vi.mock('@graphcommerce/next-config/config', () => ({
72
+ googleMapsApiKey: 'test-key',
73
+ }))
74
+
75
+ vi.mock('@graphcommerce/magento-store', () => ({
76
+ CountryRegionsDocument: {},
77
+ }))
78
+
79
+ vi.mock('@lingui/core/macro', () => ({
80
+ t: (strings: TemplateStringsArray) => strings.join(''),
81
+ }))
82
+
83
+ vi.mock('@lingui/react/macro', () => ({
84
+ Trans: ({ children }: { children: React.ReactNode }) => children,
85
+ }))
86
+
87
+ vi.mock('@mui/material', () => ({
88
+ Box: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
89
+ CircularProgress: () => <span data-loading />,
90
+ ClickAwayListener: ({ children }: { children: React.ReactNode }) => children,
91
+ List: ({ children, id, role }: { children: React.ReactNode; id: string; role: string }) => (
92
+ <ul id={id} role={role}>
93
+ {children}
94
+ </ul>
95
+ ),
96
+ ListItemButton: ({
97
+ children,
98
+ id,
99
+ onClick,
100
+ onMouseDown,
101
+ onMouseEnter,
102
+ role,
103
+ }: {
104
+ children: React.ReactNode
105
+ id: string
106
+ onClick: React.MouseEventHandler<HTMLButtonElement>
107
+ onMouseDown: React.MouseEventHandler<HTMLButtonElement>
108
+ onMouseEnter: React.MouseEventHandler<HTMLButtonElement>
109
+ role: string
110
+ }) => (
111
+ <button
112
+ id={id}
113
+ type='button'
114
+ role={role}
115
+ onClick={onClick}
116
+ onMouseDown={onMouseDown}
117
+ onMouseEnter={onMouseEnter}
118
+ >
119
+ {children}
120
+ </button>
121
+ ),
122
+ ListItemText: ({
123
+ primary,
124
+ secondary,
125
+ slotProps,
126
+ }: {
127
+ primary: React.ReactNode
128
+ secondary?: React.ReactNode
129
+ slotProps?: {
130
+ primary?: { variant?: string }
131
+ secondary?: { variant?: string }
132
+ }
133
+ }) => (
134
+ <span
135
+ data-primary-variant={slotProps?.primary?.variant}
136
+ data-secondary-variant={slotProps?.secondary?.variant}
137
+ >
138
+ {primary} {secondary}
139
+ </span>
140
+ ),
141
+ Paper: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
142
+ Popper: ({ children, open }: { children: React.ReactNode; open: boolean }) =>
143
+ open ? <div data-places-popper>{children}</div> : null,
144
+ Typography: ({ children }: { children: React.ReactNode }) => <span>{children}</span>,
145
+ useEventCallback: (callback: unknown) => callback,
146
+ }))
147
+
148
+ vi.mock('@googlemaps/js-api-loader', () => ({
149
+ Loader: class {
150
+ constructor(options: unknown) {
151
+ loaderOptions.push(options)
152
+ }
153
+
154
+ importLibrary = importLibrary
155
+ },
156
+ }))
157
+
158
+ afterEach(() => {
159
+ act(() => testRoot?.unmount())
160
+ testContainer?.remove()
161
+ testRoot = undefined
162
+ testContainer = undefined
163
+ loaderOptions.length = 0
164
+ vi.useRealTimers()
165
+ vi.clearAllMocks()
166
+ })
167
+
168
+ let testRoot: Root | undefined
169
+ let testContainer: HTMLDivElement | undefined
170
+
171
+ class AutocompleteSessionToken {}
172
+
173
+ beforeAll(() => {
174
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
175
+ })
176
+
177
+ afterAll(() => {
178
+ Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT')
179
+ })
180
+
181
+ function renderAutocomplete() {
182
+ testContainer = document.createElement('div')
183
+ document.body.appendChild(testContainer)
184
+ testRoot = createRoot(testContainer)
185
+ testRoot.render(
186
+ <AddressAutocomplete
187
+ form={{} as never}
188
+ fallback={<label htmlFor='street'>Manual street input</label>}
189
+ />,
190
+ )
191
+ }
192
+
193
+ describe('AddressAutocomplete', () => {
194
+ it('keeps manual street entry available when Google Maps fails', async () => {
195
+ const error = new Error('Maps failed')
196
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined)
197
+ importLibrary.mockRejectedValue(error)
198
+
199
+ await act(async () => renderAutocomplete())
200
+
201
+ expect(testContainer?.textContent).toContain('Manual street input')
202
+ expect(testContainer?.textContent).not.toContain('Address search is unavailable')
203
+ expect(consoleError).toHaveBeenCalledWith(error)
204
+
205
+ consoleError.mockRestore()
206
+ })
207
+
208
+ it('uses the standard styled street field after Google Maps loads', async () => {
209
+ importLibrary.mockResolvedValue({
210
+ AutocompleteSessionToken,
211
+ AutocompleteSuggestion: { fetchAutocompleteSuggestions },
212
+ })
213
+ await act(async () => renderAutocomplete())
214
+
215
+ const streetInput = testContainer?.querySelector<HTMLInputElement>('input[aria-label="Street"]')
216
+ expect(streetInput).not.toBeNull()
217
+ expect(streetInput?.dataset.variant).toBe('outlined')
218
+ expect(streetInput?.getAttribute('autocomplete')).toBe('one-time-code')
219
+ expect(streetInput?.getAttribute('role')).toBe('combobox')
220
+ expect(streetInput?.name).toMatch(/^places-search-/)
221
+ expect(loaderOptions.at(-1)).toEqual({
222
+ apiKey: 'test-key',
223
+ version: 'weekly',
224
+ })
225
+ expect(importLibrary).toHaveBeenCalledWith('places')
226
+ })
227
+
228
+ it('loads new Places suggestions and fills the selected address', async () => {
229
+ vi.useFakeTimers()
230
+
231
+ const fetchFields = vi.fn().mockResolvedValue(undefined)
232
+ const place = {
233
+ addressComponents: [
234
+ { longText: 'Baker Street', shortText: 'Baker St', types: ['route'] },
235
+ { longText: '221B', shortText: '221B', types: ['street_number'] },
236
+ { longText: 'London', shortText: 'London', types: ['postal_town'] },
237
+ { longText: 'United Kingdom', shortText: 'GB', types: ['country'] },
238
+ { longText: 'NW1 6XE', shortText: 'NW1 6XE', types: ['postal_code'] },
239
+ ],
240
+ fetchFields,
241
+ }
242
+ const prediction = {
243
+ mainText: { text: '221B Baker Street' },
244
+ placeId: 'baker-street',
245
+ secondaryText: { text: 'London, UK' },
246
+ text: { text: '221B Baker Street, London, UK' },
247
+ toPlace: () => place,
248
+ }
249
+ fetchAutocompleteSuggestions.mockResolvedValue({
250
+ suggestions: [{ placePrediction: prediction }],
251
+ })
252
+ importLibrary.mockResolvedValue({
253
+ AutocompleteSessionToken,
254
+ AutocompleteSuggestion: { fetchAutocompleteSuggestions },
255
+ })
256
+
257
+ await act(async () => renderAutocomplete())
258
+
259
+ const streetInput = testContainer?.querySelector<HTMLInputElement>('input[aria-label="Street"]')
260
+ expect(streetInput).not.toBeNull()
261
+
262
+ await act(async () => {
263
+ if (!streetInput) return
264
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set
265
+ valueSetter?.call(streetInput, 'Baker')
266
+ streetInput.dispatchEvent(new Event('input', { bubbles: true }))
267
+ await vi.advanceTimersByTimeAsync(250)
268
+ })
269
+
270
+ expect(fetchAutocompleteSuggestions).toHaveBeenCalledWith({
271
+ includedPrimaryTypes: ['street_address', 'premise', 'subpremise', 'route'],
272
+ input: 'Baker',
273
+ sessionToken: expect.any(AutocompleteSessionToken),
274
+ })
275
+ expect(testContainer?.textContent).toContain('221B Baker Street')
276
+ expect(testContainer?.textContent).toContain('Google Maps')
277
+ const suggestionText = testContainer?.querySelector('[data-primary-variant]')
278
+ expect(suggestionText?.getAttribute('data-primary-variant')).toBe('body2')
279
+ expect(suggestionText?.getAttribute('data-secondary-variant')).toBe('body2')
280
+
281
+ const option = testContainer?.querySelector<HTMLButtonElement>('button[role="option"]')
282
+ await act(async () => option?.click())
283
+
284
+ expect(fetchFields).toHaveBeenCalledWith({ fields: ['addressComponents'] })
285
+ expect(setValue).toHaveBeenCalledWith('street', 'Baker Street', expect.any(Object))
286
+ expect(setValue).toHaveBeenCalledWith('houseNumber', '221', expect.any(Object))
287
+ expect(setValue).toHaveBeenCalledWith('addition', 'B', expect.any(Object))
288
+ expect(setValue).toHaveBeenCalledWith('postcode', 'NW1 6XE', expect.any(Object))
289
+ expect(setValue).toHaveBeenCalledWith('city', 'London', expect.any(Object))
290
+ expect(setValue).toHaveBeenCalledWith('countryCode', 'GB', expect.any(Object))
291
+ })
292
+ })
@@ -0,0 +1,130 @@
1
+ import { TextFieldElement } from '@graphcommerce/ecommerce-ui'
2
+ import type { FieldPath, FieldValues, PathValue } from '@graphcommerce/ecommerce-ui'
3
+ import { useQuery } from '@graphcommerce/graphql'
4
+ import type { AddressFieldsOptions } from '@graphcommerce/magento-customer'
5
+ import { useAddressFieldsForm } from '@graphcommerce/magento-customer'
6
+ import { CountryRegionsDocument } from '@graphcommerce/magento-store'
7
+ import { Trans } from '@lingui/react/macro'
8
+ import { Box, CircularProgress, ClickAwayListener, useEventCallback } from '@mui/material'
9
+ import type { ReactNode } from 'react'
10
+ import { useEffect, useRef, useState } from 'react'
11
+ import { usePlacesAutocomplete } from '../hooks/usePlacesAutocomplete'
12
+ import { addressValues } from '../utils/addressValues'
13
+ import type { FormattedAddress } from '../utils/formatAddress'
14
+ import { AddressAutocompletePopper } from './AddressAutocompletePopper'
15
+
16
+ const updateOptions = {
17
+ shouldDirty: true,
18
+ shouldTouch: true,
19
+ shouldValidate: true,
20
+ } as const
21
+
22
+ export type AddressAutocompleteProps<
23
+ TFieldValues extends FieldValues = FieldValues,
24
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
25
+ > = AddressFieldsOptions<TFieldValues, TName> & {
26
+ fallback: ReactNode
27
+ }
28
+
29
+ export function AddressAutocomplete<
30
+ TFieldValues extends FieldValues = FieldValues,
31
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
32
+ >(options: AddressAutocompleteProps<TFieldValues, TName>) {
33
+ const { fallback } = options
34
+ const form = useAddressFieldsForm<TFieldValues, TName>(options)
35
+ const { control, getValues, name, readOnly, required, setValue } = form
36
+ const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null)
37
+ const pendingRegion = useRef<FormattedAddress | null>(null)
38
+ const countries = useQuery(CountryRegionsDocument).data?.countries
39
+
40
+ const onAddress = useEventCallback((address: FormattedAddress) => {
41
+ const values = addressValues(address, countries)
42
+ const updateValue = (fieldName: TName, value: unknown) => {
43
+ setValue(fieldName, value as PathValue<TFieldValues, TName>, updateOptions)
44
+ }
45
+
46
+ updateValue(name.regionId, null)
47
+ updateValue(name.street, values.street)
48
+ updateValue(name.houseNumber, values.houseNumber)
49
+ updateValue(name.addition, values.addition)
50
+ updateValue(name.postcode, values.postcode)
51
+ updateValue(name.city, values.city)
52
+ updateValue(name.countryCode, values.countryCode)
53
+ if (countries) {
54
+ updateValue(name.regionId, values.regionId)
55
+ pendingRegion.current = null
56
+ } else {
57
+ pendingRegion.current = address
58
+ }
59
+ })
60
+
61
+ const places = usePlacesAutocomplete({ onAddress })
62
+
63
+ useEffect(() => {
64
+ const address = pendingRegion.current
65
+ if (!address || !countries) return
66
+
67
+ pendingRegion.current = null
68
+ if (getValues(name.countryCode) !== address.country) return
69
+
70
+ setValue(
71
+ name.regionId,
72
+ addressValues(address, countries).regionId as PathValue<TFieldValues, TName>,
73
+ updateOptions,
74
+ )
75
+ }, [countries, getValues, name.countryCode, name.regionId, setValue])
76
+
77
+ return (
78
+ <>
79
+ {places.autocompleteAvailable ? (
80
+ <ClickAwayListener onClickAway={places.closeSuggestions}>
81
+ <Box ref={setAnchorElement} sx={{ position: 'relative', width: '100%' }}>
82
+ <TextFieldElement
83
+ sx={{ width: '100%' }}
84
+ variant='outlined'
85
+ control={control}
86
+ required={required[name.street]}
87
+ name={name.street}
88
+ type='text'
89
+ label={<Trans>Street</Trans>}
90
+ showValid={!places.loading}
91
+ onChange={places.onChange}
92
+ onFocus={places.onFocus}
93
+ onKeyDown={places.onKeyDown}
94
+ inputProps={{
95
+ 'aria-activedescendant':
96
+ places.activeIndex >= 0
97
+ ? `${places.listboxId}-option-${places.activeIndex}`
98
+ : undefined,
99
+ 'aria-autocomplete': 'list',
100
+ 'aria-busy': places.loading,
101
+ 'aria-controls': places.listboxOpen ? places.listboxId : undefined,
102
+ 'aria-expanded': places.listboxOpen,
103
+ 'aria-haspopup': 'listbox',
104
+ role: 'combobox',
105
+ // Force disabling browser autocomplete so it does not compete with Google suggestions.
106
+ autoComplete: 'one-time-code',
107
+ name: places.addressSearchName,
108
+ }}
109
+ InputProps={{
110
+ readOnly,
111
+ endAdornment: places.loading ? <CircularProgress size={20} /> : undefined,
112
+ }}
113
+ />
114
+ <AddressAutocompletePopper
115
+ activeIndex={places.activeIndex}
116
+ anchorElement={anchorElement}
117
+ listboxId={places.listboxId}
118
+ open={places.listboxOpen}
119
+ predictions={places.predictions}
120
+ onActiveIndexChange={places.setActiveIndex}
121
+ onSelect={(prediction) => void places.selectPrediction(prediction)}
122
+ />
123
+ </Box>
124
+ </ClickAwayListener>
125
+ ) : (
126
+ fallback
127
+ )}
128
+ </>
129
+ )
130
+ }
@@ -0,0 +1,69 @@
1
+ /// <reference types="google.maps" />
2
+ import { Box, List, ListItemButton, ListItemText, Paper, Popper, Typography } from '@mui/material'
3
+
4
+ export type AddressAutocompletePopperProps = {
5
+ activeIndex: number
6
+ anchorElement: HTMLElement | null
7
+ listboxId: string
8
+ open: boolean
9
+ predictions: google.maps.places.PlacePrediction[]
10
+ onActiveIndexChange: (index: number) => void
11
+ onSelect: (prediction: google.maps.places.PlacePrediction) => void
12
+ }
13
+
14
+ export function AddressAutocompletePopper({
15
+ activeIndex,
16
+ anchorElement,
17
+ listboxId,
18
+ open,
19
+ predictions,
20
+ onActiveIndexChange,
21
+ onSelect,
22
+ }: AddressAutocompletePopperProps) {
23
+ return (
24
+ <Popper
25
+ anchorEl={anchorElement}
26
+ open={open}
27
+ placement='bottom-start'
28
+ sx={(theme) => ({
29
+ width: anchorElement?.offsetWidth,
30
+ zIndex: theme.zIndex.modal + 1,
31
+ })}
32
+ >
33
+ <Paper elevation={8}>
34
+ <List id={listboxId} role='listbox' disablePadding>
35
+ {predictions.map((prediction, index) => (
36
+ <ListItemButton
37
+ id={`${listboxId}-option-${index}`}
38
+ // A session returns unique place IDs, so this is stable within the list.
39
+ key={prediction.placeId}
40
+ role='option'
41
+ aria-selected={index === activeIndex}
42
+ selected={index === activeIndex}
43
+ onMouseDown={(event) => event.preventDefault()}
44
+ onMouseEnter={() => onActiveIndexChange(index)}
45
+ onClick={() => onSelect(prediction)}
46
+ >
47
+ <ListItemText
48
+ primary={prediction.mainText?.text ?? prediction.text.text}
49
+ secondary={prediction.secondaryText?.text}
50
+ slotProps={{
51
+ primary: { variant: 'body2' },
52
+ secondary: { variant: 'body2' },
53
+ }}
54
+ />
55
+ </ListItemButton>
56
+ ))}
57
+ <Box sx={{ display: 'flex', justifyContent: 'flex-end', px: 1.25, py: 0.625 }}>
58
+ <Typography
59
+ translate='no'
60
+ sx={{ color: 'text.secondary', typography: 'caption', whiteSpace: 'nowrap' }}
61
+ >
62
+ Google Maps
63
+ </Typography>
64
+ </Box>
65
+ </List>
66
+ </Paper>
67
+ </Popper>
68
+ )
69
+ }
@@ -0,0 +1,177 @@
1
+ import { googleMapsApiKey } from '@graphcommerce/next-config/config'
2
+ import { Loader } from '@googlemaps/js-api-loader'
3
+ import { useEventCallback } from '@mui/material'
4
+ import type { ChangeEvent, KeyboardEvent } from 'react'
5
+ import { useEffect, useId, useRef, useState } from 'react'
6
+ import type { FormattedAddress } from '../utils/formatAddress'
7
+ import { formatAddress } from '../utils/formatAddress'
8
+
9
+ const addressPrimaryTypes = ['street_address', 'premise', 'subpremise', 'route']
10
+ const requestDelay = 250
11
+
12
+ type PlacesAutocompleteLibrary = Pick<
13
+ google.maps.PlacesLibrary,
14
+ 'AutocompleteSessionToken' | 'AutocompleteSuggestion'
15
+ >
16
+
17
+ export type UsePlacesAutocompleteOptions = {
18
+ onAddress: (address: FormattedAddress) => void
19
+ }
20
+
21
+ export function usePlacesAutocomplete({ onAddress }: UsePlacesAutocompleteOptions) {
22
+ const [placesLibrary, setPlacesLibrary] = useState<PlacesAutocompleteLibrary>()
23
+ const [isLoaded, setIsLoaded] = useState(false)
24
+ const [predictions, setPredictions] = useState<google.maps.places.PlacePrediction[]>([])
25
+ const [searchValue, setSearchValue] = useState('')
26
+ const [loading, setLoading] = useState(false)
27
+ const [open, setOpen] = useState(false)
28
+ const [activeIndex, setActiveIndex] = useState(-1)
29
+ const sessionToken = useRef<google.maps.places.AutocompleteSessionToken | undefined>(undefined)
30
+ const requestNumber = useRef(0)
31
+ const addressSearchName = `places-search-${useId()}`
32
+ const listboxId = `places-listbox-${useId()}`
33
+
34
+ useEffect(() => {
35
+ if (!googleMapsApiKey) return undefined
36
+
37
+ let active = true
38
+ const loader = new Loader({ apiKey: googleMapsApiKey, version: 'weekly' })
39
+ void loader
40
+ .importLibrary('places')
41
+ .then((library) => {
42
+ if (!active) return
43
+ setPlacesLibrary(library)
44
+ setIsLoaded(true)
45
+ })
46
+ .catch((error: unknown) => {
47
+ if (!active) return
48
+ setIsLoaded(false)
49
+ console.error(error)
50
+ })
51
+
52
+ return () => {
53
+ active = false
54
+ }
55
+ }, [])
56
+
57
+ useEffect(() => {
58
+ const input = searchValue.trim()
59
+ const currentRequest = ++requestNumber.current
60
+
61
+ if (!placesLibrary || input.length < 3) {
62
+ setLoading(false)
63
+ setPredictions([])
64
+ setActiveIndex(-1)
65
+ if (!input) sessionToken.current = undefined
66
+ return undefined
67
+ }
68
+
69
+ setLoading(true)
70
+ const timeout = window.setTimeout(() => {
71
+ sessionToken.current ??= new placesLibrary.AutocompleteSessionToken()
72
+
73
+ void placesLibrary.AutocompleteSuggestion.fetchAutocompleteSuggestions({
74
+ includedPrimaryTypes: addressPrimaryTypes,
75
+ input,
76
+ sessionToken: sessionToken.current,
77
+ })
78
+ .then(({ suggestions }) => {
79
+ if (currentRequest !== requestNumber.current) return
80
+
81
+ const nextPredictions = suggestions.flatMap((suggestion) =>
82
+ suggestion.placePrediction ? [suggestion.placePrediction] : [],
83
+ )
84
+ setPredictions(nextPredictions)
85
+ setActiveIndex(-1)
86
+ setOpen(nextPredictions.length > 0)
87
+ })
88
+ .catch((error: unknown) => {
89
+ if (currentRequest !== requestNumber.current) return
90
+ setPredictions([])
91
+ setOpen(false)
92
+ console.error(error)
93
+ })
94
+ .finally(() => {
95
+ if (currentRequest === requestNumber.current) setLoading(false)
96
+ })
97
+ }, requestDelay)
98
+
99
+ return () => window.clearTimeout(timeout)
100
+ }, [placesLibrary, searchValue])
101
+
102
+ const selectPrediction = useEventCallback(
103
+ async (prediction: google.maps.places.PlacePrediction) => {
104
+ requestNumber.current += 1
105
+ setLoading(false)
106
+ setOpen(false)
107
+ setPredictions([])
108
+ setActiveIndex(-1)
109
+
110
+ try {
111
+ const place = prediction.toPlace()
112
+ await place.fetchFields({ fields: ['addressComponents'] })
113
+ if (place.addressComponents) {
114
+ onAddress(formatAddress({ addressComponents: place.addressComponents }))
115
+ }
116
+ } catch (error) {
117
+ console.error(error)
118
+ } finally {
119
+ sessionToken.current = undefined
120
+ }
121
+ },
122
+ )
123
+
124
+ const closeSuggestions = useEventCallback(() => {
125
+ setOpen(false)
126
+ setActiveIndex(-1)
127
+ sessionToken.current = undefined
128
+ })
129
+
130
+ const onChange = useEventCallback((event: ChangeEvent<HTMLInputElement>) => {
131
+ setSearchValue(event.target.value)
132
+ })
133
+
134
+ const onFocus = useEventCallback(() => {
135
+ setOpen(predictions.length > 0)
136
+ })
137
+
138
+ const onKeyDown = useEventCallback((event: KeyboardEvent<HTMLInputElement>) => {
139
+ if (event.key === 'Escape' || event.key === 'Tab') {
140
+ closeSuggestions()
141
+ return
142
+ }
143
+ if (!predictions.length) return
144
+
145
+ if (event.key === 'ArrowDown') {
146
+ event.preventDefault()
147
+ setOpen(true)
148
+ setActiveIndex((current) => (current + 1) % predictions.length)
149
+ } else if (event.key === 'ArrowUp') {
150
+ event.preventDefault()
151
+ setOpen(true)
152
+ setActiveIndex((current) => (current <= 0 ? predictions.length - 1 : current - 1))
153
+ } else if (event.key === 'Enter' && open && activeIndex >= 0) {
154
+ event.preventDefault()
155
+ void selectPrediction(predictions[activeIndex])
156
+ }
157
+ })
158
+
159
+ const autocompleteAvailable = Boolean(googleMapsApiKey && isLoaded)
160
+ const listboxOpen = autocompleteAvailable && open && predictions.length > 0
161
+
162
+ return {
163
+ activeIndex,
164
+ addressSearchName,
165
+ autocompleteAvailable,
166
+ closeSuggestions,
167
+ listboxId,
168
+ listboxOpen,
169
+ loading,
170
+ onChange,
171
+ onFocus,
172
+ onKeyDown,
173
+ predictions,
174
+ selectPrediction,
175
+ setActiveIndex,
176
+ }
177
+ }
package/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './components/AddressAutocomplete'
2
+ export * from './utils/addressValues'
3
+ export * from './utils/findRegionId'
4
+ export * from './utils/formatAddress'
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@graphcommerce/address-autocomplete",
3
+ "homepage": "https://www.graphcommerce.org/",
4
+ "repository": "github:graphcommerce-org/graphcommerce",
5
+ "version": "10.1.0-canary.42",
6
+ "sideEffects": false,
7
+ "prettier": "@graphcommerce/prettier-config-pwa",
8
+ "eslintConfig": {
9
+ "extends": "@graphcommerce/eslint-config-pwa",
10
+ "parserOptions": {
11
+ "project": "./tsconfig.json"
12
+ }
13
+ },
14
+ "exports": {
15
+ ".": "./index.ts",
16
+ "./plugins/AddAddressAutocompleteAddressFields": "./plugins/AddAddressAutocompleteAddressFields.tsx"
17
+ },
18
+ "dependencies": {
19
+ "@googlemaps/js-api-loader": "^1.16.8",
20
+ "@types/google.maps": "^3.59.0"
21
+ },
22
+ "peerDependencies": {
23
+ "@graphcommerce/ecommerce-ui": "^10.1.0-canary.42",
24
+ "@graphcommerce/eslint-config-pwa": "^10.1.0-canary.42",
25
+ "@graphcommerce/graphql": "^10.1.0-canary.42",
26
+ "@graphcommerce/magento-customer": "^10.1.0-canary.42",
27
+ "@graphcommerce/magento-store": "^10.1.0-canary.42",
28
+ "@graphcommerce/next-config": "^10.1.0-canary.42",
29
+ "@graphcommerce/prettier-config-pwa": "^10.1.0-canary.42",
30
+ "@graphcommerce/typescript-config-pwa": "^10.1.0-canary.42",
31
+ "@lingui/core": "^5",
32
+ "@lingui/macro": "^5",
33
+ "@lingui/react": "^5",
34
+ "@mui/material": "^7.0.0",
35
+ "react": "^19.2.0",
36
+ "react-dom": "^19.2.0"
37
+ }
38
+ }
@@ -0,0 +1,19 @@
1
+ import type { FieldPath, FieldValues } from '@graphcommerce/ecommerce-ui'
2
+ import type { AddressFieldsOptions } from '@graphcommerce/magento-customer'
3
+ import type { PluginConfig, PluginProps } from '@graphcommerce/next-config'
4
+ import { AddressAutocomplete } from '../components/AddressAutocomplete'
5
+
6
+ export const config: PluginConfig = {
7
+ type: 'component',
8
+ module: '@graphcommerce/magento-customer',
9
+ ifConfig: 'googleMapsApiKey',
10
+ }
11
+
12
+ export function AddressStreet<
13
+ TFieldValues extends FieldValues = FieldValues,
14
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
15
+ >(props: PluginProps<AddressFieldsOptions<TFieldValues, TName>>) {
16
+ const { Prev, ...rest } = props
17
+
18
+ return <AddressAutocomplete {...rest} fallback={<Prev {...rest} />} />
19
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "compilerOptions": {
3
+ "moduleResolution": "Bundler",
4
+ "types": ["vitest/globals"]
5
+ },
6
+ "exclude": ["node_modules"],
7
+ "include": ["**/*.ts", "**/*.tsx"],
8
+ "extends": "@graphcommerce/typescript-config-pwa/nextjs.json"
9
+ }
@@ -0,0 +1,38 @@
1
+ import { addressValues } from './addressValues'
2
+ import type { FormattedAddress } from './formatAddress'
3
+
4
+ const emptyAddress: FormattedAddress = {
5
+ street: '',
6
+ houseNumber: '',
7
+ addition: '',
8
+ postcode: '',
9
+ city: '',
10
+ country: 'NL',
11
+ region: '',
12
+ regionCode: '',
13
+ }
14
+
15
+ describe('addressValues', () => {
16
+ it('provides explicit empty values so a partial selection clears stale form data', () => {
17
+ expect(addressValues(emptyAddress)).toEqual({
18
+ street: '',
19
+ houseNumber: '',
20
+ addition: '',
21
+ postcode: '',
22
+ city: '',
23
+ countryCode: 'NL',
24
+ regionId: null,
25
+ })
26
+ })
27
+
28
+ it('resolves the region when country metadata is available', () => {
29
+ expect(
30
+ addressValues({ ...emptyAddress, country: 'US', region: 'California', regionCode: 'CA' }, [
31
+ {
32
+ two_letter_abbreviation: 'US',
33
+ available_regions: [{ id: 12, code: 'CA', name: 'California' }],
34
+ },
35
+ ]).regionId,
36
+ ).toBe(12)
37
+ })
38
+ })
@@ -0,0 +1,18 @@
1
+ import type { AddressCountry } from './findRegionId'
2
+ import { findRegionId } from './findRegionId'
3
+ import type { FormattedAddress } from './formatAddress'
4
+
5
+ export function addressValues(
6
+ address: FormattedAddress,
7
+ countries?: readonly (AddressCountry | null)[] | null,
8
+ ) {
9
+ return {
10
+ street: address.street,
11
+ houseNumber: address.houseNumber,
12
+ addition: address.addition,
13
+ postcode: address.postcode,
14
+ city: address.city,
15
+ countryCode: address.country,
16
+ regionId: findRegionId(countries, address),
17
+ }
18
+ }
@@ -0,0 +1,43 @@
1
+ import { findRegionId } from './findRegionId'
2
+
3
+ const countries = [
4
+ {
5
+ two_letter_abbreviation: 'CA',
6
+ available_regions: [
7
+ { id: 1, code: 'QC', name: 'Québec' },
8
+ { id: 2, code: 'ON', name: 'Ontario' },
9
+ ],
10
+ },
11
+ ]
12
+
13
+ describe('findRegionId', () => {
14
+ it('prefers the stable region code', () => {
15
+ expect(
16
+ findRegionId(countries, {
17
+ country: 'ca',
18
+ regionCode: 'QC',
19
+ region: 'Different localized name',
20
+ }),
21
+ ).toBe(1)
22
+ })
23
+
24
+ it('falls back to a normalized region name', () => {
25
+ expect(
26
+ findRegionId(countries, {
27
+ country: 'CA',
28
+ regionCode: '',
29
+ region: 'Quebec',
30
+ }),
31
+ ).toBe(1)
32
+ })
33
+
34
+ it('returns null rather than retaining an unrelated region', () => {
35
+ expect(
36
+ findRegionId(countries, {
37
+ country: 'US',
38
+ regionCode: 'CA',
39
+ region: 'California',
40
+ }),
41
+ ).toBeNull()
42
+ })
43
+ })
@@ -0,0 +1,42 @@
1
+ import type { FormattedAddress } from './formatAddress'
2
+
3
+ export type AddressRegion = {
4
+ code?: string | null
5
+ id?: number | null
6
+ name?: string | null
7
+ }
8
+
9
+ export type AddressCountry = {
10
+ available_regions?: readonly (AddressRegion | null)[] | null
11
+ two_letter_abbreviation?: string | null
12
+ }
13
+
14
+ function normalize(value?: string | null) {
15
+ return value
16
+ ?.normalize('NFKD')
17
+ .replace(/\p{Diacritic}/gu, '')
18
+ .trim()
19
+ .toLocaleLowerCase()
20
+ }
21
+
22
+ export function findRegionId(
23
+ countries: readonly (AddressCountry | null)[] | null | undefined,
24
+ address: Pick<FormattedAddress, 'country' | 'region' | 'regionCode'>,
25
+ ): number | null {
26
+ const countryCode = normalize(address.country)
27
+ const country = countries?.find(
28
+ (candidate) => normalize(candidate?.two_letter_abbreviation) === countryCode,
29
+ )
30
+
31
+ if (!country) return null
32
+
33
+ const regionCode = normalize(address.regionCode)
34
+ const regionName = normalize(address.region)
35
+ const region = country.available_regions?.find((candidate) => {
36
+ if (!candidate) return false
37
+ if (regionCode && normalize(candidate.code) === regionCode) return true
38
+ return Boolean(regionName && normalize(candidate.name) === regionName)
39
+ })
40
+
41
+ return region?.id ?? null
42
+ }
@@ -0,0 +1,121 @@
1
+ import type { AddressComponent } from './formatAddress'
2
+ import { formatAddress } from './formatAddress'
3
+
4
+ function component(longText: string, shortText: string, types: string[]): AddressComponent {
5
+ return { longText, shortText, types }
6
+ }
7
+
8
+ describe('formatAddress', () => {
9
+ it('maps a selected address to the GraphCommerce address fields', () => {
10
+ const result = formatAddress({
11
+ addressComponents: [
12
+ component('221B', '221B', ['premise', 'street_number']),
13
+ component('Baker Street', 'Baker St', ['political', 'route']),
14
+ component('Flat A', 'A', ['subpremise']),
15
+ component('London', 'London', ['postal_town']),
16
+ component('England', 'ENG', ['administrative_area_level_1']),
17
+ component('United Kingdom', 'GB', ['country']),
18
+ component('NW1 6XE', 'NW1 6XE', ['postal_code']),
19
+ ],
20
+ })
21
+
22
+ expect(result).toEqual({
23
+ street: 'Baker Street',
24
+ houseNumber: '221B',
25
+ addition: 'A',
26
+ postcode: 'NW1 6XE',
27
+ city: 'London',
28
+ country: 'GB',
29
+ region: 'England',
30
+ regionCode: 'ENG',
31
+ })
32
+ })
33
+
34
+ it('uses locality first and falls back to sublocality for cities', () => {
35
+ const locality = formatAddress({
36
+ addressComponents: [
37
+ component('Montréal', 'Montréal', ['locality']),
38
+ component('Outremont', 'Outremont', ['sublocality_level_1']),
39
+ ],
40
+ })
41
+ const sublocality = formatAddress({
42
+ addressComponents: [component('Brooklyn', 'Brooklyn', ['sublocality_level_1'])],
43
+ })
44
+
45
+ expect(locality.city).toBe('Montréal')
46
+ expect(sublocality.city).toBe('Brooklyn')
47
+ })
48
+
49
+ it.each([
50
+ ['94a', 'NL', '94', 'a'],
51
+ ['221B', 'GB', '221', 'B'],
52
+ ['12/1β', 'GR', '12/1', 'β'],
53
+ ])(
54
+ 'maps the street-number suffix in %s to the addition field',
55
+ (streetNumber, country, expectedHouseNumber, expectedAddition) => {
56
+ const result = formatAddress({
57
+ addressComponents: [
58
+ component(streetNumber, streetNumber, ['street_number']),
59
+ component('Example Street', 'Example St', ['route']),
60
+ component(country, country, ['country']),
61
+ ],
62
+ })
63
+
64
+ expect(result.houseNumber).toBe(expectedHouseNumber)
65
+ expect(result.addition).toBe(expectedAddition)
66
+ },
67
+ )
68
+
69
+ it('maps Antonie van Leeuwenhoekweg 38C6 to house number and addition', () => {
70
+ const result = formatAddress({
71
+ addressComponents: [
72
+ component('38C6', '38C6', ['street_number']),
73
+ component('Antonie van Leeuwenhoekweg', 'Antonie van Leeuwenhoekweg', ['route']),
74
+ component('Nederland', 'NL', ['country']),
75
+ ],
76
+ })
77
+
78
+ expect(result).toMatchObject({
79
+ street: 'Antonie van Leeuwenhoekweg',
80
+ houseNumber: '38',
81
+ addition: 'C6',
82
+ })
83
+ })
84
+
85
+ it('preserves an explicit subpremise instead of splitting the street number', () => {
86
+ const result = formatAddress({
87
+ addressComponents: [
88
+ component('221B', '221B', ['street_number']),
89
+ component('Flat A', 'A', ['subpremise']),
90
+ ],
91
+ })
92
+
93
+ expect(result.houseNumber).toBe('221B')
94
+ expect(result.addition).toBe('A')
95
+ })
96
+
97
+ it('recognizes postal-code prefixes and suffixes', () => {
98
+ expect(
99
+ formatAddress({
100
+ addressComponents: [component('SW1A', 'SW1A', ['postal_code_prefix'])],
101
+ }).postcode,
102
+ ).toBe('SW1A')
103
+
104
+ expect(
105
+ formatAddress({
106
+ addressComponents: [
107
+ component('12345', '12345', ['postal_code']),
108
+ component('6789', '6789', ['postal_code_suffix']),
109
+ ],
110
+ }).postcode,
111
+ ).toBe('12345-6789')
112
+ })
113
+
114
+ it('supports legacy geocoder components for backwards compatibility', () => {
115
+ const result = formatAddress({
116
+ addressComponents: [{ long_name: 'Main Street', short_name: 'Main St', types: ['route'] }],
117
+ })
118
+
119
+ expect(result.street).toBe('Main Street')
120
+ })
121
+ })
@@ -0,0 +1,76 @@
1
+ type PlacesAddressComponent = Pick<
2
+ google.maps.places.AddressComponent,
3
+ 'longText' | 'shortText' | 'types'
4
+ >
5
+
6
+ type GeocoderAddressComponent = Pick<
7
+ google.maps.GeocoderAddressComponent,
8
+ 'long_name' | 'short_name' | 'types'
9
+ >
10
+
11
+ export type AddressComponent = PlacesAddressComponent | GeocoderAddressComponent
12
+
13
+ export type FormatAddressProps = {
14
+ addressComponents: readonly AddressComponent[]
15
+ }
16
+
17
+ /** @deprecated Use `FormatAddressProps` instead. */
18
+ export type formatAddressProps = FormatAddressProps
19
+
20
+ export type FormattedAddress = {
21
+ street: string
22
+ houseNumber: string
23
+ addition: string
24
+ postcode: string
25
+ city: string
26
+ country: string
27
+ region: string
28
+ regionCode: string
29
+ }
30
+
31
+ function getLongText(component: AddressComponent) {
32
+ return 'longText' in component ? (component.longText ?? '') : component.long_name
33
+ }
34
+
35
+ function getShortText(component: AddressComponent) {
36
+ return 'shortText' in component ? (component.shortText ?? '') : component.short_name
37
+ }
38
+
39
+ function findComponent(addressComponents: readonly AddressComponent[], type: string) {
40
+ return addressComponents.find((component) => component.types.includes(type))
41
+ }
42
+
43
+ export function formatAddress(props: FormatAddressProps): FormattedAddress {
44
+ const { addressComponents } = props
45
+
46
+ const getLong = (type: string) => {
47
+ const component = findComponent(addressComponents, type)
48
+ return component ? getLongText(component) : ''
49
+ }
50
+ const getShort = (type: string) => {
51
+ const component = findComponent(addressComponents, type)
52
+ return component ? getShortText(component) : ''
53
+ }
54
+
55
+ const postcode = getShort('postal_code') || getShort('postal_code_prefix')
56
+ const postcodeSuffix = getShort('postal_code_suffix')
57
+ const country = getShort('country')
58
+ let houseNumber = getShort('street_number')
59
+ let addition = getShort('subpremise')
60
+
61
+ if (!addition) {
62
+ const houseNumberParts = houseNumber.match(/^(\d+(?:[-/]\d+)*)(\p{L}[\p{L}\d]*)$/u)
63
+ if (houseNumberParts) [, houseNumber, addition] = houseNumberParts
64
+ }
65
+
66
+ return {
67
+ street: getLong('route'),
68
+ houseNumber,
69
+ addition,
70
+ postcode: postcodeSuffix ? `${postcode}-${postcodeSuffix}` : postcode,
71
+ city: getLong('locality') || getLong('postal_town') || getLong('sublocality_level_1'),
72
+ country,
73
+ region: getLong('administrative_area_level_1'),
74
+ regionCode: getShort('administrative_area_level_1'),
75
+ }
76
+ }