Repository navigation
feat: add response data type selector in response viewer - #6100
Conversation
b7fba59 to
01624b2
Compare
dc5bcea to
d079708
Compare
WalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 12
🧹 Nitpick comments (18)
tests/response/large-response-crash-prevention.spec.ts (1)
14-42: Consider addingtest.stepfor better report readability.Per coding guidelines, wrapping logical sections (create collection, create request, send request, verify warning) in
test.stepwould 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, andtext/rawmodes: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
functionkeyword 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
memobut lacks adisplayName, 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
validateJsonDatahelper 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
displayNamewill 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.stringifywill throw ifmessagecontains 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 aclassNameprop 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: MoveisValidTreeDataoutside 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.
hasArrayValueandarrayLengthare 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: UnuseddropdownTippyRef- 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 inlininghandleOptionSelect.This wrapper only calls
onChangewithout 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
ftypbox can have sizes other than 0x18 or 0x20. Consider checking just for theftypsignature 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:useMemois 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: UnusedresponseEncodingin dependency array.
responseEncodingis listed as a dependency but not passed toformatResponse. Either remove from deps or pass it to the function if needed.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 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()notfunc ()
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.jspackages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/TextPreview.jstests/response/response-format-select-and-preview/response-format-select-and-preview.spec.tspackages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultTypeSelector/index.jsxpackages/bruno-app/src/components/ErrorAlert/index.jspackages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/JsonPreview.jspackages/bruno-app/src/components/ButtonDropdown/index.jsxtests/utils/page/locators.tstests/response/large-response-crash-prevention.spec.tspackages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/VideoPreview.jspackages/bruno-app/src/utils/response/index.jspackages/bruno-app/src/utils/common/index.jspackages/bruno-app/src/utils/common/codemirror.jspackages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/HtmlPreview.jspackages/bruno-app/src/components/ResponsePane/QueryResult/StyledWrapper.jspackages/bruno-app/src/components/ResponsePane/QueryResult/index.jspackages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.jspackages/bruno-app/src/components/ErrorAlert/StyledWrapper.jspackages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.jstests/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 existingexpect()playwright callsAvoid using
page.pause()in codeUse locator variables for locators
Avoid using test.only
Use multiple assertions
Promote the use of
test.stepas much as possible so the generated reports are easier to readEnsure that the
fixtureslike the collections are nested inside thefixturesfolderFixture 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.jsontests/response/response-format-select-and-preview/response-format-select-and-preview.spec.tstests/response/response-format-select-and-preview/fixtures/collection/request-html.brutests/utils/page/locators.tstests/response/large-response-crash-prevention.spec.tstests/response/response-format-select-and-preview/fixtures/collection/bruno.jsontests/response/response-format-select-and-preview/init-user-data/preferences.jsontests/response/response-format-select-and-preview/fixtures/collection/request-json.brutests/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.jsxpackages/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/standalonewithparser-babelis 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
escapeHtmlfor sanitization is well implemented. The dual validation usingisValidHtmlandisValidHtmlSnippetproperly 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.stepfor report readability, locator variables for maintainability, and multiple assertions per step. The serial execution and cleanup inafterAllis 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/fixturesand verify the test follows all Playwright best practices including proper use oftest.step, locator variables, and absence ofpage.waitForTimeout(),page.pause(), ortest.only.packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/VideoPreview.js (1)
8-15: Solid Blob URL lifecycle management.Proper cleanup via
URL.revokeObjectURLin the useEffect return prevents memory leaks. The dependency array correctly includes bothcontentTypeanddataBuffer.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.stepfor reporting.packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/XmlPreview.js (1)
282-362: XML parsing implementation is solid.The
parseXMLStringfunction handles attributes, text nodes, and repeated elements correctly. Error detection viaparsererrorcheck 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
.activeclass 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.
| 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> | ||
| ); | ||
| }); |
There was a problem hiding this comment.
🛠️ 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.
| <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} |
There was a problem hiding this comment.
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.
| } else if (typeof data === 'object') { | ||
| displayContent = JSON.stringify(data, null); |
There was a problem hiding this comment.
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.
| } 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.
| 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; | ||
| } |
There was a problem hiding this comment.
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.
| /** | ||
| * 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(); | ||
| }); | ||
| }; |
There was a problem hiding this comment.
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'; | |||
There was a problem hiding this comment.
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', |
There was a problem hiding this comment.
No tailwind class colors please
| border-top: 1px solid transparent; | ||
| border-right: 1px solid transparent; | ||
| border-bottom: 1px solid transparent; | ||
| border-radius: 0.375rem; |
Description
Added Response Data Type selector with preview mode for each type. Closes #4963
JIRA
Contribution Checklist:
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
Tests
✏️ Tip: You can customize this high-level summary in your review settings.