Skip to content

feat: add response data type selector in response viewer - #6100

Merged
bijin-bruno merged 26 commits into
usebruno:mainfrom
abhishek-bruno:feat/response-data-type-selector
Dec 9, 2025
Merged

bijin-bruno merged 26 commits into
usebruno:mainfrom
abhishek-bruno:feat/response-data-type-selector

Conversation

@abhishek-bruno

@abhishek-bruno abhishek-bruno commented Nov 14, 2025 •

Copy link
Copy Markdown
Member

Description

Added Response Data Type selector with preview mode for each type. Closes #4963
JIRA

  • Introduced a new ButtonDropdown component for selecting options.
  • Integrated ButtonDropdown into QueryResultTypeSelector for format selection.
  • Enhanced QueryResult to support multiple preview formats including JSON, HTML, XML, and more.
  • Added new preview components for HTML, JSON, XML, Text, and more.
  • Updated formatResponse utility to handle new formats and prettify HTML/JavaScript.
  • Adjusted QueryResult styling for better layout and usability.

Contribution Checklist:

  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.

Publishing to New Package Managers

Please see here for more information.

Summary by CodeRabbit

  • New Features

    • Expanded response format selector with Editor/Preview toggle and many preview modes (JSON, HTML, XML, JavaScript, Text/Raw, Hex, Base64, media)
    • Rich, safer previews: formatted HTML/JS, JSON tree view, collapsible XML, text fallback, video/audio/image/PDF playback, and download action
    • New responsive actions menu and unified response view with format/tab controls
  • Tests

    • End-to-end tests plus new test helpers and locators for format selection, preview flows, and response actions

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

@abhishek-bruno
abhishek-bruno force-pushed the feat/response-data-type-selector branch 2 times, most recently from b7fba59 to 01624b2 Compare November 20, 2025 08:37
@abhishek-bruno
abhishek-bruno marked this pull request as draft November 20, 2025 10:27
Comment thread tests/utils/page/actions.ts Resolved
Comment thread tests/utils/page/actions.ts Resolved
@abhishek-bruno
abhishek-bruno force-pushed the feat/response-data-type-selector branch from dc5bcea to d079708 Compare December 1, 2025 06:40
@coderabbitai

coderabbitai Bot commented Dec 2, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds response format detection, formatting utilities, selector UI, multiple preview components (HTML/JSON/XML/Text/Video), response action hooks/components (copy/clear/download/layout), QueryResponse wrapper, and Playwright tests/fixtures for format selection and previews.

Changes

Cohort / File(s) Summary
Preview components
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/HtmlPreview.js, .../JsonPreview.js, .../TextPreview.js, .../VideoPreview.js, .../XmlPreview/index.js, .../XmlPreview/StyledWrapper.js
New memoized preview components: HtmlPreview (base tag injection, drag-disable via MutationObserver), JsonPreview (validation, ErrorAlert, ReactJson), TextPreview (safe stringify), VideoPreview (base64→Blob URL lifecycle), XmlPreview (DOM parse → collapsible tree).
Response utils & formatters
packages/bruno-app/src/utils/response/index.js, packages/bruno-app/src/utils/common/index.js, packages/bruno-app/src/utils/common/codemirror.js
New content-type normalization, buffer magic-number detection, isValidHtml/snippet, prettifyHtml/prettifyJavaScript (Prettier), hex dump/isHex utilities; updated CodeMirror mode mapping (javascript).
QueryResult → QueryResponse & hooks
packages/bruno-app/src/components/ResponsePane/QueryResult/index.js, packages/bruno-app/src/components/ResponsePane/QueryResponse/index.js, packages/bruno-app/src/components/ResponsePane/QueryResponse/StyledWrapper.js
Introduced useInitialResponseFormat and useResponsePreviewFormatOptions; refactored preview control to selectedFormat/selectedTab and previewMode/codeMirrorMode; added QueryResponse wrapper that surfaces selector and preview props.
Selector & dropdown UI
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultTypeSelector/index.jsx, .../StyledWrapper.js, packages/bruno-app/src/ui/ButtonDropdown/index.jsx, .../StyledWrapper.js
New QueryResultTypeSelector (toggle + ButtonDropdown) and ButtonDropdown implementation with styling.
Response actions & hooks
packages/bruno-app/src/components/ResponsePane/ResponsePaneActions/index.js, .../ResponsePaneActions/StyledWrapper.js, .../ResponseDownload/index.js, .../ResponseDownload/StyledWrapper.js, .../ResponseCopy/index.js, .../ResponseClear/index.js, .../ResponseBookmark/index.js, .../ResponseLayoutToggle/index.js
New responsive actions UI and hooks (useResponseCopy, useResponseClear, useResponseLayoutToggle); ResponseDownload replaces ResponseSave; action components accept children and keyboard interactions; unified styled wrappers.
Removed component
packages/bruno-app/src/components/ResponsePane/ResponseSave/index.js, .../ResponseSave/StyledWrapper.js
Deleted ResponseSave and its styled wrapper; download behavior moved to ResponseDownload.
Error UI
packages/bruno-app/src/ui/ErrorAlert/index.js, packages/bruno-app/src/ui/ErrorAlert/StyledWrapper.js
New ErrorAlert component and styled wrapper used by preview components for parse/validation errors.
Integration & imports
packages/bruno-app/src/components/ResponsePane/index.js, packages/bruno-app/src/components/Devtools/Console/RequestDetailsPanel/index.js, packages/bruno-app/src/components/ResponsePane/Timeline/.../Body/index.js, packages/bruno-app/src/components/RunnerResults/ResponsePane/index.js
Replaced QueryResult usages with QueryResponse, wired selector/actions into ResponsePane, propagated selectedFormat/selectedTab props, and adjusted imports/layout.
Tests, fixtures & helpers
tests/utils/page/actions.ts, tests/utils/page/locators.ts, tests/response/response-format-select-and-preview/*.spec.ts, tests/response/response-format-select-and-preview/fixtures/*, tests/response/large-response-crash-prevention.spec.ts, various tests/response-examples/*
New E2E Playwright suite and fixtures for format selection/preview; updated locators and helpers (collection-first openRequest, sendRequestAndWaitForResponse, switchResponseFormat, switchToPreviewTab, switchToEditorTab, clickResponseAction); one tightened test assertion.
Styling & minor UI tweaks
many packages/bruno-app/src/components/ResponsePane/*/StyledWrapper.js and related index files
Numerous cosmetic style/token adjustments: font-weight, margins, hover/bg, border-radius, separator class, and small className changes across response components.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant User
    participant ResponsePane
    participant Detector as ResponseUtils
    participant QueryResponse
    participant Selector as TypeSelector
    participant Preview as PreviewComponent

    User->>ResponsePane: response arrives (dataBuffer, headers)
    ResponsePane->>Detector: detectContentTypeFromBuffer / getDefaultResponseFormat
    Detector-->>ResponsePane: initialFormat, previewOptions
    ResponsePane->>QueryResponse: render(selectedFormat, selectedTab, codeMirrorMode)
    QueryResponse->>Selector: render format selector
    User->>Selector: choose format
    Selector->>QueryResponse: onFormatChange(format)
    QueryResponse->>Preview: mount appropriate PreviewComponent
    Preview->>Detector: validate/format (isValidHtml / JSON.parse / prettify / formatHexView)
    Preview-->>User: display rendered preview or ErrorAlert
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Focus areas:
    • format-detection utilities and magic-number mapping (packages/.../utils/response/index.js)
    • HtmlPreview: base tag injection, MutationObserver lifecycle and drag-state handling
    • JsonPreview/ErrorAlert integration and JSON parsing/error surfaces
    • VideoPreview: base64→Blob conversion and object URL cleanup
    • Hooks: useInitialResponseFormat / useResponsePreviewFormatOptions and prop synchronization between ResponsePane → QueryResponse
    • Tests: new Playwright helpers, locators, and the E2E suite

Possibly related PRs

Suggested reviewers

  • lohit-bruno
  • naman-bruno

Poem

A pane that learns what bytes can be,
HTML, JSON, video — pick and see,
Helpers tidy, previews play,
Tests keep watch to guard the way,
Tiny hooks make the UI free. 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.94% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 'feat: add response data type selector in response viewer' is concise, descriptive, and accurately reflects the main feature added—a selector for choosing response data types in the response viewer.
Linked Issues check ✅ Passed The PR fully implements the objectives from issue #4963: enables response data type selection, supports multiple preview formats (JSON, HTML, XML, Text), and provides an in-app mechanism to switch formats without external tools.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the response data type selector feature. Supporting changes include new preview components, format utilities, ButtonDropdown UI component, test utilities, and styling adjustments—all necessary for the core feature.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1db2ef6 and da74540.

📒 Files selected for processing (1)
  • tests/response/response-format-select-and-preview/response-format-select-and-preview.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/response/response-format-select-and-preview/response-format-select-and-preview.spec.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). (6)
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: Unit Tests
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: CLI Tests

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

@abhishek-bruno
abhishek-bruno marked this pull request as ready for review December 2, 2025 14:15

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 12

🧹 Nitpick comments (18)
tests/response/large-response-crash-prevention.spec.ts (1)

14-42: Consider adding test.step for better report readability.

Per coding guidelines, wrapping logical sections (create collection, create request, send request, verify warning) in test.step would improve generated report clarity.

packages/bruno-app/src/utils/common/index.js (3)

327-424: Consider extracting duplicated large-response handling logic.

The same pattern appears for html, javascript, and text/raw modes:

if (isVeryLargeResponse) {
  if (typeof data === 'string') { return data; }
  if (data === null || data === undefined) { return String(data); }
  if (typeof data === 'object') { return safeStringifyJSON(data, false); }
  return String(data);
}

Extract to a helper function to reduce duplication:

+const handleLargeResponse = (data) => {
+  if (typeof data === 'string') return data;
+  if (data === null || data === undefined) return String(data);
+  if (typeof data === 'object') return safeStringifyJSON(data, false);
+  return String(data);
+};
+
 // Then use in each mode:
 if (mode.includes('html')) {
-  if (isVeryLargeResponse) {
-    if (typeof data === 'string') {
-      return data;
-    }
-    if (data === null || data === undefined) {
-      return String(data);
-    }
-    if (typeof data === 'object') {
-      return safeStringifyJSON(data, false);
-    }
-    return String(data);
-  }
+  if (isVeryLargeResponse) return handleLargeResponse(data);

450-466: Inconsistent function declaration style.

These new functions use function keyword while the rest of the file uses arrow function exports (e.g., export const simpleHash = (str) => {). Consider using arrow functions for consistency.

-export function prettifyHtmlString(htmlString) {
+export const prettifyHtmlString = (htmlString) => {
   if (typeof htmlString !== 'string') return htmlString;
   // ...
-};
+};

385-400: Empty string return on error may hide formatting issues.

When hex encoding fails, returning '' silently could confuse users. Consider logging a warning or returning a more informative fallback.

       } catch (stringError) {
-        return '';
+        console.warn('Failed to format hex view:', stringError);
+        return '';
       }
     }
-    return '';
+    console.warn('Failed to format hex view for non-string data');
+    return '';
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/TextPreview.js (1)

3-23: Consider adding a display name for better debugging.

The component uses memo but lacks a displayName, which can make React DevTools harder to navigate.

Apply this diff:

 const TextPreview = memo(({ data }) => {
   const displayData = useMemo(() => {
     if (data === null || data === undefined) {
       return String(data);
     }
     if (typeof data === 'object') {
       try {
         return JSON.stringify(data);
       } catch {
         return String(data);
       }
     }
     return String(data);
   }, [data]);

   return (
     <div className="p-4 font-mono text-[13px] whitespace-pre-wrap break-words overflow-auto overflow-x-hidden w-full max-w-full h-full">
       {displayData}
     </div>
   );
 });

+TextPreview.displayName = 'TextPreview';
+
 export default TextPreview;
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/JsonPreview.js (2)

7-25: Extract helper function outside component for better performance.

The validateJsonData helper is recreated on every render. Since it doesn't depend on props or state, extracting it outside the component body will improve performance.

Apply this diff:

 import React from 'react';
 import ReactJson from 'react-json-view';
 import ErrorAlert from 'components/ErrorAlert/index';

+// Helper function to validate and parse JSON data
+const validateJsonData = (data) => {
+  // If data is already an object or array, use it directly
+  if (typeof data === 'object' && data !== null) {
+    return { data, error: null };
+  }
+
+  // If data is a string, try to parse it
+  if (typeof data === 'string') {
+    try {
+      const parsed = JSON.parse(data);
+      return { data: parsed, error: null };
+    } catch (e) {
+      return { data: null, error: `Invalid JSON format: ${e.message}` };
+    }
+  }
+
+  // For other types, return error
+  return { data: null, error: 'Invalid input. Expected a JSON object, array, or valid JSON string.' };
+};
+
 const JsonPreview = ({ data, displayedTheme }) => {
-  // Helper function to validate and parse JSON data
-  const validateJsonData = (data) => {
-    // If data is already an object or array, use it directly
-    if (typeof data === 'object' && data !== null) {
-      return { data, error: null };
-    }
-
-    // If data is a string, try to parse it
-    if (typeof data === 'string') {
-      try {
-        const parsed = JSON.parse(data);
-        return { data: parsed, error: null };
-      } catch (e) {
-        return { data: null, error: `Invalid JSON format: ${e.message}` };
-      }
-    }
-
-    // For other types, return error
-    return { data: null, error: 'Invalid input. Expected a JSON object, array, or valid JSON string.' };
-  };
-
   // Validate and parse JSON data
   const jsonData = validateJsonData(data);

5-61: Consider adding a display name for better debugging.

Adding a displayName will make this component easier to identify in React DevTools.

Add after the component definition:

 const JsonPreview = ({ data, displayedTheme }) => {
   // ... component implementation
 };

+JsonPreview.displayName = 'JsonPreview';
+
 export default JsonPreview;
packages/bruno-app/src/components/ErrorAlert/index.js (2)

13-13: Add error handling for JSON.stringify to prevent crashes.

JSON.stringify will throw if message contains circular references. Since this component handles error display, it should be resilient to malformed input.

Apply this diff:

-          <div className="error-message">{typeof message === 'string' ? message : JSON.stringify(message, null, 2)}</div>
+          <div className="error-message">
+            {typeof message === 'string' ? message : (() => {
+              try {
+                return JSON.stringify(message, null, 2);
+              } catch {
+                return String(message);
+              }
+            })()}
+          </div>

9-9: Consider making margins configurable via props.

Hardcoded margin classes (mt-4 mb-2) reduce reusability. Consider accepting a className prop to allow customization when needed.

Example implementation:

-const ErrorAlert = ({ title, message, onClose }) => {
+const ErrorAlert = ({ title, message, onClose, className = 'mt-4 mb-2' }) => {
   if (!message) return null;

   return (
-    <StyledWrapper className="mt-4 mb-2">
+    <StyledWrapper className={className}>
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/VideoPreview.js (1)

1-3: Consolidate React imports.

Minor cleanup: merge the two React import statements.

-import React from 'react';
-import { useEffect, useState } from 'react';
+import React, { useEffect, useState } from 'react';
packages/bruno-app/src/components/ErrorAlert/StyledWrapper.js (1)

13-13: Fragile dark theme detection.

Comparing against a hardcoded hex value ('#1e1e1e') is brittle. If the theme's background color changes, this condition breaks.

Consider using a dedicated theme property if available (e.g., props.theme.mode === 'dark') or define the background colors in the theme itself.

packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.js (2)

27-32: Move isValidTreeData outside the component.

This function is recreated on every render. Move it to module scope since it doesn't depend on component state or props.

+const isValidTreeData = (data) => {
+  if (data === null || data === undefined) return false;
+  if (typeof data === 'object' && !Array.isArray(data)) return true;
+  if (Array.isArray(data)) return true;
+  return false;
+};
+
 export default function XmlPreview({ data, defaultExpanded = true }) {
   // ...
-  const isValidTreeData = (data) => {
-    if (data === null || data === undefined) return false;
-    if (typeof data === 'object' && !Array.isArray(data)) return true;
-    if (Array.isArray(data)) return true;
-    return false;
-  };

175-177: Remove unused variables.

hasArrayValue and arrayLength are declared but never used. Array nodes are handled earlier at lines 82-99.

-  // Determine if this node's value is an array
-  const hasArrayValue = Array.isArray(node);
-  const arrayLength = hasArrayValue ? node.length : 0;
packages/bruno-app/src/components/ButtonDropdown/index.jsx (2)

20-20: Unused dropdownTippyRef - remove or utilize.

The ref is assigned but never read. If intended for programmatic dropdown control (e.g., closing on selection), implement that; otherwise, remove the dead code.

Also applies to: 42-44


46-48: Consider inlining handleOptionSelect.

This wrapper only calls onChange without additional logic. Per coding guidelines, avoid single-line abstractions that only increase the call stack.

-  const handleOptionSelect = (optionValue) => {
-    onChange(optionValue);
-  };
...
-                onClick={() => handleOptionSelect(option.value)}
+                onClick={() => onChange(option.value)}
packages/bruno-app/src/utils/response/index.js (1)

213-218: MP4 detection may miss some valid files.

The MP4/MOV ftyp box can have sizes other than 0x18 or 0x20. Consider checking just for the ftyp signature at bytes 4-7 regardless of box size.

-  if (bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0x00
-    && (bytes[3] === 0x18 || bytes[3] === 0x20)
-    && bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70) {
+  // ftyp box - check signature at offset 4 regardless of box size
+  if (bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70) {
     return 'video/mp4';
   }
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js (1)

1-1: useMemo is imported but not used.

Remove unused import to keep the codebase clean.

-import React, { useState, useMemo } from 'react';
+import React, { useState } from 'react';
packages/bruno-app/src/components/ResponsePane/QueryResult/index.js (1)

117-125: Unused responseEncoding in dependency array.

responseEncoding is listed as a dependency but not passed to formatResponse. Either remove from deps or pass it to the function if needed.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd72ee5 and 4bdd37d.

📒 Files selected for processing (25)
  • packages/bruno-app/src/components/ButtonDropdown/StyledWrapper.js (1 hunks)
  • packages/bruno-app/src/components/ButtonDropdown/index.jsx (1 hunks)
  • packages/bruno-app/src/components/ErrorAlert/StyledWrapper.js (1 hunks)
  • packages/bruno-app/src/components/ErrorAlert/index.js (1 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/HtmlPreview.js (1 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/JsonPreview.js (1 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/TextPreview.js (1 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/VideoPreview.js (1 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.js (1 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js (4 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultTypeSelector/index.jsx (1 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/StyledWrapper.js (1 hunks)
  • packages/bruno-app/src/components/ResponsePane/QueryResult/index.js (4 hunks)
  • packages/bruno-app/src/utils/common/codemirror.js (1 hunks)
  • packages/bruno-app/src/utils/common/index.js (4 hunks)
  • packages/bruno-app/src/utils/response/index.js (1 hunks)
  • tests/response/large-response-crash-prevention.spec.ts (1 hunks)
  • tests/response/response-format-select-and-preview/fixtures/collection/bruno.json (1 hunks)
  • tests/response/response-format-select-and-preview/fixtures/collection/request-html.bru (1 hunks)
  • tests/response/response-format-select-and-preview/fixtures/collection/request-json.bru (1 hunks)
  • tests/response/response-format-select-and-preview/init-user-data/collection-security.json (1 hunks)
  • tests/response/response-format-select-and-preview/init-user-data/preferences.json (1 hunks)
  • tests/response/response-format-select-and-preview/response-format-select-and-preview.spec.ts (1 hunks)
  • tests/utils/page/actions.ts (2 hunks)
  • tests/utils/page/locators.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single parameters
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses. Keep 'em tight
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Avoid single line abstractions where all that's being done is increasing the call stack with one additional function
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/ButtonDropdown/StyledWrapper.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/TextPreview.js
  • tests/response/response-format-select-and-preview/response-format-select-and-preview.spec.ts
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultTypeSelector/index.jsx
  • packages/bruno-app/src/components/ErrorAlert/index.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/JsonPreview.js
  • packages/bruno-app/src/components/ButtonDropdown/index.jsx
  • tests/utils/page/locators.ts
  • tests/response/large-response-crash-prevention.spec.ts
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/VideoPreview.js
  • packages/bruno-app/src/utils/response/index.js
  • packages/bruno-app/src/utils/common/index.js
  • packages/bruno-app/src/utils/common/codemirror.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/HtmlPreview.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/StyledWrapper.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/index.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.js
  • packages/bruno-app/src/components/ErrorAlert/StyledWrapper.js
  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js
  • tests/utils/page/actions.ts
tests/**/**.*

⚙️ CodeRabbit configuration file

tests/**/**.*: Review the following e2e test code written using the Playwright test library. Ensure that:

  • Follow best practices for Playwright code and e2e automation

  • Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls

  • Avoid using page.pause() in code

  • Use locator variables for locators

  • Avoid using test.only

  • Use multiple assertions

  • Promote the use of test.step as much as possible so the generated reports are easier to read

  • Ensure that the fixtures like the collections are nested inside the fixtures folder

    Fixture Example*: Here's an example of possible fixture and test pair

    .
    ├── fixtures
    │   └── collection
    │       ├── base.bru
    │       ├── bruno.json
    │       ├── collection.bru
    │       ├── ws-test-request-with-headers.bru
    │       ├── ws-test-request-with-subproto.bru
    │       └── ws-test-request.bru
    ├── connection.spec.ts # <- Depends on the collection in ./fixtures/collection
    ├── headers.spec.ts
    ├── persistence.spec.ts
    ├── variable-interpolation
    │   ├── fixtures
    │   │   └── collection
    │   │       ├── environments
    │   │       ├── bruno.json
    │   │       └── ws-interpolation-test.bru
    │   ├── init-user-data
    │   └── variable-interpolation.spec.ts # <- Depends on the collection in ./variable-interpolation/fixtures/collection
    └── subproto.spec.ts
    

Files:

  • tests/response/response-format-select-and-preview/init-user-data/collection-security.json
  • tests/response/response-format-select-and-preview/response-format-select-and-preview.spec.ts
  • tests/response/response-format-select-and-preview/fixtures/collection/request-html.bru
  • tests/utils/page/locators.ts
  • tests/response/large-response-crash-prevention.spec.ts
  • tests/response/response-format-select-and-preview/fixtures/collection/bruno.json
  • tests/response/response-format-select-and-preview/init-user-data/preferences.json
  • tests/response/response-format-select-and-preview/fixtures/collection/request-json.bru
  • tests/utils/page/actions.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

Multiple expressions per line in JSX are fine – flexibility is nice

Files:

  • packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultTypeSelector/index.jsx
  • packages/bruno-app/src/components/ButtonDropdown/index.jsx
🧬 Code graph analysis (8)
packages/bruno-app/src/components/ButtonDropdown/StyledWrapper.js (1)
packages/bruno-app/src/components/ResponsePane/QueryResult/StyledWrapper.js (1)
  • StyledWrapper (3-59)
tests/response/response-format-select-and-preview/response-format-select-and-preview.spec.ts (3)
tests/utils/page/actions.ts (6)
  • closeAllCollections (205-205)
  • openRequest (214-214)
  • sendRequestAndWaitForResponse (210-210)
  • switchToPreviewTab (212-212)
  • switchToEditorTab (213-213)
  • switchResponseFormat (211-211)
tests/utils/page/locators.ts (1)
  • buildCommonLocators (3-65)
packages/bruno-app/src/utils/codemirror/brunoVarInfo.js (1)
  • editorContainer (298-298)
packages/bruno-app/src/components/ErrorAlert/index.js (1)
packages/bruno-app/src/components/ErrorAlert/StyledWrapper.js (1)
  • StyledWrapper (3-42)
packages/bruno-app/src/components/ButtonDropdown/index.jsx (3)
packages/bruno-app/src/components/Icons/IconCaretDown/index.js (1)
  • IconCaretDown (3-16)
packages/bruno-app/src/components/ButtonDropdown/StyledWrapper.js (1)
  • StyledWrapper (3-7)
packages/bruno-app/src/components/Dropdown/index.js (1)
  • Dropdown (5-25)
packages/bruno-app/src/utils/response/index.js (3)
packages/bruno-app/src/components/ResponsePane/QueryResult/index.js (1)
  • contentType (56-56)
packages/bruno-app/src/utils/common/index.js (3)
  • contentType (94-94)
  • i (21-21)
  • i (498-498)
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.js (1)
  • parser (287-287)
packages/bruno-app/src/utils/common/codemirror.js (2)
packages/bruno-app/src/components/ResponsePane/QueryResult/index.js (1)
  • contentType (56-56)
packages/bruno-app/src/utils/common/index.js (1)
  • contentType (94-94)
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.js (3)
packages/bruno-app/src/utils/common/index.js (3)
  • parsed (320-320)
  • i (21-21)
  • i (498-498)
packages/bruno-app/src/components/ErrorAlert/index.js (1)
  • ErrorAlert (5-23)
packages/bruno-app/src/utils/response/index.js (2)
  • parser (156-156)
  • i (79-79)
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js (3)
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/HtmlPreview.js (1)
  • HtmlPreview (5-39)
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/JsonPreview.js (1)
  • JsonPreview (5-61)
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.js (1)
  • XmlPreview (5-68)
🔇 Additional comments (30)
packages/bruno-app/src/components/ResponsePane/QueryResult/StyledWrapper.js (1)

6-6: LGTM!

The row height increase to 1.75rem properly accommodates the new response format selector dropdown, maintaining adequate vertical space for the enhanced preview UI.

tests/response/large-response-crash-prevention.spec.ts (1)

41-41: LGTM!

Good addition of exact: true - prevents false matches with other buttons like "View Raw" that might contain "View" in the name.

tests/response/response-format-select-and-preview/fixtures/collection/request-html.bru (1)

1-23: LGTM!

Fixture correctly defines an HTML echo request for testing the HTML preview functionality. The timeout: 0 (no timeout) is acceptable for test fixtures where external service latency may vary.

Note: This test depends on httpfaker.org - ensure this external service is reliable for CI/CD pipelines.

tests/response/response-format-select-and-preview/init-user-data/preferences.json (1)

1-6: LGTM!

Properly structured test initialization data with the {{projectRoot}} placeholder for portable collection path resolution.

packages/bruno-app/src/utils/common/index.js (3)

7-8: LGTM on prettier integration.

Using prettier/standalone with parser-babel is the correct approach for browser/Electron environments where the full prettier package isn't available.


106-117: LGTM on JavaScript content-type detection.

The pattern correctly matches common JavaScript MIME types (application/javascript, text/javascript, application/ecmascript, text/ecmascript).


494-511: LGTM on hex view formatting.

Clean implementation with proper offset display, hex bytes, and ASCII representation. The 16-byte width is standard for hex dumps.

tests/response/response-format-select-and-preview/init-user-data/collection-security.json (1)

1-10: LGTM!

The test configuration is correctly structured with appropriate sandbox settings for testing response format features.

packages/bruno-app/src/components/ButtonDropdown/StyledWrapper.js (1)

1-9: LGTM!

Clean styled component wrapper with appropriate SVG color inheritance for the caret icon.

tests/response/response-format-select-and-preview/fixtures/collection/request-json.bru (1)

1-17: LGTM!

Well-formed Bruno request fixture using the echo endpoint to test JSON response handling.

packages/bruno-app/src/utils/common/codemirror.js (1)

106-107: LGTM!

Correctly adds JavaScript content-type detection following the established pattern. The check for both 'javascript' and 'ecmascript' ensures comprehensive coverage of JS MIME types.

tests/utils/page/locators.ts (1)

54-64: LGTM!

Well-structured locator additions that follow the existing patterns and conventions. The use of both test IDs and CSS selectors is appropriate for the different element types.

packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/HtmlPreview.js (1)

5-18: LGTM on the HTML preview logic.

The webview injection with base URL and the use of escapeHtml for sanitization is well implemented. The dual validation using isValidHtml and isValidHtmlSnippet properly handles both full HTML documents and snippets.

tests/response/response-format-select-and-preview/response-format-select-and-preview.spec.ts (3)

1-16: Well-structured test suite following Playwright best practices.

Good use of test.step for report readability, locator variables for maintainability, and multiple assertions per step. The serial execution and cleanup in afterAll is appropriate for this stateful UI flow.


18-88: Comprehensive JSON response format coverage.

The test covers all format options (JSON, HTML, XML, JavaScript, Raw, Hex, Base64) with both editor and preview verification. The error state assertions (e.g., "Cannot preview as XML" for JSON data) properly validate fallback behavior.


90-160: Thorough HTML response format test.

Validates the webview visibility for HTML preview and error states for incompatible formats (e.g., "Cannot preview as JSON"). The Hex and Base64 content assertions provide good regression coverage. Ensure fixture files exist in the expected location at tests/response/response-format-select-and-preview/fixtures and verify the test follows all Playwright best practices including proper use of test.step, locator variables, and absence of page.waitForTimeout(), page.pause(), or test.only.

packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/VideoPreview.js (1)

8-15: Solid Blob URL lifecycle management.

Proper cleanup via URL.revokeObjectURL in the useEffect return prevents memory leaks. The dependency array correctly includes both contentType and dataBuffer.

packages/bruno-app/src/components/ErrorAlert/StyledWrapper.js (1)

28-41: Clean error styling with theme awareness.

The error-title and error-message styles appropriately use theme tokens for colors and font sizing.

tests/utils/page/actions.ts (2)

136-144: Clean implementation of openRequest helper.

Properly scopes the request locator within the collection context.


152-163: Well-designed sendRequestAndWaitForResponse with configurable options.

The default timeout of 15000ms and options object pattern is clean. Good use of test.step for reporting.

packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.js (1)

282-362: XML parsing implementation is solid.

The parseXMLString function handles attributes, text nodes, and repeated elements correctly. Error detection via parsererror check is appropriate.

packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultTypeSelector/index.jsx (1)

6-39: Clean component structure with good UX patterns.

The ToggleSwitch header with conditional title and the IconEye suffix for preview mode provide clear visual feedback. Props are well-named.

Verify the "active" class on line 35 is actually styled, as it may be unused:

className="active mr-[2px]"

Search for .active class definitions in CSS/SCSS files in the ResponsePane and ButtonDropdown component directories.

packages/bruno-app/src/utils/response/index.js (2)

1-59: LGTM!

Clean rule-based MIME type matching with sensible fallback. The pattern is extensible for future content types.


61-70: LGTM!

Standard HTML entity escaping implementation - covers the essential characters for XSS prevention.

packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js (2)

64-80: LGTM!

Clean separation of the editor rendering path with proper prop forwarding.


121-132: LGTM!

Good fallback UX for unsupported content types instead of failing silently.

packages/bruno-app/src/components/ResponsePane/QueryResult/index.js (4)

14-32: LGTM!

Well-structured format options constant with appropriate CodeMirror modes.


48-56: LGTM!

Proper error handling for buffer conversion with fallback to null.


66-86: LGTM!

Sensible restriction of format options for binary content types.


213-227: LGTM!

Clean integration of the new preview system with proper prop forwarding to QueryResultPreview.

Comment on lines +99 to +133
const ButtonIcon = forwardRef((iconProps, ref) => {
return (
<button
ref={ref}
className={classnames('flex items-center gap-1.5 text-xs',
'cursor-pointer select-none',
'h-7 rounded-[6px] border px-2 transition-colors',
// Text color
'text-gray-700 dark:text-gray-300',
// Border color
'border-gray-300 dark:border-[#343434]',
// Background color
// Hover background color
'hover:bg-gray-200 dark:hover:bg-[#303030]',
{
// Disabled styles
'opacity-50 cursor-not-allowed': disabled
},
className)}
data-testid={props['data-testid']}
style={style}
role="button"
{...iconProps}
>
{prefix && (
<span>{prefix}</span>
)}
<span className="active">{selectedLabel}</span>
{suffix && (
<span>{suffix}</span>
)}
<IconCaretDown className="caret ml-1" size={14} strokeWidth={2} />
</button>
);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Move ButtonIcon outside the component or memoize it.

Defining a forwardRef component inside the render function causes React to recreate it on every render, losing internal state and causing unnecessary DOM updates.

+const ButtonIcon = forwardRef(({ disabled, className, style, prefix, selectedLabel, suffix, ...props }, ref) => {
+  return (
+    <button
+      ref={ref}
+      className={classnames('flex items-center gap-1.5 text-xs',
+        'cursor-pointer select-none',
+        'h-7 rounded-[6px] border px-2 transition-colors',
+        'text-gray-700 dark:text-gray-300',
+        'border-gray-300 dark:border-[#343434]',
+        'hover:bg-gray-200 dark:hover:bg-[#303030]',
+        { 'opacity-50 cursor-not-allowed': disabled },
+        className)}
+      data-testid={props['data-testid']}
+      style={style}
+      role="button"
+      {...props}
+    >
+      {prefix && <span>{prefix}</span>}
+      <span className="active">{selectedLabel}</span>
+      {suffix && <span>{suffix}</span>}
+      <IconCaretDown className="caret ml-1" size={14} strokeWidth={2} />
+    </button>
+  );
+});
+ButtonIcon.displayName = 'ButtonIcon';
+
 const ButtonDropdown = ({ ... }) => {
   // ...
-  const ButtonIcon = forwardRef((iconProps, ref) => { ... });
-  ButtonIcon.displayName = 'ButtonIcon';

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/bruno-app/src/components/ButtonDropdown/index.jsx around lines 99 to
133, ButtonIcon is defined inline with forwardRef inside the render which causes
it to be recreated on every render; move the forwardRef component definition out
of the parent component (to module scope) or memoize it with React.memo so it is
stable between renders, ensure it receives needed props (disabled, className,
style, prefix, suffix, selectedLabel, props/data-testid) via parameters rather
than closing over local variables, and update any refs/prop forwarding
accordingly so behavior and styling remain identical.

Comment on lines +101 to +121
<button
ref={ref}
className={classnames('flex items-center gap-1.5 text-xs',
'cursor-pointer select-none',
'h-7 rounded-[6px] border px-2 transition-colors',
// Text color
'text-gray-700 dark:text-gray-300',
// Border color
'border-gray-300 dark:border-[#343434]',
// Background color
// Hover background color
'hover:bg-gray-200 dark:hover:bg-[#303030]',
{
// Disabled styles
'opacity-50 cursor-not-allowed': disabled
},
className)}
data-testid={props['data-testid']}
style={style}
role="button"
{...iconProps}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Add disabled attribute to the button for accessibility.

The button has visual disabled styling but lacks the actual disabled attribute, which means keyboard/screen reader users can still interact with it.

       <button
         ref={ref}
         className={classnames(...)}
         data-testid={props['data-testid']}
         style={style}
         role="button"
+        disabled={disabled}
         {...iconProps}
       >
🤖 Prompt for AI Agents
In packages/bruno-app/src/components/ButtonDropdown/index.jsx around lines
101-121, the <button> uses visual disabled styles but lacks the actual disabled
attribute so assistive tech and keyboard users can still interact; update the
element to include disabled={disabled} and also set tabIndex={disabled ? -1 :
undefined} (and optionally aria-disabled={disabled}) so the button is
non-interactive to screen readers and keyboard when disabled while preserving
semantics.

Comment on lines +24 to +25
} else if (typeof data === 'object') {
displayContent = JSON.stringify(data, null);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Missing indentation argument in JSON.stringify.

The comment states "render safely as formatted text", but objects won't be prettified without the third argument.

-  } else if (typeof data === 'object') {
-    displayContent = JSON.stringify(data, null);
+  } else if (typeof data === 'object') {
+    displayContent = JSON.stringify(data, null, 2);
📝 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
} else if (typeof data === 'object') {
displayContent = JSON.stringify(data, null);
} else if (typeof data === 'object') {
displayContent = JSON.stringify(data, null, 2);
🤖 Prompt for AI Agents
In
packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/HtmlPreview.js
around lines 24-25, the code uses JSON.stringify(data, null) which omits the
indentation argument so objects are not prettified; update the call to include a
spacing argument (for example JSON.stringify(data, null, 2)) so the object is
rendered as formatted text and remains safe for display.

Comment on lines +154 to +168
try {
// Parse with DOMParser
const parser = new DOMParser();
const doc = parser.parseFromString(trimmed, 'text/html');

// Check for parsing errors
const parseError = doc.querySelector('parsererror');
if (parseError) {
return false;
}

return true;
} catch (error) {
return false;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

DOMParser with 'text/html' never produces parsererror.

The HTML parser is lenient and won't generate a parsererror element - that behavior is specific to XML parsing. The try-catch and parsererror check are effectively dead code here. Consider removing them or clarifying the intent.

   try {
-    // Parse with DOMParser
     const parser = new DOMParser();
     const doc = parser.parseFromString(trimmed, 'text/html');
-
-    // Check for parsing errors
-    const parseError = doc.querySelector('parsererror');
-    if (parseError) {
-      return false;
-    }
-
+    // HTML parser is lenient; if we reach here with valid tags, consider it valid
     return true;
   } catch (error) {
     return false;
   }
🤖 Prompt for AI Agents
In packages/bruno-app/src/utils/response/index.js around lines 154-168, the
DOMParser parseFromString(..., 'text/html') branch will never produce a
'parsererror' node and the try-catch/parseError check is therefore dead; remove
the parsererror check and unnecessary try-catch, and either (a) simply return
true after parsing since the HTML parser is lenient, or (b) if strict validation
is required, switch to parsing as XML (e.g., 'application/xml') and
handle/document parseError reliably or use a proper HTML validation library
(htmlparser2/validator) to check for well-formedness — implement one of these
fixes and update comments accordingly.

Comment on lines +191 to +202
/**
* Switch to the editor tab
* @param page - The page object
*/
const switchToEditorTab = async (page: Page) => {
await test.step('Switch to editor tab', async () => {
const responseFormatTab = page.getByTestId('format-response-tab');
await responseFormatTab.click();
const previewTab = page.getByTestId('preview-response-tab');
await previewTab.click();
});
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Copy-paste bug: switchToEditorTab is identical to switchToPreviewTab.

Both functions click the same preview-response-tab toggle. While this might accidentally work (toggling the switch), the implementation is misleading. If the preview is already off, switchToEditorTab would incorrectly turn it on.

 const switchToEditorTab = async (page: Page) => {
   await test.step('Switch to editor tab', async () => {
     const responseFormatTab = page.getByTestId('format-response-tab');
     await responseFormatTab.click();
     const previewTab = page.getByTestId('preview-response-tab');
-    await previewTab.click();
+    // Only toggle off if preview is currently on
+    const isPreviewOn = await previewTab.isChecked();
+    if (isPreviewOn) {
+      await previewTab.click();
+    }
   });
 };

Alternatively, if the toggle state is managed differently, verify the intended behavior matches the implementation.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In tests/utils/page/actions.ts around lines 191 to 202, the switchToEditorTab
function mistakenly clicks the preview tab (copy-paste from switchToPreviewTab);
change the second click to the editor tab test id (e.g., 'editor-response-tab')
so it explicitly selects the editor view, and verify the test-id name matches
the app implementation; keep the outer test.step and await calls intact.

@@ -0,0 +1,159 @@
import React, { useRef, forwardRef } from 'react';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please move generic components to ui folder

'cursor-pointer select-none',
'h-7 rounded-[6px] border px-2 transition-colors',
// Text color
'text-gray-700 dark:text-gray-300',

@helloanoop helloanoop Dec 2, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No tailwind class colors please

border-top: 1px solid transparent;
border-right: 1px solid transparent;
border-bottom: 1px solid transparent;
border-radius: 0.375rem;