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

Add drawing feature #34

Closed
wants to merge 2 commits into from
Closed

Add drawing feature #34

wants to merge 2 commits into from

Conversation

harperreed
Copy link
Owner

@harperreed harperreed commented Oct 30, 2024

Fixes #2


For more details, open the Copilot Workspace session.

Summary by CodeRabbit

  • New Features

    • Introduced a drawing mode allowing users to draw on a canvas.
    • Added a toggle button for activating drawing features.
  • Enhancements

    • Updated the application’s metadata for improved SEO.
    • Integrated a new drawing canvas element in the user interface.
  • Style

    • Added CSS rules for the drawing canvas to ensure proper positioning and visibility.

Copy link

coderabbitai bot commented Oct 30, 2024

Walkthrough

The changes introduce new drawing functionality to the Orbiting application. A new button allows users to toggle a drawing mode, which displays a drawing canvas while hiding the main interface. The drawing canvas is initialized with specific dimensions and event listeners for mouse and touch interactions. Additionally, CSS rules are added to style the canvas, ensuring it overlays other elements. HTML modifications include the addition of the canvas and toggle button, enhancing user interactivity.

Changes

File Change Summary
assets/js/orbiting.js Added toggleDrawing() and setupDrawingCanvas(canvas) methods; implemented drawing event listeners.
assets/scss/components/_orbit.scss Added CSS rules for #drawingCanvas to position it fixed and cover the viewport.
content/_index.html Added metadata for title, URL, and description; included <canvas> element and toggle button for drawing.

Assessment against linked issues

Objective Addressed Explanation
Allow user to draw on touch screen

🐰 In the realm of orbiting delight,
A canvas now waits, ready to ignite.
With a toggle, we draw, both big and small,
Creating our visions, we’ll have a ball!
So grab your brush, let creativity flow,
In this magical space, let your colors glow! 🌈


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

sweep-ai bot commented Oct 30, 2024

Hey @harperreed, here is an example of how you can ask me to improve this pull request:

@Sweep Add unit tests for the `toggleDrawing` method to verify:
- The drawing canvas is properly shown/hidden
- The orbit element is properly toggled in opposite state to the canvas

📖 For more information on how to use Sweep, please read our documentation.

Copy link

netlify bot commented Oct 30, 2024

Deploy Preview for orbit-ing ready!

Name Link
🔨 Latest commit ef09815
🔍 Latest deploy log https://app.netlify.com/sites/orbit-ing/deploys/672807e82afe5000086aa2cc
😎 Deploy Preview https://deploy-preview-34--orbit-ing.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 100 (no change from production)
Accessibility: 77 (no change from production)
Best Practices: 100 (no change from production)
SEO: 100 (🟢 up 9 from production)
PWA: 80 (no change from production)
View the detailed breakdown and full score reports

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

Copy link

github-actions bot commented Oct 30, 2024

Visit the preview URL for this PR (updated for commit ef09815):

https://orbiting-14a48--pr34-add-drawing-nd8dx3dx.web.app

(expires Sun, 10 Nov 2024 23:32:31 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 7dc3c0322897b88ddfaefe1e19ebdfa3f8942fc3

@harperreed
Copy link
Owner Author

sweep: can you debug why the drawing doesn't seem to work on desktop

Copy link

sweep-ai bot commented Nov 3, 2024

can you debug why the drawing doesn't seem to work on desktop

Hey, @harperreed, I finished working on this. Here are the changes I made:


🚀 I've committed these changes to your branch via this PR! #34

Sweeping

Search Results

  • assets/js/orbiting.js
  • content/_index.html

Response

I'll help fix the drawing functionality on desktop by addressing the canvas sizing and coordinate mapping issues. Based on the existing patterns in the codebase, we need to properly handle canvas dimensions and add resize handling similar to how text resizing is handled.

Let's modify the setupDrawingCanvas method to properly initialize and maintain canvas dimensions:

assets/js/orbiting.js

--- 
+++ 
@@ -2,39 +2,92 @@
         const ctx = canvas.getContext("2d");
         let drawing = false;
 
+        // Set initial canvas dimensions
+        const updateCanvasSize = () => {
+            const viewportHeight = window.visualViewport
+                ? window.visualViewport.height
+                : window.innerHeight;
+            const viewportWidth = window.visualViewport
+                ? window.visualViewport.width
+                : window.innerWidth;
+
+            canvas.width = viewportWidth;
+            canvas.height = viewportHeight;
+
+            // Set up drawing context properties
+            ctx.strokeStyle = '#000';
+            ctx.lineWidth = 2;
+            ctx.lineCap = 'round';
+            ctx.lineJoin = 'round';
+        };
+
+        // Initial setup
+        updateCanvasSize();
+
+        // Add resize handlers
+        if (window.visualViewport) {
+            window.visualViewport.addEventListener('resize', updateCanvasSize);
+        } else {
+            window.addEventListener('resize', updateCanvasSize);
+        }
+
+        const getCoordinates = (e) => {
+            const rect = canvas.getBoundingClientRect();
+            const scaleX = canvas.width / rect.width;
+            const scaleY = canvas.height / rect.height;
+
+            if (e.touches) {
+                return {
+                    x: (e.touches[0].clientX - rect.left) * scaleX,
+                    y: (e.touches[0].clientY - rect.top) * scaleY
+                };
+            }
+            return {
+                x: (e.clientX - rect.left) * scaleX,
+                y: (e.clientY - rect.top) * scaleY
+            };
+        };
+
         const startDrawing = (e) => {
+            e.preventDefault();
             drawing = true;
+            const coords = getCoordinates(e);
             ctx.beginPath();
-            ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
+            ctx.moveTo(coords.x, coords.y);
         };
 
         const draw = (e) => {
+            e.preventDefault();
             if (!drawing) return;
-            ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
+            const coords = getCoordinates(e);
+            ctx.lineTo(coords.x, coords.y);
             ctx.stroke();
         };
 
-        const stopDrawing = () => {
+        const stopDrawing = (e) => {
+            e.preventDefault();
             drawing = false;
+            ctx.closePath();
         };
 
+        // Mouse events
         canvas.addEventListener("mousedown", startDrawing);
         canvas.addEventListener("mousemove", draw);
         canvas.addEventListener("mouseup", stopDrawing);
         canvas.addEventListener("mouseout", stopDrawing);
 
-        canvas.addEventListener("touchstart", (e) => {
-            const touch = e.touches[0];
-            startDrawing(touch);
-        });
-
-        canvas.addEventListener("touchmove", (e) => {
-            const touch = e.touches[0];
-            draw(touch);
-        });
-
+        // Touch events
+        canvas.addEventListener("touchstart", startDrawing);
+        canvas.addEventListener("touchmove", draw);
         canvas.addEventListener("touchend", stopDrawing);
         canvas.addEventListener("touchcancel", stopDrawing);
+
+        // Prevent scrolling while drawing
+        canvas.addEventListener('touchmove', (e) => {
+            e.preventDefault();
+        }, { passive: false });
+
+        this.log("Drawing canvas initialized");
     }
 }
 

The key changes made to fix the drawing functionality on desktop include:

  1. Added proper canvas dimension initialization and updating using visualViewport or window.innerWidth/Height
  2. Added a getCoordinates helper function to properly map mouse/touch coordinates to canvas coordinates
  3. Added scaling calculations to handle high DPI displays
  4. Improved event handling with preventDefault() to prevent unwanted behaviors
  5. Added proper touch event handling with passive: false to prevent scrolling while drawing
  6. Added proper context setup with stroke style, line width, and line join/cap settings
  7. Added proper path management with beginPath() and closePath()
  8. Added resize handling similar to the text resizing pattern used in the codebase

These changes should make the drawing functionality work correctly on desktop browsers while maintaining compatibility with mobile devices. The code follows the existing patterns in the codebase for handling viewport changes and event management.

Continue the conversation with Sweep here: https://app.sweep.dev/c/00c81a4e-ccff-488e-9a6f-5422cf2d6cf6.

🔄 Revert ef09815?

To revert Add drawing feature click the checkbox below.

📖 For more information on how to use Sweep, please read our documentation.

Tracking ID: 1e6dd9076f

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

🧹 Outside diff range comments (1)
content/_index.html (1)

Line range hint 1-5: Consider using clean URL format

The URL index.html includes a file extension. Consider using a clean URL format (e.g., / or /home) for better SEO and maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 11c9212 and ef09815.

📒 Files selected for processing (3)
  • assets/js/orbiting.js (2 hunks)
  • assets/scss/components/_orbit.scss (1 hunks)
  • content/_index.html (2 hunks)
🔇 Additional comments (1)
assets/js/orbiting.js (1)

86-90: Event Listener for Drawing Toggle Button Implemented Correctly

The event listener for the drawing toggle button is set up properly.

@@ -15,6 +15,8 @@
placeholder="type here"
></div>

<canvas id="drawingCanvas" style="display: none;"></canvas>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance canvas accessibility and initialization

The canvas element needs:

  1. ARIA attributes for accessibility
  2. Explicit dimensions to prevent rendering issues

Apply this diff:

-<canvas id="drawingCanvas" style="display: none;"></canvas>
+<canvas 
+    id="drawingCanvas" 
+    style="display: none;" 
+    aria-label="Drawing Canvas" 
+    role="img"
+    width="100%" 
+    height="100%">
+    Your browser does not support the canvas element.
+</canvas>
📝 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
<canvas id="drawingCanvas" style="display: none;"></canvas>
<canvas
id="drawingCanvas"
style="display: none;"
aria-label="Drawing Canvas"
role="img"
width="100%"
height="100%">
Your browser does not support the canvas element.
</canvas>

Comment on lines +38 to +40
<button id="toggleDrawingBtn" class="control-btn" title="Toggle Drawing">
<span class="icon">&#x1F58C;</span>
</button>
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Add keyboard shortcut and improve toggle state handling

The verification reveals:

  1. The drawing functionality has proper mouse/touch event handling for both desktop and mobile
  2. Other controls already use keyboard shortcuts (e.g., Ctrl+H)
  3. The toggle implementation exists but doesn't maintain ARIA state

Apply this updated diff to address both accessibility and state management:

-    <button id="toggleDrawingBtn" class="control-btn" title="Toggle Drawing">
+    <button 
+        id="toggleDrawingBtn" 
+        class="control-btn" 
+        title="Toggle Drawing (Ctrl+D)"
+        aria-pressed="false"
+        aria-label="Toggle Drawing Mode">
         <span class="icon">&#x1F58C;</span>
     </button>

Additional changes needed in assets/js/orbiting.js:

  • Add keyboard shortcut handler in the existing keydown listener:
case "d":
case "D":
    e.preventDefault();
    this.toggleDrawing();
    break;
  • Update ARIA state in toggleDrawing():
const drawingBtn = document.getElementById("toggleDrawingBtn");
drawingBtn.setAttribute("aria-pressed", !isDrawingEnabled);
🔗 Analysis chain

Improve button accessibility and desktop support

  1. Add keyboard shortcut for consistency with other controls
  2. Add ARIA attributes for toggle state

Apply this diff:

-    <button id="toggleDrawingBtn" class="control-btn" title="Toggle Drawing">
+    <button 
+        id="toggleDrawingBtn" 
+        class="control-btn" 
+        title="Toggle Drawing (Ctrl+D)"
+        aria-pressed="false"
+        aria-label="Toggle Drawing Mode">
         <span class="icon">&#x1F58C;</span>
     </button>

Let's verify the desktop compatibility issue mentioned in the PR:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for mouse/touch event handlers in JS files
echo "Checking event handlers in JS files..."
rg -A 5 "addEventListener\((('mouse|touch)|(`mouse|touch))" 

# Check if there are separate desktop/mobile handlers
echo "Checking for platform-specific code..."
rg -A 5 "(navigator\.maxTouchPoints|ontouchstart|userAgent)"

Length of output: 180


Script:

#!/bin/bash
# Search for mouse/touch event handlers in JS files with correct syntax
echo "Checking event handlers in JS files..."
rg -A 5 "addEventListener\([\'\"](?:mouse|touch)"

# Check for platform-specific code with correct syntax
echo "Checking for platform-specific code..."
rg -A 5 "(?:navigator\.maxTouchPoints|ontouchstart|userAgent)"

# Look for any drawing-related event handlers
echo "Checking drawing-related event handlers..."
rg -A 5 "toggleDrawingBtn"

Length of output: 1077


Script:

#!/bin/bash
# Search for mouse/touch event handlers with simpler pattern
echo "Checking event handlers in JS files..."
rg "addEventListener.*mouse|addEventListener.*touch" -A 5

# Look at the full context of drawing-related code
echo "Checking drawing toggle implementation..."
rg "toggleDrawing" -B 5 -A 10 assets/js/orbiting.js

# Check for keyboard event handlers
echo "Checking keyboard shortcuts..."
rg "addEventListener.*keydown|addEventListener.*keypress" -A 5

Length of output: 3507

@@ -110,3 +110,15 @@ body {
filter: invert(100%);
background: #000;
}

/* Pcbf8 */
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Remove or clarify the purpose of the "Pcbf8" comment.

The comment appears to be a temporary marker or debugging artifact. If it serves a specific purpose, please document it; otherwise, consider removing it.

Comment on lines +115 to +124
#drawingCanvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
z-index: 10;
background-color: rgba(255, 255, 255, 0.8);
display: none;
}
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Adjust z-index values to maintain proper layering hierarchy

Based on the z-index analysis:

  • Modal has highest z-index (2000)
  • Drawer, orbit container, and controls share z-index (1000)
  • Both orbit element and drawing canvas have z-index (10)

Recommended changes:

  • Set drawing canvas z-index to 1500 (between modal and drawer layers)
  • Keep other suggested improvements (touch-action, pointer-events, transitions)
 #drawingCanvas {
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 100vh;
-  z-index: 10;
+  z-index: 1500; /* Position between modal (2000) and drawer (1000) */
   background-color: rgba(255, 255, 255, 0.8);
   display: none;
+  touch-action: none;
+  pointer-events: auto;
+  transition: opacity 0.3s ease;
+  
+  @media (max-width: 768px) {
+    height: 100%;
+  }
 }
🔗 Analysis chain

Enhance drawing canvas styles for better user experience and compatibility.

Several improvements can be made to the drawing canvas styles:

  1. The z-index (10) conflicts with #orbit's z-index, which could cause layering issues
  2. Missing touch-specific properties for better mobile support
  3. No smooth transitions when toggling visibility

Apply these improvements:

 #drawingCanvas {
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 100vh;
-  z-index: 10;
+  z-index: 20; /* Ensure it's above #orbit */
   background-color: rgba(255, 255, 255, 0.8);
   display: none;
+  touch-action: none; /* Prevent default touch behaviors */
+  pointer-events: auto; /* Ensure it captures all pointer events */
+  transition: opacity 0.3s ease; /* Smooth transition when toggling */
+  
+  /* Adjust for different screen sizes */
+  @media (max-width: 768px) {
+    height: 100%; /* Use % instead of vh for better mobile support */
+  }
 }
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify if there are other elements with conflicting z-index values
rg -n "z-index:" --type css

Length of output: 393

Comment on lines +555 to +558
window.visualViewport.addEventListener('resize', updateCanvasSize);
} else {
window.addEventListener('resize', updateCanvasSize);
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Ensure Consistent Reference for updateCanvasSize

When adding the updateCanvasSize function as an event listener, ensure that the reference remains consistent to facilitate potential removal of the event listener in the future.

Comment on lines +611 to +614
// Prevent scrolling while drawing
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
}, { passive: false });
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Optimize touchmove Event Listener for Performance

Using { passive: false } in the touchmove event listener can impact scrolling performance. Verify if preventing the default behavior is necessary, and consider optimizing it to enhance performance.

Comment on lines +513 to +525
toggleDrawing() {
const drawingCanvas = document.getElementById("drawingCanvas");
const isDrawingEnabled = drawingCanvas.style.display === "block";

if (isDrawingEnabled) {
drawingCanvas.style.display = "none";
this.orbit.style.display = "block";
} else {
drawingCanvas.style.display = "block";
this.orbit.style.display = "none";
this.setupDrawingCanvas(drawingCanvas);
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add Null Checks for DOM Elements in toggleDrawing Method

To prevent potential runtime errors, ensure that drawingCanvas and this.orbit exist before accessing their properties.

Apply this diff to add null checks:

 toggleDrawing() {
     const drawingCanvas = document.getElementById("drawingCanvas");
+    if (!drawingCanvas) {
+        this.logError("Drawing canvas element not found");
+        return;
+    }
     const isDrawingEnabled = drawingCanvas.style.display === "block";

     if (isDrawingEnabled) {
         drawingCanvas.style.display = "none";
+        if (this.orbit) {
             this.orbit.style.display = "block";
+        } else {
+            this.logError("Orbit element not found");
+        }
     } else {
         drawingCanvas.style.display = "block";
+        if (this.orbit) {
             this.orbit.style.display = "none";
+        } else {
+            this.logError("Orbit element not found");
+        }
         this.setupDrawingCanvas(drawingCanvas);
     }
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +527 to +617
setupDrawingCanvas(canvas) {
const ctx = canvas.getContext("2d");
let drawing = false;

// Set initial canvas dimensions
const updateCanvasSize = () => {
const viewportHeight = window.visualViewport
? window.visualViewport.height
: window.innerHeight;
const viewportWidth = window.visualViewport
? window.visualViewport.width
: window.innerWidth;

canvas.width = viewportWidth;
canvas.height = viewportHeight;

// Set up drawing context properties
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
};

// Initial setup
updateCanvasSize();

// Add resize handlers
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', updateCanvasSize);
} else {
window.addEventListener('resize', updateCanvasSize);
}

const getCoordinates = (e) => {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;

if (e.touches) {
return {
x: (e.touches[0].clientX - rect.left) * scaleX,
y: (e.touches[0].clientY - rect.top) * scaleY
};
}
return {
x: (e.clientX - rect.left) * scaleX,
y: (e.clientY - rect.top) * scaleY
};
};

const startDrawing = (e) => {
e.preventDefault();
drawing = true;
const coords = getCoordinates(e);
ctx.beginPath();
ctx.moveTo(coords.x, coords.y);
};

const draw = (e) => {
e.preventDefault();
if (!drawing) return;
const coords = getCoordinates(e);
ctx.lineTo(coords.x, coords.y);
ctx.stroke();
};

const stopDrawing = (e) => {
e.preventDefault();
drawing = false;
ctx.closePath();
};

// Mouse events
canvas.addEventListener("mousedown", startDrawing);
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", stopDrawing);
canvas.addEventListener("mouseout", stopDrawing);

// Touch events
canvas.addEventListener("touchstart", startDrawing);
canvas.addEventListener("touchmove", draw);
canvas.addEventListener("touchend", stopDrawing);
canvas.addEventListener("touchcancel", stopDrawing);

// Prevent scrolling while drawing
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
}, { passive: false });

this.log("Drawing canvas initialized");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Prevent Multiple Event Listeners and Potential Memory Leaks

Each time setupDrawingCanvas is called, new event listeners are added to canvas and window, which could lead to multiple listeners being attached if toggleDrawing is toggled multiple times. Consider adding a flag to ensure that event listeners are only added once, or remove them when the drawing canvas is hidden.

Apply this diff to manage event listeners appropriately:

+        // Add a flag to check if event listeners are already added
+        if (this.drawingCanvasInitialized) {
+            return;
+        }

         setupDrawingCanvas(canvas) {
             const ctx = canvas.getContext("2d");
             let drawing = false;

             // Set initial canvas dimensions
             const updateCanvasSize = () => {
                 // ...
             };

             // Initial setup
             updateCanvasSize();

             // Add resize handlers
             if (window.visualViewport) {
                 window.visualViewport.addEventListener('resize', updateCanvasSize);
             } else {
                 window.addEventListener('resize', updateCanvasSize);
             }

             // Event handlers...
             // Mouse events
             canvas.addEventListener("mousedown", startDrawing);
             // ...

             // Touch events
             canvas.addEventListener("touchstart", startDrawing);
             // ...

             // Prevent scrolling while drawing
             canvas.addEventListener('touchmove', (e) => {
                 e.preventDefault();
             }, { passive: false });

+            // Set flag to indicate event listeners have been added
+            this.drawingCanvasInitialized = true;

             this.log("Drawing canvas initialized");
         }

Alternatively, remove event listeners when the drawing canvas is hidden:

        toggleDrawing() {
            const drawingCanvas = document.getElementById("drawingCanvas");
            const isDrawingEnabled = drawingCanvas.style.display === "block";

            if (isDrawingEnabled) {
                drawingCanvas.style.display = "none";
                this.orbit.style.display = "block";
+               this.teardownDrawingCanvas(drawingCanvas);
            } else {
                drawingCanvas.style.display = "block";
                this.orbit.style.display = "none";
                this.setupDrawingCanvas(drawingCanvas);
            }
        }

+        teardownDrawingCanvas(canvas) {
+            // Remove event listeners added in setupDrawingCanvas
+            // Example:
+            // canvas.removeEventListener("mousedown", startDrawing);
+            // ... Remove other event listeners accordingly ...
+        }

Committable suggestion skipped: line range outside the PR's diff.

@harperreed harperreed closed this Nov 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

add drawing
1 participant