Files
calendar/packages/features/components/phone-input/PhoneInput.tsx
T
MorganGitHubmorgan@cal.com <morgan@cal.com>Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>Rajiv Sahal
037cb8ee2a feat: add defaultPhoneCountry prop with ISO 3166-1 alpha-2 type safety (#25204)
* feat: add defaultPhoneCountry prop to BookerPlatformWrapper

- Add defaultPhoneCountry to BookerStore type and implementation
- Add defaultPhoneCountry prop to BookerPlatformWrapper types
- Pass defaultPhoneCountry through store initialization
- Update PhoneInput to use defaultPhoneCountry from store
- Support default phone country extension for phone inputs in booker form

* feat: add strict typing for defaultPhoneCountry with ISO 3166-1 alpha-2 codes

- Define CountryCode type using ISO 3166-1 alpha-2 country codes
- Update defaultPhoneCountry prop type in BookerPlatformWrapper to use CountryCode
- Update defaultPhoneCountry type in BookerStore to use CountryCode
- Ensures type safety by only allowing valid country codes like 'us', 'gb', 'ee', etc.
- Fix lint warnings by prefixing type-only constants with underscore

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* refactor: export CountryCode from store to avoid duplication

- Export CountryCode type from packages/features/bookings/Booker/store.ts
- Import CountryCode in packages/platform/atoms/booker/types.ts from store
- Remove duplicate CountryCode definition from types.ts
- Maintains single source of truth for country code type definition

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* fix: add type-safe casts for CountryCode in PhoneInput

- Import CountryCode type from store
- Add explicit type annotation to useState<CountryCode>
- Add safe type casts with isSupportedCountry validation
- Validate navigator.language country code before using it
- Fixes CI type error: string not assignable to CountryCode

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* docs: add defaultPhoneCountry prop documentation and changeset

- Add defaultPhoneCountry prop to booker.mdx documentation
- Add changeset for minor version bump
- Document ISO 3166-1 alpha-2 country code support

Co-Authored-By: morgan@cal.com <morgan@cal.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
2025-11-17 15:56:10 +00:00

194 lines
5.6 KiB
TypeScript

"use client";
import { isSupportedCountry } from "libphonenumber-js";
import type { CSSProperties } from "react";
import { useState, useEffect } from "react";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { useBookerStore, type CountryCode } from "@calcom/features/bookings/Booker/store";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
export type PhoneInputProps = {
value?: string;
id?: string;
placeholder?: string;
required?: boolean;
className?: string;
name?: string;
disabled?: boolean;
onChange: (value: string) => void;
defaultCountry?: string;
inputStyle?: CSSProperties;
flagButtonStyle?: CSSProperties;
};
function BasePhoneInput({
name,
className = "",
onChange,
value,
defaultCountry = "us",
...rest
}: PhoneInputProps) {
const isPlatform = useIsPlatform();
const defaultPhoneCountryFromStore = useBookerStore((state) => state.defaultPhoneCountry);
const effectiveDefaultCountry = defaultPhoneCountryFromStore || defaultCountry;
// This is to trigger validation on prefill value changes
useEffect(() => {
if (!value) return;
const sanitized = value
.trim()
.replace(/[^\d+]/g, "")
.replace(/^\+?/, "+");
if (sanitized === "+" || sanitized === "") return;
if (value !== sanitized) {
onChange(sanitized);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (!isPlatform) {
return (
<BasePhoneInputWeb name={name} className={className} onChange={onChange} value={value} {...rest} />
);
}
return (
<PhoneInput
{...rest}
value={value ? value.trim().replace(/^\+?/, "+") : undefined}
enableSearch
disableSearchIcon
country={effectiveDefaultCountry}
inputProps={{
name,
required: rest.required,
placeholder: rest.placeholder,
autoComplete: "tel",
}}
onChange={(val: string) => {
onChange(`+${val}`);
}}
containerClass={classNames(
"hover:border-emphasis dark:focus:border-emphasis border-default !bg-default rounded-md border focus-within:outline-none focus-within:ring-2 focus-within:ring-brand-default disabled:cursor-not-allowed",
className
)}
inputClass="text-sm focus:ring-0 !bg-default text-default placeholder:text-muted"
buttonClass="text-emphasis !bg-default hover:!bg-emphasis"
searchClass="!text-default !bg-default hover:!bg-emphasis"
dropdownClass="!text-default !bg-default"
inputStyle={{ width: "inherit", border: 0 }}
searchStyle={{
display: "flex",
flexDirection: "row",
alignItems: "center",
padding: "6px 12px",
gap: "8px",
width: "296px",
height: "28px",
marginLeft: "-4px",
}}
dropdownStyle={{ width: "max-content" }}
/>
);
}
function BasePhoneInputWeb({
name,
className = "",
onChange,
value,
inputStyle,
flagButtonStyle,
...rest
}: Omit<PhoneInputProps, "defaultCountry">) {
const defaultCountry = useDefaultCountry();
return (
<PhoneInput
{...rest}
value={value ? value.trim().replace(/^\+?/, "+") : undefined}
country={value ? undefined : defaultCountry}
enableSearch
disableSearchIcon
inputProps={{
name,
required: rest.required,
placeholder: rest.placeholder,
autoComplete: "tel",
}}
onChange={(val: string) => {
onChange(`+${val}`);
}}
containerClass={classNames(
"hover:border-emphasis dark:focus:border-emphasis border-default !bg-default rounded-md border focus-within:outline-none focus-within:ring-2 focus-within:ring-brand-default disabled:cursor-not-allowed",
className
)}
inputClass="text-sm focus:ring-0 !bg-default text-default placeholder:text-muted"
buttonClass="text-emphasis !bg-default hover:!bg-emphasis"
buttonStyle={{ ...flagButtonStyle }}
searchClass="!text-default !bg-default hover:!bg-emphasis"
dropdownClass="!text-default !bg-default"
inputStyle={{ width: "inherit", border: 0, ...inputStyle }}
searchStyle={{
display: "flex",
flexDirection: "row",
alignItems: "center",
padding: "6px 12px",
gap: "8px",
width: "296px",
height: "28px",
marginLeft: "-4px",
}}
dropdownStyle={{ width: "max-content" }}
/>
);
}
const useDefaultCountry = () => {
const defaultPhoneCountryFromStore = useBookerStore((state) => state.defaultPhoneCountry);
const [defaultCountry, setDefaultCountry] = useState<CountryCode>(defaultPhoneCountryFromStore || "us");
const query = trpc.viewer.public.countryCode.useQuery(undefined, {
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: false,
});
useEffect(
function refactorMeWithoutEffect() {
if (defaultPhoneCountryFromStore) {
setDefaultCountry(defaultPhoneCountryFromStore);
return;
}
const data = query.data;
if (!data?.countryCode) {
return;
}
if (isSupportedCountry(data?.countryCode)) {
setDefaultCountry(data.countryCode.toLowerCase() as CountryCode);
} else {
const navCountry = navigator.language.split("-")[1]?.toUpperCase();
if (navCountry && isSupportedCountry(navCountry)) {
setDefaultCountry(navCountry.toLowerCase() as CountryCode);
} else {
setDefaultCountry("us");
}
}
},
[query.data, defaultPhoneCountryFromStore]
);
return defaultCountry;
};
export default BasePhoneInput;