Skip to content

feat: add Clear Code and Copy Output buttons to LiveCodeRunner#992

Open
OmanshiRaj wants to merge 1 commit into
durdana3105:mainfrom
OmanshiRaj:feat/live-code-runner-clear-copy
Open

feat: add Clear Code and Copy Output buttons to LiveCodeRunner#992
OmanshiRaj wants to merge 1 commit into
durdana3105:mainfrom
OmanshiRaj:feat/live-code-runner-clear-copy

Conversation

@OmanshiRaj

@OmanshiRaj OmanshiRaj commented Jun 15, 2026

Copy link
Copy Markdown

Closes #928
Added two utility buttons to the LiveCodeRunner component in study rooms:

Clear button (Trash2 icon) — resets both the code editor and output panel in one click, replacing the tedious select-all + delete workflow
Copy button (Clipboard icon) — appears in the Output section header when output is present, uses the Clipboard API to copy output text with success/error toast feedback

Both buttons are disabled while code is running (isRunning: true) to prevent accidental state changes mid-execution.

Summary by CodeRabbit

  • New Features
    • Added Copy button to output pane for easy clipboard access with confirmation feedback
    • Added Clear button to reset both code and output simultaneously

@vercel

vercel Bot commented Jun 15, 2026

Copy link
Copy Markdown

@OmanshiRaj is attempting to deploy a commit to the durdana3105's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

LiveCodeRunner gains two new user actions: a "Clear" button that resets both code and output state, and a "Copy" button in the output pane header that writes current output to the clipboard with toast feedback. Two new icons are imported and two internal handlers implement the logic.

Changes

Copy Output & Clear Code in LiveCodeRunner

Layer / File(s) Summary
Icon imports and action handlers
src/components/studyroom/LiveCodeRunner.tsx
Clipboard and Trash2 added to lucide-react imports. handleCopyOutput uses the Clipboard API with toast.success/toast.error feedback; handleClearCode sets both code and output to empty strings.
Clear and Copy button UI
src/components/studyroom/LiveCodeRunner.tsx
A "Clear" button (Trash2 icon) added to the toolbar alongside Run/Share, disabled while isRunning. Output pane header conditionally renders a "Copy" button (Clipboard icon) when output is non-empty, triggering handleCopyOutput.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~4 minutes

Poem

🐇 Hop hop, the runner is tidy now,
A Trash2 clears the mess somehow.
Clipboard grabs the output neat,
Toast pops up — success so sweet!
Clean slates and copied lines, hooray,
The bunny coded well today! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add Clear Code and Copy Output buttons to LiveCodeRunner' directly and accurately summarizes the main changes in the PR.
Linked Issues check ✅ Passed The PR implements all three requirements from issue #928: Clear button resets code/output, Copy button uses Clipboard API for output, and both are disabled during code execution.
Out of Scope Changes check ✅ Passed All changes in LiveCodeRunner.tsx are directly related to adding the Clear and Copy buttons as specified in issue #928, with no unrelated modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/components/studyroom/LiveCodeRunner.tsx (1)

27-34: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add an internal re-entry guard in runCode to prevent duplicate executions.

The button is visually/HTML-disabled, but runCode itself still has no isRunning guard. A fast/re-entrant trigger can still schedule duplicate fetches before state disable settles.

Proposed fix
   const runCode = async () => {
+    if (isRunning) return;
     if (!code.trim()) {
       toast.error("Please enter some code to run");
       return;
     }

Also applies to: 136-138

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/studyroom/LiveCodeRunner.tsx` around lines 27 - 34, The
runCode async function lacks an internal re-entry guard to prevent duplicate
executions. Even though the button is HTML-disabled, rapid calls to runCode can
schedule multiple fetches before the setIsRunning state update takes effect. Add
a guard condition at the start of the runCode function that checks if isRunning
is already true and returns early if so, ensuring the function body only
executes once at a time and preventing duplicate API calls.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/components/studyroom/LiveCodeRunner.tsx`:
- Around line 83-89: The handleCopyOutput function calls
navigator.clipboard.writeText without guarding against unavailability in
non-secure contexts (HTTP), which can cause synchronous errors before the
promise handler executes. Add a try/catch block around the clipboard operation
and use optional chaining to check if navigator.clipboard exists before calling
writeText. This ensures the code gracefully handles environments where the
Clipboard API is undefined or unavailable, displaying an appropriate error toast
instead of crashing.

---

Outside diff comments:
In `@src/components/studyroom/LiveCodeRunner.tsx`:
- Around line 27-34: The runCode async function lacks an internal re-entry guard
to prevent duplicate executions. Even though the button is HTML-disabled, rapid
calls to runCode can schedule multiple fetches before the setIsRunning state
update takes effect. Add a guard condition at the start of the runCode function
that checks if isRunning is already true and returns early if so, ensuring the
function body only executes once at a time and preventing duplicate API calls.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: af2a84b7-2341-45c6-8722-57c32d397165

📥 Commits

Reviewing files that changed from the base of the PR and between 7200d81 and 9d164d0.

📒 Files selected for processing (1)
  • src/components/studyroom/LiveCodeRunner.tsx

Comment on lines +83 to +89
const handleCopyOutput = () => {
if (!output) { toast.error("No output to copy"); return; }
navigator.clipboard.writeText(output).then(
() => toast.success("Output copied!"),
() => toast.error("Failed to copy output")
);
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

MDN Clipboard API: is navigator.clipboard available only in secure contexts, and what are the main browser support caveats for Clipboard.writeText?

💡 Result:

Yes, the navigator.clipboard property is available only in secure contexts (HTTPS) [1][2][3]. If accessed in an insecure context (such as HTTP or local files, excluding localhost), navigator.clipboard will be undefined, and attempts to call methods like writeText will result in an error [4]. Beyond the secure context requirement, the main browser support caveats for Clipboard.writeText include the following: 1. Transient User Activation: Most browsers require the call to be made in response to a user-initiated action (such as a click or keypress) [2][5]. Attempting to write to the clipboard on page load or without a direct user gesture often fails or triggers browser security prompts [5][4]. 2. Focus Requirements: For Chromium-based browsers, the script must typically be running in the active, focused tab to successfully write to the clipboard [5][4]. 3. Permission Policies: The browser may require explicit permission (e.g., the clipboard-write permission) or display a prompt to the user before allowing the operation [2][5]. Behavior can vary between browsers, particularly concerning whether transient activation is required or if a persistent permission grant is available [2][5]. 4. Browser Interoperability: While widely supported, specific implementation details regarding user gestures and permission prompts can differ between browsers (e.g., Firefox and Safari vs. Chromium-based browsers) [5]. Developers should always wrap these calls in try-catch blocks to handle scenarios where the operation is denied or unavailable [6][4].

Citations:


🏁 Script executed:

cd /tmp && find . -type f -name "LiveCodeRunner.tsx" 2>/dev/null | head -5

Repository: durdana3105/peer-learning

Length of output: 51


🏁 Script executed:

rg -l "LiveCodeRunner" --type=tsx 2>/dev/null | head -3

Repository: durdana3105/peer-learning

Length of output: 51


🏁 Script executed:

git ls-files | grep -i livecode | head -10

Repository: durdana3105/peer-learning

Length of output: 113


🏁 Script executed:

wc -l src/components/studyroom/LiveCodeRunner.tsx

Repository: durdana3105/peer-learning

Length of output: 117


🏁 Script executed:

cat -n src/components/studyroom/LiveCodeRunner.tsx | sed -n '75,140p'

Repository: durdana3105/peer-learning

Length of output: 3038


🏁 Script executed:

cat -n src/components/studyroom/LiveCodeRunner.tsx | sed -n '140,185p'

Repository: durdana3105/peer-learning

Length of output: 2293


Guard navigator.clipboard before calling writeText to handle unavailability in non-secure contexts.

The Clipboard API is undefined in HTTP contexts and may throw synchronously before your .then() handler runs. Wrap this in a try/catch block with an optional chaining check as shown below.

Proposed fix
-  const handleCopyOutput = () => {
-    if (!output) { toast.error("No output to copy"); return; }
-    navigator.clipboard.writeText(output).then(
-      () => toast.success("Output copied!"),
-      () => toast.error("Failed to copy output")
-    );
-  };
+  const handleCopyOutput = async () => {
+    if (!output) {
+      toast.error("No output to copy");
+      return;
+    }
+    if (!navigator.clipboard?.writeText) {
+      toast.error("Clipboard is not available in this browser/context");
+      return;
+    }
+    try {
+      await navigator.clipboard.writeText(output);
+      toast.success("Output copied!");
+    } catch {
+      toast.error("Failed to copy output");
+    }
+  };
📝 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 handleCopyOutput = () => {
if (!output) { toast.error("No output to copy"); return; }
navigator.clipboard.writeText(output).then(
() => toast.success("Output copied!"),
() => toast.error("Failed to copy output")
);
};
const handleCopyOutput = async () => {
if (!output) {
toast.error("No output to copy");
return;
}
if (!navigator.clipboard?.writeText) {
toast.error("Clipboard is not available in this browser/context");
return;
}
try {
await navigator.clipboard.writeText(output);
toast.success("Output copied!");
} catch {
toast.error("Failed to copy output");
}
};
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/studyroom/LiveCodeRunner.tsx` around lines 83 - 89, The
handleCopyOutput function calls navigator.clipboard.writeText without guarding
against unavailability in non-secure contexts (HTTP), which can cause
synchronous errors before the promise handler executes. Add a try/catch block
around the clipboard operation and use optional chaining to check if
navigator.clipboard exists before calling writeText. This ensures the code
gracefully handles environments where the Clipboard API is undefined or
unavailable, displaying an appropriate error toast instead of crashing.

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.

feat: add Clear Code and Copy Output buttons to LiveCodeRunner

1 participant