Skip to content

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

    • JSON files uploaded to the editor are automatically minified and the editor refreshes/loads the saved file after upload.
  • Bug Fixes

    • Improved validation with clearer prompts when JSON is invalid (option to continue with original file).
    • File-type detection is now case-insensitive for more reliable handling.
    • Safer upload flow when no file is selected; better success/error feedback.

✏️ 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 the upload flow, changes uploadFile signature to accept a callback, and refactors the editor page to load scripts/styles dynamically, use case-insensitive JSON detection, and call the new upload utility for saves (initialization hook renamed).

Changes

Cohort / File(s) Summary
JSON Upload Enhancement
wled00/data/common.js
uploadFile(fileObj, name)uploadFile(fileObj, name, callback). Early exit when no file selected (invokes callback(false)). If filename matches JSON (case-insensitive) the file text is parsed and re-serialized (minified) into a Blob; parse errors prompt the user and may continue with original file. Uses processed file for FormData; onload/onerror invoke callback(boolean). Removed final return value.
Editor Refactor & Save Flow
wled00/data/edit.htm
Replaced static includes with dynamic loader (IIFE loads common.js with retry, then style.css). Replaced .endsWith('.json') checks with case-insensitive /\.json$/i across editor mode selection, validation, and pretty-printing. Renamed page init from onBodyLoad() to S() and removed body onload. Save workflow now uses uploadFile(..., callback) and refreshes tree/reloads file on success; simplified JSON error messaging.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

  • new file editor #4956 — Modifies wled00/data/edit.htm and related editor save/upload logic with overlapping JSON validation/minification and save workflow changes.

Pre-merge checks and finishing touches

❌ 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%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and directly describes the main changes: adding JSON validation to file inputs and minifying JSON before upload.
Linked Issues check ✅ Passed The PR addresses issue #5246 by adding JSON validation to prevent invalid presets from being applied, and implements minification to optimize file uploads.
Out of Scope Changes check ✅ Passed All changes are directly related to JSON validation and minification objectives. The dynamic script loading and editor initialization updates support the main validation feature.
✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

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

📒 Files selected for processing (1)
  • wled00/data/common.js
🧰 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/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/common.js
🧠 Learnings (2)
📚 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
📚 Learning: 2025-09-25T05:52:09.044Z
Learnt from: DedeHai
Repo: wled/WLED PR: 4956
File: wled00/data/edit.htm:213-222
Timestamp: 2025-09-25T05:52:09.044Z
Learning: In the WLED file editor (wled00/data/edit.htm), file renaming upon upload is not supported. The filename field is used for other purposes like creating new files or saving edited content, but uploaded files keep their original names.

Applied to files:

  • wled00/data/common.js
🧬 Code graph analysis (1)
wled00/data/common.js (2)
tools/cdata.js (1)
  • minified (179-179)
wled00/data/index.js (2)
  • e (1463-1463)
  • formData (3431-3431)
⏰ 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). (2)
  • GitHub Check: wled_build / Build Environments (usermods)
  • GitHub Check: wled_build / Build Environments (nodemcuv2_160)
🔇 Additional comments (4)
wled00/data/common.js (4)

140-142: LGTM: Clean function signature extension with proper defensive checks.

The addition of the callback parameter and async declaration enable the new validation workflow. The early return with optional chaining prevents errors when no file is selected.


143-151: LGTM: JSON validation and minification logic is sound.

The case-insensitive filename check, parse-then-stringify minification, and user confirmation on parse errors provide a good balance between safety and flexibility.


153-154: LGTM: Error handling correctly fixed.

The error handler now uses a generic message instead of accessing the non-existent e.stack property on ProgressEvent, addressing the past review comment. The callback invocation pattern is consistent across success and error paths.


157-157: LGTM: Correctly uses the potentially modified file variable.

Using the local file variable ensures that minified/validated JSON content (if applicable) is uploaded while preserving the original filename via the name parameter.


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.

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