feat: add public profiles

This commit is contained in:
David Nguyen
2024-06-06 14:46:48 +10:00
parent d11a68fc4c
commit 5514dad4d8
43 changed files with 2067 additions and 137 deletions

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,236 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { motion } from 'framer-motion';
import { AnimatePresence } from 'framer-motion';
import { 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 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.userMessage,
});
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 () =>
copy(formatUserProfilePath(form.getValues('url') ?? '')).then(() => {
toast({
title: 'Copied to clipboard',
description: 'The profile link has been copied to your clipboard',
});
});
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">
<CopyIcon className="h-3.5 w-3.5" />
</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,423 @@
'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 must be at least 1 character long' })
.max(MAX_TEMPLATE_PUBLIC_TITLE_LENGTH),
publicDescription: z
.string()
.min(1, { message: 'Description must be at least 1 character long' })
.max(MAX_TEMPLATE_PUBLIC_DESCRIPTION_LENGTH),
});
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,
});
} 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" />
) : (
<CircleIcon className="h-5 w-5 text-neutral-300" />
)}
</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>
);
};