Skip to content

feat: add copy button to code blocks#7243

Open
deepak0x wants to merge 1 commit intoRocketChat:developfrom
deepak0x:feat/code-block-copy-button
Open

feat: add copy button to code blocks#7243
deepak0x wants to merge 1 commit intoRocketChat:developfrom
deepak0x:feat/code-block-copy-button

Conversation

@deepak0x
Copy link
Copy Markdown
Contributor

@deepak0x deepak0x commented Apr 24, 2026

Code blocks in messages don't have a way to copy just the code. You have to long-press the whole message and use "Copy", which grabs everything including the backtick markers. This adds a small copy icon to the top-right corner of each code block — tap it, and the code content goes to the clipboard without any markdown syntax. A toast confirms the copy.

Issue(s)

Closes #5499

How to test or reproduce

  1. Send a message containing a code block (triple backticks)
  2. Look for the copy icon in the top-right corner of the rendered code block
  3. Tap it
  4. Paste somewhere — should contain only the code, no backtick markers
  5. A "Copied to clipboard!" toast should appear

Types of changes

  • Bugfix (non-breaking change which fixes an issue)
  • Improvement (non-breaking change which improves a current function)
  • New feature (non-breaking change which adds functionality)
  • Documentation update (if none of the other choices apply)

Checklist

  • I have read the CONTRIBUTING doc
  • I have signed the CLA
  • Lint and unit tests pass locally with my changes
  • I have added tests that prove my fix is effective or that my feature works (if applicable)
  • I have added necessary documentation (if applicable)
  • Any dependent changes have been merged and published in downstream modules

Further comments

Two files changed. Code.tsx gets a Pressable with a copy icon that extracts CODE_LINE text, joins it with newlines, and sends it to the clipboard. Uses the same Clipboard + toast pattern as Link.tsx. The styles.ts file gets position: relative on the code block and position: absolute on the button.

Summary by CodeRabbit

  • New Features
    • Added a copy-to-clipboard button to code blocks positioned in the top-right corner. Users can copy code snippets with a single click, with a confirmation message displayed upon successful copying.

Code blocks now have a copy icon in the top-right corner. Pressing it
copies the code content to the clipboard without the markdown backtick
markers, and shows a "Copied to clipboard!" toast.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 24, 2026

Walkthrough

A copy-to-clipboard feature is added to code blocks. Users can press a button in the top-right corner to extract plain text content (excluding triple-backtick delimiters) and copy it to the clipboard, with a success notification displayed.

Changes

Cohort / File(s) Summary
Code Block Copy Button
app/containers/markdown/components/code/Code.tsx
Adds Pressable button overlay with CustomIcon that extracts plain text from CODE_LINE blocks, copies via Clipboard.setString, and emits an event with localized "Copied_to_clipboard" notification message.
Code Block Styling
app/containers/markdown/styles.ts
Updates codeBlock style with position: 'relative' and introduces new codeBlockCopyButton style for absolute top-right positioning with elevated zIndex.

Sequence Diagram

sequenceDiagram
    participant User
    participant Pressable as Copy Button<br/>(Pressable)
    participant Code as Code Component
    participant Clipboard
    participant EventEmitter
    participant UI as Notification UI

    User->>Pressable: Press copy button
    Pressable->>Code: Trigger press handler
    Code->>Code: Extract plain text from<br/>CODE_LINE blocks
    Code->>Clipboard: setString(extracted text)
    Clipboard-->>Code: Text copied
    Code->>EventEmitter: emit(LISTENER,<br/>Copied_to_clipboard msg)
    EventEmitter->>UI: Trigger notification
    UI-->>User: Show success message
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

type: feature

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and clearly describes the primary change: adding a copy button feature to code blocks.
Linked Issues check ✅ Passed The PR fully implements the core requirement from issue #5499: a copy button at the top-right corner that copies only the internal text of code blocks without backticks.
Out of Scope Changes check ✅ Passed All changes are narrowly scoped to implementing the copy button feature; no unrelated modifications are present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Copy Markdown
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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/containers/markdown/components/code/Code.tsx`:
- Around line 39-41: The copy Pressable lacks accessibility metadata; update the
Pressable that wraps CustomIcon (the element using styles.codeBlockCopyButton
and onPress={handleCopy}) to include accessibilityRole="button", a descriptive
accessibilityLabel like "Copy code to clipboard" (or "Copy code" if shorter),
and an accessibilityHint such as "Copies the code block to the clipboard" so
screen readers convey purpose and action; keep the existing onPress handler
(handleCopy) and styling unchanged.

In `@app/containers/markdown/styles.ts`:
- Around line 80-91: The copy button overlay (codeBlockCopyButton) sits at top:
4,right: 4 and overlaps the first line because codeBlock only has padding: 4;
update the styles so the codeBlock reserves space for the button—add a right
padding sized to the icon plus spacing (e.g., paddingRight: 28 or 32) to
codeBlock and keep codeBlockCopyButton positioned absolutely; this ensures code
content isn't occluded while preserving the existing button positioning and
zIndex.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ad60520f-7a0d-4203-87b1-805cf253bd8c

📥 Commits

Reviewing files that changed from the base of the PR and between 53c3364 and 354e494.

📒 Files selected for processing (2)
  • app/containers/markdown/components/code/Code.tsx
  • app/containers/markdown/styles.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{js,ts,jsx,tsx}: Use descriptive names for functions, variables, and classes that clearly convey their purpose
Write comments that explain the 'why' behind code decisions, not the 'what'
Keep functions small and focused on a single responsibility
Use const by default, let when reassignment is needed, and avoid var
Prefer async/await over .then() chains for handling asynchronous operations
Use explicit error handling with try/catch blocks for async operations
Avoid deeply nested code; refactor complex logic into helper functions

Files:

  • app/containers/markdown/styles.ts
  • app/containers/markdown/components/code/Code.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript for type safety; add explicit type annotations to function parameters and return types
Prefer interfaces over type aliases for defining object shapes in TypeScript
Use enums for sets of related constants rather than magic strings or numbers

**/*.{ts,tsx}: Use TypeScript with strict mode enabled and baseUrl set to app/ for module imports
Support iOS 13.4+ and Android 6.0+ as minimum target platforms

Files:

  • app/containers/markdown/styles.ts
  • app/containers/markdown/components/code/Code.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx,js,jsx}: Use tabs for indentation with single quotes, 130 character line width, no trailing commas, and avoid arrow function parentheses when possible
Use ESLint with @rocket.chat/eslint-config base including React, React Native, TypeScript, and Jest plugins

Files:

  • app/containers/markdown/styles.ts
  • app/containers/markdown/components/code/Code.tsx
app/containers/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Create reusable UI components in app/containers/ directory

Files:

  • app/containers/markdown/styles.ts
  • app/containers/markdown/components/code/Code.tsx
🧠 Learnings (1)
📚 Learning: 2026-03-10T15:21:45.098Z
Learnt from: Rohit3523
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7046
File: app/containers/InAppNotification/NotifierComponent.stories.tsx:46-75
Timestamp: 2026-03-10T15:21:45.098Z
Learning: In `app/containers/InAppNotification/NotifierComponent.tsx` (React Native, Rocket.Chat), `NotifierComponent` is exported as a Redux-connected component via `connect(mapStateToProps)`. The `isMasterDetail` prop is automatically injected from `state.app.isMasterDetail` and does not need to be passed explicitly at call sites or in Storybook stories that use the default (connected) export.

Applied to files:

  • app/containers/markdown/components/code/Code.tsx
🔇 Additional comments (1)
app/containers/markdown/components/code/Code.tsx (1)

27-27: Both Copied_to_clipboard i18n key and copy CustomIcon mapping exist in the codebase.

The i18n key is defined across all locale files (including en.json), and the CustomIcon 'copy' mapping exists in mappedIcons.js. The toast and icon will render correctly.

Comment on lines +39 to +41
<Pressable style={styles.codeBlockCopyButton} onPress={handleCopy} hitSlop={8}>
<CustomIcon name='copy' size={18} color={colors.fontSecondaryInfo} />
</Pressable>
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

Missing accessibility props on the copy button.

The Pressable has no accessibilityLabel or accessibilityRole, so screen reader users will hear nothing meaningful (or just "button" with no context) when they focus this control. This makes the copy action undiscoverable for VoiceOver/TalkBack users.

♿ Proposed fix
-			<Pressable style={styles.codeBlockCopyButton} onPress={handleCopy} hitSlop={8}>
+			<Pressable
+				style={styles.codeBlockCopyButton}
+				onPress={handleCopy}
+				hitSlop={8}
+				accessibilityRole='button'
+				accessibilityLabel={I18n.t('Copy')}>
 				<CustomIcon name='copy' size={18} color={colors.fontSecondaryInfo} />
 			</Pressable>

As per coding guidelines: "Use descriptive names ... that clearly convey their purpose" — the same principle applies to accessibility labels exposed to assistive technologies.

📝 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
<Pressable style={styles.codeBlockCopyButton} onPress={handleCopy} hitSlop={8}>
<CustomIcon name='copy' size={18} color={colors.fontSecondaryInfo} />
</Pressable>
<Pressable
style={styles.codeBlockCopyButton}
onPress={handleCopy}
hitSlop={8}
accessibilityRole='button'
accessibilityLabel={I18n.t('Copy')}>
<CustomIcon name='copy' size={18} color={colors.fontSecondaryInfo} />
</Pressable>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/containers/markdown/components/code/Code.tsx` around lines 39 - 41, The
copy Pressable lacks accessibility metadata; update the Pressable that wraps
CustomIcon (the element using styles.codeBlockCopyButton and
onPress={handleCopy}) to include accessibilityRole="button", a descriptive
accessibilityLabel like "Copy code to clipboard" (or "Copy code" if shorter),
and an accessibilityHint such as "Copies the code block to the clipboard" so
screen readers convey purpose and action; keep the existing onPress handler
(handleCopy) and styling unchanged.

Comment on lines 80 to 91
codeBlock: {
borderWidth: 1,
borderRadius: 4,
padding: 4
padding: 4,
position: 'relative' as const
},
codeBlockCopyButton: {
position: 'absolute' as const,
top: 4,
right: 4,
zIndex: 1
},
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 | 🟡 Minor

Copy button may overlap the first line of code.

codeBlock has padding: 4 and the button is positioned at top: 4, right: 4 with an 18px icon (plus hitSlop) and zIndex: 1. That places the icon directly on top of the beginning of the first code line, so any text at the end of line 1 will be visually occluded by the overlay.

Consider reserving space for the button—e.g., add a right padding to codeBlock (or right margin on the first line) sized to fit the icon—so code content isn't hidden behind the copy affordance.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/containers/markdown/styles.ts` around lines 80 - 91, The copy button
overlay (codeBlockCopyButton) sits at top: 4,right: 4 and overlaps the first
line because codeBlock only has padding: 4; update the styles so the codeBlock
reserves space for the button—add a right padding sized to the icon plus spacing
(e.g., paddingRight: 28 or 32) to codeBlock and keep codeBlockCopyButton
positioned absolutely; this ensures code content isn't occluded while preserving
the existing button positioning and zIndex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feature: Code Block Optimization

1 participant