Skip to content

refactor: split swagger viewer components - #80

Closed
Ivan-khodorov wants to merge 3 commits into
story/4-curl-generationfrom
refactor/4-split-swagger-viewer
Closed

refactor: split swagger viewer components#80
Ivan-khodorov wants to merge 3 commits into
story/4-curl-generationfrom
refactor/4-split-swagger-viewer

Conversation

@Ivan-khodorov

@Ivan-khodorov Ivan-khodorov commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator

Task

Refactor Swagger Viewer files to reduce component size and avoid large "god file" penalties.

What Was Done

  • Split swagger-viewer.tsx into focused modules:
    • endpoint-details.tsx
    • try-it-out-panel.tsx
    • swagger-viewer.helpers.ts
  • Kept SwaggerViewer public export unchanged.
  • Preserved existing Viewer behavior, Try-It-Out behavior, cURL generation, and UI structure.
  • Reduced swagger-viewer.tsx to 152 lines.

Validation

  • npm test -- src/components/swagger-viewer/swagger-viewer.test.tsx
  • npm test
  • npm run lint
  • npm run build
  • git diff --check

Notes

This PR is stacked on top of story/4-curl-generation and should be reviewed/merged after PR #78.

Summary by CodeRabbit

  • New Features
    • Added richer Swagger endpoint detail sections for parameters, request bodies, and responses, including content-type chips, examples, schema text, and graceful empty states.
    • Enhanced the “Try it out” experience with a cURL preview (copy to clipboard) and execution with translated error handling, plus a response details view (status, duration, headers, body).
  • Refactor
    • Modularized Swagger Viewer UI by extracting endpoint-detail and Try-it-out components.
  • Tests
    • Added interaction tests for cURL generation gating, execution concurrency, and blocked-URL error display.
  • Documentation
    • Added a new English/Russian i18n message prompting users to fill required fields before generating cURL.

@vercel

vercel Bot commented Jul 12, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
swagger-editor-app Ready Ready Preview, Comment Jul 12, 2026 5:45am

@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds reusable Swagger endpoint detail components, extracts Try-It-Out request and cURL helpers, and introduces an interactive panel that builds, executes, copies, and displays API requests and responses.

Changes

Swagger Viewer Try-It-Out

Layer / File(s) Summary
Endpoint detail rendering
src/components/swagger-viewer/endpoint-details.tsx
Adds reusable parameter, request body, and response detail components with content types, schemas, examples, descriptions, and fallback rendering.
Try-It-Out request helpers
src/components/swagger-viewer/swagger-viewer.helpers.ts
Builds resolved requests and shell-safe cURL commands, handles headers and cookies, and maps Try-It-Out errors to translation keys.
Try-It-Out panel integration
src/components/swagger-viewer/try-it-out-panel.tsx, src/components/swagger-viewer/curl-command-preview.tsx, src/components/swagger-viewer/try-it-out-response-details.tsx, src/components/swagger-viewer/swagger-viewer.tsx, src/components/swagger-viewer/try-it-out-panel.test.tsx, src/i18n/messages/*.json
Adds the Try-It-Out form, request execution, clipboard copying, error handling, response display, extracted component wiring, interaction tests, and translations.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related PRs

Suggested labels: feature-3-editor

Suggested reviewers: YuliaDemir, lexarudak

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: refactoring Swagger Viewer into separate components.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/4-split-swagger-viewer

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
src/components/swagger-viewer/endpoint-details.tsx (3)

1-14: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing 'use client' despite hook usage.

ParameterDetails/RequestBodyDetails/Examples/SchemaText call the useTranslations hook, but this file has no 'use client' directive. It currently works only because it's transitively bundled via files that already declare 'use client' (swagger-viewer.tsx, try-it-out-panel.tsx); if this module is ever imported directly by a Server Component, it will break at runtime.

As per path instructions, "Flag components missing 'use client' directive when using hooks."

🛠️ Proposed fix
+'use client';
+
 import type { ReactNode } from 'react';

Also applies to: 35-35

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/swagger-viewer/endpoint-details.tsx` around lines 1 - 14, Add
the 'use client' directive at the top of endpoint-details.tsx before imports,
since ParameterDetails, RequestBodyDetails, Examples, and SchemaText use
useTranslations. Keep the existing component implementations unchanged.

Source: Path instructions


35-109: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate Paper/Stack scaffolding across three components.

ParameterDetails, RequestBodyDetails, and ResponseDetails all repeat the same <Paper><Stack spacing={1}><Stack direction="row" ...> wrapper and description block. Consider extracting a shared DetailCard({ badges, description, children }) wrapper to reduce duplication.

As per path instructions, "Flag code smells: God-objects, duplicate code chunks, unused files or exports."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/swagger-viewer/endpoint-details.tsx` around lines 35 - 109,
Extract the repeated Paper/Stack layout and optional description handling from
ParameterDetails, RequestBodyDetails, and ResponseDetails into a shared
DetailCard component accepting badges, description, and children. Replace each
component’s duplicated wrapper with DetailCard while preserving its existing
badges, content, spacing, and conditional description behavior.

Source: Path instructions


125-156: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Code-block styling duplicated with try-it-out-panel.tsx.

The sx styling for <Box component="pre"> here (bgcolor/borderRadius/fontSize/overflow/whiteSpace) is repeated verbatim three more times in try-it-out-panel.tsx (curl command, response headers, response body). Worth extracting into a shared CodeBlock component used by both files.

As per path instructions, "Flag duplicate implementations of the same logic in different files."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/swagger-viewer/endpoint-details.tsx` around lines 125 - 156,
Extract the duplicated code-block presentation from Examples and the three
corresponding preformatted blocks in try-it-out-panel.tsx into a shared
CodeBlock component. Move the common Box component="pre" styling (including
bgcolor, borderRadius, fontSize, overflow, and whiteSpace) into that component,
then replace each duplicated implementation while preserving its existing
content, spacing, and behavior.

Source: Path instructions

src/components/swagger-viewer/try-it-out-panel.tsx (1)

192-206: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Same pre/code-block styling repeated three times here (and again in endpoint-details.tsx).

See the corresponding note in endpoint-details.tsx — extracting a shared CodeBlock component would remove this duplication across both files.

As per path instructions, "Flag duplicate implementations of the same logic in different files."

Also applies to: 236-251, 256-269

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/swagger-viewer/try-it-out-panel.tsx` around lines 192 - 206,
Extract the repeated preformatted code styling from the try-it-out panel’s curl,
request, and response blocks into a shared CodeBlock component, then reuse that
component for all three blocks and in endpoint-details.tsx. Preserve the
existing content, scrolling, wrapping, spacing, and visual styling.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/components/swagger-viewer/try-it-out-panel.tsx`:
- Around line 172-174: Update handleGenerateCurl and the "Generate cURL" Button
flow so required-field validation runs before generating the command. Prevent
generation when required parameters are empty, preserving the existing behavior
for valid input and avoiding unresolved placeholders in the resulting URL.
- Around line 118-122: Remove the showToast call from the !result.ok branch in
the Try-It-Out execution flow, while preserving
setError(t(getTryItOutErrorKey(payload.errorCode))) and the early return so
proxy 4xx/5xx errors remain displayed only in the response UI.
- Around line 96-108: Add an early return at the start of handleSubmit when
isExecuting is already true, before resetting state or building the request, so
Enter-key submissions cannot launch overlapping requests while execution is in
progress.

---

Nitpick comments:
In `@src/components/swagger-viewer/endpoint-details.tsx`:
- Around line 1-14: Add the 'use client' directive at the top of
endpoint-details.tsx before imports, since ParameterDetails, RequestBodyDetails,
Examples, and SchemaText use useTranslations. Keep the existing component
implementations unchanged.
- Around line 35-109: Extract the repeated Paper/Stack layout and optional
description handling from ParameterDetails, RequestBodyDetails, and
ResponseDetails into a shared DetailCard component accepting badges,
description, and children. Replace each component’s duplicated wrapper with
DetailCard while preserving its existing badges, content, spacing, and
conditional description behavior.
- Around line 125-156: Extract the duplicated code-block presentation from
Examples and the three corresponding preformatted blocks in try-it-out-panel.tsx
into a shared CodeBlock component. Move the common Box component="pre" styling
(including bgcolor, borderRadius, fontSize, overflow, and whiteSpace) into that
component, then replace each duplicated implementation while preserving its
existing content, spacing, and behavior.

In `@src/components/swagger-viewer/try-it-out-panel.tsx`:
- Around line 192-206: Extract the repeated preformatted code styling from the
try-it-out panel’s curl, request, and response blocks into a shared CodeBlock
component, then reuse that component for all three blocks and in
endpoint-details.tsx. Preserve the existing content, scrolling, wrapping,
spacing, and visual styling.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 599f3a95-5491-4614-8423-2d8e3b59756e

📥 Commits

Reviewing files that changed from the base of the PR and between d7a53a3 and 408db76.

📒 Files selected for processing (4)
  • src/components/swagger-viewer/endpoint-details.tsx
  • src/components/swagger-viewer/swagger-viewer.helpers.ts
  • src/components/swagger-viewer/swagger-viewer.tsx
  • src/components/swagger-viewer/try-it-out-panel.tsx

Comment thread src/components/swagger-viewer/try-it-out-panel.tsx
Comment thread src/components/swagger-viewer/try-it-out-panel.tsx
Comment thread src/components/swagger-viewer/try-it-out-panel.tsx

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/components/swagger-viewer/try-it-out-panel.test.tsx (2)

50-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing vi.unstubAllGlobals() cleanup for stubbed fetch.

vi.stubGlobal('fetch', ...) is used in later tests (Lines 78, 91-97) but afterEach only calls vi.restoreAllMocks(). Per Vitest docs, stubbed globals persist until vi.unstubAllGlobals() is called explicitly (or the unstubGlobals config option is enabled) — restoreAllMocks() does not reset them. This risks leaking the stubbed fetch into subsequent test files/suites if module state isn't otherwise isolated.

🧹 Proposed fix
   afterEach(() => {
     vi.restoreAllMocks();
+    vi.unstubAllGlobals();
   });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/swagger-viewer/try-it-out-panel.test.tsx` around lines 50 -
52, Update the afterEach cleanup in the test suite to call vi.unstubAllGlobals()
alongside vi.restoreAllMocks(), ensuring the fetch stub created by the later
tests is removed after each test.

88-105: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a counterpart test for the network-error toast path.

This test verifies the toast is suppressed on a validation/proxy error (blockedUrl), but there's no test confirming requestNetworkError toast is shown when fetch rejects (the catch branch in handleSubmit). Adding that would round out coverage of the two divergent error paths.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/swagger-viewer/try-it-out-panel.test.tsx` around lines 88 -
105, Add a counterpart test alongside the existing proxy-validation test that
mocks fetch to reject, submits the panel through handleSubmit, and asserts
requestNetworkError is displayed while preserving the existing blockedUrl
suppression coverage.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/components/swagger-viewer/try-it-out-panel.test.tsx`:
- Around line 50-52: Update the afterEach cleanup in the test suite to call
vi.unstubAllGlobals() alongside vi.restoreAllMocks(), ensuring the fetch stub
created by the later tests is removed after each test.
- Around line 88-105: Add a counterpart test alongside the existing
proxy-validation test that mocks fetch to reject, submits the panel through
handleSubmit, and asserts requestNetworkError is displayed while preserving the
existing blockedUrl suppression coverage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2ebf86a0-a484-4aa2-adb0-b9225d6633e0

📥 Commits

Reviewing files that changed from the base of the PR and between eb5852d and 2587c14.

📒 Files selected for processing (4)
  • src/components/swagger-viewer/try-it-out-panel.test.tsx
  • src/components/swagger-viewer/try-it-out-panel.tsx
  • src/i18n/messages/en.json
  • src/i18n/messages/ru.json
✅ Files skipped from review due to trivial changes (2)
  • src/i18n/messages/en.json
  • src/i18n/messages/ru.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/swagger-viewer/try-it-out-panel.tsx

@AlyaEngineer AlyaEngineer left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

норм, god object теперь отсутствует)
можно еще изменить радиус скругления в этом компоненте, а то не очень смотрится (не обязательно тут, прост чтоб не забыть )
Снимок экрана 2026-07-13 003356

@AlyaEngineer
AlyaEngineer deleted the refactor/4-split-swagger-viewer branch July 13, 2026 23:33
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.

2 participants