Skip to content

Expandable code blocks #1683

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

Merged
merged 5 commits into from
Feb 28, 2025
Merged

Expandable code blocks #1683

merged 5 commits into from
Feb 28, 2025

Conversation

samejr
Copy link
Member

@samejr samejr commented Feb 9, 2025

This adds a new "Expand" icon next to the copy button on all code blocks

CleanShot 2025-02-09 at 13 08 22

It opens the code in a large modal so you can view it more clearly

CleanShot 2025-02-09 at 13 09 27

It's default visible for all code blocks but can be turned off.

Summary by CodeRabbit

  • New Features
    • Introduced a modal view for code blocks, enabling users to open and interact with code in a dedicated popup with viewing and copy options.
  • Style
    • Refined the appearance of modal titles for improved text readability and a cleaner user interface.

Copy link

changeset-bot bot commented Feb 9, 2025

⚠️ No Changeset found

Latest commit: 642e076

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Feb 9, 2025

Walkthrough

The CodeBlock component now supports an optional modal view for displaying code. A new property, showOpenInModal, allows the component to render an extra button that opens a modal. Additional state variables (modalCopied and isModalOpen) manage the modal’s visibility and clipboard copy status. The modal renders the code with existing highlighting and provides its own copy functionality using Dialog components. Separately, the DialogTitle component’s styling was updated by removing a line-height modifier.

Changes

File(s) Change Summary
apps/webapp/.../components/code/CodeBlock.tsx Added optional property showOpenInModal to CodeBlockProps; introduced state variables modalCopied and isModalOpen; implemented modal rendering with code display and copy functionality using Dialog components and an ArrowsPointingOutIcon.
apps/webapp/.../components/primitives/Dialog.tsx Removed the "leading-none" class from the DialogTitle component to modify the line height styling for the title text.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CB as CodeBlock
    participant D as Dialog

    U->>CB: Click "Open in Modal" button
    CB-->>CB: Set isModalOpen = true
    CB->>D: Render modal with code and copy button
    U->>D: Click modal copy button
    D-->>CB: Trigger onModalCopied callback
    CB-->>CB: Set modalCopied = true
Loading

Poem

I'm a little rabbit, hopping with glee,
Code now opens in a modal, easy to see.
With a click, the code unfolds its view,
And a copy tap brings magic anew.
Hoppy updates make my circuits sing,
Celebrating changes with a joyful spring!


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
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 (4)
apps/webapp/app/components/code/CodeBlock.tsx (4)

203-204: Consider combining copy states

The component now maintains two separate copy states (copied and modalCopied) that serve the same purpose. Consider unifying them into a single state to reduce complexity.

-const [copied, setCopied] = useState(false);
-const [modalCopied, setModalCopied] = useState(false);
+const [copyState, setCopyState] = useState({ main: false, modal: false });

219-230: Consolidate copy handlers

The onModalCopied function is nearly identical to onCopied. Consider creating a single reusable copy handler.

-const onCopied = useCallback(
+const createCopyHandler = useCallback(
+  (setState: (value: boolean) => void) =>
   (event: React.MouseEvent<HTMLButtonElement>) => {
     event.preventDefault();
     event.stopPropagation();
     navigator.clipboard.writeText(code);
-    setCopied(true);
+    setState(true);
     setTimeout(() => {
-      setCopied(false);
+      setState(false);
     }, 1500);
   },
-  [code]
+  [code]
 );

-const onModalCopied = useCallback(/* ... */);

413-433: Consider accessibility improvements for the modal

The modal implementation looks good, but could benefit from some accessibility enhancements:

  1. Add aria-label to the modal for screen readers
  2. Consider trapping focus within the modal when open
  3. Add keyboard shortcuts for common actions
 <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
-  <DialogContent className="flex flex-col gap-0 p-0 pt-[2.9rem] sm:h-[80vh] sm:max-h-[80vh] sm:max-w-[80vw]">
+  <DialogContent 
+    className="flex flex-col gap-0 p-0 pt-[2.9rem] sm:h-[80vh] sm:max-h-[80vh] sm:max-w-[80vw]"
+    aria-label="Code block expanded view"
+  >

444-449: Consider preserving text size preference

The modal view forces a larger text size (text-base) compared to the inline view (text-xs). Consider making this configurable or preserving the user's text size preference.

 <pre
   className={cn(
-    "relative mr-2 font-mono text-base leading-relaxed",
+    "relative mr-2 font-mono leading-relaxed",
+    modalTextSize ?? "text-base",
     inheritedClassName
   )}
   style={inheritedStyle}
   dir="ltr"
 >
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1f1a6b0 and 3eeadc8.

📒 Files selected for processing (2)
  • apps/webapp/app/components/code/CodeBlock.tsx (6 hunks)
  • apps/webapp/app/components/primitives/Dialog.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
apps/webapp/app/components/primitives/Dialog.tsx (1)

97-97: LGTM! Style adjustment for dialog titles

The removal of leading-none and tracking-tight classes improves readability of dialog titles, particularly beneficial for the new code block modal view.

apps/webapp/app/components/code/CodeBlock.tsx (2)

1-8: LGTM! Well-organized imports

The new imports are properly organized and include all necessary components for the modal functionality.


58-59: LGTM! Clear prop definition

The showOpenInModal prop is well-documented and follows the existing pattern of boolean flags.

Copy link
Member

@matt-aitken matt-aitken left a comment

Choose a reason for hiding this comment

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

It's hard to tell on my phone but are we duplicating all the syntax highlighting code? If so we should pull that out until a separate non-exported component.

@@ -193,6 +200,9 @@ export const CodeBlock = forwardRef<HTMLDivElement, CodeBlockProps>(
) => {
const [mouseOver, setMouseOver] = useState(false);
const [copied, setCopied] = useState(false);
const [modalCopied, setModalCopied] = useState(false);
Copy link
Member

Choose a reason for hiding this comment

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

Can't we use the existing copied state?

Copy link
Member Author

Choose a reason for hiding this comment

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

I tried this at first but when you do, it triggers the copied UI to animated below the modal. You can see it through the modal's overlay and it looks like a bug.

@@ -206,6 +216,19 @@ export const CodeBlock = forwardRef<HTMLDivElement, CodeBlockProps>(
[code]
);

const onModalCopied = useCallback(
Copy link
Member

Choose a reason for hiding this comment

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

Can't we use the existing copy callback?

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

♻️ Duplicate comments (1)
apps/webapp/app/components/code/CodeBlock.tsx (1)

219-230: 🛠️ Refactor suggestion

Avoid duplicating copy logic.

The onModalCopied callback duplicates the logic from onCopied. Consider creating a reusable copy function.

+const copyToClipboard = useCallback(
+  (event: React.MouseEvent<HTMLButtonElement>, setStateFn: (value: boolean) => void) => {
+    event.preventDefault();
+    event.stopPropagation();
+    navigator.clipboard.writeText(code);
+    setStateFn(true);
+    setTimeout(() => {
+      setStateFn(false);
+    }, 1500);
+  },
+  [code]
+);

-const onCopied = useCallback(
-  (event: React.MouseEvent<HTMLButtonElement>) => {
-    event.preventDefault();
-    event.stopPropagation();
-    navigator.clipboard.writeText(code);
-    setCopied(true);
-    setTimeout(() => {
-      setCopied(false);
-    }, 1500);
-  },
-  [code]
-);

-const onModalCopied = useCallback(
-  (event: React.MouseEvent<HTMLButtonElement>) => {
-    event.preventDefault();
-    event.stopPropagation();
-    navigator.clipboard.writeText(code);
-    setModalCopied(true);
-    setTimeout(() => {
-      setModalCopied(false);
-    }, 1500);
-  },
-  [code]
-);

+const onCopied = useCallback(
+  (event: React.MouseEvent<HTMLButtonElement>) => copyToClipboard(event, setCopied),
+  [copyToClipboard]
+);

+const onModalCopied = useCallback(
+  (event: React.MouseEvent<HTMLButtonElement>) => copyToClipboard(event, setModalCopied),
+  [copyToClipboard]
+);
🧹 Nitpick comments (3)
apps/webapp/app/components/code/CodeBlock.tsx (3)

58-59: Consider adding JSDoc comment for the new prop.

Add documentation for the showOpenInModal prop to maintain consistency with other props.

+  /** Whether to show the expand button that opens the code in a modal */
   showOpenInModal?: boolean;

203-204: Consider using a single state object for related states.

The component now has multiple copy-related states (copied, modalCopied) and modal state. Consider combining them into a single state object for better maintainability.

-const [copied, setCopied] = useState(false);
-const [modalCopied, setModalCopied] = useState(false);
-const [isModalOpen, setIsModalOpen] = useState(false);
+const [state, setState] = useState({
+  copied: false,
+  modalCopied: false,
+  isModalOpen: false,
+});

330-370: Consider accessibility improvements for the modal.

The modal implementation looks good, but could benefit from some accessibility improvements:

  1. Add aria-label to the copy button
  2. Add keyboard shortcuts for closing the modal (ESC key)
 <Button
   variant="tertiary/small"
   onClick={onModalCopied}
   className="absolute right-4 top-16 z-50"
   LeadingIcon={modalCopied ? undefined : Clipboard}
   leadingIconClassName="size-3 -ml-1"
+  aria-label={modalCopied ? "Code copied" : "Copy code"}
 >
   {modalCopied ? "Copied" : "Copy"}
 </Button>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3eeadc8 and e8d9b99.

📒 Files selected for processing (1)
  • apps/webapp/app/components/code/CodeBlock.tsx (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
apps/webapp/app/components/code/CodeBlock.tsx (3)

1-1: LGTM! Clean import organization.

The new imports are logically grouped and follow the component's dependencies.

Also applies to: 7-8


290-302: LGTM! Clean implementation of the expand button.

The expand button implementation follows the same pattern as the copy button and uses appropriate tooltips for better UX.


404-517: LGTM! Clean extraction of highlighting logic.

The highlighting logic has been cleanly extracted into a separate component with proper prop types. This improves code organization and reusability.

@ericallam ericallam merged commit e1db12b into main Feb 28, 2025
11 checks passed
@ericallam ericallam deleted the expandable-code-blocks branch February 28, 2025 09:18
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.

3 participants