Skip to content

Conversation

@iAmNsengi
Copy link
Contributor

@iAmNsengi iAmNsengi commented May 28, 2025

This PR adds the ability to load sample data presets for the Formatter, Compare, and Code Generator tabs, similar to the existing Mock Data Generator.

  • Created presets.js to store structured sample data for each tab type.
  • Modified index.html to include presets.js and add dropdown selectors in the UI for each relevant tab section.
  • Implemented JavaScript functions in index.js (populatePresetSelects, loadFormatterPreset, loadComparePreset, loadCodegenPreset) to populate the dropdowns and load selected preset data into the active tab.
  • Updated the existing loadMockPreset function to use the new global window.PRESETS structure and removed the old local presets object.
  • Added basic CSS styles for the new preset selectors.
  • Fixed issues where presets were not loading due to incorrect variable scope and the population function not being called on page load.

Screenshots

image

Fixes #40

Summary by CodeRabbit

  • New Features

    • Introduced preset dropdown selectors in the Formatter, Compare, and Code Generator sections, allowing users to quickly load example configurations.
    • Added a collection of built-in presets for formatting, comparing, code generation, and mock data generation.
  • Style

    • Enhanced the appearance of preset selectors with new interactive styling for better usability.
  • Refactor

    • Improved code formatting and consistency across the application for a cleaner user experience.

@coderabbitai
Copy link

coderabbitai bot commented May 28, 2025

Walkthrough

The changes introduce a preset management system for formatter, compare, and codegen tabs by adding preset dropdowns to the UI, corresponding event handlers, and a centralized presets.js file containing preset data. Supporting CSS styles and JavaScript functions for loading and populating these presets are also included.

Changes

Files Change Summary
index.css Added .preset-select class and hover/focus styles for preset dropdown elements.
index.html Added <select> preset dropdowns to formatter, compare, and codegen tab containers; included presets.js.
index.js Refactored code style; added functions to populate and load presets for each tab; integrated with UI events.
presets.js Introduced new file defining global window.PRESETS object with sample data for all tab types.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PresetDropdown as Preset Dropdown
    participant JS as JavaScript Functions
    participant PRESETS as window.PRESETS
    participant Tab as Active Tab

    User->>PresetDropdown: Selects a preset
    PresetDropdown->>JS: Triggers onchange event
    JS->>PRESETS: Retrieves selected preset data
    JS->>Tab: Loads preset data into active tab
Loading

Assessment against linked issues

Objective Addressed Explanation
Add presets/sample values as dropdowns for every tab and load on select (#40)

Possibly related PRs

Poem

A dropdown of wonders, oh what a delight!
Presets for tabs, now just click to ignite.
Formatter, compare, and codegen in sync,
With sample-filled magic, much faster than you think.
The rabbit hops on, with a joyful cheer—
Presets for all, the best update this year!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@iAmNsengi
Copy link
Contributor Author

iAmNsengi commented May 28, 2025

Hello @Shravan20
There is a small issue with the biome formatter, when I ran a git commit changing the index.js it made a lot of whitespace changes and code formatting leading to a big diff on GitHub changes.

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: 7

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

1769-1796: Add null safety to populatePresetSelects function.

The function assumes window.PRESETS and its properties exist, which could cause errors if the presets.js file fails to load.

Add defensive checks:

 function populatePresetSelects() {
+  if (!window.PRESETS) {
+    console.error("Presets not loaded");
+    return;
+  }
+
   // Populate formatter presets
   const formatterSelect = document.querySelector("#formatter-tabs-container .preset-select");
-  Object.keys(window.PRESETS.formatter).forEach((key) => {
+  if (formatterSelect && window.PRESETS.formatter) {
+    Object.keys(window.PRESETS.formatter).forEach((key) => {
       const option = document.createElement("option");
       option.value = key;
       option.textContent = window.PRESETS.formatter[key].name;
       formatterSelect.appendChild(option);
     });
+  }

   // Populate compare presets
   const compareSelect = document.querySelector("#compare-tabs-container .preset-select");
-  Object.keys(window.PRESETS.compare).forEach((key) => {
+  if (compareSelect && window.PRESETS.compare) {
+    Object.keys(window.PRESETS.compare).forEach((key) => {
       const option = document.createElement("option");
       option.value = key;
       option.textContent = window.PRESETS.compare[key].name;
       compareSelect.appendChild(option);
     });
+  }

   // Populate codegen presets
   const codegenSelect = document.querySelector("#codegen-tabs-container .preset-select");
-  Object.keys(window.PRESETS.codegen).forEach((key) => {
+  if (codegenSelect && window.PRESETS.codegen) {
+    Object.keys(window.PRESETS.codegen).forEach((key) => {
       const option = document.createElement("option");
       option.value = key;
       option.textContent = window.PRESETS.codegen[key].name;
       codegenSelect.appendChild(option);
     });
+  }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b7450d5 and afbea65.

📒 Files selected for processing (4)
  • index.css (1 hunks)
  • index.html (4 hunks)
  • index.js (49 hunks)
  • presets.js (1 hunks)

Comment on lines +1201 to +1221
.preset-select {
margin-left: 10px;
padding: 5px 10px;
border: 1px solid var(--border-color);
border-radius: 4px;
background-color: var(--bg-color);
color: var(--text-color);
font-size: 14px;
cursor: pointer;
transition: border-color 0.2s;
}

.preset-select:hover {
border-color: var(--primary-color);
}

.preset-select:focus {
outline: none;
border-color: var(--primary-color);
box-shadow: 0 0 0 2px var(--primary-color-light);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

CSS variables are undefined and may cause styling issues.

The .preset-select class uses CSS variables (--border-color, --bg-color, --text-color, --primary-color, --primary-color-light) that are not defined anywhere in the CSS file. This will cause the styles to fall back to browser defaults.

Additionally, this introduces inconsistency as the rest of the CSS file uses hardcoded color values (e.g., #007bff for primary color).

Consider either:

  1. Define the CSS variables at the root level:
+:root {
+  --border-color: #ccc;
+  --bg-color: #ffffff;
+  --text-color: #333;
+  --primary-color: #007bff;
+  --primary-color-light: rgba(0, 123, 255, 0.2);
+}
+
+body.dark-mode {
+  --border-color: #555;
+  --bg-color: #2e2e2e;
+  --text-color: #e0e0e0;
+}
+
 .preset-select {
   margin-left: 10px;
   padding: 5px 10px;
  1. Or use hardcoded values consistent with the rest of the file:
 .preset-select {
   margin-left: 10px;
   padding: 5px 10px;
-  border: 1px solid var(--border-color);
+  border: 1px solid #ccc;
   border-radius: 4px;
-  background-color: var(--bg-color);
-  color: var(--text-color);
+  background-color: #ffffff;
+  color: #333;
   font-size: 14px;
   cursor: pointer;
   transition: border-color 0.2s;
 }
 
 .preset-select:hover {
-  border-color: var(--primary-color);
+  border-color: #007bff;
 }
 
 .preset-select:focus {
   outline: none;
-  border-color: var(--primary-color);
-  box-shadow: 0 0 0 2px var(--primary-color-light);
+  border-color: #007bff;
+  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
 }
🤖 Prompt for AI Agents
In index.css around lines 1201 to 1221, the CSS variables used in the
.preset-select class are not defined, causing fallback to browser defaults and
inconsistency with the rest of the file. Fix this by either defining these
variables (e.g., --border-color, --bg-color, --text-color, --primary-color,
--primary-color-light) at the :root selector with appropriate color values or
replace the variables in the .preset-select styles with the hardcoded color
values used elsewhere in the CSS to maintain consistency.

Comment on lines +103 to +105
<select onchange="loadFormatterPreset(this.value)" class="preset-select">
<option value="">-- Load Preset --</option>
</select>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add accessibility attributes to preset select elements.

The preset select elements lack accessibility attributes, which makes it difficult for screen reader users to understand their purpose.

Add aria-label attributes to improve accessibility:

-<select onchange="loadFormatterPreset(this.value)" class="preset-select">
+<select onchange="loadFormatterPreset(this.value)" class="preset-select" aria-label="Load formatter preset">
   <option value="">-- Load Preset --</option>
 </select>
-<select onchange="loadComparePreset(this.value)" class="preset-select">
+<select onchange="loadComparePreset(this.value)" class="preset-select" aria-label="Load compare preset">
   <option value="">-- Load Preset --</option>
 </select>
-<select onchange="loadCodegenPreset(this.value)" class="preset-select">
+<select onchange="loadCodegenPreset(this.value)" class="preset-select" aria-label="Load code generator preset">
   <option value="">-- Load Preset --</option>
 </select>

Also applies to: 118-120, 133-135

🤖 Prompt for AI Agents
In index.html at lines 103-105, 118-120, and 133-135, the preset select elements
lack accessibility attributes, specifically aria-labels, which are necessary for
screen readers to convey their purpose. Add appropriate aria-label attributes to
each select element to describe their function clearly for assistive
technologies.

name: "Sample JSON",
content: JSON.stringify(
{
name: "Eliezer Nsengi",
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace personal information with generic sample data.

The sample JSON contains what appears to be a real person's name. For privacy and professional reasons, sample data should use clearly fictional names.

Replace with generic sample data:

-          name: "Eliezer Nsengi",
+          name: "John Doe",
📝 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
name: "Eliezer Nsengi",
name: "John Doe",
🤖 Prompt for AI Agents
In presets.js at line 8, replace the personal name "Eliezer Nsengi" with a
generic, clearly fictional name to avoid using real personal information in
sample data. Choose a common placeholder name like "John Doe" or "Jane Smith" to
maintain professionalism and privacy.

Comment on lines +98 to +119
id: "{{datatype.uuid}}",
name: "{{name.fullName}}",
email: "{{internet.email}}",
age: "{{datatype.number({'min': 18, 'max': 65})}}",
address: {
street: "{{address.streetAddress}}",
city: "{{address.city}}",
country: "{{address.country}}",
},
isActive: "{{datatype.boolean}}",
},
},
Product: {
name: "Product",
schema: {
id: "{{datatype.uuid}}",
name: "{{commerce.productName}}",
price: "{{commerce.price}}",
description: "{{commerce.productDescription}}",
inStock: "{{datatype.boolean}}",
categories: "{{commerce.department}}",
},
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify faker.js template syntax parsing.

The mockgen presets use faker.js template syntax (e.g., {{datatype.uuid}}).

Ensure that the mockFromSchema function in index.js correctly handles this template syntax. Run this script to verify the implementation:


🏁 Script executed:

#!/bin/bash
# Description: Verify that mockFromSchema function properly handles the faker.js template syntax

# Search for the mockFromSchema function implementation
ast-grep --pattern 'function mockFromSchema($_) {
  $$$
}'

# Also check for any regex patterns that parse the template syntax
rg -A 5 '{{.*}}' --type js

Length of output: 1107


🏁 Script executed:

#!/bin/bash
# Locate and inspect resolveFakerPath implementation in index.js
rg -n "function resolveFakerPath" -n index.js
rg -A 10 -n "function resolveFakerPath" -n index.js

# Look for any regex that strips or parses '{{...}}' in index.js
rg -n '\\{\\{[^}]*\\}\\}' -n index.js

Length of output: 746


Handle faker.js template syntax in mockFromSchema

The current implementation in mockFromSchema passes raw strings like "{{datatype.uuid}}" directly to resolveFakerPath, causing an invalid-path error. We need to strip the double-brace syntax before resolution.

• Location: index.js in mockFromSchema, around lines 1210–1217
• Add a regex match for {{…}} and extract the inner path

Suggested diff:

   if (typeof schema === "string") {
     if (schema === "boolean") return Math.random() < 0.5;
     if (schema.startsWith("number|")) {
       const [min, max] = schema.split("|")[1].split("-").map(Number);
       return faker.number.int({ min, max });
     }
-    // currently fails on "{{datatype.uuid}}"
-    return resolveFakerPath(schema);
+    // Handle faker.js template syntax {{path.to.method}}
+    const templateMatch = schema.match(/^{{\s*([\w.]+)\s*}}$/);
+    if (templateMatch) {
+      return resolveFakerPath(templateMatch[1]);
+    }
+    return resolveFakerPath(schema);
   }

This ensures "{{datatype.uuid}}" is correctly resolved to faker.datatype.uuid().

📝 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
id: "{{datatype.uuid}}",
name: "{{name.fullName}}",
email: "{{internet.email}}",
age: "{{datatype.number({'min': 18, 'max': 65})}}",
address: {
street: "{{address.streetAddress}}",
city: "{{address.city}}",
country: "{{address.country}}",
},
isActive: "{{datatype.boolean}}",
},
},
Product: {
name: "Product",
schema: {
id: "{{datatype.uuid}}",
name: "{{commerce.productName}}",
price: "{{commerce.price}}",
description: "{{commerce.productDescription}}",
inStock: "{{datatype.boolean}}",
categories: "{{commerce.department}}",
},
// In index.js, inside mockFromSchema around where you handle string schemas:
if (typeof schema === "string") {
if (schema === "boolean") return Math.random() < 0.5;
if (schema.startsWith("number|")) {
const [min, max] = schema.split("|")[1].split("-").map(Number);
return faker.number.int({ min, max });
}
// Handle faker.js template syntax {{path.to.method}}
const templateMatch = schema.match(/^{{\s*([\w.]+)\s*}}$/);
if (templateMatch) {
return resolveFakerPath(templateMatch[1]);
}
return resolveFakerPath(schema);
}
🤖 Prompt for AI Agents
In index.js around lines 1210 to 1217, the mockFromSchema function currently
passes faker template strings like "{{datatype.uuid}}" directly to
resolveFakerPath, causing invalid path errors. To fix this, update
mockFromSchema to detect strings matching the "{{...}}" pattern, extract the
inner content using a regex, and pass only that inner path (e.g.,
"datatype.uuid") to resolveFakerPath. This will allow correct resolution of
faker methods and proper mock data generation.

Comment on lines 1153 to 1163
function loadMockPreset(name) {
if (presets[name]) {
document.getElementById("mock-schema-input").value = JSON.stringify(
presets[name],
null,
2
);
if (!name) return;

const preset = window.PRESETS.mockgen[name];
if (!preset) return;

const schemaInput = document.getElementById('mock-schema-input');
if (schemaInput) {
schemaInput.value = JSON.stringify(preset.schema, null, 2);
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reset select element when no preset is selected.

The function returns early without resetting the select element value when no preset name is provided. This could leave the dropdown showing a previously selected preset name even though no preset is loaded.

Reset the select element value:

 function loadMockPreset(name) {
+  const selectElement = document.querySelector('#mockgen-section select[onchange*="loadMockPreset"]');
   if (!name) {
+    if (selectElement) selectElement.value = "";
     return;
   }
   
   const preset = window.PRESETS.mockgen[name];
-  if (!preset) return;
+  if (!preset) {
+    if (selectElement) selectElement.value = "";
+    return;
+  }

   const schemaInput = document.getElementById('mock-schema-input');
   if (schemaInput) {
     schemaInput.value = JSON.stringify(preset.schema, 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
function loadMockPreset(name) {
if (presets[name]) {
document.getElementById("mock-schema-input").value = JSON.stringify(
presets[name],
null,
2
);
if (!name) return;
const preset = window.PRESETS.mockgen[name];
if (!preset) return;
const schemaInput = document.getElementById('mock-schema-input');
if (schemaInput) {
schemaInput.value = JSON.stringify(preset.schema, null, 2);
}
}
function loadMockPreset(name) {
const selectElement = document.querySelector(
'#mockgen-section select[onchange*="loadMockPreset"]'
);
if (!name) {
if (selectElement) selectElement.value = "";
return;
}
const preset = window.PRESETS.mockgen[name];
if (!preset) {
if (selectElement) selectElement.value = "";
return;
}
const schemaInput = document.getElementById('mock-schema-input');
if (schemaInput) {
schemaInput.value = JSON.stringify(preset.schema, null, 2);
}
}
🤖 Prompt for AI Agents
In index.js around lines 1153 to 1163, the function loadMockPreset returns early
when no preset name is provided but does not reset the select element value,
causing the dropdown to show an outdated selection. To fix this, add code to
reset the select element's value to an empty string or default option before
returning when the name is falsy, ensuring the dropdown reflects that no preset
is selected.

Comment on lines +1758 to +1761
btn.classList.remove("drag-over");

if (draggedBtn && draggedBtn !== button) {
container.insertBefore(draggedBtn, button);
if (draggedBtn && draggedBtn !== btn) {
container.insertBefore(draggedBtn, btn);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix undefined variable error in tab reordering.

The code uses an undefined variable btn instead of button, which will cause a runtime error.

Apply this fix:

-      btn.classList.remove("drag-over");
+      button.classList.remove("drag-over");

-      if (draggedBtn && draggedBtn !== btn) {
-        container.insertBefore(draggedBtn, btn);
+      if (draggedBtn && draggedBtn !== button) {
+        container.insertBefore(draggedBtn, button);
         saveGlobalState();
       }
📝 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
btn.classList.remove("drag-over");
if (draggedBtn && draggedBtn !== button) {
container.insertBefore(draggedBtn, button);
if (draggedBtn && draggedBtn !== btn) {
container.insertBefore(draggedBtn, btn);
button.classList.remove("drag-over");
if (draggedBtn && draggedBtn !== button) {
container.insertBefore(draggedBtn, button);
saveGlobalState();
}
🤖 Prompt for AI Agents
In index.js around lines 1758 to 1761, the variable `btn` is used but not
defined, causing a runtime error. Replace all instances of `btn` with the
correctly defined variable `button` to fix the undefined variable error in the
tab reordering logic.

Comment on lines +1798 to +1850
function loadFormatterPreset(presetName) {
if (!presetName) return;

const preset = window.PRESETS.formatter[presetName];
if (!preset) return;

const activeTab = document.querySelector("#formatter-tab-contents .json-tab-content.active");
if (!activeTab) return;

const textarea = activeTab.querySelector(".json-input");
if (textarea) {
textarea.value = preset.content;
updateFormatterPreview(activeTab.id);
}
}

function loadComparePreset(presetName) {
if (!presetName) return;

const preset = window.PRESETS.compare[presetName];
if (!preset) return;

const activeTab = document.querySelector("#compare-tab-contents .json-tab-content.active");
if (!activeTab) return;

const leftTextarea = activeTab.querySelector(".json-input-left");
const rightTextarea = activeTab.querySelector(".json-input-right");

if (leftTextarea && rightTextarea) {
leftTextarea.value = preset.leftContent;
rightTextarea.value = preset.rightContent;
compareJSONs(activeTab.id);
}
}

function loadCodegenPreset(presetName) {
if (!presetName) return;

const preset = window.PRESETS.codegen[presetName];
if (!preset) return;

const activeTab = document.querySelector("#codegen-tab-contents .json-tab-content.active");
if (!activeTab) return;

const textarea = activeTab.querySelector(".json-input");
const langSelect = document.getElementById("lang-select-" + activeTab.id);

if (textarea && langSelect) {
textarea.value = preset.input;
langSelect.value = preset.lang;
generateCode(activeTab.id);
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling to preset loading functions.

The preset loading functions don't handle cases where preset data might be malformed or missing expected properties.

Add try-catch blocks and validation:

 function loadFormatterPreset(presetName) {
   if (!presetName) return;

   const preset = window.PRESETS.formatter[presetName];
   if (!preset) return;

   const activeTab = document.querySelector("#formatter-tab-contents .json-tab-content.active");
   if (!activeTab) return;

   const textarea = activeTab.querySelector(".json-input");
   if (textarea) {
+    try {
+      // Validate that content is valid JSON
+      JSON.parse(preset.content);
       textarea.value = preset.content;
       updateFormatterPreview(activeTab.id);
+    } catch (error) {
+      console.error("Invalid preset content:", error);
+      Swal.fire({
+        icon: "error",
+        title: "Invalid preset",
+        text: "The selected preset contains invalid JSON",
+        toast: true,
+        timer: 3000,
+        position: "top-end"
+      });
+    }
   }
 }

Apply similar error handling to loadComparePreset and loadCodegenPreset functions.

📝 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
function loadFormatterPreset(presetName) {
if (!presetName) return;
const preset = window.PRESETS.formatter[presetName];
if (!preset) return;
const activeTab = document.querySelector("#formatter-tab-contents .json-tab-content.active");
if (!activeTab) return;
const textarea = activeTab.querySelector(".json-input");
if (textarea) {
textarea.value = preset.content;
updateFormatterPreview(activeTab.id);
}
}
function loadComparePreset(presetName) {
if (!presetName) return;
const preset = window.PRESETS.compare[presetName];
if (!preset) return;
const activeTab = document.querySelector("#compare-tab-contents .json-tab-content.active");
if (!activeTab) return;
const leftTextarea = activeTab.querySelector(".json-input-left");
const rightTextarea = activeTab.querySelector(".json-input-right");
if (leftTextarea && rightTextarea) {
leftTextarea.value = preset.leftContent;
rightTextarea.value = preset.rightContent;
compareJSONs(activeTab.id);
}
}
function loadCodegenPreset(presetName) {
if (!presetName) return;
const preset = window.PRESETS.codegen[presetName];
if (!preset) return;
const activeTab = document.querySelector("#codegen-tab-contents .json-tab-content.active");
if (!activeTab) return;
const textarea = activeTab.querySelector(".json-input");
const langSelect = document.getElementById("lang-select-" + activeTab.id);
if (textarea && langSelect) {
textarea.value = preset.input;
langSelect.value = preset.lang;
generateCode(activeTab.id);
}
}
function loadFormatterPreset(presetName) {
if (!presetName) return;
const preset = window.PRESETS.formatter[presetName];
if (!preset) return;
const activeTab = document.querySelector("#formatter-tab-contents .json-tab-content.active");
if (!activeTab) return;
const textarea = activeTab.querySelector(".json-input");
if (textarea) {
try {
// Validate that content is valid JSON
JSON.parse(preset.content);
textarea.value = preset.content;
updateFormatterPreview(activeTab.id);
} catch (error) {
console.error("Invalid preset content:", error);
Swal.fire({
icon: "error",
title: "Invalid preset",
text: "The selected preset contains invalid JSON",
toast: true,
timer: 3000,
position: "top-end"
});
}
}
}
🤖 Prompt for AI Agents
In index.js around lines 1798 to 1850, the preset loading functions lack error
handling for malformed or incomplete preset data. Wrap the code inside each
function (loadFormatterPreset, loadComparePreset, loadCodegenPreset) in
try-catch blocks to catch any runtime errors. Additionally, validate that the
preset object contains the expected properties before accessing them, and handle
cases where properties are missing by logging an error or returning early. This
ensures robust handling of invalid preset data and prevents runtime exceptions.

@zhravan
Copy link
Owner

zhravan commented May 28, 2025

Hello @Shravan20
There is a small issue with the biome formatter, when I ran a git commit changing the index.js it made a lot of whitespace changes and code formatting leading to a big diff on GitHub changes.

Would you please create an issue and someone interested or myself will pick up the issue going ahead?

@iAmNsengi
Copy link
Contributor Author

Would you please create an issue and someone interested or myself will pick up the issue going ahead?

Hello @Shravan20 I think it's not a big deal; it's just that it created a lot of changes on my PR, and it is going to be very hard for you to detect the changes; hence, the index.js contains a lot of whitespace changes and code formatting.

@zhravan
Copy link
Owner

zhravan commented May 29, 2025

PR LGTM
Thank you so much for your contribution!! 🔥 Really appreciate your efforts into this project @iAmNsengi

Copy link
Owner

@zhravan zhravan left a comment

Choose a reason for hiding this comment

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

LGTM

@zhravan zhravan merged commit ff634c6 into zhravan:main May 29, 2025
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: add presets for all the tabs for reference

2 participants