Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrating MUI Autocomplete for searching and filtering countries #54

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ dist-ssr
*.sln
*.sw?
coverage

.nvmrc
ja153903 marked this conversation as resolved.
Show resolved Hide resolved
ja153903 marked this conversation as resolved.
Show resolved Hide resolved
11 changes: 11 additions & 0 deletions docs/docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,14 @@ Props for the MUI [Menu](https://mui.com/material-ui/api/menu/) component.
```tsx
<MuiTelInput MenuProps={{ disableAutoFocusItem: true }} />
```

## `allowSearch`

- Type: `boolean`
- Default: `false`

Adds a search input to filter countries by ISO code or name.

```tsx
<MuiTelInput allowSearch>
```
39 changes: 32 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@
}
},
"dependencies": {
"libphonenumber-js": "^1.10.15"
"libphonenumber-js": "^1.10.15",
"match-sorter": "^6.3.1"
},
"devDependencies": {
"@babel/core": "^7.19.3",
Expand Down
66 changes: 66 additions & 0 deletions src/components/FlagsAutocomplete/FlagsAutocomplete.styled.ts
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of having all styles "hardcoded", please make them optional / customisable and provide the possibility to add custom CSS classes to each element.

Copy link
Author

@ja153903 ja153903 Mar 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@emkayy I think there needs to be baseline styling so that it matches the current FlagMenu. Do you have components of the autocomplete in mind that you'd think would benefit from making it optional?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Baseline styling yes, but I think it's important to be able to customize it. Unfortunately I don't know what you mean by "Do you have components of the autocomplete in mind ...".

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you read the source code for FlagsAutocomplete there are different components in there that would require some styling. I'm asking which ones you would actually consider important to have customized styling for.

It might be a good idea for you to clone my fork and see what might be important for you to have some control over.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think for the input it would be better to have a plain input without a label that spans across the whole popper width.
However, for complete customization, the renderInput prop for Autocomplete would be great, like
<MuiTelInput flagPopupProps={{ AutocompleteProps: {renderInput: ()=> MyCustomInput }}} />

For the popper I would use the theme default style and not do any custom styling. But if you do, you should also provide props to override them.

Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { autocompleteClasses } from '@mui/material/Autocomplete'
import InputBase from '@mui/material/InputBase'
import Popper from '@mui/material/Popper'
import { styled } from '@mui/material/styles'

const Styled = {
AutocompletePopper: styled('div')(({ theme }) => {
return {
[`& .${autocompleteClasses.paper}`]: {
boxShadow: 'none',
margin: 0,
color: 'inherit'
},
[`& .${autocompleteClasses.listbox}`]: {
backgroundColor: '#fff',
padding: 0,
[`& .${autocompleteClasses.option}`]: {
minHeight: 'auto',
alignItems: 'flex-start',
padding: 8,
borderBottom: `1px solid #eaecef`,
'&[aria-selected="true"]': {
backgroundColor: 'transparent'
},
[`&.${autocompleteClasses.focused}, &.${autocompleteClasses.focused}[aria-selected="true"]`]:
{
backgroundColor: theme.palette.action.hover
}
}
},
[`&.${autocompleteClasses.popperDisablePortal}`]: {
position: 'relative'
}
}
}),
Popper: styled(Popper)(({ theme }) => {
return {
border: '1px solid #e1e4e8',
boxShadow: '0 8px 24px rgba(149, 157, 165, 0.2)',
borderRadius: 6,
width: 300,
zIndex: theme.zIndex.modal,
color: '#24292e',
backgroundColor: '#fff'
}
}),
Input: styled(InputBase)(() => {
return {
padding: 10,
width: '100%',
borderBottom: '1px solid #eaecef',
'& input': {
borderRadius: 4,
backgroundColor: '#fff',
padding: 8,
border: '1px solid #eaecef',
'&:focus': {
boxShadow: '0px 0px 0px 3px rgba(3, 102, 214, 0.3)',
borderColor: '#0366d6'
}
}
}
})
}

export { Styled }
173 changes: 173 additions & 0 deletions src/components/FlagsAutocomplete/FlagsAutocomplete.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import React from 'react'
import { expect, vi } from 'vitest'
import { ISO_CODES, MuiTelInputCountry } from '@shared/constants/countries'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import FlagsAutocomplete from './FlagsAutocomplete'
import '@testing-library/jest-dom'

function getAnchorEl() {
return screen.getByText('My textfield')
}

describe('components/FlagsAutocomplete', () => {
beforeAll(() => {
document.body.innerHTML = `<div>My textfield</div>`
})

test('should be displayed when anchorEl is valid', () => {
render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
isoCode="FR"
onSelectCountry={() => {}}
onClose={() => {}}
/>
)
})

test('should render correctly', () => {
render(
<FlagsAutocomplete
isoCode="FR"
excludedCountries={['FR']}
onSelectCountry={() => {}}
onClose={() => {}}
anchorEl={null}
/>
)
})

test('should list all countries without filters props', () => {
render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
isoCode="FR"
onSelectCountry={() => {}}
onClose={() => {}}
/>
)
expect(screen.getAllByRole('option').length).toBe(ISO_CODES.length)
})

test('should fire onSelectCountry', () => {
const callback = vi.fn((country: MuiTelInputCountry) => {
return country
})

render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
isoCode="FR"
onSelectCountry={callback}
onClose={() => {}}
/>
)
fireEvent.click(screen.getByText('France'))
expect(callback).toBeCalledTimes(1)
})

test('should exclude countries', () => {
render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
isoCode="FR"
excludedCountries={['FR']}
onSelectCountry={() => {}}
onClose={() => {}}
/>
)
expect(screen.queryByText('France')).toBeNull()
})

test('should display EU countries except FR', () => {
render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
excludedCountries={['FR']}
continents={['EU']}
isoCode="FR"
onSelectCountry={() => {}}
onClose={() => {}}
/>
)

expect(screen.queryByText('France')).toBeNull()
expect(screen.queryByText('Venezuela')).toBeNull()
expect(screen.getByText('Belgium')).toBeTruthy()
})

test('should display onlyCountries and not continents', () => {
render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
onlyCountries={['VE']}
continents={['EU']}
isoCode="FR"
onSelectCountry={() => {}}
onClose={() => {}}
/>
)

expect(screen.getByText('Venezuela')).toBeTruthy()
expect(screen.getAllByRole('option').length).toBe(1)
})

test('should highlight preferred countries and in good order', () => {
render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
preferredCountries={['FR', 'BE', 'VE']}
isoCode="FR"
onSelectCountry={() => {}}
onClose={() => {}}
/>
)

const options = screen.getAllByRole('option')
expect(options[0]).toHaveTextContent('FR')
expect(options[1]).toHaveTextContent('BE')
expect(options[2]).toHaveTextContent('VE')
})

test('should highlight preferred countries not excluded', () => {
render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
preferredCountries={['FR', 'BE', 'VE']}
excludedCountries={['FR']}
isoCode="FR"
onSelectCountry={() => {}}
onClose={() => {}}
/>
)

const options = screen.getAllByRole('option')
expect(options[0]).toHaveTextContent('BE')
expect(options[1]).toHaveTextContent('VE')
})

test('should filter options based input value', async () => {
render(
<FlagsAutocomplete
anchorEl={getAnchorEl()}
onlyCountries={['FR', 'BE', 'VE']}
isoCode="FR"
onSelectCountry={() => {}}
onClose={() => {}}
/>
)

const autocompleteInput = screen.getByTestId('flagsautocomplete-input')

await userEvent.type(autocompleteInput, 'bel', { delay: 1 })

await waitFor(() => {
expect(autocompleteInput).toHaveValue('bel')
})

const options = screen.getAllByRole('option')
expect(options.length).toBe(1)
expect(options[0]).toHaveTextContent('BE')
})
})
Loading