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

docs: custom docs rendering instead of autodocs for API #756

Merged
merged 3 commits into from
Dec 17, 2024

Conversation

aversini
Copy link
Collaborator

@aversini aversini commented Dec 17, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new documentation pages for the Button and ButtonIcon components in Storybook.
    • Enhanced control configuration in Storybook for better customization and usability.
    • Added a new AutoDoc component for generating structured documentation for UI components.
  • Bug Fixes

    • Updated import paths for several helper modules across multiple documentation files to ensure correct resolution.
  • Refactor

    • Improved structure and organization of story definitions for the Button and ButtonIcon components.
    • Simplified Storybook configuration by removing unnecessary properties.
  • Chores

    • Updated the package configuration to support ECMAScript modules.

@aversini aversini added the Enhancement New feature or request label Dec 17, 2024
Copy link

coderabbitai bot commented Dec 17, 2024

Walkthrough

This pull request involves multiple changes across the packages/api directory, focusing on Storybook configuration, documentation, and module structure. The modifications include updating Storybook configuration files, adjusting import paths in MDX documentation files, introducing new documentation components, refactoring story definitions, and adding a new AutoDoc helper component. The changes aim to improve the documentation and story organization for UI components.

Changes

File Change Summary
.storybook/main.js Removed docs property from Storybook configuration
.storybook/preview.jsx Added controls parameter with expanded and matchers settings
package.json Added "type": "module" to enable ECMAScript modules
src/getting-started/*.mdx Updated import paths for helper modules from ./helpers/ to ../helpers/
src/helpers/Highlight.tsx Made language parameter optional in component signature
src/helpers/AutoDoc.tsx New component for generating documentation with configurable props
src/stories/Button.mdx New Storybook documentation page for Button component
src/stories/Button.stories.tsx Refactored story definitions using StoryObj and object format
src/stories/ButtonIcon.mdx New Storybook documentation page for ButtonIcon component
src/stories/ButtonIcon.stories.tsx Updated story definition with StoryObj and object format

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6950c5d and 580fdff.

📒 Files selected for processing (1)
  • packages/api/src/getting-started/ReleaseTags.mdx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/getting-started/ReleaseTags.mdx

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

@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: 3

🔭 Outside diff range comments (1)
packages/api/src/helpers/Highlight.tsx (1)

Line range hint 4-5: Review global Prism modification and top-level await

There are potential issues to address:

  1. Modifying the global object could cause conflicts
  2. Top-level await might not be supported in all environments

Consider refactoring to:

-await import("prismjs/components/prism-bash" as string);
+(typeof global !== "undefined" ? global : window).Prism = Prism;
+
+// Move to an async initialization function
+async function initializePrism() {
+  await import("prismjs/components/prism-bash");
+}
+
+// Call during component initialization
+useEffect(() => {
+  initializePrism();
+}, []);
🧹 Nitpick comments (9)
packages/api/src/getting-started/Overview.mdx (1)

Line range hint 19-24: Consider enhancing image accessibility.

While the image includes an alt text, it could be more descriptive to better convey the visual content to screen reader users.

       <img
         className="my-0 ml-auto mr-auto h-52 w-52 object-cover sm:h-52 sm:w-52 md:h-full md:w-60"
         src={Hero}
-        alt="An illustration of web page rendered on both desktop and mobile devices"
+        alt="An illustration showing responsive web page layouts across desktop and mobile devices, demonstrating the UI library's adaptability"
       />
packages/api/src/stories/ButtonIcon.stories.tsx (2)

12-14: Document the reason for excluding the spacing control

While excluding the spacing control is valid, it would be helpful to add a comment explaining why this control is being excluded from the docs.

 parameters: {
   layout: "centered",
   docs: {
+    // Spacing control is excluded because...
     controls: { exclude: ["spacing"] },
   },
 },

23-29: Consider adding a description field to the story

The implementation looks good, but adding a description field would improve the documentation quality.

 export const Basic: Story = {
+  description: 'A basic example of ButtonIcon with Settings icon',
   render: (args) => (
     <ButtonIcon {...args}>
       <IconSettings />
     </ButtonIcon>
   ),
 };
packages/api/src/stories/Button.stories.tsx (2)

23-31: Consider adding aria-label for better accessibility

While the implementation is good, consider adding descriptive aria-labels to differentiate between the buttons in screen readers.

 export const Basic: Story = {
   render: (args) => (
     <div className="flex flex-wrap gap-2">
-      <Button {...args}>Button lorem ipsum</Button>
-      <Button {...args}>Button lorem ipsum dolor</Button>
-      <Button {...args}>Button lorem ipsum dolor sit amet</Button>
+      <Button {...args} aria-label="Short button">Button lorem ipsum</Button>
+      <Button {...args} aria-label="Medium button">Button lorem ipsum dolor</Button>
+      <Button {...args} aria-label="Long button">Button lorem ipsum dolor sit amet</Button>
     </div>
   ),
 };

33-52: Enhance code example accessibility and styling

The implementation is good, but the code example could benefit from better semantic markup and styling.

       <div className="pt-4">
         <p>
           For text to truncate, you need to limit the width of the buttons.
         </p>
         <p>This can be done by using Tailwind width classes, for example</p>
-        <code>{args.className}</code>
+        <pre className="mt-2 rounded bg-gray-100 p-2">
+          <code>{args.className}</code>
+        </pre>
       </div>
packages/api/src/helpers/Usage.tsx (2)

5-7: Add JSDoc documentation for the UsageProps interface

Consider adding documentation to describe the purpose and expected format of the codeBlock prop.

+/**
+ * Props for the Usage component
+ * @interface UsageProps
+ * @property {string} codeBlock - The code snippet to be displayed
+ */
interface UsageProps {
	codeBlock: string;
}

9-17: Consider adding explicit return type and component documentation

The implementation looks good, but could benefit from additional type safety and documentation.

+/**
+ * Renders a code block with consistent styling using Storybook's Unstyled wrapper
+ * @param {UsageProps} props - The component props
+ * @returns {JSX.Element} A styled code block
+ */
-export default ({ codeBlock }: UsageProps) => {
+export default ({ codeBlock }: UsageProps): JSX.Element => {
packages/api/src/helpers/Title.tsx (2)

5-8: Add prop validation for required props.

The props interface is well-defined, but since both props are required, consider adding runtime validation.

+import { type ReactElement } from "react";

 interface TitleProps {
 	label: string;
 	level: "beta" | "stable" | "alpha";
 }

+const validateProps = ({ label, level }: TitleProps) => {
+  if (!label) {
+    throw new Error("Title: label prop is required");
+  }
+  if (!level) {
+    throw new Error("Title: level prop is required");
+  }
+};

10-40: Consider memoizing the component for performance.

The component implementation is clean, but since it's likely to be used across multiple documentation pages, it could benefit from memoization.

-export default ({ label, level }: TitleProps) => {
+import { memo } from "react";
+
+const Title = ({ label, level }: TitleProps): ReactElement => {
+  validateProps({ label, level });
   // ... rest of the implementation
-};
+};
+
+export default memo(Title);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3141aae and 5c26aea.

📒 Files selected for processing (16)
  • packages/api/.storybook/main.js (0 hunks)
  • packages/api/.storybook/preview.jsx (1 hunks)
  • packages/api/package.json (1 hunks)
  • packages/api/src/getting-started/Changelogs.mdx (1 hunks)
  • packages/api/src/getting-started/Configuration.mdx (1 hunks)
  • packages/api/src/getting-started/Installation.mdx (1 hunks)
  • packages/api/src/getting-started/Overview.mdx (1 hunks)
  • packages/api/src/getting-started/ReleaseTags.mdx (1 hunks)
  • packages/api/src/getting-started/Usage.mdx (1 hunks)
  • packages/api/src/helpers/Highlight.tsx (1 hunks)
  • packages/api/src/helpers/Title.tsx (1 hunks)
  • packages/api/src/helpers/Usage.tsx (1 hunks)
  • packages/api/src/stories/Button.mdx (1 hunks)
  • packages/api/src/stories/Button.stories.tsx (1 hunks)
  • packages/api/src/stories/ButtonIcon.mdx (1 hunks)
  • packages/api/src/stories/ButtonIcon.stories.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/api/.storybook/main.js
✅ Files skipped from review due to trivial changes (4)
  • packages/api/src/stories/Button.mdx
  • packages/api/src/stories/ButtonIcon.mdx
  • packages/api/src/getting-started/Installation.mdx
  • packages/api/src/getting-started/Configuration.mdx
🔇 Additional comments (10)
packages/api/src/getting-started/Changelogs.mdx (1)

4-4: LGTM! Verify helper components restructuring

The import path change aligns with centralizing helper components at the parent directory level.

Let's verify the consistency of this restructuring:

✅ Verification successful

Import path change verified and consistent

The verification confirms:

  • The Navigators component exists at packages/api/src/helpers/Navigators.tsx
  • All MDX files in getting-started directory consistently import Navigators from the helpers directory
  • No remaining old-style imports using ./helpers/ were found
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the helpers directory structure and its usage

# Check if helpers directory exists at the new location
fd -t d "helpers" packages/api/src

# Verify no remaining helpers directory in getting-started
fd -t d "helpers" packages/api/src/getting-started

# Check for any remaining old import paths that might need updating
rg -t mdx "from ['\"]./helpers/" packages/api/src/getting-started

Length of output: 209


Script:

#!/bin/bash
# Let's verify the import paths and Navigators component usage with more generic commands

# Check if Navigators component exists in the helpers directory
rg -l "Navigators" packages/api/src/helpers/

# Check all imports of Navigators across the codebase to verify consistency
rg -l "import.*Navigators.*from.*helpers" packages/api/src/

# Check for any potential old paths still using ./helpers
rg -l "from ['\"]./helpers/" packages/api/src/

Length of output: 484

packages/api/src/getting-started/Overview.mdx (1)

8-8: LGTM! Verifying the new helper component location.

The import path change aligns with the directory restructuring effort.

Let's verify the new location of the Navigators component:

✅ Verification successful

✅ Import path change is correct and consistent

The Navigators component exists at packages/api/src/helpers/Navigators.tsx and all MDX files in the getting-started directory consistently use the "../helpers/Navigators" import path. The change aligns perfectly with the codebase structure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and consistency of the Navigators component
# in the new location

# Check if the Navigators component exists in the new location
fd -t f "Navigators\.(js|jsx|ts|tsx)" packages/api/src/helpers

# Verify consistent usage of the new path across other MDX files
rg -t mdx "import.*Navigators.*from.*helpers/Navigators" packages/api/src

Length of output: 208


Script:

#!/bin/bash
# Let's modify our search to handle MDX files and get a better view of the imports
# First, verify the Navigators component exists
ls -l packages/api/src/helpers/Navigators.tsx

# Then search for Navigators imports without file type restriction
rg "import.*Navigators.*from.*helpers/Navigators" packages/api/src

# Also search for any other potential Navigators import patterns
rg "import.*Navigators.*from" packages/api/src

Length of output: 1404

packages/api/src/stories/ButtonIcon.stories.tsx (1)

1-7: LGTM! Well-structured type definitions and imports

The changes follow Storybook's best practices for TypeScript integration. The Story type alias improves type safety and maintainability.

packages/api/src/stories/Button.stories.tsx (1)

8-20: LGTM! Good use of Storybook features

The meta configuration is well structured with:

  • Proper control exclusions for documentation
  • Mock handler for onClick using fn()
packages/api/src/helpers/Highlight.tsx (1)

Line range hint 6-10: LGTM: Optional language parameter with default value

The change to make language optional with a default value of "jsx" is a good improvement that maintains backward compatibility while adding flexibility.

packages/api/src/getting-started/Usage.mdx (2)

Line range hint 1-35: LGTM: Well-structured documentation with examples

The documentation provides a good mix of code examples and visual demonstrations, which aligns well with the PR's objective of improving API documentation.


5-7: Verify import path consistency across documentation files

The import path changes look correct, but let's ensure consistency across all documentation files.

✅ Verification successful

Let me verify the actual import statements in these files to ensure they are all using the correct ../helpers/ path consistently.


Import paths are consistent across documentation files

All documentation files in the getting-started directory are correctly using the ../helpers/ relative path for their imports. Each file follows the same pattern and there are no remaining instances of ./helpers/ paths.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining old import paths and verify consistency

# Check for any remaining old helper import paths
rg -l "from ['\"]./helpers/" "packages/api/src/getting-started/"

# Verify all new helper import paths
rg -l "from ['\"]../helpers/" "packages/api/src/getting-started/"

Length of output: 421


Script:

#!/bin/bash
# Show the actual import statements from each file
rg "from ['\"].*helpers/" packages/api/src/getting-started/ -A 1

Length of output: 1971

packages/api/src/getting-started/ReleaseTags.mdx (1)

5-7: Verify helper components directory structure

Let's verify that the helper components are correctly located in the parent directory structure.

✅ Verification successful

Helper components directory structure is correct

All imported helper components exist at the expected location:

  • packages/api/src/helpers/Navigators.tsx
  • packages/api/src/helpers/Highlight.tsx
  • packages/api/src/helpers/codeBlocks.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and location of helper components

# Check if the helpers directory exists in the parent directory
fd -t d "helpers" packages/api/src

# Verify the existence of the imported helper components
fd -t f "Navigators|Highlight|codeBlocks" packages/api/src/helpers

Length of output: 247

packages/api/.storybook/preview.jsx (1)

Line range hint 20-28: LGTM! Control configuration aligns with custom docs approach.

The addition of expanded controls and matchers enhances the documentation experience, properly supporting the transition from autodocs to custom docs.

Let's verify the control matchers are being utilized:

✅ Verification successful

Let me analyze the results. The search shows extensive usage of args in story files, which is the standard way Storybook handles control props. Let me search specifically for color and date properties to verify if the matchers are being utilized.


Based on the search results, I can now generate the final response:

Control matchers configuration is properly utilized in the codebase.

The control matchers for color and date properties are being effectively used throughout the codebase:

  • Color properties are extensively used in components with proper color tokens and theme support (e.g., background, color properties in UI components)
  • Date properties are used in Table components and system utilities (e.g., Date column in tables, date formatting)

The expanded controls and matchers configuration aligns well with the component documentation needs and follows Storybook's best practices for control customization.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for color and date properties in stories
rg -g '*.stories.*' -g '*.mdx' -A 3 'props|args' 

Length of output: 59702


Script:

#!/bin/bash
# Search for color and date properties in component props and stories
rg -g '*.tsx' -g '*.jsx' -g '*.ts' -g '*.js' '(background|color|Date)' -B 2 -A 2

Length of output: 50231

packages/api/package.json (1)

7-7: Verify ESM compatibility across documentation.

The switch to ESM ("type": "module") is good for modernization, but ensure all documentation files and imports are compatible.

✅ Verification successful

Based on the search results, I can now generate the final response since I have enough information to verify ESM compatibility:

ESM configuration is properly set up across the codebase

The codebase already follows ESM import/export patterns consistently:

  • All imports use ESM syntax (import from)
  • No CommonJS require() usage in source files
  • .js extensions are properly included in imports
  • Configuration files that need CommonJS are correctly using .cjs extension

The only CommonJS usage is in configuration files (like postcss.config.cjs) which explicitly use the .cjs extension to maintain compatibility with tools that require CommonJS.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential CommonJS usage that needs updating
rg "require\(|module\.exports" 

# Check for .js extensions in imports which are required in ESM
rg "from ['\"]\.[^'\"]+['\"]" 

Length of output: 51799

packages/api/src/stories/Button.stories.tsx Show resolved Hide resolved
packages/api/src/getting-started/ReleaseTags.mdx Outdated Show resolved Hide resolved
Copy link

@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: 1

🧹 Nitpick comments (3)
packages/api/src/helpers/AutoDoc.tsx (3)

7-13: Consider using a type alias for stage values.

For better maintainability and reusability, consider extracting the stage values into a separate type alias.

+type Stage = "alpha" | "beta" | "stable";
+
 interface AutoDocProps {
 	importName: string;
 
 	header?: string;
 	importPackage?: string;
-	stage?: "alpha" | "beta" | "stable";
+	stage?: Stage;
 }

15-15: Name the component for better debugging.

Consider naming the component for better debugging experience in React DevTools.

-export default ({ importName, importPackage, stage, header }: AutoDocProps) => {
+const AutoDoc = ({ importName, importPackage, stage, header }: AutoDocProps) => {
+
+export default AutoDoc;

46-50: Remove redundant prose class and improve code organization.

The prose className is duplicated, and the Highlight component section could be better organized.

-					<div className="prose">
-						<Highlight
-							codeBlock={`import { ${importName} } from "@versini/${packageName}";`}
-						/>
-					</div>
+					<Highlight
+						codeBlock={`import { ${importName} } from "@versini/${packageName}";`}
+					/>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5c26aea and 6950c5d.

📒 Files selected for processing (3)
  • packages/api/src/helpers/AutoDoc.tsx (1 hunks)
  • packages/api/src/stories/Button.mdx (1 hunks)
  • packages/api/src/stories/ButtonIcon.mdx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/api/src/stories/Button.mdx
  • packages/api/src/stories/ButtonIcon.mdx
🔇 Additional comments (2)
packages/api/src/helpers/AutoDoc.tsx (2)

1-5: LGTM! Imports are well-organized.

The imports are properly structured, following the convention of external dependencies first, followed by internal imports.


33-56: 🛠️ Refactor suggestion

Consider adding prop validation for better error handling.

The component should validate the stage prop to ensure it receives valid values.

Let's verify if there are any PropTypes or validation patterns used in other components:

+const isValidStage = (stage?: string): stage is Stage => {
+  return stage === undefined || ["alpha", "beta", "stable"].includes(stage);
+};

 const AutoDoc = ({ importName, importPackage, stage, header }: AutoDocProps) => {
+  if (stage && !isValidStage(stage)) {
+    console.warn(`Invalid stage value: ${stage}. Defaulting to "alpha"`);
+  }
   const packageName = importPackage || `ui-${importName.toLowerCase()}`;

packages/api/src/helpers/AutoDoc.tsx Show resolved Hide resolved
Copy link

Bundle Size (components)

Status File Size (Gzip) Limits
style.css 7.37 KB 8 KB
index.js 11 KB (-12 B -0.11%) 12 KB
vendor.js 66.34 KB 67 KB

Overall bundle size: 84.72 KB (-12 B -0.01%)
Overall status: ✅

Bundle Size (fingerprint)

Status File Size (Gzip) Limits
index.js 3.94 KB (-1 B -0.02%) 4 KB
vendor.js 44.34 KB 45 KB

Overall bundle size: 48.28 KB (-1 B 0.00%)
Overall status: ✅

Bundle Size (form components)

Status File Size (Gzip) Limits
index.js 9.55 KB (-4 B -0.04%) 20 KB
vendor.js 44.46 KB 67 KB

Overall bundle size: 54.01 KB (-4 B -0.01%)
Overall status: ✅

Bundle Size (system)

Status File Size (Gzip) Limits
style.css 2.74 KB 8 KB
index.js 1.93 KB (+1 B +0.05%) 3 KB
vendor.js 44.46 KB 46 KB

Overall bundle size: 49.13 KB (+1 B 0.00%)
Overall status: ✅

@aversini aversini merged commit b15edc7 into main Dec 17, 2024
7 checks passed
@aversini aversini deleted the docs-custom-docs-rendering-instead-of-autodocs-for-API branch December 17, 2024 22:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant