Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: move post-form validation logic to onUpdated event #1487

Merged

Conversation

nas-tabchiche
Copy link
Contributor

@nas-tabchiche nas-tabchiche commented Feb 10, 2025

This aims to centralize all post-valid behaviours, e.g. redirects,
closing modals...

Summary by CodeRabbit

  • Refactor
    • Streamlined form handling by consolidating configuration and submission logic.
    • Improved user feedback with structured error and warning messages.
    • Removed automatic redirection after form submissions, offering a more controlled and predictable user flow.
    • Reorganized import statements for clarity and consistency.
    • Made certain form fields optional during serialization, enhancing flexibility in data submission.

This aims to centralize all post-valid behaviours, e.g. redirects,
closing modals...
Copy link

coderabbitai bot commented Feb 10, 2025

Walkthrough

This pull request refactors multiple form-related components and utilities. In the main form component, a new _form variable is introduced via the superForm function, consolidating configuration and update logic. The error and validation handling has been adjusted in the utilities by replacing direct form returns with a structured message response. Furthermore, redirection logic previously driven by reactive statements in several page components is removed, and import orders have been reorganized for clarity.

Changes

Files Change Summary
frontend/src/lib/components/Forms/ModelForm.svelte Introduced a new _form variable using superForm and updated import and properties; removed the explicit onUpdated handler and simplified the save button by eliminating asynchronous validations.
frontend/src/lib/utils/actions.ts Updated error and action handling by integrating the message function from sveltekit-superforms to wrap responses, replacing direct form returns (including usage of fail(400)).
frontend/src/routes/(app)/(internal)/[model=urlmodel]/+page.server.ts Added import for message from sveltekit-superforms; modified error handling logic in the importFolder action to return structured messages instead of failing with status 400.
frontend/src/routes/(app)/(internal)/[model=urlmodel]/+page.svelte and +page.svelte (third-party, compliance-assessments) Reorganized import statements and removed reactive redirection logic (e.g., goto(getSecureRedirect(...))) across multiple route pages, simplifying control flow and navigation handling.
frontend/src/routes/(app)/(third-party)/[model=thirdparty_urlmodels]/+page.svelte Reorganized import statements and removed reactive redirection logic based on the form's state, impacting how modals are triggered.
backend/core/serializers.py Updated EvidenceWriteSerializer to make applied_controls and requirement_assessments fields optional by adding required=False.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant SF as SuperForm Component
    participant F as _form (superForm)
    participant A as Action Handler
    participant S as Server API

    U->>SF: Submit form
    SF->>F: Delegate submission & validation
    F->>A: Process form submission (validate, update, etc.)
    A->>S: Send API request
    S-->>A: Return response (success/error)
    A-->>F: Wrap response with message()
    F->>SF: Update form state via onUpdated callback
Loading

Possibly related PRs

Suggested reviewers

  • ab-smith
  • eric-intuitem

Poem

I'm a rabbit in the code burrow, swift and free,
Hopping over redirections, as neat as can be.
With super forms and messages, the path is now clear,
No more tangled callbacks to fear.
I dance with joy in every new line—oh happy coding time! 🐇✨


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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

@nas-tabchiche nas-tabchiche changed the title refactor: move post-form validation logic to onUpdatedEvent refactor: move post-form validation logic to onUpdated event Feb 10, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
frontend/src/lib/components/Forms/ModelForm.svelte (2)

118-138: Remove console.log statement.

The console.log statement on line 129 should be removed before production deployment.

-			console.log('form', form);

Optimize cache cleanup in onUpdated callback.

The cache is deleted twice when the form is valid - once at the start of the callback and again after checking form validity.

 		onUpdated: async ({ form }) => {
-			createModalCache.deleteCache(model.urlModel);
 			if (form.message?.redirect) {
 				goto(getSecureRedirect(form.message.redirect));
 			}
 			if (form.valid) {
 				parent.onConfirm();
 				createModalCache.deleteCache(model.urlModel);
 			}
 		}

141-154: Remove duplicate form configuration props.

The dataType and enctype props are defined both in the _form configuration and directly on the SuperForm component. Since they're already configured in _form, they can be removed from the component props.

 <SuperForm
 	class="flex flex-col space-y-3"
-	dataType={shape.attachment ? 'form' : 'json'}
-	enctype={shape.attachment ? 'multipart/form-data' : 'application/x-www-form-urlencoded'}
 	data={form}
 	{_form}
 	{invalidateAll}
 	let:form
 	let:data
 	let:initialData
 	validators={zod(schema)}
 	onUpdated={() => createModalCache.deleteCache(model.urlModel)}
 	{...$$restProps}
 >
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7893fdb and e6cb6a6.

📒 Files selected for processing (8)
  • frontend/src/lib/components/Forms/ModelForm.svelte (3 hunks)
  • frontend/src/lib/utils/actions.ts (8 hunks)
  • frontend/src/routes/(app)/(internal)/[model=urlmodel]/+page.server.ts (2 hunks)
  • frontend/src/routes/(app)/(internal)/[model=urlmodel]/+page.svelte (1 hunks)
  • frontend/src/routes/(app)/(internal)/[model=urlmodel]/[id=uuid]/+page.svelte (0 hunks)
  • frontend/src/routes/(app)/(internal)/ebios-rm/[id=uuid]/+page.svelte (0 hunks)
  • frontend/src/routes/(app)/(third-party)/[model=thirdparty_urlmodels]/+page.svelte (1 hunks)
  • frontend/src/routes/(app)/(third-party)/compliance-assessments/[id=uuid]/+page.svelte (0 hunks)
💤 Files with no reviewable changes (3)
  • frontend/src/routes/(app)/(internal)/[model=urlmodel]/[id=uuid]/+page.svelte
  • frontend/src/routes/(app)/(third-party)/compliance-assessments/[id=uuid]/+page.svelte
  • frontend/src/routes/(app)/(internal)/ebios-rm/[id=uuid]/+page.svelte
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: migrations-check (3.12)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: functional-tests (3.12, chromium)
  • GitHub Check: enterprise-functional-tests (3.12, chromium)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (8)
frontend/src/routes/(app)/(third-party)/[model=thirdparty_urlmodels]/+page.svelte (1)

5-7: LGTM!

The removal of redirection logic aligns with the PR objective to centralize post-validation behaviors in onUpdatedEvent.

frontend/src/routes/(app)/(internal)/[model=urlmodel]/+page.server.ts (1)

11-11: Improved error handling with structured messages.

Using message from sveltekit-superforms provides a more structured way to handle form responses, especially for error cases. This change aligns with the PR objective of centralizing post-validation behaviors.

Also applies to: 124-124

frontend/src/routes/(app)/(internal)/[model=urlmodel]/+page.svelte (1)

5-8: LGTM!

The removal of redirection logic and reorganization of imports aligns with the PR objective to centralize post-validation behaviors in onUpdatedEvent.

frontend/src/lib/utils/actions.ts (3)

79-79: Improved error handling in handleErrorResponse.

The function now returns structured messages using message from sveltekit-superforms, providing a more consistent way to handle warnings and errors.

Also applies to: 83-83, 88-88


114-114: Enhanced form action responses in defaultWriteFormAction.

The function now uses structured messages for all response types:

  • Invalid form validation
  • Redirection after successful creation
  • Object creation success
    This provides a more consistent interface for handling form responses.

Also applies to: 171-171, 173-173


217-217: Consistent error handling in defaultDeleteFormAction.

The function now follows the same pattern of using structured messages for all response types, maintaining consistency with other form actions.

Also applies to: 228-228, 233-233, 245-245

frontend/src/lib/components/Forms/ModelForm.svelte (2)

40-40: LGTM!

Clean import combining both the function and type from sveltekit-superforms.


319-321: LGTM!

The save button now correctly uses the form's built-in validation mechanism, aligning with the PR's objective to centralize form validation logic.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/core/serializers.py (1)

9-9: Consider replacing star import with explicit imports.

Using star imports (from core.models import *) makes it harder to track dependencies and can lead to naming conflicts. Consider explicitly importing the required models.

-from core.models import *
+from core.models import (
+    AppliedControl,
+    Evidence,
+    RequirementAssessment,
+    # Add other required models
+)
🧰 Tools
🪛 Ruff (0.8.2)

9-9: from core.models import * used; unable to detect undefined names

(F403)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e6cb6a6 and bd0c8af.

📒 Files selected for processing (1)
  • backend/core/serializers.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
backend/core/serializers.py

824-824: AppliedControl may be undefined, or defined from star imports

(F405)


827-827: RequirementAssessment may be undefined, or defined from star imports

(F405)

⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: functional-tests (3.12, chromium)
  • GitHub Check: enterprise-functional-tests (3.12, chromium)
  • GitHub Check: test (3.12)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: build (3.12)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: ruff (3.12)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
backend/core/serializers.py (1)

823-828: LGTM! Making fields optional aligns with form validation refactoring.

The changes make applied_controls and requirement_assessments fields optional by adding required=False. This aligns with the PR objective of centralizing form validation logic.

🧰 Tools
🪛 Ruff (0.8.2)

824-824: AppliedControl may be undefined, or defined from star imports

(F405)


827-827: RequirementAssessment may be undefined, or defined from star imports

(F405)

Copy link
Collaborator

@Mohamed-Hacene Mohamed-Hacene left a comment

Choose a reason for hiding this comment

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

0k

Copy link

@coderabbitai coderabbitai bot left a comment

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 comments (1)
frontend/src/lib/components/Forms/ModelForm.svelte (1)

140-153: Remove redundant onUpdated handler from SuperForm component.

The onUpdated handler is now managed in the _form configuration, but it's also present in the SuperForm component. This duplication could lead to the cache being deleted multiple times or cause race conditions.

 <SuperForm
   class="flex flex-col space-y-3"
   dataType={shape.attachment ? 'form' : 'json'}
   enctype={shape.attachment ? 'multipart/form-data' : 'application/x-www-form-urlencoded'}
   data={form}
   {_form}
   {invalidateAll}
   let:form
   let:data
   let:initialData
   validators={zod(schema)}
-  onUpdated={() => createModalCache.deleteCache(model.urlModel)}
   {...$$restProps}
 >
🧹 Nitpick comments (1)
frontend/src/lib/components/Forms/ModelForm.svelte (1)

127-136: Remove duplicate cache deletion in onUpdated callback.

The cache is being deleted twice:

  1. At the start of the callback (line 128)
  2. After form validation (line 134)

This redundancy should be removed.

 onUpdated: async ({ form }) => {
-  createModalCache.deleteCache(model.urlModel);
   if (form.message?.redirect) {
     goto(getSecureRedirect(form.message.redirect));
   }
   if (form.valid) {
     parent.onConfirm();
     createModalCache.deleteCache(model.urlModel);
   }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bd0c8af and 3dfad3e.

📒 Files selected for processing (1)
  • frontend/src/lib/components/Forms/ModelForm.svelte (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: enterprise-startup-docker-compose-test
  • GitHub Check: startup-functional-test (3.12)
  • GitHub Check: startup-docker-compose-test
  • GitHub Check: build (3.12)
  • GitHub Check: enterprise-startup-functional-test (3.12)
  • GitHub Check: functional-tests (3.12, chromium)
  • GitHub Check: Analyze (python)
  • GitHub Check: enterprise-functional-tests (3.12, chromium)
  • GitHub Check: test (3.12)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
frontend/src/lib/components/Forms/ModelForm.svelte (3)

40-40: LGTM! Import changes align with centralization goal.

The addition of superForm import from sveltekit-superforms aligns with the PR's objective of centralizing form validation logic.


118-137: LGTM! Form configuration effectively centralizes form behavior.

The _form configuration successfully centralizes form validation and post-submission behavior, including data type handling, validation method, and navigation logic.


317-320: LGTM! Button handling simplified correctly.

The save button now correctly relies on the form's built-in validation and submission handling, which aligns with the centralization of form validation logic.

@Mohamed-Hacene Mohamed-Hacene merged commit 46350a9 into main Feb 10, 2025
21 checks passed
@Mohamed-Hacene Mohamed-Hacene deleted the refactor/move-post-form-validation-logic-to-superform branch February 10, 2025 15:34
@github-actions github-actions bot locked and limited conversation to collaborators Feb 10, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants