Skip to content

chore: add more field types - #1141

Merged
Mythie merged 117 commits into
mainfrom
feat/more-field-types
Jul 18, 2024
Merged

Mythie merged 117 commits into
mainfrom
feat/more-field-types

Conversation

@catalinpit

@catalinpit catalinpit commented May 3, 2024 •

Copy link
Copy Markdown
Member

Description

What I've done:

  • Created an optional fieldMeta field of JSONB type in the Field model (prisma/schema.prisma). This way, we can store advanced configuration for each field. Also, the selected/chosen/entered value for each field is stored in the customText field.

  • Created schemas and types for fieldMeta.

  • Added the fieldMeta field in the appropriate schemas and types.

  • Moved the title and description (DocumentFlowFormContainerHeader) from edit-template page into each template step - add-template-settings.tsx, add-template-placeholder.tsx and add-template-fields.tsx. They have their own title and description. Exactly like it's done for the documents.

    • Why did I do that? So, the header and description from "Field Advanced settings" doesn't collide with the info for each step.
    • Also added the code for clearing the localStorage of fields' settings when the fields get saved in a template (edit-template.tsx)
  • Added the code for clearing the localStorage of fields' settings when the fields get saved in a document (edit-document.tsx).

  • Created a new file for each field's advanced settings (checkbox, number, dropdown, radio). Also updated the text field to include advanced settings.

    • Also added the validation for each field both on the frontend and backend. We have the following:
      • For the Text field - field-items-advanced-settings/text-field.tsx:
        • If the field has the readOnly and required checked at the same time, it will throw an error.
        • If the field is readOnly, it should have a value for the text field.
        • If the characterLimit is not a number, it will throw an error.
        • If the value entered by the user is over the characterLimit, it will throw an error.
      • For the Number field - field-items-advanced-settings/number-field.tsx:
        • The minValue can't be greater than the maxValue and vice-versa.
        • The value entered by the user can't be lower than the minValue and greater than the maxValue.
        • The field can't have the value field empty when the field is readOnly.
        • If the field has the readOnly and required checked at the same time, it will throw an error.
      • For the Radio field - field-items-advanced-settings/radio-field.tsx:
        • The radio field can't be required and readOnly at the same time.
        • If the field is readOnly, it should have at least one option.
      • For the Checkbox field - field-items-advanced-settings/checkbox-field.tsx:
        • The field can't be required and readOnly at the same time.
        • If the field is readOnly, it should have at least one option.
        • The checkbox options must match the validation rule (Select at least..., Select at most..., Select exactly...) and the validation length (1....10). So for example, if the validation is set to Select exactly 5, there should be at least 5 checkbox options.
      • For the Dropdown field - field-items-advanced-settings/dropdown-field.tsx:
        • The field can't be required and readOnly at the same time.
        • If the field is readOnly, it should have at least one option.
  • Created the field-item-advanced-settings.tsx component for the fields' advanced settings. The component renders the appropriate advanced settings form based on the field type, validates user input, and saves the field settings to local storage and triggers a callback function when the "Save" button is clicked.

  • Created a new file for each field for the signing page:

    • Updated the Text field to take into account the new advanced settings (sign/[token]/text-field.tsx).
      • The field also validates the data entered by the user:
        • If the field is required and the user tries to sign it without entering a value, it throws an error.
        • If the value entered by the user is greater than the character limit, it will also throw an errors.
      • If the field has the text value set by default and the field is not already inserted, the app will insert the field automatically when you visit the signing page.
    • Created the Radio field (sign/[token]/radio-field.tsx):
      • The user cannot sign a Radio field without choosing one option.
    • Created the Number field (sign/[token]/number.tsx):
      • The field also validates the data entered by the user:
        • It checks that the number matches the selected number format. If it doesn't, it throws an error.
        • If the field is required and the user doesn't enter a number, it throws an error.
        • If the user enters a value that is a number, it will throw an error.
        • If the value entered by the user is less than the minimum value, it throws an error.
        • If the value entered by the user is greater than the maximum value, it throws an error.
      • If the field has the value field set by default and the field is not already inserted, the app will insert the field automatically when you visit the signing page.
    • Created the Checkbox field (sign/[token]/checkbox-field.tsx):
      • If the Checkbox contains options that have the checked option set to true, those will be checked automatically.
      • If a validation rule & length is set, the user can't sign the field until the selected options match the validation.
    • Created the Dropdown field (sign/[token]/dropdown-field.tsx):
      • If the field has a default value set, it will automatically sign the field with that value when visiting the signing page.
    • If any of the fields is required, the field should either have a default value set or a value should be entered by the user.
    • If any of the fields is readonly, it should have a default value and the user shouldn't be able to change it.
  • All the validation for these fields are available on the backend as well:

  • Updated the d/[token]/sign-direct-template.tsx file to include all the new fields.

  • Added the new fields in the (signing)/sign/[token]/signing-page-view.tsx so they are visible and usable.

  • Modified the document audit log lib/types/document-audit-logs.ts to include all the new fields.

  • Modified the (signing)/sign/[token]/signing-field-container.tsx code so the Radio and Checkbox fields are clickable and work properly.

  • Created tRPC procedures for retrieving and updating a field - packages/trpc/server/field-router/router.ts.

  • Added colors for each recipient so it's easier to distinguish between them. The recipients and their associated fields will have the same color.

  • Added the FieldIcon component - primitives/document-flow/field-icon.tsx - to avoid repeating code.

  • Modified ui/primitives/document-flow/field-item.tsx so the fields have the same border color as the recipient.

  • Changed the code from the lib/server-only/pdf/insert-field-in-pdf.ts file to add a circle in front of the value from the radio field and an X in front of the values from the checkbox field. Also, the values from the checkbox field will be in a column on the signed document, each having an X in front.

  • Updated the Field component (ui/components/field/field.tsx) so the design doesn't break for checkbox and radio fields.

  • Updated ui/primitives/document-flow/add-fields.tsx and ui/primitives/template-flow/add-template-fields.tsx contain mostly changes for the color of the fields and recipients.

  • Created primitives/document-flow/advanced-fields/checkbox.tsx and primitives/document-flow/advanced-fields/radio.tsx to match the design from Figma. What these 2 components do is to display the fields and their options like in the image below.

CleanShot 2024-06-05 at 14 17 39

  • You'll notice the usage of substring, which is used to shorten the customText value which overflows and messes up the field's card design.

.... plus other smaller things.

What's left:

  1. Make the new fields work in the SPM mode (not necessary after our discussion)

  2. Cleanup the code.

  3. For another PR:

    • Date and Name fields configuration
    • Document zooming

Testing Performed

  • Text field inserted into a document
    • Inserted text without any advanced configuration
      • It should display the default text "T Add Text"
      • The user should be able to sign the field without any restrictions
    • Inserted text with advanced configuration
      • The field has a label set by the user and all the other configuration fields are empty
        • The field should display the label set by the user instead of "T Add Text"
        • The user should be able to sign the field without any restrictions
      • The field has a placeholder set by the user and all the other configuration fields are empty
        • The field should still display the default text "T Add Text"
        • The field should display the placeholder set by the user when the field is empty on the signing page
        • The user should be able to sign the field without any restrictions
      • The field has a label and a placeholder set by the user and all the other configuration fields are empty
        • The field should display the label set by the user
        • The field should display the placeholder set by the user when the field is empty on the signing page
        • The user should be able to sign the field without any restrictions
      • The field has a text value set by the user and all the other configuration fields are empty
        • The field should display the text value set by the user
        • The field should sign automatically when visiting the signing page
        • The user should be able to sign the field by using the text value entered in the advanced configuration or by changing it
      • The field has a label and a text value set by the user and all the other configuration fields are empty
        • The field should display the label value set by the user instead of "T Add Text" or instead of the text value
        • The field should sign automatically when visiting the signing page
        • The user should be able to sign the field by using the text value entered in the advanced configuration or by changing it
      • The field has a placeholder and a text value set by the user and all the other configuration fields are empty
        • The field should display the text value entered in the advanced configuration
        • The field should sign automatically when visiting the signing page
        • The field should display the placeholder set by the user when the field is empty on the signing page
        • The user should be able to sign the field by using the text value entered in the advanced configuration or by changing it
        • The field should display the text value on the signing page
      • The field has a label, a placeholder and a text value set by the user and all the other configuration fields are empty
        • The field should display the label set by the user
        • The field should sign automatically when visiting the signing page
        • The field should display the placeholder set by the user when the field is empty on the signing page
        • The user should be able to sign the field by using the text value entered in the advanced configuration or by changing it
        • The field should display the text value on the signing page
      • The field has a character limit set by the user and all the other configuration fields are empty or filled
        • The user shouldn't be able to enter more characters in the text field than the character limit when configuring the field
        • The field should be prefilled with the existing value on the signing page
        • The user should be able to replace the prefilled value with any value that doesn't exceed the character limit
        • The user shouldn't be able to sign the field if the character limit is exceeded
      • The field has the "Required" checkbox checked
        • The user shouldn't be able to make the field read-only when the "Required" checkbox is checked
        • The user shouldn't be able to sign the field without entering any text
        • The user should be able to sign the field after entering text
      • The field has the "Read-only" checkbox checked
        • The user shouldn't be able to make the field required when the "Read-only" checkbox is checked
        • The user shouldn't be able to save the field configuration without entering a text value
        • The field should display the text entered by the user if no label is set. Otherwise, it should display the label.
        • The user shouldn't be able to enter any text in the field
        • The field should sign automatically when visiting the signing page
      • The field has the "Required" and character limit set by the user
        • The user shouldn't be able to make the field read-only when the "Required" checkbox is checked
        • The user shouldn't be able to sign the field without entering any text
        • The user shouldn't be able to sign the field if the character limit is exceeded
        • The user should be able to sign the field after entering text
      • The field has the "Read-only" and character limit set by the user
        • The user shouldn't be able to make the field required when the "Read-only" checkbox is checked
        • The user shouldn't be able to save the field configuration without entering a text value
        • The field should display the text value if no label is set. Otherwise, it should display the label.
        • The user shouldn't be able to enter any text in the field
        • The field should sign automatically when visiting the signing page
      • The field has all the configuration fields filled
        • The field should display the label set by the user
        • The field should display the placeholder set by the user when the field is empty on the signing page
        • The user shouldn't be able to enter more characters in the text field than the character limit when configuring the field
        • The user shouldn't be able to sign the field if the character limit is exceeded
        • The user shouldn't be able to make the field read-only when the "Required" checkbox is checked
        • The user shouldn't be able to make the field required when the "Read-only" checkbox is checked
        • The user shouldn't be able to save the field configuration without entering a text value if the "Read-only" checkbox is checked
        • The user shouldn't be able to enter any text in the field if the "Read-only" checkbox is checked
        • The field should sign automatically when visiting the signing page if the "Read-only" checkbox is checked

Checklist

  • I have tested these changes locally and they work as expected.
  • I have added/updated tests that prove the effectiveness of these changes.
  • I have updated the documentation to reflect these changes, if applicable.
  • I have followed the project's coding style guidelines.
  • I have addressed the code review feedback from the previous submission, if applicable.

Summary by CodeRabbit

  • New Features
    • Introduced CheckboxField, DropdownField, NumberField, and RadioField components for document signing.
    • Added advanced settings components for various field types including checkbox, dropdown, number, radio, and text fields.
    • Implemented color styles and utilities for signer colors.
  • Enhancements
    • Updated SignatureField and NameField components with improved styling.
    • Enhanced SigningFieldContainer to handle multiple field types.
  • Bug Fixes
    • Adjusted document sealing logic to ensure proper status updates.
  • Chores
    • Updated turbo.json configuration for prebuild paths and caching.

@coderabbitai

coderabbitai Bot commented May 3, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The updates introduced new React components for handling various field types in a document signing application, including checkboxes, dropdowns, numbers, and radio buttons. Several files were modified to incorporate these new components, enhancing the functionality and user experience. Changes also included advanced settings for these fields, stylistic adjustments, and updates to form validation logic.

Changes

File/Path Change Summary
.../sign/[token]/checkbox-field.tsx Added CheckboxField component and CheckboxFieldProps type for handling checkbox interactions in document signing.
.../sign/[token]/dropdown-field.tsx Introduced DropdownField component and DropdownFieldProps type for managing dropdown field interactions.
.../sign/[token]/number-field.tsx Added NumberField component for number field interactions, updated various imports and exports, handled validation and UI updates.
.../sign/[token]/radio-field.tsx Introduced RadioField component for radio field interactions, including signing and unsigning logic.
.../sign/[token]/signature-field.tsx Updated the styling classes for different states of the SignatureField component.
.../sign/[token]/signing-field-container.tsx Modified field type handling and UI logic, added new functions for managing checkboxes and other field types.
.../sign/[token]/name-field.tsx Updated styling classes and text content for the NameField component.
.../document-flow/add-signature.tsx Enhanced AddSignatureFormPartial component to include validation checks for new field types.
.../document-flow/advanced-fields/checkbox.tsx Added CheckboxField component for rendering checkbox inputs with associated values and states.
.../document-flow/advanced-fields/radio.tsx Introduced RadioField component for rendering radio button groups based on field metadata.
.../document-flow/field-icon.tsx Added FieldIcon component for rendering icons based on field type.
.../document-flow/field-item.tsx Updated various imports and rendering logic for field types and recipient initials display.
.../field-items-advanced-settings/checkbox-field.tsx Introduced CheckboxFieldAdvancedSettings component for managing advanced settings for checkbox fields.
.../field-items-advanced-settings/dropdown-field.tsx Added DropdownFieldAdvancedSettings component for advanced dropdown field settings.
.../field-items-advanced-settings/number-field.tsx Introduced NumberFieldAdvancedSettings component for managing advanced settings for number fields.
.../field-items-advanced-settings/radio-field.tsx Added RadioFieldAdvancedSettings component for advanced radio field settings.
.../field-items-advanced-settings/text-field.tsx Added TextFieldAdvancedSettings component for text field advanced settings.
.../lib/signer-colors.ts Added color styles for signers, including functions to retrieve and use these styles.
.../server-only/document/send-document.tsx Removed document status update logic, now directly seals documents if no recipient actions remain.
turbo.json Removed specific paths under prebuild, set cache option to false.

Poem

On a digital doc where fields abound,
Checkboxes, radios, dropdowns now found.
Numbers dance with precision clear,
Signatures penned with style sincere.
A rabbit hops through lines of code,
Bringing ease to signing's heavy load.
✨📝 In harmony, the fields compose! ✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercel Bot commented May 3, 2024 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
prd-app 🔄 Building (Inspect) Visit Preview Jul 18, 2024 1:09pm
prd-docs ❌ Failed (Inspect) Jul 18, 2024 1:09pm
prd-marketing 🔄 Building (Inspect) Visit Preview Jul 18, 2024 1:09pm
stg-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 18, 2024 1:09pm
stg-docs ❌ Failed (Inspect) Jul 18, 2024 1:09pm
stg-marketing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 18, 2024 1:09pm

@github-actions github-actions Bot added the 🚨 migrations 🚨 Be advised: PR contains database migrations - Auto-Generated by GitHub Actions on raising a PR label May 3, 2024
'pointer-events-none': passive,
'pointer-events-none opacity-75': disabled,
className={cn('group z-20', {
'active:pointer-events-none': passive,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

couldn't think of a better way of making the hover work on passive/disabled fields. happy to hear suggestions

Mythie
Mythie previously approved these changes Jul 18, 2024

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 42

Outside diff range, codebase verification and nitpick comments (4)
packages/ui/primitives/document-flow/field-icon.tsx (1)

59-63: Enhance accessibility by adding aria-label.

Add aria-label to the div for better accessibility.

- <div className="text-field-card-foreground flex items-center justify-center gap-x-1.5 text-sm">
+ <div className="text-field-card-foreground flex items-center justify-center gap-x-1.5 text-sm" aria-label={label}>
packages/lib/server-only/document/seal-document.ts (1)

121-121: Add a comment explaining the re-flattening step.

Add a comment to explain why the re-flattening step is necessary to handle fields that create arcoFields.

+ // Re-flatten the document to handle fields that create arcoFields.
flattenForm(doc);
packages/ui/lib/signer-colors.ts (1)

91-95: Enhance readability by adding a comment.

Add a comment to explain the index calculation logic.

+ // Calculate the index for the signer colors and ensure it wraps around if it exceeds the length.
const key = AVAILABLE_SIGNER_COLORS[index % AVAILABLE_SIGNER_COLORS.length];
packages/ui/primitives/template-flow/add-template-fields.tsx (1)

Line range hint 286-366:
Optimize onMouseMove and onMouseClick functions.

The onMouseMove and onMouseClick functions can be optimized to reduce redundancy and improve readability.

const onMouseMove = useCallback(
  (event: MouseEvent) => {
    const isWithinBounds = isWithinPageBounds(
      event,
      PDF_VIEWER_PAGE_SELECTOR,
      fieldBounds.current.width,
      fieldBounds.current.height,
    );

    setIsFieldWithinBounds(isWithinBounds);

    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, PDF_VIEWER_PAGE_SELECTOR);

    if (!$page || !isWithinPageBounds(event, PDF_VIEWER_PAGE_SELECTOR, fieldBounds.current.width, fieldBounds.current.height)) {
      setSelectedField(null);
      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,
      signerId: selectedSigner.id,
      signerToken: selectedSigner.token ?? '',
      fieldMeta: undefined,
    });

    setIsFieldWithinBounds(false);
    setSelectedField(null);
  },
  [append, isWithinPageBounds, selectedField, selectedSigner, getPage],
);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c4ef522 and 5a01441.

Files selected for processing (21)
  • apps/web/src/app/(recipient)/d/[token]/sign-direct-template.tsx (3 hunks)
  • apps/web/src/app/(signing)/sign/[token]/checkbox-field.tsx (1 hunks)
  • apps/web/src/app/(signing)/sign/[token]/number-field.tsx (1 hunks)
  • apps/web/src/app/(signing)/sign/[token]/radio-field.tsx (1 hunks)
  • apps/web/src/app/(signing)/sign/[token]/signature-field.tsx (2 hunks)
  • apps/web/src/app/(signing)/sign/[token]/signing-field-container.tsx (4 hunks)
  • apps/web/src/app/(signing)/sign/[token]/signing-page-view.tsx (2 hunks)
  • apps/web/src/app/(signing)/sign/[token]/text-field.tsx (7 hunks)
  • packages/lib/server-only/document/seal-document.ts (1 hunks)
  • packages/lib/server-only/pdf/insert-field-in-pdf.ts (3 hunks)
  • packages/ui/components/field/field.tsx (4 hunks)
  • packages/ui/lib/signer-colors.ts (1 hunks)
  • packages/ui/primitives/checkbox.tsx (1 hunks)
  • packages/ui/primitives/document-flow/add-fields.tsx (11 hunks)
  • packages/ui/primitives/document-flow/advanced-fields/checkbox.tsx (1 hunks)
  • packages/ui/primitives/document-flow/advanced-fields/radio.tsx (1 hunks)
  • packages/ui/primitives/document-flow/field-icon.tsx (1 hunks)
  • packages/ui/primitives/document-flow/field-item.tsx (5 hunks)
  • packages/ui/primitives/template-flow/add-template-fields.tsx (8 hunks)
  • packages/ui/styles/theme.css (1 hunks)
  • packages/ui/tsconfig.json (1 hunks)
Files skipped from review due to trivial changes (1)
  • packages/ui/styles/theme.css
Additional context used
Biome
packages/ui/primitives/document-flow/field-item.tsx

[error] 141-141: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Additional comments not posted (62)
packages/ui/tsconfig.json (1)

3-10: LGTM! The changes to the include and exclude arrays are appropriate.

The include array now includes the current directory, and the exclude array excludes common build directories (dist, build, and node_modules).

packages/ui/primitives/checkbox.tsx (1)

19-19: LGTM! The changes to the CSS class names improve visual feedback.

Adding a background color when the checkbox is checked enhances the user experience.

packages/ui/primitives/document-flow/advanced-fields/checkbox.tsx (1)

1-13: LGTM! The imports and type definitions are appropriate.

The file imports necessary types and components and defines the CheckboxFieldProps type correctly.

packages/ui/primitives/document-flow/advanced-fields/radio.tsx (1)

1-13: LGTM! The imports and type definitions are appropriate.

The file imports necessary types and components and defines the RadioFieldProps type correctly.

packages/ui/primitives/document-flow/field-icon.tsx (4)

26-31: Enhance readability by destructuring props.

Destructure the props in the function parameter to enhance readability.

- export const FieldIcon = ({ fieldMeta, type, signerEmail, fontCaveatClassName }: FieldIconProps) => {
+ export const FieldIcon = ({ fieldMeta, type, signerEmail, fontCaveatClassName }: FieldIconProps) => {

Likely invalid or redundant comment.


1-2: Optimize imports.

Consider importing only the required icons to reduce the bundle size.

- import { CalendarDays, CheckSquare, ChevronDown, Disc, Hash, Mail, Type, User } from 'lucide-react';
+ import { Mail, User, CalendarDays, Type, Hash, Disc, CheckSquare, ChevronDown } from 'lucide-react';

Likely invalid or redundant comment.


15-24: Ensure correctness of icon mappings.

Verify that the icon mappings in fieldIcons are correct and consistent with the field types.

Verification successful

Ensure correctness of icon mappings.

The icon mappings in the fieldIcons object in field-icon.tsx appear to be correct and consistent with the field types. Each FieldType is associated with an appropriate icon:

  • FieldType.EMAIL -> Mail
  • FieldType.NAME -> User
  • FieldType.DATE -> CalendarDays
  • FieldType.TEXT -> Type
  • FieldType.NUMBER -> Hash
  • FieldType.RADIO -> Disc
  • FieldType.CHECKBOX -> CheckSquare
  • FieldType.DROPDOWN -> ChevronDown

No discrepancies were found in the icon mappings.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of icon mappings.

# Test: Search for the field types and their corresponding icons. Expect: Correct mappings.
rg --type tsx -A 5 $'FieldType.'

Length of output: 59


Script:

#!/bin/bash
# Description: Verify the correctness of icon mappings.

# Find all TypeScript files and search for FieldType references within them.
fd -e ts -e tsx | xargs rg 'FieldType'

Length of output: 34164


8-13: Ensure proper handling of optional props.

The signerEmail and fontCaveatClassName props are optional. Ensure that they are handled correctly in the component.

Verification successful

Optional props are handled correctly.

The FieldIcon component correctly handles the optional props signerEmail and fontCaveatClassName. The fontCaveatClassName is used conditionally within the cn function, ensuring it does not affect the class names if not provided. The signerEmail prop is passed down as expected.

  • fontCaveatClassName is conditionally used within the cn function.
  • signerEmail is passed down as a prop but not directly used in the JSX.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `FieldIcon` to ensure optional props are handled correctly.

# Test: Search for the component usage. Expect: Proper handling of optional props.
rg --type tsx -A 5 $'<FieldIcon'

Length of output: 61


Script:

#!/bin/bash
# Description: Verify the usage of `FieldIcon` to ensure optional props are handled correctly.

# Find all .tsx files and search for the usage of <FieldIcon> component.
fd -e tsx -x rg '<FieldIcon' {}

Length of output: 454


Script:

#!/bin/bash
# Description: Verify the implementation of `FieldIcon` to ensure optional props are handled correctly.

# Find the implementation of the FieldIcon component.
fd -e tsx -x rg 'const FieldIcon' {}

Length of output: 68


Script:

#!/bin/bash
# Description: Extract the full implementation of the `FieldIcon` component to verify handling of optional props.

# Extract the full implementation of the FieldIcon component.
fd -e tsx -x rg -A 50 'export const FieldIcon = ({' {}

Length of output: 56302


Script:

#!/bin/bash
# Description: Extract the full implementation of the `FieldIcon` component to verify handling of optional props.

# Extract the full implementation of the FieldIcon component.
fd -e tsx -x rg -A 100 'export const FieldIcon = \(\{' {}

Length of output: 1231

packages/ui/components/field/field.tsx (3)

82-91: Ensure correctness of style calculations.

Verify that the style calculations for the field container are correct and consistent with the field properties.

Verification successful

The style calculations in field.tsx are correct and consistent with the field properties.

  • The styles for top, left, height, and width are correctly set based on the coords object.
  • The conditional application of height and width when isCheckboxOrRadioField is false is correctly implemented.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of style calculations.

# Test: Search for the field properties and their corresponding styles. Expect: Correct styles.
rg --type tsx -A 5 $'style='

Length of output: 55


Script:

#!/bin/bash
# Description: Verify the correctness of style calculations.

# Test: Search for the field properties and their corresponding styles. Expect: Correct styles.
rg --type-add 'tsx:*.{ts,tsx}' -t tsx -A 5 'style='

Length of output: 14283


125-137: Ensure correctness of useMemo hooks.

Verify that the useMemo hooks are set up correctly and provide the expected performance benefits.

Verification successful

Ensure correctness of useMemo hooks.

The useMemo hooks in packages/ui/components/field/field.tsx (lines 125-137) are correctly set up with appropriate dependencies. They are used to memoize values that depend on specific state variables, thus improving performance by avoiding unnecessary recalculations.

  • parsedField depends on field.fieldMeta.
  • isCheckboxOrRadio depends on parsedField.
  • cardClassNames depends on field, parsedField, isValidating, isCheckboxOrRadio, and cardClassName.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of useMemo hooks.

# Test: Search for the useMemo hooks and their corresponding dependencies. Expect: Correct setup and dependencies.
rg --type tsx -A 5 $'useMemo('

Length of output: 98


Script:

#!/bin/bash
# Description: Verify the correctness of useMemo hooks.

# Test: Search for the useMemo hooks and their corresponding dependencies. Expect: Correct setup and dependencies.
rg --type tsx -A 5 'useMemo\('

Length of output: 60


Script:

#!/bin/bash
# Description: Verify the correctness of useMemo hooks.

# Test: Add `tsx` as a recognized file type and search for the useMemo hooks and their corresponding dependencies. Expect: Correct setup and dependencies.
rg --type-add 'tsx:*.{ts,tsx}' --type tsx -A 5 'useMemo\('

Length of output: 20983


27-70: Ensure correctness of generated class names.

Verify that the generated class names are correct and consistent with the field properties and validation status.

packages/lib/server-only/document/seal-document.ts (1)

120-122: Ensure correctness of the re-flattening step.

Verify that the re-flattening step is correctly implemented and handles fields that create arcoFields.

Verification successful

The re-flattening step appears to be correctly implemented.

The flattenForm function, along with the flattenWidget function, correctly handles the process of flattening fields and their widgets, ensuring that the document is properly re-flattened after inserting fields.

  • flattenForm function: packages/lib/server-only/pdf/flatten-form.ts
  • flattenWidget function: packages/lib/server-only/pdf/flatten-form.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the re-flattening step.

# Test: Search for the re-flattening logic and its corresponding implementation. Expect: Correct implementation.
rg --type ts $'flattenForm'

Length of output: 371


Script:

#!/bin/bash
# Extract the implementation of the flattenForm function from the specified file
ast-grep --lang typescript --pattern $'export const flattenForm = (document: PDFDocument) => {
  $$$
}' packages/lib/server-only/pdf/flatten-form.ts

Length of output: 1347


Script:

#!/bin/bash
# Extract the implementation of the flattenWidget function to verify its handling of arcoFields
ast-grep --lang typescript --pattern $'const flattenWidget = (document: PDFDocument, field: PDFField, widget: PDFWidget) => {
  $$$
}' 

Length of output: 135


Script:

#!/bin/bash
# Search for the definition of the flattenWidget function across the entire codebase
rg 'flattenWidget' -A 10

Length of output: 1467


Script:

#!/bin/bash
# Extract the complete implementation of the flattenWidget function from the specified file
ast-grep --lang typescript --pattern $'const flattenWidget = (document: PDFDocument, field: PDFField, widget: PDFWidgetAnnotation) => {
  $$$
}' packages/lib/server-only/pdf/flatten-form.ts

Length of output: 2401

packages/ui/lib/signer-colors.ts (2)

91-95: Ensure correctness of index calculation.

Verify that the index calculation for the signer colors is correct and handles edge cases.

Verification successful

The index calculation in useSignerColors is correct and handles edge cases appropriately.

  • The function defaults to 0 when the index is undefined or -1, ensuring safe array access.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of index calculation.

# Test: Search for the index calculation logic and its corresponding usage. Expect: Correct calculation.
rg --type ts $'useSignerColors'

Length of output: 633


Script:

#!/bin/bash
# Description: Verify the correctness of index calculation by checking the definitions and usages of recipientIndex and the argument passed to useSignerColors in add-fields.tsx.

# Search for the definition and usage of recipientIndex in field-item.tsx
rg 'recipientIndex' packages/ui/primitives/document-flow/field-item.tsx -A 5

# Search for the argument passed to useSignerColors in add-fields.tsx
rg 'useSignerColors' packages/ui/primitives/document-flow/add-fields.tsx -A 5

Length of output: 1250


6-78: Ensure correctness of defined styles.

Verify that the defined styles for each signer color are correct and consistent.

apps/web/src/app/(signing)/sign/[token]/signing-field-container.tsx (4)

5-6: Imports look good.

The added imports for X and ZFieldMetaSchema are necessary for the new functionality.


41-42: Function signature and enum changes look good.

The changes to the onRemove function signature and the expanded type enum are necessary for the new field types.


58-60: Field metadata parsing looks good.

The introduction of parsedFieldMeta and readOnlyField variables is necessary to handle field metadata and read-only state.


112-119: Checkbox values clearing logic looks good.

The onClearCheckBoxValues function is necessary for handling the new checkbox field type.

apps/web/src/app/(signing)/sign/[token]/signing-page-view.tsx (5)

7-13: Imports look good.

The added imports for field meta types are necessary for handling the new field types.


25-32: Imports look good.

The added imports for new field components are necessary for rendering the new field types.


116-122: Text field rendering logic looks good.

The logic correctly handles the text field with metadata parsing.


123-150: Rendering logic for new field types looks good.

The logic correctly handles the number, radio, checkbox, and dropdown fields with metadata parsing.


7-13: Rendering logic for new field types looks good.

The logic correctly handles the new field types.

apps/web/src/app/(signing)/sign/[token]/radio-field.tsx (9)

1-23: Imports look good.

The added imports for necessary modules and types are necessary for the functionality of the radio field.


27-32: Type definition looks good.

The type definition correctly specifies the props for the RadioField component.


34-44: State management and parsing logic look good.

The state management and parsing logic correctly handle the field metadata.


49-57: TRPC mutations look good.

The TRPC mutations correctly handle the signing and removing of the field.


59-63: Auto-sign logic looks good.

The logic correctly determines if the field should be auto-signed.


65-102: Sign field logic looks good.

The onSign function correctly handles the signing of the field.


104-129: Remove field logic looks good.

The onRemove function correctly handles the removal of the field.


131-133: Option selection handler looks good.

The handler correctly updates the selected option state.


145-189: Rendering logic looks good.

The rendering logic correctly handles the radio field.

apps/web/src/app/(signing)/sign/[token]/signature-field.tsx (2)

193-193: Text styling for empty signature state looks good.

The changes enhance the visual presentation of the signature field.


202-202: Sanitize dynamic content to prevent XSS vulnerabilities.

packages/ui/primitives/document-flow/field-item.tsx (12)

3-3: LGTM! Added necessary hooks.

The addition of useMemo and useRef hooks from 'react' is appropriate for the new logic introduced in the component.


10-10: LGTM! Added necessary import for pattern matching.

The addition of match from 'ts-pattern' is appropriate for the new logic introduced in the component.


13-14: LGTM! Added necessary imports for field meta schemas.

The imports for TFieldMetaSchema, ZCheckboxFieldMeta, and ZRadioFieldMeta are necessary for handling advanced field settings.


16-20: LGTM! Added necessary imports for signer colors and advanced fields.

The imports for useSignerColors, CheckboxField, RadioField, and FieldIcon are appropriate for the new logic introduced in the component.


25-30: LGTM! Added font configuration.

The fontCaveat constant is correctly configured using the Caveat font from 'next/font/google'.


41-43: LGTM! Added new props for advanced settings and recipient index.

The new props onAdvancedSettings, recipientIndex, and hideRecipients are correctly added to FieldItemProps.


66-67: LGTM! Added state for settings activation and element reference.

The new state settingsActive and the reference $el are correctly added for handling advanced settings and click events.


153-153: LGTM! Added logic for fixed size.

The fixedSize constant is correctly added based on the values of checkbox and radio fields.


207-221: LGTM! Added logic for rendering recipient initials.

The logic for rendering recipient initials is correctly added, but ensure that the hideRecipients prop is used appropriately.


184-193: Ensure proper handling of click events on the field.

The click event handler for the field correctly toggles the settingsActive state, but ensure that this logic does not interfere with other components.

Verification successful

Verification Successful: Proper handling of click events on the field.

The setSettingsActive state is defined and used exclusively within the field-item.tsx file, ensuring that the click event handler logic is isolated and does not interfere with other components.

  • packages/ui/primitives/document-flow/field-item.tsx
    • const [settingsActive, setSettingsActive] = useState(false);
    • setSettingsActive(false);
    • setSettingsActive((prev) => !prev);
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the handling of click events on the field.

# Test: Search for the usage of click event handlers in the codebase. Expect: Proper usage within the component.
rg --type tsx $'onClick'

Length of output: 51


Script:

#!/bin/bash
# Description: Verify the handling of click events on the field.

# Find all .tsx files and search for onClick handlers within those files.
fd -e tsx -x rg 'onClick' {}

Length of output: 14715


Script:

#!/bin/bash
# Description: Verify the scope and usage of setSettingsActive to ensure it does not interfere with other components.

# Search for the definition and usage of setSettingsActive in the codebase.
rg 'setSettingsActive'

Length of output: 319


5-7: Ensure correct usage of imported icons and fonts.

The imports from 'next/font/google' and 'lucide-react' are correct, but ensure that the Caveat font and Settings2 icon are used appropriately within the component.

Verification successful

Verified Usage of Imported Icons and Fonts

The Caveat font and Settings2 icon are used appropriately within the field-item.tsx component.

  • Caveat font is assigned to fontCaveat and used as fontCaveat.className.
  • Settings2 icon is used within a JSX element with a class name for styling.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of imported icons and fonts.

# Test: Search for the usage of `Caveat` and `Settings2` in the codebase. Expect: Proper usage within the component.
rg --type tsx $'Caveat|Settings2'

Length of output: 62


Script:

#!/bin/bash
# Description: Verify the usage of imported icons and fonts.

# Test: Search for the usage of `Caveat` and `Settings2` in the .ts and .tsx files. Expect: Proper usage within the component.
rg 'Caveat|Settings2' --glob '*.ts' --glob '*.tsx' -A 3

Length of output: 13184


118-122: Ensure proper handling of click events outside the field.

The handleClickOutsideField function correctly handles click events outside the field, but ensure that this logic does not interfere with other components.

Verification successful

Proper handling of click events outside the field is ensured.

The handleClickOutsideField function is correctly managed within a useEffect hook, ensuring that it does not interfere with other components.

  • The event listener is added and removed in the useEffect hook based on the settingsActive dependency.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the handling of click events outside the field.

# Test: Search for the usage of `handleClickOutsideField` in the codebase. Expect: Proper usage within the component.
rg --type tsx $'handleClickOutsideField'

Length of output: 67


Script:

#!/bin/bash
# Description: Verify the handling of click events outside the field.

# Test: Search for the usage of `handleClickOutsideField` in the codebase. Expect: Proper usage within the component.
rg 'handleClickOutsideField'

Length of output: 388


Script:

#!/bin/bash
# Description: Verify the handling of click events outside the field.

# Test: Search for lifecycle methods in the `field-item.tsx` file to ensure proper management of the event listener.
rg 'useEffect|componentDidMount|componentWillUnmount' packages/ui/primitives/document-flow/field-item.tsx -A 10

Length of output: 1226

packages/lib/server-only/pdf/insert-field-in-pdf.ts (4)

4-4: LGTM! Added necessary import for pattern matching.

The addition of P from 'ts-pattern' is appropriate for the new logic introduced in the function.


16-17: LGTM! Added necessary imports for field meta schemas.

The imports for ZCheckboxFieldMeta and ZRadioFieldMeta are necessary for handling advanced field settings.


82-125: LGTM! Added pattern matching for signature fields.

The pattern matching logic for signature fields is correctly added and ensures proper handling of signature images.


199-237: LGTM! Added pattern matching for other field types.

The pattern matching logic for other field types is correctly added and ensures proper handling of text fields.

apps/web/src/app/(signing)/sign/[token]/checkbox-field.tsx (2)

3-3: LGTM! Added necessary hooks.

The addition of useTransition hook from 'react' is appropriate for the new logic introduced in the component.


12-12: LGTM! Added necessary import for checkbox field meta schema.

The import for ZCheckboxFieldMeta is necessary for handling advanced field settings.

apps/web/src/app/(signing)/sign/[token]/text-field.tsx (5)

7-7: LGTM! Added necessary import for icons and validation.

The imports for Loader, Type, and validateTextField are appropriate for the new logic introduced in the component.


13-13: LGTM! Added necessary import for text field meta schema.

The import for ZTextFieldMeta is necessary for handling advanced field settings.


41-44: LGTM! Added initial errors state.

The initialErrors state is correctly added for managing validation errors.


282-286: Ensure character limit is not displayed when it is zero.

The character limit should not be displayed when it is zero.

Example:

- {parsedFieldMeta?.characterLimit !== undefined && parsedFieldMeta?.characterLimit > 0 && !userInputHasErrors && (
+ {parsedFieldMeta?.characterLimit > 0 && !userInputHasErrors && (

Likely invalid or redundant comment.


198-205: Add dependencies to the useEffect hook.

The useEffect hook for auto-signing fields should include dependencies to avoid unintended re-executions.

Example:

- }, []);
+ }, [shouldAutoSignField, executeActionAuthProcedure, onSign]);

Likely invalid or redundant comment.

packages/ui/primitives/document-flow/add-fields.tsx (1)

7-19: Consider optimizing import statements.

You can combine multiple imports from 'lucide-react' into a single import statement to improve readability and potentially reduce the size of the import statements.
[refactor_suggestion

packages/ui/primitives/template-flow/add-template-fields.tsx (4)

492-494: LGTM!

The function handleAdvancedSettings is straightforward and does not have any issues.


498-508: LGTM!

The component FieldAdvancedSettings integrates well with the existing code and provides a clear structure for handling advanced settings.


543-544: Use optional chaining for recipientColorClasses.

Use optional chaining to handle cases where recipientColorClasses might be undefined.

-  const colorClass = recipient ? recipientColorClasses.get(recipient.id) : '';
+  const colorClass = recipient ? recipientColorClasses?.get(recipient.id) : '';

Likely invalid or redundant comment.


7-17: LGTM! Verify the usage of imported entities.

The import statements are consistent with the file's functionality and the added components and hooks.

However, ensure that all imported entities are used correctly in the code.

Also applies to: 22-27, 53-54

Verification successful

Let's correct the file type in the rg command and re-run the script to verify the usage of the imported entities.


Imports verified and used correctly.

The imported entities useRecipientColorClasses, useSelectedSignerStyles, ZFieldMetaSchema, FieldMeta, FieldFormType, and FieldAdvancedSettings are all utilized within the codebase as expected.

  • useRecipientColorClasses is used on line 232.
  • useSelectedSignerStyles is used on line 292.
  • ZFieldMetaSchema is used on lines 289 and 312.
  • FieldMeta is used on line 309.
  • FieldFormType is used on lines 225 and 227.
  • FieldAdvancedSettings is used on line 413.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of imported entities.

# Test: Search for the usage of imported entities. Expect: Only occurances of the imported entities.
rg --type typescript -A 5 $'useRecipientColorClasses|useSelectedSignerStyles|ZFieldMetaSchema|FieldMeta|FieldFormType|FieldAdvancedSettings'

Length of output: 176


Script:

#!/bin/bash
# Description: Verify the usage of imported entities.

# Test: Search for the usage of imported entities. Expect: Only occurrences of the imported entities.
rg --type ts -A 5 $'useRecipientColorClasses|useSelectedSignerStyles|ZFieldMetaSchema|FieldMeta|FieldFormType|FieldAdvancedSettings'

Length of output: 130503

Comment on lines +15 to +47
export const CheckboxField = ({ field }: CheckboxFieldProps) => {
let parsedFieldMeta: TCheckboxFieldMeta | undefined = undefined;

if (field.fieldMeta) {
parsedFieldMeta = ZCheckboxFieldMeta.parse(field.fieldMeta);
}

if (parsedFieldMeta && (!parsedFieldMeta.values || parsedFieldMeta.values.length === 0)) {
return (
<FieldIcon fieldMeta={field.fieldMeta} type={field.type} signerEmail={field.signerEmail} />
);
}

return (
<div className='flex flex-col gap-y-2'>
{!parsedFieldMeta?.values ? (
<FieldIcon fieldMeta={field.fieldMeta} type={field.type} signerEmail={field.signerEmail} />
) : (
parsedFieldMeta.values.map((item: { value: string; checked: boolean }, index: number) => (
<div key={index} className='flex items-center gap-x-1.5'>
<Checkbox
className="h-4 w-4"
checkClassName="text-white"
id={`checkbox-${index}`}
checked={item.checked}
/>
<Label htmlFor={`checkbox-${index}`}>{item.value}</Label>
</div>
))
)}
</div>
);
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well-implemented CheckboxField component.

The component handles fieldMeta and dynamically renders based on the metadata. Ensure that the component's behavior is consistent across different browsers and devices. Additionally, consider adding unit tests to cover various fieldMeta configurations.

Would you like me to help with writing these unit tests?

Comment on lines +15 to +49
export const RadioField = ({ field }: RadioFieldProps) => {
let parsedFieldMeta: TRadioFieldMeta | undefined = undefined;

if (field.fieldMeta) {
parsedFieldMeta = ZRadioFieldMeta.parse(field.fieldMeta);
}

if (parsedFieldMeta && (!parsedFieldMeta.values || parsedFieldMeta.values.length === 0)) {
return (
<FieldIcon fieldMeta={field.fieldMeta} type={field.type} signerEmail={field.signerEmail} />
);
}

return (
<div className='flex flex-col gap-y-2'>
{!parsedFieldMeta?.values ? (
<FieldIcon fieldMeta={field.fieldMeta} type={field.type} signerEmail={field.signerEmail} />
) : (
<RadioGroup>
{parsedFieldMeta.values?.map((item, index) => (
<div key={index} className="flex items-center gap-x-1.5">
<RadioGroupItem
className="pointer-events-none"
value={item.value}
id={`option-${index}`}
checked={item.checked}
/>
<Label htmlFor={`option-${index}`}>{item.value}</Label>
</div>
))}
</RadioGroup>
)}
</div>
);
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well-implemented RadioField component.

The component handles fieldMeta and dynamically renders based on the metadata. Ensure comprehensive testing, especially for edge cases where fieldMeta might be malformed or missing.

Would you like assistance in setting up tests for these edge cases?

Comment on lines +121 to +128
<div className={cn(type === 'Checkbox' ? 'group' : '')}>
<FieldRootContainer field={field}>
{!field.inserted && !loading && !readOnlyField && (
<button
type="submit"
className="absolute inset-0 z-10 h-full w-full rounded-md border"
onClick={async () => handleInsertField()}
/>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change button type to prevent unintended form submissions.

The button should have type="button" to prevent unintended form submissions.

- <button
-   type="submit"
+ <button
+   type="button"
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<div className={cn(type === 'Checkbox' ? 'group' : '')}>
<FieldRootContainer field={field}>
{!field.inserted && !loading && !readOnlyField && (
<button
type="submit"
className="absolute inset-0 z-10 h-full w-full rounded-md border"
onClick={async () => handleInsertField()}
/>
<button
type="button"
className="absolute inset-0 z-10 h-full w-full rounded-md border"
onClick={async () => handleInsertField()}
/>

Comment on lines +32 to +42
if (type === 'SIGNATURE' || type === 'FREE_SIGNATURE') {
return (
<div
className={cn(
'text-field-card-foreground flex items-center justify-center gap-x-1 text-xl',
fontCaveatClassName,
)}
>
Signature
</div>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplify conditional rendering for signature types.

The conditional rendering for signature types can be simplified for better readability.

- if (type === 'SIGNATURE' || type === 'FREE_SIGNATURE') {
+ if (['SIGNATURE', 'FREE_SIGNATURE'].includes(type)) {
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (type === 'SIGNATURE' || type === 'FREE_SIGNATURE') {
return (
<div
className={cn(
'text-field-card-foreground flex items-center justify-center gap-x-1 text-xl',
fontCaveatClassName,
)}
>
Signature
</div>
);
if (['SIGNATURE', 'FREE_SIGNATURE'].includes(type)) {
return (
<div
className={cn(
'text-field-card-foreground flex items-center justify-center gap-x-1 text-xl',
fontCaveatClassName,
)}
>
Signature
</div>
);

Comment on lines +197 to +202
useEffect(() => {
if (!showRadioModal) {
setLocalNumber(parsedFieldMeta?.value ? String(parsedFieldMeta.value) : '0');
setErrors(initialErrors);
}
}, [showRadioModal]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize useEffect dependency array.

The useEffect dependency array can be optimized by including only the necessary dependencies.

- useEffect(() => {
-   if (!showRadioModal) {
-     setLocalNumber(parsedFieldMeta?.value ? String(parsedFieldMeta.value) : '0');
-     setErrors(initialErrors);
-   }
- }, [showRadioModal]);
+ useEffect(() => {
+   if (!showRadioModal) {
+     setLocalNumber(parsedFieldMeta?.value ? String(parsedFieldMeta.value) : '0');
+     setErrors(initialErrors);
+   }
+ }, [showRadioModal, parsedFieldMeta, initialErrors]);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
if (!showRadioModal) {
setLocalNumber(parsedFieldMeta?.value ? String(parsedFieldMeta.value) : '0');
setErrors(initialErrors);
}
}, [showRadioModal]);
useEffect(() => {
if (!showRadioModal) {
setLocalNumber(parsedFieldMeta?.value ? String(parsedFieldMeta.value) : '0');
setErrors(initialErrors);
}
}, [showRadioModal, parsedFieldMeta, initialErrors]);

Comment on lines +61 to +62
const parsedFieldMeta = field.fieldMeta ? ZTextFieldMeta.parse(field.fieldMeta) : null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor to handle potential fieldMeta parsing errors.

Proper error handling for parsing operations is crucial to prevent application crashes and improve user experience by providing meaningful error messages.

Example:

- const parsedFieldMeta = field.fieldMeta ? ZTextFieldMeta.parse(field.fieldMeta) : null;
+ let parsedFieldMeta;
+ try {
+   parsedFieldMeta = field.fieldMeta ? ZTextFieldMeta.parse(field.fieldMeta) : null;
+ } catch (error) {
+   console.error('Failed to parse field metadata:', error);
+   toast({
+     title: 'Error',
+     description: 'Failed to parse field settings.',
+     variant: 'destructive',
+   });
+   return; // Optionally return or handle error further depending on UX requirements.
+ }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const parsedFieldMeta = field.fieldMeta ? ZTextFieldMeta.parse(field.fieldMeta) : null;
let parsedFieldMeta;
try {
parsedFieldMeta = field.fieldMeta ? ZTextFieldMeta.parse(field.fieldMeta) : null;
} catch (error) {
console.error('Failed to parse field metadata:', error);
toast({
title: 'Error',
description: 'Failed to parse field settings.',
variant: 'destructive',
});
return; // Optionally return or handle error further depending on UX requirements.
}

Comment on lines +94 to 97
<div className={cn('absolute', className)} style={style}>
{children}
</div>,
document.body,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enhance readability by destructuring props.

Destructure the props in the function parameter to enhance readability.

- <div className={cn('absolute', className)} style={style}>
+ <div className={cn('absolute', className)} style={style}>

Committable suggestion was skipped due to low confidence.

Comment on lines +34 to +44
const baseClasses = 'field-card-container relative z-20 h-full w-full transition-all';

const insertedClasses =
'bg-documenso/20 border-documenso ring-documenso-200 ring-offset-documenso-200 ring-2 ring-offset-2 dark:shadow-none';
const nonRequiredClasses =
'border-yellow-300 shadow-none ring-2 ring-yellow-100 ring-offset-2 ring-offset-yellow-100 dark:border-2';
const validatingClasses = 'border-orange-300 ring-1 ring-orange-300';
const requiredClasses =
'border-red-500 shadow-none ring-2 ring-red-200 ring-offset-2 ring-offset-red-200 hover:text-red-500';
const requiredCheckboxRadioClasses = 'border-dashed border-red-500';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplify class name generation for checkbox or radio fields.

The class name generation for checkbox or radio fields can be simplified for better readability.

- if (checkBoxOrRadio) {
-   return cn(
-     {
-       [insertedClasses]: field.inserted,
-       'ring-offset-yellow-200 border-dashed border-yellow-300 ring-2 ring-yellow-200 ring-offset-2 dark:shadow-none':
-         !field.inserted && !parsedField?.required,
-       'shadow-none': !field.inserted,
-       [validatingClasses]: !field.inserted && isValidating,
-       [requiredCheckboxRadioClasses]: !field.inserted && parsedField?.required,
-     },
-     cardClassName,
-   );
- }
+ if (checkBoxOrRadio) {
+   return cn({
+     [insertedClasses]: field.inserted,
+     'ring-offset-yellow-200 border-dashed border-yellow-300 ring-2 ring-yellow-200 ring-offset-2 dark:shadow-none':
+       !field.inserted && !parsedField?.required,
+     'shadow-none': !field.inserted,
+     [validatingClasses]: !field.inserted && isValidating,
+     [requiredCheckboxRadioClasses]: !field.inserted && parsedField?.required,
+   }, cardClassName);
+ }

Committable suggestion was skipped due to low confidence.

Comment on lines +134 to +137
const cardClassNames = useMemo(
() => getCardClassNames(field, parsedField, isValidating, isCheckboxOrRadio, cardClassName),
[field, parsedField, isValidating, isCheckboxOrRadio, cardClassName],
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enhance readability by simplifying useMemo hooks.

The useMemo hooks can be simplified for better readability.

- const cardClassNames = useMemo(
-   () => getCardClassNames(field, parsedField, isValidating, isCheckboxOrRadio, cardClassName),
-   [field, parsedField, isValidating, isCheckboxOrRadio, cardClassName],
- );
+ const cardClassNames = useMemo(() => getCardClassNames(field, parsedField, isValidating, isCheckboxOrRadio, cardClassName), [field, parsedField, isValidating, isCheckboxOrRadio, cardClassName]);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const cardClassNames = useMemo(
() => getCardClassNames(field, parsedField, isValidating, isCheckboxOrRadio, cardClassName),
[field, parsedField, isValidating, isCheckboxOrRadio, cardClassName],
);
const cardClassNames = useMemo(() => getCardClassNames(field, parsedField, isValidating, isCheckboxOrRadio, cardClassName), [field, parsedField, isValidating, isCheckboxOrRadio, cardClassName]);

Comment on lines +6 to +78
export const SIGNER_COLOR_STYLES = {
green: {
default: {
background: 'bg-[hsl(var(--signer-green))]',
base: 'rounded-lg shadow-[0_0_0_5px_hsl(var(--signer-green)/10%),0_0_0_2px_hsl(var(--signer-green)/60%),0_0_0_0.5px_hsl(var(--signer-green))]',
fieldItem:
'group/field-item p-2 border-none ring-none hover:bg-gradient-to-r hover:from-[hsl(var(--signer-green))]/10 hover:to-[hsl(var(--signer-green))]/10',
fieldItemInitials:
'opacity-0 transition duration-200 group-hover/field-item:opacity-100 group-hover/field-item:bg-[hsl(var(--signer-green))]',
comboxBoxItem: 'hover:bg-[hsl(var(--signer-green)/15%)] active:bg-[hsl(var(--signer-green)/15%)]',
},
},

blue: {
default: {
background: 'bg-[hsl(var(--signer-blue))]',
base: 'rounded-lg shadow-[0_0_0_5px_hsl(var(--signer-blue)/10%),0_0_0_2px_hsl(var(--signer-blue)/60%),0_0_0_0.5px_hsl(var(--signer-blue))]',
fieldItem:
'group/field-item p-2 border-none ring-none hover:bg-gradient-to-r hover:from-[hsl(var(--signer-blue))]/10 hover:to-[hsl(var(--signer-blue))]/10',
fieldItemInitials:
'opacity-0 transition duration-200 group-hover/field-item:opacity-100 group-hover/field-item:bg-[hsl(var(--signer-blue))]',
comboxBoxItem: 'hover:bg-[hsl(var(--signer-blue)/15%)] active:bg-[hsl(var(--signer-blue)/15%)]',
},
},

purple: {
default: {
background: 'bg-[hsl(var(--signer-purple))]',
base: 'rounded-lg shadow-[0_0_0_5px_hsl(var(--signer-purple)/10%),0_0_0_2px_hsl(var(--signer-purple)/60%),0_0_0_0.5px_hsl(var(--signer-purple))]',
fieldItem:
'group/field-item p-2 border-none ring-none hover:bg-gradient-to-r hover:from-[hsl(var(--signer-purple))]/10 hover:to-[hsl(var(--signer-purple))]/10',
fieldItemInitials:
'opacity-0 transition duration-200 group-hover/field-item:opacity-100 group-hover/field-item:bg-[hsl(var(--signer-purple))]',
comboxBoxItem: 'hover:bg-[hsl(var(--signer-purple)/15%)] active:bg-[hsl(var(--signer-purple)/15%)]',
},
},

orange: {
default: {
background: 'bg-[hsl(var(--signer-orange))]',
base: 'rounded-lg shadow-[0_0_0_5px_hsl(var(--signer-orange)/10%),0_0_0_2px_hsl(var(--signer-orange)/60%),0_0_0_0.5px_hsl(var(--signer-orange))]',
fieldItem:
'group/field-item p-2 border-none ring-none hover:bg-gradient-to-r hover:from-[hsl(var(--signer-orange))]/10 hover:to-[hsl(var(--signer-orange))]/10',
fieldItemInitials:
'opacity-0 transition duration-200 group-hover/field-item:opacity-100 group-hover/field-item:bg-[hsl(var(--signer-orange))]',
comboxBoxItem: 'hover:bg-[hsl(var(--signer-orange)/15%)] active:bg-[hsl(var(--signer-orange)/15%)]',
},
},

yellow: {
default: {
background: 'bg-[hsl(var(--signer-yellow))]',
base: 'rounded-lg shadow-[0_0_0_5px_hsl(var(--signer-yellow)/10%),0_0_0_2px_hsl(var(--signer-yellow)/60%),0_0_0_0.5px_hsl(var(--signer-yellow))]',
fieldItem:
'group/field-item p-2 border-none ring-none hover:bg-gradient-to-r hover:from-[hsl(var(--signer-yellow))]/10 hover:to-[hsl(var(--signer-yellow))]/10',
fieldItemInitials:
'opacity-0 transition duration-200 group-hover/field-item:opacity-100 group-hover/field-item:bg-[hsl(var(--signer-yellow))]',
comboxBoxItem: 'hover:bg-[hsl(var(--signer-yellow)/15%)] active:bg-[hsl(var(--signer-yellow)/15%)]',
},
},

pink: {
default: {
background: 'bg-[hsl(var(--signer-pink))]',
base: 'rounded-lg shadow-[0_0_0_5px_hsl(var(--signer-pink)/10%),0_0_0_2px_hsl(var(--signer-pink)/60%),0_0_0_0.5px_hsl(var(--signer-pink))]',
fieldItem:
'group/field-item p-2 border-none ring-none hover:bg-gradient-to-r hover:from-[hsl(var(--signer-pink))]/10 hover:to-[hsl(var(--signer-pink))]/10',
fieldItemInitials:
'opacity-0 transition duration-200 group-hover/field-item:opacity-100 group-hover/field-item:bg-[hsl(var(--signer-pink))]',
comboxBoxItem: 'hover:bg-[hsl(var(--signer-pink)/15%)] active:bg-[hsl(var(--signer-pink)/15%)]',
},
},
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using CSS variables for better maintainability.

Consider using CSS variables for the signer color styles to improve maintainability and flexibility.

- export const SIGNER_COLOR_STYLES = {
-   green: {
-     default: {
-       background: 'bg-[hsl(var(--signer-green))]',
-       base: 'rounded-lg shadow-[0_0_0_5px_hsl(var(--signer-green)/10%),0_0_0_2px_hsl(var(--signer-green)/60%),0_0_0_0.5px_hsl(var(--signer-green))]',
-       fieldItem:
-         'group/field-item p-2 border-none ring-none hover:bg-gradient-to-r hover:from-[hsl(var(--signer-green))]/10 hover:to-[hsl(var(--signer-green))]/10',
-       fieldItemInitials:
-         'opacity-0 transition duration-200 group-hover/field-item:opacity-100 group-hover/field-item:bg-[hsl(var(--signer-green))]',
-       comboxBoxItem: 'hover:bg-[hsl(var(--signer-green)/15%)] active:bg-[hsl(var(--signer-green)/15%)]',
-     },
-   },
-   ...
- };
+ export const SIGNER_COLOR_STYLES = {
+   green: {
+     default: {
+       background: 'bg-[hsl(var(--signer-green))]',
+       base: 'rounded-lg shadow-[0_0_0_5px_hsl(var(--signer-green)/10%),0_0_0_2px_hsl(var(--signer-green)/60%),0_0_0_0.5px_hsl(var(--signer-green))]',
+       fieldItem:
+         'group/field-item p-2 border-none ring-none hover:bg-gradient-to-r hover:from-[hsl(var(--signer-green))]/10 hover:to-[hsl(var(--signer-green))]/10',
+       fieldItemInitials:
+         'opacity-0 transition duration-200 group-hover/field-item:opacity-100 group-hover/field-item:bg-[hsl(var(--signer-green))]',
+       comboxBoxItem: 'hover:bg-[hsl(var(--signer-green)/15%)] active:bg-[hsl(var(--signer-green)/15%)]',
+     },
+   },
+   ...
+ };

Committable suggestion was skipped due to low confidence.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (2)
packages/ui/primitives/document-flow/field-item-advanced-settings.tsx (2)

57-107: Consider changing the default value type for number fields.

The default value for the number field is a string ('0'). It might be better to use a number type for consistency and to avoid potential type issues.

-        value: '0',
+        value: 0,

198-203: Remove unnecessary else clause.

The else clause can be omitted because the previous branches break early.

-        } else {
+        }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5a01441 and 69b216f.

Files selected for processing (6)
  • packages/lib/server-only/document/send-document.tsx (2 hunks)
  • packages/lib/server-only/template/create-document-from-direct-template.ts (6 hunks)
  • packages/ui/lib/signer-colors.ts (1 hunks)
  • packages/ui/primitives/document-flow/add-fields.tsx (11 hunks)
  • packages/ui/primitives/document-flow/field-item-advanced-settings.tsx (1 hunks)
  • packages/ui/primitives/template-flow/add-template-fields.tsx (9 hunks)
Files skipped from review as they are similar to previous changes (3)
  • packages/ui/lib/signer-colors.ts
  • packages/ui/primitives/document-flow/add-fields.tsx
  • packages/ui/primitives/template-flow/add-template-fields.tsx
Additional context used
Biome
packages/ui/primitives/document-flow/field-item-advanced-settings.tsx

[error] 196-196: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Additional comments not posted (10)
packages/lib/server-only/document/send-document.tsx (1)

163-165: Verify the correctness of the logic for sealing the document.

The logic to seal the document if all recipients have no actions to take appears correct. Ensure that the sealDocument function handles this scenario appropriately.

packages/ui/primitives/document-flow/field-item-advanced-settings.tsx (4)

1-19: LGTM! Imports are correct and necessary.

The imports and type definitions appear correct and necessary for the file's functionality.


20-47: LGTM! Imports and type definitions are appropriate.

The imports and type definitions for the component props are appropriate and necessary.


227-299: LGTM! JSX structure is correct.

The JSX structure of the component appears correct and follows best practices.


300-303: LGTM! Display name is correctly set.

The display name of the component is correctly set.

packages/lib/server-only/template/create-document-from-direct-template.ts (5)

30-30: LGTM! Import is correct and necessary.

The import of ZFieldMetaSchema is correct and necessary for the file's functionality.


301-310: LGTM! Creation and parsing of fieldMeta are correct.

The creation and parsing of fieldMeta for nonDirectRecipientFieldsToCreate are correct and appropriate.


340-340: LGTM! Setting of fieldMeta is correct.

The setting of fieldMeta for directTemplateNonSignatureFields is correct and appropriate.


371-371: LGTM! Setting of fieldMeta is correct.

The setting of fieldMeta for directTemplateSignatureFields is correct and appropriate.


465-478: LGTM! Expansion of the with method call is correct.

The expansion of the with method call to handle additional field types is correct and appropriate.

Comment on lines +207 to +226
const handleOnGoNextClick = () => {
try {
if (errors.length > 0) {
return;
} else {
localStorage.setItem(localStorageKey, JSON.stringify(fieldState));

onSave?.(fieldState);
onAdvancedSettings?.();
}
} catch (error) {
console.error('Failed to save to localStorage:', error);

toast({
title: 'Error',
description: 'Failed to save settings.',
variant: 'destructive',
});
}
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve error handling in the save function.

The error handling in handleOnGoNextClick could be improved by providing more specific error messages based on the type of error encountered. Additionally, consider abstracting the localStorage operations into a separate utility function to clean up the component logic.

// src/utils/localStorageUtils.ts

/**
 * Retrieves an item from localStorage.
 * @param key The key of the item to retrieve.
 */
export function getLocalStorageItem(key: string): any {
  const item = localStorage.getItem(key);
  return item ? JSON.parse(item) : null;
}

/**
 * Saves an item to localStorage.
 * @param key The key under which to store the item.
 * @param value The value to store.
 */
export function setLocalStorageItem(key: string, value: any): void {
  const item = JSON.stringify(value);
  localStorage.setItem(key, item);
}

/**
 * Removes an item from localStorage.
 * @param key The key of the item to remove.
 */
export function removeLocalStorageItem(key: string): void {
  localStorage.removeItem(key);
}

Integrating Utility Functions in Your Component

You can then use these utility functions in your component like so:

import { getLocalStorageItem, setLocalStorageItem } from 'src/utils/localStorageUtils';

const [fieldState, setFieldState] = useState<FieldMeta>(() => {
  const savedState = getLocalStorageItem(localStorageKey);
  return savedState ? { ...defaultState, ...savedState } : defaultState;
});

const handleOnGoNextClick = () => {
  const validation = defaultConfigSchema.safeParse(fieldState);

  if (!validation.success) {
    toast({
      title: 'Error',
      description: 'An error occurred while saving the field.',
      variant: 'destructive',
    });

    return;
  } else {
    try {
      setLocalStorageItem(localStorageKey, fieldState);

      onSave?.(fieldState);
      onAdvancedSettings?.();
    } catch (error) {
      console.error('Failed to save to localStorage:', error);

      toast({
        title: 'Error',
        description: 'Failed to save settings.',
        variant: 'destructive',
      });
    }
  }
};


return {
...prevState,
[key]: isNaN(parsedValue) ? undefined : parsedValue,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace isNaN with Number.isNaN.

isNaN is unsafe as it attempts type coercion. Use Number.isNaN instead.

-            [key]: isNaN(parsedValue) ? undefined : parsedValue,
+            [key]: Number.isNaN(parsedValue) ? undefined : parsedValue,
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
[key]: isNaN(parsedValue) ? undefined : parsedValue,
[key]: Number.isNaN(parsedValue) ? undefined : parsedValue,
Tools
Biome

[error] 196-196: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Comment on lines +109 to +184

export const FieldAdvancedSettings = forwardRef<HTMLDivElement, FieldAdvancedSettingsProps>(
(
{
title,
description,
field,
fields,
onAdvancedSettings,
isDocumentPdfLoaded = true,
onSave,
teamId,
},
ref,
) => {
const { toast } = useToast();
const params = useParams();
const pathname = usePathname();
const id = params?.id;
const isTemplatePage = pathname?.includes('template');
const isDocumentPage = pathname?.includes('document');
const [errors, setErrors] = useState<string[]>([]);

const { data: template } = trpc.template.getTemplateWithDetailsById.useQuery(
{
id: Number(id),
},
{
enabled: isTemplatePage,
},
);

const { data: document } = trpc.document.getDocumentById.useQuery(
{
id: Number(id),
teamId,
},
{
enabled: isDocumentPage,
},
);

const doesFieldExist = (!!document || !!template) && field.nativeId !== undefined;

const { data: fieldData } = trpc.field.getField.useQuery(
{
fieldId: Number(field.nativeId),
teamId,
},
{
enabled: doesFieldExist,
},
);

const fieldMeta = fieldData?.fieldMeta;

const localStorageKey = `field_${field.formId}_${field.type}`;

const defaultState: FieldMeta = getDefaultState(field.type);

const [fieldState, setFieldState] = useState(() => {
const savedState = localStorage.getItem(localStorageKey);
return savedState ? { ...defaultState, ...JSON.parse(savedState) } : defaultState;
});

useEffect(() => {
if (fieldMeta && typeof fieldMeta === 'object') {
const parsedFieldMeta = ZFieldMetaSchema.parse(fieldMeta);

setFieldState({
...defaultState,
...parsedFieldMeta,
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fieldMeta]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a dependency array to the useEffect hook.

The useEffect hook for fieldMeta parsing is missing a dependency array, which can lead to unintended behavior.

-    }, [fieldMeta]);
+    }, [fieldMeta, defaultState]);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const FieldAdvancedSettings = forwardRef<HTMLDivElement, FieldAdvancedSettingsProps>(
(
{
title,
description,
field,
fields,
onAdvancedSettings,
isDocumentPdfLoaded = true,
onSave,
teamId,
},
ref,
) => {
const { toast } = useToast();
const params = useParams();
const pathname = usePathname();
const id = params?.id;
const isTemplatePage = pathname?.includes('template');
const isDocumentPage = pathname?.includes('document');
const [errors, setErrors] = useState<string[]>([]);
const { data: template } = trpc.template.getTemplateWithDetailsById.useQuery(
{
id: Number(id),
},
{
enabled: isTemplatePage,
},
);
const { data: document } = trpc.document.getDocumentById.useQuery(
{
id: Number(id),
teamId,
},
{
enabled: isDocumentPage,
},
);
const doesFieldExist = (!!document || !!template) && field.nativeId !== undefined;
const { data: fieldData } = trpc.field.getField.useQuery(
{
fieldId: Number(field.nativeId),
teamId,
},
{
enabled: doesFieldExist,
},
);
const fieldMeta = fieldData?.fieldMeta;
const localStorageKey = `field_${field.formId}_${field.type}`;
const defaultState: FieldMeta = getDefaultState(field.type);
const [fieldState, setFieldState] = useState(() => {
const savedState = localStorage.getItem(localStorageKey);
return savedState ? { ...defaultState, ...JSON.parse(savedState) } : defaultState;
});
useEffect(() => {
if (fieldMeta && typeof fieldMeta === 'object') {
const parsedFieldMeta = ZFieldMetaSchema.parse(fieldMeta);
setFieldState({
...defaultState,
...parsedFieldMeta,
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fieldMeta]);
useEffect(() => {
if (fieldMeta && typeof fieldMeta === 'object') {
const parsedFieldMeta = ZFieldMetaSchema.parse(fieldMeta);
setFieldState({
...defaultState,
...parsedFieldMeta,
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fieldMeta, defaultState]);

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Outside diff range, codebase verification and nitpick comments (1)
packages/ui/primitives/document-flow/field-items-advanced-settings/text-field.tsx (1)

19-34: Optimize the validation logic to avoid redundant validations.

The current implementation validates the text field on every input change. This can be optimized to reduce unnecessary validations.

-    const textErrors = validateTextField(text, {
-      characterLimit: Number(limit),
-      readOnly,
-      required,
-    });
-    handleErrors(textErrors);
+    if (field === 'text' || field === 'characterLimit' || field === 'readOnly' || field === 'required') {
+      const textErrors = validateTextField(text, {
+        characterLimit: Number(limit),
+        readOnly,
+        required,
+      });
+      handleErrors(textErrors);
+    }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 69b216f and 0ab151b.

Files selected for processing (3)
  • apps/web/src/app/(signing)/sign/[token]/email-field.tsx (1 hunks)
  • apps/web/src/app/(signing)/sign/[token]/name-field.tsx (1 hunks)
  • packages/ui/primitives/document-flow/field-items-advanced-settings/text-field.tsx (1 hunks)
Additional comments not posted (5)
packages/ui/primitives/document-flow/field-items-advanced-settings/text-field.tsx (1)

14-103: LGTM!

The TextFieldAdvancedSettings component is well-structured and handles state management and validation appropriately.

apps/web/src/app/(signing)/sign/[token]/email-field.tsx (2)

122-124: Ensure consistency in styling.

The text styling changes are consistent with the rest of the component.


127-130: Ensure consistency in styling.

The text styling changes are consistent with the rest of the component.

apps/web/src/app/(signing)/sign/[token]/name-field.tsx (2)

166-168: Ensure consistency in styling.

The text styling changes are consistent with the rest of the component.


171-173: Ensure consistency in styling.

The text styling changes are consistent with the rest of the component.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0ab151b and ebed2b2.

Files selected for processing (1)
  • turbo.json (2 hunks)
Additional comments not posted (1)
turbo.json (1)

15-15: Approved: Cache option set to false for prebuild.

Setting the cache to false ensures the latest changes are always built, which is beneficial for accuracy. However, be aware that this might impact build performance.

This branch had an error being deployed

2 failed and 2 active deployments
Preview – stg-marketing — ebed2b27 Deployed Jul 18, 2024 by vercel[bot]
Preview – stg-app — ebed2b27 Deployed Jul 18, 2024 by vercel[bot]
Preview – stg-docs — ebed2b27 Deployed Jul 18, 2024 by vercel[bot]
Preview – prd-docs — ebed2b27 Deployed Jul 18, 2024 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

apps: web Issues related to the webapp 🚨 migrations 🚨 Be advised: PR contains database migrations - Auto-Generated by GitHub Actions on raising a PR pkg: ee changes version bump 👀

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants