feat: add public profiles (#1180)

## Description

Add public profiles

## Changes

- Add profiles settings page for users and teams
- Add profiles page `/p/<url>`

## Not completed

- Pending tests
- UI changes to promote public profiles (sign up, etc)
This commit is contained in:
Lucas Smith
2024-06-27 22:47:20 +10:00
committed by GitHub
50 changed files with 2781 additions and 164 deletions

View File

@ -7,6 +7,7 @@ import { motion } from 'framer-motion';
import { CheckCircle2, ChevronsUpDown, Plus, Settings2 } from 'lucide-react';
import { signOut } from 'next-auth/react';
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
import { TEAM_MEMBER_ROLE_MAP, TEAM_URL_REGEX } from '@documenso/lib/constants/teams';
import { isAdmin } from '@documenso/lib/next-auth/guards/is-admin';
import type { GetTeamsResponse } from '@documenso/lib/server-only/team/get-teams';
@ -99,6 +100,9 @@ export const MenuSwitcher = ({ user, teams: initialTeamsData }: MenuSwitcherProp
className="relative flex h-12 flex-row items-center px-0 py-2 ring-0 focus:outline-none focus-visible:border-0 focus-visible:ring-0 focus-visible:ring-transparent md:px-2"
>
<AvatarWithText
avatarSrc={`${NEXT_PUBLIC_WEBAPP_URL()}/api/avatar/${
selectedTeam ? selectedTeam.avatarImageId : user.avatarImageId
}`}
avatarFallback={formatAvatarFallback(selectedTeam?.name)}
primaryText={selectedTeam ? selectedTeam.name : user.name}
secondaryText={formatSecondaryAvatarText(selectedTeam)}
@ -122,6 +126,11 @@ export const MenuSwitcher = ({ user, teams: initialTeamsData }: MenuSwitcherProp
<DropdownMenuItem asChild>
<Link href={formatRedirectUrlOnSwitch()}>
<AvatarWithText
avatarSrc={
user.avatarImageId
? `${NEXT_PUBLIC_WEBAPP_URL()}/api/avatar/${user.avatarImageId}`
: undefined
}
avatarFallback={formatAvatarFallback()}
primaryText={user.name}
secondaryText={formatSecondaryAvatarText()}
@ -180,10 +189,15 @@ export const MenuSwitcher = ({ user, teams: initialTeamsData }: MenuSwitcherProp
href={formatRedirectUrlOnSwitch(team.url)}
>
<AvatarWithText
avatarSrc={
team.avatarImageId
? `${NEXT_PUBLIC_WEBAPP_URL()}/api/avatar/${team.avatarImageId}`
: undefined
}
avatarFallback={formatAvatarFallback(team.name)}
primaryText={team.name}
secondaryText={
<div className="relative">
<div className="relative w-full">
<motion.span
className="overflow-hidden"
variants={{

View File

@ -5,7 +5,7 @@ import type { HTMLAttributes } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Braces, CreditCard, Lock, User, Users, Webhook } from 'lucide-react';
import { Braces, CreditCard, Globe2Icon, Lock, User, Users, Webhook } from 'lucide-react';
import { useFeatureFlags } from '@documenso/lib/client-only/providers/feature-flag';
import { cn } from '@documenso/ui/lib/utils';
@ -19,6 +19,7 @@ export const DesktopNav = ({ className, ...props }: DesktopNavProps) => {
const { getFlag } = useFeatureFlags();
const isBillingEnabled = getFlag('app_billing');
const isPublicProfileEnabled = getFlag('app_public_profile');
return (
<div className={cn('flex flex-col gap-y-2', className)} {...props}>
@ -35,6 +36,21 @@ export const DesktopNav = ({ className, ...props }: DesktopNavProps) => {
</Button>
</Link>
{isPublicProfileEnabled && (
<Link href="/settings/public-profile">
<Button
variant="ghost"
className={cn(
'w-full justify-start',
pathname?.startsWith('/settings/public-profile') && 'bg-secondary',
)}
>
<Globe2Icon className="mr-2 h-5 w-5" />
Public Profile
</Button>
</Link>
)}
<Link href="/settings/teams">
<Button
variant="ghost"

View File

@ -5,7 +5,7 @@ import type { HTMLAttributes } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Braces, CreditCard, Lock, User, Users, Webhook } from 'lucide-react';
import { Braces, CreditCard, Globe2Icon, Lock, User, Users, Webhook } from 'lucide-react';
import { useFeatureFlags } from '@documenso/lib/client-only/providers/feature-flag';
import { cn } from '@documenso/ui/lib/utils';
@ -19,6 +19,7 @@ export const MobileNav = ({ className, ...props }: MobileNavProps) => {
const { getFlag } = useFeatureFlags();
const isBillingEnabled = getFlag('app_billing');
const isPublicProfileEnabled = getFlag('app_public_profile');
return (
<div
@ -38,6 +39,21 @@ export const MobileNav = ({ className, ...props }: MobileNavProps) => {
</Button>
</Link>
{isPublicProfileEnabled && (
<Link href="/settings/public-profile">
<Button
variant="ghost"
className={cn(
'w-full justify-start',
pathname?.startsWith('/settings/public-profile') && 'bg-secondary',
)}
>
<Globe2Icon className="mr-2 h-5 w-5" />
Public Profile
</Button>
</Link>
)}
<Link href="/settings/teams">
<Button
variant="ghost"

View File

@ -5,8 +5,9 @@ import type { HTMLAttributes } from 'react';
import Link from 'next/link';
import { useParams, usePathname } from 'next/navigation';
import { Braces, CreditCard, Settings, Users, Webhook } from 'lucide-react';
import { Braces, CreditCard, Globe2Icon, Settings, Users, Webhook } from 'lucide-react';
import { useFeatureFlags } from '@documenso/lib/client-only/providers/feature-flag';
import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
@ -17,9 +18,14 @@ export const DesktopNav = ({ className, ...props }: DesktopNavProps) => {
const pathname = usePathname();
const params = useParams();
const { getFlag } = useFeatureFlags();
const isPublicProfileEnabled = getFlag('app_public_profile');
const teamUrl = typeof params?.teamUrl === 'string' ? params?.teamUrl : '';
const settingsPath = `/t/${teamUrl}/settings`;
const publicProfilePath = `/t/${teamUrl}/settings/public-profile`;
const membersPath = `/t/${teamUrl}/settings/members`;
const tokensPath = `/t/${teamUrl}/settings/tokens`;
const webhooksPath = `/t/${teamUrl}/settings/webhooks`;
@ -37,6 +43,21 @@ export const DesktopNav = ({ className, ...props }: DesktopNavProps) => {
</Button>
</Link>
{isPublicProfileEnabled && (
<Link href={publicProfilePath}>
<Button
variant="ghost"
className={cn(
'w-full justify-start',
pathname?.startsWith(publicProfilePath) && 'bg-secondary',
)}
>
<Globe2Icon className="mr-2 h-5 w-5" />
Public Profile
</Button>
</Link>
)}
<Link href={membersPath}>
<Button
variant="ghost"

View File

@ -5,8 +5,9 @@ import type { HTMLAttributes } from 'react';
import Link from 'next/link';
import { useParams, usePathname } from 'next/navigation';
import { Braces, CreditCard, Key, User, Webhook } from 'lucide-react';
import { Braces, CreditCard, Globe2Icon, Key, User, Webhook } from 'lucide-react';
import { useFeatureFlags } from '@documenso/lib/client-only/providers/feature-flag';
import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
@ -17,9 +18,14 @@ export const MobileNav = ({ className, ...props }: MobileNavProps) => {
const pathname = usePathname();
const params = useParams();
const { getFlag } = useFeatureFlags();
const isPublicProfileEnabled = getFlag('app_public_profile');
const teamUrl = typeof params?.teamUrl === 'string' ? params?.teamUrl : '';
const settingsPath = `/t/${teamUrl}/settings`;
const publicProfilePath = `/t/${teamUrl}/settings/public-profile`;
const membersPath = `/t/${teamUrl}/settings/members`;
const tokensPath = `/t/${teamUrl}/settings/tokens`;
const webhooksPath = `/t/${teamUrl}/settings/webhooks`;
@ -45,6 +51,21 @@ export const MobileNav = ({ className, ...props }: MobileNavProps) => {
</Button>
</Link>
{isPublicProfileEnabled && (
<Link href={publicProfilePath}>
<Button
variant="ghost"
className={cn(
'w-full justify-start',
pathname?.startsWith(publicProfilePath) && 'bg-secondary',
)}
>
<Globe2Icon className="mr-2 h-5 w-5" />
Public Profile
</Button>
</Link>
)}
<Link href={membersPath}>
<Button
variant="ghost"

View File

@ -0,0 +1,189 @@
'use client';
import { useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { zodResolver } from '@hookform/resolvers/zod';
import { ErrorCode, useDropzone } from 'react-dropzone';
import { useForm } from 'react-hook-form';
import { match } from 'ts-pattern';
import { z } from 'zod';
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
import { base64 } from '@documenso/lib/universal/base64';
import { extractInitials } from '@documenso/lib/utils/recipient-formatter';
import type { Team, User } from '@documenso/prisma/client';
import { TRPCClientError } from '@documenso/trpc/client';
import { trpc } from '@documenso/trpc/react';
import { cn } from '@documenso/ui/lib/utils';
import { Avatar, AvatarFallback, AvatarImage } from '@documenso/ui/primitives/avatar';
import { Button } from '@documenso/ui/primitives/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@documenso/ui/primitives/form/form';
import { useToast } from '@documenso/ui/primitives/use-toast';
export const ZAvatarImageFormSchema = z.object({
bytes: z.string().nullish(),
});
export type TAvatarImageFormSchema = z.infer<typeof ZAvatarImageFormSchema>;
export type AvatarImageFormProps = {
className?: string;
user: User;
team?: Team;
};
export const AvatarImageForm = ({ className, user, team }: AvatarImageFormProps) => {
const { toast } = useToast();
const router = useRouter();
const { mutateAsync: setProfileImage } = trpc.profile.setProfileImage.useMutation();
const initials = extractInitials(team?.name || user.name || '');
const hasAvatarImage = useMemo(() => {
if (team) {
return team.avatarImageId !== null;
}
return user.avatarImageId !== null;
}, [team, user.avatarImageId]);
const avatarImageId = team ? team.avatarImageId : user.avatarImageId;
const form = useForm<TAvatarImageFormSchema>({
values: {
bytes: null,
},
resolver: zodResolver(ZAvatarImageFormSchema),
});
const { getRootProps, getInputProps } = useDropzone({
maxSize: 1024 * 1024,
accept: {
'image/*': ['.png', '.jpg', '.jpeg'],
},
multiple: false,
onDropAccepted: ([file]) => {
void file.arrayBuffer().then((buffer) => {
const contents = base64.encode(new Uint8Array(buffer));
form.setValue('bytes', contents);
void form.handleSubmit(onFormSubmit)();
});
},
onDropRejected: ([file]) => {
form.setError('bytes', {
type: 'onChange',
message: match(file.errors[0].code)
.with(ErrorCode.FileTooLarge, () => 'Uploaded file is too large')
.with(ErrorCode.FileTooSmall, () => 'Uploaded file is too small')
.with(ErrorCode.FileInvalidType, () => 'Uploaded file not an allowed file type')
.otherwise(() => 'An unknown error occurred'),
});
},
});
const onFormSubmit = async (data: TAvatarImageFormSchema) => {
try {
await setProfileImage({
bytes: data.bytes,
teamId: team?.id,
});
toast({
title: 'Avatar Updated',
description: 'Your avatar has been updated successfully.',
duration: 5000,
});
router.refresh();
} catch (err) {
if (err instanceof TRPCClientError && err.data?.code === 'BAD_REQUEST') {
toast({
title: 'An error occurred',
description: err.message,
variant: 'destructive',
});
} else {
toast({
title: 'An unknown error occurred',
variant: 'destructive',
description:
'We encountered an unknown error while attempting to update the avatar. Please try again later.',
});
}
}
};
return (
<Form {...form}>
<form
className={cn('flex w-full flex-col gap-y-4', className)}
// onSubmit={form.handleSubmit(onFormSubmit)}
>
<fieldset className="flex w-full flex-col gap-y-4" disabled={form.formState.isSubmitting}>
<FormField
control={form.control}
name="bytes"
render={() => (
<FormItem>
<FormLabel>Avatar</FormLabel>
<FormControl>
<div className="flex items-center gap-8">
<div className="relative">
<Avatar className="h-16 w-16 border-2 border-solid">
{avatarImageId && (
<AvatarImage
src={`${NEXT_PUBLIC_WEBAPP_URL()}/api/avatar/${avatarImageId}`}
/>
)}
<AvatarFallback className="text-sm text-gray-400">
{initials}
</AvatarFallback>
</Avatar>
{hasAvatarImage && (
<button
type="button"
className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100"
disabled={form.formState.isSubmitting}
onClick={() => void onFormSubmit({ bytes: null })}
>
Remove
</button>
)}
</div>
<Button
type="button"
variant="secondary"
size="sm"
{...getRootProps()}
loading={form.formState.isSubmitting}
disabled={form.formState.isSubmitting}
>
Upload Avatar
<input {...getInputProps()} />
</Button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</fieldset>
</form>
</Form>
);
};

View File

@ -0,0 +1,265 @@
'use client';
import { useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { motion } from 'framer-motion';
import { AnimatePresence } from 'framer-motion';
import { CheckSquareIcon, CopyIcon } from 'lucide-react';
import { useForm } from 'react-hook-form';
import type { z } from 'zod';
import { useCopyToClipboard } from '@documenso/lib/client-only/hooks/use-copy-to-clipboard';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { formatUserProfilePath } from '@documenso/lib/utils/public-profiles';
import type { TeamProfile, UserProfile } from '@documenso/prisma/client';
import {
MAX_PROFILE_BIO_LENGTH,
ZUpdatePublicProfileMutationSchema,
} from '@documenso/trpc/server/profile-router/schema';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@documenso/ui/primitives/form/form';
import { Input } from '@documenso/ui/primitives/input';
import { Textarea } from '@documenso/ui/primitives/textarea';
import { useToast } from '@documenso/ui/primitives/use-toast';
export const ZPublicProfileFormSchema = ZUpdatePublicProfileMutationSchema.pick({
bio: true,
enabled: true,
url: true,
});
export type TPublicProfileFormSchema = z.infer<typeof ZPublicProfileFormSchema>;
export type PublicProfileFormProps = {
className?: string;
profileUrl?: string | null;
teamUrl?: string;
onProfileUpdate: (data: TPublicProfileFormSchema) => Promise<unknown>;
profile: UserProfile | TeamProfile;
};
export const PublicProfileForm = ({
className,
profileUrl,
profile,
teamUrl,
onProfileUpdate,
}: PublicProfileFormProps) => {
const { toast } = useToast();
const [, copy] = useCopyToClipboard();
const [copiedTimeout, setCopiedTimeout] = useState<NodeJS.Timeout | null>(null);
const form = useForm<TPublicProfileFormSchema>({
values: {
url: profileUrl ?? '',
bio: profile?.bio ?? '',
},
resolver: zodResolver(ZPublicProfileFormSchema),
});
const isSubmitting = form.formState.isSubmitting;
const onFormSubmit = async (data: TPublicProfileFormSchema) => {
try {
await onProfileUpdate(data);
toast({
title: 'Success',
description: 'Your public profile has been updated.',
duration: 5000,
});
form.reset({
url: data.url,
bio: data.bio,
});
} catch (err) {
const error = AppError.parseError(err);
switch (error.code) {
case AppErrorCode.PREMIUM_PROFILE_URL:
case AppErrorCode.PROFILE_URL_TAKEN:
form.setError('url', {
type: 'manual',
message: error.message,
});
break;
default:
toast({
title: 'An unknown error occurred',
variant: 'destructive',
description:
'We encountered an unknown error while attempting to update your public profile. Please try again later.',
});
}
}
};
const onCopy = async () => {
await copy(formatUserProfilePath(form.getValues('url') ?? '')).then(() => {
toast({
title: 'Copied to clipboard',
description: 'The profile link has been copied to your clipboard',
});
});
if (copiedTimeout) {
clearTimeout(copiedTimeout);
}
setCopiedTimeout(
setTimeout(() => {
setCopiedTimeout(null);
}, 2000),
);
};
return (
<Form {...form}>
<form
className={cn('flex w-full flex-col gap-y-4', className)}
onSubmit={form.handleSubmit(onFormSubmit)}
>
<fieldset className="flex w-full flex-col gap-y-4" disabled={isSubmitting}>
<FormField
control={form.control}
name="url"
render={({ field }) => (
<FormItem>
<FormLabel>Public profile URL</FormLabel>
<FormControl>
<Input {...field} disabled={field.disabled || teamUrl !== undefined} />
</FormControl>
{teamUrl && (
<p className="text-muted-foreground text-xs">
You can update the profile URL by updating the team URL in the general settings
page.
</p>
)}
<div className="h-8">
{!form.formState.errors.url && (
<div className="text-muted-foreground h-8 text-sm">
{field.value ? (
<div>
<Button
type="button"
variant="none"
className="h-7 rounded bg-neutral-50 pl-2 pr-0.5 font-normal dark:border dark:border-neutral-500 dark:bg-neutral-600"
onClick={async () => onCopy()}
>
<p>
{formatUserProfilePath('').replace(/https?:\/\//, '')}
<span className="font-semibold">{field.value}</span>
</p>
<div className="ml-1 flex h-6 w-6 items-center justify-center rounded transition-all hover:bg-neutral-200 hover:active:bg-neutral-300 dark:hover:bg-neutral-500 dark:hover:active:bg-neutral-400">
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={copiedTimeout ? 'copied' : 'copy'}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0, transition: { duration: 0.1 } }}
className="absolute"
>
{copiedTimeout ? (
<CheckSquareIcon className="h-3.5 w-3.5" />
) : (
<CopyIcon className="h-3.5 w-3.5" />
)}
</motion.div>
</AnimatePresence>
</div>
</Button>
</div>
) : (
<p>A unique URL to access your profile</p>
)}
</div>
)}
<FormMessage />
</div>
</FormItem>
)}
/>
<FormField
control={form.control}
name="bio"
render={({ field }) => {
const remaningLength = MAX_PROFILE_BIO_LENGTH - (field.value || '').length;
const pluralWord = Math.abs(remaningLength) === 1 ? 'character' : 'characters';
return (
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea
{...field}
placeholder={teamUrl ? 'Write about the team' : 'Write about yourself'}
/>
</FormControl>
{!form.formState.errors.bio && (
<p className="text-muted-foreground text-sm">
{remaningLength >= 0
? `${remaningLength} ${pluralWord} remaining`
: `${Math.abs(remaningLength)} ${pluralWord} over the limit`}
</p>
)}
<FormMessage />
</FormItem>
);
}}
/>
<div className="flex flex-row justify-end space-x-4">
<AnimatePresence>
{form.formState.isDirty && (
<motion.div
initial={{
opacity: 0,
}}
animate={{
opacity: 1,
}}
exit={{
opacity: 0,
}}
>
<Button type="button" variant="secondary" onClick={() => form.reset()}>
Reset
</Button>
</motion.div>
)}
</AnimatePresence>
<Button
type="submit"
className="transition-opacity"
disabled={!form.formState.isDirty}
loading={form.formState.isSubmitting}
>
Update
</Button>
</div>
</fieldset>
</form>
</Form>
);
};

View File

@ -0,0 +1,429 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import type * as DialogPrimitive from '@radix-ui/react-dialog';
import { CheckCircle2Icon, CircleIcon } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { P, match } from 'ts-pattern';
import { z } from 'zod';
import type { Template, TemplateDirectLink } from '@documenso/prisma/client';
import { TemplateType } from '@documenso/prisma/client';
import { trpc } from '@documenso/trpc/react';
import {
MAX_TEMPLATE_PUBLIC_DESCRIPTION_LENGTH,
MAX_TEMPLATE_PUBLIC_TITLE_LENGTH,
} from '@documenso/trpc/server/template-router/schema';
import { AnimateGenericFadeInOut } from '@documenso/ui/components/animate/animate-generic-fade-in-out';
import { Button } from '@documenso/ui/primitives/button';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@documenso/ui/primitives/dialog';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@documenso/ui/primitives/form/form';
import { Input } from '@documenso/ui/primitives/input';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@documenso/ui/primitives/table';
import { Textarea } from '@documenso/ui/primitives/textarea';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { useOptionalCurrentTeam } from '~/providers/team';
import { LocaleDate } from '../formatter/locale-date';
export type ManagePublicTemplateDialogProps = {
directTemplates: (Template & {
directLink: Pick<TemplateDirectLink, 'token' | 'enabled'>;
})[];
initialTemplateId?: number | null;
initialStep?: ProfileTemplateStep;
trigger?: React.ReactNode;
isOpen?: boolean;
onIsOpenChange?: (value: boolean) => unknown;
} & Omit<DialogPrimitive.DialogProps, 'children'>;
const ZUpdatePublicTemplateFormSchema = z.object({
publicTitle: z
.string()
.min(1, { message: 'Title is required' })
.max(MAX_TEMPLATE_PUBLIC_TITLE_LENGTH, {
message: `Title cannot be longer than ${MAX_TEMPLATE_PUBLIC_TITLE_LENGTH} characters`,
}),
publicDescription: z
.string()
.min(1, { message: 'Description is required' })
.max(MAX_TEMPLATE_PUBLIC_DESCRIPTION_LENGTH, {
message: `Description cannot be longer than ${MAX_TEMPLATE_PUBLIC_DESCRIPTION_LENGTH} characters`,
}),
});
type TUpdatePublicTemplateFormSchema = z.infer<typeof ZUpdatePublicTemplateFormSchema>;
type ProfileTemplateStep = 'SELECT_TEMPLATE' | 'MANAGE' | 'CONFIRM_DISABLE';
export const ManagePublicTemplateDialog = ({
directTemplates,
trigger,
initialTemplateId = null,
initialStep = 'SELECT_TEMPLATE',
isOpen = false,
onIsOpenChange,
...props
}: ManagePublicTemplateDialogProps) => {
const { toast } = useToast();
const [open, onOpenChange] = useState(isOpen);
const team = useOptionalCurrentTeam();
const [selectedTemplateId, setSelectedTemplateId] = useState<number | null>(initialTemplateId);
const [currentStep, setCurrentStep] = useState<ProfileTemplateStep>(() => {
if (initialStep) {
return initialStep;
}
return selectedTemplateId ? 'MANAGE' : 'SELECT_TEMPLATE';
});
const form = useForm({
resolver: zodResolver(ZUpdatePublicTemplateFormSchema),
defaultValues: {
publicTitle: '',
publicDescription: '',
},
});
const { mutateAsync: updateTemplateSettings, isLoading: isUpdatingTemplateSettings } =
trpc.template.updateTemplateSettings.useMutation();
const setTemplateToPrivate = async (templateId: number) => {
try {
await updateTemplateSettings({
templateId,
teamId: team?.id,
data: {
type: TemplateType.PRIVATE,
},
});
toast({
title: 'Success',
description: 'Template has been removed from your public profile.',
duration: 5000,
});
handleOnOpenChange(false);
} catch {
toast({
title: 'An unknown error occurred',
variant: 'destructive',
description:
'We encountered an unknown error while attempting to remove this template from your profile. Please try again later.',
});
}
};
const onFormSubmit = async ({
publicTitle,
publicDescription,
}: TUpdatePublicTemplateFormSchema) => {
if (!selectedTemplateId) {
return;
}
try {
await updateTemplateSettings({
templateId: selectedTemplateId,
teamId: team?.id,
data: {
type: TemplateType.PUBLIC,
publicTitle,
publicDescription,
},
});
toast({
title: 'Success',
description: 'Template has been updated.',
duration: 5000,
});
onOpenChange(false);
} catch {
toast({
title: 'An unknown error occurred',
variant: 'destructive',
description:
'We encountered an unknown error while attempting to update the template. Please try again later.',
});
}
};
const selectedTemplate = useMemo(
() => directTemplates.find((template) => template.id === selectedTemplateId),
[directTemplates, selectedTemplateId],
);
const onManageStep = () => {
if (!selectedTemplate) {
return;
}
form.reset({
publicTitle: selectedTemplate.publicTitle,
publicDescription: selectedTemplate.publicDescription,
});
setCurrentStep('MANAGE');
};
const isLoading = isUpdatingTemplateSettings || form.formState.isSubmitting;
useEffect(() => {
const initialTemplate = directTemplates.find((template) => template.id === initialTemplateId);
if (initialTemplate) {
setSelectedTemplateId(initialTemplate.id);
form.reset({
publicTitle: initialTemplate.publicTitle,
publicDescription: initialTemplate.publicDescription,
});
} else {
setSelectedTemplateId(null);
}
const step = initialStep || (selectedTemplateId ? 'MANAGE' : 'SELECT_TEMPLATE');
setCurrentStep(step);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialTemplateId, initialStep, open, isOpen]);
const handleOnOpenChange = (value: boolean) => {
if (isLoading || typeof value !== 'boolean') {
return;
}
onOpenChange(value);
onIsOpenChange?.(value);
};
return (
<Dialog {...props} open={isOpen || open} onOpenChange={handleOnOpenChange}>
<fieldset disabled={isLoading} className="relative flex-shrink-0">
<DialogTrigger asChild>{trigger}</DialogTrigger>
<AnimateGenericFadeInOut motionKey={currentStep}>
{match({ templateId: selectedTemplateId, currentStep })
.with({ currentStep: 'SELECT_TEMPLATE' }, () => (
<DialogContent>
<DialogHeader>
<DialogTitle>{team?.name || 'Your'} direct signing templates</DialogTitle>
<DialogDescription>
Select a template you'd like to display on your {team && `team's`} public
profile
</DialogDescription>
</DialogHeader>
<div className="custom-scrollbar max-h-[60vh] overflow-y-auto rounded-md border">
<Table overflowHidden>
<TableHeader>
<TableRow>
<TableHead>Template</TableHead>
<TableHead>Created</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{directTemplates.length === 0 && (
<TableRow>
<TableCell colSpan={3} className="h-16 text-center">
<p className="text-muted-foreground">No valid direct templates found</p>
</TableCell>
</TableRow>
)}
{directTemplates.map((row) => (
<TableRow
className="w-full cursor-pointer"
key={row.id}
onClick={() => setSelectedTemplateId(row.id)}
>
<TableCell className="text-muted-foreground max-w-[30ch] text-sm">
{row.title}
</TableCell>
<TableCell className="text-muted-foreground text-sm">
<LocaleDate date={row.createdAt} />
</TableCell>
<TableCell>
{selectedTemplateId === row.id ? (
<CheckCircle2Icon className="h-5 w-5 text-neutral-600 dark:text-neutral-200" />
) : (
<CircleIcon className="h-5 w-5 text-neutral-300 dark:text-neutral-600" />
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="secondary">
Close
</Button>
</DialogClose>
<Button
type="button"
disabled={selectedTemplateId === null}
onClick={() => onManageStep()}
>
Continue
</Button>
</DialogFooter>
</DialogContent>
))
.with({ templateId: P.number, currentStep: 'MANAGE' }, () => (
<DialogContent className="relative">
<DialogHeader>
<DialogTitle>Configure template</DialogTitle>
<DialogDescription>Manage details for this public template</DialogDescription>
</DialogHeader>
<Form {...form}>
<form
className="flex h-full flex-col space-y-4"
onSubmit={form.handleSubmit(onFormSubmit)}
>
<FormField
control={form.control}
name="publicTitle"
render={({ field }) => (
<FormItem>
<FormLabel required>Title</FormLabel>
<FormControl>
<Input placeholder="The public name for your template" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="publicDescription"
render={({ field }) => {
const remaningLength =
MAX_TEMPLATE_PUBLIC_DESCRIPTION_LENGTH - (field.value || '').length;
const pluralWord =
Math.abs(remaningLength) === 1 ? 'character' : 'characters';
return (
<FormItem>
<FormLabel required>Description</FormLabel>
<FormControl>
<Textarea
placeholder="The public description that will be displayed with this template"
{...field}
/>
</FormControl>
{!form.formState.errors.publicDescription && (
<p className="text-muted-foreground text-sm">
{remaningLength >= 0
? `${remaningLength} ${pluralWord} remaining`
: `${Math.abs(remaningLength)} ${pluralWord} over the limit`}
</p>
)}
<FormMessage />
</FormItem>
);
}}
/>
<DialogFooter>
{selectedTemplate?.type === TemplateType.PUBLIC && (
<Button
variant="destructive"
className="mr-auto w-full sm:w-auto"
onClick={() => setCurrentStep('CONFIRM_DISABLE')}
>
Disable
</Button>
)}
<DialogClose asChild>
<Button variant="secondary">Close</Button>
</DialogClose>
<Button type="submit" loading={isUpdatingTemplateSettings}>
Update
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
))
.with({ templateId: P.number, currentStep: 'CONFIRM_DISABLE' }, ({ templateId }) => (
<DialogContent className="relative">
<DialogHeader>
<DialogTitle>Are you sure?</DialogTitle>
<DialogDescription>
The template will be removed from your profile
</DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="secondary">
Cancel
</Button>
</DialogClose>
<Button
type="button"
variant="destructive"
loading={isUpdatingTemplateSettings}
onClick={() => void setTemplateToPrivate(templateId)}
>
Confirm
</Button>
</DialogFooter>
</DialogContent>
))
.otherwise(() => null)}
</AnimateGenericFadeInOut>
</fieldset>
</Dialog>
);
};