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: add button open in stackblitz #4461

Merged
merged 6 commits into from
Jan 5, 2025

Conversation

winchesHe
Copy link
Member

@winchesHe winchesHe commented Dec 30, 2024

Closes #

📝 Description

⛳️ Current behavior (updates)

🚀 New behavior

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

📝 Additional Information

Summary by CodeRabbit

Release Notes

  • New Features

    • Added Stackblitz integration for code demos.
    • Introduced new Preview and Stackblitz buttons.
    • Added Stackblitz icon to social icons.
  • Performance Improvements

    • Enhanced CopyButton component with memoization.
    • Optimized React Live Demo component.
  • UI/UX Enhancements

    • Added tooltip to Stackblitz button.
    • Improved button styling and interactions.
  • Development Tools

    • Added Stackblitz SDK support.
    • Implemented TypeScript strict mode option for code demos.

Copy link

linear bot commented Dec 30, 2024

Copy link

changeset-bot bot commented Dec 30, 2024

⚠️ No Changeset found

Latest commit: 3bfe6fc

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 Dec 30, 2024

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

Name Status Preview Comments Updated (UTC)
nextui-docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 3, 2025 2:37am
nextui-storybook-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 3, 2025 2:37am

Copy link
Contributor

coderabbitai bot commented Dec 30, 2024

Walkthrough

This pull request introduces several new components and enhancements to the documentation application. The changes include adding a StackblitzButton, PreviewButton, and StackblitzIcon, along with a new useStackblitz hook. The modifications aim to improve the interactive code demonstration capabilities by integrating Stackblitz functionality and refactoring existing components like the CopyButton. The changes involve updating import statements, creating new components, and adding new dependencies to support these features.

Changes

File Change Summary
apps/docs/components/copy-button.tsx - Removed FC type import
- Wrapped component with memo
- Added displayName
- Replaced Button with PreviewButton
apps/docs/components/docs/components/code-demo/react-live-demo.tsx - Added StackblitzButton and PreviewButton imports
- Updated ReactLiveDemoProps interface
- Added typescriptStrict prop
- Integrated StackblitzButton with PreviewButton
apps/docs/components/icons/social.tsx - Added new StackblitzIcon component
apps/docs/components/preview-button.tsx - Created new PreviewButton component
- Implemented forward ref wrapper
- Added displayName
apps/docs/components/stackblitz-button.tsx - Created new StackblitzButton component
- Implemented Stackblitz project opening functionality
- Added displayName
apps/docs/hooks/use-stackblitz.ts - Added new useStackblitz hook
- Implemented Stackblitz configuration generation
apps/docs/package.json - Added @stackblitz/sdk dependency
- Minimal manipulation of clsx dependency
apps/docs/components/sandpack/sandpack.tsx - Imported StackblitzButton and integrated into Sandpack component layout

Possibly related PRs

  • fix(docs): replace twitter logo/links with x logo/links #3815: The changes in the main PR involve modifications to the CopyButton component, which now uses a PreviewButton. This is related to the updates made in the PreviewButton component in the retrieved PRs, as both involve button components and their event handling.
  • refactor(docs): use onPress event instead #4353: The main PR updates the CopyButton to use the onPress event instead of onClick, which aligns with the changes in this retrieved PR that also focuses on replacing onClick with onPress across various components.
  • refactor: use onPress event instead (component-wise) #4354: Similar to the previous PR, this one also addresses the transition from onClick to onPress for various components, which is relevant to the changes made in the main PR regarding the CopyButton.
  • fix: icon wrapper border on alert component #4383: The main PR's changes to the CopyButton component may relate to the alert component's styling and event handling, as both involve UI components that may share similar event handling practices in the NextUI framework.

Suggested labels

📋 Scope : Docs

Suggested reviewers

  • jrgarciadev
  • wingkwong

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.

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 (8)
apps/docs/components/copy-button.tsx (3)

13-15: Consider adding JSDoc comments for better documentation.

The component implementation is solid with proper memoization and hook usage.

Consider adding JSDoc comments to document the props:

+/**
+ * A button component that copies text to clipboard
+ * @param value - The text to copy
+ * @param className - Additional CSS classes
+ */
export const CopyButton = memo<CopyButtonProps>(({value, className, ...buttonProps}) => {

16-28: Consider extracting common icon styles to reduce duplication.

The icon rendering logic is correct, but there's duplicate className and styling logic.

Consider extracting the common styles:

+const iconClassName = "opacity-0 scale-50 data-[visible=true]:opacity-100 data-[visible=true]:scale-100 transition-transform-opacity";
+
 const icon = copied ? (
   <CheckLinearIcon
-    className="opacity-0 scale-50 data-[visible=true]:opacity-100 data-[visible=true]:scale-100 transition-transform-opacity"
+    className={iconClassName}
     data-visible={copied}
     size={16}
   />
 ) : (
   <CopyLinearIcon
-    className="opacity-0 scale-50 data-[visible=true]:opacity-100 data-[visible=true]:scale-100 transition-transform-opacity"
+    className={iconClassName}
     data-visible={!copied}
     size={16}
   />
 );

30-34: Consider memoizing the copy handler.

While the current implementation works, the handler could be optimized.

Consider using useCallback to prevent unnecessary re-renders:

+import {memo, useCallback} from "react";
 
-const handleCopy = () => {
+const handleCopy = useCallback(() => {
   copy(value);
-};
+}, [copy, value]);
apps/docs/components/preview-button.tsx (1)

5-7: Ensure optional property usage for the icon prop.

Currently, icon is strongly typed as a required field in the PreviewButtonProps interface. If there's a scenario where the button might not display an icon, you could consider making it optional by adding a question mark (e.g. icon?: React.ReactNode) to improve flexibility.

apps/docs/components/stackblitz-button.tsx (1)

10-14: Allow advanced customization via optional props.

All props here are straightforward and sensible. For advanced usage, consider adding a callback for handling successful or failed project opening events (e.g., onOpened, onError) to facilitate better user feedback and error handling.

apps/docs/hooks/use-stackblitz.ts (2)

7-10: Consider extending usage for global config.

typescriptStrict is helpful, and you could consider adding an option for custom ESLint or Prettier configs in the future to further standardize code formatting inside stackblitz projects.


21-31: Potential performance consideration.

useSandpack is called every render, which might be expensive if files or typescriptStrict are large or changing frequently. Memoizing or preventing repeated transformations could improve performance.

apps/docs/components/docs/components/code-demo/react-live-demo.tsx (1)

60-67: Tooltip usage is appropriate, but consider accessibility.

While the tooltip visually communicates the purpose of the button, also ensure accessibility is addressed (e.g., aria-label, keyboard focus).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f0ef58 and f8f21a5.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • apps/docs/components/copy-button.tsx (1 hunks)
  • apps/docs/components/docs/components/code-demo/react-live-demo.tsx (3 hunks)
  • apps/docs/components/icons/social.tsx (2 hunks)
  • apps/docs/components/preview-button.tsx (1 hunks)
  • apps/docs/components/stackblitz-button.tsx (1 hunks)
  • apps/docs/hooks/use-stackblitz.ts (1 hunks)
  • apps/docs/package.json (1 hunks)
🔇 Additional comments (16)
apps/docs/components/copy-button.tsx (2)

1-12: LGTM! Well-organized imports and clean type definitions.

The imports are properly structured and the component follows React best practices with proper TypeScript type definitions.


36-37: LGTM! Proper display name setup.

Setting the display name helps with debugging and follows React best practices.

apps/docs/components/preview-button.tsx (1)

9-29: Component styling and structure look well-designed.

The usage of forwardRef for PreviewButton is correct, enabling the parent to control the button’s DOM ref if necessary. The styling also properly leverages Tailwind classes and clsx.

apps/docs/components/stackblitz-button.tsx (3)

16-18: Appropriate usage of forwardRef.

Forwarding the ref to the underlying button is a good practice, enabling external focus control if needed. Good choice to destructure ...'rest' for future extensibility.


19-23: Validate stackblitzPrefillConfig correctness.

Ensure that the returned prefill config from useStackblitz is valid for every case. For instance, if a user passes incomplete or malformed file objects or invalid TS strict settings, confirm that the code handles such edge cases gracefully.


24-41: Well-designed button integration.

Using PreviewButton internally is consistent and keeps style usage DRY. The icon and stackblitzSdk.openProject call are neatly contained within the button, maintaining the single-responsibility principle.

apps/docs/hooks/use-stackblitz.ts (3)

34-35: Ensure dev and prod dependencies remain consistent.

Merging both dependencies and devDependencies into a single object can sometimes lead to version conflicts or usage confusion. Consider ensuring you maintain consistent versions or tooling disclaimers.


59-71: Excellent generation of stackblitz prefill data.

Combining viteConfig and package.json in a single open config object is well-structured. The approach should help keep the typical stackblitz usage straightforward.


72-79: Fallback logic for entryFile is robust.

Good approach to locating a fallback App file. This ensures the editor opens at the main entry if a user-specified entryFile is absent.

apps/docs/components/docs/components/code-demo/react-live-demo.tsx (4)

9-9: Inline import for Tooltip is consistent.

Importing from @nextui-org/react here lines up with the existing pattern for NextUI components, maintaining a coherent structure.


14-14: StackblitzButton usage complements the rest of the code demo.

The new import for StackblitzButton seamlessly fits into the code demo’s functionality, enhancing the user’s ability to explore interactive examples.


26-26: Optional typescriptStrict property.

This addition provides flexibility for consumers who may want to ensure stricter type checks in their demos.


55-55: Defaults for typescriptStrict are sensible.

Using false as the default ensures minimal disruption for existing code examples while giving advanced users the option to enable strict typing.

apps/docs/package.json (1)

55-55: LGTM! Dependencies updated correctly.

The addition of @stackblitz/sdk aligns with the PR objective of adding StackBlitz integration. The dependency version is specified with a caret which allows for compatible updates.

Also applies to: 58-58

apps/docs/components/icons/social.tsx (2)

426-441: LGTM! StackblitzIcon implementation follows established patterns.

The implementation:

  • Follows the same structure as other icon components
  • Uses consistent props interface
  • Has proper SVG markup with currentColor fill

490-490: LGTM! Export added correctly.

The StackblitzIcon is properly added to the named exports list, maintaining alphabetical order.

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 (3)
apps/docs/hooks/use-stackblitz.ts (3)

1-10: Add JSDoc documentation to improve code clarity.

The interface and its properties would benefit from JSDoc documentation to explain their purpose, especially the typescriptStrict flag's impact on the Stackblitz configuration.

Add documentation like this:

+/**
+ * Props for configuring the Stackblitz integration with Sandpack
+ */
 export interface UseSandpackProps {
+  /** The Sandpack files to be transformed for Stackblitz */
   files: SandpackFiles;
+  /** Whether to enable strict TypeScript checking in the Stackblitz environment */
   typescriptStrict?: boolean;
 }

59-70: Consider improving project configuration robustness.

A few suggestions for the Stackblitz configuration:

  1. The "node" template might not be optimal for React projects. Consider using "vite" or "react-typescript".
  2. The search for entry file using "App" might be too generic and could match unintended files.
 const stackblitzPrefillConfig: Project = {
   files: {
     ...Object.fromEntries(
       Object.entries(transformFiles).map(([key, value]) => [key, value.code ?? value]),
     ),
     "vite.config.js": viteConfig,
     "package.json": packageJson,
   },
   dependencies,
   title: "NextUI",
-  template: "node",
+  template: "vite",
 };

72-75: Enhance entry file detection logic.

The current entry file detection using includes("App") could be made more robust by using a more specific pattern that matches common React entry file patterns.

-  const findEntryFile = Object.keys(stackblitzPrefillConfig.files).find((key) =>
-    key.includes("App"),
-  );
+  const findEntryFile = Object.keys(stackblitzPrefillConfig.files).find((key) =>
+    /^(App\.(tsx|jsx|ts|js)|index\.(tsx|jsx|ts|js))$/.test(key)
+  );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f8f21a5 and 6619356.

📒 Files selected for processing (1)
  • apps/docs/hooks/use-stackblitz.ts (1 hunks)
🔇 Additional comments (2)
apps/docs/hooks/use-stackblitz.ts (2)

21-35: LGTM! Clean and efficient implementation.

The hook's core logic is well-implemented:

  • Proper destructuring of props with default value for typescriptStrict
  • Clean transformation of file paths
  • Efficient merging of dependencies

43-54: Verify package version compatibility.

Let's verify the existence and compatibility of the specified package versions.

✅ Verification successful

All package versions exist and are compatible

The verification shows that all specified package versions are available on npm registry:

  • React and React DOM 18.3.1
  • Vite 6.0.6 with @vitejs/plugin-react 4.3.4
  • Autoprefixer 10.4.20
  • PostCSS 8.4.49
  • TailwindCSS 3.4.17

Since we're in December 2024 and all packages return valid versions from npm, these are legitimate versions that have been released by this date.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the specified package versions exist on npm
# and if they are compatible with each other

echo "Checking package versions on npm..."
for pkg in "[email protected]" "[email protected]" "@vitejs/[email protected]" "[email protected]" "[email protected]" "[email protected]" "[email protected]"; do
  echo "Checking $pkg..."
  npm view $pkg version
done

Length of output: 1911

Copy link
Member

@wingkwong wingkwong left a comment

Choose a reason for hiding this comment

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

seems not implemented for this comment

image

image

@jrgarciadev
Copy link
Member

@winchesHe please add the stackblitz button in the code tab as well

@winchesHe
Copy link
Member Author

Updated

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 (7)
apps/docs/components/sandpack/sandpack.tsx (1)

77-88: Conditional rendering of StackblitzButton is consistent.
This approach seamlessly integrates the Stackblitz launcher. One minor suggestion is to name your boolean prop more descriptively (e.g., showOpenInStackblitz) for clarity if you expand support for additional code hosting services in the future.

apps/docs/components/stackblitz-button.tsx (3)

5-6: Icon import is straightforward.
No problems. If performance or bundle size becomes a concern, consider lazy-loading or code-splitting icons.


11-17: Interface definition is well-structured
The prop definitions make sense. To improve clarity, you could rename button to something like customButton to avoid confusion with the Button component interface.


19-58: Well-structured StackblitzButton component

  • Good use of forwardRef to pass down refs.
  • The onPress callback correctly calls stackblitzSdk.openProject with the prefill config.
  • The children vs. icon usage is a bit confusing since both are used. You may want to clarify the “icon only” scenario or unify them into a single approach for button labeling.
apps/docs/hooks/use-stackblitz.ts (2)

7-10: Props interface is straightforward
The typescriptStrict prop should be well-documented, highlighting its effect on the generated config.


12-19: Vite config string
This inline definition makes sense. Another approach could be storing it as a template file in your repo if you need more advanced modifications later.

apps/docs/components/docs/components/code-demo/react-live-demo.tsx (1)

55-66: Usage of StackblitzButton with files and TypeScript strict mode

  • The inline usage is consistent with the rest of the design.
  • UI positioning is clear.
  • Consider adding a short doc comment or user-facing tooltip if typescriptStrict mode imposes specific limitations in the generated previews.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6619356 and 3bfe6fc.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • apps/docs/components/docs/components/code-demo/react-live-demo.tsx (3 hunks)
  • apps/docs/components/sandpack/sandpack.tsx (2 hunks)
  • apps/docs/components/stackblitz-button.tsx (1 hunks)
  • apps/docs/hooks/use-stackblitz.ts (1 hunks)
  • apps/docs/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/docs/package.json
🔇 Additional comments (8)
apps/docs/components/sandpack/sandpack.tsx (1)

6-7: Import statement looks good.
No issues with the newly introduced import for StackblitzButton.

apps/docs/components/stackblitz-button.tsx (2)

1-2: Imports from React and StackBlitz SDK
All good here. Consider pinning your StackBlitz SDK version in package.json to prevent unplanned version upgrades.


7-9: Importing custom hook and UI components
The usage seems correct. Ensure that the useStackblitz hook is stable and tested for various file configurations.

apps/docs/hooks/use-stackblitz.ts (3)

4-5: Utility imports
Reusing utilities from your own shared-utils package is a good approach for consistency across the codebase.


21-28: transformSandpackFiles helper function
Implementation is concise. Watch out for large files that could trigger performance concerns, but for typical usage, this should be fine.


30-88: useStackblitz hook

  • Integrates well with the existing useSandpack logic.
  • Merging dependencies from customSetup is a convenient approach.
  • The approach to find the App file is robust, but watch for edge cases if your naming convention changes.

Overall, this is a solid addition. Consider unit tests to ensure new usage patterns don’t cause unexpected failures.

apps/docs/components/docs/components/code-demo/react-live-demo.tsx (2)

13-14: New imports for StackblitzButton and PreviewButton
These seem properly placed among other imports.


26-26: Added typescriptStrict prop
Clear addition. Ensure you pass it along consistently wherever code transformations rely on strict TypeScript.

@jrgarciadev jrgarciadev merged commit da7003e into canary Jan 5, 2025
8 checks passed
@jrgarciadev jrgarciadev deleted the feat/eng-1789-open-in-stackblitz branch January 5, 2025 12:34
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.

3 participants