Repository navigation
chore: add more field types - #1141
Conversation
WalkthroughThe 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
Poem
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? TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Additionally, you can add CodeRabbit Configuration File (
|
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
| 'pointer-events-none': passive, | ||
| 'pointer-events-none opacity-75': disabled, | ||
| className={cn('group z-20', { | ||
| 'active:pointer-events-none': passive, |
There was a problem hiding this comment.
couldn't think of a better way of making the hover work on passive/disabled fields. happy to hear suggestions
There was a problem hiding this comment.
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 addingaria-label.Add
aria-labelto 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:
OptimizeonMouseMoveandonMouseClickfunctions.The
onMouseMoveandonMouseClickfunctions 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
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 theincludeandexcludearrays are appropriate.The
includearray now includes the current directory, and theexcludearray excludes common build directories (dist,build, andnode_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
CheckboxFieldPropstype 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
RadioFieldPropstype 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
fieldIconsare correct and consistent with the field types.Verification successful
Ensure correctness of icon mappings.
The icon mappings in the
fieldIconsobject infield-icon.tsxappear to be correct and consistent with the field types. EachFieldTypeis associated with an appropriate icon:
FieldType.EMAIL->FieldType.NAME->UserFieldType.DATE->CalendarDaysFieldType.TEXT->TypeFieldType.NUMBER->HashFieldType.RADIO->DiscFieldType.CHECKBOX->CheckSquareFieldType.DROPDOWN->ChevronDownNo 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
signerEmailandfontCaveatClassNameprops are optional. Ensure that they are handled correctly in the component.Verification successful
Optional props are handled correctly.
The
FieldIconcomponent correctly handles the optional propssignerEmailandfontCaveatClassName. ThefontCaveatClassNameis used conditionally within thecnfunction, ensuring it does not affect the class names if not provided. ThesignerEmailprop is passed down as expected.
fontCaveatClassNameis conditionally used within thecnfunction.signerEmailis 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.tsxare correct and consistent with the field properties.
- The styles for
top,left,height, andwidthare correctly set based on thecoordsobject.- The conditional application of
heightandwidthwhenisCheckboxOrRadioFieldis 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
useMemohooks inpackages/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.
parsedFielddepends onfield.fieldMeta.isCheckboxOrRadiodepends onparsedField.cardClassNamesdepends onfield,parsedField,isValidating,isCheckboxOrRadio, andcardClassName.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
flattenFormfunction, along with theflattenWidgetfunction, correctly handles the process of flattening fields and their widgets, ensuring that the document is properly re-flattened after inserting fields.
flattenFormfunction:packages/lib/server-only/pdf/flatten-form.tsflattenWidgetfunction:packages/lib/server-only/pdf/flatten-form.tsScripts 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.tsLength 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 10Length 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.tsLength 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
useSignerColorsis 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 5Length 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
XandZFieldMetaSchemaare necessary for the new functionality.
41-42: Function signature and enum changes look good.The changes to the
onRemovefunction signature and the expandedtypeenum are necessary for the new field types.
58-60: Field metadata parsing looks good.The introduction of
parsedFieldMetaandreadOnlyFieldvariables is necessary to handle field metadata and read-only state.
112-119: Checkbox values clearing logic looks good.The
onClearCheckBoxValuesfunction 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
RadioFieldcomponent.
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
onSignfunction correctly handles the signing of the field.
104-129: Remove field logic looks good.The
onRemovefunction 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
useMemoanduseRefhooks from 'react' is appropriate for the new logic introduced in the component.
10-10: LGTM! Added necessary import for pattern matching.The addition of
matchfrom '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, andZRadioFieldMetaare necessary for handling advanced field settings.
16-20: LGTM! Added necessary imports for signer colors and advanced fields.The imports for
useSignerColors,CheckboxField,RadioField, andFieldIconare appropriate for the new logic introduced in the component.
25-30: LGTM! Added font configuration.The
fontCaveatconstant is correctly configured using theCaveatfont from 'next/font/google'.
41-43: LGTM! Added new props for advanced settings and recipient index.The new props
onAdvancedSettings,recipientIndex, andhideRecipientsare correctly added toFieldItemProps.
66-67: LGTM! Added state for settings activation and element reference.The new state
settingsActiveand the reference$elare correctly added for handling advanced settings and click events.
153-153: LGTM! Added logic for fixed size.The
fixedSizeconstant 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
hideRecipientsprop is used appropriately.
184-193: Ensure proper handling of click events on the field.The click event handler for the field correctly toggles the
settingsActivestate, but ensure that this logic does not interfere with other components.Verification successful
Verification Successful: Proper handling of click events on the field.
The
setSettingsActivestate is defined and used exclusively within thefield-item.tsxfile, 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
Caveatfont andSettings2icon are used appropriately within the component.Verification successful
Verified Usage of Imported Icons and Fonts
The
Caveatfont andSettings2icon are used appropriately within thefield-item.tsxcomponent.
Caveatfont is assigned tofontCaveatand used asfontCaveat.className.Settings2icon 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 3Length of output: 13184
118-122: Ensure proper handling of click events outside the field.The
handleClickOutsideFieldfunction 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
handleClickOutsideFieldfunction is correctly managed within auseEffecthook, ensuring that it does not interfere with other components.
- The event listener is added and removed in the
useEffecthook based on thesettingsActivedependency.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 10Length 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
Pfrom '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
ZCheckboxFieldMetaandZRadioFieldMetaare 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
useTransitionhook 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
ZCheckboxFieldMetais 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, andvalidateTextFieldare appropriate for the new logic introduced in the component.
13-13: LGTM! Added necessary import for text field meta schema.The import for
ZTextFieldMetais necessary for handling advanced field settings.
41-44: LGTM! Added initial errors state.The
initialErrorsstate 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_suggestionpackages/ui/primitives/template-flow/add-template-fields.tsx (4)
492-494: LGTM!The function
handleAdvancedSettingsis straightforward and does not have any issues.
498-508: LGTM!The component
FieldAdvancedSettingsintegrates well with the existing code and provides a clear structure for handling advanced settings.
543-544: Use optional chaining forrecipientColorClasses.Use optional chaining to handle cases where
recipientColorClassesmight 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
rgcommand 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, andFieldAdvancedSettingsare all utilized within the codebase as expected.
useRecipientColorClassesis used on line 232.useSelectedSignerStylesis used on line 292.ZFieldMetaSchemais used on lines 289 and 312.FieldMetais used on line 309.FieldFormTypeis used on lines 225 and 227.FieldAdvancedSettingsis 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
| 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> | ||
| ); | ||
| }; |
There was a problem hiding this comment.
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?
| 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> | ||
| ); | ||
| }; |
There was a problem hiding this comment.
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?
| <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()} | ||
| /> |
There was a problem hiding this comment.
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.
| <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()} | |
| /> |
| 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> | ||
| ); |
There was a problem hiding this comment.
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.
| 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> | |
| ); |
| useEffect(() => { | ||
| if (!showRadioModal) { | ||
| setLocalNumber(parsedFieldMeta?.value ? String(parsedFieldMeta.value) : '0'); | ||
| setErrors(initialErrors); | ||
| } | ||
| }, [showRadioModal]); |
There was a problem hiding this comment.
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.
| 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]); |
| const parsedFieldMeta = field.fieldMeta ? ZTextFieldMeta.parse(field.fieldMeta) : null; | ||
|
|
There was a problem hiding this comment.
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.
| 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. | |
| } |
| <div className={cn('absolute', className)} style={style}> | ||
| {children} | ||
| </div>, | ||
| document.body, |
There was a problem hiding this comment.
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.
| 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'; | ||
|
|
There was a problem hiding this comment.
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.
| const cardClassNames = useMemo( | ||
| () => getCardClassNames(field, parsedField, isValidating, isCheckboxOrRadio, cardClassName), | ||
| [field, parsedField, isValidating, isCheckboxOrRadio, cardClassName], | ||
| ); |
There was a problem hiding this comment.
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.
| 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]); |
| 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%)]', | ||
| }, | ||
| }, | ||
| }; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
numberfield 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
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
sealDocumentfunction 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
ZFieldMetaSchemais correct and necessary for the file's functionality.
301-310: LGTM! Creation and parsing offieldMetaare correct.The creation and parsing of
fieldMetafornonDirectRecipientFieldsToCreateare correct and appropriate.
340-340: LGTM! Setting offieldMetais correct.The setting of
fieldMetafordirectTemplateNonSignatureFieldsis correct and appropriate.
371-371: LGTM! Setting offieldMetais correct.The setting of
fieldMetafordirectTemplateSignatureFieldsis correct and appropriate.
465-478: LGTM! Expansion of thewithmethod call is correct.The expansion of the
withmethod call to handle additional field types is correct and appropriate.
| 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', | ||
| }); | ||
| } | ||
| }; |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
| [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)
|
|
||
| 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]); |
There was a problem hiding this comment.
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.
| 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]); |
There was a problem hiding this comment.
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
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
TextFieldAdvancedSettingscomponent 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.
There was a problem hiding this comment.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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 forprebuild.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.
Description
What I've done:
Created an optional
fieldMetafield of JSONB type in theFieldmodel (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 thecustomTextfield.Created schemas and types for
fieldMeta.Added the
fieldMetafield in the appropriate schemas and types.Moved the title and description (
DocumentFlowFormContainerHeader) fromedit-templatepage into each template step -add-template-settings.tsx,add-template-placeholder.tsxandadd-template-fields.tsx. They have their own title and description. Exactly like it's done for the documents.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.
readOnlyandrequiredchecked at the same time, it will throw an error.readOnly, it should have a value for thetextfield.characterLimitis not a number, it will throw an error.valueentered by the user is over thecharacterLimit, it will throw an error.minValuecan't be greater than themaxValueand vice-versa.valueentered by the user can't be lower than theminValueand greater than themaxValue.valuefield empty when the field isreadOnly.readOnlyandrequiredchecked at the same time, it will throw an error.requiredandreadOnlyat the same time.readOnly, it should have at least one option.requiredandreadOnlyat the same time.readOnly, it should have at least one option.requiredandreadOnlyat the same time.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:
textvalue set by default and the field is not already inserted, the app will insert the field automatically when you visit the signing page.valuefield set by default and the field is not already inserted, the app will insert the field automatically when you visit the signing page.checkedoption set totrue, those will be checked automatically.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
FieldIconcomponent - 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
Fieldcomponent (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.
substring, which is used to shorten thecustomTextvalue which overflows and messes up the field's card design..... plus other smaller things.
What's left:
Make the new fields work in the SPM mode (not necessary after our discussion)
Cleanup the code.
For another PR:
Testing Performed
Checklist
Summary by CodeRabbit
CheckboxField,DropdownField,NumberField, andRadioFieldcomponents for document signing.SignatureFieldandNameFieldcomponents with improved styling.SigningFieldContainerto handle multiple field types.turbo.jsonconfiguration for prebuild paths and caching.