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

Integrated Excalidraw for drawing Files #10680

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

NikhilA8606
Copy link
Contributor

@NikhilA8606 NikhilA8606 commented Feb 18, 2025

Integrated Excalidraw for drawing Files

After saving the drawing using filename users can view and update the file as they needed
image

@rithviknishad

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 an interactive drawing editor and viewer, enabling users to create, edit, and review drawings directly within patient and encounter workflows.
    • Enhanced navigation in file sections for quick access to drawing details.
  • Documentation

    • Added clear labels and error notifications related to drawing actions and file uploads.

@NikhilA8606 NikhilA8606 requested a review from a team as a code owner February 18, 2025 16:28
Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Walkthrough

This pull request integrates Excalidraw drawing capabilities into the application. It adds new dependencies and localization strings, introduces new routes for patient and consultation drawing operations, and enhances navigation within file-related components. New components—ExcalidrawEditor and ExcalidrawView—handle drawing creation and viewing with lazy loading and suspense fallbacks. Additional utility functions and environment configuration updates further support these features.

Changes

File(s) Change Summary
package.json Added dependency @excalidraw/excalidraw@^0.17.6 and updated sonner from ^1.7.2 to ^1.7.4.
public/locale/en.json Added new entries: "add_drawings", "error_in_createUpload", "error_uploading_file", and "file_success__upload_complete".
src/Routers/routes/PatientRoutes.tsx
src/Routers/routes/ConsultationRoutes.tsx
Introduced new routes for patient and consultation drawings that render ExcalidrawEditor and ExcalidrawView using Suspense for lazy loading.
src/components/Files/FilesTab.tsx
src/pages/Encounters/tabs/EncounterFilesTab.tsx
Enhanced navigation by integrating raviger for drawing-related buttons and added a patientId prop for improved routing.
src/components/Files/ExcalidrawEditor.tsx
src/components/Files/ExcalidrawView.tsx
Added new components to support creating and viewing Excalidraw drawings with state management, data fetching, and error handling.
src/lib/utils.ts
vite.config.mts
Added a debounce utility function and defined the process.env.IS_PREACT environment variable.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant F as FilesTab
  participant R as Router
  participant S as Suspense Loader
  participant E as Excalidraw Component

  U->>F: Clicks drawing button
  F->>R: Calls navigate()
  R->>S: Matches route & lazy loads component
  S->>E: Renders ExcalidrawEditor/ExcalidrawView
  E-->>U: Displays drawing interface
Loading
sequenceDiagram
  participant U as User
  participant E as ExcalidrawEditor
  participant M as Mutation Handler

  U->>E: Clicks Save button
  E->>M: Initiates handleSave (upload process)
  M-->>E: Returns success/error response
  E-->>U: Displays notification via toast
Loading

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

I'm a hopping rabbit with a code-filled heart,
Skipping through routes with a brand-new start.
Drawings bloom like carrots in a digital field,
With Excalidraw magic, new visions are revealed.
Debounce keeps the rhythm, steady and true,
Celebrating each change—oh, how joyous and new!
🥕 Hop on, dear coder, the art is all for you!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 Feb 18, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit a84bd76
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67b81e7771e9640009003f2e
😎 Deploy Preview https://deploy-preview-10680.preview.ohc.network
📱 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.

@NikhilA8606 NikhilA8606 marked this pull request as draft February 18, 2025 16:29
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 (8)
src/components/Files/ExcalidrawDialog.tsx (4)

40-40: Remove console.log statement.

Remove debugging console.log statement before production deployment.

-  console.log(data);

82-86: Consider using application/json content type for Excalidraw files.

The current implementation uses text/plain which works but application/json would be more semantically correct for JSON data.

-      const file = new File([JSON.stringify(obj)], `${name}.excalidraw`, {
-        type: "text/plain",
-      });
+      const file = new File([JSON.stringify(obj)], `${name}.excalidraw`, {
+        type: "application/json",
+      });

164-166: Consider memoizing the debounced function.

The current implementation creates a new debounced function on every render. Consider memoizing it with useCallback for better performance.

+ const debouncedOnChange = useCallback(
+   debounce(async (elements) => {
+     setElements(elements);
+   }, 100),
+   []
+ );

  return (
    // ...
    <Excalidraw
      // ...
-     onChange={debounce(async (elements) => {
-       setElements(elements);
-     }, 100)}
+     onChange={debouncedOnChange}
    />
  );

108-112: Improve error handling for upload failures.

The current implementation only shows a generic error message. Consider providing more detailed error information to help users understand and resolve issues.

       if (!upload.ok) {
-        toast.error("Error uploading file");
+        const errorMessage = await upload.text();
+        toast.error(`Error uploading file: ${errorMessage || upload.statusText}`);
         return;
       }
src/components/Files/FilesTab.tsx (2)

112-113: Remove console.log statements.

Remove debugging console.log statements before production deployment.

-  console.log("facilityId", props.facilityId);
-  console.log("PatientId", props.patientId);
-  console.log("fileName", file.extension);

Also applies to: 550-550


265-279: Consider using a type-safe routing solution.

The current implementation uses template literals for route construction. Consider using a type-safe routing solution to prevent potential runtime errors.

For example, you could create a route builder utility:

const routes = {
  drawings: {
    list: (facilityId: string, patientId: string) => 
      `/facility/${facilityId}/patient/${patientId}/drawings`,
    detail: (facilityId: string, patientId: string, drawingId: string) =>
      `/facility/${facilityId}/patient/${patientId}/drawings/${drawingId}`
  }
};

Then use it in the component:

- onClick={() =>
-   navigate(
-     `/facility/${props.facilityId}/patient/${props.patientId}/drawings/${file.id}`,
-   )
- }
+ onClick={() =>
+   navigate(routes.drawings.detail(props.facilityId, props.patientId, file.id))
+ }

Also applies to: 443-457

src/lib/utils.ts (1)

8-19: Add error handling and cleanup mechanism.

The debounce implementation could be improved with:

  1. Error handling for the callback execution
  2. A cleanup mechanism to prevent memory leaks
 export function debounce<T extends unknown[], U>(
   callback: (...args: T) => PromiseLike<U> | U,
   wait: number
 ) {
   let timer: ReturnType<typeof setTimeout>;
   return (...args: T): Promise<U> => {
     clearTimeout(timer);
-    return new Promise((resolve) => {
+    return new Promise((resolve, reject) => {
       timer = setTimeout(() => {
-        resolve(callback(...args))
+        try {
+          const result = callback(...args);
+          if (result instanceof Promise) {
+            result.then(resolve).catch(reject);
+          } else {
+            resolve(result);
+          }
+        } catch (error) {
+          reject(error);
+        }
       }, wait);
     });
   };
 }

Additionally, consider adding a cancel method to clear the timer when needed:

export function debounce<T extends unknown[], U>(
  callback: (...args: T) => PromiseLike<U> | U,
  wait: number
) {
  let timer: ReturnType<typeof setTimeout>;
  const debouncedFn = (...args: T): Promise<U> => {
    clearTimeout(timer);
    return new Promise((resolve, reject) => {
      timer = setTimeout(() => {
        try {
          const result = callback(...args);
          if (result instanceof Promise) {
            result.then(resolve).catch(reject);
          } else {
            resolve(result);
          }
        } catch (error) {
          reject(error);
        }
      }, wait);
    });
  };
  debouncedFn.cancel = () => {
    clearTimeout(timer);
  };
  return debouncedFn;
}
src/hooks/useFilters.tsx (1)

5-5: LGTM! Successful migration with room for improvement.

The replacement of classNames with cn is correctly implemented. Consider extracting the base classes for better readability:

-        className={cn(
-          "flex w-full justify-center",
-          totalCount > limit ? "visible" : "invisible",
-          !noMargin && "mt-4",
-        )}
+        const baseClasses = "flex w-full justify-center"
+        className={cn(
+          baseClasses,
+          totalCount > limit ? "visible" : "invisible",
+          !noMargin && "mt-4",
+        )}

Also applies to: 227-231

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2fd019f and 6bb0ab6.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (14)
  • package.json (3 hunks)
  • public/locale/en.json (2 hunks)
  • src/Routers/routes/PatientRoutes.tsx (3 hunks)
  • src/Utils/utils.ts (0 hunks)
  • src/components/Common/LanguageSelector.tsx (2 hunks)
  • src/components/Common/LanguageSelectorLogin.tsx (2 hunks)
  • src/components/Common/UpdatableApp.tsx (2 hunks)
  • src/components/Files/ExcalidrawDialog.tsx (1 hunks)
  • src/components/Files/FilesTab.tsx (7 hunks)
  • src/components/Users/UserFormValidations.tsx (2 hunks)
  • src/components/ui/sidebar/patient-switcher.tsx (2 hunks)
  • src/hooks/useFilters.tsx (2 hunks)
  • src/lib/utils.ts (1 hunks)
  • vite.config.mts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/Utils/utils.ts
🔇 Additional comments (11)
src/Routers/routes/PatientRoutes.tsx (1)

16-18: LGTM! Well-implemented drawing routes with lazy loading.

The implementation uses lazy loading for the ExcalidrawPage component and shows a loading indicator during component load. The routes are properly structured with required parameters.

Also applies to: 54-71

public/locale/en.json (1)

294-294: LGTM! Well-structured translations for new drawing features.

The new translations follow the existing naming conventions and provide clear, user-friendly messages.

Also applies to: 1056-1056

src/components/Common/LanguageSelector.tsx (1)

32-35: LGTM!

The migration from classNames to cn utility is correctly implemented, maintaining proper class merging behavior.

src/components/Common/LanguageSelectorLogin.tsx (1)

37-42: LGTM!

The migration from classNames to cn utility is correctly implemented, maintaining proper conditional class handling.

src/components/Users/UserFormValidations.tsx (1)

75-81: LGTM!

The migration from classNames to cn utility is correctly implemented, maintaining proper conditional class handling for validation states.

src/components/ui/sidebar/patient-switcher.tsx (1)

3-3: LGTM! Successful migration to the new cn utility.

The replacement of the deprecated classNames utility with cn is correctly implemented, maintaining the same className concatenation functionality.

Also applies to: 33-33

src/components/Common/UpdatableApp.tsx (1)

4-4: LGTM! Successful migration to the new cn utility.

The replacement of classNames with cn is correctly implemented, maintaining the same conditional animation class functionality.

Also applies to: 123-123

vite.config.mts (1)

164-164:

✅ Verification successful

Verify Excalidraw's Preact configuration.

Let's confirm if setting IS_PREACT to "true" is the recommended configuration for Excalidraw.


🌐 Web query:

Does Excalidraw require IS_PREACT environment variable to be set to true?

💡 Result:

Excalidraw requires the IS_PREACT environment variable to be set only when using Preact instead of React. This requirement exists because Excalidraw's UMD build includes React dependencies by default, which conflict with Preact[1][2][9].

Key implementation details:

  1. Set IS_PREACT as a string "true" in your build configuration:
// vite.config.js
define: {
  "process.env.IS_PREACT": JSON.stringify("true"), // Must be string "true"
},
  1. Vite-specific configuration requires explicit declaration since Vite strips process.env variables by default[2][9].

This environment variable switch tells Excalidraw to use its Preact-compatible build instead of the default React build[1][2]. The requirement doesn't apply if you're using React or other frameworks without Preact integration[1].

Citations:


Excalidraw Preact Configuration Verified

Setting "process.env.IS_PREACT" to "true" in vite.config.mts (line 164) is correct. This configuration aligns with Excalidraw’s requirements when using Preact, as it instructs the library to use its Preact-compatible build. No changes are needed here.

package.json (3)

98-100: LGTM! Dependencies align with drawing feature requirements.

The added dependencies make sense for the drawing feature:

  • idb-keyval for local storage of drawings
  • jotai for state management

120-120: LGTM! Minor version update.

The update to sonner from 1.7.2 to 1.7.4 is a minor version bump, likely containing bug fixes.


52-52:

✅ Verification successful

Verify Excalidraw version.

Let's check if there's a newer version of Excalidraw available with potential bug fixes or improvements.


🌐 Web query:

What is the latest version of @excalidraw/excalidraw?

💡 Result:

The latest version of @excalidraw/excalidraw is 0.17.6, released approximately 10 months ago as of February 2025[4][6][9]. This version includes features like:

  • Programmatic API support for frames and element alignment[1]
  • Enhanced security measures for URL sanitization and embed validation[1]
  • Improved dark mode themes and UI components[1]

The package follows semantic versioning and maintains backward compatibility where possible, though some breaking changes were introduced in earlier versions (e.g., v0.16.x)[1]. For access to unreleased features, developers can use @excalidraw/excalidraw@next which includes experimental builds with commit hash suffixes[2][5].

Citations:


Excalidraw dependency is up-to-date.

The specified version, 0.17.6, is confirmed to be the latest available release as of February 2025. No action is required regarding an update for this dependency. The additional dependency updates and additions (idb-keyval, jotai, and the patch update for sonner) appear appropriate.

@NikhilA8606 NikhilA8606 force-pushed the issues/#10616/Integrating-Excalidraw-for-drawing-files branch 2 times, most recently from d2732f1 to ed2bd40 Compare February 19, 2025 07:11
@NikhilA8606 NikhilA8606 force-pushed the issues/#10616/Integrating-Excalidraw-for-drawing-files branch from ed2bd40 to 1837fbb Compare February 19, 2025 07:31
@NikhilA8606 NikhilA8606 marked this pull request as ready for review February 20, 2025 20:48
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: 6

🧹 Nitpick comments (5)
src/components/Files/ExcalidrawView.tsx (1)

40-42: Add loading state for fetch operation.

The fetch operation should show a loading state while retrieving the drawing data.

+  const [isLoadingElements, setIsLoadingElements] = useState(false);
   const fetchData = async () => {
+    setIsLoadingElements(true);
     try {
       const response = await fetch(data.read_signed_url!);
       const json = await response.json();
       setElements(json.elements);
+    } finally {
+      setIsLoadingElements(false);
+    }
   };

Then update the loading check:

-  if (isLoading || elements === null) {
+  if (isLoading || isLoadingElements || elements === null) {
src/Routers/routes/PatientRoutes.tsx (2)

53-59: Maintain consistent parameter naming across routes.

The parameter naming is inconsistent between routes (:id vs :patientId). Consider using consistent parameter names for better maintainability.

-  "/facility/:facilityId/patient/:id/drawings": ({ id }) => {
+  "/facility/:facilityId/patient/:patientId/drawings": ({ patientId }) => {
     return (
       <Suspense fallback={<Loading />}>
-        <ExcalidrawPage associatingId={id} fileType="patient" />
+        <ExcalidrawPage associatingId={patientId} fileType="patient" />
       </Suspense>
     );
   },

Also applies to: 61-69


55-57: Add error boundary around lazy-loaded components.

Consider wrapping the Suspense components with an error boundary to handle loading failures gracefully.

// Create an error boundary component
const ErrorBoundary = ({ children }: { children: React.ReactNode }) => {
  return (
    <ErrorBoundaryComponent
      fallback={<div>Failed to load drawing component</div>}
    >
      {children}
    </ErrorBoundaryComponent>
  );
};

// Use it in the routes
<ErrorBoundary>
  <Suspense fallback={<Loading />}>
    <ExcalidrawPage ... />
  </Suspense>
</ErrorBoundary>

Also applies to: 65-67

src/components/Files/ExcalidrawPage.tsx (1)

166-182: Optimize Excalidraw component rendering.

The debounce delay of 100ms for onChange might be too aggressive and cause unnecessary re-renders.

Consider:

  1. Increasing the debounce delay
  2. Memoizing the onChange handler
-          onChange={debounce(async (elements) => {
-            setElements(elements);
-          }, 100)}
+          onChange={useMemo(
+            () =>
+              debounce(async (elements) => {
+                setElements(elements);
+              }, 300),
+            []
+          )}
src/components/Files/FilesTab.tsx (1)

478-479: Add aria-label to improve accessibility.

The drawing button lacks proper accessibility attributes.

-              <CareIcon icon="l-pen" />
-              <span>{t("add_drawings")}</span>
+              <CareIcon icon="l-pen" aria-hidden="true" />
+              <span aria-label={t("add_drawings")}>{t("add_drawings")}</span>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6bb0ab6 and aa5327a.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (10)
  • package.json (2 hunks)
  • public/locale/en.json (2 hunks)
  • src/Routers/routes/ConsultationRoutes.tsx (3 hunks)
  • src/Routers/routes/PatientRoutes.tsx (3 hunks)
  • src/components/Files/ExcalidrawPage.tsx (1 hunks)
  • src/components/Files/ExcalidrawView.tsx (1 hunks)
  • src/components/Files/FilesTab.tsx (5 hunks)
  • src/lib/utils.ts (1 hunks)
  • src/pages/Encounters/tabs/EncounterFilesTab.tsx (1 hunks)
  • vite.config.mts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • package.json
  • vite.config.mts
  • public/locale/en.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/pages/Encounters/tabs/EncounterFilesTab.tsx (1)

10-10: Verify patient object existence.

Consider adding a null check for props.patient to prevent potential runtime errors if the patient object is undefined.

-      patientId={props.patient.id}
+      patientId={props.patient?.id}
src/Routers/routes/ConsultationRoutes.tsx (2)

1-1: LGTM! Good use of code splitting.

The implementation of lazy loading for Excalidraw components is well done, which will help reduce the initial bundle size.

Also applies to: 12-13


36-48: LGTM! Well-structured route definitions.

The new routes for drawings are properly structured and follow the existing patterns. The Suspense wrapper with Loading fallback is correctly implemented.

src/components/Files/ExcalidrawPage.tsx (1)

85-92:

✅ Verification successful

Add version validation for Excalidraw data format.

The hardcoded version "2" might cause compatibility issues if Excalidraw's data format changes.

Let's check the latest Excalidraw version and data format:


🌐 Web query:

What is the latest version of Excalidraw's data format?

💡 Result:

The latest version of Excalidraw's data format as of February 2025 remains version 2, based on documentation and recent updates[8][10]. This JSON-based structure includes elements like type, version, elements, appState, and files, maintaining backward compatibility while introducing incremental improvements[8].

Key details from recent updates:

  • Compression defaults: Starting with Excalidraw-Obsidian plugin v2.2.0 (May 2024), compressed JSON became the default storage format using LZ-String compression[1][8]
  • Font handling: Recent updates introduced embedded font subsets in SVG exports and CJK font support while keeping file sizes manageable[10]
  • Security: Added URL sanitization for element links and improved encryption for shared diagrams[4][5]

The core schema remains stable since v2, though implementation details like compression methods and export options continue evolving[1][8]. Developers should reference the official JSON schema documentation for implementation specifics[8].

Citations:


Excalidraw Data Format Version is Up-to-Date

The Excalidraw JSON schema still uses version "2" as of February 2025 based on the latest documentation. While hardcoding the version isn’t a current issue, you might consider abstracting it (e.g., using a constant or config value) to ease future updates should the schema change.

  • File: src/components/Files/ExcalidrawPage.tsx (lines 85–92)
  • Current State: The hardcoded "2" aligns with the latest Excalidraw format.
  • Suggestion: For increased maintainability, abstract the version into a configurable constant if you're anticipating future changes.

Comment on lines +8 to +19
export function debounce<T extends unknown[], U>(
callback: (...args: T) => PromiseLike<U> | U,
wait: number
) {
let timer: ReturnType<typeof setTimeout>;
return (...args: T): Promise<U> => {
clearTimeout(timer);
return new Promise((resolve) => {
timer = setTimeout(() => resolve(callback(...args)), wait);
});
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add cleanup mechanism to prevent memory leaks.

The debounce implementation should clean up the timer when the component unmounts. Consider returning a cleanup function that can be used in useEffect.

 export function debounce<T extends unknown[], U>(
   callback: (...args: T) => PromiseLike<U> | U,
   wait: number
 ) {
   let timer: ReturnType<typeof setTimeout>;
-  return (...args: T): Promise<U> => {
+  const debouncedFn = (...args: T): Promise<U> => {
     clearTimeout(timer);
     return new Promise((resolve) => {
       timer = setTimeout(() => resolve(callback(...args)), wait);
     });
   };
+  debouncedFn.cancel = () => {
+    clearTimeout(timer);
+  };
+  return debouncedFn;
 }

Usage example:

useEffect(() => {
  const debouncedFn = debounce(callback, 1000);
  return () => debouncedFn.cancel();
}, [callback]);

<CareIcon icon="l-pen" className="text-lg text-primary-500" />
</div>
<div className="m-4">
<Input type="text" value={name} />
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Disable input field in view mode.

The name input field should be read-only since this is a view-only component.

-            <Input type="text" value={name} />
+            <Input type="text" value={name} readOnly />
📝 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
<Input type="text" value={name} />
<Input type="text" value={name} readOnly />

Comment on lines +34 to +45
useEffect(() => {
if (!data) {
return;
}
setName(data.name!);
const fetchData = async () => {
const response = await fetch(data.read_signed_url!);
const json = await response.json();
setElements(json.elements);
};
fetchData();
}, [data]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Prevent potential race conditions in useEffect.

The fetch operation should be cancelled if the component unmounts or if data changes before the fetch completes.

   useEffect(() => {
     if (!data) {
       return;
     }
     setName(data.name!);
+    const controller = new AbortController();
     const fetchData = async () => {
-      const response = await fetch(data.read_signed_url!);
+      const response = await fetch(data.read_signed_url!, {
+        signal: controller.signal
+      });
       const json = await response.json();
       setElements(json.elements);
     };
     fetchData();
+    return () => controller.abort();
   }, [data]);
📝 Committable suggestion

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

Suggested change
useEffect(() => {
if (!data) {
return;
}
setName(data.name!);
const fetchData = async () => {
const response = await fetch(data.read_signed_url!);
const json = await response.json();
setElements(json.elements);
};
fetchData();
}, [data]);
useEffect(() => {
if (!data) {
return;
}
setName(data.name!);
const controller = new AbortController();
const fetchData = async () => {
const response = await fetch(data.read_signed_url!, {
signal: controller.signal
});
const json = await response.json();
setElements(json.elements);
};
fetchData();
return () => controller.abort();
}, [data]);

Comment on lines +39 to +45
const fetchData = async () => {
const response = await fetch(data.read_signed_url!);
const json = await response.json();
setElements(json.elements);
};
fetchData();
}, [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

Add error handling for fetch operations.

The fetch operation lacks error handling, which could lead to unhandled promise rejections.

   const fetchData = async () => {
+    try {
       const response = await fetch(data.read_signed_url!);
+      if (!response.ok) {
+        throw new Error(`HTTP error! status: ${response.status}`);
+      }
       const json = await response.json();
       setElements(json.elements);
+    } catch (error) {
+      console.error('Failed to fetch drawing:', error);
+      // Consider showing an error state to the user
+    }
   };
   fetchData();
📝 Committable suggestion

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

Suggested change
const fetchData = async () => {
const response = await fetch(data.read_signed_url!);
const json = await response.json();
setElements(json.elements);
};
fetchData();
}, [data]);
const fetchData = async () => {
try {
const response = await fetch(data.read_signed_url!);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
setElements(json.elements);
} catch (error) {
console.error('Failed to fetch drawing:', error);
// Consider showing an error state to the user
}
};
fetchData();
}, [data]);

Comment on lines 79 to 83
const handleSave = async () => {
if (!name.trim()) {
toast.error("Please enter a name for the drawing.");
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling in the save operation.

The error handling in the save operation could be improved:

  1. The error message in the catch block only logs to console
  2. No user feedback for upload failures
  3. No cleanup or state reset on error

Consider this implementation:

 try {
   const file = new File([JSON.stringify(obj)], `${name}.excalidraw`, {
     type: "text/plain",
   });
   let signedUrl = data?.read_signed_url || "";
   let response: CreateFileResponse | null = null;
   if (!id) {
     response = await createUpload({
       original_name: `${name}.excalidraw`,
       name: name,
       file_type: fileType,
       file_category: "unspecified",
       associating_id: associatingId,
       mime_type: "text/plain",
     });
     signedUrl = response.signed_url;
   }
 } catch (error) {
-  console.error("Error in Step 1 (createUpload):", error);
+  toast.error(t("file_error__create_upload_failed"));
+  setIsDirty(true); // Preserve changes
+  return;
 }

Also applies to: 94-124

Comment on lines +277 to +297
{file.extension === ".excalidraw" && (
<Button
variant="secondary"
onClick={() => {
if (type === "encounter") {
navigate(
`/facility/${props.facilityId}/patient/${props.patientId}/encounter/${props.encounter?.id}/drawings/${file.id}`,
);
} else {
navigate(
`/facility/${props.facilityId}/patient/${props.patientId}/drawings/${file.id}`,
);
}
}}
>
<span className="flex flex-row items-center gap-1">
<CareIcon icon="l-eye" />
{t("view")}
</span>
</Button>
)}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicate navigation logic.

The navigation logic for drawings is duplicated between DetailButtons and FileUploadButtons. This violates the DRY principle and makes maintenance harder.

Extract the navigation logic into a utility function:

+const navigateToDrawings = (props: FilesTabProps, fileId?: string) => {
+  const basePath = `/facility/${props.facilityId}/patient/${props.patientId}`;
+  const drawingsPath = props.type === "encounter" 
+    ? `${basePath}/encounter/${props.encounter?.id}/drawings`
+    : `${basePath}/drawings`;
+  return fileId ? `${drawingsPath}/${fileId}` : drawingsPath;
+};

// In DetailButtons
-if (type === "encounter") {
-  navigate(`/facility/${props.facilityId}/patient/${props.patientId}/encounter/${props.encounter?.id}/drawings/${file.id}`);
-} else {
-  navigate(`/facility/${props.facilityId}/patient/${props.patientId}/drawings/${file.id}`);
-}
+navigate(navigateToDrawings(props, file.id));

// In FileUploadButtons
-if (type === "encounter") {
-  navigate(`/facility/${props.facilityId}/patient/${props.patientId}/encounter/${props.encounter?.id}/drawings`);
-} else {
-  navigate(`/facility/${props.facilityId}/patient/${props.patientId}/drawings`);
-}
+navigate(navigateToDrawings(props));

Also applies to: 461-481

Comment on lines 12 to 14
const ExcalidrawPage = lazy(() => import("@/components/Files/ExcalidrawPage"));
const ExcalidrawView = lazy(() => import("@/components/Files/ExcalidrawView"));

Copy link
Member

Choose a reason for hiding this comment

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

Nice, but we could simplify things by lazy loading the Excalidraw component itself directly inside the ExcalidrawPage and ExcalidrawView component instead;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

But what about the import("")); we have no Excalidraw.tsx (or .jsx) file inside the File

Copy link
Member

@rithviknishad rithviknishad Feb 21, 2025

Choose a reason for hiding this comment

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

we could do something like this inside ExcalidrawEditor and Viewer since excalidraw doesn't have a default export

const Excalidraw = lazy(() =>
  import("@excalidraw/excalidraw").then((module) => ({
    default: module.Excalidraw,
  })),
);


const handleSave = async () => {
if (!name.trim()) {
toast.error("Please enter a name for the drawing.");
Copy link
Member

Choose a reason for hiding this comment

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

i18n

Comment on lines +43 to +48
"/facility/:facilityId/patient/:patientId/encounter/:encounterId/drawings/:drawingId":
({ drawingId }) => (
<Suspense fallback={<Loading />}>
<ExcalidrawView drawingId={drawingId} />
</Suspense>
),
Copy link
Member

Choose a reason for hiding this comment

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

@bodhish marking this for hold since backend would not allow editing a file due to audit reasons.

@vigneshhari suggests making a plug and writing the elements to the DB itself instead of a file upload.

Copy link
Member

Choose a reason for hiding this comment

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

Buckets have versions what stops us from editing 🤔

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: 2

🧹 Nitpick comments (2)
src/components/Files/ExcalidrawEditor.tsx (2)

27-38: Consider using useReducer for better state management.

The component manages multiple related states that could be consolidated using useReducer for better maintainability and state transitions.

Here's a suggested implementation:

-  const [elements, setElements] = useState<readonly ExcalidrawElement[] | null>([]);
-  const [name, setName] = useState("");
-  const [id, setId] = useState("");
-  const [isDirty, setIsDirty] = useState(false);
-
-  useEffect(() => {
-    setIsDirty(!!elements?.length);
-  }, [elements?.length]);
+  type State = {
+    elements: readonly ExcalidrawElement[] | null;
+    name: string;
+    id: string;
+    isDirty: boolean;
+  };
+
+  type Action =
+    | { type: 'SET_ELEMENTS'; payload: readonly ExcalidrawElement[] | null }
+    | { type: 'SET_NAME'; payload: string }
+    | { type: 'SET_ID'; payload: string }
+    | { type: 'RESET' };
+
+  const initialState: State = {
+    elements: [],
+    name: '',
+    id: '',
+    isDirty: false,
+  };
+
+  const reducer = (state: State, action: Action): State => {
+    switch (action.type) {
+      case 'SET_ELEMENTS':
+        return {
+          ...state,
+          elements: action.payload,
+          isDirty: !!action.payload?.length,
+        };
+      case 'SET_NAME':
+        return { ...state, name: action.payload };
+      case 'SET_ID':
+        return { ...state, id: action.payload };
+      case 'RESET':
+        return initialState;
+      default:
+        return state;
+    }
+  };
+
+  const [state, dispatch] = useReducer(reducer, initialState);

113-159: Improve component rendering and configuration.

Consider the following improvements:

  1. Memoize the debounced onChange handler
  2. Support system theme preference
  3. Simplify height calculations
+  const debouncedOnChange = useMemo(
+    () =>
+      debounce((elements) => {
+        setElements(elements);
+      }, 100),
+    []
+  );
+
+  const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
+
   return (
-    <div className="flex flex-col h-[calc(100vh-4rem)]">
+    <div className="flex flex-col h-screen">
       {/* ... */}
-      <div className="flex-grow h-[calc(100vh-10rem)] -m-2">
+      <div className="flex-grow -m-2">
         <Excalidraw
           UIOptions={{
             canvasActions: {
               saveAsImage: true,
               export: false,
               loadScene: false,
             },
           }}
           initialData={{
-            appState: { theme: "light" },
+            appState: { theme },
           }}
-          onChange={debounce((elements) => {
-            setElements(elements);
-          }, 100)}
+          onChange={debouncedOnChange}
         />
       </div>
     </div>
   );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aa5327a and a84bd76.

📒 Files selected for processing (4)
  • public/locale/en.json (4 hunks)
  • src/Routers/routes/ConsultationRoutes.tsx (3 hunks)
  • src/Routers/routes/PatientRoutes.tsx (3 hunks)
  • src/components/Files/ExcalidrawEditor.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/Routers/routes/ConsultationRoutes.tsx
  • src/Routers/routes/PatientRoutes.tsx
  • public/locale/en.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (1)
src/components/Files/ExcalidrawEditor.tsx (1)

1-25: LGTM! Well-organized imports and clear type definitions.

The imports are logically grouped and the Props interface is well-defined with appropriate types.

Comment on lines +53 to +111
const handleSave = async () => {
if (!name.trim()) {
toast.error(t("please_enter_a_name_for_the_drawing"));
return;
}

const obj = {
type: "excalidraw",
version: "2",
source: window.location.origin,
elements: elements,
appState: {},
files: {},
};

try {
const file = new File([JSON.stringify(obj)], `${name}.excalidraw`, {
type: "application/vnd.excalidraw",
});
let signedUrl = "";
let response: CreateFileResponse | null = null;
if (!id) {
response = await createUpload({
original_name: `${name}.excalidraw`,
name: name,
file_type: fileType,
file_category: "unspecified",
associating_id: associatingId,
mime_type: "text/plain",
});
signedUrl = response.signed_url;
}

const formData = new FormData();
formData.append("file", file);

const upload = await fetch(signedUrl, {
method: "PUT",
body: file,
});

if (!upload.ok) {
toast.error(t("error_uploading_file"));

return;
}
await markUploadComplete({ id: response?.id });
if (markUploadCompleteError) {
toast.error(t("file_error__mark_complete_failed"));

return;
} else {
toast.success(t("file_success__upload_complete"));
navigate(`drawings/${response!.id}`);
}
} catch {
toast.error(t("error_in_createUpload"));
}
};
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

Fix file upload implementation and improve error handling.

Several issues need attention:

  1. FormData is created but not used
  2. Generic error handling could be more specific
  3. Upload progress tracking is missing
-      const formData = new FormData();
-      formData.append("file", file);
-
       const upload = await fetch(signedUrl, {
         method: "PUT",
         body: file,
+        headers: {
+          'Content-Type': 'application/vnd.excalidraw',
+        },
       });

       if (!upload.ok) {
-        toast.error(t("error_uploading_file"));
+        toast.error(t("error_uploading_file_with_status", { status: upload.status }));
         return;
       }

Also consider adding upload progress tracking:

const upload = await fetch(signedUrl, {
  method: "PUT",
  body: file,
  headers: {
    'Content-Type': 'application/vnd.excalidraw',
  },
  onUploadProgress: (progressEvent) => {
    const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    // Update progress state
  },
});

Comment on lines +39 to +52
const { mutateAsync: markUploadComplete, error: markUploadCompleteError } =
useMutation({
mutationFn: mutate(routes.markUploadCompleted, {
pathParams: { id: id || "" },
}),
});

const { mutateAsync: createUpload } = useMutation({
mutationFn: mutate(routes.createUpload),
onSuccess: (response: CreateFileResponse) => {
setId(response.id);
},
});

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance mutation hooks with better error handling and retry logic.

The mutation hooks could benefit from:

  1. Error handling for createUpload
  2. Retry configuration for transient failures
  3. Loading states for better UX
   const { mutateAsync: markUploadComplete, error: markUploadCompleteError } =
     useMutation({
       mutationFn: mutate(routes.markUploadCompleted, {
         pathParams: { id: id || "" },
       }),
+      retry: 3,
+      retryDelay: 1000,
     });

-  const { mutateAsync: createUpload } = useMutation({
+  const { mutateAsync: createUpload, error: createUploadError, isLoading: isUploading } = useMutation({
     mutationFn: mutate(routes.createUpload),
     onSuccess: (response: CreateFileResponse) => {
       setId(response.id);
     },
+    onError: (error) => {
+      toast.error(t("error_in_createUpload"));
+    },
+    retry: 3,
+    retryDelay: 1000,
   });
📝 Committable suggestion

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

Suggested change
const { mutateAsync: markUploadComplete, error: markUploadCompleteError } =
useMutation({
mutationFn: mutate(routes.markUploadCompleted, {
pathParams: { id: id || "" },
}),
});
const { mutateAsync: createUpload } = useMutation({
mutationFn: mutate(routes.createUpload),
onSuccess: (response: CreateFileResponse) => {
setId(response.id);
},
});
const { mutateAsync: markUploadComplete, error: markUploadCompleteError } =
useMutation({
mutationFn: mutate(routes.markUploadCompleted, {
pathParams: { id: id || "" },
}),
retry: 3,
retryDelay: 1000,
});
const { mutateAsync: createUpload, error: createUploadError, isLoading: isUploading } = useMutation({
mutationFn: mutate(routes.createUpload),
onSuccess: (response: CreateFileResponse) => {
setId(response.id);
},
onError: (error) => {
toast.error(t("error_in_createUpload"));
},
retry: 3,
retryDelay: 1000,
});

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Feb 21, 2025
Copy link

Conflicts have been detected against the base branch. Please merge the base branch into your branch.
cc: @NikhilA8606

See: https://docs.ohc.network/docs/contributing#how-to-resolve-merge-conflicts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
hold merge conflict pull requests with merge conflict
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add support for drawings as files by integrating excalidraw
3 participants