Commit ec4958c6 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add a country-code dropdown to Telegram phone entry

The single free-text phone field made the required "+" country prefix
easy to miss or mistype. Split into a country select (built from
libphonenumber-js's own ISO list + the browser's Intl.DisplayNames for
names - no hand-maintained country/dial-code table) defaulting to a guess
from navigator.language, plus a national-number field; the two compose
into the same E.164 string requestTelegramCode already expected, so
nothing downstream changed.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent ab82a396
Pipeline #1257 canceled with stages
......@@ -15,6 +15,7 @@
"class-variance-authority": "^0.7.1",
"cn": "^0.4.0",
"leaflet": "^1.9.4",
"libphonenumber-js": "^1.13.15",
"lottie-react": "^3.1.2",
"lucide-react": "^1.31.0",
"react": "^19.2.8",
......@@ -7673,6 +7674,12 @@
"node": ">=6"
}
},
"node_modules/libphonenumber-js": {
"version": "1.13.15",
"resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.13.15.tgz",
"integrity": "sha512-AHdhEQeDFEJ4GKDAQ9AwxChy+v2kUILUB3TGQRpkXMkWePjXTU/WQEzWVQoIx/Gz8fE73Wr5SEuZCy2vk8jrMQ==",
"license": "MIT"
},
"node_modules/lightningcss": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
......
......@@ -19,6 +19,7 @@
"class-variance-authority": "^0.7.1",
"cn": "^0.4.0",
"leaflet": "^1.9.4",
"libphonenumber-js": "^1.13.15",
"lottie-react": "^3.1.2",
"lucide-react": "^1.31.0",
"react": "^19.2.8",
......
import { forwardRef, type InputHTMLAttributes, type TextareaHTMLAttributes } from 'react'
const FIELD_CLASSES =
export const FIELD_CLASSES =
// text-base (16px), not smaller: anything under 16px triggers iOS Safari's auto-zoom-on-focus
'min-h-[44px] w-full rounded-lg border border-outline-variant bg-surface-container px-3.5 text-base text-on-surface placeholder-outline outline-none transition-colors duration-150 focus:border-primary'
......
import { getCountries, getCountryCallingCode, type CountryCode } from 'libphonenumber-js'
export interface CountryOption {
code: CountryCode
name: string
callingCode: string
}
// Built once at module load from libphonenumber-js's own ISO list - no hand-maintained
// country/dial-code table to keep in sync. Country names come from the browser's own Intl
// API (supported everywhere this app already requires JS for), not a second dependency.
const displayNames = new Intl.DisplayNames(['en'], { type: 'region' })
export const COUNTRIES: CountryOption[] = getCountries()
.map((code) => ({
code,
name: displayNames.of(code) ?? code,
callingCode: getCountryCallingCode(code),
}))
.sort((a, b) => a.name.localeCompare(b.name))
/** Best-effort guess from the browser's own locale (e.g. "en-US" -> "US") - just a sane
* default selection, never a validation source; the user can always change it. */
export function guessDefaultCountry(): CountryCode {
const region = navigator.language?.split('-')[1]?.toUpperCase()
if (region && COUNTRIES.some((c) => c.code === region)) return region as CountryCode
return 'US'
}
......@@ -75,7 +75,7 @@ describe('TelegramLink', () => {
})
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.type(await screen.findByLabelText('Phone number'), '5551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
expect(requestTelegramCode).toHaveBeenCalledWith('+15551234567')
......@@ -83,6 +83,21 @@ describe('TelegramLink', () => {
expect(screen.getByText(/Enter the code sent to \+15551234567/)).toBeInTheDocument()
})
it('composes the full number from the selected country code, not just the default', async () => {
vi.spyOn(authApi, 'getChats').mockRejectedValue(new ApiError(400, 'No linked Telegram session', null))
const requestTelegramCode = vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
renderPage()
await userEvent.selectOptions(await screen.findByLabelText('Country code'), 'GB')
await userEvent.type(screen.getByLabelText('Phone number'), '7911123456')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
expect(requestTelegramCode).toHaveBeenCalledWith('+447911123456')
})
it('verifies the code, links the account, and shows the chat list', async () => {
vi.spyOn(authApi, 'getChats')
.mockRejectedValueOnce(new ApiError(400, 'No linked Telegram session', null))
......@@ -94,7 +109,7 @@ describe('TelegramLink', () => {
const linkTelegram = vi.spyOn(authApi, 'linkTelegram').mockResolvedValue({ status: 'success', phone_number: '+15551234567' })
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.type(await screen.findByLabelText('Phone number'), '5551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
......@@ -112,7 +127,7 @@ describe('TelegramLink', () => {
vi.spyOn(authApi, 'linkTelegram').mockRejectedValue(new ApiError(412, 'Two-step verification password required', null))
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.type(await screen.findByLabelText('Phone number'), '5551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
......@@ -135,7 +150,7 @@ describe('TelegramLink', () => {
.mockResolvedValue({ status: 'success', phone_number: '+15551234567' })
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.type(await screen.findByLabelText('Phone number'), '5551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
......@@ -156,7 +171,7 @@ describe('TelegramLink', () => {
vi.spyOn(authApi, 'submitTelegramPassword').mockRejectedValue(new ApiError(400, 'Invalid password', null))
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.type(await screen.findByLabelText('Phone number'), '5551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
......@@ -175,7 +190,7 @@ describe('TelegramLink', () => {
vi.spyOn(authApi, 'linkTelegram').mockRejectedValue(new ApiError(400, 'Invalid code', null))
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.type(await screen.findByLabelText('Phone number'), '5551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '00000')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
......@@ -192,7 +207,7 @@ describe('TelegramLink', () => {
})
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.type(await screen.findByLabelText('Phone number'), '5551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await screen.findByLabelText('Verification code')
......
import { useEffect, useState } from 'react'
import { Check, Download, MessageCircle, Music2, Pause, Play } from 'lucide-react'
import { getCountryCallingCode, type CountryCode } from 'libphonenumber-js'
import {
fetchChatMusicPreviewUrl,
getChatMusic,
......@@ -14,10 +15,11 @@ import { tagFromChat, type TagMetadata } from '../api/music'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { Input, FIELD_CLASSES } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
import { usePlayer } from '../context/PlayerContext'
import { COUNTRIES, guessDefaultCountry } from '../lib/countries'
function toPreviewPlayable(chatId: number, m: ChatMusic) {
return {
......@@ -37,6 +39,12 @@ export function TelegramLink() {
const [chats, setChats] = useState<Chat[]>([])
const [chatsError, setChatsError] = useState<string | null>(null)
// countryCode/nationalNumber are the two editable pieces of the form; phoneNumber is the
// final E.164 string (e.g. "+15551234567"), only set once a code has actually been sent -
// everything downstream (code/password steps, loadChats) keeps using phoneNumber exactly
// as before.
const [countryCode, setCountryCode] = useState<CountryCode>(() => guessDefaultCountry())
const [nationalNumber, setNationalNumber] = useState('')
const [phoneNumber, setPhoneNumber] = useState('')
const [phoneCodeHash, setPhoneCodeHash] = useState('')
const [code, setCode] = useState('')
......@@ -82,11 +90,14 @@ export function TelegramLink() {
async function handleSendCode(e: React.FormEvent) {
e.preventDefault()
if (!phoneNumber.trim()) return
const digits = nationalNumber.replace(/\D/g, '')
if (!digits) return
const fullNumber = `+${getCountryCallingCode(countryCode)}${digits}`
setBusy(true)
setError(null)
try {
const res = await requestTelegramCode(phoneNumber.trim())
const res = await requestTelegramCode(fullNumber)
setPhoneNumber(fullNumber)
setPhoneCodeHash(res.data.phone_code_hash)
setStep('code')
} catch (err) {
......@@ -132,6 +143,7 @@ export function TelegramLink() {
function handleChangeNumber() {
setStep('phone')
setNationalNumber('')
setCode('')
setPassword('')
setError(null)
......@@ -227,18 +239,33 @@ export function TelegramLink() {
{step === 'phone' && (
<form onSubmit={handleSendCode} className="space-y-3">
<div className="flex gap-2">
<select
value={countryCode}
onChange={(e) => setCountryCode(e.target.value as CountryCode)}
aria-label="Country code"
className={`${FIELD_CLASSES} w-32 shrink-0`}
>
{COUNTRIES.map((c) => (
<option key={c.code} value={c.code}>
+{c.callingCode} {c.name}
</option>
))}
</select>
<Input
type="tel"
inputMode="tel"
autoComplete="tel"
autoComplete="tel-national"
autoFocus
placeholder="+1 555 123 4567"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
placeholder="555 123 4567"
value={nationalNumber}
onChange={(e) => setNationalNumber(e.target.value)}
aria-label="Phone number"
className="flex-1"
/>
</div>
{error && <p className="text-sm text-error">{error}</p>}
<Button type="submit" disabled={busy || !phoneNumber.trim()} className="w-full">
<Button type="submit" disabled={busy || !nationalNumber.replace(/\D/g, '')} className="w-full">
{busy ? 'Sending code…' : 'Send code'}
</Button>
</form>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment