Skip to content

add json validation to file inputs in UI and minify before upload#5248

Merged
DedeHai merged 3 commits intowled:mainfrom
DedeHai:jsonValidation
Jan 30, 2026
Merged

add json validation to file inputs in UI and minify before upload#5248
DedeHai merged 3 commits intowled:mainfrom
DedeHai:jsonValidation

Conversation

@DedeHai
Copy link
Collaborator

@DedeHai DedeHai commented Dec 31, 2025

this prevents invalid files even making it to the file system.
also updated edit.htm to make use of that so even files uploaded through edit.htm benefit from this new functionality. While I was at it I also added sequential file loading in edit.htm like all other htm files already do.

Fixes #5246

Summary by CodeRabbit

  • New Features

    • Editor adds a queued request utility for smoother saves and loader behavior.
    • Uploads now accept a callback to refresh and reload the saved file after upload.
  • Bug Fixes

    • JSON uploads may be auto-minified/validated with an option to continue on parse error.
    • File-type detection and editor mode switching are now case-insensitive.
    • Improved empty-file handling and clearer success/error feedback; live JSON validation updates editor border.

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 31, 2025

Walkthrough

Adds JSON validation/minification to file uploads, changes uploadFile to accept a callback and early-exit when no file selected, and refactors the editor to use a queued requester, case-insensitive JSON detection, and the new upload flow that refreshes the file tree and reloads saved files.

Changes

Cohort / File(s) Summary
Upload utility
wled00/data/common.js
Changed uploadFile(fileObj, name)uploadFile(fileObj, name, callback). Early exit when no file selected (calls callback(false)). If filename matches JSON (/.json$/i) read/parse/minify text into a Blob; on parse error prompt user and optionally continue. Use processed file in FormData; invoke `callback(true
Editor, save & validation
wled00/data/edit.htm
Added QueuedRequester utility for queued AJAX with loader handling. Replaced .endsWith('.json') checks with case-insensitive /\.json$/i for mode, validation, and formatting. Switched JSON save/upload path to call uploadFile(..., callback) and on success refresh tree and reload saved file. Adjusted live JSON validation visuals and minor control-flow/syntactic tweaks.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

  • new file editor #4956 — Overlapping changes to the editor frontend and upload/save logic, including JSON validation/minification and upload API adjustments.

Suggested reviewers

  • netmindz
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main changes: adding JSON validation and minification to file inputs before upload.
Linked Issues check ✅ Passed The PR successfully addresses issue #5246 by implementing JSON validation to verify preset/config format before application, preventing invalid files and factory resets.
Out of Scope Changes check ✅ Passed All changes are directly scoped to JSON validation and minification: uploadFile signature updates, JSON parsing/validation logic, case-insensitive regex checks, and QueuedRequester for file loading management.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

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

@DedeHai DedeHai changed the title add json validation to file uplod in UI and minify before upload add json validation to file inputs in UI and minify before upload Dec 31, 2025
@DedeHai DedeHai requested a review from netmindz December 31, 2025 15:38
Copy link
Contributor

@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 (3)
wled00/data/common.js (1)

142-151: Inconsistent indentation: use tabs instead of spaces.

Lines 142, 144–150 use 2-space indentation, while the rest of the file uses tabs. As per coding guidelines, web files under wled00/data should use tabs for indentation.

🔎 Proposed fix
 async function uploadFile(fileObj, name, callback) {
 	let file = fileObj.files?.[0]; // get first file, "?"" = optional chaining in case no file is selected
-  if (!file) { callback?.(false); return; }
+	if (!file) { callback?.(false); return; }
 	if (/\.json$/i.test(name)) { // same as name.toLowerCase().endsWith('.json')
-    try {
-      const minified = JSON.stringify(JSON.parse(await file.text())); // validate and minify JSON
-      file = new Blob([minified], { type: file.type || "application/json" });
-    } catch (err) {
-      if (!confirm("JSON invalid. Continue?")) { callback?.(false); return; }
-      // proceed with original file if invalid but user confirms
-    }
-  }
+		try {
+			const minified = JSON.stringify(JSON.parse(await file.text())); // validate and minify JSON
+			file = new Blob([minified], { type: file.type || "application/json" });
+		} catch (err) {
+			if (!confirm("JSON invalid. Continue?")) { callback?.(false); return; }
+			// proceed with original file if invalid but user confirms
+		}
+	}
wled00/data/edit.htm (2)

487-503: Double JSON validation occurs for .json files.

The saveFile function validates and minifies JSON (lines 489-496), then uploadFile in common.js will parse and minify it again. This is harmless but redundant. Consider adding a flag to skip re-validation in uploadFile when the caller has already validated, or accept this minor overhead for simpler code.


540-540: Missing semicolon.

Minor style inconsistency—this line lacks a trailing semicolon while other statements in the file use them.

🔎 Proposed fix
-			saveFile(fn, getContent()) 
+			saveFile(fn, getContent());
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 787d8a7 and f02c7e2.

📒 Files selected for processing (2)
  • wled00/data/common.js
  • wled00/data/edit.htm
🧰 Additional context used
📓 Path-based instructions (2)
wled00/data/**/*.{htm,html,css,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use tabs for indentation in web files (.htm/.html/.css/.js) under wled00/data

Files:

  • wled00/data/edit.htm
  • wled00/data/common.js
wled00/data/**

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

wled00/data/**: When modifying web UI files, run npm run build to regenerate embedded headers before any firmware build
For web UI changes, edit files only under wled00/data (not firmware or generated files)

Files:

  • wled00/data/edit.htm
  • wled00/data/common.js
🧠 Learnings (3)
📚 Learning: 2025-10-05T15:24:05.545Z
Learnt from: CR
Repo: wled/WLED PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-05T15:24:05.545Z
Learning: Applies to wled00/data/** : For web UI changes, edit files only under wled00/data (not firmware or generated files)

Applied to files:

  • wled00/data/edit.htm
📚 Learning: 2025-10-05T15:24:05.545Z
Learnt from: CR
Repo: wled/WLED PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-05T15:24:05.545Z
Learning: Applies to wled00/data/**/*.{htm,html,css,js} : Use tabs for indentation in web files (.htm/.html/.css/.js) under wled00/data

Applied to files:

  • wled00/data/edit.htm
📚 Learning: 2025-11-27T13:54:01.277Z
Learnt from: DedeHai
Repo: wled/WLED PR: 5116
File: wled00/data/index.js:3474-3484
Timestamp: 2025-11-27T13:54:01.277Z
Learning: In WLED, the server-side upload handler automatically normalizes file paths by prepending a leading slash if missing (`if (finalname.charAt(0) != '/') { finalname = '/' + finalname; }`). This means client-side code uploading files (e.g., via `/upload` endpoint) can use paths with or without leading slashes—both will resolve to the same location.

Applied to files:

  • wled00/data/common.js
⏰ 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). (10)
  • GitHub Check: wled_build / Build Environments (esp32c3dev_qio)
  • GitHub Check: wled_build / Build Environments (lolin_s2_mini)
  • GitHub Check: wled_build / Build Environments (esp32s3_4M_qspi)
  • GitHub Check: wled_build / Build Environments (esp32S3_wroom2)
  • GitHub Check: wled_build / Build Environments (usermods)
  • GitHub Check: wled_build / Build Environments (esp32dev)
  • GitHub Check: wled_build / Build Environments (esp32s3dev_16MB_opi)
  • GitHub Check: wled_build / Build Environments (nodemcuv2_compat)
  • GitHub Check: wled_build / Build Environments (esp8266_2m_compat)
  • GitHub Check: wled_build / Build Environments (esp32s3dev_8MB_opi)
🔇 Additional comments (4)
wled00/data/common.js (1)

140-160: LGTM on the overall JSON validation and callback pattern.

The async file handling, JSON validation/minification logic, and callback signaling are implemented correctly. The function properly handles both successful uploads and error cases.

wled00/data/edit.htm (3)

114-122: LGTM on the dynamic resource loading approach.

The IIFE with retry mechanism ensures common.js loads reliably before initializing the page. Chaining loadResources for CSS follows the sequential loading pattern used elsewhere.


421-421: LGTM on case-insensitive JSON detection.

The use of /\.json$/i regex consistently across all JSON checks (lines 421, 477, 489, 511, 513) ensures robust handling of files regardless of extension casing.


563-582: LGTM on the initialization refactor.

Renaming to S() and triggering it via loadResources callback ensures all dependencies are loaded before initialization. Removing onload from <body> is the correct approach with this pattern.

@DedeHai
Copy link
Collaborator Author

DedeHai commented Dec 31, 2025

I tested this with a valid and an invalid json file, works as intended. Also can confirm that pretty-printed json files are minified after upload i.e. when downloaded from the FS.
Note: if you test this using the new file editor, you will not see it minified as the editor pretty-prints when displaying and minifies again when saving. you need to download the file to see its actual contents as-is.

@DedeHai DedeHai merged commit f19d29c into wled:main Jan 30, 2026
23 checks passed
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.

Restore preset/config

1 participant