The Open Source DocuSign Alternative.
TypeScript digital-signaturedocument-signingdocusign-alternativee-signatureesignesignaturenext-authnextjsopen-sourcepades-standardpdfpdf-signpdf-signaturepostgresqlprismaself-hostedsigningtypescript
fix: improve text field signing ux (#3504)
David Nguyen86a0ff2da8d6
diff --git a/apps/remix/app/components/dialogs/sign-field-text-dialog.tsx b/apps/remix/app/components/dialogs/sign-field-text-dialog.tsxindex d651282ed..c16f86dac 100644--- a/apps/remix/app/components/dialogs/sign-field-text-dialog.tsx+++ b/apps/remix/app/components/dialogs/sign-field-text-dialog.tsx@@ -12,89 +12,173 @@ import {import { Form, FormControl, FormField, FormItem, FormMessage } from '@documenso/ui/primitives/form/form';import { Textarea } from '@documenso/ui/primitives/textarea';import { zodResolver } from '@hookform/resolvers/zod';-import { msg } from '@lingui/core/macro';+import { msg, plural } from '@lingui/core/macro';import { Plural, Trans, useLingui } from '@lingui/react/macro';import { createCallable } from 'react-call';import { useForm } from 'react-hook-form';import { z } from 'zod';-const ZSignFieldTextFormSchema = z.object({- text: z.string().min(1, { message: msg`Text is required`.id }),-});+const createSignFieldTextFormSchema = ({+ isInserted,+ characterLimit,+}: {+ isInserted: boolean;+ characterLimit?: number;+}) =>+ z.object({+ text: z.string().superRefine((text, ctx) => {+ // Inserted text can be cleared, which removes it from the field.+ if (!isInserted && text.trim().length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: msg`Text is required`.id,+ });-type TSignFieldTextFormSchema = z.infer<typeof ZSignFieldTextFormSchema>;+ return;+ }++ if (characterLimit !== undefined && text.length > characterLimit) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: plural(text.length - characterLimit, {+ one: '# character over the limit',+ other: '# characters over the limit',+ }),+ });+ }+ }),+ });++type TSignFieldTextFormSchema = z.infer<ReturnType<typeof createSignFieldTextFormSchema>>;export type SignFieldTextDialogProps = {fieldMeta?: TTextFieldMeta;+ /**+ * The text currently inserted into the field.+ *+ * When provided, the dialog is prefilled with this text and the user can remove it+ * by either clearing the text or clicking the remove button.+ */+ insertedText?: string;};-export const SignFieldTextDialog = createCallable<SignFieldTextDialogProps, string | null>(({ call, fieldMeta }) => {- const { t } = useLingui();+export type SignFieldTextDialogResult = { action: 'save'; text: string } | { action: 'remove' };- const form = useForm<TSignFieldTextFormSchema>({- resolver: zodResolver(ZSignFieldTextFormSchema),- defaultValues: {- text: '',- },- });+export const SignFieldTextDialog = createCallable<SignFieldTextDialogProps, SignFieldTextDialogResult | null>(+ ({ call, fieldMeta, insertedText }) => {+ const { t } = useLingui();++ const isInserted = insertedText !== undefined;++ // A limit of 0 means the field has no limit.+ const characterLimit = fieldMeta?.characterLimit || undefined;++ const form = useForm<TSignFieldTextFormSchema>({+ resolver: zodResolver(createSignFieldTextFormSchema({ isInserted, characterLimit })),+ defaultValues: {+ text: insertedText ?? '',+ },+ });++ const onFormSubmit = ({ text }: TSignFieldTextFormSchema) => {+ if (isInserted && text.trim().length === 0) {+ call.end({ action: 'remove' });+ return;+ }++ call.end({ action: 'save', text });+ };++ return (+ <Dialog open={true} onOpenChange={(value) => (!value ? call.end(null) : null)}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{fieldMeta?.label || <Trans>Enter Text</Trans>}</DialogTitle>++ <DialogDescription className="mt-4">+ <Trans>Please enter a value</Trans>+ </DialogDescription>+ </DialogHeader>++ <Form {...form}>+ <form onSubmit={form.handleSubmit(onFormSubmit)}>+ <fieldset className="flex h-full flex-col space-y-4" disabled={form.formState.isSubmitting}>+ <FormField+ control={form.control}+ name="text"+ render={({ field, fieldState }) => {+ const isCounterVisible = characterLimit !== undefined && !fieldState.error;++ return (+ <FormItem>+ {/* The dialog doesn't scroll, so the max height leaves 20rem for its title and buttons. */}+ <FormControl>+ <Textarea+ id="custom-text"+ placeholder={fieldMeta?.placeholder ?? t`Enter your text here`}+ className={cn(+ 'h-auto max-h-[calc(100dvh-20rem)] min-h-20 w-full rounded-md [field-sizing:content]',+ {+ 'border-2 border-red-300 text-left ring-2 ring-red-200 ring-offset-2 ring-offset-red-200 focus-visible:border-red-400 focus-visible:ring-4 focus-visible:ring-red-200 focus-visible:ring-offset-2 focus-visible:ring-offset-red-200':+ fieldState.error,+ },+ )}+ {...field}+ />+ </FormControl>++ {(fieldState.error !== undefined || isCounterVisible || isInserted) && (+ <div className="flex items-center gap-x-4 text-sm">+ <FormMessage className="text-sm" />++ {isCounterVisible &&+ (field.value.length <= characterLimit ? (+ <span className="text-muted-foreground">+ <Plural+ value={characterLimit - field.value.length}+ one="# character remaining"+ other="# characters remaining"+ />+ </span>+ ) : (+ <span className="text-destructive">+ <Plural+ value={field.value.length - characterLimit}+ one="# character over the limit"+ other="# characters over the limit"+ />+ </span>+ ))}++ {isInserted && (+ <Button+ type="button"+ variant="link"+ className="ml-auto h-auto p-0 text-destructive"+ onClick={() => call.end({ action: 'remove' })}+ >+ <Trans>Remove</Trans>+ </Button>+ )}+ </div>+ )}+ </FormItem>+ );+ }}+ />++ <DialogFooter>+ <Button type="button" variant="secondary" onClick={() => call.end(null)}>+ <Trans>Cancel</Trans>+ </Button>- return (- <Dialog open={true} onOpenChange={(value) => (!value ? call.end(null) : null)}>- <DialogContent>- <DialogHeader>- <DialogTitle>{fieldMeta?.label || <Trans>Enter Text</Trans>}</DialogTitle>-- <DialogDescription className="mt-4">- <Trans>Please enter a value</Trans>- </DialogDescription>- </DialogHeader>-- <Form {...form}>- <form onSubmit={form.handleSubmit((data) => call.end(data.text))}>- <fieldset className="flex h-full flex-col space-y-4" disabled={form.formState.isSubmitting}>- <FormField- control={form.control}- name="text"- render={({ field, fieldState }) => (- <FormItem>- <FormControl>- <Textarea- id="custom-text"- placeholder={fieldMeta?.placeholder ?? t`Enter your text here`}- className={cn('w-full rounded-md', {- 'border-2 border-red-300 text-left ring-2 ring-red-200 ring-offset-2 ring-offset-red-200 focus-visible:border-red-400 focus-visible:ring-4 focus-visible:ring-red-200 focus-visible:ring-offset-2 focus-visible:ring-offset-red-200':- fieldState.error,- })}- {...field}- />- </FormControl>- <FormMessage />- {fieldMeta?.characterLimit !== undefined && fieldMeta?.characterLimit > 0 && !fieldState.error && (- <div className="text-muted-foreground text-sm">- <Plural- value={fieldMeta?.characterLimit - (field.value?.length ?? 0)}- one="# character remaining"- other="# characters remaining"- />- </div>- )}- </FormItem>- )}- />-- <DialogFooter>- <Button type="button" variant="secondary" onClick={() => call.end(null)}>- <Trans>Cancel</Trans>- </Button>-- <Button type="submit">- <Trans>Enter</Trans>- </Button>- </DialogFooter>- </fieldset>- </form>- </Form>- </DialogContent>- </Dialog>- );-});+ <Button type="submit">{isInserted ? <Trans>Save</Trans> : <Trans>Enter</Trans>}</Button>+ </DialogFooter>+ </fieldset>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+ },+);diff --git a/apps/remix/app/utils/field-signing/text-field.ts b/apps/remix/app/utils/field-signing/text-field.tsindex 48873faee..8a5cc2737 100644--- a/apps/remix/app/utils/field-signing/text-field.ts+++ b/apps/remix/app/utils/field-signing/text-field.ts@@ -21,27 +21,37 @@ export const handleTextFieldClick = async (});}- if (field.inserted) {+ if (text && !field.inserted) {return {type: FieldType.TEXT,- value: null,+ value: text,};}- let textToInsert = text;+ // Inserted fields reopen the dialog with their current text so it can be edited or removed.+ const result = await SignFieldTextDialog.call({+ fieldMeta: field.fieldMeta,+ insertedText: field.inserted ? field.customText : undefined,+ });- if (!textToInsert) {- textToInsert = await SignFieldTextDialog.call({- fieldMeta: field.fieldMeta,- });+ if (!result) {+ return null;+ }++ if (result.action === 'remove') {+ return {+ type: FieldType.TEXT,+ value: null,+ };}- if (!textToInsert) {+ // Avoid re-signing the field when the text has not changed.+ if (field.inserted && result.text === field.customText) {return null;}return {type: FieldType.TEXT,- value: textToInsert,+ value: result.text,};};diff --git a/packages/app-tests/e2e/envelopes/envelope-v2-text-field-signing.spec.ts b/packages/app-tests/e2e/envelopes/envelope-v2-text-field-signing.spec.tsnew file mode 100644index 000000000..0a0f3b956--- /dev/null+++ b/packages/app-tests/e2e/envelopes/envelope-v2-text-field-signing.spec.ts@@ -0,0 +1,141 @@+import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';+import { prisma } from '@documenso/prisma';+import type { TGetEnvelopeResponse } from '@documenso/trpc/server/envelope-router/get-envelope.types';+import type { APIRequestContext, Page } from '@playwright/test';+import { expect, test } from '@playwright/test';+import { FieldType } from '@prisma/client';++import { apiSeedPendingDocument } from '../fixtures/api-seeds';+import { getKonvaFieldTextForPage } from '../fixtures/konva';++test.describe('V2 envelope text field signing', () => {+ test('inserted text can be edited and removed', async ({ page, request }) => {+ const { envelope, token, textField } = await seedTextFieldDocument(request);++ await openSigningPage(page, token);++ const dialog = page.getByRole('dialog');+ const textInput = dialog.locator('#custom-text');++ await clickField(page, textField);+ await textInput.fill('First value');+ await dialog.getByRole('button', { name: 'Enter' }).click();+ await expect.poll(() => getKonvaFieldTextForPage(page, 1, textField.id)).toBe('First value');++ await clickField(page, textField);+ await expect(textInput).toHaveValue('First value');+ await textInput.fill('Second value');+ await dialog.getByRole('button', { name: 'Save' }).click();+ await expect.poll(() => getKonvaFieldTextForPage(page, 1, textField.id)).toBe('Second value');++ await clickField(page, textField);+ await expect(textInput).toHaveValue('Second value');+ await dialog.getByRole('button', { name: 'Save' }).click();+ await expect(dialog).toBeHidden();++ await clickField(page, textField);+ await dialog.getByRole('button', { name: 'Remove' }).click();+ await expect.poll(() => getKonvaFieldTextForPage(page, 1, textField.id)).toBe('Text');++ await clickField(page, textField);+ await expect(textInput).toHaveValue('');+ await textInput.fill('Third value');+ await dialog.getByRole('button', { name: 'Enter' }).click();+ await expect.poll(() => getKonvaFieldTextForPage(page, 1, textField.id)).toBe('Third value');++ await clickField(page, textField);+ await textInput.fill('');+ await dialog.getByRole('button', { name: 'Save' }).click();+ await expect.poll(() => getKonvaFieldTextForPage(page, 1, textField.id)).toBe('Text');++ const dbTextField = await prisma.field.findUniqueOrThrow({ where: { id: textField.id } });++ expect(dbTextField.inserted).toBe(false);+ expect(dbTextField.customText).toBe('');++ const insertedAuditLogs = await prisma.documentAuditLog.findMany({+ where: {+ envelopeId: envelope.id,+ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_FIELD_INSERTED,+ },+ orderBy: { createdAt: 'asc' },+ });++ // Saving "Second value" unchanged must not have written a second entry for it.+ expect(insertedAuditLogs.map((auditLog) => auditLog.data)).toEqual([+ expect.objectContaining({ field: { type: FieldType.TEXT, data: 'First value' } }),+ expect.objectContaining({ field: { type: FieldType.TEXT, data: 'Second value' } }),+ expect.objectContaining({ field: { type: FieldType.TEXT, data: 'Third value' } }),+ ]);+ });++ test('text over the character limit is rejected before the field is signed', async ({ page, request }) => {+ const { token, textField } = await seedTextFieldDocument(request, { type: 'text', characterLimit: 10 });++ await openSigningPage(page, token);++ const dialog = page.getByRole('dialog');+ const textInput = dialog.locator('#custom-text');++ await clickField(page, textField);+ await textInput.fill('12345678901');+ await expect(dialog.getByText('1 character over the limit')).toBeVisible();++ await dialog.getByRole('button', { name: 'Enter' }).click();+ await expect(textInput).toHaveAttribute('aria-invalid', 'true');+ await expect(textInput).toHaveAccessibleDescription('1 character over the limit');++ await textInput.fill('1234567890');+ await expect(textInput).toHaveAttribute('aria-invalid', 'false');++ await dialog.getByRole('button', { name: 'Enter' }).click();+ await expect.poll(() => getKonvaFieldTextForPage(page, 1, textField.id)).toBe('1234567890');++ const dbTextField = await prisma.field.findUniqueOrThrow({ where: { id: textField.id } });++ expect(dbTextField.inserted).toBe(true);+ expect(dbTextField.customText).toBe('1234567890');+ });+});++const seedTextFieldDocument = async (request: APIRequestContext, textFieldMeta?: Record<string, unknown>) => {+ const { envelope, distributeResult } = await apiSeedPendingDocument(request, {+ recipients: [{ email: '[email protected]', name: 'Text Signer' }],+ fieldsPerRecipient: [+ [+ { type: FieldType.SIGNATURE, page: 1, positionX: 5, positionY: 5, width: 20, height: 5 },+ { type: FieldType.TEXT, page: 1, positionX: 5, positionY: 20, width: 30, height: 5, fieldMeta: textFieldMeta },+ ],+ ],+ });++ const textField = envelope.fields.find((field) => field.type === FieldType.TEXT);++ if (!textField) {+ throw new Error('Text field not found');+ }++ return { envelope, token: distributeResult.recipients[0].token, textField };+};++const openSigningPage = async (page: Page, token: string) => {+ await page.goto(`/sign/${token}`);++ await expect(page.locator('img[data-page-number]').first()).toBeVisible({ timeout: 30_000 });+ await expect(page.locator('.konva-container canvas').first()).toBeVisible({ timeout: 30_000 });+};++const clickField = async (page: Page, field: TGetEnvelopeResponse['fields'][number]) => {+ const canvas = page.locator('.konva-container canvas').first();+ const canvasBox = await canvas.boundingBox();++ if (!canvasBox) {+ throw new Error('Canvas bounding box not found');+ }++ // Field positions and sizes are percentages of the page.+ const x = ((Number(field.positionX) + Number(field.width) / 2) / 100) * canvasBox.width;+ const y = ((Number(field.positionY) + Number(field.height) / 2) / 100) * canvasBox.height;++ await canvas.click({ position: { x, y } });+};diff --git a/packages/app-tests/e2e/fixtures/konva.ts b/packages/app-tests/e2e/fixtures/konva.tsindex 87973ab97..ef8492ba7 100644--- a/packages/app-tests/e2e/fixtures/konva.ts+++ b/packages/app-tests/e2e/fixtures/konva.ts@@ -48,3 +48,22 @@ export const getKonvaTransformerNodeCountForPage = async (page: Page, pageNumber{ pageNumber },);};++/**+ * Returns the text a field renders on the page's canvas: its inserted value once+ * signed, otherwise its label or field type name.+ */+export const getKonvaFieldTextForPage = async (page: Page, pageNumber: number, fieldId: number) => {+ await page.locator('.konva-container canvas').first().waitFor({ state: 'visible' });++ return await page.evaluate(+ ({ pageNumber, fieldId }) => {+ const konva: typeof Konva = (window as unknown as { Konva: typeof Konva }).Konva;++ const stage = konva.stages.find((stage) => stage.attrs.id === `page-${pageNumber}`);++ return stage?.findOne<Konva.Text>(`#${fieldId}-text`)?.text() ?? null;+ },+ { pageNumber, fieldId },+ );+};diff --git a/packages/lib/utils/envelope-signing.ts b/packages/lib/utils/envelope-signing.tsindex 73c68479f..795fdfecf 100644--- a/packages/lib/utils/envelope-signing.ts+++ b/packages/lib/utils/envelope-signing.ts@@ -128,7 +128,7 @@ export const extractFieldInsertionValues = ({if (errors.length > 0) {throw new AppError(AppErrorCode.INVALID_BODY, {- message: 'Invalid email',+ message: 'Invalid text',});}