'use client'; import { useCallback, useEffect, useRef, useState } from 'react'; import { Caveat } from 'next/font/google'; import { useRouter } from 'next/navigation'; import { Check, ChevronsUpDown, Info } from 'lucide-react'; import { nanoid } from 'nanoid'; import { useFieldArray, useForm } from 'react-hook-form'; import { Document, Field, FieldType, Recipient, SendStatus } from '@documenso/prisma/client'; import { cn } from '@documenso/ui/lib/utils'; import { Button } from '@documenso/ui/primitives/button'; import { Card, CardContent } from '@documenso/ui/primitives/card'; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, } from '@documenso/ui/primitives/command'; import { Popover, PopoverContent, PopoverTrigger } from '@documenso/ui/primitives/popover'; import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip'; import { useToast } from '@documenso/ui/primitives/use-toast'; import { PDF_VIEWER_PAGE_SELECTOR } from '~/components/(dashboard)/pdf-viewer/types'; import { getBoundingClientRect } from '~/helpers/getBoundingClientRect'; import { addFields } from './add-fields.action'; import { TAddFieldsFormSchema } from './add-fields.types'; import { EditDocumentFormContainer, EditDocumentFormContainerActions, EditDocumentFormContainerContent, EditDocumentFormContainerFooter, EditDocumentFormContainerStep, } from './container'; import { FieldItem } from './field-item'; import { FRIENDLY_FIELD_TYPE } from './types'; const fontCaveat = Caveat({ weight: ['500'], subsets: ['latin'], display: 'swap', variable: '--font-caveat', }); const DEFAULT_HEIGHT_PERCENT = 5; const DEFAULT_WIDTH_PERCENT = 15; const MIN_HEIGHT_PX = 60; const MIN_WIDTH_PX = 200; export type AddFieldsFormProps = { recipients: Recipient[]; fields: Field[]; document: Document; onContinue?: () => void; onGoBack?: () => void; }; export const AddFieldsFormPartial = ({ recipients, fields, document, onContinue, onGoBack, }: AddFieldsFormProps) => { const { toast } = useToast(); const router = useRouter(); const { control, handleSubmit, formState: { isSubmitting }, } = useForm({ defaultValues: { fields: fields.map((field) => ({ nativeId: field.id, formId: `${field.id}-${field.documentId}`, pageNumber: field.page, type: field.type, pageX: Number(field.positionX), pageY: Number(field.positionY), pageWidth: Number(field.width), pageHeight: Number(field.height), signerEmail: recipients.find((recipient) => recipient.id === field.recipientId)?.email ?? '', })), }, }); const { append, remove, update, fields: localFields, } = useFieldArray({ control, name: 'fields', }); const [selectedField, setSelectedField] = useState(null); const [selectedSigner, setSelectedSigner] = useState(null); const hasSelectedSignerBeenSent = selectedSigner?.sendStatus === SendStatus.SENT; const [visible, setVisible] = useState(false); const [coords, setCoords] = useState({ x: 0, y: 0, }); const fieldBounds = useRef({ height: 0, width: 0, }); /** * Given a mouse event, find the nearest pdf page element. */ const getPage = (event: MouseEvent) => { if (!(event.target instanceof HTMLElement)) { return null; } const target = event.target; const $page = target.closest(PDF_VIEWER_PAGE_SELECTOR) ?? target.querySelector(PDF_VIEWER_PAGE_SELECTOR); if (!$page) { return null; } return $page; }; /** * Provided a page and a field, calculate the position of the field * as a percentage of the page width and height. */ const getFieldPosition = (page: HTMLElement, field: HTMLElement) => { const { top: pageTop, left: pageLeft, height: pageHeight, width: pageWidth, } = getBoundingClientRect(page); const { top: fieldTop, left: fieldLeft, height: fieldHeight, width: fieldWidth, } = getBoundingClientRect(field); return { x: ((fieldLeft - pageLeft) / pageWidth) * 100, y: ((fieldTop - pageTop) / pageHeight) * 100, width: (fieldWidth / pageWidth) * 100, height: (fieldHeight / pageHeight) * 100, }; }; /** * Given a mouse event, determine if the mouse is within the bounds of the * nearest pdf page element. */ const isWithinPageBounds = useCallback((event: MouseEvent) => { const $page = getPage(event); if (!$page) { return false; } const { top, left, height, width } = $page.getBoundingClientRect(); if (event.clientY > top + height || event.clientY < top) { return false; } if (event.clientX > left + width || event.clientX < left) { return false; } return true; }, []); const onMouseMove = useCallback( (event: MouseEvent) => { if (!isWithinPageBounds(event)) { setVisible(false); return; } setVisible(true); setCoords({ x: event.clientX - fieldBounds.current.width / 2, y: event.clientY - fieldBounds.current.height / 2, }); }, [isWithinPageBounds], ); const onMouseClick = useCallback( (event: MouseEvent) => { if (!selectedField || !selectedSigner) { return; } const $page = getPage(event); if (!$page || !isWithinPageBounds(event)) { 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; append({ formId: nanoid(12), type: selectedField, pageNumber, pageX, pageY, pageWidth: fieldPageWidth, pageHeight: fieldPageHeight, signerEmail: selectedSigner.email, }); setVisible(false); setSelectedField(null); }, [append, isWithinPageBounds, selectedField, selectedSigner], ); const onFieldResize = useCallback( (node: HTMLElement, index: number) => { const field = localFields[index]; const $page = window.document.querySelector( `${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, }); }, [localFields, update], ); const onFieldMove = useCallback( (node: HTMLElement, index: number) => { const field = localFields[index]; const $page = window.document.querySelector( `${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, }); }, [localFields, update], ); const onFormSubmit = handleSubmit(async (data: TAddFieldsFormSchema) => { try { // Custom invocation server action await addFields({ documentId: document.id, fields: data.fields, }); router.refresh(); onContinue?.(); } catch (err) { console.error(err); toast({ title: 'Error', description: 'An error occurred while adding signers.', variant: 'destructive', }); } }); useEffect(() => { if (selectedField) { window.addEventListener('mousemove', onMouseMove); window.addEventListener('click', onMouseClick); } return () => { window.removeEventListener('mousemove', onMouseMove); window.removeEventListener('click', onMouseClick); }; }, [onMouseClick, onMouseMove, selectedField]); useEffect(() => { const $page = window.document.querySelector(PDF_VIEWER_PAGE_SELECTOR); if (!$page) { return; } const { height, width } = $page.getBoundingClientRect(); fieldBounds.current = { height: Math.max(height * (DEFAULT_HEIGHT_PERCENT / 100), MIN_HEIGHT_PX), width: Math.max(width * (DEFAULT_WIDTH_PERCENT / 100), MIN_WIDTH_PX), }; }, []); useEffect(() => { setSelectedSigner(recipients.find((r) => r.sendStatus !== SendStatus.SENT) ?? recipients[0]); }, [recipients]); return (
{selectedField && visible && ( {FRIENDLY_FIELD_TYPE[selectedField]} )} {localFields.map((field, index) => ( onFieldResize(options, index)} onMove={(options) => onFieldMove(options, index)} onRemove={() => remove(index)} /> ))} {recipients.map((recipient, index) => ( setSelectedSigner(recipient)} > {recipient.sendStatus !== SendStatus.SENT ? ( ) : ( This document has already been sent to this recipient. You can no longer edit this recipient. )} {recipient.name && ( {recipient.name} ({recipient.email}) )} {!recipient.name && ( {recipient.email} )} ))}
onFormSubmit()} onGoBackClick={onGoBack} />
); };