From ba98a8e82f1d52c1dfce472e367d3f42b1ab20b7 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 13 Jul 2022 18:08:59 -0500 Subject: [PATCH] PhoneInput: prettify input while typing --- .../components/ui/phone-input/phone-input.tsx | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/app/soapbox/components/ui/phone-input/phone-input.tsx b/app/soapbox/components/ui/phone-input/phone-input.tsx index a3efc5791..ec8584581 100644 --- a/app/soapbox/components/ui/phone-input/phone-input.tsx +++ b/app/soapbox/components/ui/phone-input/phone-input.tsx @@ -1,4 +1,4 @@ -import { parsePhoneNumber } from 'libphonenumber-js'; +import { parsePhoneNumber, AsYouType } from 'libphonenumber-js'; import React, { useState, useEffect } from 'react'; import { CountryCode } from 'soapbox/utils/phone'; @@ -29,7 +29,15 @@ const PhoneInput: React.FC = (props) => { }; const handleChange: React.ChangeEventHandler = ({ target }) => { - setNationalNumber(target.value); + // HACK: AsYouType is not meant to be used this way. But it works! + const asYouType = new AsYouType({ defaultCallingCode: countryCode }); + const formatted = asYouType.input(target.value); + + if (formatted === nationalNumber && target.value !== nationalNumber) { + setNationalNumber(target.value); + } else { + setNationalNumber(formatted); + } }; // When the internal state changes, update the external state.