Skip to content

The Open Source DocuSign Alternative.

feat: support embedded authoring for creation (#1741)

Lucas Smithe613e0e347df
diff --git a/apps/documentation/providers/plausible.tsx b/apps/documentation/providers/plausible.tsx
index dceaa4d93..ca8f3c691 100644
--- a/apps/documentation/providers/plausible.tsx
+++ b/apps/documentation/providers/plausible.tsx
@@ -1,5 +1,3 @@
-'use client';
-
import React from 'react';
import NextPlausibleProvider from 'next-plausible';
diff --git a/apps/remix/app/components/embed/authoring/configure-document-advanced-settings.tsx b/apps/remix/app/components/embed/authoring/configure-document-advanced-settings.tsx
new file mode 100644
index 000000000..7beecdcbe
--- /dev/null
+++ b/apps/remix/app/components/embed/authoring/configure-document-advanced-settings.tsx
@@ -0,0 +1,355 @@
+import { useLingui } from '@lingui/react';
+import { Trans } from '@lingui/react/macro';
+import { DocumentDistributionMethod } from '@prisma/client';
+import { InfoIcon } from 'lucide-react';
+import type { Control } from 'react-hook-form';
+import { useFormContext } from 'react-hook-form';
+
+import { DATE_FORMATS } from '@documenso/lib/constants/date-formats';
+import { DOCUMENT_SIGNATURE_TYPES } from '@documenso/lib/constants/document';
+import { SUPPORTED_LANGUAGES } from '@documenso/lib/constants/i18n';
+import { TIME_ZONES } from '@documenso/lib/constants/time-zones';
+import { DocumentEmailCheckboxes } from '@documenso/ui/components/document/document-email-checkboxes';
+import { DocumentSendEmailMessageHelper } from '@documenso/ui/components/document/document-send-email-message-helper';
+import { Combobox } from '@documenso/ui/primitives/combobox';
+import {
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from '@documenso/ui/primitives/form/form';
+import { Input } from '@documenso/ui/primitives/input';
+import { MultiSelectCombobox } from '@documenso/ui/primitives/multi-select-combobox';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@documenso/ui/primitives/select';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@documenso/ui/primitives/tabs';
+import { Textarea } from '@documenso/ui/primitives/textarea';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
+
+import { useConfigureDocument } from './configure-document-context';
+import type { TConfigureEmbedFormSchema } from './configure-document-view.types';
+
+interface ConfigureDocumentAdvancedSettingsProps {
+ control: Control<TConfigureEmbedFormSchema>;
+ isSubmitting: boolean;
+}
+
+export const ConfigureDocumentAdvancedSettings = ({
+ control,
+ isSubmitting,
+}: ConfigureDocumentAdvancedSettingsProps) => {
+ const { _ } = useLingui();
+
+ const form = useFormContext<TConfigureEmbedFormSchema>();
+ const { features } = useConfigureDocument();
+
+ const { watch, setValue } = form;
+
+ // Lift watch() calls to reduce re-renders
+ const distributionMethod = watch('meta.distributionMethod');
+ const emailSettings = watch('meta.emailSettings');
+ const isEmailDistribution = distributionMethod === DocumentDistributionMethod.EMAIL;
+
+ return (
+ <div>
+ <h3 className="text-foreground mb-1 text-lg font-medium">
+ <Trans>Advanced Settings</Trans>
+ </h3>
+
+ <p className="text-muted-foreground mb-6 text-sm">
+ <Trans>Configure additional options and preferences</Trans>
+ </p>
+
+ <Tabs defaultValue="general">
+ <TabsList className="mb-6 inline-flex">
+ <TabsTrigger value="general" className="px-4">
+ <Trans>General</Trans>
+ </TabsTrigger>
+
+ {features.allowConfigureCommunication && (
+ <TabsTrigger value="communication" className="px-4">
+ <Trans>Communication</Trans>
+ </TabsTrigger>
+ )}
+ </TabsList>
+
+ <TabsContent value="general" className="mt-0">
+ <div className="flex flex-col space-y-6">
+ {/* <FormField
+ control={control}
+ name="meta.externalId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="flex flex-row items-center">
+ <Trans>External ID</Trans>
+ <Tooltip>
+ <TooltipTrigger>
+ <InfoIcon className="mx-2 h-4 w-4" />
+ </TooltipTrigger>
+ <TooltipContent className="text-muted-foreground max-w-xs">
+ <Trans>
+ Add an external ID to the document. This can be used to identify the
+ document in external systems.
+ </Trans>
+ </TooltipContent>
+ </Tooltip>
+ </FormLabel>
+ <FormControl>
+ <Input className="bg-background" {...field} disabled={isSubmitting} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ /> */}
+
+ {features.allowConfigureSignatureTypes && (
+ <FormField
+ control={control}
+ name="meta.signatureTypes"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans>Allowed Signature Types</Trans>
+ </FormLabel>
+ <FormControl>
+ <MultiSelectCombobox
+ options={Object.values(DOCUMENT_SIGNATURE_TYPES).map((option) => ({
+ label: _(option.label),
+ value: option.value,
+ }))}
+ selectedValues={field.value}
+ onChange={field.onChange}
+ className="bg-background w-full"
+ emptySelectionPlaceholder="Select signature types"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ {features.allowConfigureLanguage && (
+ <FormField
+ control={control}
+ name="meta.language"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans>Language</Trans>
+ </FormLabel>
+ <FormControl>
+ <Select {...field} onValueChange={field.onChange} disabled={isSubmitting}>
+ <SelectTrigger className="bg-background">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(SUPPORTED_LANGUAGES).map(([code, language]) => (
+ <SelectItem key={code} value={code}>
+ {language.full}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ {features.allowConfigureDateFormat && (
+ <FormField
+ control={control}
+ name="meta.dateFormat"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans>Date Format</Trans>
+ </FormLabel>
+ <FormControl>
+ <Select {...field} onValueChange={field.onChange} disabled={isSubmitting}>
+ <SelectTrigger className="bg-background">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {DATE_FORMATS.map((format) => (
+ <SelectItem key={format.key} value={format.value}>
+ {format.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ {features.allowConfigureTimezone && (
+ <FormField
+ control={control}
+ name="meta.timezone"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans>Time Zone</Trans>
+ </FormLabel>
+ <FormControl>
+ <Combobox
+ className="bg-background"
+ options={TIME_ZONES}
+ {...field}
+ onChange={(value) => value && field.onChange(value)}
+ disabled={isSubmitting}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ {features.allowConfigureRedirectUrl && (
+ <FormField
+ control={control}
+ name="meta.redirectUrl"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="flex flex-row items-center">
+ <Trans>Redirect URL</Trans>
+ <Tooltip>
+ <TooltipTrigger>
+ <InfoIcon className="mx-2 h-4 w-4" />
+ </TooltipTrigger>
+ <TooltipContent className="text-muted-foreground max-w-xs">
+ <Trans>
+ Add a URL to redirect the user to once the document is signed
+ </Trans>
+ </TooltipContent>
+ </Tooltip>
+ </FormLabel>
+ <FormControl>
+ <Input className="bg-background" {...field} disabled={isSubmitting} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+ </div>
+ </TabsContent>
+
+ {features.allowConfigureCommunication && (
+ <TabsContent value="communication" className="mt-0">
+ <div className="flex flex-col space-y-6">
+ <FormField
+ control={control}
+ name="meta.distributionMethod"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans>Distribution Method</Trans>
+ </FormLabel>
+
+ <FormControl>
+ <Select {...field} onValueChange={field.onChange} disabled={isSubmitting}>
+ <SelectTrigger className="bg-background">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={DocumentDistributionMethod.EMAIL}>
+ <Trans>Email</Trans>
+ </SelectItem>
+ <SelectItem value={DocumentDistributionMethod.NONE}>
+ <Trans>None</Trans>
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </FormControl>
+
+ <FormDescription>
+ <Trans>
+ Choose how to distribute your document to recipients. Email will send
+ notifications, None will generate signing links for manual distribution.
+ </Trans>
+ </FormDescription>
+
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <fieldset
+ className="flex flex-col space-y-6 disabled:cursor-not-allowed disabled:opacity-60"
+ disabled={!isEmailDistribution}
+ >
+ <FormField
+ control={control}
+ name="meta.subject"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel htmlFor="subject">
+ <Trans>
+ Subject <span className="text-muted-foreground">(Optional)</span>
+ </Trans>
+ </FormLabel>
+ <FormControl>
+ <Input
+ id="subject"
+ className="bg-background mt-2"
+ disabled={isSubmitting || !isEmailDistribution}
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={control}
+ name="meta.message"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel htmlFor="message">
+ <Trans>
+ Message <span className="text-muted-foreground">(Optional)</span>
+ </Trans>
+ </FormLabel>
+ <FormControl>
+ <Textarea
+ id="message"
+ className="bg-background mt-2 h-32 resize-none"
+ disabled={isSubmitting || !isEmailDistribution}
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <DocumentSendEmailMessageHelper />
+
+ <DocumentEmailCheckboxes
+ className={`mt-2 ${!isEmailDistribution ? 'pointer-events-none' : ''}`}
+ value={emailSettings}
+ onChange={(value) => setValue('meta.emailSettings', value)}
+ />
+ </fieldset>
+ </div>
+ </TabsContent>
+ )}
+ </Tabs>
+ </div>
+ );
+};
diff --git a/apps/remix/app/components/embed/authoring/configure-document-context.tsx b/apps/remix/app/components/embed/authoring/configure-document-context.tsx
new file mode 100644
index 000000000..a89b62b7f
--- /dev/null
+++ b/apps/remix/app/components/embed/authoring/configure-document-context.tsx
@@ -0,0 +1,68 @@
+import { createContext, useContext } from 'react';
+
+export type ConfigureDocumentContext = {
+ // General
+ isTemplate: boolean;
+ isPersisted: boolean;
+ // Features
+ features: {
+ allowConfigureSignatureTypes?: boolean;
+ allowConfigureLanguage?: boolean;
+ allowConfigureDateFormat?: boolean;
+ allowConfigureTimezone?: boolean;
+ allowConfigureRedirectUrl?: boolean;
+ allowConfigureCommunication?: boolean;
+ };
+};
+
+const ConfigureDocumentContext = createContext<ConfigureDocumentContext | null>(null);
+
+export type ConfigureDocumentProviderProps = {
+ isTemplate?: boolean;
+ isPersisted?: boolean;
+ features: {
+ allowConfigureSignatureTypes?: boolean;
+ allowConfigureLanguage?: boolean;
+ allowConfigureDateFormat?: boolean;
+ allowConfigureTimezone?: boolean;
+ allowConfigureRedirectUrl?: boolean;
+ allowConfigureCommunication?: boolean;
+ };
+ children: React.ReactNode;
+};
+
+export const ConfigureDocumentProvider = ({
+ isTemplate,
+ isPersisted,
+ features,
+ children,
+}: ConfigureDocumentProviderProps) => {
+ return (
+ <ConfigureDocumentContext.Provider
+ value={{
+ isTemplate: isTemplate ?? false,
+ isPersisted: isPersisted ?? false,
+ features: {
+ allowConfigureSignatureTypes: features.allowConfigureSignatureTypes ?? true,
+ allowConfigureLanguage: features.allowConfigureLanguage ?? true,
+ allowConfigureDateFormat: features.allowConfigureDateFormat ?? true,
+ allowConfigureTimezone: features.allowConfigureTimezone ?? true,
+ allowConfigureRedirectUrl: features.allowConfigureRedirectUrl ?? true,
+ allowConfigureCommunication: features.allowConfigureCommunication ?? true,
+ },
+ }}
+ >
+ {children}
+ </ConfigureDocumentContext.Provider>
+ );
+};
+
+export const useConfigureDocument = () => {
+ const context = useContext(ConfigureDocumentContext);
+
+ if (!context) {
+ throw new Error('useConfigureDocument must be used within a ConfigureDocumentProvider');
+ }
+
+ return context;
+};
diff --git a/apps/remix/app/components/embed/authoring/configure-document-recipients.tsx b/apps/remix/app/components/embed/authoring/configure-document-recipients.tsx
new file mode 100644
index 000000000..06b70f3c7
--- /dev/null
+++ b/apps/remix/app/components/embed/authoring/configure-document-recipients.tsx
@@ -0,0 +1,393 @@
+import { useCallback, useRef } from 'react';
+
+import type { DropResult, SensorAPI } from '@hello-pangea/dnd';
+import { DragDropContext, Draggable, Droppable } from '@hello-pangea/dnd';
+import { msg } from '@lingui/core/macro';
+import { useLingui } from '@lingui/react';
+import { Trans } from '@lingui/react/macro';
+import { DocumentSigningOrder, RecipientRole } from '@prisma/client';
+import { motion } from 'framer-motion';
+import { GripVertical, HelpCircle, Plus, Trash } from 'lucide-react';
+import { nanoid } from 'nanoid';
+import type { Control } from 'react-hook-form';
+import { useFieldArray, useFormContext, useFormState } from 'react-hook-form';
+
+import { RecipientRoleSelect } from '@documenso/ui/components/recipient/recipient-role-select';
+import { cn } from '@documenso/ui/lib/utils';
+import { Button } from '@documenso/ui/primitives/button';
+import { Checkbox } from '@documenso/ui/primitives/checkbox';
+import {
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from '@documenso/ui/primitives/form/form';
+import { Input } from '@documenso/ui/primitives/input';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
+
+import { useConfigureDocument } from './configure-document-context';
+import type { TConfigureEmbedFormSchema } from './configure-document-view.types';
+
+// Define a type for signer items
+type SignerItem = TConfigureEmbedFormSchema['signers'][number];
+
+export interface ConfigureDocumentRecipientsProps {
+ control: Control<TConfigureEmbedFormSchema>;
+ isSubmitting: boolean;
+}
+
+export const ConfigureDocumentRecipients = ({
+ control,
+ isSubmitting,
+}: ConfigureDocumentRecipientsProps) => {
+ const { _ } = useLingui();
+ const { isTemplate } = useConfigureDocument();
+
+ const $sensorApi = useRef<SensorAPI | null>(null);
+
+ const {
+ fields: signers,
+ append: appendSigner,
+ remove: removeSigner,
+ replace,
+ move,
+ } = useFieldArray({
+ control,
+ name: 'signers',
+ });
+
+ const { getValues, watch } = useFormContext<TConfigureEmbedFormSchema>();
+
+ const signingOrder = watch('meta.signingOrder');
+
+ const { errors } = useFormState({
+ control,
+ });
+
+ const onAddSigner = useCallback(() => {
+ const signerNumber = signers.length + 1;
+
+ appendSigner({
+ formId: nanoid(8),
+ name: isTemplate ? `Recipient ${signerNumber}` : '',
+ email: isTemplate ? `recipient.${signerNumber}@document.com` : '',
+ role: RecipientRole.SIGNER,
+ signingOrder: signers.length > 0 ? (signers[signers.length - 1]?.signingOrder || 0) + 1 : 1,
+ });
+ }, [appendSigner, signers]);
+
+ const isSigningOrderEnabled = signingOrder === DocumentSigningOrder.SEQUENTIAL;
+
+ const handleSigningOrderChange = useCallback(
+ (index: number, newOrderString: string) => {
+ const trimmedOrderString = newOrderString.trim();
+ if (!trimmedOrderString) {
+ return;
+ }
+
+ const newOrder = Number(trimmedOrderString);
+ if (!Number.isInteger(newOrder) || newOrder < 1) {
+ return;
+ }
+
+ // Get current form values to preserve unsaved input data
+ const currentSigners = getValues('signers') || [...signers];
+ const signer = currentSigners[index];
+
+ // Remove signer from current position and insert at new position
+ const remainingSigners = currentSigners.filter((_: unknown, idx: number) => idx !== index);
+ const newPosition = Math.min(Math.max(0, newOrder - 1), currentSigners.length - 1);
+ remainingSigners.splice(newPosition, 0, signer);
+
+ // Update signing order for each item
+ const updatedSigners = remainingSigners.map((s: SignerItem, idx: number) => ({
+ ...s,
+ signingOrder: idx + 1,
+ }));
+
+ // Update the form
+ replace(updatedSigners);
+ },
+ [signers, replace, getValues],
+ );
+
+ const onDragEnd = useCallback(
+ (result: DropResult) => {
+ if (!result.destination) return;
+
+ // Use the move function from useFieldArray which preserves input values
+ move(result.source.index, result.destination.index);
+
+ // Update signing orders after move
+ const currentSigners = getValues('signers');
+ const updatedSigners = currentSigners.map((signer: SignerItem, index: number) => ({
+ ...signer,
+ signingOrder: index + 1,
+ }));
+
+ // Update the form with new ordering
+ replace(updatedSigners);
+ },
+ [move, replace, getValues],
+ );
+
+ return (
+ <div>
+ <h3 className="text-foreground mb-1 text-lg font-medium">
+ <Trans>Recipients</Trans>
+ </h3>
+
+ <p className="text-muted-foreground mb-6 text-sm">
+ <Trans>Add signers and configure signing preferences</Trans>
+ </p>
+
+ <FormField
+ control={control}
+ name="meta.signingOrder"
+ render={({ field }) => (
+ <FormItem className="mb-6 flex flex-row items-center space-x-2 space-y-0">
+ <FormControl>
+ <Checkbox
+ {...field}
+ id="signingOrder"
+ checked={field.value === DocumentSigningOrder.SEQUENTIAL}
+ onCheckedChange={(checked) => {
+ field.onChange(
+ checked ? DocumentSigningOrder.SEQUENTIAL : DocumentSigningOrder.PARALLEL,
+ );
+ }}
+ disabled={isSubmitting}
+ />
+ </FormControl>
+ <FormLabel
+ htmlFor="signingOrder"
+ className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ <Trans>Enable signing order</Trans>
+ </FormLabel>
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={control}
+ name="meta.allowDictateNextSigner"
+ render={({ field: { value, ...field } }) => (
+ <FormItem className="mb-6 flex flex-row items-center space-x-2 space-y-0">
+ <FormControl>
+ <Checkbox
+ {...field}
+ id="allowDictateNextSigner"
+ checked={value}
+ onCheckedChange={field.onChange}
+ disabled={isSubmitting || !isSigningOrderEnabled}
+ />
+ </FormControl>
+ <div className="flex items-center">
+ <FormLabel
+ htmlFor="allowDictateNextSigner"
+ className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ <Trans>Allow signers to dictate next signer</Trans>
+ </FormLabel>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-muted-foreground ml-1 cursor-help">
+ <HelpCircle className="h-3.5 w-3.5" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-80 p-4">
+ <p>
+ <Trans>
+ When enabled, signers can choose who should sign next in the sequence instead
+ of following the predefined order.
+ </Trans>
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </FormItem>
+ )}
+ />
+
+ <DragDropContext
+ onDragEnd={onDragEnd}
+ sensors={[
+ (api: SensorAPI) => {
+ $sensorApi.current = api;
+ },
+ ]}
+ >
+ <Droppable droppableId="signers">
+ {(provided) => (
+ <div {...provided.droppableProps} ref={provided.innerRef} className="space-y-2">
+ {signers.map((signer, index) => (
+ <Draggable
+ key={signer.id}
+ draggableId={signer.id}
+ index={index}
+ isDragDisabled={!isSigningOrderEnabled || isSubmitting}
+ >
+ {(provided, snapshot) => (
+ <div
+ ref={provided.innerRef}
+ {...provided.draggableProps}
+ {...provided.dragHandleProps}
+ className={cn('py-1', {
+ 'bg-widget-foreground pointer-events-none rounded-md pt-2':
+ snapshot.isDragging,
+ })}
+ >
+ <motion.div
+ className={cn('flex items-end gap-2 pb-2', {
+ 'border-destructive/50': errors?.signers?.[index],
+ })}
+ >
+ {isSigningOrderEnabled && (
+ <FormField
+ control={control}
+ name={`signers.${index}.signingOrder`}
+ render={({ field }) => (
+ <FormItem
+ className={cn('flex w-16 flex-none items-center gap-x-1', {
+ 'mb-6':
+ errors?.signers?.[index] &&
+ !errors?.signers?.[index]?.signingOrder,
+ })}
+ >
+ <GripVertical className="h-5 w-5 flex-shrink-0 opacity-40" />
+ <FormControl>
+ <Input
+ type="number"
+ max={signers.length}
+ min={1}
+ className="w-full text-center [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
+ {...field}
+ disabled={isSubmitting || snapshot.isDragging}
+ onChange={(e) => {
+ field.onChange(e);
+ }}
+ onBlur={(e) => {
+ field.onBlur();
+ handleSigningOrderChange(index, e.target.value);
+ }}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ <FormField
+ control={control}
+ name={`signers.${index}.name`}
+ render={({ field }) => (
+ <FormItem
+ className={cn('flex-1', {
+ 'mb-6': errors?.signers?.[index] && !errors?.signers?.[index]?.name,
+ })}
+ >
+ <FormLabel className="sr-only">
+ <Trans>Name</Trans>
+ </FormLabel>
+ <FormControl>
+ <Input
+ placeholder={_(msg`Name`)}
+ className="w-full"
+ {...field}
+ disabled={isSubmitting || snapshot.isDragging}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={control}
+ name={`signers.${index}.email`}
+ render={({ field }) => (
+ <FormItem
+ className={cn('flex-1', {
+ 'mb-6':
+ errors?.signers?.[index] && !errors?.signers?.[index]?.email,
+ })}
+ >
+ <FormLabel className="sr-only">
+ <Trans>Email</Trans>
+ </FormLabel>
+ <FormControl>
+ <Input
+ type="email"
+ placeholder={_(msg`Email`)}
+ className="w-full"
+ {...field}
+ disabled={isSubmitting || snapshot.isDragging}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={control}
+ name={`signers.${index}.role`}
+ render={({ field }) => (
+ <FormItem
+ className={cn('flex-none', {
+ 'mb-6': errors?.signers?.[index] && !errors?.signers?.[index]?.role,
+ })}
+ >
+ <FormLabel className="sr-only">
+ <Trans>Role</Trans>
+ </FormLabel>
+ <FormControl>
+ <RecipientRoleSelect
+ {...field}
+ isAssistantEnabled={isSigningOrderEnabled}
+ onValueChange={field.onChange}
+ disabled={isSubmitting || snapshot.isDragging}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={isSubmitting || signers.length === 1 || snapshot.isDragging}
+ onClick={() => removeSigner(index)}
+ >
+ <Trash className="h-4 w-4" />
+ </Button>
+ </motion.div>
+ </div>
+ )}
+ </Draggable>
+ ))}
+ {provided.placeholder}
+ </div>
+ )}
+ </Droppable>
+ </DragDropContext>
+
+ <div className="mt-4 flex justify-end">
+ <Button
+ type="button"
+ variant="outline"
+ className="w-auto"
+ disabled={isSubmitting}
+ onClick={onAddSigner}
+ >
+ <Plus className="-ml-1 mr-2 h-5 w-5" />
+ <Trans>Add Signer</Trans>
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/remix/app/components/embed/authoring/configure-document-upload.tsx b/apps/remix/app/components/embed/authoring/configure-document-upload.tsx
new file mode 100644
index 000000000..271a1d8a3
--- /dev/null
+++ b/apps/remix/app/components/embed/authoring/configure-document-upload.tsx
@@ -0,0 +1,241 @@
+import { useState } from 'react';
+
+import { msg } from '@lingui/core/macro';
+import { useLingui } from '@lingui/react';
+import { Trans } from '@lingui/react/macro';
+import { Cloud, FileText, Loader, X } from 'lucide-react';
+import { useDropzone } from 'react-dropzone';
+import { useFormContext } from 'react-hook-form';
+
+import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';
+import { cn } from '@documenso/ui/lib/utils';
+import { Button } from '@documenso/ui/primitives/button';
+import {
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from '@documenso/ui/primitives/form/form';
+import { useToast } from '@documenso/ui/primitives/use-toast';
+
+import { useConfigureDocument } from './configure-document-context';
+import type { TConfigureEmbedFormSchema } from './configure-document-view.types';
+
+export interface ConfigureDocumentUploadProps {
+ isSubmitting?: boolean;
+}
+
+export const ConfigureDocumentUpload = ({ isSubmitting = false }: ConfigureDocumentUploadProps) => {
+ const { _ } = useLingui();
+ const { toast } = useToast();
+ const { isPersisted } = useConfigureDocument();
+
+ const form = useFormContext<TConfigureEmbedFormSchema>();
+
+ const [isLoading, setIsLoading] = useState(false);
+
+ // Watch the documentData field from the form
+ const documentData = form.watch('documentData');
+
+ const onFileDrop = async (acceptedFiles: File[]) => {
+ try {
+ const file = acceptedFiles[0];
+
+ if (!file) {
+ return;
+ }
+
+ setIsLoading(true);
+
+ // Convert file to UInt8Array
+ const arrayBuffer = await file.arrayBuffer();
+ const uint8Array = new Uint8Array(arrayBuffer);
+
+ // Store file metadata and UInt8Array in form data
+ form.setValue('documentData', {
+ name: file.name,
+ type: file.type,
+ size: file.size,
+ data: uint8Array, // Store as UInt8Array
+ });
+
+ // Auto-populate title if it's empty
+ const currentTitle = form.getValues('title');
+
+ if (!currentTitle) {
+ // Get filename without extension
+ const fileNameWithoutExtension = file.name.replace(/\.[^/.]+$/, '');
+ form.setValue('title', fileNameWithoutExtension);
+ }
+ } catch (error) {
+ console.error('Error uploading file', error);
+
+ toast({
+ title: _(msg`Error uploading file`),
+ description: _(msg`There was an error uploading your file. Please try again.`),
+ variant: 'destructive',
+ duration: 5000,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const onDropRejected = () => {
+ toast({
+ title: _(msg`Your document failed to upload.`),
+ description: _(msg`File cannot be larger than ${APP_DOCUMENT_UPLOAD_SIZE_LIMIT}MB`),
+ duration: 5000,
+ variant: 'destructive',
+ });
+ };
+
+ const onRemoveFile = () => {
+ if (isPersisted) {
+ toast({
+ title: _(msg`Cannot remove document`),
+ description: _(msg`The document is already saved and cannot be changed.`),
+ duration: 5000,
+ variant: 'destructive',
+ });
+ return;
+ }
+
+ form.unregister('documentData');
+ };
+
+ const formatFileSize = (bytes: number) => {
+ if (bytes === 0) return '0 Bytes';
+
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
+ return `${parseFloat((bytes / Math.pow(1024, i)).toFixed(2))} ${sizes[i]}`;
+ };
+
+ const { getRootProps, getInputProps, isDragActive } = useDropzone({
+ accept: {
+ 'application/pdf': ['.pdf'],
+ 'application/msword': ['.doc'],
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
+ 'text/plain': ['.txt'],
+ },
+ maxSize: APP_DOCUMENT_UPLOAD_SIZE_LIMIT * 1024 * 1024,
+ multiple: false,
+ disabled: isSubmitting || isLoading || isPersisted,
+ onDrop: (files) => {
+ void onFileDrop(files);
+ },
+ onDropRejected,
+ });
+
+ return (
+ <div>
+ <FormField
+ control={form.control}
+ name="documentData"
+ render={() => (
+ <FormItem>
+ <FormLabel required>
+ <Trans>Upload Document</Trans>
+ </FormLabel>
+
+ <div className="relative">
+ {!documentData ? (
+ <div className="relative">
+ <FormControl>
+ <div
+ {...getRootProps()}
+ className={cn(
+ 'border-border bg-background relative flex min-h-[160px] cursor-pointer flex-col items-center justify-center rounded-lg border border-dashed transition',
+ {
+ 'border-primary/50 bg-primary/5': isDragActive,
+ 'hover:bg-muted/30':
+ !isDragActive && !isSubmitting && !isLoading && !isPersisted,
+ 'cursor-not-allowed opacity-60': isSubmitting || isLoading || isPersisted,
+ },
+ )}
+ >
+ <input {...getInputProps()} />
+
+ <div className="flex flex-col items-center justify-center gap-y-2 px-4 py-4 text-center">
+ <Cloud
+ className={cn('h-10 w-10', {
+ 'text-primary': isDragActive,
+ 'text-muted-foreground': !isDragActive,
+ })}
+ />
+
+ <div
+ className={cn('flex flex-col space-y-1', {
+ 'text-primary': isDragActive,
+ 'text-muted-foreground': !isDragActive,
+ })}
+ >
+ <p className="text-sm font-medium">
+ {isDragActive ? (
+ <Trans>Drop your document here</Trans>
+ ) : isPersisted ? (
+ <Trans>Document is already uploaded</Trans>
+ ) : (
+ <Trans>Drag and drop or click to upload</Trans>
+ )}
+ </p>
+ <p className="text-xs">
+ {isPersisted ? (
+ <Trans>This document cannot be changed</Trans>
+ ) : (
+ <Trans>
+ .PDF documents accepted (max {APP_DOCUMENT_UPLOAD_SIZE_LIMIT}MB)
+ </Trans>
+ )}
+ </p>
+ </div>
+ </div>
+ </div>
+ </FormControl>
+
+ {isLoading && (
+ <div className="bg-background/50 absolute inset-0 flex items-center justify-center rounded-lg">
+ <Loader className="text-muted-foreground h-10 w-10 animate-spin" />
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="mt-2 rounded-lg border p-4">
+ <div className="flex items-center gap-x-4">
+ <div className="bg-primary/10 text-primary flex h-12 w-12 items-center justify-center rounded-md">
+ <FileText className="h-6 w-6" />
+ </div>
+
+ <div className="flex-1">
+ <div className="text-sm font-medium">{documentData.name}</div>
+ <div className="text-muted-foreground text-xs">
+ {formatFileSize(documentData.size)}
+ </div>
+ </div>
+
+ {!isPersisted && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={onRemoveFile}
+ disabled={isSubmitting}
+ className="h-8 w-8 p-0"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ );
+};
diff --git a/apps/remix/app/components/embed/authoring/configure-document-view.tsx b/apps/remix/app/components/embed/authoring/configure-document-view.tsx
new file mode 100644
index 000000000..c9e5097ce
--- /dev/null
+++ b/apps/remix/app/components/embed/authoring/configure-document-view.tsx
@@ -0,0 +1,131 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { Trans } from '@lingui/react/macro';
+import { DocumentDistributionMethod, DocumentSigningOrder, RecipientRole } from '@prisma/client';
+import { nanoid } from 'nanoid';
+import { useForm } from 'react-hook-form';
+
+import { DEFAULT_DOCUMENT_DATE_FORMAT } from '@documenso/lib/constants/date-formats';
+import { DEFAULT_DOCUMENT_TIME_ZONE } from '@documenso/lib/constants/time-zones';
+import { ZDocumentEmailSettingsSchema } from '@documenso/lib/types/document-email';
+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 { ConfigureDocumentAdvancedSettings } from './configure-document-advanced-settings';
+import { useConfigureDocument } from './configure-document-context';
+import { ConfigureDocumentRecipients } from './configure-document-recipients';
+import { ConfigureDocumentUpload } from './configure-document-upload';
+import {
+ type TConfigureEmbedFormSchema,
+ ZConfigureEmbedFormSchema,
+} from './configure-document-view.types';
+
+export interface ConfigureDocumentViewProps {
+ onSubmit: (data: TConfigureEmbedFormSchema) => void | Promise<void>;
+ defaultValues?: Partial<TConfigureEmbedFormSchema>;
+ isSubmitting?: boolean;
+}
+
+export const ConfigureDocumentView = ({ onSubmit, defaultValues }: ConfigureDocumentViewProps) => {
+ const { isTemplate } = useConfigureDocument();
+
+ const form = useForm<TConfigureEmbedFormSchema>({
+ resolver: zodResolver(ZConfigureEmbedFormSchema),
+ defaultValues: {
+ title: defaultValues?.title || '',
+ signers: defaultValues?.signers || [
+ {
+ formId: nanoid(8),
+ name: isTemplate ? `Recipient ${1}` : '',
+ email: isTemplate ? `recipient.${1}@document.com` : '',
+ role: RecipientRole.SIGNER,
+ signingOrder: 1,
+ },
+ ],
+ meta: {
+ subject: defaultValues?.meta?.subject || '',
+ message: defaultValues?.meta?.message || '',
+ distributionMethod:
+ defaultValues?.meta?.distributionMethod || DocumentDistributionMethod.EMAIL,
+ emailSettings: defaultValues?.meta?.emailSettings || ZDocumentEmailSettingsSchema.parse({}),
+ dateFormat: defaultValues?.meta?.dateFormat || DEFAULT_DOCUMENT_DATE_FORMAT,
+ timezone: defaultValues?.meta?.timezone || DEFAULT_DOCUMENT_TIME_ZONE,
+ redirectUrl: defaultValues?.meta?.redirectUrl || '',
+ language: defaultValues?.meta?.language || 'en',
+ signatureTypes: defaultValues?.meta?.signatureTypes || [],
+ signingOrder: defaultValues?.meta?.signingOrder || DocumentSigningOrder.PARALLEL,
+ allowDictateNextSigner: defaultValues?.meta?.allowDictateNextSigner || false,
+ externalId: defaultValues?.meta?.externalId || '',
+ },
+ documentData: defaultValues?.documentData,
+ },
+ });
+
+ const { control, handleSubmit } = form;
+
+ const isSubmitting = form.formState.isSubmitting;
+
+ const onFormSubmit = handleSubmit(onSubmit);
+
+ return (
+ <div className="flex w-full flex-col space-y-8">
+ <div>
+ <h2 className="text-foreground mb-1 text-xl font-semibold">
+ {isTemplate ? <Trans>Configure Template</Trans> : <Trans>Configure Document</Trans>}
+ </h2>
+
+ <p className="text-muted-foreground text-sm">
+ {isTemplate ? (
+ <Trans>Set up your template properties and recipient information</Trans>
+ ) : (
+ <Trans>Set up your document properties and recipient information</Trans>
+ )}
+ </p>
+ </div>
+
+ <Form {...form}>
+ <div className="flex flex-col space-y-8">
+ <div>
+ <FormField
+ control={control}
+ name="title"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel required>
+ <Trans>Title</Trans>
+ </FormLabel>
+ <FormControl>
+ <Input {...field} disabled={isSubmitting} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <ConfigureDocumentUpload isSubmitting={isSubmitting} />
+ <ConfigureDocumentRecipients control={control} isSubmitting={isSubmitting} />
+ <ConfigureDocumentAdvancedSettings control={control} isSubmitting={isSubmitting} />
+
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ onClick={onFormSubmit}
+ disabled={isSubmitting}
+ className="w-full sm:w-auto"
+ >
+ <Trans>Continue</Trans>
+ </Button>
+ </div>
+ </div>
+ </Form>
+ </div>
+ );
+};
diff --git a/apps/remix/app/components/embed/authoring/configure-document-view.types.ts b/apps/remix/app/components/embed/authoring/configure-document-view.types.ts
new file mode 100644
index 000000000..bbd90e4a0
--- /dev/null
+++ b/apps/remix/app/components/embed/authoring/configure-document-view.types.ts
@@ -0,0 +1,48 @@
+import { z } from 'zod';
+
+import { ZDocumentEmailSettingsSchema } from '@documenso/lib/types/document-email';
+import { DocumentDistributionMethod } from '@documenso/prisma/generated/types';
+import {
+ ZDocumentMetaDateFormatSchema,
+ ZDocumentMetaLanguageSchema,
+} from '@documenso/trpc/server/document-router/schema';
+
+// Define the schema for configuration
+export type TConfigureEmbedFormSchema = z.infer<typeof ZConfigureEmbedFormSchema>;
+
+export const ZConfigureEmbedFormSchema = z.object({
+ title: z.string().min(1, { message: 'Title is required' }),
+ signers: z
+ .array(
+ z.object({
+ formId: z.string(),
+ name: z.string().min(1, { message: 'Name is required' }),
+ email: z.string().email('Invalid email address'),
+ role: z.enum(['SIGNER', 'CC', 'APPROVER', 'VIEWER', 'ASSISTANT']),
+ signingOrder: z.number().optional(),
+ }),
+ )
+ .min(1, { message: 'At least one signer is required' }),
+ meta: z.object({
+ subject: z.string().optional(),
+ message: z.string().optional(),
+ distributionMethod: z.nativeEnum(DocumentDistributionMethod),
+ emailSettings: ZDocumentEmailSettingsSchema,
+ dateFormat: ZDocumentMetaDateFormatSchema.optional(),
+ timezone: z.string().min(1, 'Timezone is required'),
+ redirectUrl: z.string().optional(),
+ language: ZDocumentMetaLanguageSchema.optional(),
+ signatureTypes: z.array(z.string()).default([]),
+ signingOrder: z.enum(['SEQUENTIAL', 'PARALLEL']),
+ allowDictateNextSigner: z.boolean().default(false),
+ externalId: z.string().optional(),
+ }),
+ documentData: z
+ .object({
+ name: z.string(),
+ type: z.string(),
+ size: z.number(),
+ data: z.instanceof(Uint8Array), // UInt8Array can't be directly validated by zod
+ })
+ .optional(),
+});
diff --git a/apps/remix/app/components/embed/authoring/configure-fields-view.tsx b/apps/remix/app/components/embed/authoring/configure-fields-view.tsx
new file mode 100644
index 000000000..24b4801c1
--- /dev/null
+++ b/apps/remix/app/components/embed/authoring/configure-fields-view.tsx
@@ -0,0 +1,661 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+
+import { useLingui } from '@lingui/react';
+import { Trans } from '@lingui/react/macro';
+import type { DocumentData } from '@prisma/client';
+import { FieldType, ReadStatus, type Recipient, SendStatus, SigningStatus } from '@prisma/client';
+import { ChevronsUpDown } from 'lucide-react';
+import { useFieldArray, useForm } from 'react-hook-form';
+import { useHotkeys } from 'react-hotkeys-hook';
+import { z } from 'zod';
+
+import { getBoundingClientRect } from '@documenso/lib/client-only/get-bounding-client-rect';
+import { useDocumentElement } from '@documenso/lib/client-only/hooks/use-document-element';
+import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
+import { type TFieldMetaSchema, ZFieldMetaSchema } from '@documenso/lib/types/field-meta';
+import { base64 } from '@documenso/lib/universal/base64';
+import { nanoid } from '@documenso/lib/universal/id';
+import { ADVANCED_FIELD_TYPES_WITH_OPTIONAL_SETTING } from '@documenso/lib/utils/advanced-fields-helpers';
+import { useSignerColors } from '@documenso/ui/lib/signer-colors';
+import { cn } from '@documenso/ui/lib/utils';
+import { Button } from '@documenso/ui/primitives/button';
+import { FieldItem } from '@documenso/ui/primitives/document-flow/field-item';
+import { FRIENDLY_FIELD_TYPE } from '@documenso/ui/primitives/document-flow/types';
+import { ElementVisible } from '@documenso/ui/primitives/element-visible';
+import { FieldSelector } from '@documenso/ui/primitives/field-selector';
+import { Form } from '@documenso/ui/primitives/form/form';
+import PDFViewer from '@documenso/ui/primitives/pdf-viewer';
+import { RecipientSelector } from '@documenso/ui/primitives/recipient-selector';
+import { Sheet, SheetContent, SheetTrigger } from '@documenso/ui/primitives/sheet';
+import { useToast } from '@documenso/ui/primitives/use-toast';
+
+import type { TConfigureEmbedFormSchema } from './configure-document-view.types';
+import { FieldAdvancedSettingsDrawer } from './field-advanced-settings-drawer';
+
+const MIN_HEIGHT_PX = 12;
+const MIN_WIDTH_PX = 36;
+
+const DEFAULT_HEIGHT_PX = MIN_HEIGHT_PX * 2.5;
+const DEFAULT_WIDTH_PX = MIN_WIDTH_PX * 2.5;
+
+export const ZConfigureFieldsFormSchema = z.object({
+ fields: z.array(
+ z.object({
+ formId: z.string().min(1),
+ id: z.string().min(1),
+ type: z.nativeEnum(FieldType),
+ signerEmail: z.string().min(1),
+ recipientId: z.number().min(0),
+ pageNumber: z.number().min(1),
+ pageX: z.number().min(0),
+ pageY: z.number().min(0),
+ pageWidth: z.number().min(0),
+ pageHeight: z.number().min(0),
+ fieldMeta: ZFieldMetaSchema.optional(),
+ }),
+ ),
+});
+
+export type TConfigureFieldsFormSchema = z.infer<typeof ZConfigureFieldsFormSchema>;
+
+export type ConfigureFieldsViewProps = {
+ configData: TConfigureEmbedFormSchema;
+ defaultValues?: Partial<TConfigureFieldsFormSchema>;
+ onBack: (data: TConfigureFieldsFormSchema) => void;
+ onSubmit: (data: TConfigureFieldsFormSchema) => void;
+};
+
+export const ConfigureFieldsView = ({
+ configData,
+ defaultValues,
+ onBack,
+ onSubmit,
+}: ConfigureFieldsViewProps) => {
+ const { toast } = useToast();
+ const { isWithinPageBounds, getFieldPosition, getPage } = useDocumentElement();
+ const { _ } = useLingui();
+
+ // Track if we're on a mobile device
+ const [isMobile, setIsMobile] = useState(false);
+
+ // State for managing the mobile drawer
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+
+ // Check for mobile viewport on component mount and resize
+ useEffect(() => {
+ const checkIfMobile = () => {
+ setIsMobile(window.innerWidth < 768);
+ };
+
+ // Initial check
+ checkIfMobile();
+
+ // Add resize listener
+ window.addEventListener('resize', checkIfMobile);
+
+ // Cleanup
+ return () => {
+ window.removeEventListener('resize', checkIfMobile);
+ };
+ }, []);
+
+ const documentData = useMemo(() => {
+ if (!configData.documentData) {
+ return null;
+ }
+
+ const data = base64.encode(configData.documentData?.data);
+
+ return {
+ id: 'preview',
+ type: 'BYTES_64',
+ data,
+ initialData: data,
+ } satisfies DocumentData;
+ }, [configData.documentData]);
+
+ const recipients = useMemo(() => {
+ return configData.signers.map<Recipient>((signer, index) => ({
+ id: index,
+ name: signer.name || '',
+ email: signer.email || '',
+ role: signer.role,
+ signingOrder: signer.signingOrder || null,
+ documentId: null,
+ templateId: null,
+ token: '',
+ documentDeletedAt: null,
+ expired: null,
+ signedAt: null,
+ authOptions: null,
+ rejectionReason: null,
+ sendStatus: SendStatus.NOT_SENT,
+ readStatus: ReadStatus.NOT_OPENED,
+ signingStatus: SigningStatus.NOT_SIGNED,
+ }));
+ }, [configData.signers]);
+
+ const [selectedRecipient, setSelectedRecipient] = useState<Recipient | null>(
+ () => recipients[0] || null,
+ );
+ const [selectedField, setSelectedField] = useState<FieldType | null>(null);
+ const [isFieldWithinBounds, setIsFieldWithinBounds] = useState(false);
+ const [coords, setCoords] = useState({
+ x: 0,
+ y: 0,
+ });
+ const [activeFieldId, setActiveFieldId] = useState<string | null>(null);
+ const [lastActiveField, setLastActiveField] = useState<
+ TConfigureFieldsFormSchema['fields'][0] | null
+ >(null);
+ const [fieldClipboard, setFieldClipboard] = useState<
+ TConfigureFieldsFormSchema['fields'][0] | null
+ >(null);
+ const [showAdvancedSettings, setShowAdvancedSettings] = useState(false);
+ const [currentField, setCurrentField] = useState<TConfigureFieldsFormSchema['fields'][0] | null>(
+ null,
+ );
+
+ const fieldBounds = useRef({
+ height: DEFAULT_HEIGHT_PX,
+ width: DEFAULT_WIDTH_PX,
+ });
+
+ const selectedRecipientIndex = recipients.findIndex((r) => r.id === selectedRecipient?.id);
+ const selectedSignerStyles = useSignerColors(
+ selectedRecipientIndex === -1 ? 0 : selectedRecipientIndex,
+ );
+
+ const form = useForm<TConfigureFieldsFormSchema>({
+ defaultValues: {
+ fields: defaultValues?.fields ?? [],
+ },
+ });
+
+ const { control, handleSubmit } = form;
+
+ const onFormSubmit = handleSubmit(onSubmit);
+
+ const {
+ append,
+ remove,
+ update,
+ fields: localFields,
+ } = useFieldArray({
+ control: control,
+ name: 'fields',
+ });
+
+ const onFieldCopy = useCallback(
+ (event?: KeyboardEvent | null, options?: { duplicate?: boolean }) => {
+ const { duplicate = false } = options ?? {};
+
+ if (lastActiveField) {
+ event?.preventDefault();
+
+ if (!duplicate) {
+ setFieldClipboard(lastActiveField);
+
+ toast({
+ title: 'Copied field',
+ description: 'Copied field to clipboard',
+ });
+
+ return;
+ }
+
+ const newField: TConfigureFieldsFormSchema['fields'][0] = {
+ ...structuredClone(lastActiveField),
+ formId: nanoid(12),
+ id: nanoid(12),
+ signerEmail: selectedRecipient?.email ?? lastActiveField.signerEmail,
+ recipientId: selectedRecipient?.id ?? lastActiveField.recipientId,
+ pageX: lastActiveField.pageX + 3,
+ pageY: lastActiveField.pageY + 3,
+ };
+
+ append(newField);
+ }
+ },
+ [append, lastActiveField, selectedRecipient?.email, selectedRecipient?.id, toast],
+ );
+
+ const onFieldPaste = useCallback(
+ (event: KeyboardEvent) => {
+ if (fieldClipboard) {
+ event.preventDefault();
+
+ const copiedField = structuredClone(fieldClipboard);
+
+ append({
+ ...copiedField,
+ formId: nanoid(12),
+ id: nanoid(12),
+ signerEmail: selectedRecipient?.email ?? copiedField.signerEmail,
+ recipientId: selectedRecipient?.id ?? copiedField.recipientId,
+ pageX: copiedField.pageX + 3,
+ pageY: copiedField.pageY + 3,
+ });
+ }
+ },
+ [append, fieldClipboard, selectedRecipient?.email, selectedRecipient?.id],
+ );
+
+ useHotkeys(['ctrl+c', 'meta+c'], (evt) => onFieldCopy(evt));
+ useHotkeys(['ctrl+v', 'meta+v'], (evt) => onFieldPaste(evt));
+ useHotkeys(['ctrl+d', 'meta+d'], (evt) => onFieldCopy(evt, { duplicate: true }));
+
+ const onMouseMove = useCallback(
+ (event: MouseEvent) => {
+ if (!selectedField) return;
+
+ setIsFieldWithinBounds(
+ isWithinPageBounds(
+ event,
+ PDF_VIEWER_PAGE_SELECTOR,
+ fieldBounds.current.width,
+ fieldBounds.current.height,
+ ),
+ );
+
+ setCoords({
+ x: event.clientX - fieldBounds.current.width / 2,
+ y: event.clientY - fieldBounds.current.height / 2,
+ });
+ },
+ [isWithinPageBounds, selectedField],
+ );
+
+ const onMouseClick = useCallback(
+ (event: MouseEvent) => {
+ if (!selectedField || !selectedRecipient) {
+ return;
+ }
+
+ const $page = getPage(event, PDF_VIEWER_PAGE_SELECTOR);
+
+ if (
+ !$page ||
+ !isWithinPageBounds(
+ event,
+ PDF_VIEWER_PAGE_SELECTOR,
+ fieldBounds.current.width,
+ fieldBounds.current.height,
+ )
+ ) {
+ return;
+ }
+
+ const { top, left, height, width } = getBoundingClientRect($page);
+
+ const pageNumber = parseInt($page.getAttribute('data-page-number') ?? '1', 10);
+
+ // Calculate x and y as a percentage of the page width and height
+ let pageX = ((event.pageX - left) / width) * 100;
+ let pageY = ((event.pageY - top) / height) * 100;
+
+ // Get the bounds as a percentage of the page width and height
+ const fieldPageWidth = (fieldBounds.current.width / width) * 100;
+ const fieldPageHeight = (fieldBounds.current.height / height) * 100;
+
+ // And center it based on the bounds
+ pageX -= fieldPageWidth / 2;
+ pageY -= fieldPageHeight / 2;
+
+ const field = {
+ id: nanoid(12),
+ formId: nanoid(12),
+ type: selectedField,
+ pageNumber,
+ pageX,
+ pageY,
+ pageWidth: fieldPageWidth,
+ pageHeight: fieldPageHeight,
+ recipientId: selectedRecipient.id,
+ signerEmail: selectedRecipient.email,
+ fieldMeta: undefined,
+ };
+
+ append(field);
+
+ // Automatically open advanced settings for field types that need configuration
+ if (ADVANCED_FIELD_TYPES_WITH_OPTIONAL_SETTING.includes(selectedField)) {
+ setCurrentField(field);
+ setShowAdvancedSettings(true);
+ }
+
+ setSelectedField(null);
+ },
+ [append, getPage, isWithinPageBounds, selectedField, selectedRecipient],
+ );
+
+ const onFieldResize = useCallback(
+ (node: HTMLElement, index: number) => {
+ const field = localFields[index];
+
+ const $page = window.document.querySelector<HTMLElement>(
+ `${PDF_VIEWER_PAGE_SELECTOR}[data-page-number="${field.pageNumber}"]`,
+ );
+
+ if (!$page) {
+ return;
+ }
+
+ const {
+ x: pageX,
+ y: pageY,
+ width: pageWidth,
+ height: pageHeight,
+ } = getFieldPosition($page, node);
+
+ update(index, {
+ ...field,
+ pageX,
+ pageY,
+ pageWidth,
+ pageHeight,
+ });
+ },
+ [getFieldPosition, localFields, update],
+ );
+
+ const onFieldMove = useCallback(
+ (node: HTMLElement, index: number) => {
+ const field = localFields[index];
+
+ const $page = window.document.querySelector<HTMLElement>(
+ `${PDF_VIEWER_PAGE_SELECTOR}[data-page-number="${field.pageNumber}"]`,
+ );
+
+ if (!$page) {
+ return;
+ }
+
+ const { x: pageX, y: pageY } = getFieldPosition($page, node);
+
+ update(index, {
+ ...field,
+ pageX,
+ pageY,
+ });
+ },
+ [getFieldPosition, localFields, update],
+ );
+
+ const handleUpdateFieldMeta = useCallback(
+ (formId: string, fieldMeta: TFieldMetaSchema) => {
+ const fieldIndex = localFields.findIndex((field) => field.formId === formId);
+
+ if (fieldIndex !== -1) {
+ const parsedFieldMeta = ZFieldMetaSchema.parse(fieldMeta);
+
+ update(fieldIndex, {
+ ...localFields[fieldIndex],
+ fieldMeta: parsedFieldMeta,
+ });
+ }
+ },
+ [localFields, update],
+ );
+
+ useEffect(() => {
+ if (selectedField) {
+ window.addEventListener('mousemove', onMouseMove);
+ window.addEventListener('mouseup', onMouseClick);
+ }
+
+ return () => {
+ window.removeEventListener('mousemove', onMouseMove);
+ window.removeEventListener('mouseup', onMouseClick);
+ };
+ }, [onMouseClick, onMouseMove, selectedField]);
+
+ useEffect(() => {
+ const observer = new MutationObserver((_mutations) => {
+ const $page = document.querySelector(PDF_VIEWER_PAGE_SELECTOR);
+
+ if (!$page) {
+ return;
+ }
+
+ fieldBounds.current = {
+ height: Math.max(DEFAULT_HEIGHT_PX),
+ width: Math.max(DEFAULT_WIDTH_PX),
+ };
+ });
+
+ observer.observe(document.body, {
+ childList: true,
+ subtree: true,
+ });
+
+ return () => {
+ observer.disconnect();
+ };
+ }, []);
+
+ // Close drawer when a field is selected on mobile
+ useEffect(() => {
+ if (isMobile && selectedField) {
+ setIsDrawerOpen(false);
+ }
+ }, [isMobile, selectedField]);
+
+ return (
+ <>
+ <div className="grid w-full grid-cols-12 gap-4">
+ {/* Desktop sidebar */}
+ {!isMobile && (
+ <div className="order-2 col-span-12 md:order-1 md:col-span-4">
+ <div className="bg-widget border-border sticky top-4 max-h-[calc(100vh-2rem)] rounded-lg border p-4 pb-6">
+ <h2 className="mb-1 text-lg font-medium">
+ <Trans>Configure Fields</Trans>
+ </h2>
+
+ <p className="text-muted-foreground mb-6 text-sm">
+ <Trans>Configure the fields you want to place on the document.</Trans>
+ </p>
+
+ <RecipientSelector
+ selectedRecipient={selectedRecipient}
+ onSelectedRecipientChange={setSelectedRecipient}
+ recipients={recipients}
+ className="w-full"
+ />
+
+ <hr className="my-6" />
+
+ <div className="space-y-2">
+ <FieldSelector
+ selectedField={selectedField}
+ onSelectedFieldChange={setSelectedField}
+ className="w-full"
+ disabled={!selectedRecipient}
+ />
+ </div>
+
+ <div className="mt-6 flex gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ className="flex-1"
+ loading={form.formState.isSubmitting}
+ onClick={() => onBack(form.getValues())}
+ >
+ <Trans>Back</Trans>
+ </Button>
+
+ <Button
+ className="flex-1"
+ type="button"
+ loading={form.formState.isSubmitting}
+ disabled={!form.formState.isValid}
+ onClick={async () => onFormSubmit()}
+ >
+ <Trans>Save</Trans>
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div className={cn('order-1 col-span-12 md:order-2', !isMobile && 'md:col-span-8')}>
+ <div className="relative">
+ {selectedField && (
+ <div
+ className={cn(
+ 'text-muted-foreground dark:text-muted-background pointer-events-none fixed z-50 flex cursor-pointer flex-col items-center justify-center bg-white transition duration-200 [container-type:size]',
+ selectedSignerStyles.default.base,
+ {
+ '-rotate-6 scale-90 opacity-50 dark:bg-black/20': !isFieldWithinBounds,
+ 'dark:text-black/60': isFieldWithinBounds,
+ },
+ selectedField === 'SIGNATURE' && 'font-signature',
+ )}
+ style={{
+ top: coords.y,
+ left: coords.x,
+ height: fieldBounds.current.height,
+ width: fieldBounds.current.width,
+ }}
+ >
+ <span className="text-[clamp(0.425rem,25cqw,0.825rem)]">
+ {_(FRIENDLY_FIELD_TYPE[selectedField])}
+ </span>
+ </div>
+ )}
+
+ <Form {...form}>
+ {documentData && (
+ <div>
+ <PDFViewer documentData={documentData} />
+
+ <ElementVisible target={PDF_VIEWER_PAGE_SELECTOR}>
+ {localFields.map((field, index) => {
+ const recipientIndex = recipients.findIndex(
+ (r) => r.id === field.recipientId,
+ );
+
+ return (
+ <FieldItem
+ key={field.formId}
+ field={field}
+ minHeight={MIN_HEIGHT_PX}
+ minWidth={MIN_WIDTH_PX}
+ defaultHeight={DEFAULT_HEIGHT_PX}
+ defaultWidth={DEFAULT_WIDTH_PX}
+ onResize={(node) => onFieldResize(node, index)}
+ onMove={(node) => onFieldMove(node, index)}
+ onRemove={() => remove(index)}
+ onDuplicate={() => onFieldCopy(null, { duplicate: true })}
+ onFocus={() => setLastActiveField(field)}
+ onBlur={() => setLastActiveField(null)}
+ onAdvancedSettings={() => {
+ setCurrentField(field);
+ setShowAdvancedSettings(true);
+ }}
+ recipientIndex={recipientIndex}
+ active={activeFieldId === field.formId}
+ onFieldActivate={() => setActiveFieldId(field.formId)}
+ onFieldDeactivate={() => setActiveFieldId(null)}
+ disabled={selectedRecipient?.id !== field.recipientId}
+ />
+ );
+ })}
+ </ElementVisible>
+ </div>
+ )}
+ </Form>
+ </div>
+ </div>
+ </div>
+
+ {/* Mobile Floating Action Bar and Drawer */}
+ {isMobile && (
+ <Sheet open={isDrawerOpen} onOpenChange={setIsDrawerOpen}>
+ <SheetTrigger asChild>
+ <div className="bg-widget border-border fixed bottom-6 left-6 right-6 z-50 flex items-center justify-between gap-2 rounded-lg border p-4">
+ <span className="text-lg font-medium">
+ <Trans>Configure Fields</Trans>
+ </span>
+
+ <button
+ type="button"
+ className="border-border text-muted-foreground inline-flex h-10 w-10 items-center justify-center rounded-lg border"
+ >
+ <ChevronsUpDown className="h-6 w-6" />
+ </button>
+ </div>
+ </SheetTrigger>
+
+ <SheetContent
+ position="bottom"
+ size="xl"
+ className="bg-widget h-fit max-h-[80vh] overflow-y-auto rounded-t-xl p-4"
+ >
+ <h2 className="mb-1 text-lg font-medium">
+ <Trans>Configure Fields</Trans>
+ </h2>
+
+ <p className="text-muted-foreground mb-6 text-sm">
+ <Trans>Configure the fields you want to place on the document.</Trans>
+ </p>
+
+ <RecipientSelector
+ selectedRecipient={selectedRecipient}
+ onSelectedRecipientChange={setSelectedRecipient}
+ recipients={recipients}
+ className="w-full"
+ />
+
+ <hr className="my-6" />
+
+ <div className="space-y-2">
+ <FieldSelector
+ selectedField={selectedField}
+ onSelectedFieldChange={(field) => {
+ setSelectedField(field);
+ if (field) {
+ setIsDrawerOpen(false);
+ }
+ }}
+ className="w-full"
+ disabled={!selectedRecipient}
+ />
+ </div>
+
+ <div className="mt-6 flex gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ className="flex-1"
+ loading={form.formState.isSubmitting}
+ onClick={() => onBack(form.getValues())}
+ >
+ <Trans>Back</Trans>
+ </Button>
+
+ <Button
+ className="flex-1"
+ type="button"
+ loading={form.formState.isSubmitting}
+ disabled={!form.formState.isValid}
+ onClick={async () => onFormSubmit()}
+ >
+ <Trans>Save</Trans>
+ </Button>
+ </div>
+ </SheetContent>
+ </Sheet>
+ )}
+
+ <FieldAdvancedSettingsDrawer
+ isOpen={showAdvancedSettings}
+ onOpenChange={setShowAdvancedSettings}
+ currentField={currentField}
+ fields={localFields}
+ onFieldUpdate={handleUpdateFieldMeta}
+ />
+ </>
+ );
+};
diff --git a/apps/remix/app/components/embed/authoring/field-advanced-settings-drawer.tsx b/apps/remix/app/components/embed/authoring/field-advanced-settings-drawer.tsx
new file mode 100644
index 000000000..6646586a7
--- /dev/null
+++ b/apps/remix/app/components/embed/authoring/field-advanced-settings-drawer.tsx
@@ -0,0 +1,83 @@
+import { msg } from '@lingui/core/macro';
+import { useLingui } from '@lingui/react';
+import type { FieldType } from '@prisma/client';
+
+import { type TFieldMetaSchema as FieldMeta } from '@documenso/lib/types/field-meta';
+import { parseMessageDescriptor } from '@documenso/lib/utils/i18n';
+import { FieldAdvancedSettings } from '@documenso/ui/primitives/document-flow/field-item-advanced-settings';
+import { FRIENDLY_FIELD_TYPE } from '@documenso/ui/primitives/document-flow/types';
+import { Sheet, SheetContent, SheetTitle } from '@documenso/ui/primitives/sheet';
+
+export type FieldAdvancedSettingsDrawerProps = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ currentField: {
+ id: string;
+ formId: string;
+ type: FieldType;
+ pageNumber: number;
+ pageX: number;
+ pageY: number;
+ pageWidth: number;
+ pageHeight: number;
+ recipientId: number;
+ signerEmail: string;
+ fieldMeta?: FieldMeta;
+ } | null;
+ fields: Array<{
+ id: string;
+ formId: string;
+ type: FieldType;
+ pageNumber: number;
+ pageX: number;
+ pageY: number;
+ pageWidth: number;
+ pageHeight: number;
+ recipientId: number;
+ signerEmail: string;
+ fieldMeta?: FieldMeta;
+ }>;
+ onFieldUpdate: (formId: string, fieldMeta: FieldMeta) => void;
+};
+
+export const FieldAdvancedSettingsDrawer = ({
+ isOpen,
+ onOpenChange,
+ currentField,
+ fields,
+ onFieldUpdate,
+}: FieldAdvancedSettingsDrawerProps) => {
+ const { _ } = useLingui();
+
+ if (!currentField) {
+ return null;
+ }
+
+ return (
+ <Sheet open={isOpen} onOpenChange={onOpenChange}>
+ <SheetContent position="right" size="lg" className="w-9/12 max-w-sm overflow-y-auto">
+ <SheetTitle className="sr-only">
+ {parseMessageDescriptor(
+ _,
+ msg`Configure ${parseMessageDescriptor(_, FRIENDLY_FIELD_TYPE[currentField.type])} Field`,
+ )}
+ </SheetTitle>
+
+ <FieldAdvancedSettings
+ title={msg`Advanced settings`}
+ description={msg`Configure the ${parseMessageDescriptor(
+ _,
+ FRIENDLY_FIELD_TYPE[currentField.type],
+ )} field`}
+ field={currentField}
+ fields={fields}
+ onAdvancedSettings={() => onOpenChange(false)}
+ onSave={(fieldMeta) => {
+ onFieldUpdate(currentField.formId, fieldMeta);
+ onOpenChange(false);
+ }}
+ />
+ </SheetContent>
+ </Sheet>
+ );
+};
diff --git a/apps/remix/app/components/embed/embed-client-loading.tsx b/apps/remix/app/components/embed/embed-client-loading.tsx
index d67af37a2..0d4c2340b 100644
--- a/apps/remix/app/components/embed/embed-client-loading.tsx
+++ b/apps/remix/app/components/embed/embed-client-loading.tsx
@@ -1,7 +1,11 @@
+import { Loader } from 'lucide-react';
+
export const EmbedClientLoading = () => {
return (
<div className="bg-background fixed left-0 top-0 z-[9999] flex h-full w-full items-center justify-center">
- Loading...
+ <Loader className="mr-2 h-4 w-4 animate-spin" />
+
+ <span>Loading...</span>
</div>
);
};
diff --git a/apps/remix/app/routes/embed+/_layout.tsx b/apps/remix/app/routes/embed+/_v0+/_layout.tsx
similarity index 100%
rename from apps/remix/app/routes/embed+/_layout.tsx
rename to apps/remix/app/routes/embed+/_v0+/_layout.tsx
diff --git a/apps/remix/app/routes/embed+/direct.$url.tsx b/apps/remix/app/routes/embed+/_v0+/direct.$url.tsx
similarity index 100%
rename from apps/remix/app/routes/embed+/direct.$url.tsx
rename to apps/remix/app/routes/embed+/_v0+/direct.$url.tsx
diff --git a/apps/remix/app/routes/embed+/sign.$url.tsx b/apps/remix/app/routes/embed+/_v0+/sign.$url.tsx
similarity index 100%
rename from apps/remix/app/routes/embed+/sign.$url.tsx
rename to apps/remix/app/routes/embed+/_v0+/sign.$url.tsx
diff --git a/apps/remix/app/routes/embed+/v1.authoring+/_layout.tsx b/apps/remix/app/routes/embed+/v1.authoring+/_layout.tsx
new file mode 100644
index 000000000..fb03d91b6
--- /dev/null
+++ b/apps/remix/app/routes/embed+/v1.authoring+/_layout.tsx
@@ -0,0 +1,66 @@
+import { useLayoutEffect, useState } from 'react';
+
+import { Outlet } from 'react-router';
+
+import { TrpcProvider, trpc } from '@documenso/trpc/react';
+
+import { EmbedClientLoading } from '~/components/embed/embed-client-loading';
+import { ZBaseEmbedAuthoringSchema } from '~/types/embed-authoring-base-schema';
+import { injectCss } from '~/utils/css-vars';
+
+export default function AuthoringLayout() {
+ const [token, setToken] = useState('');
+
+ const {
+ mutateAsync: verifyEmbeddingPresignToken,
+ isPending: isVerifyingEmbeddingPresignToken,
+ data: isVerified,
+ } = trpc.embeddingPresign.verifyEmbeddingPresignToken.useMutation();
+
+ useLayoutEffect(() => {
+ try {
+ const hash = window.location.hash.slice(1);
+
+ const result = ZBaseEmbedAuthoringSchema.safeParse(
+ JSON.parse(decodeURIComponent(atob(hash))),
+ );
+
+ if (!result.success) {
+ return;
+ }
+
+ const { token, css, cssVars, darkModeDisabled } = result.data;
+
+ if (darkModeDisabled) {
+ document.documentElement.classList.add('dark-mode-disabled');
+ }
+
+ injectCss({
+ css,
+ cssVars,
+ });
+
+ void verifyEmbeddingPresignToken({ token }).then((result) => {
+ if (result.success) {
+ setToken(token);
+ }
+ });
+ } catch (err) {
+ console.error('Error verifying embedding presign token:', err);
+ }
+ }, []);
+
+ if (isVerifyingEmbeddingPresignToken) {
+ return <EmbedClientLoading />;
+ }
+
+ if (typeof isVerified !== 'undefined' && !isVerified.success) {
+ return <div>Invalid embedding presign token</div>;
+ }
+
+ return (
+ <TrpcProvider headers={{ authorization: `Bearer ${token}` }}>
+ <Outlet />
+ </TrpcProvider>
+ );
+}
diff --git a/apps/remix/app/routes/embed+/v1.authoring+/create-completed.tsx b/apps/remix/app/routes/embed+/v1.authoring+/create-completed.tsx
new file mode 100644
index 000000000..39ded5172
--- /dev/null
+++ b/apps/remix/app/routes/embed+/v1.authoring+/create-completed.tsx
@@ -0,0 +1,53 @@
+import { useEffect } from 'react';
+
+import { Trans } from '@lingui/react/macro';
+import { CheckCircle2 } from 'lucide-react';
+import { useSearchParams } from 'react-router';
+
+export default function EmbeddingAuthoringCompletedPage() {
+ const [searchParams] = useSearchParams();
+
+ // Get templateId and externalId from URL search params
+ const templateId = searchParams.get('templateId');
+ const documentId = searchParams.get('documentId');
+ const externalId = searchParams.get('externalId');
+
+ const id = Number(templateId || documentId);
+ const type = templateId ? 'template' : 'document';
+
+ // Send postMessage to parent window with the details
+ useEffect(() => {
+ if (!id || !window.parent || window.parent === window) {
+ return;
+ }
+
+ window.parent.postMessage(
+ {
+ type: `${type}-created`,
+ [`${type}Id`]: id,
+ externalId,
+ },
+ '*',
+ );
+ }, [id, type, externalId]);
+
+ return (
+ <div className="flex min-h-[100dvh] flex-col items-center justify-center p-6 text-center">
+ <div className="mx-auto w-full max-w-md">
+ <CheckCircle2 className="text-primary mx-auto h-16 w-16" />
+
+ <h1 className="mt-6 text-2xl font-bold">
+ {type === 'template' ? <Trans>Template Created</Trans> : <Trans>Document Created</Trans>}
+ </h1>
+
+ <p className="text-muted-foreground mt-2">
+ {type === 'template' ? (
+ <Trans>Your template has been created successfully</Trans>
+ ) : (
+ <Trans>Your document has been created successfully</Trans>
+ )}
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/remix/app/routes/embed+/v1.authoring+/document.create.tsx b/apps/remix/app/routes/embed+/v1.authoring+/document.create.tsx
new file mode 100644
index 000000000..e80b1558c
--- /dev/null
+++ b/apps/remix/app/routes/embed+/v1.authoring+/document.create.tsx
@@ -0,0 +1,184 @@
+import { useLayoutEffect, useState } from 'react';
+
+import { useLingui } from '@lingui/react';
+import { useNavigate } from 'react-router';
+
+import { DocumentSignatureType } from '@documenso/lib/constants/document';
+import { putPdfFile } from '@documenso/lib/universal/upload/put-file';
+import { trpc } from '@documenso/trpc/react';
+import { Stepper } from '@documenso/ui/primitives/stepper';
+import { useToast } from '@documenso/ui/primitives/use-toast';
+
+import { ConfigureDocumentProvider } from '~/components/embed/authoring/configure-document-context';
+import { ConfigureDocumentView } from '~/components/embed/authoring/configure-document-view';
+import type { TConfigureEmbedFormSchema } from '~/components/embed/authoring/configure-document-view.types';
+import {
+ ConfigureFieldsView,
+ type TConfigureFieldsFormSchema,
+} from '~/components/embed/authoring/configure-fields-view';
+import {
+ type TBaseEmbedAuthoringSchema,
+ ZBaseEmbedAuthoringSchema,
+} from '~/types/embed-authoring-base-schema';
+
+export default function EmbeddingAuthoringDocumentCreatePage() {
+ const { _ } = useLingui();
+
+ const { toast } = useToast();
+ const navigate = useNavigate();
+
+ const [configuration, setConfiguration] = useState<TConfigureEmbedFormSchema | null>(null);
+ const [fields, setFields] = useState<TConfigureFieldsFormSchema | null>(null);
+ const [features, setFeatures] = useState<TBaseEmbedAuthoringSchema['features'] | null>(null);
+ const [externalId, setExternalId] = useState<string | null>(null);
+ const [currentStep, setCurrentStep] = useState(1);
+
+ const { mutateAsync: createEmbeddingDocument } =
+ trpc.embeddingPresign.createEmbeddingDocument.useMutation();
+
+ const handleConfigurePageViewSubmit = (data: TConfigureEmbedFormSchema) => {
+ // Store the configuration data and move to the field placement stage
+ setConfiguration(data);
+ setCurrentStep(2);
+ };
+
+ const handleBackToConfig = (data: TConfigureFieldsFormSchema) => {
+ // Return to the configuration view but keep the data
+ setFields(data);
+ setCurrentStep(1);
+ };
+
+ const handleConfigureFieldsSubmit = async (data: TConfigureFieldsFormSchema) => {
+ try {
+ if (!configuration || !configuration.documentData) {
+ toast({
+ variant: 'destructive',
+ title: _('Error'),
+ description: _('Please configure the document first'),
+ });
+
+ return;
+ }
+
+ const fields = data.fields;
+
+ const documentData = await putPdfFile({
+ arrayBuffer: async () => Promise.resolve(configuration.documentData!.data.buffer),
+ name: configuration.documentData.name,
+ type: configuration.documentData.type,
+ });
+
+ // Use the externalId from the URL fragment if available
+ const documentExternalId = externalId || configuration.meta.externalId;
+
+ const createResult = await createEmbeddingDocument({
+ title: configuration.title,
+ documentDataId: documentData.id,
+ externalId: documentExternalId,
+ meta: {
+ ...configuration.meta,
+ drawSignatureEnabled:
+ configuration.meta.signatureTypes.length === 0 ||
+ configuration.meta.signatureTypes.includes(DocumentSignatureType.DRAW),
+ typedSignatureEnabled:
+ configuration.meta.signatureTypes.length === 0 ||
+ configuration.meta.signatureTypes.includes(DocumentSignatureType.TYPE),
+ uploadSignatureEnabled:
+ configuration.meta.signatureTypes.length === 0 ||
+ configuration.meta.signatureTypes.includes(DocumentSignatureType.UPLOAD),
+ },
+ recipients: configuration.signers.map((signer) => ({
+ name: signer.name,
+ email: signer.email,
+ role: signer.role,
+ fields: fields
+ .filter((field) => field.signerEmail === signer.email)
+ // There's a gnarly discriminated union that makes this hard to satisfy, we're casting for the second
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ .map<any>((f) => ({
+ ...f,
+ pageX: f.pageX,
+ pageY: f.pageY,
+ width: f.pageWidth,
+ height: f.pageHeight,
+ })),
+ })),
+ });
+
+ toast({
+ title: _('Success'),
+ description: _('Document created successfully'),
+ });
+
+ // Send a message to the parent window with the document details
+ if (window.parent !== window) {
+ window.parent.postMessage(
+ {
+ type: 'document-created',
+ documentId: createResult.documentId,
+ externalId: documentExternalId,
+ },
+ '*',
+ );
+ }
+
+ const hash = window.location.hash.slice(1);
+
+ // Navigate to the completion page instead of the document details page
+ await navigate(
+ `/embed/v1/authoring/create-completed?documentId=${createResult.documentId}&externalId=${documentExternalId}#${hash}`,
+ );
+ } catch (err) {
+ console.error('Error creating document:', err);
+
+ toast({
+ variant: 'destructive',
+ title: _('Error'),
+ description: _('Failed to create document'),
+ });
+ }
+ };
+
+ useLayoutEffect(() => {
+ try {
+ const hash = window.location.hash.slice(1);
+
+ const result = ZBaseEmbedAuthoringSchema.safeParse(
+ JSON.parse(decodeURIComponent(atob(hash))),
+ );
+
+ if (!result.success) {
+ return;
+ }
+
+ setFeatures(result.data.features);
+
+ // Extract externalId from the parsed data if available
+ if (result.data.externalId) {
+ setExternalId(result.data.externalId);
+ }
+ } catch (err) {
+ console.error('Error parsing embedding params:', err);
+ }
+ }, []);
+
+ return (
+ <div className="relative mx-auto flex min-h-[100dvh] max-w-screen-lg p-6">
+ <ConfigureDocumentProvider isTemplate={false} features={features ?? {}}>
+ <Stepper currentStep={currentStep} setCurrentStep={setCurrentStep}>
+ <ConfigureDocumentView
+ defaultValues={configuration ?? undefined}
+ onSubmit={handleConfigurePageViewSubmit}
+ />
+
+ <ConfigureFieldsView
+ configData={configuration!}
+ defaultValues={fields ?? undefined}
+ onBack={handleBackToConfig}
+ onSubmit={handleConfigureFieldsSubmit}
+ />
+ </Stepper>
+ </ConfigureDocumentProvider>
+ </div>
+ );
+}
diff --git a/apps/remix/app/routes/embed+/v1.authoring+/template.create.tsx b/apps/remix/app/routes/embed+/v1.authoring+/template.create.tsx
new file mode 100644
index 000000000..252f6b473
--- /dev/null
+++ b/apps/remix/app/routes/embed+/v1.authoring+/template.create.tsx
@@ -0,0 +1,175 @@
+import { useLayoutEffect, useState } from 'react';
+
+import { useLingui } from '@lingui/react';
+import { useNavigate } from 'react-router';
+
+import { putPdfFile } from '@documenso/lib/universal/upload/put-file';
+import { trpc } from '@documenso/trpc/react';
+import { Stepper } from '@documenso/ui/primitives/stepper';
+import { useToast } from '@documenso/ui/primitives/use-toast';
+
+import { ConfigureDocumentProvider } from '~/components/embed/authoring/configure-document-context';
+import { ConfigureDocumentView } from '~/components/embed/authoring/configure-document-view';
+import type { TConfigureEmbedFormSchema } from '~/components/embed/authoring/configure-document-view.types';
+import {
+ ConfigureFieldsView,
+ type TConfigureFieldsFormSchema,
+} from '~/components/embed/authoring/configure-fields-view';
+import {
+ type TBaseEmbedAuthoringSchema,
+ ZBaseEmbedAuthoringSchema,
+} from '~/types/embed-authoring-base-schema';
+
+export default function EmbeddingAuthoringTemplateCreatePage() {
+ const { _ } = useLingui();
+ const { toast } = useToast();
+ const navigate = useNavigate();
+
+ const [configuration, setConfiguration] = useState<TConfigureEmbedFormSchema | null>(null);
+ const [fields, setFields] = useState<TConfigureFieldsFormSchema | null>(null);
+ const [features, setFeatures] = useState<TBaseEmbedAuthoringSchema['features'] | null>(null);
+ const [externalId, setExternalId] = useState<string | null>(null);
+ const [currentStep, setCurrentStep] = useState(1);
+
+ const { mutateAsync: createEmbeddingTemplate } =
+ trpc.embeddingPresign.createEmbeddingTemplate.useMutation();
+
+ const handleConfigurePageViewSubmit = (data: TConfigureEmbedFormSchema) => {
+ // Store the configuration data and move to the field placement stage
+ setConfiguration(data);
+ setCurrentStep(2);
+ };
+
+ const handleBackToConfig = (data: TConfigureFieldsFormSchema) => {
+ // Return to the configuration view but keep the data
+ setFields(data);
+ setCurrentStep(1);
+ };
+
+ const handleConfigureFieldsSubmit = async (data: TConfigureFieldsFormSchema) => {
+ try {
+ console.log('configuration', configuration);
+ console.log('data', data);
+ if (!configuration || !configuration.documentData) {
+ toast({
+ variant: 'destructive',
+ title: _('Error'),
+ description: _('Please configure the template first'),
+ });
+
+ return;
+ }
+
+ const fields = data.fields;
+
+ const documentData = await putPdfFile({
+ arrayBuffer: async () => Promise.resolve(configuration.documentData!.data.buffer),
+ name: configuration.documentData.name,
+ type: configuration.documentData.type,
+ });
+
+ // Use the externalId from the URL fragment if available
+ const metaWithExternalId = {
+ ...configuration.meta,
+ externalId: externalId || configuration.meta.externalId,
+ };
+
+ const createResult = await createEmbeddingTemplate({
+ title: configuration.title,
+ documentDataId: documentData.id,
+ meta: metaWithExternalId,
+ recipients: configuration.signers.map((signer) => ({
+ name: signer.name,
+ email: signer.email,
+ role: signer.role,
+ fields: fields
+ .filter((field) => field.signerEmail === signer.email)
+ // There's a gnarly discriminated union that makes this hard to satisfy, we're casting for the second
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ .map<any>((field) => ({
+ ...field,
+ pageX: field.pageX,
+ pageY: field.pageY,
+ width: field.pageWidth,
+ height: field.pageHeight,
+ })),
+ })),
+ });
+
+ toast({
+ title: _('Success'),
+ description: _('Template created successfully'),
+ });
+
+ // Send a message to the parent window with the template details
+ if (window.parent !== window) {
+ window.parent.postMessage(
+ {
+ type: 'template-created',
+ templateId: createResult.templateId,
+ externalId: metaWithExternalId.externalId,
+ },
+ '*',
+ );
+ }
+
+ const hash = window.location.hash.slice(1);
+
+ // Navigate to the completion page instead of the template details page
+ await navigate(
+ `/embed/v1/authoring/create-completed?templateId=${createResult.templateId}&externalId=${metaWithExternalId.externalId}#${hash}`,
+ );
+ } catch (err) {
+ console.error('Error creating template:', err);
+
+ toast({
+ variant: 'destructive',
+ title: _('Error'),
+ description: _('Failed to create template'),
+ });
+ }
+ };
+
+ useLayoutEffect(() => {
+ try {
+ const hash = window.location.hash.slice(1);
+
+ const result = ZBaseEmbedAuthoringSchema.safeParse(
+ JSON.parse(decodeURIComponent(atob(hash))),
+ );
+
+ if (!result.success) {
+ return;
+ }
+
+ setFeatures(result.data.features);
+
+ // Extract externalId from the parsed data if available
+ if (result.data.externalId) {
+ setExternalId(result.data.externalId);
+ }
+ } catch (err) {
+ console.error('Error parsing embedding params:', err);
+ }
+ }, []);
+
+ return (
+ <div className="relative mx-auto flex min-h-[100dvh] max-w-screen-lg p-6">
+ <ConfigureDocumentProvider isTemplate={true} features={features ?? {}}>
+ <Stepper currentStep={currentStep} setCurrentStep={setCurrentStep}>
+ <ConfigureDocumentView
+ defaultValues={configuration ?? undefined}
+ onSubmit={handleConfigurePageViewSubmit}
+ />
+
+ <ConfigureFieldsView
+ configData={configuration!}
+ defaultValues={fields ?? undefined}
+ onBack={handleBackToConfig}
+ onSubmit={handleConfigureFieldsSubmit}
+ />
+ </Stepper>
+ </ConfigureDocumentProvider>
+ </div>
+ );
+}
diff --git a/apps/remix/app/types/embed-authoring-base-schema.ts b/apps/remix/app/types/embed-authoring-base-schema.ts
new file mode 100644
index 000000000..2d3a50282
--- /dev/null
+++ b/apps/remix/app/types/embed-authoring-base-schema.ts
@@ -0,0 +1,23 @@
+import { z } from 'zod';
+
+import { ZBaseEmbedDataSchema } from './embed-base-schemas';
+
+export const ZBaseEmbedAuthoringSchema = z
+ .object({
+ token: z.string(),
+ externalId: z.string().optional(),
+ features: z
+ .object({
+ allowConfigureSignatureTypes: z.boolean().optional(),
+ allowConfigureLanguage: z.boolean().optional(),
+ allowConfigureDateFormat: z.boolean().optional(),
+ allowConfigureTimezone: z.boolean().optional(),
+ allowConfigureRedirectUrl: z.boolean().optional(),
+ allowConfigureCommunication: z.boolean().optional(),
+ })
+ .optional()
+ .default({}),
+ })
+ .and(ZBaseEmbedDataSchema);
+
+export type TBaseEmbedAuthoringSchema = z.infer<typeof ZBaseEmbedAuthoringSchema>;
diff --git a/apps/remix/vite.config.ts b/apps/remix/vite.config.ts
index 990423bd0..b411bd395 100644
--- a/apps/remix/vite.config.ts
+++ b/apps/remix/vite.config.ts
@@ -2,6 +2,7 @@ import { lingui } from '@lingui/vite-plugin';
import { reactRouter } from '@react-router/dev/vite';
import autoprefixer from 'autoprefixer';
import serverAdapter from 'hono-react-router-adapter/vite';
+import path from 'node:path';
import tailwindcss from 'tailwindcss';
import { defineConfig } from 'vite';
import macrosPlugin from 'vite-plugin-babel-macros';
@@ -44,9 +45,15 @@ export default defineConfig({
resolve: {
alias: {
https: 'node:https',
- '.prisma/client/default': '../../node_modules/.prisma/client/default.js',
- '.prisma/client/index-browser': '../../node_modules/.prisma/client/index-browser.js',
- canvas: './app/types/empty-module.ts',
+ '.prisma/client/default': path.resolve(
+ __dirname,
+ '../../node_modules/.prisma/client/default.js',
+ ),
+ '.prisma/client/index-browser': path.resolve(
+ __dirname,
+ '../../node_modules/.prisma/client/index-browser.js',
+ ),
+ canvas: path.resolve(__dirname, './app/types/empty-module.ts'),
},
},
/**
diff --git a/package-lock.json b/package-lock.json
index be14fb162..f5ee31a8c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -41560,6 +41560,7 @@
"@vvo/tzdb": "^6.117.0",
"csv-parse": "^5.6.0",
"inngest": "^3.19.13",
+ "jose": "^6.0.0",
"kysely": "0.26.3",
"luxon": "^3.4.0",
"micro": "^10.0.1",
@@ -41582,6 +41583,15 @@
"@types/pg": "^8.11.4"
}
},
+ "packages/lib/node_modules/jose": {
+ "version": "6.0.10",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.0.10.tgz",
+ "integrity": "sha512-skIAxZqcMkOrSwjJvplIPYrlXGpxTPnro2/QWTDCxAdWQrSTV5/KqspMWmi5WAx5+ULswASJiZ0a+1B/Lxt9cw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"packages/prettier-config": {
"name": "@documenso/prettier-config",
"version": "0.0.0",
diff --git a/package.json b/package.json
index 5b7c76443..46265aa37 100644
--- a/package.json
+++ b/package.json
@@ -18,7 +18,7 @@
"dx": "npm i && npm run dx:up && npm run prisma:migrate-dev && npm run prisma:seed",
"dx:up": "docker compose -f docker/development/compose.yml up -d",
"dx:down": "docker compose -f docker/development/compose.yml down",
- "ci": "turbo run test:e2e",
+ "ci": "turbo run build --filter=@documenso/remix && turbo run test:e2e",
"prisma:generate": "npm run with:env -- npm run prisma:generate -w @documenso/prisma",
"prisma:migrate-dev": "npm run with:env -- npm run prisma:migrate-dev -w @documenso/prisma",
"prisma:migrate-deploy": "npm run with:env -- npm run prisma:migrate-deploy -w @documenso/prisma",
@@ -80,4 +80,4 @@
"trigger.dev": {
"endpointId": "documenso-app"
}
-}
+}
\ No newline at end of file
diff --git a/packages/app-tests/e2e/api/v2/embedding-presign.spec.ts b/packages/app-tests/e2e/api/v2/embedding-presign.spec.ts
new file mode 100644
index 000000000..35a94f6f1
--- /dev/null
+++ b/packages/app-tests/e2e/api/v2/embedding-presign.spec.ts
@@ -0,0 +1,203 @@
+import { expect, test } from '@playwright/test';
+
+import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
+import { createApiToken } from '@documenso/lib/server-only/public-api/create-api-token';
+import { seedUser } from '@documenso/prisma/seed/users';
+
+test.describe('Embedding Presign API', () => {
+ test('createEmbeddingPresignToken: should create a token with default expiration', async ({
+ request,
+ }) => {
+ const user = await seedUser();
+
+ const { token } = await createApiToken({
+ userId: user.id,
+ tokenName: 'test',
+ expiresIn: null,
+ });
+
+ const response = await request.post(
+ `${NEXT_PUBLIC_WEBAPP_URL()}/api/v2-beta/embedding/create-presign-token`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ data: {
+ apiToken: token,
+ },
+ },
+ );
+
+ const responseData = await response.json();
+
+ console.log(responseData);
+
+ expect(response.ok()).toBeTruthy();
+ expect(response.status()).toBe(200);
+
+ expect(responseData.token).toBeDefined();
+ expect(responseData.expiresAt).toBeDefined();
+ expect(responseData.expiresIn).toBe(3600); // Default 1 hour in seconds
+ });
+
+ test('createEmbeddingPresignToken: should create a token with custom expiration', async ({
+ request,
+ }) => {
+ const user = await seedUser();
+
+ const { token } = await createApiToken({
+ userId: user.id,
+ tokenName: 'test',
+ expiresIn: null,
+ });
+
+ const response = await request.post(
+ `${NEXT_PUBLIC_WEBAPP_URL()}/api/v2-beta/embedding/create-presign-token`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ data: {
+ apiToken: token,
+ expiresIn: 120, // 2 hours
+ },
+ },
+ );
+
+ const responseData = await response.json();
+
+ console.log(responseData);
+
+ expect(response.ok()).toBeTruthy();
+ expect(response.status()).toBe(200);
+
+ expect(responseData.token).toBeDefined();
+ expect(responseData.expiresAt).toBeDefined();
+ expect(responseData.expiresIn).toBe(7200); // 2 hours in seconds
+ });
+
+ test('createEmbeddingPresignToken: should create a token with immediate expiration in dev mode', async ({
+ request,
+ }) => {
+ const user = await seedUser();
+
+ const { token } = await createApiToken({
+ userId: user.id,
+ tokenName: 'test',
+ expiresIn: null,
+ });
+
+ const response = await request.post(
+ `${NEXT_PUBLIC_WEBAPP_URL()}/api/v2-beta/embedding/create-presign-token`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ data: {
+ apiToken: token,
+ expiresIn: 0, // Immediate expiration
+ },
+ },
+ );
+
+ expect(response.ok()).toBeTruthy();
+ expect(response.status()).toBe(200);
+
+ const responseData = await response.json();
+
+ console.log(responseData);
+
+ expect(responseData.token).toBeDefined();
+ expect(responseData.expiresAt).toBeDefined();
+ expect(responseData.expiresIn).toBe(0); // 0 seconds
+ });
+
+ test('verifyEmbeddingPresignToken: should verify a valid token', async ({ request }) => {
+ const user = await seedUser();
+
+ const { token } = await createApiToken({
+ userId: user.id,
+ tokenName: 'test',
+ expiresIn: null,
+ });
+
+ // First create a token
+ const createResponse = await request.post(
+ `${NEXT_PUBLIC_WEBAPP_URL()}/api/v2-beta/embedding/create-presign-token`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ data: {
+ apiToken: token,
+ },
+ },
+ );
+
+ expect(createResponse.ok()).toBeTruthy();
+ const createResponseData = await createResponse.json();
+
+ console.log('Create response:', createResponseData);
+
+ const presignToken = createResponseData.token;
+
+ // Then verify it
+ const verifyResponse = await request.post(
+ `${NEXT_PUBLIC_WEBAPP_URL()}/api/v2-beta/embedding/verify-presign-token`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ data: {
+ token: presignToken,
+ },
+ },
+ );
+
+ expect(verifyResponse.ok()).toBeTruthy();
+ expect(verifyResponse.status()).toBe(200);
+
+ const verifyResponseData = await verifyResponse.json();
+
+ console.log('Verify response:', verifyResponseData);
+
+ expect(verifyResponseData.success).toBe(true);
+ });
+
+ test('verifyEmbeddingPresignToken: should reject an invalid token', async ({ request }) => {
+ const user = await seedUser();
+
+ const { token } = await createApiToken({
+ userId: user.id,
+ tokenName: 'test',
+ expiresIn: null,
+ });
+
+ const response = await request.post(
+ `${NEXT_PUBLIC_WEBAPP_URL()}/api/v2-beta/embedding/verify-presign-token`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ data: {
+ token: 'invalid-token',
+ },
+ },
+ );
+
+ const responseData = await response.json();
+
+ console.log('Invalid token response:', responseData);
+
+ expect(response.ok()).toBeTruthy();
+ expect(response.status()).toBe(200);
+
+ expect(responseData.success).toBe(false);
+ });
+});
diff --git a/packages/app-tests/package.json b/packages/app-tests/package.json
index 1807dac8f..516a8f844 100644
--- a/packages/app-tests/package.json
+++ b/packages/app-tests/package.json
@@ -7,7 +7,7 @@
"scripts": {
"test:dev": "NODE_OPTIONS=--experimental-require-module playwright test",
"test-ui:dev": "NODE_OPTIONS=--experimental-require-module playwright test --ui",
- "test:e2e": "NODE_OPTIONS=--experimental-require-module start-server-and-test \"npm run start -w @documenso/remix\" http://localhost:3000 \"playwright test $E2E_TEST_PATH\""
+ "test:e2e": "NODE_OPTIONS=--experimental-require-module NODE_ENV=test start-server-and-test \"npm run start -w @documenso/remix\" http://localhost:3000 \"playwright test $E2E_TEST_PATH\""
},
"keywords": [],
"author": "",
diff --git a/packages/ee/server-only/util/is-document-platform.ts b/packages/ee/server-only/util/is-document-platform.ts
index 6a0dbbb61..e7d7b47af 100644
--- a/packages/ee/server-only/util/is-document-platform.ts
+++ b/packages/ee/server-only/util/is-document-platform.ts
@@ -6,7 +6,7 @@ import { prisma } from '@documenso/prisma';
import { getPlatformPlanPriceIds } from '../stripe/get-platform-plan-prices';
-export type IsDocumentPlatformOptions = Pick<Document, 'id' | 'userId' | 'teamId'>;
+export type IsDocumentPlatformOptions = Pick<Document, 'userId' | 'teamId'>;
/**
* Whether the user is platform, or has permission to use platform features on
diff --git a/packages/lib/package.json b/packages/lib/package.json
index 8afe56c85..af94ca9af 100644
--- a/packages/lib/package.json
+++ b/packages/lib/package.json
@@ -28,6 +28,7 @@
"@lingui/core": "^5.2.0",
"@lingui/macro": "^5.2.0",
"@lingui/react": "^5.2.0",
+ "jose": "^6.0.0",
"@noble/ciphers": "0.4.0",
"@noble/hashes": "1.3.2",
"@node-rs/bcrypt": "^1.10.0",
@@ -58,4 +59,4 @@
"@types/luxon": "^3.3.1",
"@types/pg": "^8.11.4"
}
-}
+}
\ No newline at end of file
diff --git a/packages/lib/server-only/embedding-presign/create-embedding-presign-token.ts b/packages/lib/server-only/embedding-presign/create-embedding-presign-token.ts
new file mode 100644
index 000000000..ecdf95d24
--- /dev/null
+++ b/packages/lib/server-only/embedding-presign/create-embedding-presign-token.ts
@@ -0,0 +1,63 @@
+import { SignJWT } from 'jose';
+import { DateTime } from 'luxon';
+
+import { AppError, AppErrorCode } from '../../errors/app-error';
+import { env } from '../../utils/env';
+import { getApiTokenByToken } from '../public-api/get-api-token-by-token';
+
+export type CreateEmbeddingPresignTokenOptions = {
+ apiToken: string;
+ /**
+ * Number of hours until the token expires
+ * In development mode, can be set to 0 to create a token that expires immediately (for testing)
+ */
+ expiresIn?: number;
+};
+
+export const createEmbeddingPresignToken = async ({
+ apiToken,
+ expiresIn,
+}: CreateEmbeddingPresignTokenOptions) => {
+ try {
+ // Validate the API token
+ const validatedToken = await getApiTokenByToken({ token: apiToken });
+
+ const now = DateTime.now();
+
+ // In development mode, allow setting expiresIn to 0 for testing
+ // In production, enforce a minimum expiration time
+ const isDevelopment = env('NODE_ENV') !== 'production';
+ console.log('isDevelopment', isDevelopment);
+ const minExpirationMinutes = isDevelopment ? 0 : 5;
+
+ // Ensure expiresIn is at least the minimum allowed value
+ const effectiveExpiresIn =
+ expiresIn !== undefined && expiresIn >= minExpirationMinutes ? expiresIn : 60; // Default to 1 hour if not specified or below minimum
+
+ const expiresAt = now.plus({ minutes: effectiveExpiresIn });
+
+ const secret = new TextEncoder().encode(validatedToken.token);
+
+ const token = await new SignJWT({
+ aud: String(validatedToken.teamId ?? validatedToken.userId),
+ sub: String(validatedToken.id),
+ })
+ .setProtectedHeader({ alg: 'HS256' })
+ .setIssuedAt(now.toJSDate())
+ .setExpirationTime(expiresAt.toJSDate())
+ .sign(secret);
+
+ return {
+ token,
+ expiresAt: expiresAt.toJSDate(),
+ expiresIn: Math.floor(expiresAt.diff(now).toMillis() / 1000),
+ };
+ } catch (error) {
+ if (error instanceof AppError) {
+ throw error;
+ }
+ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
+ message: 'Failed to create presign token',
+ });
+ }
+};
diff --git a/packages/lib/server-only/embedding-presign/verify-embedding-presign-token.ts b/packages/lib/server-only/embedding-presign/verify-embedding-presign-token.ts
new file mode 100644
index 000000000..ff9907d5b
--- /dev/null
+++ b/packages/lib/server-only/embedding-presign/verify-embedding-presign-token.ts
@@ -0,0 +1,115 @@
+import type { JWTPayload } from 'jose';
+import { decodeJwt, jwtVerify } from 'jose';
+
+import { prisma } from '@documenso/prisma';
+
+import { AppError, AppErrorCode } from '../../errors/app-error';
+
+export type VerifyEmbeddingPresignTokenOptions = {
+ token: string;
+};
+
+export const verifyEmbeddingPresignToken = async ({
+ token,
+}: VerifyEmbeddingPresignTokenOptions) => {
+ // First decode the JWT to get the claims without verification
+ let decodedToken: JWTPayload;
+
+ try {
+ decodedToken = decodeJwt<JWTPayload>(token);
+ } catch (error) {
+ console.error('Error decoding JWT token:', error);
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid presign token format',
+ });
+ }
+
+ // Validate the required claims
+ if (!decodedToken.sub || typeof decodedToken.sub !== 'string') {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid presign token format: missing or invalid subject claim',
+ });
+ }
+
+ if (!decodedToken.aud || typeof decodedToken.aud !== 'string') {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid presign token format: missing or invalid audience claim',
+ });
+ }
+
+ // Convert string IDs to numbers
+ const tokenId = Number(decodedToken.sub);
+ const audienceId = Number(decodedToken.aud);
+
+ if (Number.isNaN(tokenId) || !Number.isInteger(tokenId)) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid token ID format in subject claim',
+ });
+ }
+
+ if (Number.isNaN(audienceId) || !Number.isInteger(audienceId)) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid user ID format in audience claim',
+ });
+ }
+
+ // Get the API token to use as the verification secret
+ const apiToken = await prisma.apiToken.findFirst({
+ where: {
+ id: tokenId,
+ },
+ });
+
+ if (!apiToken) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid presign token: API token not found',
+ });
+ }
+
+ // This should never happen but we need to narrow types
+ if (!apiToken.userId) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid presign token: API token does not have a user attached',
+ });
+ }
+
+ const userId = apiToken.userId;
+
+ if (audienceId !== apiToken.teamId && audienceId !== apiToken.userId) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid presign token: API token does not match audience',
+ });
+ }
+
+ // Now verify the token with the actual secret
+ const secret = new TextEncoder().encode(apiToken.token);
+
+ try {
+ await jwtVerify(token, secret);
+ } catch (error) {
+ // Check if the token has expired
+ if (error instanceof Error && error.name === 'JWTExpired') {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Presign token has expired',
+ });
+ }
+
+ // Handle invalid signature
+ if (error instanceof Error && error.name === 'JWSInvalid') {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid presign token signature',
+ });
+ }
+
+ // Log and rethrow other errors
+ console.error('Error verifying JWT token:', error);
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Failed to verify presign token',
+ });
+ }
+
+ return {
+ ...apiToken,
+ userId,
+ };
+};
diff --git a/packages/trpc/server/embedding-router/_router.ts b/packages/trpc/server/embedding-router/_router.ts
new file mode 100644
index 000000000..ca65e0418
--- /dev/null
+++ b/packages/trpc/server/embedding-router/_router.ts
@@ -0,0 +1,14 @@
+import { router } from '../trpc';
+import { createEmbeddingDocumentRoute } from './create-embedding-document';
+import { createEmbeddingPresignTokenRoute } from './create-embedding-presign-token';
+import { createEmbeddingTemplateRoute } from './create-embedding-template';
+import { getEmbeddingDocumentRoute } from './get-embedding-document';
+import { verifyEmbeddingPresignTokenRoute } from './verify-embedding-presign-token';
+
+export const embeddingPresignRouter = router({
+ createEmbeddingPresignToken: createEmbeddingPresignTokenRoute,
+ verifyEmbeddingPresignToken: verifyEmbeddingPresignTokenRoute,
+ createEmbeddingDocument: createEmbeddingDocumentRoute,
+ createEmbeddingTemplate: createEmbeddingTemplateRoute,
+ getEmbeddingDocument: getEmbeddingDocumentRoute,
+});
diff --git a/packages/trpc/server/embedding-router/create-embedding-document.ts b/packages/trpc/server/embedding-router/create-embedding-document.ts
new file mode 100644
index 000000000..e3271c1b4
--- /dev/null
+++ b/packages/trpc/server/embedding-router/create-embedding-document.ts
@@ -0,0 +1,63 @@
+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
+import { createDocumentV2 } from '@documenso/lib/server-only/document/create-document-v2';
+import { verifyEmbeddingPresignToken } from '@documenso/lib/server-only/embedding-presign/verify-embedding-presign-token';
+
+import { procedure } from '../trpc';
+import {
+ ZCreateEmbeddingDocumentRequestSchema,
+ ZCreateEmbeddingDocumentResponseSchema,
+} from './create-embedding-document.types';
+
+export const createEmbeddingDocumentRoute = procedure
+ .input(ZCreateEmbeddingDocumentRequestSchema)
+ .output(ZCreateEmbeddingDocumentResponseSchema)
+ .mutation(async ({ input, ctx: { req, metadata } }) => {
+ try {
+ const authorizationHeader = req.headers.get('authorization');
+
+ const [presignToken] = (authorizationHeader || '')
+ .split('Bearer ')
+ .filter((s) => s.length > 0);
+
+ if (!presignToken) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'No presign token provided',
+ });
+ }
+
+ const apiToken = await verifyEmbeddingPresignToken({ token: presignToken });
+
+ const { title, documentDataId, externalId, recipients, meta } = input;
+
+ const document = await createDocumentV2({
+ data: {
+ title,
+ externalId,
+ recipients,
+ },
+ meta,
+ documentDataId,
+ userId: apiToken.userId,
+ teamId: apiToken.teamId ?? undefined,
+ requestMetadata: metadata,
+ });
+
+ if (!document.id) {
+ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
+ message: 'Failed to create document: missing document ID',
+ });
+ }
+
+ return {
+ documentId: document.id,
+ };
+ } catch (error) {
+ if (error instanceof AppError) {
+ throw error;
+ }
+
+ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
+ message: 'Failed to create document',
+ });
+ }
+ });
diff --git a/packages/trpc/server/embedding-router/create-embedding-document.types.ts b/packages/trpc/server/embedding-router/create-embedding-document.types.ts
new file mode 100644
index 000000000..662136c17
--- /dev/null
+++ b/packages/trpc/server/embedding-router/create-embedding-document.types.ts
@@ -0,0 +1,83 @@
+import { z } from 'zod';
+
+import { ZDocumentEmailSettingsSchema } from '@documenso/lib/types/document-email';
+import {
+ ZFieldHeightSchema,
+ ZFieldPageNumberSchema,
+ ZFieldPageXSchema,
+ ZFieldPageYSchema,
+ ZFieldWidthSchema,
+} from '@documenso/lib/types/field';
+import { ZFieldAndMetaSchema } from '@documenso/lib/types/field-meta';
+import { DocumentSigningOrder } from '@documenso/prisma/generated/types';
+
+import {
+ ZDocumentExternalIdSchema,
+ ZDocumentMetaDateFormatSchema,
+ ZDocumentMetaDistributionMethodSchema,
+ ZDocumentMetaDrawSignatureEnabledSchema,
+ ZDocumentMetaLanguageSchema,
+ ZDocumentMetaMessageSchema,
+ ZDocumentMetaRedirectUrlSchema,
+ ZDocumentMetaSubjectSchema,
+ ZDocumentMetaTimezoneSchema,
+ ZDocumentMetaTypedSignatureEnabledSchema,
+ ZDocumentMetaUploadSignatureEnabledSchema,
+ ZDocumentTitleSchema,
+} from '../document-router/schema';
+import { ZCreateRecipientSchema } from '../recipient-router/schema';
+
+export const ZCreateEmbeddingDocumentRequestSchema = z.object({
+ title: ZDocumentTitleSchema,
+ documentDataId: z.string(),
+ externalId: ZDocumentExternalIdSchema.optional(),
+ recipients: z
+ .array(
+ ZCreateRecipientSchema.extend({
+ fields: ZFieldAndMetaSchema.and(
+ z.object({
+ pageNumber: ZFieldPageNumberSchema,
+ pageX: ZFieldPageXSchema,
+ pageY: ZFieldPageYSchema,
+ width: ZFieldWidthSchema,
+ height: ZFieldHeightSchema,
+ }),
+ )
+ .array()
+ .optional(),
+ }),
+ )
+ .refine(
+ (recipients) => {
+ const emails = recipients.map((recipient) => recipient.email);
+
+ return new Set(emails).size === emails.length;
+ },
+ { message: 'Recipients must have unique emails' },
+ )
+ .optional(),
+ meta: z
+ .object({
+ subject: ZDocumentMetaSubjectSchema.optional(),
+ message: ZDocumentMetaMessageSchema.optional(),
+ timezone: ZDocumentMetaTimezoneSchema.optional(),
+ dateFormat: ZDocumentMetaDateFormatSchema.optional(),
+ distributionMethod: ZDocumentMetaDistributionMethodSchema.optional(),
+ signingOrder: z.nativeEnum(DocumentSigningOrder).optional(),
+ redirectUrl: ZDocumentMetaRedirectUrlSchema.optional(),
+ language: ZDocumentMetaLanguageSchema.optional(),
+ typedSignatureEnabled: ZDocumentMetaTypedSignatureEnabledSchema.optional(),
+ drawSignatureEnabled: ZDocumentMetaDrawSignatureEnabledSchema.optional(),
+ uploadSignatureEnabled: ZDocumentMetaUploadSignatureEnabledSchema.optional(),
+ emailSettings: ZDocumentEmailSettingsSchema.optional(),
+ })
+ .optional(),
+});
+
+export const ZCreateEmbeddingDocumentResponseSchema = z.object({
+ documentId: z.number(),
+});
+
+export type TCreateEmbeddingDocumentRequestSchema = z.infer<
+ typeof ZCreateEmbeddingDocumentRequestSchema
+>;
diff --git a/packages/trpc/server/embedding-router/create-embedding-presign-token.ts b/packages/trpc/server/embedding-router/create-embedding-presign-token.ts
new file mode 100644
index 000000000..819581286
--- /dev/null
+++ b/packages/trpc/server/embedding-router/create-embedding-presign-token.ts
@@ -0,0 +1,73 @@
+import { isCommunityPlan } from '@documenso/ee/server-only/util/is-community-plan';
+import { isUserEnterprise } from '@documenso/ee/server-only/util/is-document-enterprise';
+import { isDocumentPlatform } from '@documenso/ee/server-only/util/is-document-platform';
+import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
+import { createEmbeddingPresignToken } from '@documenso/lib/server-only/embedding-presign/create-embedding-presign-token';
+import { getApiTokenByToken } from '@documenso/lib/server-only/public-api/get-api-token-by-token';
+
+import { procedure } from '../trpc';
+import {
+ ZCreateEmbeddingPresignTokenRequestSchema,
+ ZCreateEmbeddingPresignTokenResponseSchema,
+ createEmbeddingPresignTokenMeta,
+} from './create-embedding-presign-token.types';
+
+/**
+ * Route to create embedding presign tokens.
+ */
+export const createEmbeddingPresignTokenRoute = procedure
+ .meta(createEmbeddingPresignTokenMeta)
+ .input(ZCreateEmbeddingPresignTokenRequestSchema)
+ .output(ZCreateEmbeddingPresignTokenResponseSchema)
+ .mutation(async ({ input, ctx: { req } }) => {
+ try {
+ const authorizationHeader = req.headers.get('authorization');
+ const [apiToken] = (authorizationHeader || '').split('Bearer ').filter((s) => s.length > 0);
+
+ if (!apiToken) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'No API token provided',
+ });
+ }
+
+ const { expiresIn } = input;
+
+ if (IS_BILLING_ENABLED()) {
+ const token = await getApiTokenByToken({ token: apiToken });
+
+ if (!token.userId) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Invalid API token',
+ });
+ }
+
+ const [hasCommunityPlan, hasPlatformPlan, hasEnterprisePlan] = await Promise.all([
+ isCommunityPlan({ userId: token.userId, teamId: token.teamId ?? undefined }),
+ isDocumentPlatform({ userId: token.userId, teamId: token.teamId }),
+ isUserEnterprise({ userId: token.userId, teamId: token.teamId ?? undefined }),
+ ]);
+
+ if (!hasCommunityPlan && !hasPlatformPlan && !hasEnterprisePlan) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'You do not have permission to create embedding presign tokens',
+ });
+ }
+ }
+
+ const presignToken = await createEmbeddingPresignToken({
+ apiToken,
+ expiresIn,
+ });
+
+ return { ...presignToken };
+ } catch (error) {
+ if (error instanceof AppError) {
+ throw error;
+ }
+
+ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
+ message: 'Failed to create embedding presign token',
+ });
+ }
+ });
diff --git a/packages/trpc/server/embedding-router/create-embedding-presign-token.types.ts b/packages/trpc/server/embedding-router/create-embedding-presign-token.types.ts
new file mode 100644
index 000000000..a50e3942f
--- /dev/null
+++ b/packages/trpc/server/embedding-router/create-embedding-presign-token.types.ts
@@ -0,0 +1,38 @@
+import { z } from 'zod';
+
+import type { TrpcRouteMeta } from '../trpc';
+
+export const createEmbeddingPresignTokenMeta: TrpcRouteMeta = {
+ openapi: {
+ method: 'POST',
+ path: '/embedding/create-presign-token',
+ summary: 'Create embedding presign token',
+ description:
+ 'Creates a presign token for embedding operations with configurable expiration time',
+ tags: ['Embedding'],
+ },
+};
+
+export const ZCreateEmbeddingPresignTokenRequestSchema = z.object({
+ expiresIn: z
+ .number()
+ .min(0)
+ .max(10080)
+ .optional()
+ .default(60)
+ .describe('Expiration time in minutes (default: 60, max: 10,080)'),
+});
+
+export const ZCreateEmbeddingPresignTokenResponseSchema = z.object({
+ token: z.string(),
+ expiresAt: z.date(),
+ expiresIn: z.number().describe('Expiration time in seconds'),
+});
+
+export type TCreateEmbeddingPresignTokenRequestSchema = z.infer<
+ typeof ZCreateEmbeddingPresignTokenRequestSchema
+>;
+
+export type TCreateEmbeddingPresignTokenResponseSchema = z.infer<
+ typeof ZCreateEmbeddingPresignTokenResponseSchema
+>;
diff --git a/packages/trpc/server/embedding-router/create-embedding-template.ts b/packages/trpc/server/embedding-router/create-embedding-template.ts
new file mode 100644
index 000000000..b238cd167
--- /dev/null
+++ b/packages/trpc/server/embedding-router/create-embedding-template.ts
@@ -0,0 +1,112 @@
+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
+import { verifyEmbeddingPresignToken } from '@documenso/lib/server-only/embedding-presign/verify-embedding-presign-token';
+import { createTemplate } from '@documenso/lib/server-only/template/create-template';
+import { prisma } from '@documenso/prisma';
+
+import { procedure } from '../trpc';
+import {
+ ZCreateEmbeddingTemplateRequestSchema,
+ ZCreateEmbeddingTemplateResponseSchema,
+} from './create-embedding-template.types';
+
+export const createEmbeddingTemplateRoute = procedure
+ .input(ZCreateEmbeddingTemplateRequestSchema)
+ .output(ZCreateEmbeddingTemplateResponseSchema)
+ .mutation(async ({ input, ctx: { req } }) => {
+ try {
+ const authorizationHeader = req.headers.get('authorization');
+
+ const [presignToken] = (authorizationHeader || '')
+ .split('Bearer ')
+ .filter((s) => s.length > 0);
+
+ if (!presignToken) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'No presign token provided',
+ });
+ }
+
+ const apiToken = await verifyEmbeddingPresignToken({ token: presignToken });
+
+ const { title, documentDataId, recipients, meta } = input;
+
+ // First create the template
+ const template = await createTemplate({
+ userId: apiToken.userId,
+ title,
+ templateDocumentDataId: documentDataId,
+ teamId: apiToken.teamId ?? undefined,
+ });
+
+ await Promise.all(
+ recipients.map(async (recipient) => {
+ const createdRecipient = await prisma.recipient.create({
+ data: {
+ templateId: template.id,
+ email: recipient.email,
+ name: recipient.name || '',
+ role: recipient.role || 'SIGNER',
+ token: `template-${template.id}-${recipient.email}`,
+ signingOrder: recipient.signingOrder,
+ },
+ });
+
+ const fields = recipient.fields ?? [];
+
+ const createdFields = await prisma.field.createMany({
+ data: fields.map((field) => ({
+ recipientId: createdRecipient.id,
+ type: field.type,
+ page: field.pageNumber,
+ positionX: field.pageX,
+ positionY: field.pageY,
+ width: field.width,
+ height: field.height,
+ customText: '',
+ inserted: false,
+ templateId: template.id,
+ })),
+ });
+
+ return {
+ ...createdRecipient,
+ fields: createdFields,
+ };
+ }),
+ );
+
+ // Update the template meta if needed
+ if (meta) {
+ await prisma.templateMeta.upsert({
+ where: {
+ templateId: template.id,
+ },
+ create: {
+ templateId: template.id,
+ ...meta,
+ },
+ update: {
+ ...meta,
+ },
+ });
+ }
+
+ if (!template.id) {
+ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
+ message: 'Failed to create template: missing template ID',
+ });
+ }
+
+ return {
+ templateId: template.id,
+ };
+ } catch (error) {
+ if (error instanceof AppError) {
+ throw error;
+ }
+
+ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
+ message: 'Failed to create template',
+ });
+ }
+ });
diff --git a/packages/trpc/server/embedding-router/create-embedding-template.types.ts b/packages/trpc/server/embedding-router/create-embedding-template.types.ts
new file mode 100644
index 000000000..90ab1edea
--- /dev/null
+++ b/packages/trpc/server/embedding-router/create-embedding-template.types.ts
@@ -0,0 +1,74 @@
+import { DocumentSigningOrder, FieldType, RecipientRole } from '@prisma/client';
+import { z } from 'zod';
+
+import { ZDocumentEmailSettingsSchema } from '@documenso/lib/types/document-email';
+import {
+ ZFieldHeightSchema,
+ ZFieldPageNumberSchema,
+ ZFieldPageXSchema,
+ ZFieldPageYSchema,
+ ZFieldWidthSchema,
+} from '@documenso/lib/types/field';
+import { ZFieldMetaSchema } from '@documenso/lib/types/field-meta';
+
+import {
+ ZDocumentMetaDateFormatSchema,
+ ZDocumentMetaDistributionMethodSchema,
+ ZDocumentMetaDrawSignatureEnabledSchema,
+ ZDocumentMetaLanguageSchema,
+ ZDocumentMetaMessageSchema,
+ ZDocumentMetaRedirectUrlSchema,
+ ZDocumentMetaSubjectSchema,
+ ZDocumentMetaTimezoneSchema,
+ ZDocumentMetaTypedSignatureEnabledSchema,
+ ZDocumentMetaUploadSignatureEnabledSchema,
+ ZDocumentTitleSchema,
+} from '../document-router/schema';
+
+const ZFieldSchema = z.object({
+ type: z.nativeEnum(FieldType),
+ pageNumber: ZFieldPageNumberSchema,
+ pageX: ZFieldPageXSchema,
+ pageY: ZFieldPageYSchema,
+ width: ZFieldWidthSchema,
+ height: ZFieldHeightSchema,
+ fieldMeta: ZFieldMetaSchema.optional(),
+});
+
+export const ZCreateEmbeddingTemplateRequestSchema = z.object({
+ title: ZDocumentTitleSchema,
+ documentDataId: z.string(),
+ recipients: z.array(
+ z.object({
+ email: z.string().email(),
+ name: z.string().optional(),
+ role: z.nativeEnum(RecipientRole).optional(),
+ signingOrder: z.number().optional(),
+ fields: z.array(ZFieldSchema).optional(),
+ }),
+ ),
+ meta: z
+ .object({
+ subject: ZDocumentMetaSubjectSchema.optional(),
+ message: ZDocumentMetaMessageSchema.optional(),
+ timezone: ZDocumentMetaTimezoneSchema.optional(),
+ dateFormat: ZDocumentMetaDateFormatSchema.optional(),
+ distributionMethod: ZDocumentMetaDistributionMethodSchema.optional(),
+ signingOrder: z.nativeEnum(DocumentSigningOrder).optional(),
+ redirectUrl: ZDocumentMetaRedirectUrlSchema.optional(),
+ language: ZDocumentMetaLanguageSchema.optional(),
+ typedSignatureEnabled: ZDocumentMetaTypedSignatureEnabledSchema.optional(),
+ drawSignatureEnabled: ZDocumentMetaDrawSignatureEnabledSchema.optional(),
+ uploadSignatureEnabled: ZDocumentMetaUploadSignatureEnabledSchema.optional(),
+ emailSettings: ZDocumentEmailSettingsSchema.optional(),
+ })
+ .optional(),
+});
+
+export const ZCreateEmbeddingTemplateResponseSchema = z.object({
+ templateId: z.number(),
+});
+
+export type TCreateEmbeddingTemplateRequestSchema = z.infer<
+ typeof ZCreateEmbeddingTemplateRequestSchema
+>;
diff --git a/packages/trpc/server/embedding-router/get-embedding-document.ts b/packages/trpc/server/embedding-router/get-embedding-document.ts
new file mode 100644
index 000000000..cfa3b7ba2
--- /dev/null
+++ b/packages/trpc/server/embedding-router/get-embedding-document.ts
@@ -0,0 +1,63 @@
+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
+import { verifyEmbeddingPresignToken } from '@documenso/lib/server-only/embedding-presign/verify-embedding-presign-token';
+import { prisma } from '@documenso/prisma';
+
+import { procedure } from '../trpc';
+import {
+ ZGetEmbeddingDocumentRequestSchema,
+ ZGetEmbeddingDocumentResponseSchema,
+} from './get-embedding-document.types';
+
+export const getEmbeddingDocumentRoute = procedure
+ .input(ZGetEmbeddingDocumentRequestSchema)
+ .output(ZGetEmbeddingDocumentResponseSchema)
+ .query(async ({ input, ctx: { req } }) => {
+ try {
+ const authorizationHeader = req.headers.get('authorization');
+
+ const [presignToken] = (authorizationHeader || '')
+ .split('Bearer ')
+ .filter((s) => s.length > 0);
+
+ if (!presignToken) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'No presign token provided',
+ });
+ }
+
+ const apiToken = await verifyEmbeddingPresignToken({ token: presignToken });
+
+ const { documentId } = input;
+
+ const document = await prisma.document.findFirst({
+ where: {
+ id: documentId,
+ userId: apiToken.userId,
+ ...(apiToken.teamId ? { teamId: apiToken.teamId } : {}),
+ },
+ include: {
+ documentData: true,
+ recipients: true,
+ fields: true,
+ },
+ });
+
+ if (!document) {
+ throw new AppError(AppErrorCode.NOT_FOUND, {
+ message: 'Document not found',
+ });
+ }
+
+ return {
+ document,
+ };
+ } catch (error) {
+ if (error instanceof AppError) {
+ throw error;
+ }
+
+ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
+ message: 'Failed to get document',
+ });
+ }
+ });
diff --git a/packages/trpc/server/embedding-router/get-embedding-document.types.ts b/packages/trpc/server/embedding-router/get-embedding-document.types.ts
new file mode 100644
index 000000000..58f7d4a2c
--- /dev/null
+++ b/packages/trpc/server/embedding-router/get-embedding-document.types.ts
@@ -0,0 +1,34 @@
+import { DocumentDataType, type Field, type Recipient } from '@prisma/client';
+import { z } from 'zod';
+
+export const ZGetEmbeddingDocumentRequestSchema = z.object({
+ documentId: z.number(),
+});
+
+export const ZGetEmbeddingDocumentResponseSchema = z.object({
+ document: z
+ .object({
+ id: z.number(),
+ title: z.string(),
+ status: z.string(),
+ documentDataId: z.string(),
+ userId: z.number(),
+ teamId: z.number().nullable(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ documentData: z.object({
+ id: z.string(),
+ type: z.nativeEnum(DocumentDataType),
+ data: z.string(),
+ initialData: z.string(),
+ }),
+ recipients: z.array(z.custom<Recipient>()),
+ fields: z.array(z.custom<Field>()),
+ })
+ .nullable(),
+});
+
+export type TGetEmbeddingDocumentRequestSchema = z.infer<typeof ZGetEmbeddingDocumentRequestSchema>;
+export type TGetEmbeddingDocumentResponseSchema = z.infer<
+ typeof ZGetEmbeddingDocumentResponseSchema
+>;
diff --git a/packages/trpc/server/embedding-router/verify-embedding-presign-token.ts b/packages/trpc/server/embedding-router/verify-embedding-presign-token.ts
new file mode 100644
index 000000000..7f171347f
--- /dev/null
+++ b/packages/trpc/server/embedding-router/verify-embedding-presign-token.ts
@@ -0,0 +1,36 @@
+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
+import { verifyEmbeddingPresignToken } from '@documenso/lib/server-only/embedding-presign/verify-embedding-presign-token';
+
+import { procedure } from '../trpc';
+import {
+ ZVerifyEmbeddingPresignTokenRequestSchema,
+ ZVerifyEmbeddingPresignTokenResponseSchema,
+ verifyEmbeddingPresignTokenMeta,
+} from './verify-embedding-presign-token.types';
+
+/**
+ * Public route.
+ */
+export const verifyEmbeddingPresignTokenRoute = procedure
+ .meta(verifyEmbeddingPresignTokenMeta)
+ .input(ZVerifyEmbeddingPresignTokenRequestSchema)
+ .output(ZVerifyEmbeddingPresignTokenResponseSchema)
+ .mutation(async ({ input }) => {
+ try {
+ const { token } = input;
+
+ const apiToken = await verifyEmbeddingPresignToken({
+ token,
+ }).catch(() => null);
+
+ return { success: !!apiToken };
+ } catch (error) {
+ if (error instanceof AppError) {
+ throw error;
+ }
+
+ throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
+ message: 'Failed to verify embedding presign token',
+ });
+ }
+ });
diff --git a/packages/trpc/server/embedding-router/verify-embedding-presign-token.types.ts b/packages/trpc/server/embedding-router/verify-embedding-presign-token.types.ts
new file mode 100644
index 000000000..1474ff755
--- /dev/null
+++ b/packages/trpc/server/embedding-router/verify-embedding-presign-token.types.ts
@@ -0,0 +1,33 @@
+import { z } from 'zod';
+
+import type { TrpcRouteMeta } from '../trpc';
+
+export const verifyEmbeddingPresignTokenMeta: TrpcRouteMeta = {
+ openapi: {
+ method: 'POST',
+ path: '/embedding/verify-presign-token',
+ summary: 'Verify embedding presign token',
+ description:
+ 'Verifies a presign token for embedding operations and returns the associated API token',
+ tags: ['Embedding'],
+ },
+};
+
+export const ZVerifyEmbeddingPresignTokenRequestSchema = z.object({
+ token: z
+ .string()
+ .min(1, { message: 'Token is required' })
+ .describe('The presign token to verify'),
+});
+
+export const ZVerifyEmbeddingPresignTokenResponseSchema = z.object({
+ success: z.boolean(),
+});
+
+export type TVerifyEmbeddingPresignTokenRequestSchema = z.infer<
+ typeof ZVerifyEmbeddingPresignTokenRequestSchema
+>;
+
+export type TVerifyEmbeddingPresignTokenResponseSchema = z.infer<
+ typeof ZVerifyEmbeddingPresignTokenResponseSchema
+>;
diff --git a/packages/trpc/server/router.ts b/packages/trpc/server/router.ts
index 9f6a78946..8096bd121 100644
--- a/packages/trpc/server/router.ts
+++ b/packages/trpc/server/router.ts
@@ -2,6 +2,7 @@ import { adminRouter } from './admin-router/router';
import { apiTokenRouter } from './api-token-router/router';
import { authRouter } from './auth-router/router';
import { documentRouter } from './document-router/router';
+import { embeddingPresignRouter } from './embedding-router/_router';
import { fieldRouter } from './field-router/router';
import { profileRouter } from './profile-router/router';
import { recipientRouter } from './recipient-router/router';
@@ -23,6 +24,7 @@ export const appRouter = router({
team: teamRouter,
template: templateRouter,
webhook: webhookRouter,
+ embeddingPresign: embeddingPresignRouter,
});
export type AppRouter = typeof appRouter;
diff --git a/packages/ui/primitives/document-flow/add-fields.tsx b/packages/ui/primitives/document-flow/add-fields.tsx
index 2209bfc71..377bc0812 100644
--- a/packages/ui/primitives/document-flow/add-fields.tsx
+++ b/packages/ui/primitives/document-flow/add-fields.tsx
@@ -8,14 +8,11 @@ import type { Field, Recipient } from '@prisma/client';
import { FieldType, RecipientRole, SendStatus } from '@prisma/client';
import {
CalendarDays,
- Check,
CheckSquare,
ChevronDown,
- ChevronsUpDown,
Contact,
Disc,
Hash,
- Info,
Mail,
Type,
User,
@@ -27,7 +24,6 @@ import { prop, sortBy } from 'remeda';
import { getBoundingClientRect } from '@documenso/lib/client-only/get-bounding-client-rect';
import { useDocumentElement } from '@documenso/lib/client-only/hooks/use-document-element';
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
-import { RECIPIENT_ROLES_DESCRIPTION } from '@documenso/lib/constants/recipient-roles';
import {
type TFieldMetaSchema as FieldMeta,
ZFieldMetaSchema,
@@ -42,16 +38,13 @@ import {
} from '@documenso/lib/utils/recipients';
import { FieldToolTip } from '../../components/field/field-tooltip';
-import { getSignerColorStyles, useSignerColors } from '../../lib/signer-colors';
+import { useSignerColors } from '../../lib/signer-colors';
import { cn } from '../../lib/utils';
import { Alert, AlertDescription } from '../alert';
-import { Button } from '../button';
import { Card, CardContent } from '../card';
-import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from '../command';
import { Form } from '../form/form';
-import { Popover, PopoverContent, PopoverTrigger } from '../popover';
+import { RecipientSelector } from '../recipient-selector';
import { useStep } from '../stepper';
-import { Tooltip, TooltipContent, TooltipTrigger } from '../tooltip';
import { useToast } from '../use-toast';
import type { TAddFieldsFormSchema } from './add-fields.types';
import {
@@ -663,123 +656,12 @@ export const AddFieldsFormPartial = ({
})}
{!hideRecipients && (
- <Popover open={showRecipientsSelector} onOpenChange={setShowRecipientsSelector}>
- <PopoverTrigger asChild>
- <Button
- type="button"
- variant="outline"
- role="combobox"
- className={cn(
- 'bg-background text-muted-foreground hover:text-foreground mb-12 mt-2 justify-between font-normal',
- selectedSignerStyles.default.base,
- )}
- >
- {selectedSigner?.email && (
- <span className="flex-1 truncate text-left">
- {selectedSigner?.name} ({selectedSigner?.email})
- </span>
- )}
-
- {!selectedSigner?.email && (
- <span className="flex-1 truncate text-left">{selectedSigner?.email}</span>
- )}
-
- <ChevronsUpDown className="ml-2 h-4 w-4" />
- </Button>
- </PopoverTrigger>
-
- <PopoverContent className="p-0" align="start">
- <Command value={selectedSigner?.email}>
- <CommandInput />
-
- <CommandEmpty>
- <span className="text-muted-foreground inline-block px-4">
- <Trans>No recipient matching this description was found.</Trans>
- </span>
- </CommandEmpty>
-
- {recipientsByRoleToDisplay.map(([role, roleRecipients], roleIndex) => (
- <CommandGroup key={roleIndex}>
- <div className="text-muted-foreground mb-1 ml-2 mt-2 text-xs font-medium">
- {_(RECIPIENT_ROLES_DESCRIPTION[role].roleNamePlural)}
- </div>
-
- {roleRecipients.length === 0 && (
- <div
- key={`${role}-empty`}
- className="text-muted-foreground/80 px-4 pb-4 pt-2.5 text-center text-xs"
- >
- <Trans>No recipients with this role</Trans>
- </div>
- )}
-
- {roleRecipients.map((recipient) => (
- <CommandItem
- key={recipient.id}
- className={cn(
- 'px-2 last:mb-1 [&:not(:first-child)]:mt-1',
- getSignerColorStyles(
- Math.max(
- recipients.findIndex((r) => r.id === recipient.id),
- 0,
- ),
- ).default.comboxBoxItem,
- {
- 'text-muted-foreground': recipient.sendStatus === SendStatus.SENT,
- },
- )}
- onSelect={() => {
- setSelectedSigner(recipient);
- setShowRecipientsSelector(false);
- }}
- >
- <span
- className={cn('text-foreground/70 truncate', {
- 'text-foreground/80': recipient === selectedSigner,
- })}
- >
- {recipient.name && (
- <span title={`${recipient.name} (${recipient.email})`}>
- {recipient.name} ({recipient.email})
- </span>
- )}
-
- {!recipient.name && (
- <span title={recipient.email}>{recipient.email}</span>
- )}
- </span>
-
- <div className="ml-auto flex items-center justify-center">
- {recipient.sendStatus !== SendStatus.SENT ? (
- <Check
- aria-hidden={recipient !== selectedSigner}
- className={cn('h-4 w-4 flex-shrink-0', {
- 'opacity-0': recipient !== selectedSigner,
- 'opacity-100': recipient === selectedSigner,
- })}
- />
- ) : (
- <Tooltip>
- <TooltipTrigger>
- <Info className="ml-2 h-4 w-4" />
- </TooltipTrigger>
-
- <TooltipContent className="text-muted-foreground max-w-xs">
- <Trans>
- This document has already been sent to this recipient. You
- can no longer edit this recipient.
- </Trans>
- </TooltipContent>
- </Tooltip>
- )}
- </div>
- </CommandItem>
- ))}
- </CommandGroup>
- ))}
- </Command>
- </PopoverContent>
- </Popover>
+ <RecipientSelector
+ selectedRecipient={selectedSigner}
+ onSelectedRecipientChange={setSelectedSigner}
+ recipients={recipients}
+ className="mb-12 mt-2"
+ />
)}
<Form {...form}>
diff --git a/packages/ui/primitives/field-selector.tsx b/packages/ui/primitives/field-selector.tsx
new file mode 100644
index 000000000..ba7c1f673
--- /dev/null
+++ b/packages/ui/primitives/field-selector.tsx
@@ -0,0 +1,128 @@
+import { FieldType } from '@prisma/client';
+import {
+ CalendarDays,
+ CheckSquare,
+ ChevronDown,
+ Contact,
+ Disc,
+ Hash,
+ Mail,
+ Type,
+ User,
+} from 'lucide-react';
+
+import { cn } from '../lib/utils';
+import { Card, CardContent } from './card';
+
+export interface FieldSelectorProps {
+ className?: string;
+ selectedField: FieldType | null;
+ onSelectedFieldChange: (fieldType: FieldType) => void;
+ disabled?: boolean;
+}
+
+export const FieldSelector = ({
+ className,
+ selectedField,
+ onSelectedFieldChange,
+ disabled = false,
+}: FieldSelectorProps) => {
+ const fieldTypes = [
+ {
+ type: FieldType.SIGNATURE,
+ label: 'Signature',
+ icon: null,
+ },
+ {
+ type: FieldType.INITIALS,
+ label: 'Initials',
+ icon: Contact,
+ },
+ {
+ type: FieldType.EMAIL,
+ label: 'Email',
+ icon: Mail,
+ },
+ {
+ type: FieldType.NAME,
+ label: 'Name',
+ icon: User,
+ },
+ {
+ type: FieldType.DATE,
+ label: 'Date',
+ icon: CalendarDays,
+ },
+ {
+ type: FieldType.TEXT,
+ label: 'Text',
+ icon: Type,
+ },
+ {
+ type: FieldType.NUMBER,
+ label: 'Number',
+ icon: Hash,
+ },
+ {
+ type: FieldType.RADIO,
+ label: 'Radio',
+ icon: Disc,
+ },
+ {
+ type: FieldType.CHECKBOX,
+ label: 'Checkbox',
+ icon: CheckSquare,
+ },
+ {
+ type: FieldType.DROPDOWN,
+ label: 'Dropdown',
+ icon: ChevronDown,
+ },
+ ];
+
+ return (
+ <div className="grid grid-cols-2 gap-2">
+ {fieldTypes.map((field) => {
+ const Icon = field.icon;
+
+ return (
+ <button
+ key={field.type}
+ type="button"
+ className="group w-full"
+ onPointerDown={() => onSelectedFieldChange(field.type)}
+ disabled={disabled}
+ data-selected={selectedField === field.type ? true : undefined}
+ >
+ <Card
+ className={cn(
+ 'flex w-full cursor-pointer items-center justify-center group-disabled:opacity-50',
+ {
+ 'border-primary': selectedField === field.type,
+ },
+ )}
+ >
+ <CardContent className="relative flex items-center justify-center gap-x-2 px-6 py-4">
+ {Icon && <Icon className="text-muted-foreground h-4 w-4" />}
+ <span
+ className={cn(
+ 'text-muted-foreground group-data-[selected]:text-foreground text-sm',
+ field.type === FieldType.SIGNATURE && 'invisible',
+ )}
+ >
+ {field.label}
+ </span>
+
+ {field.type === FieldType.SIGNATURE && (
+ <div className="text-muted-foreground font-signature absolute inset-0 flex items-center justify-center text-lg">
+ Signature
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </button>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/packages/ui/primitives/recipient-selector.tsx b/packages/ui/primitives/recipient-selector.tsx
new file mode 100644
index 000000000..7e3d16865
--- /dev/null
+++ b/packages/ui/primitives/recipient-selector.tsx
@@ -0,0 +1,195 @@
+import { useCallback, useState } from 'react';
+
+import { useLingui } from '@lingui/react';
+import { Trans } from '@lingui/react/macro';
+import type { Recipient } from '@prisma/client';
+import { RecipientRole, SendStatus } from '@prisma/client';
+import { Check, ChevronsUpDown, Info } from 'lucide-react';
+import { sortBy } from 'remeda';
+
+import { RECIPIENT_ROLES_DESCRIPTION } from '@documenso/lib/constants/recipient-roles';
+
+import { getSignerColorStyles } from '../lib/signer-colors';
+import { cn } from '../lib/utils';
+import { Button } from './button';
+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from './command';
+import { Popover, PopoverContent, PopoverTrigger } from './popover';
+import { Tooltip, TooltipContent, TooltipTrigger } from './tooltip';
+
+export interface RecipientSelectorProps {
+ className?: string;
+ selectedRecipient: Recipient | null;
+ onSelectedRecipientChange: (recipient: Recipient) => void;
+ recipients: Recipient[];
+}
+
+export const RecipientSelector = ({
+ className,
+ selectedRecipient,
+ onSelectedRecipientChange,
+ recipients,
+}: RecipientSelectorProps) => {
+ const { _ } = useLingui();
+ const [showRecipientsSelector, setShowRecipientsSelector] = useState(false);
+
+ const recipientsByRole = useCallback(() => {
+ const recipientsByRole: Record<RecipientRole, Recipient[]> = {
+ CC: [],
+ VIEWER: [],
+ SIGNER: [],
+ APPROVER: [],
+ ASSISTANT: [],
+ };
+
+ recipients.forEach((recipient) => {
+ recipientsByRole[recipient.role].push(recipient);
+ });
+
+ return recipientsByRole;
+ }, [recipients]);
+
+ const recipientsByRoleToDisplay = useCallback(() => {
+ return Object.entries(recipientsByRole())
+ .filter(
+ ([role]) =>
+ role !== RecipientRole.CC &&
+ role !== RecipientRole.VIEWER &&
+ role !== RecipientRole.ASSISTANT,
+ )
+ .map(
+ ([role, roleRecipients]) =>
+ [
+ role,
+ sortBy(
+ roleRecipients,
+ [(r) => r.signingOrder || Number.MAX_SAFE_INTEGER, 'asc'],
+ [(r) => r.id, 'asc'],
+ ),
+ ] as [RecipientRole, Recipient[]],
+ );
+ }, [recipientsByRole]);
+
+ return (
+ <Popover open={showRecipientsSelector} onOpenChange={setShowRecipientsSelector}>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ role="combobox"
+ className={cn(
+ 'bg-background text-muted-foreground hover:text-foreground justify-between font-normal',
+ getSignerColorStyles(
+ Math.max(
+ recipients.findIndex((r) => r.id === selectedRecipient?.id),
+ 0,
+ ),
+ ).default.base,
+ className,
+ )}
+ >
+ {selectedRecipient?.email && (
+ <span className="flex-1 truncate text-left">
+ {selectedRecipient?.name} ({selectedRecipient?.email})
+ </span>
+ )}
+
+ {!selectedRecipient?.email && (
+ <span className="flex-1 truncate text-left">{selectedRecipient?.email}</span>
+ )}
+
+ <ChevronsUpDown className="ml-2 h-4 w-4" />
+ </Button>
+ </PopoverTrigger>
+
+ <PopoverContent className="p-0" align="start">
+ <Command value={selectedRecipient?.email}>
+ <CommandInput />
+
+ <CommandEmpty>
+ <span className="text-muted-foreground inline-block px-4">
+ <Trans>No recipient matching this description was found.</Trans>
+ </span>
+ </CommandEmpty>
+
+ {recipientsByRoleToDisplay().map(([role, roleRecipients], roleIndex) => (
+ <CommandGroup key={roleIndex}>
+ <div className="text-muted-foreground mb-1 ml-2 mt-2 text-xs font-medium">
+ {_(RECIPIENT_ROLES_DESCRIPTION[role].roleNamePlural)}
+ </div>
+
+ {roleRecipients.length === 0 && (
+ <div
+ key={`${role}-empty`}
+ className="text-muted-foreground/80 px-4 pb-4 pt-2.5 text-center text-xs"
+ >
+ <Trans>No recipients with this role</Trans>
+ </div>
+ )}
+
+ {roleRecipients.map((recipient) => (
+ <CommandItem
+ key={recipient.id}
+ className={cn(
+ 'px-2 last:mb-1 [&:not(:first-child)]:mt-1',
+ getSignerColorStyles(
+ Math.max(
+ recipients.findIndex((r) => r.id === recipient.id),
+ 0,
+ ),
+ ).default.comboxBoxItem,
+ {
+ 'text-muted-foreground': recipient.sendStatus === SendStatus.SENT,
+ },
+ )}
+ onSelect={() => {
+ onSelectedRecipientChange(recipient);
+ setShowRecipientsSelector(false);
+ }}
+ >
+ <span
+ className={cn('text-foreground/70 truncate', {
+ 'text-foreground/80': recipient === selectedRecipient,
+ })}
+ >
+ {recipient.name && (
+ <span title={`${recipient.name} (${recipient.email})`}>
+ {recipient.name} ({recipient.email})
+ </span>
+ )}
+
+ {!recipient.name && <span title={recipient.email}>{recipient.email}</span>}
+ </span>
+
+ <div className="ml-auto flex items-center justify-center">
+ {recipient.sendStatus !== SendStatus.SENT ? (
+ <Check
+ aria-hidden={recipient !== selectedRecipient}
+ className={cn('h-4 w-4 flex-shrink-0', {
+ 'opacity-0': recipient !== selectedRecipient,
+ 'opacity-100': recipient === selectedRecipient,
+ })}
+ />
+ ) : (
+ <Tooltip>
+ <TooltipTrigger>
+ <Info className="ml-2 h-4 w-4" />
+ </TooltipTrigger>
+
+ <TooltipContent className="text-muted-foreground max-w-xs">
+ <Trans>
+ This document has already been sent to this recipient. You can no longer
+ edit this recipient.
+ </Trans>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ ))}
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+};