Skip to content

Commit

Permalink
Merge pull request #29 from emrysal/main
Browse files Browse the repository at this point in the history
Implemented findFuzzyTz, allowing for (valid) non-dropdown timezones
  • Loading branch information
ndom91 authored May 2, 2021
2 parents 4757c3d + fb88ef4 commit 19805d8
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/__tests__/TimezoneSelect.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,21 @@ test('load and passes react-select props', async () => {
expect(getByText('Please Select a Timezone')).toBeInTheDocument()
})

test('can determine timezone by approximate match', async () => {
const { getByText } = render(
<TimezoneSelect
value="Europe/Rome"
onChange={e => e}
/>
)

expect(
getByText(
/\(GMT\+[1-2]:00\) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna$/
)
).toBeInTheDocument()
})

test('select drop-downs must use the fireEvent.change', () => {
const onChangeSpy = jest.fn()
const { container } = render(
Expand Down
34 changes: 33 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,42 @@ const TimezoneSelect = ({
onChange && onChange(tz)
}

const findFuzzyTz = (zone: string): ITimezoneOption => {
let currentTime;
try {
currentTime = spacetime.now(zone);
}
catch (err) {
return;
}
return getOptions.filter( (tz: ITimezoneOption) => (tz.offset === currentTime.timezone().current.offset))
.map( (tz: ITimezoneOption) => {
let score = 0;
if (currentTime.timezones[ tz.value.toLowerCase() ] && !!currentTime.timezones[ tz.value.toLowerCase() ].dst === currentTime.timezone().hasDst) {

if (tz.value.toLowerCase().indexOf(currentTime.tz.substr(currentTime.tz.indexOf('/') + 1)) !== -1) {
score += 8;
}
if (tz.label.toLowerCase().indexOf(currentTime.tz.substr(currentTime.tz.indexOf('/') + 1)) !== -1) {
score += 4;
}
if (tz.value.toLowerCase().indexOf(currentTime.tz.substr(0, currentTime.tz.indexOf('/')))) {
score += 2;
}
score += 1;
} else if (tz.value === 'GMT') {
score += 1;
}
return { tz, score };
})
.sort( (a, b) => b.score - a.score )
.map( ({ tz, score }) => tz )[0];
};

const parseTimezone = (zone: ITimezone) => {
if (typeof zone === 'object' && zone.value && zone.label) return zone
if (typeof zone === 'string') {
return getOptions.find(tz => tz.value === zone)
return getOptions.find(tz => tz.value === zone) || ( zone.indexOf('/') !== -1 && findFuzzyTz(zone) )
} else if (zone.value && !zone.label) {
return getOptions.find(tz => tz.value === zone.value)
}
Expand Down

0 comments on commit 19805d8

Please sign in to comment.