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

feat: open in chat button in doc examples #4996

Open
wants to merge 3 commits into
base: canary
Choose a base branch
from

Conversation

Peterl561
Copy link
Member

@Peterl561 Peterl561 commented Mar 6, 2025

Closes #

open in heroui chat button for component code demos
parses dependencies from demo code to pass to api
the error handling toast needs a check for the toast docs page as it already has a provider

📝 Description

⛳️ Current behavior (updates)

🚀 New behavior

💣 Is this a breaking change (Yes/No):

📝 Additional Information

Summary by CodeRabbit

  • New Features
    • Introduced integrated chat functionality across documentation and interactive code demos.
    • Added an “Open in Chat” button that launches a dedicated chat interface with real-time loading indicators and toast notifications.
    • Enhanced the process for gathering necessary code context, ensuring a smoother chat experience.

Copy link

changeset-bot bot commented Mar 6, 2025

⚠️ No Changeset found

Latest commit: e963480

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

vercel bot commented Mar 6, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
heroui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 7, 2025 5:04pm
heroui-sb ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 7, 2025 5:04pm

Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

Walkthrough

This pull request integrates a new chat feature into the docs app. New environment variables are added to configure the chat API. An asynchronous function (openInChat) is implemented to retrieve file content, ensure proper React import, parse dependencies, and make a POST request to the chat API. The chat integration is further supported by updates in the CodeDemo component to handle button actions, loading states, and error tracking. Additionally, the documentation page now conditionally renders the ToastProvider based on the document title.

Changes

File(s) Change Summary
apps/docs/.env.example Added new environment variables: IMPORT_API_KEY, CHAT_API_URL, and CHAT_URL under a new # Chat section.
apps/docs/actions/open-in-chat.ts
apps/docs/components/docs/components/code-demo/code-demo.tsx
apps/docs/components/docs/components/code-demo/parse-dependencies.ts
Implemented the chat integration feature: introduced the asynchronous openInChat function to process file content (with dependency parsing via parseDependencies), updated the CodeDemo component with a new handleOpenInChat method to trigger the chat process, and added dependency extraction logic.
apps/docs/app/docs/[[...slug]]/page.tsx Added conditional import and rendering of ToastProvider from @heroui/react in the DocPage component based on the document title.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CodeDemo
    participant OpenInChat as openInChat Function
    participant ChatAPI as Chat API

    User->>CodeDemo: Click "Open in Chat"
    CodeDemo->>OpenInChat: Call openInChat({title, files})
    OpenInChat->>files: Retrieve `/App.jsx` content
    OpenInChat->>OpenInChat: Validate content and prepend React import if missing
    OpenInChat->>OpenInChat: Parse dependencies via parseDependencies
    OpenInChat->>ChatAPI: POST request (title, content, dependencies)
    ChatAPI-->>OpenInChat: Return chat URL or error
    OpenInChat-->>CodeDemo: Return result (chat URL or error message)
    CodeDemo->>User: Open new window with chat URL (or display error)
Loading

Suggested labels

📋 Scope : Docs

Suggested reviewers

  • wingkwong
  • jrgarciadev
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
  • @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.

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

pkg-pr-new bot commented Mar 6, 2025

Open in Stackblitz

@heroui/accordion

npm i https://pkg.pr.new/@heroui/accordion@4996

@heroui/alert

npm i https://pkg.pr.new/@heroui/alert@4996

@heroui/autocomplete

npm i https://pkg.pr.new/@heroui/autocomplete@4996

@heroui/avatar

npm i https://pkg.pr.new/@heroui/avatar@4996

@heroui/badge

npm i https://pkg.pr.new/@heroui/badge@4996

@heroui/breadcrumbs

npm i https://pkg.pr.new/@heroui/breadcrumbs@4996

@heroui/button

npm i https://pkg.pr.new/@heroui/button@4996

@heroui/calendar

npm i https://pkg.pr.new/@heroui/calendar@4996

@heroui/card

npm i https://pkg.pr.new/@heroui/card@4996

@heroui/checkbox

npm i https://pkg.pr.new/@heroui/checkbox@4996

@heroui/chip

npm i https://pkg.pr.new/@heroui/chip@4996

@heroui/code

npm i https://pkg.pr.new/@heroui/code@4996

@heroui/date-input

npm i https://pkg.pr.new/@heroui/date-input@4996

@heroui/date-picker

npm i https://pkg.pr.new/@heroui/date-picker@4996

@heroui/divider

npm i https://pkg.pr.new/@heroui/divider@4996

@heroui/drawer

npm i https://pkg.pr.new/@heroui/drawer@4996

@heroui/dropdown

npm i https://pkg.pr.new/@heroui/dropdown@4996

@heroui/form

npm i https://pkg.pr.new/@heroui/form@4996

@heroui/image

npm i https://pkg.pr.new/@heroui/image@4996

@heroui/input

npm i https://pkg.pr.new/@heroui/input@4996

@heroui/input-otp

npm i https://pkg.pr.new/@heroui/input-otp@4996

@heroui/kbd

npm i https://pkg.pr.new/@heroui/kbd@4996

@heroui/link

npm i https://pkg.pr.new/@heroui/link@4996

@heroui/listbox

npm i https://pkg.pr.new/@heroui/listbox@4996

@heroui/menu

npm i https://pkg.pr.new/@heroui/menu@4996

@heroui/modal

npm i https://pkg.pr.new/@heroui/modal@4996

@heroui/navbar

npm i https://pkg.pr.new/@heroui/navbar@4996

@heroui/number-input

npm i https://pkg.pr.new/@heroui/number-input@4996

@heroui/pagination

npm i https://pkg.pr.new/@heroui/pagination@4996

@heroui/popover

npm i https://pkg.pr.new/@heroui/popover@4996

@heroui/progress

npm i https://pkg.pr.new/@heroui/progress@4996

@heroui/radio

npm i https://pkg.pr.new/@heroui/radio@4996

@heroui/ripple

npm i https://pkg.pr.new/@heroui/ripple@4996

@heroui/scroll-shadow

npm i https://pkg.pr.new/@heroui/scroll-shadow@4996

@heroui/select

npm i https://pkg.pr.new/@heroui/select@4996

@heroui/skeleton

npm i https://pkg.pr.new/@heroui/skeleton@4996

@heroui/slider

npm i https://pkg.pr.new/@heroui/slider@4996

@heroui/snippet

npm i https://pkg.pr.new/@heroui/snippet@4996

@heroui/spacer

npm i https://pkg.pr.new/@heroui/spacer@4996

@heroui/spinner

npm i https://pkg.pr.new/@heroui/spinner@4996

@heroui/switch

npm i https://pkg.pr.new/@heroui/switch@4996

@heroui/table

npm i https://pkg.pr.new/@heroui/table@4996

@heroui/tabs

npm i https://pkg.pr.new/@heroui/tabs@4996

@heroui/toast

npm i https://pkg.pr.new/@heroui/toast@4996

@heroui/tooltip

npm i https://pkg.pr.new/@heroui/tooltip@4996

@heroui/user

npm i https://pkg.pr.new/@heroui/user@4996

@heroui/react

npm i https://pkg.pr.new/@heroui/react@4996

@heroui/system

npm i https://pkg.pr.new/@heroui/system@4996

@heroui/system-rsc

npm i https://pkg.pr.new/@heroui/system-rsc@4996

@heroui/theme

npm i https://pkg.pr.new/@heroui/theme@4996

@heroui/use-aria-accordion

npm i https://pkg.pr.new/@heroui/use-aria-accordion@4996

@heroui/use-aria-accordion-item

npm i https://pkg.pr.new/@heroui/use-aria-accordion-item@4996

@heroui/use-aria-button

npm i https://pkg.pr.new/@heroui/use-aria-button@4996

@heroui/use-aria-link

npm i https://pkg.pr.new/@heroui/use-aria-link@4996

@heroui/use-aria-modal-overlay

npm i https://pkg.pr.new/@heroui/use-aria-modal-overlay@4996

@heroui/use-aria-multiselect

npm i https://pkg.pr.new/@heroui/use-aria-multiselect@4996

@heroui/use-callback-ref

npm i https://pkg.pr.new/@heroui/use-callback-ref@4996

@heroui/use-clipboard

npm i https://pkg.pr.new/@heroui/use-clipboard@4996

@heroui/use-data-scroll-overflow

npm i https://pkg.pr.new/@heroui/use-data-scroll-overflow@4996

@heroui/use-disclosure

npm i https://pkg.pr.new/@heroui/use-disclosure@4996

@heroui/use-draggable

npm i https://pkg.pr.new/@heroui/use-draggable@4996

@heroui/use-image

npm i https://pkg.pr.new/@heroui/use-image@4996

@heroui/use-infinite-scroll

npm i https://pkg.pr.new/@heroui/use-infinite-scroll@4996

@heroui/use-intersection-observer

npm i https://pkg.pr.new/@heroui/use-intersection-observer@4996

@heroui/use-is-mobile

npm i https://pkg.pr.new/@heroui/use-is-mobile@4996

@heroui/use-is-mounted

npm i https://pkg.pr.new/@heroui/use-is-mounted@4996

@heroui/use-measure

npm i https://pkg.pr.new/@heroui/use-measure@4996

@heroui/use-pagination

npm i https://pkg.pr.new/@heroui/use-pagination@4996

@heroui/use-real-shape

npm i https://pkg.pr.new/@heroui/use-real-shape@4996

@heroui/use-ref-state

npm i https://pkg.pr.new/@heroui/use-ref-state@4996

@heroui/use-resize

npm i https://pkg.pr.new/@heroui/use-resize@4996

@heroui/use-safe-layout-effect

npm i https://pkg.pr.new/@heroui/use-safe-layout-effect@4996

@heroui/use-scroll-position

npm i https://pkg.pr.new/@heroui/use-scroll-position@4996

@heroui/use-ssr

npm i https://pkg.pr.new/@heroui/use-ssr@4996

@heroui/use-theme

npm i https://pkg.pr.new/@heroui/use-theme@4996

@heroui/use-update-effect

npm i https://pkg.pr.new/@heroui/use-update-effect@4996

@heroui/aria-utils

npm i https://pkg.pr.new/@heroui/aria-utils@4996

@heroui/dom-animation

npm i https://pkg.pr.new/@heroui/dom-animation@4996

@heroui/framer-utils

npm i https://pkg.pr.new/@heroui/framer-utils@4996

@heroui/react-rsc-utils

npm i https://pkg.pr.new/@heroui/react-rsc-utils@4996

@heroui/react-utils

npm i https://pkg.pr.new/@heroui/react-utils@4996

@heroui/shared-icons

npm i https://pkg.pr.new/@heroui/shared-icons@4996

@heroui/shared-utils

npm i https://pkg.pr.new/@heroui/shared-utils@4996

@heroui/stories-utils

npm i https://pkg.pr.new/@heroui/stories-utils@4996

@heroui/test-utils

npm i https://pkg.pr.new/@heroui/test-utils@4996

commit: e963480

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 (5)
apps/docs/components/docs/components/code-demo/parse-dependencies.ts (2)

1-2: Consider adding more robust package detection

The regex pattern looks good for basic import/from statements but might miss complex imports or dynamic imports.

Consider enhancing the regex to handle more edge cases or adding a comment about its limitations. For complex projects, a more robust parsing approach might be needed in the future.


30-33: Consider making fixedVersions more maintainable

The hardcoded version mapping works but could become difficult to maintain as dependencies grow.

Consider moving this to a separate configuration file that can be more easily maintained, possibly with comments explaining why specific versions are required.

apps/docs/actions/open-in-chat.ts (1)

9-19: Add type declaration for return value

The function's return type should be explicitly defined for better type safety and documentation.

- export const openInChat = async ({title, files}: {title?: string; files: SandpackFiles}) => {
+ export const openInChat = async ({title, files}: {title?: string; files: SandpackFiles}): Promise<{error: string | null; data: string | null}> => {
apps/docs/components/docs/components/code-demo/code-demo.tsx (2)

178-178: Consider a more robust path check.

Using pathname.includes("/components/") works but could potentially catch false positives if there are other paths containing this string.

-  const isComponentsPage = pathname.includes("/components/");
+  const isComponentsPage = /^\/components\/[^\/]+/.test(pathname);

180-212: Well-implemented chat integration with analytics tracking.

The implementation handles the complete flow well: capturing analytics events, managing loading state, handling errors, and opening the chat in a new window.

A few suggestions for improvement:

  1. The component name extraction logic could be more robust for handling kebab-case paths:
-  const component = pathname.split("/components/")[1];
+  // Handle paths with trailing slash and extract just the component segment
+  const componentSegment = pathname.split("/components/")[1]?.split("/")[0] || "";
+  const component = componentSegment;

-  const capitalizedPath = component.charAt(0).toUpperCase() + component.slice(1);
+  // Convert kebab-case to Title Case (e.g., "button-group" → "Button Group")
+  const capitalizedPath = component
+    .split("-")
+    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
+    .join(" ");
  1. Consider adding more specific error messages when possible instead of just displaying the generic error:
   addToast({
     title: "Error",
-    description: error ?? "Unknown error",
+    description: error ? `Failed to open chat: ${error}` : "Failed to open chat due to an unknown error",
     color: "danger",
   });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9a95a71 and e963480.

📒 Files selected for processing (5)
  • apps/docs/.env.example (1 hunks)
  • apps/docs/actions/open-in-chat.ts (1 hunks)
  • apps/docs/app/docs/[[...slug]]/page.tsx (2 hunks)
  • apps/docs/components/docs/components/code-demo/code-demo.tsx (3 hunks)
  • apps/docs/components/docs/components/code-demo/parse-dependencies.ts (1 hunks)
🔇 Additional comments (9)
apps/docs/app/docs/[[...slug]]/page.tsx (2)

5-5: Import addition looks good

The ToastProvider import from @heroui/react has been correctly added to support the new chat feature's error notifications.


107-108: Conditional ToastProvider rendering implemented correctly

Good implementation to avoid duplicate ToastProvider on the Toast documentation page. The conditional check and comment provide clear context for why this approach was taken.

apps/docs/.env.example (1)

24-29: Environment variables added correctly for chat feature

The new environment variables for the chat feature have been properly documented in the .env.example file with a clear section header. This will help other developers understand what environment variables they need to set up.

apps/docs/components/docs/components/code-demo/parse-dependencies.ts (1)

3-28: Dependencies parsing logic looks solid

The function correctly filters out internal (@heroui) and relative imports while constructing a dependencies array with appropriate versions.

One minor suggestion: Consider adding type annotations for better clarity and documentation:

- export const parseDependencies = (content: string) => {
+ export const parseDependencies = (content: string): {name: string; version: string}[] => {
apps/docs/actions/open-in-chat.ts (2)

21-28: React import check logic is correct

Good approach to ensure React is imported when React.* syntax is used in the code.


47-54: Validate environment variables

The code assumes process.env.CHAT_URL will be defined, but doesn't check for it.

Add a check to ensure environment variables are defined:

+    if (!process.env.CHAT_URL) {
+      return {
+        error: "CHAT_URL environment variable is not defined",
+        data: null,
+      };
+    }
+
     return {error: null, data: `${process.env.CHAT_URL}${result.path}`};
apps/docs/components/docs/components/code-demo/code-demo.tsx (3)

3-8: Well-structured imports, good organization.

The new imports are organized logically, bringing in all the necessary functionality for the chat feature while maintaining clean code structure.


83-85: Good setup of state and hooks.

Proper use of PostHog for analytics tracking and useState for managing the loading state of the chat button.


233-253: Good UI implementation of the chat button.

The button is nicely integrated with loading state indicators. The conditional rendering based on the page type is appropriate.

One consideration:

The absolute positioning (absolute right-0 top-1) might overlap with other elements depending on the layout. Verify that this positioning works well across different viewport sizes and doesn't interfere with other UI elements in the header area.

Comment on lines +55 to +57
} catch (error) {
return {error: error, data: null};
}
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

Improve error handling in catch block

The error message may not be a string, which could cause issues when returned.

-    return {error: error, data: null};
+    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
+    console.error("Error in openInChat:", error);
+    return {error: errorMessage, data: null};
📝 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
} catch (error) {
return {error: error, data: null};
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
console.error("Error in openInChat:", error);
return {error: errorMessage, data: null};
}

Comment on lines +32 to +43
const response = await fetch(`${process.env.CHAT_API_URL}/import`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.IMPORT_API_KEY}`,
},
body: JSON.stringify({
title,
content,
dependencies,
}),
});
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 error handling for API request

The fetch request lacks timeout and network error handling.

-    const response = await fetch(`${process.env.CHAT_API_URL}/import`, {
+    const controller = new AbortController();
+    const timeoutId = setTimeout(() => controller.abort(), 10000); // 10-second timeout
+
+    const response = await fetch(`${process.env.CHAT_API_URL}/import`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${process.env.IMPORT_API_KEY}`,
      },
+     signal: controller.signal,
      body: JSON.stringify({
        title,
        content,
        dependencies,
      }),
    });
+
+    clearTimeout(timeoutId);
📝 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 response = await fetch(`${process.env.CHAT_API_URL}/import`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.IMPORT_API_KEY}`,
},
body: JSON.stringify({
title,
content,
dependencies,
}),
});
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10-second timeout
const response = await fetch(`${process.env.CHAT_API_URL}/import`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.IMPORT_API_KEY}`,
},
signal: controller.signal,
body: JSON.stringify({
title,
content,
dependencies,
}),
});
clearTimeout(timeoutId);

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.

1 participant