Skip to content

The Open Source DocuSign Alternative.

feat: horizontal checkboxes (#1911)

Lucas Smith512e3555b4c8
diff --git a/apps/remix/app/components/general/document-signing/document-signing-checkbox-field.tsx b/apps/remix/app/components/general/document-signing/document-signing-checkbox-field.tsx
index ab15d21f7..be7c8e02b 100644
--- a/apps/remix/app/components/general/document-signing/document-signing-checkbox-field.tsx
+++ b/apps/remix/app/components/general/document-signing/document-signing-checkbox-field.tsx
@@ -17,6 +17,7 @@ import type {
TSignFieldWithTokenMutationSchema,
} from '@documenso/trpc/server/field-router/schema';
import { FieldToolTip } from '@documenso/ui/components/field/field-tooltip';
+import { cn } from '@documenso/ui/lib/utils';
import { Checkbox } from '@documenso/ui/primitives/checkbox';
import { checkboxValidationSigns } from '@documenso/ui/primitives/document-flow/field-items-advanced-settings/constants';
import { Label } from '@documenso/ui/primitives/label';
@@ -276,7 +277,14 @@ export const DocumentSigningCheckboxField = ({
{validationSign?.label} {checkboxValidationLength}
</FieldToolTip>
)}
- <div className="z-50 my-0.5 flex flex-col gap-y-1">
+ <div
+ className={cn(
+ 'z-50 my-0.5 flex gap-1',
+ parsedFieldMeta.direction === 'horizontal'
+ ? 'flex-row flex-wrap'
+ : 'flex-col gap-y-1',
+ )}
+ >
{values?.map((item: { id: number; value: string; checked: boolean }, index: number) => {
const itemValue = item.value || `empty-value-${item.id}`;
@@ -305,7 +313,12 @@ export const DocumentSigningCheckboxField = ({
)}
{field.inserted && (
- <div className="my-0.5 flex flex-col gap-y-1">
+ <div
+ className={cn(
+ 'my-0.5 flex gap-1',
+ parsedFieldMeta.direction === 'horizontal' ? 'flex-row flex-wrap' : 'flex-col gap-y-1',
+ )}
+ >
{values?.map((item: { id: number; value: string; checked: boolean }, index: number) => {
const itemValue = item.value || `empty-value-${item.id}`;
diff --git a/packages/lib/client-only/hooks/use-element-bounds.ts b/packages/lib/client-only/hooks/use-element-bounds.ts
index c2f453b51..560accca6 100644
--- a/packages/lib/client-only/hooks/use-element-bounds.ts
+++ b/packages/lib/client-only/hooks/use-element-bounds.ts
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { getBoundingClientRect } from '@documenso/lib/client-only/get-bounding-client-rect';
@@ -10,7 +10,7 @@ export const useElementBounds = (elementOrSelector: HTMLElement | string, withSc
width: 0,
});
- const calculateBounds = () => {
+ const calculateBounds = useCallback(() => {
const $el =
typeof elementOrSelector === 'string'
? document.querySelector<HTMLElement>(elementOrSelector)
@@ -32,11 +32,11 @@ export const useElementBounds = (elementOrSelector: HTMLElement | string, withSc
width,
height,
};
- };
+ }, [elementOrSelector, withScroll]);
useEffect(() => {
setBounds(calculateBounds());
- }, [calculateBounds]);
+ }, []);
useEffect(() => {
const onResize = () => {
@@ -48,7 +48,7 @@ export const useElementBounds = (elementOrSelector: HTMLElement | string, withSc
return () => {
window.removeEventListener('resize', onResize);
};
- }, [calculateBounds]);
+ }, []);
useEffect(() => {
const $el =
@@ -69,7 +69,7 @@ export const useElementBounds = (elementOrSelector: HTMLElement | string, withSc
return () => {
observer.disconnect();
};
- }, [calculateBounds]);
+ }, []);
return bounds;
};
diff --git a/packages/lib/server-only/pdf/insert-field-in-pdf.ts b/packages/lib/server-only/pdf/insert-field-in-pdf.ts
index a89a3c3f9..fe0a5749a 100644
--- a/packages/lib/server-only/pdf/insert-field-in-pdf.ts
+++ b/packages/lib/server-only/pdf/insert-field-in-pdf.ts
@@ -240,35 +240,79 @@ export const insertFieldInPDF = async (pdf: PDFDocument, field: FieldWithSignatu
}));
const selected: string[] = fromCheckboxValue(field.customText);
+ const direction = meta.data.direction ?? 'vertical';
const topPadding = 12;
const leftCheckboxPadding = 8;
const leftCheckboxLabelPadding = 12;
const checkboxSpaceY = 13;
- for (const [index, item] of (values ?? []).entries()) {
- const offsetY = index * checkboxSpaceY + topPadding;
+ if (direction === 'horizontal') {
+ // Horizontal layout: arrange checkboxes side by side with wrapping
+ let currentX = leftCheckboxPadding;
+ let currentY = topPadding;
+ const maxWidth = pageWidth - fieldX - leftCheckboxPadding * 2;
- const checkbox = pdf.getForm().createCheckBox(`checkbox.${field.secondaryId}.${index}`);
+ for (const [index, item] of (values ?? []).entries()) {
+ const checkbox = pdf.getForm().createCheckBox(`checkbox.${field.secondaryId}.${index}`);
- if (selected.includes(item.value)) {
- checkbox.check();
+ if (selected.includes(item.value)) {
+ checkbox.check();
+ }
+
+ const labelText = item.value.includes('empty-value-') ? '' : item.value;
+ const labelWidth = font.widthOfTextAtSize(labelText, 12);
+ const itemWidth = leftCheckboxLabelPadding + labelWidth + 16; // checkbox + padding + label + margin
+
+ // Check if item fits on current line, if not wrap to next line
+ if (currentX + itemWidth > maxWidth && index > 0) {
+ currentX = leftCheckboxPadding;
+ currentY += checkboxSpaceY;
+ }
+
+ page.drawText(labelText, {
+ x: fieldX + currentX + leftCheckboxLabelPadding,
+ y: pageHeight - (fieldY + currentY),
+ size: 12,
+ font,
+ rotate: degrees(pageRotationInDegrees),
+ });
+
+ checkbox.addToPage(page, {
+ x: fieldX + currentX,
+ y: pageHeight - (fieldY + currentY),
+ height: 8,
+ width: 8,
+ });
+
+ currentX += itemWidth;
}
+ } else {
+ // Vertical layout: original behavior
+ for (const [index, item] of (values ?? []).entries()) {
+ const offsetY = index * checkboxSpaceY + topPadding;
- page.drawText(item.value.includes('empty-value-') ? '' : item.value, {
- x: fieldX + leftCheckboxPadding + leftCheckboxLabelPadding,
- y: pageHeight - (fieldY + offsetY),
- size: 12,
- font,
- rotate: degrees(pageRotationInDegrees),
- });
+ const checkbox = pdf.getForm().createCheckBox(`checkbox.${field.secondaryId}.${index}`);
- checkbox.addToPage(page, {
- x: fieldX + leftCheckboxPadding,
- y: pageHeight - (fieldY + offsetY),
- height: 8,
- width: 8,
- });
+ if (selected.includes(item.value)) {
+ checkbox.check();
+ }
+
+ page.drawText(item.value.includes('empty-value-') ? '' : item.value, {
+ x: fieldX + leftCheckboxPadding + leftCheckboxLabelPadding,
+ y: pageHeight - (fieldY + offsetY),
+ size: 12,
+ font,
+ rotate: degrees(pageRotationInDegrees),
+ });
+
+ checkbox.addToPage(page, {
+ x: fieldX + leftCheckboxPadding,
+ y: pageHeight - (fieldY + offsetY),
+ height: 8,
+ width: 8,
+ });
+ }
}
})
.with({ type: FieldType.RADIO }, (field) => {
diff --git a/packages/lib/server-only/template/create-document-from-template.ts b/packages/lib/server-only/template/create-document-from-template.ts
index 3150670a3..afe2d5e95 100644
--- a/packages/lib/server-only/template/create-document-from-template.ts
+++ b/packages/lib/server-only/template/create-document-from-template.ts
@@ -228,6 +228,7 @@ const getUpdatedFieldMeta = (field: Field, prefillField?: TFieldMetaPrefillField
type: 'checkbox',
label: field.label,
values: newValues,
+ direction: checkboxMeta.direction ?? 'vertical',
};
return meta;
diff --git a/packages/lib/types/field-meta.ts b/packages/lib/types/field-meta.ts
index dcc586bac..b0db24316 100644
--- a/packages/lib/types/field-meta.ts
+++ b/packages/lib/types/field-meta.ts
@@ -96,6 +96,7 @@ export const ZCheckboxFieldMeta = ZBaseFieldMeta.extend({
.optional(),
validationRule: z.string().optional(),
validationLength: z.number().optional(),
+ direction: z.enum(['vertical', 'horizontal']).optional().default('vertical'),
});
export type TCheckboxFieldMeta = z.infer<typeof ZCheckboxFieldMeta>;
diff --git a/packages/ui/components/field/field.tsx b/packages/ui/components/field/field.tsx
index 5c2c3f300..e28e7b0c5 100644
--- a/packages/ui/components/field/field.tsx
+++ b/packages/ui/components/field/field.tsx
@@ -3,7 +3,9 @@ import React, { useEffect, useMemo, useState } from 'react';
import { type Field, FieldType } from '@prisma/client';
import { createPortal } from 'react-dom';
+import { useElementBounds } from '@documenso/lib/client-only/hooks/use-element-bounds';
import { useFieldPageCoords } from '@documenso/lib/client-only/hooks/use-field-page-coords';
+import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
import { isFieldUnsignedAndRequired } from '@documenso/lib/utils/advanced-fields-helpers';
import type { RecipientColorStyles } from '../../lib/recipient-colors';
@@ -23,6 +25,11 @@ export function FieldContainerPortal({
const alternativePortalRoot = document.getElementById('document-field-portal-root');
const coords = useFieldPageCoords(field);
+ const $pageBounds = useElementBounds(
+ `${PDF_VIEWER_PAGE_SELECTOR}[data-page-number="${field.page}"]`,
+ );
+
+ const maxWidth = $pageBounds?.width ? $pageBounds.width - coords.x : undefined;
const isCheckboxOrRadioField = field.type === 'CHECKBOX' || field.type === 'RADIO';
@@ -32,10 +39,14 @@ export function FieldContainerPortal({
const bounds = {
top: `${coords.y}px`,
left: `${coords.x}px`,
- ...(!isCheckboxOrRadioField && {
- height: `${coords.height}px`,
- width: `${coords.width}px`,
- }),
+ ...(!isCheckboxOrRadioField
+ ? {
+ height: `${coords.height}px`,
+ width: `${coords.width}px`,
+ }
+ : {
+ maxWidth: `${maxWidth}px`,
+ }),
};
if (portalBounds) {
@@ -44,7 +55,7 @@ export function FieldContainerPortal({
}
return bounds;
- }, [coords, isCheckboxOrRadioField]);
+ }, [coords, maxWidth, isCheckboxOrRadioField]);
return createPortal(
<div className={cn('absolute', className)} style={style}>
diff --git a/packages/ui/primitives/document-flow/field-content.tsx b/packages/ui/primitives/document-flow/field-content.tsx
index c80287257..3ebff09ae 100644
--- a/packages/ui/primitives/document-flow/field-content.tsx
+++ b/packages/ui/primitives/document-flow/field-content.tsx
@@ -38,13 +38,8 @@ export const FieldContent = ({ field, documentMeta }: FieldIconProps) => {
const { type, fieldMeta } = field;
- // Only render checkbox if values exist, otherwise render the empty checkbox field content.
- if (
- field.type === FieldType.CHECKBOX &&
- field.fieldMeta?.type === 'checkbox' &&
- field.fieldMeta.values &&
- field.fieldMeta.values.length > 0
- ) {
+ // Render checkbox layout for checkbox fields, even if no values exist yet
+ if (field.type === FieldType.CHECKBOX && field.fieldMeta?.type === 'checkbox') {
let checkedValues: string[] = [];
try {
@@ -55,8 +50,32 @@ export const FieldContent = ({ field, documentMeta }: FieldIconProps) => {
console.error(err);
}
+ // If no values exist yet, show a placeholder checkbox
+ if (!field.fieldMeta.values || field.fieldMeta.values.length === 0) {
+ return (
+ <div
+ className={cn(
+ 'flex gap-1 py-0.5',
+ field.fieldMeta.direction === 'horizontal' ? 'flex-row flex-wrap' : 'flex-col gap-y-1',
+ )}
+ >
+ <div className="flex items-center">
+ <Checkbox className="h-3 w-3" disabled />
+ <Label className="text-foreground ml-1.5 text-xs font-normal opacity-50">
+ Checkbox option
+ </Label>
+ </div>
+ </div>
+ );
+ }
+
return (
- <div className="flex flex-col gap-y-1 py-0.5">
+ <div
+ className={cn(
+ 'flex gap-1 py-0.5',
+ field.fieldMeta.direction === 'horizontal' ? 'flex-row flex-wrap' : 'flex-col gap-y-1',
+ )}
+ >
{field.fieldMeta.values.map((item, index) => (
<div key={index} className="flex items-center">
<Checkbox
diff --git a/packages/ui/primitives/document-flow/field-item-advanced-settings.tsx b/packages/ui/primitives/document-flow/field-item-advanced-settings.tsx
index 2b14059ed..1d0a03cc4 100644
--- a/packages/ui/primitives/document-flow/field-item-advanced-settings.tsx
+++ b/packages/ui/primitives/document-flow/field-item-advanced-settings.tsx
@@ -129,6 +129,7 @@ const getDefaultState = (fieldType: FieldType): FieldMeta => {
validationLength: 0,
required: false,
readOnly: false,
+ direction: 'vertical',
};
case FieldType.DROPDOWN:
return {
diff --git a/packages/ui/primitives/document-flow/field-item.tsx b/packages/ui/primitives/document-flow/field-item.tsx
index 11c3e1f2f..da09ed471 100644
--- a/packages/ui/primitives/document-flow/field-item.tsx
+++ b/packages/ui/primitives/document-flow/field-item.tsx
@@ -8,6 +8,7 @@ import { createPortal } from 'react-dom';
import { Rnd } from 'react-rnd';
import { useSearchParams } from 'react-router';
+import { useElementBounds } from '@documenso/lib/client-only/hooks/use-element-bounds';
import { PDF_VIEWER_PAGE_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
import type { TFieldMetaSchema } from '@documenso/lib/types/field-meta';
import { ZCheckboxFieldMeta, ZRadioFieldMeta } from '@documenso/lib/types/field-meta';
@@ -81,7 +82,11 @@ export const FieldItem = ({
pageWidth: defaultWidth || 0,
});
const [settingsActive, setSettingsActive] = useState(false);
- const $el = useRef(null);
+ const $el = useRef<HTMLDivElement>(null);
+
+ const $pageBounds = useElementBounds(
+ `${PDF_VIEWER_PAGE_SELECTOR}[data-page-number="${field.pageNumber}"]`,
+ );
const signerStyles = useRecipientColors(recipientIndex);
@@ -233,9 +238,10 @@ export const FieldItem = ({
default={{
x: coords.pageX,
y: coords.pageY,
- height: fixedSize ? '' : coords.pageHeight,
- width: fixedSize ? '' : coords.pageWidth,
+ height: fixedSize ? 'auto' : coords.pageHeight,
+ width: fixedSize ? 'auto' : coords.pageWidth,
}}
+ maxWidth={fixedSize && $pageBounds?.width ? $pageBounds.width - coords.pageX : undefined}
bounds={`${PDF_VIEWER_PAGE_SELECTOR}[data-page-number="${field.pageNumber}"]`}
onDragStart={() => onFieldActivate?.()}
onResizeStart={() => onFieldActivate?.()}
diff --git a/packages/ui/primitives/document-flow/field-items-advanced-settings/checkbox-field.tsx b/packages/ui/primitives/document-flow/field-items-advanced-settings/checkbox-field.tsx
index 708f14927..85a1b979e 100644
--- a/packages/ui/primitives/document-flow/field-items-advanced-settings/checkbox-field.tsx
+++ b/packages/ui/primitives/document-flow/field-items-advanced-settings/checkbox-field.tsx
@@ -44,6 +44,9 @@ export const CheckboxFieldAdvancedSettings = ({
const [required, setRequired] = useState(fieldState.required ?? false);
const [validationLength, setValidationLength] = useState(fieldState.validationLength ?? 0);
const [validationRule, setValidationRule] = useState(fieldState.validationRule ?? '');
+ const [direction, setDirection] = useState<'vertical' | 'horizontal'>(
+ fieldState.direction ?? 'vertical',
+ );
const handleToggleChange = (field: keyof CheckboxFieldMeta, value: string | boolean) => {
const readOnly = field === 'readOnly' ? Boolean(value) : Boolean(fieldState.readOnly);
@@ -52,11 +55,14 @@ export const CheckboxFieldAdvancedSettings = ({
field === 'validationRule' ? String(value) : String(fieldState.validationRule);
const validationLength =
field === 'validationLength' ? Number(value) : Number(fieldState.validationLength);
+ const currentDirection =
+ field === 'direction' && String(value) === 'horizontal' ? 'horizontal' : 'vertical';
setReadOnly(readOnly);
setRequired(required);
setValidationRule(validationRule);
setValidationLength(validationLength);
+ setDirection(currentDirection);
const errors = validateCheckboxField(
values.map((item) => item.value),
@@ -65,6 +71,7 @@ export const CheckboxFieldAdvancedSettings = ({
required,
validationRule,
validationLength,
+ direction: currentDirection,
type: 'checkbox',
},
);
@@ -86,6 +93,7 @@ export const CheckboxFieldAdvancedSettings = ({
required,
validationRule,
validationLength,
+ direction: direction,
type: 'checkbox',
},
);
@@ -137,6 +145,29 @@ export const CheckboxFieldAdvancedSettings = ({
onChange={(e) => handleFieldChange('label', e.target.value)}
/>
</div>
+
+ <div className="mb-2">
+ <Label>
+ <Trans>Direction</Trans>
+ </Label>
+ <Select
+ value={fieldState.direction ?? 'vertical'}
+ onValueChange={(val) => handleToggleChange('direction', val)}
+ >
+ <SelectTrigger className="text-muted-foreground bg-background mt-2 w-full">
+ <SelectValue placeholder={_(msg`Select direction`)} />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value="vertical">
+ <Trans>Vertical</Trans>
+ </SelectItem>
+ <SelectItem value="horizontal">
+ <Trans>Horizontal</Trans>
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
<div className="flex flex-row items-center gap-x-4">
<div className="flex w-2/3 flex-col">
<Label>