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

UX Enhancement for Middleware Override Workflow #9358

Conversation

saikiranpatil
Copy link

@saikiranpatil saikiranpatil commented Dec 10, 2024

Proposed Changes

  • Closes UX Enhancement for Middleware Override Workflow. #8335

  • Changes
    image

    • When the asset configuration is pre-filled from the location management or facility page, instead of making the user hover over the exclamation mark, add fine text below the input box, along with the pre-filled middleware placeholder, to provide details about the middleware's source.

    image

    • In the location creation form, under the middleware field, add fine text indicating that if left blank, the facility middleware will be applied to assets.

    image

    • In the location management card, display the facility configuration middleware with a "Pre-filled Facility Middleware" badge if no middleware is set for the location.

    image

    • Under the facility configuration middleware field, add fine text stating that the facility middleware will be applied to all assets when asset and location middleware are Unspecified.

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Introduced a new message display feature in form fields to enhance user feedback.
    • Added guidance messages for middleware address fields in various components.
    • Added new components and hooks for improved form handling using react-hook-form.
  • Bug Fixes

    • Retained error handling for invalid IP addresses in relevant components.
  • Refactor

    • Streamlined UI by replacing tooltips with message properties in form fields for better clarity.
    • Enhanced label handling in form fields for improved functionality.
    • Updated form handling logic to utilize react-hook-form and integrated validation.
  • Chores

    • Updated component interfaces to support new messaging capabilities.
    • Updated dependencies in package.json to include new libraries and versions.

prefilled middleware displayed as message in asset congiguration, added new attributes `message` and `messageClass` to `FormFeild` component`
add fine default behaviour text in facility configuration page
@saikiranpatil saikiranpatil requested a review from a team as a code owner December 10, 2024 18:56
Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

Walkthrough

The changes in this pull request involve modifications across several components to enhance the user interface by replacing tooltips with direct message displays in form fields. Specifically, the TextFormField component in HL7Monitor.tsx, ConfigureCamera.tsx, and other components has been updated to show contextual messages instead of tooltips. Additionally, new properties have been added to support these changes, and a new component for displaying messages has been introduced. The overall functionality and control flow of the components remain unchanged.

Changes

File Path Change Summary
src/components/Assets/AssetType/HL7Monitor.tsx Replaced tooltip with a message in TextFormField for middleware hostname; retained error handling for IP address input.
src/components/CameraFeed/ConfigureCamera.tsx Replaced tooltip with a message in TextFormField for middleware hostname; overall structure and error handling remain unchanged.
src/components/Facility/AddLocationForm.tsx Added a message to TextFormField for middleware address input to provide guidance on leaving it blank.
src/components/Facility/FacilityConfigure.tsx Replaced existing form handling with react-hook-form and added a validation schema; updated middleware address input to include a message.
src/components/Facility/LocationManagement.tsx Added facilityMiddleware property to LocationProps; updated state management and rendering logic to display middleware addresses.
src/components/Form/FormFields/FormField.tsx Introduced FieldMessageText component for displaying messages; updated FormField to include this new component.
src/components/Form/FormFields/Utils.ts Added message and messageClassName properties to FormFieldBaseProps type to support new messaging capabilities.
src/components/ui/form.tsx Introduced new components and hooks for form handling using react-hook-form, enhancing structure and usability of form fields.
package.json Updated dependencies to include react-hook-form and @hookform/resolvers, along with other version updates.

Assessment against linked issues

Objective Addressed Explanation
Add fine text below the input box for pre-filled middleware (related to #8335)
In the location creation form, add fine text indicating that leaving blank applies facility middleware (related to #8335)
Under the facility configuration middleware field, add fine text regarding application to all assets (related to #8335)

Possibly related PRs

  • Fixes UI Bug Issue in Symptom Editor #9270: The changes in this PR also involve modifying how information is presented in a form field, specifically replacing tooltip logic with a message property in the TextFormField, similar to the changes made in HL7Monitor.tsx.
  • Fix: Duplicate network requests in Patient Details page #9297: While this PR primarily focuses on optimizing network requests, it includes changes to the PatientNotesList component that may indirectly relate to form handling and UI updates, but it does not directly modify the same components or logic as the main PR.

Suggested labels

tested, reviewed

Suggested reviewers

  • Jacobjeevan
  • rithviknishad

🐇 In the fields where we play,
Messages guide us on our way.
Tooltips gone, clarity's here,
In every form, we cheer and cheer!
With each change, our paths align,
A smoother journey, oh how fine! 🌼


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.

Copy link

netlify bot commented Dec 10, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit c3d564c
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6762a474b862d40008c089e0
😎 Deploy Preview https://deploy-preview-9358--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@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: 1

🧹 Outside diff range and nitpick comments (1)
src/components/Assets/AssetType/HL7Monitor.tsx (1)

105-109: Consider enhancing message clarity and maintainability

While the implementation works, consider these improvements:

  1. Use an enum or constant for the "asset" source type
  2. Structure the message text for better maintainability
+ const MIDDLEWARE_SOURCE = {
+   ASSET: "asset"
+ } as const;
+
+ const getMiddlewareMessage = (source?: string) => {
+   return source && source !== MIDDLEWARE_SOURCE.ASSET
+     ? `Middleware hostname sourced from ${source}`
+     : undefined;
+ };

  <TextFormField
    message={
-     resolvedMiddleware?.source != "asset"
-       ? `Middleware hostname sourced from asset ${resolvedMiddleware?.source}`
-       : undefined
+     getMiddlewareMessage(resolvedMiddleware?.source)
    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b25ecd0 and 937e6fd.

📒 Files selected for processing (7)
  • src/components/Assets/AssetType/HL7Monitor.tsx (1 hunks)
  • src/components/CameraFeed/ConfigureCamera.tsx (1 hunks)
  • src/components/Facility/AddLocationForm.tsx (1 hunks)
  • src/components/Facility/FacilityConfigure.tsx (1 hunks)
  • src/components/Facility/LocationManagement.tsx (5 hunks)
  • src/components/Form/FormFields/FormField.tsx (2 hunks)
  • src/components/Form/FormFields/Utils.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/components/Facility/AddLocationForm.tsx
  • src/components/Facility/FacilityConfigure.tsx
🔇 Additional comments (8)
src/components/Form/FormFields/Utils.ts (1)

23-23: LGTM: Type definitions for new message properties

The addition of message and messageClassName optional properties to FormFieldBaseProps provides a clean way to support the new messaging functionality while maintaining backward compatibility.

Also applies to: 27-27

src/components/Form/FormFields/FormField.tsx (2)

51-68: LGTM: Well-structured message component implementation

The FieldMessageText component follows established patterns and includes proper transition effects. The use of primary-400 color effectively distinguishes informative messages from error text.


95-98: LGTM: Clean integration of message component

The message component is properly integrated into the FormField component, maintaining consistency with the existing error text display pattern.

src/components/Assets/AssetType/HL7Monitor.tsx (1)

105-109: Verify consistent middleware source handling

Let's ensure the middleware source message implementation is consistent across all relevant components.

✅ Verification successful

Middleware source handling is consistent across components

The implementation is consistent with other components in the codebase:

  • Both ConfigureCamera.tsx and HL7Monitor.tsx use the same pattern to display middleware source messages
  • Both check resolvedMiddleware?.source != "asset" condition
  • Both provide informative messages about the source of middleware hostname
  • Other middleware-related messages in FacilityConfigure.tsx and AddLocationForm.tsx serve different purposes and don't need this specific source handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other components that might need similar middleware source handling
rg -l "middleware.*source|resolvedMiddleware" --type ts --type tsx

# Look for existing message implementations in form fields
rg "message[=:].*middleware" --type ts --type tsx

Length of output: 176


Script:

#!/bin/bash
# Search for other components that might need similar middleware source handling
rg -t typescript -t javascriptreact -t typescriptreact -l "middleware.*source|resolvedMiddleware"

# Look for existing message implementations in form fields
rg -t typescript -t javascriptreact -t typescriptreact "message[=:].*middleware"

Length of output: 252


Script:

#!/bin/bash
# First, let's find all TypeScript and React files that might contain middleware source handling
fd -e ts -e tsx | xargs rg -l "middleware.*source|resolvedMiddleware"

# Then search for message implementations related to middleware
fd -e ts -e tsx | xargs rg "message[=:].*middleware"

Length of output: 510


Script:

#!/bin/bash
# Let's examine the middleware source handling in ConfigureCamera.tsx
rg -A 5 -B 5 "middleware.*source|resolvedMiddleware" src/components/CameraFeed/ConfigureCamera.tsx

# And check the specific implementation in HL7Monitor.tsx for comparison
rg -A 5 -B 5 "middleware.*source|resolvedMiddleware" src/components/Assets/AssetType/HL7Monitor.tsx

Length of output: 2218

src/components/Facility/LocationManagement.tsx (3)

30-30: LGTM: Clean implementation of facility middleware state management

The implementation properly handles facility middleware through well-typed props and efficient state management using React hooks.

Also applies to: 46-57


286-293: LGTM: Clear and informative middleware source display

The implementation effectively communicates the middleware source to users, aligning with the PR's UX enhancement goals.


298-298: LGTM: Well-structured middleware fallback logic

The implementation properly handles the middleware address display hierarchy, falling back to facility middleware when appropriate.

src/components/CameraFeed/ConfigureCamera.tsx (1)

154-161: LGTM: Improved middleware source visibility

The implementation effectively replaces tooltips with direct messages, improving user experience by making middleware source information immediately visible.

src/components/Facility/LocationManagement.tsx Outdated Show resolved Hide resolved
@saikiranpatil
Copy link
Author

@ohcnetwork/care-fe-code-reviewers @nihal467 please review this PR

@Jacobjeevan
Copy link
Contributor

I don't think the color scheme fits with rest of the UI 🤔 Plus, we should probably add the note as a badge on Location management page. I'll ping the design team in Slack for feedback.

@rithviknishad
Copy link
Member

Let's also switch to using shadcn's input fields from the ui directory!

@saikiranpatil
Copy link
Author

I don't think the color scheme fits with rest of the UI 🤔 Plus, we should probably add the note as a badge on Location management page. I'll ping the design team in Slack for feedback.

agreed,
i changed text to badge in location management as below
image

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 12, 2024
@saikiranpatil
Copy link
Author

i also tried to change the color to gray (color used in few elements) as below, let me know if looks better
image

@saikiranpatil
Copy link
Author

Let's also switch to using shadcn's input fields from the ui directory!

@rithviknishad were the recent changes made as expected?

</p>
</span>
{!middleware_address && facilityMiddleware && (
<span className="ml-2 mt-2 text-xs h-fit rounded-full border-2 border-primary-500 bg-primary-100 px-3 py-[3px]">
Copy link
Contributor

@Jacobjeevan Jacobjeevan Dec 12, 2024

Choose a reason for hiding this comment

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

Make use of the badge component (src/components/ui) here instead of custom logic.

As for the UI feedback, I'd wait for design team to respond.

src/components/Facility/LocationManagement.tsx Outdated Show resolved Hide resolved
src/components/Facility/LocationManagement.tsx Outdated Show resolved Hide resolved
@Jacobjeevan Jacobjeevan added changes required and removed question Further information is requested needs-triage labels Dec 16, 2024
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Dec 16, 2024
src/components/Facility/LocationManagement.tsx Outdated Show resolved Hide resolved
@@ -14,7 +16,7 @@ type LabelProps = {

export const FieldLabel = (props: LabelProps) => {
return (
<label
<Label
Copy link
Member

Choose a reason for hiding this comment

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

instead of modifying this, directly use shadcn's components in the forms. components in FormFields are not going to be used in newer codebase.

Copy link
Author

Choose a reason for hiding this comment

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

i didn't get what is to be done.

are you suggesting to use https://ui.shadcn.com/docs/components/form

Copy link
Member

Choose a reason for hiding this comment

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

yup

@saikiranpatil saikiranpatil force-pushed the issues/8335/middleware-override-workflow branch from 760eb94 to b9b0ed0 Compare December 18, 2024 05:10
Copy link
Contributor

@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)
src/components/Facility/LocationManagement.tsx (2)

51-58: Consider adding error handling for the facility query

While the query implementation is correct, it would be beneficial to handle potential error states.

Consider adding error handling:

- const { data } = useQuery({
+ const { data, error, isError } = useQuery({
   queryKey: [routes.getPermittedFacility.path, facilityId],
   queryFn: query(routes.getPermittedFacility, {
     pathParams: { id: facilityId },
   }),
 });

+ if (isError) {
+   Notification.Error({
+     msg: "Failed to fetch facility middleware information",
+   });
+ }

271-273: Consider extracting Badge styles to a reusable component

The Badge styling is repeated in multiple places. Consider creating a custom Badge variant for consistency.

Create a custom Badge variant in your UI components:

// components/ui/badge.tsx
const locationBadge = cva(
  "rounded-full bg-primary-100 text-primary-500 hover:bg-primary-100 border-2 border-primary-500 font-bold px-3 py-[3px]",
  {
    variants: {
      intent: {
        location: "ml-2",
        // Add more variants as needed
      }
    }
  }
);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c0d403 and b9b0ed0.

📒 Files selected for processing (1)
  • src/components/Facility/LocationManagement.tsx (8 hunks)
🔇 Additional comments (3)
src/components/Facility/LocationManagement.tsx (3)

Line range hint 1-34: LGTM! Clean import organization and type definitions

The new imports and type definitions are well-structured and properly typed.


285-294: LGTM! Clear middleware source indication

The implementation effectively shows the source of middleware configuration, improving UX as per PR objectives.


Line range hint 271-289: Verify consistent Badge usage across the codebase

Let's ensure the new Badge styling is consistently applied across similar components.

Copy link
Contributor

@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: 1

🧹 Nitpick comments (4)
src/components/ui/form.tsx (2)

17-17: Consider renaming the 'Form' component alias for clarity.
While this shorthand is convenient, aliasing FormProvider to 'Form' may be slightly confusing when using an actual

element in JSX. Consider using a more explicit name like FormProviderWrapper or RHFForm for better clarity.


88-97: Validate accessibility attributes when switching themes.
Label color changes to red text on error. With Tailwind’s dark mode classes, ensure that the “text-red-900” remains sufficiently visible against a dark background. Regularly test for contrast to maintain accessibility.

src/components/Facility/FacilityConfigure.tsx (2)

68-68: Remove or gate console.log statements.
Consider removing the console.log statement in production or gating it with a debug flag. Frequent unintended logs can clutter console output.


95-95: Use optional chaining to simplify checks.
Static analysis suggests converting “if (data && data.middleware_address) { … }” to “if (data?.middleware_address) { … }” for brevity and clarity. This approach avoids repeated conditions.

- if (data && data.middleware_address) {
+ if (data?.middleware_address) {
    form.setValue("middleware_address", data.middleware_address);
}
🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b9b0ed0 and c28d3a0.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (3 hunks)
  • src/components/Facility/FacilityConfigure.tsx (2 hunks)
  • src/components/ui/form.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Facility/FacilityConfigure.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (3)
src/components/ui/form.tsx (2)

30-35: Confirm that any additional ControllerProps are handled or documented.
You are destructuring and passing all props directly to . Double-check that any custom props are properly documented or typed, especially if the form library or your application extends ControllerProps with new attributes.


155-158: Good defensive null check.
Returning null when there's no error ensures the component doesn't render superfluous markup. This pattern helps keep the DOM clean and avoids potential confusion for screen readers.

package.json (1)

59-59: Validate library compatibility and potential breaking changes.
Multiple dependencies—@hookform/resolvers, @radix-ui/react-label, @radix-ui/react-slot, react-hook-form, and zod—were updated or introduced. Confirm that each library version is compatible with your existing code, especially if older code references earlier versions or deprecated APIs.

Run the following script to search for old usage patterns across the codebase:

Also applies to: 65-65, 68-68, 99-99, 157-157

✅ Verification successful

Let me analyze the search results to verify the library usage and compatibility.

The initial search showed usage of these libraries, but I need to verify the specific patterns and versions to ensure compatibility.


Based on the verification results, I can now generate the final response:

Library updates appear compatible with existing codebase
The codebase shows modern usage patterns that are compatible with the updated versions:

  • useForm from react-hook-form is used correctly in FacilityConfigure.tsx
  • Zod schemas follow the current API pattern with z.object() and chain validations
  • @radix-ui components (Label, Slot) are imported and used according to v2.x specifications
  • No deprecated patterns or APIs were detected
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for references to older versions or deprecated APIs for each library
rg 'useForm|z\.|@radix-ui/react-label|@radix-ui/react-slot'

Length of output: 9291


Script:

#!/bin/bash
# Check for specific imports and usage patterns
ast-grep --pattern 'import { useForm } from "react-hook-form"'

# Check for zod schema definitions and validations
ast-grep --pattern 'z.object({
  $$$
})'

# Check package.json for exact versions
cat package.json | grep -A 10 '"dependencies":'

Length of output: 1314

Comment on lines 56 to 72
if (!data) return;

const data = {
...state.form,
middleware_address: state.form.middleware_address,
const formData = {
name: data.name,
state: data.state,
district: data.district,
local_body: data.local_body,
ward: data.ward,
middleware_address: values.middleware_address,
};

setIsLoading(true);
console.log(formData);

const { res, error } = await request(routes.partialUpdateFacility, {
pathParams: { id: facilityId },
body: data,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use the updated form data in the request body.
It appears you create formData (lines 58-64) but pass data (the original facility data) to the request body (line ~ 69). This likely discards the updated middleware address in formData.

Apply this diff to fix the request body:

- const { res, error } = await request(routes.partialUpdateFacility, {
-   pathParams: { id: facilityId },
-   body: data,
- });
+ const { res, error } = await request(routes.partialUpdateFacility, {
+   pathParams: { id: facilityId },
+   body: formData,
+ });
📝 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 (!data) return;
const data = {
...state.form,
middleware_address: state.form.middleware_address,
const formData = {
name: data.name,
state: data.state,
district: data.district,
local_body: data.local_body,
ward: data.ward,
middleware_address: values.middleware_address,
};
setIsLoading(true);
console.log(formData);
const { res, error } = await request(routes.partialUpdateFacility, {
pathParams: { id: facilityId },
body: data,
if (!data) return;
const formData = {
name: data.name,
state: data.state,
district: data.district,
local_body: data.local_body,
ward: data.ward,
middleware_address: values.middleware_address,
};
setIsLoading(true);
console.log(formData);
const { res, error } = await request(routes.partialUpdateFacility, {
pathParams: { id: facilityId },
body: formData,

@saikiranpatil
Copy link
Author

@rithviknishad i am not used to useQuery, might be having some mistakes, please review.

if we are moving from FormText components to shadcn forms, why not create issues regarding the same

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 18, 2024
Copy link
Contributor

@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: 1

🧹 Nitpick comments (3)
src/components/Facility/FacilityConfigure.tsx (3)

47-53: Consolidate loading states

The component uses two separate loading states:

  1. isLoading for form submission
  2. loading (from isPending) for data fetching

Consider consolidating these into a single loading state to prevent potential UI inconsistencies.

- const [isLoading, setIsLoading] = useState(false);
  const { isPending: loading, data } = useQuery({
    queryKey: [routes.getPermittedFacility.path, facilityId],
    queryFn: query(routes.getPermittedFacility, {
      pathParams: { id: facilityId },
    }),
  });

- if (isLoading || !data || loading) {
+ if (!data || loading) {
    return <Loading />;
  }

Also applies to: 99-101


Line range hint 55-87: Remove duplicate setIsLoading(false) call

The loading state is being reset twice: once after the request and once at the end of the function.

    setIsLoading(false);
    if (res?.ok) {
      Notification.Success({
        msg: t("update_facility_middleware_success"),
      });
      navigate(`/facility/${facilityId}`);
    } else {
      Notification.Error({
        msg: error?.detail ?? "Something went wrong",
      });
    }
-   setIsLoading(false);

Add type safety for formData

Consider defining an interface for the facility data structure to ensure type safety.

interface FacilityData {
  name: string;
  state: string;
  district: string;
  local_body: string;
  ward: string;
  middleware_address: string;
}

93-97: Use optional chaining for safer property access

The current code might throw an error if data is defined but middleware_address is undefined.

  useEffect(() => {
-   if (data && data.middleware_address) {
+   if (data?.middleware_address) {
      form.setValue("middleware_address", data.middleware_address);
    }
  }, [form, data]);
🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c28d3a0 and c3d564c.

📒 Files selected for processing (1)
  • src/components/Facility/FacilityConfigure.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Facility/FacilityConfigure.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
src/components/Facility/FacilityConfigure.tsx (1)

113-142: Well-structured form implementation with clear user guidance

The form implementation:

  • Uses shadcn/ui components consistently
  • Provides clear labeling and validation messages
  • Includes helpful description about middleware inheritance
  • Follows accessibility best practices with proper form labels and messages

This aligns well with the PR objectives to enhance UX clarity.

Comment on lines +35 to +42
const formSchema = z.object({
middleware_address: z
.string()
.nonempty({ message: "Middleware Address is required" })
.regex(/^(?!https?:\/\/)[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*\.[a-zA-Z]{2,}$/, {
message: "Invalid Middleware Address",
}),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

The middleware address validation pattern should be relaxed to support more formats

The codebase search reveals that middleware addresses can be in various formats:

  • Domain names (e.g., example.ohc.network)
  • WebSocket URLs with hostnames and IP addresses (e.g., wss://<middleware>/observations/<ipAddress>)
  • Local IP addresses for development/testing

The current regex pattern ^(?!https?:\/\/)[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*\.[a-zA-Z]{2,}$ is too restrictive as it:

  • Doesn't allow IP addresses (e.g., 192.168.1.100)
  • Doesn't allow ports (e.g., localhost:8000)
  • Requires at least one dot and a TLD-like suffix

Consider updating the validation pattern to support these common middleware address formats.

🔗 Analysis chain

Consider reviewing the middleware address validation pattern

The current regex pattern might be too restrictive as it:

  1. Disallows URLs with http/https prefix
  2. Requires a domain-like format with at least one dot
  3. Only allows letters, numbers, underscores, and hyphens

This could prevent valid middleware addresses like localhost:8000 or IP addresses.

Let's check other middleware address patterns in the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other middleware address validation patterns
rg -A 2 'middleware.*address.*regex'

Length of output: 38


Script:

#!/bin/bash
# Let's search for any middleware address validation or usage patterns
rg -i "middleware.*address" -A 3

# Also search for any middleware URL or connection patterns
rg -i "middleware.*(url|connection|host)" -A 3

# Look for any middleware configuration files
fd -e json -e yaml -e yml -e config middleware

Length of output: 21921

@saikiranpatil
Copy link
Author

so happy by your support in helping reviews of my contributions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required Deploy-Failed Deplyment is not showing preview needs-triage question Further information is requested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

UX Enhancement for Middleware Override Workflow.
3 participants