feat(custom-domains): allow to register a custom domain (without UI) (#9879)

# In this PR
- Allow to register a custom domain
- Refacto subdomain generation

# In other PRs
- Add UI to deal with a custom domain
- Add logic to work with custom domain
This commit is contained in:
Antoine Moreaux
2025-01-30 13:51:16 +01:00
committed by GitHub
parent ae4bf8d929
commit e895aa27e6
33 changed files with 1049 additions and 240 deletions

View File

@ -1,42 +1,27 @@
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useRedirectToWorkspaceDomain } from '@/domain-manager/hooks/useRedirectToWorkspaceDomain';
import { domainConfigurationState } from '@/domain-manager/states/domainConfigurationState';
import { useRecoilState } from 'recoil';
import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { SettingsPath } from '@/types/SettingsPath';
import { SnackBarVariant } from '@/ui/feedback/snack-bar-manager/components/SnackBar';
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
import { TextInputV2 } from '@/ui/input/components/TextInputV2';
import { SubMenuTopBarContainer } from '@/ui/layout/page/components/SubMenuTopBarContainer';
import { ApolloError } from '@apollo/client';
import styled from '@emotion/styled';
import { zodResolver } from '@hookform/resolvers/zod';
import { Trans, useLingui } from '@lingui/react/macro';
import { Controller, useForm } from 'react-hook-form';
import { useRecoilState, useRecoilValue } from 'recoil';
import { H2Title, Section } from 'twenty-ui';
import { z } from 'zod';
import { useUpdateWorkspaceMutation } from '~/generated/graphql';
import {
FeatureFlagKey,
useUpdateWorkspaceMutation,
} from '~/generated/graphql';
import { useRedirectToWorkspaceDomain } from '@/domain-manager/hooks/useRedirectToWorkspaceDomain';
import { SettingsHostname } from '~/pages/settings/workspace/SettingsHostname';
import { SettingsSubdomain } from '~/pages/settings/workspace/SettingsSubdomain';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import { useNavigateSettings } from '~/hooks/useNavigateSettings';
import { isDefined } from '~/utils/isDefined';
import { getSettingsPath } from '~/utils/navigation/getSettingsPath';
type Form = {
subdomain: string;
};
const StyledDomainFromWrapper = styled.div`
align-items: center;
display: flex;
`;
const StyledDomain = styled.h2`
align-self: flex-start;
color: ${({ theme }) => theme.font.color.secondary};
font-size: ${({ theme }) => theme.font.size.md};
font-weight: ${({ theme }) => theme.font.weight.medium};
margin: ${({ theme }) => theme.spacing(2)};
`;
import { ApolloError } from '@apollo/client';
import { Trans, useLingui } from '@lingui/react/macro';
import { z } from 'zod';
import { FormProvider, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { SubMenuTopBarContainer } from '@/ui/layout/page/components/SubMenuTopBarContainer';
import { SettingsPath } from '@/types/SettingsPath';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { SettingsHostnameEffect } from '~/pages/settings/workspace/SettingsHostnameEffect';
export const SettingsDomain = () => {
const navigate = useNavigateSettings();
@ -54,22 +39,21 @@ export const SettingsDomain = () => {
})
.required();
const domainConfiguration = useRecoilValue(domainConfigurationState);
const { enqueueSnackBar } = useSnackBar();
const [updateWorkspace] = useUpdateWorkspaceMutation();
const { redirectToWorkspaceDomain } = useRedirectToWorkspaceDomain();
const isCustomDomainEnabled = useIsFeatureEnabled(
FeatureFlagKey.IsCustomDomainEnabled,
);
const [currentWorkspace, setCurrentWorkspace] = useRecoilState(
currentWorkspaceState,
);
const {
control,
watch,
getValues,
formState: { isValid },
} = useForm<Form>({
const form = useForm<{
subdomain: string;
}>({
mode: 'onChange',
delayError: 500,
defaultValues: {
@ -78,12 +62,12 @@ export const SettingsDomain = () => {
resolver: zodResolver(validationSchema),
});
const subdomainValue = watch('subdomain');
const subdomainValue = form.watch('subdomain');
const handleSave = async () => {
const values = getValues();
const values = form.getValues();
if (!values || !isValid || !currentWorkspace) {
if (!values || !form.formState.isValid || !currentWorkspace) {
return enqueueSnackBar(t`Invalid form values`, {
variant: SnackBarVariant.Error,
});
@ -100,7 +84,7 @@ export const SettingsDomain = () => {
error instanceof ApolloError &&
error.graphQLErrors[0]?.extensions?.code === 'CONFLICT'
) {
return control.setError('subdomain', {
return form.control.setError('subdomain', {
type: 'manual',
message: t`Subdomain already taken`,
});
@ -137,7 +121,8 @@ export const SettingsDomain = () => {
actionButton={
<SaveAndCancelButtons
isSaveDisabled={
!isValid || subdomainValue === currentWorkspace?.subdomain
!form.formState.isValid ||
subdomainValue === currentWorkspace?.subdomain
}
onCancel={() => navigate(SettingsPath.Workspace)}
onSave={handleSave}
@ -145,39 +130,18 @@ export const SettingsDomain = () => {
}
>
<SettingsPageContainer>
<Section>
<H2Title
title={t`Domain`}
description={t`Set the name of your subdomain`}
/>
{currentWorkspace?.subdomain && (
<StyledDomainFromWrapper>
<Controller
name="subdomain"
control={control}
render={({
field: { onChange, value },
fieldState: { error },
}) => (
<>
<TextInputV2
value={value}
type="text"
onChange={onChange}
error={error?.message}
fullWidth
/>
{isDefined(domainConfiguration.frontDomain) && (
<StyledDomain>
.{domainConfiguration.frontDomain}
</StyledDomain>
)}
</>
)}
/>
</StyledDomainFromWrapper>
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<FormProvider {...form}>
{isCustomDomainEnabled && (
<>
<SettingsHostnameEffect />
<SettingsHostname />
</>
)}
</Section>
{(!currentWorkspace?.hostname || !isCustomDomainEnabled) && (
<SettingsSubdomain />
)}
</FormProvider>
</SettingsPageContainer>
</SubMenuTopBarContainer>
);

View File

@ -0,0 +1,150 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { Button, H2Title, Section } from 'twenty-ui';
import { TextInputV2 } from '@/ui/input/components/TextInputV2';
import { Controller, useForm } from 'react-hook-form';
import { z } from 'zod';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useRecoilState } from 'recoil';
import styled from '@emotion/styled';
import {
useUpdateWorkspaceMutation,
useGetHostnameDetailsQuery,
} from '~/generated/graphql';
import { isDefined } from '~/utils/isDefined';
import { useRedirectToWorkspaceDomain } from '@/domain-manager/hooks/useRedirectToWorkspaceDomain';
import { useLingui } from '@lingui/react/macro';
const validationSchema = z
.object({
hostname: z
.string()
.regex(
/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/,
{
message:
"Invalid custom hostname. Custom hostnames have to be smaller than 256 characters in length, cannot be IP addresses, cannot contain spaces, cannot contain any special characters such as _~`!@#$%^*()=+{}[]|\\;:'\",<>/? and cannot begin or end with a '-' character.",
},
)
.max(256)
.nullable(),
})
.required();
type Form = z.infer<typeof validationSchema>;
const StyledDomainFromWrapper = styled.div`
align-items: center;
display: flex;
`;
export const SettingsHostname = () => {
const [updateWorkspace] = useUpdateWorkspaceMutation();
const { data: getHostnameDetailsData } = useGetHostnameDetailsQuery();
const { redirectToWorkspaceDomain } = useRedirectToWorkspaceDomain();
const { t } = useLingui();
const [currentWorkspace, setCurrentWorkspace] = useRecoilState(
currentWorkspaceState,
);
const {
control,
getValues,
clearErrors,
handleSubmit,
formState: { isValid },
} = useForm<Form>({
mode: 'onSubmit',
defaultValues: {
hostname: currentWorkspace?.hostname ?? '',
},
resolver: zodResolver(validationSchema),
});
const handleDelete = async () => {
try {
if (!currentWorkspace) {
throw new Error('Invalid form values');
}
await updateWorkspace({
variables: {
input: {
hostname: null,
},
},
});
redirectToWorkspaceDomain(currentWorkspace.subdomain);
} catch (error) {
control.setError('hostname', {
type: 'manual',
message: (error as Error).message,
});
}
};
const handleSave = async () => {
const values = getValues();
try {
clearErrors();
if (!values || !isValid || !currentWorkspace) {
throw new Error('Invalid form values');
}
await updateWorkspace({
variables: {
input: {
hostname: values.hostname,
},
},
});
setCurrentWorkspace({
...currentWorkspace,
hostname: values.hostname,
});
// redirectToWorkspaceDomain(values.subdomain);
} catch (error) {
control.setError('hostname', {
type: 'manual',
message: (error as Error).message,
});
}
};
return (
<Section>
<H2Title title={t`Domain`} description={t`Set the name of your domain`} />
<StyledDomainFromWrapper>
<Controller
name="hostname"
control={control}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<TextInputV2
value={value ?? undefined}
type="text"
onChange={onChange}
error={error?.message}
fullWidth
/>
)}
/>
</StyledDomainFromWrapper>
<Button onClick={handleSubmit(handleSave)} title={'save'}></Button>
<Button onClick={handleSubmit(handleDelete)} title={'delete'}></Button>
{isDefined(getHostnameDetailsData?.getHostnameDetails?.hostname) && (
<pre>
{getHostnameDetailsData.getHostnameDetails.hostname} CNAME
app.twenty-main.com
</pre>
)}
{getHostnameDetailsData && (
<pre>{JSON.stringify(getHostnameDetailsData, null, 4)}</pre>
)}
</Section>
);
};

View File

@ -0,0 +1,28 @@
import { isDefined } from '~/utils/isDefined';
import { useEffect } from 'react';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useRecoilValue } from 'recoil';
import { useGetHostnameDetailsQuery } from '~/generated/graphql';
export const SettingsHostnameEffect = () => {
const { refetch } = useGetHostnameDetailsQuery();
const currentWorkspace = useRecoilValue(currentWorkspaceState);
useEffect(() => {
let pollIntervalFn: null | ReturnType<typeof setInterval> = null;
if (isDefined(currentWorkspace?.hostname)) {
pollIntervalFn = setInterval(async () => {
refetch();
}, 3000);
}
return () => {
if (isDefined(pollIntervalFn)) {
clearInterval(pollIntervalFn);
}
};
}, [currentWorkspace?.hostname, refetch]);
return <></>;
};

View File

@ -0,0 +1,63 @@
import { H2Title, Section } from 'twenty-ui';
import { TextInputV2 } from '@/ui/input/components/TextInputV2';
import { Controller, useFormContext } from 'react-hook-form';
import styled from '@emotion/styled';
import { useLingui } from '@lingui/react/macro';
import { isDefined } from '~/utils/isDefined';
import { domainConfigurationState } from '@/domain-manager/states/domainConfigurationState';
import { useRecoilValue } from 'recoil';
const StyledDomainFormWrapper = styled.div`
align-items: center;
display: flex;
`;
const StyledDomain = styled.h2`
align-self: flex-start;
color: ${({ theme }) => theme.font.color.secondary};
font-size: ${({ theme }) => theme.font.size.md};
font-weight: ${({ theme }) => theme.font.weight.medium};
margin: ${({ theme }) => theme.spacing(2)};
white-space: nowrap;
`;
export const SettingsSubdomain = () => {
const domainConfiguration = useRecoilValue(domainConfigurationState);
const { t } = useLingui();
const { control } = useFormContext<{
subdomain: string;
}>();
return (
<Section>
<H2Title
title={t`Subdomain`}
description={t`Set the name of your subdomain`}
/>
<StyledDomainFormWrapper>
<Controller
name="subdomain"
control={control}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<>
<TextInputV2
value={value}
type="text"
onChange={onChange}
error={error?.message}
fullWidth
/>
{isDefined(domainConfiguration.frontDomain) && (
<StyledDomain>
{`.${domainConfiguration.frontDomain}`}
</StyledDomain>
)}
</>
)}
/>
</StyledDomainFormWrapper>
</Section>
);
};