The Open Source DocuSign Alternative.
TypeScript digital-signaturedocument-signingdocusign-alternativee-signatureesignesignaturenext-authnextjsopen-sourcepades-standardpdfpdf-signpdf-signaturepostgresqlprismaself-hostedsigningtypescript
feat: add handwriting font option for initials fields (#3474)
Catalin Pit052aca2f955a
diff --git a/apps/docs/content/docs/concepts/field-types.mdx b/apps/docs/content/docs/concepts/field-types.mdxindex 54516d90b..ed3f47a03 100644--- a/apps/docs/content/docs/concepts/field-types.mdx+++ b/apps/docs/content/docs/concepts/field-types.mdx@@ -52,12 +52,18 @@ The initials field captures abbreviated signatures, typically used to acknowledg### Configuration Options-| Option | Description |-| -------------- | -------------------------------------- |-| Required | Whether the field must be completed |-| Read-only | Lock the field with a pre-filled value |-| Label | Display text shown above the field |-| Text alignment | Left, center, or right alignment |+| Option | Description |+| -------------- | ---------------------------------------------------------------- |+| Required | Whether the field must be completed |+| Read-only | Lock the field with a pre-filled value |+| Label | Display text shown above the field |+| Font family | Sans-serif (default) or handwriting (cursive, 18px default size) |+| Text alignment | Left, center, or right alignment |++<Callout type="info">+ Font family is only available on envelopes. Legacy documents ignore the setting and always render+ initials in sans-serif, even if the value is configured.+</Callout>### Common Use Casesdiff --git a/apps/docs/content/docs/developers/api/fields.mdx b/apps/docs/content/docs/developers/api/fields.mdxindex 918f62cad..4f5f9e396 100644--- a/apps/docs/content/docs/developers/api/fields.mdx+++ b/apps/docs/content/docs/developers/api/fields.mdx@@ -614,6 +614,24 @@ All field types support these base options:}```+### Initials Field++```json+{+ "type": "INITIALS",+ "fieldMeta": {+ "type": "initials",+ "fontFamily": "handwriting",+ "textAlign": "center"+ }+}+```++| Option | Type | Description |+| ------------ | ------ | -------------------------------------------------------------------- |+| `fontFamily` | string | `sans-serif` (default) or `handwriting` (cursive, 18px default size) |+| `textAlign` | string | `left`, `center`, or `right` |+### Text Field```jsondiff --git a/apps/docs/content/docs/users/documents/advanced/pdf-placeholders.mdx b/apps/docs/content/docs/users/documents/advanced/pdf-placeholders.mdxindex 7c28b7b4e..0ed15dfff 100644--- a/apps/docs/content/docs/users/documents/advanced/pdf-placeholders.mdx+++ b/apps/docs/content/docs/users/documents/advanced/pdf-placeholders.mdx@@ -109,12 +109,24 @@ You can customize fields by adding options after the recipient identifier:| `maxValue` | Number | Maximum allowed value || `numberFormat` | Format string | Number display format |+### Initials Field Options++| Option | Values | Description |+| ------------ | --------------------------- | -------------------------------------------------- |+| `fontFamily` | `sans-serif`, `handwriting` | Font family, `handwriting` defaults to font size 18 |++<Callout type="info">+ `fontFamily` is only applied on envelopes. Legacy documents ignore it and render initials in+ sans-serif.+</Callout>+### Examples with Options```{{text, r1, required=true, label=Company Name}}{{number, r1, minValue=0, maxValue=100, value=50}}{{name, r1, fontSize=14}}+{{initials, r1, fontFamily=handwriting}}{{text, r2, readOnly=true, text=Contract #12345}}```diff --git a/apps/remix/app/components/forms/editor/editor-field-initials-form.tsx b/apps/remix/app/components/forms/editor/editor-field-initials-form.tsxindex 31e95e25b..94d495baa 100644--- a/apps/remix/app/components/forms/editor/editor-field-initials-form.tsx+++ b/apps/remix/app/components/forms/editor/editor-field-initials-form.tsx@@ -1,11 +1,15 @@import {DEFAULT_FIELD_FONT_SIZE,+ DEFAULT_HANDWRITING_INITIALS_FONT_SIZE,FIELD_DEFAULT_GENERIC_ALIGN,type TInitialsFieldMeta as InitialsFieldMeta,+ resolveFieldFontSize,ZInitialsFieldMeta,} from '@documenso/lib/types/field-meta';-import { Form } from '@documenso/ui/primitives/form/form';+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@documenso/ui/primitives/form/form';+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@documenso/ui/primitives/select';import { zodResolver } from '@hookform/resolvers/zod';+import { Trans, useLingui } from '@lingui/react/macro';import { useEffect } from 'react';import { useForm, useWatch } from 'react-hook-form';import type { z } from 'zod';@@ -15,6 +19,7 @@ import { EditorGenericFontSizeField, EditorGenericTextAlignField } from './editoconst ZInitialsFieldFormSchema = ZInitialsFieldMeta.pick({fontSize: true,textAlign: true,+ fontFamily: true,});type TInitialsFieldFormSchema = z.infer<typeof ZInitialsFieldFormSchema>;@@ -30,12 +35,15 @@ export const EditorFieldInitialsForm = ({},onValueChange,}: EditorFieldInitialsFormProps) => {+ const { t } = useLingui();+const form = useForm<TInitialsFieldFormSchema>({resolver: zodResolver(ZInitialsFieldFormSchema),mode: 'onChange',defaultValues: {- fontSize: value.fontSize || DEFAULT_FIELD_FONT_SIZE,+ fontSize: resolveFieldFontSize(value),textAlign: value.textAlign ?? FIELD_DEFAULT_GENERIC_ALIGN,+ fontFamily: value.fontFamily ?? 'sans-serif',},});@@ -63,6 +71,49 @@ export const EditorFieldInitialsForm = ({<fieldset className="flex flex-col gap-2"><EditorGenericFontSizeField formControl={form.control} />+ <FormField+ control={form.control}+ name="fontFamily"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans>Font Family</Trans>+ </FormLabel>+ <FormControl>+ <Select+ value={field.value}+ onValueChange={(fontFamily) => {+ const fontSize = form.getValues('fontSize');++ if (fontFamily === 'handwriting' && fontSize === DEFAULT_FIELD_FONT_SIZE) {+ form.setValue('fontSize', DEFAULT_HANDWRITING_INITIALS_FONT_SIZE);+ }++ if (fontFamily === 'sans-serif' && fontSize === DEFAULT_HANDWRITING_INITIALS_FONT_SIZE) {+ form.setValue('fontSize', DEFAULT_FIELD_FONT_SIZE);+ }++ field.onChange(fontFamily);+ }}+ >+ <SelectTrigger data-testid="field-form-fontFamily">+ <SelectValue placeholder={t`Select font family`} />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="sans-serif">+ <Trans>Sans-Serif</Trans>+ </SelectItem>+ <SelectItem value="handwriting">+ <Trans>Handwriting</Trans>+ </SelectItem>+ </SelectContent>+ </Select>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+<EditorGenericTextAlignField formControl={form.control} /></fieldset></form>diff --git a/apps/remix/app/components/general/envelope-editor/envelope-editor-preview-page.tsx b/apps/remix/app/components/general/envelope-editor/envelope-editor-preview-page.tsxindex df5339360..d2623cc27 100644--- a/apps/remix/app/components/general/envelope-editor/envelope-editor-preview-page.tsx+++ b/apps/remix/app/components/general/envelope-editor/envelope-editor-preview-page.tsx@@ -7,7 +7,7 @@ import { PDF_VIEWER_ERROR_MESSAGES } from '@documenso/lib/constants/pdf-viewer-iimport { ZFieldAndMetaSchema } from '@documenso/lib/types/field-meta';import { extractFieldInsertionValues } from '@documenso/lib/utils/envelope-signing';import { toCheckboxCustomText } from '@documenso/lib/utils/fields';-import { extractInitials } from '@documenso/lib/utils/recipient-formatter';+import { extractFullInitials } from '@documenso/lib/utils/recipient-formatter';import { AnimateGenericFadeInOut } from '@documenso/ui/components/animate/animate-generic-fade-in-out';import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';import { RecipientSelector } from '@documenso/ui/primitives/recipient-selector';@@ -121,7 +121,7 @@ export const EnvelopeEditorPreviewPage = () => {}).with({ type: FieldType.INITIALS }, () => {return {- customText: extractInitials(recipientName),+ customText: extractFullInitials(recipientName),};}).with({ type: FieldType.RADIO }, ({ fieldMeta }) => {diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsxindex 4c76a5a46..93c9018dd 100644--- a/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx+++ b/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx@@ -18,7 +18,7 @@ import { createSpinner } from '@documenso/lib/universal/field-renderer/field-genimport { renderField } from '@documenso/lib/universal/field-renderer/render-field';import { isFieldUnsignedAndRequired } from '@documenso/lib/utils/advanced-fields-helpers';import { getClientSideFieldTranslations } from '@documenso/lib/utils/fields';-import { extractInitials } from '@documenso/lib/utils/recipient-formatter';+import { extractFullInitials } from '@documenso/lib/utils/recipient-formatter';import type { TSignEnvelopeFieldValue } from '@documenso/trpc/server/envelope-router/sign-envelope-field.types';import { EnvelopeRecipientFieldTooltip } from '@documenso/ui/components/document/envelope-recipient-field-tooltip';import { EnvelopeFieldToolTip } from '@documenso/ui/components/field/envelope-field-tooltip';@@ -315,7 +315,7 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD* INITIALS FIELD.*/.with({ type: FieldType.INITIALS }, (field) => {- const initials = localFullName ? extractInitials(localFullName) : null;+ const initials = localFullName ? extractFullInitials(localFullName) : null;void handleInitialsFieldClick({ field, initials }).then(async (payload) => {diff --git a/packages/app-tests/e2e/envelope-editor-v2/envelope-fields.spec.ts b/packages/app-tests/e2e/envelope-editor-v2/envelope-fields.spec.tsindex 0a4c3ab73..6e40c7509 100644--- a/packages/app-tests/e2e/envelope-editor-v2/envelope-fields.spec.ts+++ b/packages/app-tests/e2e/envelope-editor-v2/envelope-fields.spec.ts@@ -353,8 +353,11 @@ const runAllFieldTypesFlow = async (surface: TEnvelopeEditorSurface): Promise<TAawait root.locator('[data-testid="field-form-textAlign"]').click();await root.getByRole('option', { name: 'Right' }).click();- // 4. Initials: place and set fontSize to 16.+ // 4. Initials: switch to handwriting, which bumps the default fontSize to 18, then set fontSize to 16.await placeFieldOnPdf(root, 'Initials', { x: 120, y: 200 });+ await root.locator('[data-testid="field-form-fontFamily"]').click();+ await root.getByRole('option', { name: 'Handwriting' }).click();+ await expect(root.locator('[data-testid="field-form-fontSize"]')).toHaveValue('18');await root.locator('[data-testid="field-form-fontSize"]').fill('16');// 5. Date: place and set textAlign to center.@@ -496,6 +499,7 @@ const assertAllFieldTypesPersistedInDatabase = async ({// INITIALSexpect(meta(FieldType.INITIALS).type).toBe('initials');expect(meta(FieldType.INITIALS).fontSize).toBe(16);+ expect(meta(FieldType.INITIALS).fontFamily).toBe('handwriting');// DATEexpect(meta(FieldType.DATE).type).toBe('date');diff --git a/packages/lib/types/field-meta.ts b/packages/lib/types/field-meta.tsindex bb65bf782..095105361 100644--- a/packages/lib/types/field-meta.ts+++ b/packages/lib/types/field-meta.ts@@ -15,6 +15,7 @@ export const FIELD_MIN_LETTER_SPACING = 0;export const FIELD_MAX_LETTER_SPACING = 100;export const DEFAULT_FIELD_FONT_SIZE = 12;+export const DEFAULT_HANDWRITING_INITIALS_FONT_SIZE = 18;export const DEFAULT_SIGNATURE_OVERFLOW_MODE = 'auto';export const DEFAULT_DATE_OVERFLOW_MODE = 'auto';@@ -53,6 +54,18 @@ export type GenericTextFieldTypeMetas =| TTextFieldMeta| TNumberFieldMeta;+export const resolveFieldFontSize = (fieldMeta?: GenericTextFieldTypeMetas | null): number => {+ if (fieldMeta?.fontSize !== undefined) {+ return fieldMeta.fontSize;+ }++ if (fieldMeta?.type === 'initials' && fieldMeta.fontFamily === 'handwriting') {+ return DEFAULT_HANDWRITING_INITIALS_FONT_SIZE;+ }++ return DEFAULT_FIELD_FONT_SIZE;+};+const ZFieldMetaLineHeight = z.coerce.number().min(FIELD_MIN_LINE_HEIGHT)@@ -64,6 +77,11 @@ const ZFieldMetaLetterSpacing = z.coerce.max(FIELD_MAX_LETTER_SPACING).describe('The spacing between each character');const ZFieldMetaVerticalAlign = z.enum(['top', 'middle', 'bottom']).describe('The vertical alignment of the text');+const ZFieldMetaFontFamily = z+ .enum(['sans-serif', 'handwriting'])+ .describe(+ 'The font family of the text, handwriting uses a cursive font. Only applied on envelopes, legacy documents ignore this value.',+ );export const ZBaseFieldMeta = z.object({label: z.string().optional(),@@ -83,6 +101,7 @@ export type TFieldTextAlignSchema = z.infer<typeof ZFieldTextAlignSchema>;export const ZInitialsFieldMeta = ZBaseFieldMeta.extend({type: z.literal('initials'),textAlign: ZFieldTextAlignSchema.optional(),+ fontFamily: ZFieldMetaFontFamily.optional(),});export type TInitialsFieldMeta = z.infer<typeof ZInitialsFieldMeta>;diff --git a/packages/lib/universal/field-renderer/render-generic-text-field.ts b/packages/lib/universal/field-renderer/render-generic-text-field.tsindex c4163fea2..d246e0f56 100644--- a/packages/lib/universal/field-renderer/render-generic-text-field.ts+++ b/packages/lib/universal/field-renderer/render-generic-text-field.ts@@ -1,12 +1,13 @@import Konva from 'konva';-import { DEFAULT_STANDARD_FONT_SIZE } from '../../constants/pdf';+import { getSignatureFontFamily } from '../../constants/pdf';import type { GenericTextFieldTypeMetas } from '../../types/field-meta';import {FIELD_DEFAULT_GENERIC_ALIGN,FIELD_DEFAULT_GENERIC_VERTICAL_ALIGN,FIELD_DEFAULT_LETTER_SPACING,FIELD_DEFAULT_LINE_HEIGHT,+ resolveFieldFontSize,resolveFieldOverflowMode,} from '../../types/field-meta';import { calculateOverflowLayout } from './calculate-overflow-layout';@@ -28,6 +29,7 @@ const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOptionconst { fieldX, fieldY, fieldWidth, fieldHeight } = calculateFieldPosition(field, pageWidth, pageHeight);const fieldMeta = field.fieldMeta as GenericTextFieldTypeMetas | undefined;+ const isHandwriting = fieldMeta?.type === 'initials' && fieldMeta.fontFamily === 'handwriting';const fieldTypeName = translations?.[field.type] || field.type;@@ -42,7 +44,7 @@ const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOption// Calculate text positioning based on alignmentconst textX = 0;const textY = 0;- const textFontSize = fieldMeta?.fontSize || DEFAULT_STANDARD_FONT_SIZE;+ const textFontSize = resolveFieldFontSize(fieldMeta);// By default, render the field name or label centered.// isLabel tracks whether we're rendering the field type name (like "Text", "Date", "Email")@@ -104,12 +106,14 @@ const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOption}}+ const textFontFamily = isHandwriting ? getSignatureFontFamily(textToRender) : konvaTextFontFamily;+const overflowLayout = calculateOverflowLayout({overflowMode: resolveFieldOverflowMode(fieldMeta),isLabel,textToRender,fontSize: textFontSize,- fontFamily: konvaTextFontFamily,+ fontFamily: textFontFamily,lineHeight: textLineHeight,letterSpacing: textLetterSpacing,textAlign,@@ -136,7 +140,7 @@ const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOptionalign: overflowLayout.textAlign,lineHeight: textLineHeight,letterSpacing: textLetterSpacing,- fontFamily: konvaTextFontFamily,+ fontFamily: textFontFamily,fill: konvaTextFill,width: overflowLayout.width,height: overflowLayout.height,@@ -147,6 +151,7 @@ const upsertFieldText = (field: FieldToRender, options: RenderFieldElementOptionisLabel,textToRender,textFontSize,+ textFontFamily,textAlign,textVerticalAlign,textLineHeight,@@ -178,6 +183,7 @@ export const renderGenericTextFieldElement = (field: FieldToRender, options: RenisLabel,textToRender,textFontSize,+ textFontFamily,textAlign,textVerticalAlign,textLineHeight,@@ -221,7 +227,7 @@ export const renderGenericTextFieldElement = (field: FieldToRender, options: RenisLabel,textToRender,fontSize: textFontSize,- fontFamily: konvaTextFontFamily,+ fontFamily: textFontFamily,lineHeight: textLineHeight,letterSpacing: textLetterSpacing,textAlign,diff --git a/packages/lib/utils/recipient-formatter.ts b/packages/lib/utils/recipient-formatter.tsindex efda74817..02032b285 100644--- a/packages/lib/utils/recipient-formatter.ts+++ b/packages/lib/utils/recipient-formatter.ts@@ -2,11 +2,28 @@ import type { Recipient } from '@prisma/client';export const extractInitials = (text: string) =>text- .split(' ')+ .trim()+ .split(/\s+/).map((name: string) => name.slice(0, 1).toUpperCase()).slice(0, 2).join('');+// \p{L} matches any Unicode letter (accented, CJK, etc). Anchored to the start so tokens that+// begin with punctuation or digits ("-", "(John)", "3rd") contribute nothing instead of a stray symbol.+const LEADING_LETTER_REGEX = /^\p{L}/u;++// Clamp initials to a fixed value so comound names don't overflow.+const MAX_FULL_INITIALS = 8;++export const extractFullInitials = (text: string) =>+ text+ .trim()+ .split(/\s+/)+ .map((name) => name.match(LEADING_LETTER_REGEX)?.[0].toUpperCase())+ .filter(Boolean)+ .slice(0, MAX_FULL_INITIALS)+ .join('');+export const recipientAbbreviation = (recipient: Pick<Recipient, 'name' | 'email'>) => {- return extractInitials(recipient.name) || recipient.email.slice(0, 1).toUpperCase();+ return extractFullInitials(recipient.name).slice(0, 3) || recipient.email.slice(0, 1).toUpperCase();};