Skip to content

Conversation

@BDFL669
Copy link
Contributor

@BDFL669 BDFL669 commented Apr 18, 2025

  • Implemented exportMockOutput function to generate mock data as .json or .csv
  • Utilized Blob and URL.createObjectURL to enable direct file downloads
  • Added "Export as JSON" and "Export as CSV" buttons to the UI

Summary by CodeRabbit

  • New Features
    • Added "Export as JSON" and "Export as CSV" buttons to the Mock Data Generator section.
    • Users can now directly export generated mock data as downloadable JSON or CSV files.
    • Introduced an optional filename input to customize the download file name.

@coderabbitai
Copy link

coderabbitai bot commented Apr 18, 2025

Walkthrough

This change introduces two new export buttons to the Mock Data Generator interface, allowing users to download generated mock data as either JSON or CSV files. The HTML is updated to include these buttons and a text input for an optional filename. New JavaScript functions handle file creation and download by serializing the data in the chosen format and triggering a file download with the appropriate file extension and MIME type. The logic verifies the presence and validity of the generated data before exporting. No changes are made to existing public APIs beyond adding these new functions.

Changes

File(s) Change Summary
index.html Added "Export as JSON" and "Export as CSV" buttons plus a filename input field to the Mock Data Generator section.
index.js Added downloadFile and exportMockOutput functions for exporting mock data as downloadable JSON or CSV files.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI
    participant JSLogic

    User->>UI: Clicks "Export as JSON" or "Export as CSV"
    UI->>JSLogic: Calls exportMockOutput(format)
    JSLogic->>JSLogic: Validate latestMockData
    alt Valid Data
        JSLogic->>JSLogic: Serialize data (JSON or CSV)
        JSLogic->>JSLogic: Call downloadFile(content, filename, type)
        JSLogic->>User: Triggers file download
    else Invalid Data
        JSLogic->>JSLogic: Log error, abort
    end
Loading

Possibly related PRs

  • feat: mock data generator #32: Implements the mock data generation UI and schema handling, which is directly extended by this PR to add export functionality for generated data.

Poem

Two shiny buttons, side by side,
Export your data with rabbit pride!
JSON or CSV, just one click away,
Download your mock dreams, hooray!
With blobs and anchors, files take flight—
The generator hops with new delight!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
index.js (1)

1189-1211: The export function handles data validation and different formats well.

The function properly validates that data exists before attempting to export, handles both JSON and CSV formats appropriately, and reuses the downloadFile utility. The special handling for single-item arrays in JSON export is a good user experience touch.

A small suggestion for improved error handling:

if (!Array.isArray(latestMockData) || latestMockData.length === 0) {
    console.error("No data available to export.");
+   alert("No data available to export. Please generate data first.");
    return;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d62acad and 3d5987d.

📒 Files selected for processing (2)
  • index.html (1 hunks)
  • index.js (1 hunks)
🔇 Additional comments (2)
index.js (1)

1177-1187: Well-implemented file download utility function.

This utility function implements the Blob API and URL.createObjectURL pattern correctly to facilitate browser downloads. Good job properly cleaning up resources with URL.revokeObjectURL.

index.html (1)

164-165: Good addition of export buttons that match the existing UI pattern.

The new export buttons are properly positioned alongside the existing copy buttons and follow the same naming convention and function call pattern. This maintains UI consistency and provides users with intuitive export functionality.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
index.js (2)

1196-1218: CSV generation could be improved for special characters.

The current CSV implementation uses JSON.stringify() on each value, which could cause issues with CSV formatting if the data contains commas, quotes, or newlines. A more robust CSV generation approach would be better.

 function exportMockOutput(format = "json") {
     if (!Array.isArray(latestMockData) || latestMockData.length === 0) {
         console.error("No data available to export.");
         return;
     }

     let content = "";
     let filename = userInputValue !== "" ? userInputValue : "mock_data"; // Use user input if available

     if (format === "json") {
         content = JSON.stringify(latestMockData.length === 1 ? latestMockData[0] : latestMockData, null, 2);
         filename += ".json";
         downloadFile(content, filename, "application/json");
     } else if (format === "csv") {
         if (!latestMockData.length || typeof latestMockData[0] !== "object") return;

         const keys = Object.keys(latestMockData[0]);
-        const rows = latestMockData.map(obj => keys.map(k => JSON.stringify(obj[k] ?? "")));
+        // Properly escape CSV values to handle commas, quotes, and newlines
+        const escapeCSV = (value) => {
+            if (value === null || value === undefined) return '';
+            const str = typeof value === 'object' ? JSON.stringify(value) : String(value);
+            if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
+                return `"${str.replace(/"/g, '""')}"`;
+            }
+            return str;
+        };
+        const rows = latestMockData.map(obj => keys.map(k => escapeCSV(obj[k])));
         content = [keys.join(","), ...rows.map(r => r.join(","))].join("\n");
         filename += ".csv";
         downloadFile(content, filename, "text/csv");
     }
 }

Also, you might want to add error handling for the download process and provide user feedback if the export fails.


1196-1209: Consider validating the filename before download.

The function uses the raw user input for the filename which could potentially contain invalid characters for filenames. Adding validation or sanitization would be beneficial.

 function exportMockOutput(format = "json") {
     if (!Array.isArray(latestMockData) || latestMockData.length === 0) {
         console.error("No data available to export.");
         return;
     }

     let content = "";
-    let filename = userInputValue !== "" ? userInputValue : "mock_data"; // Use user input if available
+    // Sanitize filename to remove invalid characters
+    let filename = userInputValue !== "" ? userInputValue.replace(/[^\w\-\.]/g, '_') : "mock_data"; // Use user input if available

     if (format === "json") {
         content = JSON.stringify(latestMockData.length === 1 ? latestMockData[0] : latestMockData, null, 2);
         filename += ".json";
         downloadFile(content, filename, "application/json");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d5987d and 13bdb78.

📒 Files selected for processing (2)
  • index.html (1 hunks)
  • index.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • index.html
🔇 Additional comments (1)
index.js (1)

1177-1187: Good implementation of file download functionality.

The function creates a Blob, generates a temporary URL, triggers a download via a dynamically created anchor element, and properly cleans up resources by removing the element and revoking the URL.

Comment on lines +1189 to +1194
let userInputValue = ""; // This variable will store filename input from user using the following event listener:

document.getElementById("userInput").addEventListener("input", function (e) {
userInputValue = e.target.value;
//console.log("Saved input:", userInputValue); // Optional: see it live
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling for the missing DOM element.

The event listener assumes that the element with id "userInput" exists in the DOM, but there's no defensive check for this. If the element doesn't exist when this code runs, it will throw an error.

-  document.getElementById("userInput").addEventListener("input", function (e) {
+  const userInputElement = document.getElementById("userInput");
+  if (userInputElement) {
+    userInputElement.addEventListener("input", function (e) {
       userInputValue = e.target.value;
       //console.log("Saved input:", userInputValue); // Optional: see it live
-  });
+    });
+  }

Also, the commented console.log should be removed for production code.

📝 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
let userInputValue = ""; // This variable will store filename input from user using the following event listener:
document.getElementById("userInput").addEventListener("input", function (e) {
userInputValue = e.target.value;
//console.log("Saved input:", userInputValue); // Optional: see it live
});
let userInputValue = ""; // This variable will store filename input from user using the following event listener:
const userInputElement = document.getElementById("userInput");
if (userInputElement) {
userInputElement.addEventListener("input", function (e) {
userInputValue = e.target.value;
//console.log("Saved input:", userInputValue); // Optional: see it live
});
}

@zhravan zhravan linked an issue Apr 18, 2025 that may be closed by this pull request
@zhravan
Copy link
Owner

zhravan commented Apr 18, 2025

Nice work @BDFL669
Thank you so much for your contribution. Look forward for more active participation and contribution!!
Thank you for your time!! Really appreciate your efforts! <3 🔥

@zhravan
Copy link
Owner

zhravan commented Apr 18, 2025

Overall LGTM

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.

feat: export as csv and json in mock-data generator

2 participants