Skip to content

Conversation

@valentinpalkovic
Copy link
Contributor

@valentinpalkovic valentinpalkovic commented Dec 12, 2025

Closes #

What I did

Added self-closing fallback rendering for synthesized snippets with no children in React code snippets, and added a regression test verifying the no-children case now outputs .

Checklist for Contributors

Testing

The changes in this PR are covered in the following automated tests:

  • stories
  • unit tests
  • integration tests
  • end-to-end tests

Manual testing

This section is mandatory for all contributions. If you believe no manual test is necessary, please state so explicitly. Thanks!

Documentation

  • Add or update documentation reflecting your changes
  • If you are deprecating/removing a feature, make sure to update
    MIGRATION.MD

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli-storybook/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This PR does not have a canary release associated. You can request a canary release of this pull request by mentioning the @storybookjs/core team here.

core team members can create a canary release here or locally with gh workflow run --repo storybookjs/storybook publish.yml --field pr=<PR_NUMBER>

Summary by CodeRabbit

  • Bug Fixes

    • Code generation now emits self-closing JSX tags when a component has no children, improving generated snippets and documentation previews.
  • Tests

    • Added tests to verify components without children produce self-closing JSX output, ensuring consistent snippet formatting.
  • Chores

    • Updated generated component manifests: story lists, snippets and prop descriptions were refreshed (including a change to the reported size prop format and multi-line description formatting).

✏️ Tip: You can customize this high-level summary in your review settings.

@nx-cloud
Copy link

nx-cloud bot commented Dec 12, 2025

View your CI Pipeline Execution ↗ for commit 883720a

Command Status Duration Result
nx run-many -t compile,check,knip,test,pretty-d... ✅ Succeeded 6m 2s View ↗

☁️ Nx Cloud last updated this comment at 2025-12-15 09:38:50 UTC

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 12, 2025

📝 Walkthrough

Walkthrough

Make JSX snippet generation emit self-closing elements when there are no children, precompute JSX children into a children variable, and add/update tests and snapshots to assert self-closing output for stories without children.

Changes

Cohort / File(s) Summary
Code snippet generation logic
code/renderers/react/src/componentManifest/generateCodeSnippet.ts
Precomputes children via toJsxChildren(merged.children), introduces selfClosing when no children, sets openingElement.selfClosing = selfClosing, uses children as the JSX children, and only emits a closingElement when not selfClosing.
Unit tests — generateCodeSnippet
code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
Adds test "Synthesizes self-closing when no children" that builds a CSF4 module with a NoChildren story and asserts the generated snippet is a self-closing <Button /> via inline snapshot.
Unit tests — enrichCsf snapshots
code/renderers/react/src/enrichCsf.test.ts
Updates inline snapshots to expect self-closing <Button /> in affected Primary/Secondary story snippets; only snapshot string changes.
Component manifest snapshot / generator tests
code/renderers/react/src/componentManifest/generator.test.ts
Updates generated manifest snapshots: story arrays, story snippets, prop types and description formatting reflect the new snippet emission and adjusted manifest content (added/modified stories, formatting changes).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas to review:
    • Correctness of the selfClosing condition (ensure it treats empty arrays, whitespace, and null/undefined children consistently).
    • Interaction between toJsxChildren output and the new children variable (edge-case formatting, fragments, text nodes).
    • Snapshot updates in enrichCsf.test.ts and componentManifest/generator.test.ts to confirm the updated manifest content and formatting are intentional.

Possibly related PRs

✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 470bb37 and 883720a.

📒 Files selected for processing (1)
  • code/renderers/react/src/componentManifest/generator.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{test,spec}.{ts,tsx}: Test files should follow the naming pattern *.test.ts, *.test.tsx, *.spec.ts, or *.spec.tsx
Follow the spy mocking rules defined in .cursor/rules/spy-mocking.mdc for consistent mocking patterns with Vitest

Files:

  • code/renderers/react/src/componentManifest/generator.test.ts
**/*.test.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/spy-mocking.mdc)

**/*.test.{ts,tsx,js,jsx}: Use vi.mock() with the spy: true option for all package and file mocks in Vitest tests
Place all mocks at the top of the test file before any test cases
Use vi.mocked() to type and access the mocked functions in Vitest tests
Implement mock behaviors in beforeEach blocks in Vitest tests
Mock all required dependencies that the test subject uses
Each mock implementation should return a Promise for async functions in Vitest
Mock implementations should match the expected return type of the original function
Mock all required properties and methods that the test subject uses in Vitest tests
Avoid direct function mocking without vi.mocked() in Vitest tests
Avoid mock implementations outside of beforeEach blocks in Vitest tests
Avoid mocking without the spy: true option in Vitest tests
Avoid inline mock implementations within test cases in Vitest tests
Avoid mocking only a subset of required dependencies in Vitest tests
Mock at the highest level of abstraction needed in Vitest tests
Keep mock implementations simple and focused in Vitest tests
Use type-safe mocking with vi.mocked() in Vitest tests
Document complex mock behaviors in Vitest tests
Group related mocks together in Vitest tests

Files:

  • code/renderers/react/src/componentManifest/generator.test.ts
**/*.{js,jsx,json,html,ts,tsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use ESLint and Prettier configurations that are enforced in the codebase

Files:

  • code/renderers/react/src/componentManifest/generator.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Enable TypeScript strict mode

Files:

  • code/renderers/react/src/componentManifest/generator.test.ts
code/**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

code/**/*.{ts,tsx,js,jsx,mjs}: Use server-side logger from 'storybook/internal/node-logger' for Node.js code
Use client-side logger from 'storybook/internal/client-logger' for browser code
Do not use console.log, console.warn, or console.error directly unless in isolated files where importing loggers would significantly increase bundle size

Files:

  • code/renderers/react/src/componentManifest/generator.test.ts
code/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Export functions that need to be tested from their modules

Files:

  • code/renderers/react/src/componentManifest/generator.test.ts
code/**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

code/**/*.{test,spec}.{ts,tsx,js,jsx}: Write meaningful unit tests that actually import and call the functions being tested
Mock external dependencies using vi.mock() for file system, loggers, and other external dependencies in tests
Aim for high test coverage of business logic (75%+ for statements/lines) using coverage reports

Files:

  • code/renderers/react/src/componentManifest/generator.test.ts
code/**/*.{js,jsx,json,html,ts,tsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

code/**/*.{js,jsx,json,html,ts,tsx,mjs}: Run Prettier with --write flag to format code before committing
Run ESLint with yarn lint:js:cmd to check for linting issues and fix errors before committing

Files:

  • code/renderers/react/src/componentManifest/generator.test.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: Sidnioulz
Repo: storybookjs/storybook PR: 32458
File: code/core/src/components/components/Tabs/Tabs.stories.tsx:222-227
Timestamp: 2025-11-05T09:36:55.944Z
Learning: Repo: storybookjs/storybook PR: 32458 — In code/core/src/components/components/Button/Button.tsx (React/TypeScript), ButtonProps includes ariaLabel?: string | false and the component maps it to the DOM aria-label. Convention: ariaLabel is mandatory on all Button usages — provide a descriptive string for icon-only buttons; set ariaLabel=false when the button’s children already serve as the accessible name. Do not suggest using a raw aria-label prop on Button call sites.
📚 Learning: 2025-11-28T14:50:24.889Z
Learnt from: CR
Repo: storybookjs/storybook PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-28T14:50:24.889Z
Learning: Follow existing patterns and conventions in the Storybook codebase

Applied to files:

  • code/renderers/react/src/componentManifest/generator.test.ts
📚 Learning: 2025-09-24T09:39:39.233Z
Learnt from: ndelangen
Repo: storybookjs/storybook PR: 32507
File: code/core/src/manager/globals/globals-module-info.ts:25-33
Timestamp: 2025-09-24T09:39:39.233Z
Learning: In Storybook, storybook/actions/decorator is a preview-only entrypoint and should not be included in manager globals configuration. The duplicatedKeys array in code/core/src/manager/globals/globals-module-info.ts is specifically for manager-side externalization, not preview entrypoints.

Applied to files:

  • code/renderers/react/src/componentManifest/generator.test.ts
📚 Learning: 2025-11-05T09:38:47.712Z
Learnt from: Sidnioulz
Repo: storybookjs/storybook PR: 32458
File: code/core/src/components/components/Select/Select.tsx:200-204
Timestamp: 2025-11-05T09:38:47.712Z
Learning: Repo: storybookjs/storybook — Guidance: Until Storybook 11 is released, do not suggest using React.useId anywhere (e.g., in code/core/src/components/components/Select/Select.tsx) to maintain compatibility with React 17 runtimes. Prefer advising: accept a caller-provided props.id and, if needed, generate a client-only fallback id to minimize SSR hydration issues — but avoid useId. Resume prompting for useId after Storybook 11.

Applied to files:

  • code/renderers/react/src/componentManifest/generator.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: normal
  • GitHub Check: Core Unit Tests, windows-latest
  • GitHub Check: nx
🔇 Additional comments (6)
code/renderers/react/src/componentManifest/generator.test.ts (6)

11-14: LGTM!

The test setup correctly uses vi.spyOn for process.cwd() and memfs for file system mocking in the beforeEach block, following the coding guidelines for implementing mock behaviors in beforeEach blocks.


114-139: Snapshot correctly reflects self-closing JSX snippets.

The stories array now shows self-closing JSX syntax (e.g., <Button onClick={fn()} primary label="Button" />), which aligns with the PR objective of rendering empty components as self-closing tags. The addition of the "Small" story is also captured correctly.


241-291: LGTM!

The helper function is well-structured for parameterized manifest testing, properly setting up isolated file system mocks and returning the specific component manifest for validation.


293-306: LGTM!

Clean helper function that provides a consistent CSF3 wrapper for story test cases.


349-356: Self-closing JSX snippet correctly captured.

The snapshot validates that even for CSF1-style stories without a component name in meta, the generated snippet uses self-closing JSX syntax (<Button csf1="story" />).


362-464: LGTM!

The error handling tests properly validate that the manifest generator produces meaningful error messages for unsupported story patterns (re-exported components and unknown expressions), with descriptive error context including line numbers and code snippets.


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

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 (2)
code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx (1)

53-66: Prefer reusing withCSF3()/withCSF4() helpers (and consider aligning test name vs CSF version).

This test inlines CSF boilerplate that the file already centralizes in helpers, and despite the PR description mentioning CSF4 it’s currently exercising the CSF3-style default export meta. Consider rewriting via withCSF3() (or switching to withCSF4() if that’s the intended coverage) to reduce duplication and keep intent crisp.

code/renderers/react/src/componentManifest/generateCodeSnippet.ts (1)

225-234: Self-closing synthesis looks correct; consider treating children: '' as “no children” (if desired).

Current logic won’t self-close when args set children to an empty string, because toJsxChildren() produces a JSXText(''). If you want <Button /> for that case too, one low-risk place to encode it is toJsxChildren():

 const toJsxChildren = (node: t.Node | null | undefined) =>
   !node
     ? []
     : t.isStringLiteral(node)
-      ? [t.jsxText(node.value)]
+      ? node.value === ''
+        ? []
+        : [t.jsxText(node.value)]
       : t.isJSXElement(node) || t.isJSXFragment(node)
         ? [node]
         : t.isExpression(node)
           ? [t.jsxExpressionContainer(node)]
           : [];

(Only do this if product expectation is that empty-string children should render self-closing.)

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6f262ad and a819b69.

📒 Files selected for processing (2)
  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx (1 hunks)
  • code/renderers/react/src/componentManifest/generateCodeSnippet.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,json,html,ts,tsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use ESLint and Prettier configurations that are enforced in the codebase

Files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.ts
  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Enable TypeScript strict mode

Files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.ts
  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
code/**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

code/**/*.{ts,tsx,js,jsx,mjs}: Use server-side logger from 'storybook/internal/node-logger' for Node.js code
Use client-side logger from 'storybook/internal/client-logger' for browser code
Do not use console.log, console.warn, or console.error directly unless in isolated files where importing loggers would significantly increase bundle size

Files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.ts
  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
code/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Export functions that need to be tested from their modules

Files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.ts
  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
code/**/*.{js,jsx,json,html,ts,tsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

code/**/*.{js,jsx,json,html,ts,tsx,mjs}: Run Prettier with --write flag to format code before committing
Run ESLint with yarn lint:js:cmd to check for linting issues and fix errors before committing

Files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.ts
  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{test,spec}.{ts,tsx}: Test files should follow the naming pattern *.test.ts, *.test.tsx, *.spec.ts, or *.spec.tsx
Follow the spy mocking rules defined in .cursor/rules/spy-mocking.mdc for consistent mocking patterns with Vitest

Files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
**/*.test.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/spy-mocking.mdc)

**/*.test.{ts,tsx,js,jsx}: Use vi.mock() with the spy: true option for all package and file mocks in Vitest tests
Place all mocks at the top of the test file before any test cases
Use vi.mocked() to type and access the mocked functions in Vitest tests
Implement mock behaviors in beforeEach blocks in Vitest tests
Mock all required dependencies that the test subject uses
Each mock implementation should return a Promise for async functions in Vitest
Mock implementations should match the expected return type of the original function
Mock all required properties and methods that the test subject uses in Vitest tests
Avoid direct function mocking without vi.mocked() in Vitest tests
Avoid mock implementations outside of beforeEach blocks in Vitest tests
Avoid mocking without the spy: true option in Vitest tests
Avoid inline mock implementations within test cases in Vitest tests
Avoid mocking only a subset of required dependencies in Vitest tests
Mock at the highest level of abstraction needed in Vitest tests
Keep mock implementations simple and focused in Vitest tests
Use type-safe mocking with vi.mocked() in Vitest tests
Document complex mock behaviors in Vitest tests
Group related mocks together in Vitest tests

Files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
code/**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

code/**/*.{test,spec}.{ts,tsx,js,jsx}: Write meaningful unit tests that actually import and call the functions being tested
Mock external dependencies using vi.mock() for file system, loggers, and other external dependencies in tests
Aim for high test coverage of business logic (75%+ for statements/lines) using coverage reports

Files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
🧠 Learnings (2)
📓 Common learnings
Learnt from: Sidnioulz
Repo: storybookjs/storybook PR: 32458
File: code/core/src/components/components/Tabs/Tabs.stories.tsx:222-227
Timestamp: 2025-11-05T09:36:55.944Z
Learning: Repo: storybookjs/storybook PR: 32458 — In code/core/src/components/components/Button/Button.tsx (React/TypeScript), ButtonProps includes ariaLabel?: string | false and the component maps it to the DOM aria-label. Convention: ariaLabel is mandatory on all Button usages — provide a descriptive string for icon-only buttons; set ariaLabel=false when the button’s children already serve as the accessible name. Do not suggest using a raw aria-label prop on Button call sites.
📚 Learning: 2025-11-05T09:36:55.944Z
Learnt from: Sidnioulz
Repo: storybookjs/storybook PR: 32458
File: code/core/src/components/components/Tabs/Tabs.stories.tsx:222-227
Timestamp: 2025-11-05T09:36:55.944Z
Learning: Repo: storybookjs/storybook PR: 32458 — In code/core/src/components/components/Button/Button.tsx (React/TypeScript), ButtonProps includes ariaLabel?: string | false and the component maps it to the DOM aria-label. Convention: ariaLabel is mandatory on all Button usages — provide a descriptive string for icon-only buttons; set ariaLabel=false when the button’s children already serve as the accessible name. Do not suggest using a raw aria-label prop on Button call sites.

Applied to files:

  • code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx
🧬 Code graph analysis (1)
code/renderers/react/src/componentManifest/generateCodeSnippet.test.tsx (1)
scripts/utils/tools.ts (1)
  • dedent (119-119)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: normal
  • GitHub Check: nx
  • GitHub Check: Core Unit Tests, windows-latest

@storybook-app-bot
Copy link

storybook-app-bot bot commented Dec 15, 2025

Package Benchmarks

Commit: 883720a, ran on 15 December 2025 at 10:47:15 UTC

The following packages have significant changes to their size or dependencies:

@storybook/nextjs-vite

Before After Difference
Dependency count 127 128 🚨 +1 🚨
Self size 1.12 MB 1.12 MB 0 B
Dependency size 21.97 MB 21.96 MB 🎉 -11 KB 🎉
Bundle Size Analyzer Link Link

@storybook/react-native-web-vite

Before After Difference
Dependency count 159 160 🚨 +1 🚨
Self size 30 KB 30 KB 🚨 +18 B 🚨
Dependency size 23.15 MB 23.14 MB 🎉 -11 KB 🎉
Bundle Size Analyzer Link Link

@storybook/react-vite

Before After Difference
Dependency count 117 118 🚨 +1 🚨
Self size 35 KB 35 KB 🎉 -1 B 🎉
Dependency size 19.76 MB 19.75 MB 🎉 -11 KB 🎉
Bundle Size Analyzer Link Link

@valentinpalkovic valentinpalkovic merged commit a1c20cf into next Dec 15, 2025
67 of 69 checks passed
@valentinpalkovic valentinpalkovic deleted the valentin/self-closing-tag-code-snippet branch December 15, 2025 11:14
@github-actions github-actions bot mentioned this pull request Dec 15, 2025
18 tasks
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