2023-02-15 18:40:29 +00:00
|
|
|
import { useRouter } from "next/router";
|
|
|
|
import { useState } from "react";
|
2022-12-07 20:15:15 +00:00
|
|
|
import { Controller, useForm } from "react-hook-form";
|
|
|
|
|
2022-07-06 19:31:07 +00:00
|
|
|
import { IS_SELF_HOSTED } from "@calcom/lib/constants";
|
2023-02-16 22:39:57 +00:00
|
|
|
import type { User } from "@calcom/prisma/client";
|
|
|
|
import type { TRPCClientErrorLike } from "@calcom/trpc/client";
|
|
|
|
import type { AppRouter } from "@calcom/trpc/server/routers/_app";
|
2022-07-06 19:31:07 +00:00
|
|
|
|
2023-02-10 13:23:24 +00:00
|
|
|
import useRouterQuery from "@lib/hooks/useRouterQuery";
|
|
|
|
|
2022-07-06 19:31:07 +00:00
|
|
|
import { PremiumTextfield } from "./PremiumTextfield";
|
|
|
|
import { UsernameTextfield } from "./UsernameTextfield";
|
|
|
|
|
|
|
|
export const UsernameAvailability = IS_SELF_HOSTED ? UsernameTextfield : PremiumTextfield;
|
2022-12-07 20:15:15 +00:00
|
|
|
|
|
|
|
interface UsernameAvailabilityFieldProps {
|
|
|
|
onSuccessMutation?: () => void;
|
|
|
|
onErrorMutation?: (error: TRPCClientErrorLike<AppRouter>) => void;
|
2022-12-08 09:50:03 +00:00
|
|
|
user: Pick<User, "username" | "metadata">;
|
2022-12-07 20:15:15 +00:00
|
|
|
}
|
|
|
|
export const UsernameAvailabilityField = ({
|
|
|
|
onSuccessMutation,
|
|
|
|
onErrorMutation,
|
|
|
|
user,
|
|
|
|
}: UsernameAvailabilityFieldProps) => {
|
2023-02-15 18:40:29 +00:00
|
|
|
const router = useRouter();
|
|
|
|
const [currentUsernameState, setCurrentUsernameState] = useState(user.username || "");
|
|
|
|
const { username: usernameFromQuery, setQuery: setUsernameFromQuery } = useRouterQuery("username");
|
|
|
|
const { username: currentUsername, setQuery: setCurrentUsername } =
|
|
|
|
router.query["username"] && user.username === null
|
|
|
|
? { username: usernameFromQuery, setQuery: setUsernameFromQuery }
|
|
|
|
: { username: currentUsernameState || "", setQuery: setCurrentUsernameState };
|
2022-12-07 20:15:15 +00:00
|
|
|
const formMethods = useForm({
|
|
|
|
defaultValues: {
|
|
|
|
username: currentUsername,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return (
|
|
|
|
<Controller
|
|
|
|
control={formMethods.control}
|
|
|
|
name="username"
|
|
|
|
render={({ field: { ref, onChange, value } }) => {
|
|
|
|
return (
|
|
|
|
<UsernameAvailability
|
|
|
|
currentUsername={currentUsername}
|
|
|
|
setCurrentUsername={setCurrentUsername}
|
|
|
|
inputUsernameValue={value}
|
|
|
|
usernameRef={ref}
|
|
|
|
setInputUsernameValue={onChange}
|
|
|
|
onSuccessMutation={onSuccessMutation}
|
|
|
|
onErrorMutation={onErrorMutation}
|
|
|
|
user={user}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
}}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
};
|