Merge branch 'main' into harkirat/Protect

This commit is contained in:
Adithya Krishna
2024-01-03 11:34:42 +05:30
committed by GitHub
63 changed files with 703 additions and 200 deletions

View File

@ -15,11 +15,10 @@ jobs:
- uses: actions/stale@v4
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
days-before-pr-stale: 30
days-before-issue-stale: 30
stale-issue-message: 'This issue has not seen activity for a while. It will be closed in 30 days unless further activity is detected'
days-before-pr-stale: 90
days-before-issue-stale: 90
days-before-issue-close: 180
stale-pr-message: 'This PR has not seen activitiy for a while. It will be closed in 30 days unless further activity is detected.'
close-issue-message: 'This issue has been closed because of inactivity.'
close-pr-message: 'This PR has been closed because of inactivity.'
exempt-pr-labels: 'WIP,on-hold,needs review'
exempt-issue-labels: 'WIP,on-hold,needs review,roadmap,assigned'
exempt-issue-labels: 'WIP,on-hold,needs review,roadmap,assigned,needs triage'

View File

@ -115,10 +115,12 @@ To run Documenso locally, you will need
Want to get up and running quickly? Follow these steps:
1. [Clone the repository](https://help.github.com/articles/cloning-a-repository/) it to your local device.
1. [Fork this repository](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/about-forks) to your GitHub account.
After forking the repository, clone it to your local device by using the following command:
```sh
git clone https://github.com/documenso/documenso
git clone https://github.com/<your-username>/documenso
```
2. Set up your `.env` file using the recommendations in the `.env.example` file. Alternatively, just run `cp .env.example .env` to get started with our handpicked defaults.
@ -152,10 +154,12 @@ npm run d
Follow these steps to setup Documenso on your local machine:
1. [Clone the repository](https://help.github.com/articles/cloning-a-repository/) it to your local device.
1. [Fork this repository](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/about-forks) to your GitHub account.
After forking the repository, clone it to your local device by using the following command:
```sh
git clone https://github.com/documenso/documenso
git clone https://github.com/<your-username>/documenso
```
2. Run `npm i` in the root directory

View File

@ -3,7 +3,7 @@
import { DateTime } from 'luxon';
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { GetUserMonthlyGrowthResult } from '@documenso/lib/server-only/user/get-user-monthly-growth';
import type { GetUserMonthlyGrowthResult } from '@documenso/lib/server-only/user/get-user-monthly-growth';
import { cn } from '@documenso/ui/lib/utils';
export type MonthlyNewUsersChartProps = {
@ -22,7 +22,7 @@ export const MonthlyNewUsersChart = ({ className, data }: MonthlyNewUsersChartPr
return (
<div className={cn('flex flex-col', className)}>
<div className="flex items-center px-4">
<h3 className="text-lg font-semibold">Monthly New Users</h3>
<h3 className="text-lg font-semibold">New Users</h3>
</div>
<div className="border-border mt-2.5 flex flex-1 items-center justify-center rounded-2xl border p-6 pl-2 pt-12 shadow-sm hover:shadow">

View File

@ -3,7 +3,7 @@
import { DateTime } from 'luxon';
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { GetUserMonthlyGrowthResult } from '@documenso/lib/server-only/user/get-user-monthly-growth';
import type { GetUserMonthlyGrowthResult } from '@documenso/lib/server-only/user/get-user-monthly-growth';
import { cn } from '@documenso/ui/lib/utils';
export type MonthlyTotalUsersChartProps = {
@ -22,7 +22,7 @@ export const MonthlyTotalUsersChart = ({ className, data }: MonthlyTotalUsersCha
return (
<div className={cn('flex flex-col', className)}>
<div className="flex items-center px-4">
<h3 className="text-lg font-semibold">Monthly Total Users</h3>
<h3 className="text-lg font-semibold">Total Users</h3>
</div>
<div className="border-border mt-2.5 flex flex-1 items-center justify-center rounded-2xl border p-6 pl-2 pt-12 shadow-sm hover:shadow">

View File

@ -29,10 +29,7 @@ export function OpenPageTooltip() {
</svg>
</TooltipTrigger>
<TooltipContent>
<p>
August and earlier: Active subscribers. September and beyond: Numbers of active
subscriptions.
</p>
<p>Active Subscriptions.</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>

View File

@ -39,7 +39,7 @@ export const Footer = ({ className, ...props }: FooterProps) => {
return (
<div className={cn('border-t py-12', className)} {...props}>
<div className="mx-auto flex w-full max-w-screen-xl flex-wrap items-start justify-between gap-8 px-8">
<div>
<div className="flex-shrink-0">
<Link href="/">
<Image
src={LogoImage}
@ -64,13 +64,13 @@ export const Footer = ({ className, ...props }: FooterProps) => {
</div>
</div>
<div className="grid max-w-xs flex-1 grid-cols-2 gap-x-4 gap-y-2">
<div className="grid w-full max-w-sm grid-cols-2 gap-x-4 gap-y-2 md:w-auto md:gap-x-8">
{FOOTER_LINKS.map((link, index) => (
<Link
key={index}
href={link.href}
target={link.target}
className="text-muted-foreground hover:text-muted-foreground/80 flex-shrink-0 text-sm"
className="text-muted-foreground hover:text-muted-foreground/80 flex-shrink-0 break-words text-sm"
>
{link.text}
</Link>

View File

@ -1,4 +1,4 @@
import { NextApiRequest, NextApiResponse } from 'next';
import type { NextApiRequest, NextApiResponse } from 'next';
import { randomBytes } from 'crypto';
import { buffer } from 'micro';
@ -6,7 +6,8 @@ import { buffer } from 'micro';
import { insertImageInPDF } from '@documenso/lib/server-only/pdf/insert-image-in-pdf';
import { insertTextInPDF } from '@documenso/lib/server-only/pdf/insert-text-in-pdf';
import { redis } from '@documenso/lib/server-only/redis';
import { Stripe, stripe } from '@documenso/lib/server-only/stripe';
import type { Stripe } from '@documenso/lib/server-only/stripe';
import { stripe } from '@documenso/lib/server-only/stripe';
import { getFile } from '@documenso/lib/universal/upload/get-file';
import { updateFile } from '@documenso/lib/universal/upload/update-file';
import { prisma } from '@documenso/prisma';

View File

@ -9,7 +9,6 @@ import type { z } from 'zod';
import { trpc } from '@documenso/trpc/react';
import { ZUpdateProfileMutationByAdminSchema } from '@documenso/trpc/server/admin-router/schema';
import { Button } from '@documenso/ui/primitives/button';
import { Combobox } from '@documenso/ui/primitives/combobox';
import {
Form,
FormControl,
@ -19,6 +18,7 @@ import {
FormMessage,
} from '@documenso/ui/primitives/form/form';
import { Input } from '@documenso/ui/primitives/input';
import { MultiSelectCombobox } from '@documenso/ui/primitives/multiselect-combobox';
import { useToast } from '@documenso/ui/primitives/use-toast';
const ZUserFormSchema = ZUpdateProfileMutationByAdminSchema.omit({ id: true });
@ -117,7 +117,7 @@ export default function UserPage({ params }: { params: { id: number } }) {
<fieldset className="flex flex-col gap-2">
<FormLabel className="text-muted-foreground">Roles</FormLabel>
<FormControl>
<Combobox
<MultiSelectCombobox
listValues={roles}
onChange={(values: string[]) => onChange(values)}
/>

View File

@ -4,8 +4,8 @@ import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { DocumentStatus } from '@documenso/prisma/client';
import type { DocumentData, Field, Recipient, User } from '@documenso/prisma/client';
import { DocumentStatus } from '@documenso/prisma/client';
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
import { trpc } from '@documenso/trpc/react';
import { cn } from '@documenso/ui/lib/utils';
@ -145,14 +145,16 @@ export const EditDocumentForm = ({
};
const onAddSubjectFormSubmit = async (data: TAddSubjectFormSchema) => {
const { subject, message } = data.email;
const { subject, message, timezone, dateFormat } = data.meta;
try {
await sendDocument({
documentId: document.id,
email: {
meta: {
subject,
message,
timezone,
dateFormat,
},
});

View File

@ -1,6 +1,6 @@
'use client';
import { useState } from 'react';
import { useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
@ -25,6 +25,7 @@ export type UploadDocumentProps = {
export const UploadDocument = ({ className }: UploadDocumentProps) => {
const router = useRouter();
const analytics = useAnalytics();
const { data: session } = useSession();
const { toast } = useToast();
@ -35,6 +36,16 @@ export const UploadDocument = ({ className }: UploadDocumentProps) => {
const { mutateAsync: createDocument } = trpc.document.createDocument.useMutation();
const disabledMessage = useMemo(() => {
if (remaining.documents === 0) {
return 'You have reached your document limit.';
}
if (!session?.user.emailVerified) {
return 'Verify your email to upload documents.';
}
}, [remaining.documents, session?.user.emailVerified]);
const onFileDrop = async (file: File) => {
try {
setIsLoading(true);
@ -90,6 +101,7 @@ export const UploadDocument = ({ className }: UploadDocumentProps) => {
<DocumentDropzone
className="min-h-[40vh]"
disabled={remaining.documents === 0 || !session?.user.emailVerified}
disabledMessage={disabledMessage}
onDrop={onFileDrop}
/>

View File

@ -15,6 +15,8 @@ import { DocumentDownloadButton } from '@documenso/ui/components/document/docume
import { DocumentShareButton } from '@documenso/ui/components/document/document-share-button';
import { SigningCard3D } from '@documenso/ui/components/signing-card';
import { truncateTitle } from '~/helpers/truncate-title';
export type CompletedSigningPageProps = {
params: {
token?: string;
@ -36,6 +38,8 @@ export default async function CompletedSigningPage({
return notFound();
}
const truncatedTitle = truncateTitle(document.title);
const { documentData } = document;
const [fields, recipient] = await Promise.all([
@ -89,7 +93,7 @@ export default async function CompletedSigningPage({
<h2 className="mt-6 max-w-[35ch] text-center text-2xl font-semibold leading-normal md:text-3xl lg:text-4xl">
You have signed
<span className="mt-1.5 block">"{document.title}"</span>
<span className="mt-1.5 block">"{truncatedTitle}"</span>
</h2>
{match({ status: document.status, deletedAt: document.deletedAt })

View File

@ -6,8 +6,13 @@ import { useRouter } from 'next/navigation';
import { Loader } from 'lucide-react';
import { Recipient } from '@documenso/prisma/client';
import { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import {
DEFAULT_DOCUMENT_DATE_FORMAT,
convertToLocalSystemFormat,
} from '@documenso/lib/constants/date-formats';
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
import type { Recipient } from '@documenso/prisma/client';
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import { trpc } from '@documenso/trpc/react';
import { useToast } from '@documenso/ui/primitives/use-toast';
@ -16,9 +21,16 @@ import { SigningFieldContainer } from './signing-field-container';
export type DateFieldProps = {
field: FieldWithSignature;
recipient: Recipient;
dateFormat?: string | null;
timezone?: string | null;
};
export const DateField = ({ field, recipient }: DateFieldProps) => {
export const DateField = ({
field,
recipient,
dateFormat = DEFAULT_DOCUMENT_DATE_FORMAT,
timezone = DEFAULT_DOCUMENT_TIME_ZONE,
}: DateFieldProps) => {
const router = useRouter();
const { toast } = useToast();
@ -35,12 +47,18 @@ export const DateField = ({ field, recipient }: DateFieldProps) => {
const isLoading = isSignFieldWithTokenLoading || isRemoveSignedFieldWithTokenLoading || isPending;
const localDateString = convertToLocalSystemFormat(field.customText, dateFormat, timezone);
const isDifferentTime = field.inserted && localDateString !== field.customText;
const tooltipText = `"${field.customText}" will appear on the document as it has a timezone of "${timezone}".`;
const onSign = async () => {
try {
await signFieldWithToken({
token: recipient.token,
fieldId: field.id,
value: '',
value: dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT,
});
startTransition(() => router.refresh());
@ -75,7 +93,13 @@ export const DateField = ({ field, recipient }: DateFieldProps) => {
};
return (
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove}>
<SigningFieldContainer
field={field}
onSign={onSign}
onRemove={onRemove}
type="Date"
tooltipText={isDifferentTime ? tooltipText : undefined}
>
{isLoading && (
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />
@ -87,7 +111,7 @@ export const DateField = ({ field, recipient }: DateFieldProps) => {
)}
{field.inserted && (
<p className="text-muted-foreground text-sm duration-200">{field.customText}</p>
<p className="text-muted-foreground text-sm duration-200">{localDateString}</p>
)}
</SigningFieldContainer>
);

View File

@ -6,8 +6,8 @@ import { useRouter } from 'next/navigation';
import { Loader } from 'lucide-react';
import { Recipient } from '@documenso/prisma/client';
import { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import type { Recipient } from '@documenso/prisma/client';
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import { trpc } from '@documenso/trpc/react';
import { useToast } from '@documenso/ui/primitives/use-toast';
@ -79,7 +79,7 @@ export const EmailField = ({ field, recipient }: EmailFieldProps) => {
};
return (
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove}>
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove} type="Email">
{isLoading && (
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />

View File

@ -34,6 +34,7 @@ export const SigningForm = ({ document, recipient, fields }: SigningFormProps) =
const { data: session } = useSession();
const { fullName, signature, setFullName, setSignature } = useRequiredSigningContext();
const [validateUninsertedFields, setValidateUninsertedFields] = useState(false);
const { mutateAsync: completeDocumentWithToken } =
@ -92,7 +93,11 @@ export const SigningForm = ({ document, recipient, fields }: SigningFormProps) =
disabled={isSubmitting}
className={cn('-mx-2 flex flex-1 flex-col overflow-hidden px-2')}
>
<div className={cn('flex flex-1 flex-col')}>
<div
className={cn(
'custom-scrollbar -mx-2 flex flex-1 flex-col overflow-y-auto overflow-x-hidden px-2',
)}
>
<h3 className="text-foreground text-2xl font-semibold">Sign Document</h3>
<p className="text-muted-foreground mt-2 text-sm">

View File

@ -6,8 +6,8 @@ import { useRouter } from 'next/navigation';
import { Loader } from 'lucide-react';
import { Recipient } from '@documenso/prisma/client';
import { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import type { Recipient } from '@documenso/prisma/client';
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import { trpc } from '@documenso/trpc/react';
import { Button } from '@documenso/ui/primitives/button';
import { Dialog, DialogContent, DialogFooter, DialogTitle } from '@documenso/ui/primitives/dialog';
@ -98,7 +98,7 @@ export const NameField = ({ field, recipient }: NameFieldProps) => {
};
return (
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove}>
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove} type="Name">
{isLoading && (
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />

View File

@ -2,9 +2,12 @@ import { notFound, redirect } from 'next/navigation';
import { match } from 'ts-pattern';
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
import { getServerComponentSession } from '@documenso/lib/next-auth/get-server-component-session';
import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';
import { getDocumentMetaByDocumentId } from '@documenso/lib/server-only/document/get-document-meta-by-document-id';
import { viewedDocument } from '@documenso/lib/server-only/document/viewed-document';
import { getFieldsForToken } from '@documenso/lib/server-only/field/get-fields-for-token';
import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';
@ -14,6 +17,8 @@ import { Card, CardContent } from '@documenso/ui/primitives/card';
import { ElementVisible } from '@documenso/ui/primitives/element-visible';
import { LazyPDFViewer } from '@documenso/ui/primitives/lazy-pdf-viewer';
import { truncateTitle } from '~/helpers/truncate-title';
import { DateField } from './date-field';
import { EmailField } from './email-field';
import { SigningForm } from './form';
@ -42,10 +47,14 @@ export default async function SigningPage({ params: { token } }: SigningPageProp
viewedDocument({ token }).catch(() => null),
]);
const documentMeta = await getDocumentMetaByDocumentId({ id: document!.id }).catch(() => null);
if (!document || !document.documentData || !recipient) {
return notFound();
}
const truncatedTitle = truncateTitle(document.title);
const { documentData } = document;
const { user } = await getServerComponentSession();
@ -77,7 +86,7 @@ export default async function SigningPage({ params: { token } }: SigningPageProp
>
<div className="mx-auto w-full max-w-screen-xl">
<h1 className="mt-4 truncate text-2xl font-semibold md:text-3xl" title={document.title}>
{document.title}
{truncatedTitle}
</h1>
<div className="mt-2.5 flex items-center gap-x-6">
@ -111,7 +120,13 @@ export default async function SigningPage({ params: { token } }: SigningPageProp
<NameField key={field.id} field={field} recipient={recipient} />
))
.with(FieldType.DATE, () => (
<DateField key={field.id} field={field} recipient={recipient} />
<DateField
key={field.id}
field={field}
recipient={recipient}
dateFormat={documentMeta?.dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT}
timezone={documentMeta?.timezone ?? DEFAULT_DOCUMENT_TIME_ZONE}
/>
))
.with(FieldType.EMAIL, () => (
<EmailField key={field.id} field={field} recipient={recipient} />

View File

@ -1,6 +1,6 @@
import { useState } from 'react';
import { Document, Field } from '@documenso/prisma/client';
import type { Document, Field } from '@documenso/prisma/client';
import { Button } from '@documenso/ui/primitives/button';
import {
Dialog,
@ -9,6 +9,8 @@ import {
DialogTrigger,
} from '@documenso/ui/primitives/dialog';
import { truncateTitle } from '~/helpers/truncate-title';
export type SignDialogProps = {
isSubmitting: boolean;
document: Document;
@ -23,7 +25,7 @@ export const SignDialog = ({
onSignatureComplete,
}: SignDialogProps) => {
const [showDialog, setShowDialog] = useState(false);
const truncatedTitle = truncateTitle(document.title);
const isComplete = fields.every((field) => field.inserted);
return (
@ -43,7 +45,7 @@ export const SignDialog = ({
<div className="text-center">
<div className="text-xl font-semibold text-neutral-800">Sign Document</div>
<div className="text-muted-foreground mx-auto w-4/5 py-2 text-center">
You are about to finish signing "{document.title}". Are you sure?
You are about to finish signing "{truncatedTitle}". Are you sure?
</div>
</div>

View File

@ -127,7 +127,7 @@ export const SignatureField = ({ field, recipient }: SignatureFieldProps) => {
};
return (
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove}>
<SigningFieldContainer field={field} onSign={onSign} onRemove={onRemove} type="Signature">
{isLoading && (
<div className="bg-background absolute inset-0 flex items-center justify-center rounded-md">
<Loader className="text-primary h-5 w-5 animate-spin md:h-8 md:w-8" />

View File

@ -2,8 +2,9 @@
import React from 'react';
import { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import { FieldRootContainer } from '@documenso/ui/components/field/field';
import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
export type SignatureFieldProps = {
field: FieldWithSignature;
@ -11,6 +12,8 @@ export type SignatureFieldProps = {
children: React.ReactNode;
onSign?: () => Promise<void> | void;
onRemove?: () => Promise<void> | void;
type?: 'Date' | 'Email' | 'Name' | 'Signature';
tooltipText?: string | null;
};
export const SigningFieldContainer = ({
@ -19,6 +22,8 @@ export const SigningFieldContainer = ({
onSign,
onRemove,
children,
type,
tooltipText,
}: SignatureFieldProps) => {
const onSignFieldClick = async () => {
if (field.inserted) {
@ -46,7 +51,22 @@ export const SigningFieldContainer = ({
/>
)}
{field.inserted && !loading && (
{type === 'Date' && field.inserted && !loading && (
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<button
className="text-destructive bg-background/40 absolute inset-0 z-10 flex h-full w-full items-center justify-center rounded-md text-sm opacity-0 backdrop-blur-sm duration-200 group-hover:opacity-100"
onClick={onRemoveSignedFieldClick}
>
Remove
</button>
</TooltipTrigger>
{tooltipText && <TooltipContent className="max-w-xs">{tooltipText}</TooltipContent>}
</Tooltip>
)}
{type !== 'Date' && field.inserted && !loading && (
<button
className="text-destructive bg-background/40 absolute inset-0 z-10 flex h-full w-full items-center justify-center rounded-md text-sm opacity-0 backdrop-blur-sm duration-200 group-hover:opacity-100"
onClick={onRemoveSignedFieldClick}

View File

@ -11,6 +11,7 @@ import { useHotkeys } from 'react-hotkeys-hook';
import {
DOCUMENTS_PAGE_SHORTCUT,
SETTINGS_PAGE_SHORTCUT,
TEMPLATES_PAGE_SHORTCUT,
} from '@documenso/lib/constants/keyboard-shortcuts';
import { trpc as trpcReact } from '@documenso/trpc/react';
import {
@ -22,6 +23,7 @@ import {
CommandList,
CommandShortcut,
} from '@documenso/ui/primitives/command';
import { THEMES_TYPE } from '@documenso/ui/primitives/constants';
const DOCUMENTS_PAGES = [
{
@ -38,6 +40,14 @@ const DOCUMENTS_PAGES = [
{ label: 'Inbox documents', path: '/documents?status=INBOX' },
];
const TEMPLATES_PAGES = [
{
label: 'All templates',
path: '/templates',
shortcut: TEMPLATES_PAGE_SHORTCUT.replace('+', ''),
},
];
const SETTINGS_PAGES = [
{
label: 'Settings',
@ -124,10 +134,12 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {
const goToSettings = useCallback(() => push(SETTINGS_PAGES[0].path), [push]);
const goToDocuments = useCallback(() => push(DOCUMENTS_PAGES[0].path), [push]);
const goToTemplates = useCallback(() => push(TEMPLATES_PAGES[0].path), [push]);
useHotkeys(['ctrl+k', 'meta+k'], toggleOpen);
useHotkeys(SETTINGS_PAGE_SHORTCUT, goToSettings);
useHotkeys(DOCUMENTS_PAGE_SHORTCUT, goToDocuments);
useHotkeys(TEMPLATES_PAGE_SHORTCUT, goToTemplates);
const handleKeyDown = (e: React.KeyboardEvent) => {
// Escape goes to previous page
@ -174,6 +186,9 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {
<CommandGroup heading="Documents">
<Commands push={push} pages={DOCUMENTS_PAGES} />
</CommandGroup>
<CommandGroup heading="Templates">
<Commands push={push} pages={TEMPLATES_PAGES} />
</CommandGroup>
<CommandGroup heading="Settings">
<Commands push={push} pages={SETTINGS_PAGES} />
</CommandGroup>
@ -215,9 +230,9 @@ const Commands = ({
const ThemeCommands = ({ setTheme }: { setTheme: (_theme: string) => void }) => {
const THEMES = useMemo(
() => [
{ label: 'Light Mode', theme: 'light', icon: Sun },
{ label: 'Dark Mode', theme: 'dark', icon: Moon },
{ label: 'System Theme', theme: 'system', icon: Monitor },
{ label: 'Light Mode', theme: THEMES_TYPE.LIGHT, icon: Sun },
{ label: 'Dark Mode', theme: THEMES_TYPE.DARK, icon: Moon },
{ label: 'System Theme', theme: THEMES_TYPE.SYSTEM, icon: Monitor },
],
[],
);

View File

@ -33,7 +33,7 @@ export const Header = ({ className, user, ...props }: HeaderProps) => {
return (
<header
className={cn(
'supports-backdrop-blur:bg-background/60 bg-background/95 sticky top-0 z-[1000] flex h-16 w-full items-center border-b border-b-transparent backdrop-blur duration-200',
'supports-backdrop-blur:bg-background/60 bg-background/95 sticky top-0 z-[50] flex h-16 w-full items-center border-b border-b-transparent backdrop-blur duration-200',
scrollY > 5 && 'border-b-border',
className,
)}

View File

@ -1,9 +1,9 @@
import { HTMLAttributes } from 'react';
import type { HTMLAttributes } from 'react';
import { CheckCircle2, Clock, File } from 'lucide-react';
import type { LucideIcon } from 'lucide-react/dist/lucide-react';
import { ExtendedDocumentStatus } from '@documenso/prisma/types/extended-document-status';
import type { ExtendedDocumentStatus } from '@documenso/prisma/types/extended-document-status';
import { SignatureIcon } from '@documenso/ui/icons/signature';
import { cn } from '@documenso/ui/lib/utils';

View File

@ -1,8 +1,10 @@
'use client';
import { HTMLAttributes, useEffect, useState } from 'react';
import type { HTMLAttributes } from 'react';
import { useEffect, useState } from 'react';
import { DateTime, DateTimeFormatOptions } from 'luxon';
import type { DateTimeFormatOptions } from 'luxon';
import { DateTime } from 'luxon';
import { useLocale } from '@documenso/lib/client-only/providers/locale';

View File

@ -0,0 +1,10 @@
export const truncateTitle = (title: string, maxLength: number = 16) => {
if (title.length <= maxLength) {
return title;
}
const start = title.slice(0, maxLength / 2);
const end = title.slice(-maxLength / 2);
return `${start}.....${end}`;
};

View File

@ -2,7 +2,7 @@
import React from 'react';
import { Session } from 'next-auth';
import type { Session } from 'next-auth';
import { SessionProvider } from 'next-auth/react';
export type NextAuthProviderProps = {

View File

@ -1,6 +1,7 @@
/** @type {import('lint-staged').Config} */
module.exports = {
'**/*.{ts,tsx,cts,mts}': ['eslint --fix'],
'**/*.{js,jsx,cjs,mjs}': ['prettier --write'],
'**/*.{yml,mdx}': ['prettier --write'],
'**/*/package.json': ['npm run precommit'],
'**/*.{ts,tsx,cts,mts}': (files) => `eslint --fix ${files.join(' ')}`,
'**/*.{js,jsx,cjs,mjs}': (files) => `prettier --write ${files.join(' ')}`,
'**/*.{yml,mdx}': (files) => `prettier --write ${files.join(' ')}`,
'**/*/package.json': 'npm run precommit',
};

6
package-lock.json generated
View File

@ -6431,6 +6431,11 @@
"crypto-js": "^4.2.0"
}
},
"node_modules/@vvo/tzdb": {
"version": "6.117.0",
"resolved": "https://registry.npmjs.org/@vvo/tzdb/-/tzdb-6.117.0.tgz",
"integrity": "sha512-vZkfoag1kHqItK/zebxT0Fkt3R/zscjgD+Ib7kaAdum0Sz9psXDfVHPW1Benv91d02zPWlLIvZtjBmzX4a+6fw=="
},
"node_modules/abbrev": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
@ -19359,6 +19364,7 @@
"@scure/base": "^1.1.3",
"@sindresorhus/slugify": "^2.2.1",
"@upstash/redis": "^1.20.6",
"@vvo/tzdb": "^6.117.0",
"bcrypt": "^5.1.0",
"luxon": "^3.4.0",
"nanoid": "^4.0.2",

View File

@ -1,4 +1,5 @@
import { ReadStatus, Recipient, SendStatus, SigningStatus } from '@documenso/prisma/client';
import type { Recipient } from '@documenso/prisma/client';
import { ReadStatus, SendStatus, SigningStatus } from '@documenso/prisma/client';
export const getRecipientType = (recipient: Recipient) => {
if (

View File

@ -0,0 +1,79 @@
import { DateTime } from 'luxon';
import { DEFAULT_DOCUMENT_TIME_ZONE } from './time-zones';
export const DEFAULT_DOCUMENT_DATE_FORMAT = 'yyyy-MM-dd hh:mm a';
export const DATE_FORMATS = [
{
key: 'yyyy-MM-dd_hh:mm_a',
label: 'YYYY-MM-DD HH:mm a',
value: DEFAULT_DOCUMENT_DATE_FORMAT,
},
{
key: 'YYYYMMDD',
label: 'YYYY-MM-DD',
value: 'YYYY-MM-DD',
},
{
key: 'DDMMYYYY',
label: 'DD/MM/YYYY',
value: 'dd/MM/yyyy hh:mm a',
},
{
key: 'MMDDYYYY',
label: 'MM/DD/YYYY',
value: 'MM/dd/yyyy hh:mm a',
},
{
key: 'YYYYMMDDHHmm',
label: 'YYYY-MM-DD HH:mm',
value: 'yyyy-MM-dd HH:mm',
},
{
key: 'YYMMDD',
label: 'YY-MM-DD',
value: 'yy-MM-dd hh:mm a',
},
{
key: 'YYYYMMDDhhmmss',
label: 'YYYY-MM-DD HH:mm:ss',
value: 'yyyy-MM-dd HH:mm:ss',
},
{
key: 'MonthDateYear',
label: 'Month Date, Year',
value: 'MMMM dd, yyyy hh:mm a',
},
{
key: 'DayMonthYear',
label: 'Day, Month Year',
value: 'EEEE, MMMM dd, yyyy hh:mm a',
},
{
key: 'ISO8601',
label: 'ISO 8601',
value: "yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
},
];
export const convertToLocalSystemFormat = (
customText: string,
dateFormat: string | null = DEFAULT_DOCUMENT_DATE_FORMAT,
timeZone: string | null = DEFAULT_DOCUMENT_TIME_ZONE,
): string => {
const coalescedDateFormat = dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT;
const coalescedTimeZone = timeZone ?? DEFAULT_DOCUMENT_TIME_ZONE;
const parsedDate = DateTime.fromFormat(customText, coalescedDateFormat, {
zone: coalescedTimeZone,
});
if (!parsedDate.isValid) {
return 'Invalid date';
}
const formattedDate = parsedDate.toLocal().toFormat(coalescedDateFormat);
return formattedDate;
};

View File

@ -1,2 +1,3 @@
export const SETTINGS_PAGE_SHORTCUT = 'N+S';
export const DOCUMENTS_PAGE_SHORTCUT = 'N+D';
export const TEMPLATES_PAGE_SHORTCUT = 'N+T';

View File

@ -0,0 +1,44 @@
import { rawTimeZones, timeZonesNames } from '@vvo/tzdb';
export const TIME_ZONE_DATA = rawTimeZones;
export const DEFAULT_DOCUMENT_TIME_ZONE = 'Etc/UTC';
export type TimeZone = {
name: string;
rawOffsetInMinutes: number;
};
export const minutesToHours = (minutes: number): string => {
const hours = Math.abs(Math.floor(minutes / 60));
const min = Math.abs(minutes % 60);
const sign = minutes >= 0 ? '+' : '-';
return `${sign}${String(hours).padStart(2, '0')}:${String(min).padStart(2, '0')}`;
};
const getGMTOffsets = (timezones: TimeZone[]): string[] => {
const gmtOffsets: string[] = [];
for (const timezone of timezones) {
const offsetValue = minutesToHours(timezone.rawOffsetInMinutes);
const gmtText = `(${offsetValue})`;
gmtOffsets.push(`${timezone.name} ${gmtText}`);
}
return gmtOffsets;
};
export const splitTimeZone = (input: string | null): string => {
if (input === null) {
return '';
}
const [timeZone] = input.split('(');
return timeZone.trim();
};
export const TIME_ZONES_FULL = getGMTOffsets(TIME_ZONE_DATA);
export const TIME_ZONES = ['Etc/UTC', ...timeZonesNames];

View File

@ -31,6 +31,7 @@
"@scure/base": "^1.1.3",
"@sindresorhus/slugify": "^2.2.1",
"@upstash/redis": "^1.20.6",
"@vvo/tzdb": "^6.117.0",
"bcrypt": "^5.1.0",
"luxon": "^3.4.0",
"nanoid": "^4.0.2",

View File

@ -6,11 +6,15 @@ export type CreateDocumentMetaOptions = {
documentId: number;
subject: string;
message: string;
timezone: string;
dateFormat: string;
};
export const upsertDocumentMeta = async ({
subject,
message,
timezone,
dateFormat,
documentId,
}: CreateDocumentMetaOptions) => {
return await prisma.documentMeta.upsert({
@ -20,11 +24,15 @@ export const upsertDocumentMeta = async ({
create: {
subject,
message,
dateFormat,
timezone,
documentId,
},
update: {
subject,
message,
dateFormat,
timezone,
},
});
};

View File

@ -25,6 +25,8 @@ export const duplicateDocumentById = async ({ id, userId }: DuplicateDocumentByI
select: {
message: true,
subject: true,
dateFormat: true,
timezone: true,
},
},
},

View File

@ -0,0 +1,13 @@
import { prisma } from '@documenso/prisma';
export interface GetDocumentMetaByDocumentIdOptions {
id: number;
}
export const getDocumentMetaByDocumentId = async ({ id }: GetDocumentMetaByDocumentIdOptions) => {
return await prisma.documentMeta.findFirstOrThrow({
where: {
documentId: id,
},
});
};

View File

@ -1,6 +1,6 @@
'use server';
import { Prisma } from '@prisma/client';
import type { Prisma } from '@prisma/client';
import { prisma } from '@documenso/prisma';

View File

@ -5,6 +5,9 @@ import { DateTime } from 'luxon';
import { prisma } from '@documenso/prisma';
import { DocumentStatus, FieldType, SigningStatus } from '@documenso/prisma/client';
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '../../constants/date-formats';
import { DEFAULT_DOCUMENT_TIME_ZONE } from '../../constants/time-zones';
export type SignFieldWithTokenOptions = {
token: string;
fieldId: number;
@ -58,6 +61,12 @@ export const signFieldWithToken = async ({
throw new Error(`Field ${fieldId} has no recipientId`);
}
const documentMeta = await prisma.documentMeta.findFirst({
where: {
documentId: document.id,
},
});
const isSignatureField =
field.type === FieldType.SIGNATURE || field.type === FieldType.FREE_SIGNATURE;
@ -67,7 +76,9 @@ export const signFieldWithToken = async ({
const typedSignature = isSignatureField && !isBase64 ? value : undefined;
if (field.type === FieldType.DATE) {
customText = DateTime.now().toFormat('yyyy-MM-dd hh:mm a');
customText = DateTime.now()
.setZone(documentMeta?.timezone ?? DEFAULT_DOCUMENT_TIME_ZONE)
.toFormat(documentMeta?.dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT);
}
if (isSignatureField && !signatureImageAsBase64 && !typedSignature) {

View File

@ -1,4 +1,4 @@
import { Recipient } from '@documenso/prisma/client';
import type { Recipient } from '@documenso/prisma/client';
export const recipientInitials = (text: string) =>
text

View File

@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "DocumentMeta" ADD COLUMN "dateFormat" TEXT DEFAULT 'yyyy-MM-dd hh:mm a',
ADD COLUMN "timezone" TEXT DEFAULT 'Etc/UTC';

View File

@ -161,6 +161,8 @@ model DocumentMeta {
id String @id @default(cuid())
subject String?
message String?
timezone String? @db.Text @default("Etc/UTC")
dateFormat String? @db.Text @default("yyyy-MM-dd hh:mm a")
documentId Int @unique
document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
}

View File

@ -1,4 +1,4 @@
import { Document, DocumentData, DocumentMeta } from '@documenso/prisma/client';
import type { Document, DocumentData, DocumentMeta } from '@documenso/prisma/client';
export type DocumentWithData = Document & {
documentData?: DocumentData | null;

View File

@ -1,4 +1,4 @@
import { Document, DocumentData, Recipient } from '@documenso/prisma/client';
import type { Document, DocumentData, Recipient } from '@documenso/prisma/client';
export type DocumentWithRecipients = Document & {
Recipient: Recipient[];

View File

@ -1,4 +1,4 @@
import { Field, Signature } from '@documenso/prisma/client';
import type { Field, Signature } from '@documenso/prisma/client';
export type FieldWithSignature = Field & {
Signature?: Signature | null;

View File

@ -179,13 +179,15 @@ export const documentRouter = router({
.input(ZSendDocumentMutationSchema)
.mutation(async ({ input, ctx }) => {
try {
const { documentId, email } = input;
const { documentId, meta } = input;
if (email.message || email.subject) {
if (meta.message || meta.subject || meta.timezone || meta.dateFormat) {
await upsertDocumentMeta({
documentId,
subject: email.subject,
message: email.message,
subject: meta.subject,
message: meta.message,
dateFormat: meta.dateFormat,
timezone: meta.timezone,
});
}

View File

@ -65,9 +65,11 @@ export type TSetFieldsForDocumentMutationSchema = z.infer<
export const ZSendDocumentMutationSchema = z.object({
documentId: z.number(),
email: z.object({
meta: z.object({
subject: z.string(),
message: z.string(),
timezone: z.string(),
dateFormat: z.string(),
}),
});

View File

@ -3,7 +3,7 @@ import SuperJSON from 'superjson';
import { isAdmin } from '@documenso/lib/next-auth/guards/is-admin';
import { TrpcContext } from './context';
import type { TrpcContext } from './context';
const t = initTRPC.context<TrpcContext>().create({
transformer: SuperJSON,

View File

@ -1,4 +1,5 @@
import { ClassValue, clsx } from 'clsx';
import type { ClassValue } from 'clsx';
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {

View File

@ -1,8 +1,6 @@
import * as React from 'react';
import { Check, ChevronsUpDown } from 'lucide-react';
import { Role } from '@documenso/prisma/client';
import { Check, ChevronDown } from 'lucide-react';
import { cn } from '../lib/utils';
import { Button } from './button';
@ -10,34 +8,31 @@ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from '
import { Popover, PopoverContent, PopoverTrigger } from './popover';
type ComboboxProps = {
listValues: string[];
onChange: (_values: string[]) => void;
className?: string;
options: string[];
value: string | null;
onChange: (_value: string | null) => void;
placeholder?: string;
disabled?: boolean;
};
const Combobox = ({ listValues, onChange }: ComboboxProps) => {
const Combobox = ({
className,
options,
value,
onChange,
disabled = false,
placeholder,
}: ComboboxProps) => {
const [open, setOpen] = React.useState(false);
const [selectedValues, setSelectedValues] = React.useState<string[]>([]);
const dbRoles = Object.values(Role);
React.useEffect(() => {
setSelectedValues(listValues);
}, [listValues]);
const allRoles = [...new Set([...dbRoles, ...selectedValues])];
const handleSelect = (currentValue: string) => {
let newSelectedValues;
if (selectedValues.includes(currentValue)) {
newSelectedValues = selectedValues.filter((value) => value !== currentValue);
} else {
newSelectedValues = [...selectedValues, currentValue];
}
setSelectedValues(newSelectedValues);
onChange(newSelectedValues);
const onOptionSelected = (newValue: string) => {
onChange(newValue === value ? null : newValue);
setOpen(false);
};
const placeholderValue = placeholder ?? 'Select an option';
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
@ -45,26 +40,28 @@ const Combobox = ({ listValues, onChange }: ComboboxProps) => {
variant="outline"
role="combobox"
aria-expanded={open}
className="w-[200px] justify-between"
className={cn('my-2 w-full justify-between', className)}
disabled={disabled}
>
{selectedValues.length > 0 ? selectedValues.join(', ') : 'Select values...'}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
{value ? value : placeholderValue}
<ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0">
<PopoverContent className="p-0" side="bottom" align="start">
<Command>
<CommandInput placeholder={selectedValues.join(', ')} />
<CommandInput placeholder={value || placeholderValue} />
<CommandEmpty>No value found.</CommandEmpty>
<CommandGroup>
{allRoles.map((value: string, i: number) => (
<CommandItem key={i} onSelect={() => handleSelect(value)}>
<CommandGroup className="max-h-[250px] overflow-y-auto">
{options.map((option, index) => (
<CommandItem key={index} onSelect={() => onOptionSelected(option)}>
<Check
className={cn(
'mr-2 h-4 w-4',
selectedValues.includes(value) ? 'opacity-100' : 'opacity-0',
)}
className={cn('mr-2 h-4 w-4', option === value ? 'opacity-100' : 'opacity-0')}
/>
{value}
{option}
</CommandItem>
))}
</CommandGroup>

View File

@ -2,7 +2,7 @@
import * as React from 'react';
import { DialogProps } from '@radix-ui/react-dialog';
import type { DialogProps } from '@radix-ui/react-dialog';
import { Command as CommandPrimitive } from 'cmdk';
import { Search } from 'lucide-react';

View File

@ -0,0 +1,5 @@
export const THEMES_TYPE = {
DARK: 'dark',
LIGHT: 'light',
SYSTEM: 'system'
};

View File

@ -20,7 +20,7 @@ const DialogPortal = ({
}: DialogPrimitive.DialogPortalProps & { position?: 'start' | 'end' | 'center' }) => (
<DialogPrimitive.Portal {...props}>
<div
className={cn('fixed inset-0 z-[9999] flex justify-center sm:items-center', {
className={cn('fixed inset-0 z-[1000] flex justify-center sm:items-center', {
'items-start': position === 'start',
'items-end': position === 'end',
'items-center': position === 'center',

View File

@ -87,6 +87,7 @@ const DocumentDescription = {
export type DocumentDropzoneProps = {
className?: string;
disabled?: boolean;
disabledMessage?: string;
onDrop?: (_file: File) => void | Promise<void>;
type?: 'document' | 'template';
[key: string]: unknown;
@ -96,6 +97,7 @@ export const DocumentDropzone = ({
className,
onDrop,
disabled,
disabledMessage = 'You cannot upload documents at this time.',
type = 'document',
...props
}: DocumentDropzoneProps) => {
@ -115,11 +117,12 @@ export const DocumentDropzone = ({
return (
<motion.div
className={cn('flex', className)}
className={cn('flex aria-disabled:cursor-not-allowed', className)}
variants={DocumentDropzoneContainerVariants}
initial="initial"
animate="animate"
whileHover="hover"
aria-disabled={disabled}
>
<Card
role="button"
@ -137,8 +140,8 @@ export const DocumentDropzone = ({
{/* <FilePlus strokeWidth="1px" className="h-16 w-16"/> */}
<div className="flex">
<motion.div
className="border-muted-foreground/20 group-hover:border-documenso/80 dark:bg-muted/80 z-10 flex aspect-[3/4] w-24 origin-top-right -rotate-[22deg] flex-col gap-y-1 rounded-lg border bg-white/80 px-2 py-4 backdrop-blur-sm"
variants={DocumentDropzoneCardLeftVariants}
className="border-muted-foreground/20 group-hover:border-documenso/80 dark:bg-muted/80 a z-10 flex aspect-[3/4] w-24 origin-top-right -rotate-[22deg] flex-col gap-y-1 rounded-lg border bg-white/80 px-2 py-4 backdrop-blur-sm"
variants={!disabled ? DocumentDropzoneCardLeftVariants : undefined}
>
<div className="bg-muted-foreground/20 group-hover:bg-documenso h-2 w-full rounded-[2px]" />
<div className="bg-muted-foreground/20 group-hover:bg-documenso h-2 w-5/6 rounded-[2px]" />
@ -147,7 +150,7 @@ export const DocumentDropzone = ({
<motion.div
className="border-muted-foreground/20 group-hover:border-documenso/80 dark:bg-muted/80 z-20 flex aspect-[3/4] w-24 flex-col items-center justify-center gap-y-1 rounded-lg border bg-white/80 px-2 py-4 backdrop-blur-sm"
variants={DocumentDropzoneCardCenterVariants}
variants={!disabled ? DocumentDropzoneCardCenterVariants : undefined}
>
<Plus
strokeWidth="2px"
@ -157,7 +160,7 @@ export const DocumentDropzone = ({
<motion.div
className="border-muted-foreground/20 group-hover:border-documenso/80 dark:bg-muted/80 z-10 flex aspect-[3/4] w-24 origin-top-left rotate-[22deg] flex-col gap-y-1 rounded-lg border bg-white/80 px-2 py-4 backdrop-blur-sm"
variants={DocumentDropzoneCardRightVariants}
variants={!disabled ? DocumentDropzoneCardRightVariants : undefined}
>
<div className="bg-muted-foreground/20 group-hover:bg-documenso h-2 w-full rounded-[2px]" />
<div className="bg-muted-foreground/20 group-hover:bg-documenso h-2 w-5/6 rounded-[2px]" />
@ -171,7 +174,9 @@ export const DocumentDropzone = ({
{DocumentDescription[type].headline}
</p>
<p className="text-muted-foreground/80 mt-1 text-sm ">Drag & drop your document here.</p>
<p className="text-muted-foreground/80 mt-1 text-sm">
{disabled ? disabledMessage : 'Drag & drop your document here.'}
</p>
</CardContent>
</Card>
</motion.div>

View File

@ -7,11 +7,13 @@ import { DateTime } from 'luxon';
import { useForm } from 'react-hook-form';
import { match } from 'ts-pattern';
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
import { sortFieldsByPosition, validateFieldsInserted } from '@documenso/lib/utils/fields';
import type { Field } from '@documenso/prisma/client';
import { FieldType } from '@documenso/prisma/client';
import type { FieldWithSignature } from '@documenso/prisma/types/field-with-signature';
import type { DocumentFlowStep } from '@documenso/ui/primitives/document-flow/types';
import { FieldToolTip } from '../../components/field/field-tooltip';
import { cn } from '../../lib/utils';
@ -34,7 +36,6 @@ import {
SinglePlayerModeCustomTextField,
SinglePlayerModeSignatureField,
} from './single-player-mode-fields';
import type { DocumentFlowStep } from './types';
export type AddSignatureFormProps = {
defaultValues?: TAddSignatureFormSchema;
@ -140,7 +141,7 @@ export const AddSignatureFormPartial = ({
return match(field.type)
.with(FieldType.DATE, () => ({
...field,
customText: DateTime.now().toFormat('yyyy-MM-dd hh:mm a'),
customText: DateTime.now().toFormat(DEFAULT_DOCUMENT_DATE_FORMAT),
inserted: true,
}))
.with(FieldType.EMAIL, () => ({

View File

@ -1,11 +1,30 @@
'use client';
import { useForm } from 'react-hook-form';
import { useEffect } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { DATE_FORMATS, DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
import { DEFAULT_DOCUMENT_TIME_ZONE, TIME_ZONES } from '@documenso/lib/constants/time-zones';
import type { Field, Recipient } from '@documenso/prisma/client';
import { DocumentStatus } from '@documenso/prisma/client';
import { SendStatus } from '@documenso/prisma/client';
import type { DocumentWithData } from '@documenso/prisma/types/document-with-data';
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from '@documenso/ui/primitives/accordion';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@documenso/ui/primitives/select';
import { Combobox } from '../combobox';
import { FormErrorMessage } from '../form/form-error-message';
import { Input } from '../input';
import { Label } from '../label';
@ -31,20 +50,25 @@ export type AddSubjectFormProps = {
export const AddSubjectFormPartial = ({
documentFlow,
recipients: _recipients,
fields: _fields,
recipients: recipients,
fields: fields,
document,
onSubmit,
}: AddSubjectFormProps) => {
const {
control,
register,
handleSubmit,
formState: { errors, isSubmitting },
formState: { errors, isSubmitting, touchedFields },
getValues,
setValue,
} = useForm<TAddSubjectFormSchema>({
defaultValues: {
email: {
meta: {
subject: document.documentMeta?.subject ?? '',
message: document.documentMeta?.message ?? '',
timezone: document.documentMeta?.timezone ?? DEFAULT_DOCUMENT_TIME_ZONE,
dateFormat: document.documentMeta?.dateFormat ?? DEFAULT_DOCUMENT_DATE_FORMAT,
},
},
});
@ -52,6 +76,20 @@ export const AddSubjectFormPartial = ({
const onFormSubmit = handleSubmit(onSubmit);
const { currentStep, totalSteps, previousStep } = useStep();
const hasDateField = fields.find((field) => field.type === 'DATE');
const documentHasBeenSent = recipients.some(
(recipient) => recipient.sendStatus === SendStatus.SENT,
);
// We almost always want to set the timezone to the user's local timezone to avoid confusion
// when the document is signed.
useEffect(() => {
if (!touchedFields.meta?.timezone && !documentHasBeenSent) {
setValue('meta.timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
}
}, [documentHasBeenSent, setValue, touchedFields.meta?.timezone]);
return (
<>
<DocumentFlowFormContainerHeader
@ -71,10 +109,10 @@ export const AddSubjectFormPartial = ({
// placeholder="Subject"
className="bg-background mt-2"
disabled={isSubmitting}
{...register('email.subject')}
{...register('meta.subject')}
/>
<FormErrorMessage className="mt-2" error={errors.email?.subject} />
<FormErrorMessage className="mt-2" error={errors.meta?.subject} />
</div>
<div>
@ -86,14 +124,12 @@ export const AddSubjectFormPartial = ({
id="message"
className="bg-background mt-2 h-32 resize-none"
disabled={isSubmitting}
{...register('email.message')}
{...register('meta.message')}
/>
<FormErrorMessage
className="mt-2"
error={
typeof errors.email?.message !== 'string' ? errors.email?.message : undefined
}
error={typeof errors.meta?.message !== 'string' ? errors.meta?.message : undefined}
/>
</div>
@ -123,6 +159,65 @@ export const AddSubjectFormPartial = ({
</li>
</ul>
</div>
{hasDateField && (
<Accordion type="multiple" className="mt-8 border-none">
<AccordionItem value="advanced-options" className="border-none">
<AccordionTrigger className="mb-2 border-b text-left hover:no-underline">
Advanced Options
</AccordionTrigger>
<AccordionContent className="text-muted-foreground -mx-1 flex max-w-prose flex-col px-1 text-sm leading-relaxed">
<div className="mt-2 flex flex-col">
<Label htmlFor="date-format">
Date Format <span className="text-muted-foreground">(Optional)</span>
</Label>
<Controller
control={control}
name={`meta.dateFormat`}
disabled={documentHasBeenSent}
render={({ field: { value, onChange, disabled } }) => (
<Select value={value} onValueChange={onChange} disabled={disabled}>
<SelectTrigger className="bg-background mt-2">
<SelectValue />
</SelectTrigger>
<SelectContent>
{DATE_FORMATS.map((format) => (
<SelectItem key={format.key} value={format.value}>
{format.label}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
<div className="mt-4 flex flex-col">
<Label htmlFor="time-zone">
Time Zone <span className="text-muted-foreground">(Optional)</span>
</Label>
<Controller
control={control}
name={`meta.timezone`}
render={({ field: { value, onChange } }) => (
<Combobox
className="bg-background"
options={TIME_ZONES}
value={value}
onChange={(value) => value && onChange(value)}
disabled={documentHasBeenSent}
/>
)}
/>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
)}
</div>
</div>
</DocumentFlowFormContainerContent>

View File

@ -1,9 +1,14 @@
import { z } from 'zod';
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
export const ZAddSubjectFormSchema = z.object({
email: z.object({
meta: z.object({
subject: z.string(),
message: z.string(),
timezone: z.string().optional().default(DEFAULT_DOCUMENT_TIME_ZONE),
dateFormat: z.string().optional().default(DEFAULT_DOCUMENT_DATE_FORMAT),
}),
});

View File

@ -64,7 +64,7 @@ export const AddTitleFormPartial = ({
<Input
id="title"
className="bg-background mt-2"
className="bg-background my-2"
disabled={isSubmitting}
{...register('title', { required: "Title can't be empty" })}
/>

View File

@ -22,12 +22,12 @@ export const DocumentFlowFormContainer = ({
<form
id={id}
className={cn(
'dark:bg-background border-border bg-widget sticky top-20 flex h-full max-h-[64rem] flex-col rounded-xl border px-4 py-6',
'dark:bg-background border-border bg-widget sticky top-20 flex h-full max-h-[64rem] flex-col overflow-auto rounded-xl border px-4 py-6',
className,
)}
{...props}
>
<div className={cn('-mx-2 flex flex-1 flex-col overflow-hidden px-2')}>{children}</div>
<div className={cn('-mx-2 flex flex-1 flex-col px-2')}>{children}</div>
</form>
);
};
@ -63,10 +63,7 @@ export const DocumentFlowFormContainerContent = ({
}: DocumentFlowFormContainerContentProps) => {
return (
<div
className={cn(
'custom-scrollbar -mx-2 flex flex-1 flex-col overflow-y-auto overflow-x-hidden px-2',
className,
)}
className={cn('custom-scrollbar -mx-2 flex flex-1 flex-col overflow-hidden px-2', className)}
{...props}
>
<div className="flex flex-1 flex-col">{children}</div>

View File

@ -0,0 +1,82 @@
import * as React from 'react';
import { Check, ChevronsUpDown } from 'lucide-react';
import { Role } from '@documenso/prisma/client';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
} from '@documenso/ui/primitives/command';
import { Popover, PopoverContent, PopoverTrigger } from '@documenso/ui/primitives/popover';
type ComboboxProps = {
listValues: string[];
onChange: (_values: string[]) => void;
};
const MultiSelectCombobox = ({ listValues, onChange }: ComboboxProps) => {
const [open, setOpen] = React.useState(false);
const [selectedValues, setSelectedValues] = React.useState<string[]>([]);
const dbRoles = Object.values(Role);
React.useEffect(() => {
setSelectedValues(listValues);
}, [listValues]);
const allRoles = [...new Set([...dbRoles, ...selectedValues])];
const handleSelect = (currentValue: string) => {
let newSelectedValues;
if (selectedValues.includes(currentValue)) {
newSelectedValues = selectedValues.filter((value) => value !== currentValue);
} else {
newSelectedValues = [...selectedValues, currentValue];
}
setSelectedValues(newSelectedValues);
onChange(newSelectedValues);
setOpen(false);
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className="w-[200px] justify-between"
>
{selectedValues.length > 0 ? selectedValues.join(', ') : 'Select values...'}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[200px] p-0">
<Command>
<CommandInput placeholder={selectedValues.join(', ')} />
<CommandEmpty>No value found.</CommandEmpty>
<CommandGroup>
{allRoles.map((value: string, i: number) => (
<CommandItem key={i} onSelect={() => handleSelect(value)}>
<Check
className={cn(
'mr-2 h-4 w-4',
selectedValues.includes(value) ? 'opacity-100' : 'opacity-0',
)}
/>
{value}
</CommandItem>
))}
</CommandGroup>
</Command>
</PopoverContent>
</Popover>
);
};
export { MultiSelectCombobox };

View File

@ -42,7 +42,7 @@ const SelectContent = React.forwardRef<
<SelectPrimitive.Content
ref={ref}
className={cn(
'bg-popover text-popover-foreground animate-in fade-in-80 relative z-50 min-w-[8rem] overflow-hidden rounded-md border shadow-md',
'bg-popover text-popover-foreground animate-in fade-in-80 relative z-[1001] min-w-[8rem] overflow-hidden rounded-md border shadow-md',
position === 'popper' && 'translate-y-1',
className,
)}

View File

@ -3,6 +3,7 @@
import type { HTMLAttributes, MouseEvent, PointerEvent, TouchEvent } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Undo2 } from 'lucide-react';
import type { StrokeOptions } from 'perfect-freehand';
import { getStroke } from 'perfect-freehand';
@ -27,7 +28,8 @@ export const SignaturePad = ({
const $el = useRef<HTMLCanvasElement>(null);
const [isPressed, setIsPressed] = useState(false);
const [points, setPoints] = useState<Point[]>([]);
const [lines, setLines] = useState<Point[][]>([]);
const [currentLine, setCurrentLine] = useState<Point[]>([]);
const perfectFreehandOptions = useMemo(() => {
const size = $el.current ? Math.min($el.current.height, $el.current.width) * 0.03 : 10;
@ -52,26 +54,7 @@ export const SignaturePad = ({
const point = Point.fromEvent(event, DPI, $el.current);
const newPoints = [...points, point];
setPoints(newPoints);
if ($el.current) {
const ctx = $el.current.getContext('2d');
if (ctx) {
ctx.save();
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
const pathData = new Path2D(
getSvgPathFromStroke(getStroke(newPoints, perfectFreehandOptions)),
);
ctx.fill(pathData);
}
}
setCurrentLine([point]);
};
const onMouseMove = (event: MouseEvent | PointerEvent | TouchEvent) => {
@ -85,31 +68,36 @@ export const SignaturePad = ({
const point = Point.fromEvent(event, DPI, $el.current);
if (point.distanceTo(points[points.length - 1]) > 5) {
const newPoints = [...points, point];
setPoints(newPoints);
if (point.distanceTo(currentLine[currentLine.length - 1]) > 5) {
setCurrentLine([...currentLine, point]);
// Update the canvas here to draw the lines
if ($el.current) {
const ctx = $el.current.getContext('2d');
if (ctx) {
ctx.restore();
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
const pathData = new Path2D(
getSvgPathFromStroke(getStroke(points, perfectFreehandOptions)),
);
lines.forEach((line) => {
const pathData = new Path2D(
getSvgPathFromStroke(getStroke(line, perfectFreehandOptions)),
);
ctx.fill(pathData);
});
const pathData = new Path2D(
getSvgPathFromStroke(getStroke([...currentLine, point], perfectFreehandOptions)),
);
ctx.fill(pathData);
}
}
}
};
const onMouseUp = (event: MouseEvent | PointerEvent | TouchEvent, addPoint = true) => {
const onMouseUp = (event: MouseEvent | PointerEvent | TouchEvent, addLine = true) => {
if (event.cancelable) {
event.preventDefault();
}
@ -118,15 +106,16 @@ export const SignaturePad = ({
const point = Point.fromEvent(event, DPI, $el.current);
const newPoints = [...points];
const newLines = [...lines];
if (addPoint) {
newPoints.push(point);
setPoints(newPoints);
if (addLine && currentLine.length > 0) {
newLines.push([...currentLine, point]);
setCurrentLine([]);
}
if ($el.current && newPoints.length > 0) {
setLines(newLines);
if ($el.current && newLines.length > 0) {
const ctx = $el.current.getContext('2d');
if (ctx) {
@ -135,19 +124,18 @@ export const SignaturePad = ({
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
const pathData = new Path2D(
getSvgPathFromStroke(getStroke(newPoints, perfectFreehandOptions)),
);
newLines.forEach((line) => {
const pathData = new Path2D(
getSvgPathFromStroke(getStroke(line, perfectFreehandOptions)),
);
ctx.fill(pathData);
});
ctx.fill(pathData);
onChange?.($el.current.toDataURL());
ctx.save();
}
onChange?.($el.current.toDataURL());
}
setPoints([]);
};
const onMouseEnter = (event: MouseEvent | PointerEvent | TouchEvent) => {
@ -177,7 +165,29 @@ export const SignaturePad = ({
onChange?.(null);
setPoints([]);
setLines([]);
setCurrentLine([]);
};
const onUndoClick = () => {
if (lines.length === 0) {
return;
}
const newLines = [...lines];
newLines.pop(); // Remove the last line
setLines(newLines);
// Clear the canvas
if ($el.current) {
const ctx = $el.current.getContext('2d');
ctx?.clearRect(0, 0, $el.current.width, $el.current.height);
newLines.forEach((line) => {
const pathData = new Path2D(getSvgPathFromStroke(getStroke(line, perfectFreehandOptions)));
ctx?.fill(pathData);
});
}
};
useEffect(() => {
@ -217,15 +227,29 @@ export const SignaturePad = ({
{...props}
/>
<div className="absolute bottom-4 right-4">
<div className="absolute bottom-4 right-4 flex gap-2">
<button
type="button"
className="focus-visible:ring-ring ring-offset-background text-muted-foreground rounded-full p-0 text-xs focus-visible:outline-none focus-visible:ring-2"
className="focus-visible:ring-ring ring-offset-background text-muted-foreground/60 hover:text-muted-foreground rounded-full p-0 text-xs focus-visible:outline-none focus-visible:ring-2"
onClick={() => onClearClick()}
>
Clear Signature
</button>
</div>
{lines.length > 0 && (
<div className="absolute bottom-4 left-4 flex gap-2">
<button
type="button"
title="undo"
className="focus-visible:ring-ring ring-offset-background text-muted-foreground/60 hover:text-muted-foreground rounded-full p-0 text-xs focus-visible:outline-none focus-visible:ring-2"
onClick={() => onUndoClick()}
>
<Undo2 className="h-4 w-4" />
<span className="sr-only">Undo</span>
</button>
</div>
)}
</div>
);
};

View File

@ -4,6 +4,8 @@ import { useTheme } from 'next-themes';
import { useIsMounted } from '@documenso/lib/client-only/hooks/use-is-mounted';
import { THEMES_TYPE } from './constants';
export const ThemeSwitcher = () => {
const { theme, setTheme } = useTheme();
const isMounted = useIsMounted();
@ -12,9 +14,9 @@ export const ThemeSwitcher = () => {
<div className="bg-muted flex items-center gap-x-1 rounded-full p-1">
<button
className="text-muted-foreground relative z-10 flex h-8 w-8 items-center justify-center rounded-full"
onClick={() => setTheme('light')}
onClick={() => setTheme(THEMES_TYPE.LIGHT)}
>
{isMounted && theme === 'light' && (
{isMounted && theme === THEMES_TYPE.LIGHT && (
<motion.div
className="bg-background absolute inset-0 rounded-full mix-blend-exclusion"
layoutId="selected-theme"
@ -25,9 +27,9 @@ export const ThemeSwitcher = () => {
<button
className="text-muted-foreground relative z-10 flex h-8 w-8 items-center justify-center rounded-full"
onClick={() => setTheme('dark')}
onClick={() => setTheme(THEMES_TYPE.DARK)}
>
{isMounted && theme === 'dark' && (
{isMounted && theme === THEMES_TYPE.DARK && (
<motion.div
className="bg-background absolute inset-0 rounded-full mix-blend-exclusion"
layoutId="selected-theme"
@ -39,9 +41,9 @@ export const ThemeSwitcher = () => {
<button
className="text-muted-foreground relative z-10 flex h-8 w-8 items-center justify-center rounded-full"
onClick={() => setTheme('system')}
onClick={() => setTheme(THEMES_TYPE.SYSTEM)}
>
{isMounted && theme === 'system' && (
{isMounted && theme === THEMES_TYPE.SYSTEM && (
<motion.div
className="bg-background absolute inset-0 rounded-full mix-blend-exclusion"
layoutId="selected-theme"

View File

@ -1,7 +1,8 @@
import * as React from 'react';
import * as ToastPrimitives from '@radix-ui/react-toast';
import { VariantProps, cva } from 'class-variance-authority';
import { cva } from 'class-variance-authority';
import type { VariantProps } from 'class-variance-authority';
import { X } from 'lucide-react';
import { cn } from '../lib/utils';
@ -15,7 +16,7 @@ const ToastViewport = React.forwardRef<
<ToastPrimitives.Viewport
ref={ref}
className={cn(
'fixed top-0 z-[9999] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]',
'fixed top-0 z-[1001] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]',
className,
)}
{...props}

View File

@ -1,7 +1,7 @@
// Inspired by react-hot-toast library
import * as React from 'react';
import { ToastActionElement, type ToastProps } from './toast';
import type { ToastActionElement, ToastProps } from './toast';
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;