Skip to content

Port genPresets from WLED-MM #4735

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Port genPresets from WLED-MM #4735

wants to merge 5 commits into from

Conversation

netmindz
Copy link
Member

@netmindz netmindz commented Jun 17, 2025

author [email protected]

Generate presets and playlists to act as demo mode or during testing

Summary by CodeRabbit

  • New Features
    • Added buttons in the "Info" modal to generate and save presets.
    • Introduced functionality to automatically create and display presets and playlists based on available effects.
    • Enabled users to save the generated presets directly from the interface.

Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

Walkthrough

New UI controls for generating and saving presets were added inside the "Info" modal in the HTML. Corresponding JavaScript functions were introduced to programmatically generate a presets JSON from existing effects, categorize them into playlists, display the JSON, and provide an option to save it by uploading to the server.

Changes

Files Change Summary
wled00/data/index.htm Added "Generate presets" and "Save generated presets" buttons inside the "Info" modal, plus a hidden textarea for displaying generated JSON.
wled00/data/index.js Added genPresets(), uploadFileWithText(), and savePresetsGen() functions to generate presets JSON, handle file upload, and save generated presets.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0bc8be3 and affd642.

📒 Files selected for processing (1)
  • wled00/data/index.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • wled00/data/index.js
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: wled_build / Build Environments (usermods)
  • GitHub Check: wled_build / Build Environments (esp32_wrover)
  • GitHub Check: wled_build / Build Environments (esp32s3dev_16MB_opi)
  • GitHub Check: wled_build / Build Environments (esp32s3_4M_qspi)
  • GitHub Check: wled_build / Build Environments (esp32s3dev_8MB_opi)
  • GitHub Check: wled_build / Build Environments (lolin_s2_mini)
  • GitHub Check: wled_build / Build Environments (esp32_eth)
  • GitHub Check: wled_build / Build Environments (esp32c3dev)
  • GitHub Check: wled_build / Build Environments (esp01_1m_full_compat)
  • GitHub Check: wled_build / Build Environments (esp32dev_V4)
  • GitHub Check: wled_build / Build Environments (esp32dev)
  • GitHub Check: wled_build / Build Environments (nodemcuv2_compat)
  • GitHub Check: wled_build / Build Environments (esp01_1m_full_160)
  • GitHub Check: wled_build / Build Environments (esp8266_2m_160)
  • GitHub Check: wled_build / Build Environments (esp8266_2m_compat)
  • GitHub Check: wled_build / Build Environments (nodemcuv2_160)
  • GitHub Check: wled_build / Build Environments (esp01_1m_full)
  • GitHub Check: wled_build / Build Environments (esp8266_2m)
  • GitHub Check: wled_build / Build Environments (nodemcuv2)
  • GitHub Check: wled_build / Test cdata.js
✨ 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.

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

🧹 Nitpick comments (2)
wled00/data/index.htm (1)

334-336: Explicitly set type="button" + add accessibility metadata to the new controls

The new buttons are inside a <div> that is not within a <form>, yet browsers still treat <button> without an explicit type as type="submit" by default.
Although in practice submission is unlikely here, explicitly declaring the type avoids accidental form-submission side-effects if this HTML is ever embedded in a form container (e.g., via component reuse).

While touching the element, consider small a11y & semantics polish:

-<button class="btn infobtn" id="genPresets" onclick="genPresets()">Generate presets</button>
-<button class="btn infobtn" id="savePresetsGen" onclick="savePresetsGen()" hidden="true">Save generated presets</button>
+<button class="btn infobtn"
+        id="genPresets"
+        type="button"
+        onclick="genPresets()"
+        aria-label="Generate demo presets and playlists">
+  Generate presets
+</button>
+<button class="btn infobtn"
+        id="savePresetsGen"
+        type="button"
+        onclick="savePresetsGen()"
+        hidden
+        aria-label="Save the generated presets JSON to presets.json">
+  Save generated presets
+</button>
-<textarea id="presetsGen" hidden="true"></textarea>
+<textarea id="presetsGen" hidden aria-label="Generated presets JSON"></textarea>

Key changes
type="button" → prevents implicit submit behaviour.
hidden as a boolean attribute (no value needed) for consistency.
aria-label → screen-reader clarity.
These tweaks cost nothing, future-proof the markup, and immediately improve accessibility.

wled00/data/index.js (1)

3407-3419: Use application/json and getURL() in uploadFileWithText

Minor polish:

  1. The payload is JSON, so advertise it:
  • var blob = new Blob([text], {type : 'application/text'});
  • var blob = new Blob([text], {type : 'application/json'});
  1. When the UI is running from “file mode” the hard-coded /upload won’t reach the device.
    Re-use the existing helper to stay consistent:

  • req.open("POST", "/upload");
  • req.open("POST", getURL("/upload"));
    
    

These tweaks avoid MIME confusion and keep the function working in all hosting modes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d2d5c42 and 7c196c5.

📒 Files selected for processing (2)
  • wled00/data/index.htm (1 hunks)
  • wled00/data/index.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
wled00/data/index.js

[error] 3429-3431: Shouldn't redeclare 'savePresetsGen'. Consider to delete it or rename it.

'savePresetsGen' is defined here:

(lint/suspicious/noRedeclare)

⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: wled_build / Build Environments (esp32_wrover)
  • GitHub Check: wled_build / Build Environments (esp32s3dev_8MB_opi)
  • GitHub Check: wled_build / Build Environments (esp32_eth)
  • GitHub Check: wled_build / Build Environments (esp32c3dev)
  • GitHub Check: wled_build / Build Environments (esp32dev_V4)
  • GitHub Check: wled_build / Build Environments (usermods)
  • GitHub Check: wled_build / Build Environments (esp32dev)
  • GitHub Check: wled_build / Build Environments (esp32s3_4M_qspi)
  • GitHub Check: wled_build / Build Environments (esp32s3dev_16MB_opi)
  • GitHub Check: wled_build / Build Environments (lolin_s2_mini)
  • GitHub Check: wled_build / Build Environments (nodemcuv2_160)
  • GitHub Check: wled_build / Build Environments (esp01_1m_full_compat)
  • GitHub Check: wled_build / Build Environments (nodemcuv2_compat)
  • GitHub Check: wled_build / Build Environments (esp01_1m_full_160)
  • GitHub Check: wled_build / Build Environments (esp8266_2m_160)
  • GitHub Check: wled_build / Build Environments (esp8266_2m_compat)
  • GitHub Check: wled_build / Build Environments (nodemcuv2)
  • GitHub Check: wled_build / Build Environments (esp01_1m_full)
  • GitHub Check: wled_build / Build Environments (esp8266_2m)
  • GitHub Check: wled_build / Test cdata.js

Comment on lines 3309 to 3404

function genPresets()
{
var result = "";
var sep = "{";

var effects = eJson;
var playlistPS = JSON.parse("{}");
var playlistSep = JSON.parse("{}");
var playlistDur = JSON.parse("{}");
var playlistTrans = JSON.parse("{}");
var playlistQL = JSON.parse("{}");
function addToPlaylist(m, id, ql = undefined) {
if (!playlistPS[m]) playlistPS[m] = "";
if (!playlistDur[m]) playlistDur[m] = "";
if (!playlistTrans[m]) playlistTrans[m] = "";
if (!playlistSep[m]) playlistSep[m] = "";
playlistPS[m] += playlistSep[m] + `${id}`;
playlistDur[m] += playlistSep[m] + "100";
playlistTrans[m] += playlistSep[m] + "7";
playlistSep[m] = ",";
if(ql) playlistQL[m] = `${ql}`;
}
var seq=230; //Playlist start here
for (let ef of effects) {
if (ef.name.indexOf("RSVD") < 0) {
if (Array.isArray(fxdata) && fxdata.length>ef.id) {
let fd = fxdata[ef.id];
let eP = (fd == '')?[]:fd.split(";"); // effect parameters
let m = (eP.length<4 || eP[3]==='')?'1':eP[3]; // flags
// console.log(ef, eP);
//transform key values in json format
var defaultString = "";
//if key/values defined, convert them to json in defaultString
if (eP.length>4) {
let defaults = (eP[4] == '')?[]:eP[4].split(",");
for (let i=0; i<defaults.length;i++) {
let keyValue = (defaults[i] == '')?[]:defaults[i].split("=");
defaultString += `,"${keyValue[0]}":${keyValue[1]}`;
}
}
//if not defined set to default
if (!defaultString.includes("sx")) defaultString += ',"sx":128'; //Speed
if (!defaultString.includes("ix")) defaultString += ',"ix":128'; //Intensity
if (!defaultString.includes("c1")) defaultString += ',"c1":128'; //Custom 1
if (!defaultString.includes("c2")) defaultString += ',"c2":128'; //Custom 2
if (!defaultString.includes("c3")) defaultString += ',"c3":16'; //Custom 3
if (!defaultString.includes("o1")) defaultString += ',"o1":0'; //Check 1
if (!defaultString.includes("o2")) defaultString += ',"o2":0'; //Check 2
if (!defaultString.includes("o3")) defaultString += ',"o3":0'; //Check 3
if (!defaultString.includes("pal")) defaultString += ',"pal":11'; //Temporary for deterministic effects test: Set to 11/Raibow instead of 1/Random smooth palette (if not set different)
if (!defaultString.includes("m12") && m.includes("1") && !m.includes("1.5") && !m.includes("12"))
defaultString += ',"rev":true,"mi":true,"rY":true,"mY":true,"m12":2'; //Arc expansion
else {
if (!defaultString.includes("rev")) defaultString += ',"rev":false';
if (!defaultString.includes("mi")) defaultString += ',"mi":false';
if (!defaultString.includes("rY")) defaultString += ',"rY":false';
if (!defaultString.includes("mY")) defaultString += ',"mY":false';
}
result += `${sep}"${ef.id}":{"n":"${ef.name}","mainseg":0,"seg":[{"id":0,"fx":${ef.id}${defaultString}}]}`;
sep = "\n,";
if(m.length <= 3) {
addToPlaylist(m, ef.id, m);
}
else {
addToPlaylist(m, ef.id);
}
addToPlaylist("All", ef.id, "ALL");
if(ef.name.startsWith("Y💡")) addToPlaylist("AnimARTrix", ef.id, "AM");
if (m.includes("1")) addToPlaylist("All 1D", ef.id, "1D");
if (m.includes("2")) addToPlaylist("All 2D", ef.id, "2D");

seq = Math.max(seq, (parseInt(ef.id) + 1));
} //fxdata is array
} //not RSVD
} //all effects

// console.log(playlistPS, playlistDur, playlistTrans);
for (const m in playlistPS) {
if(!playlistQL[m]) playlistQL[m] = seq;
let playListString = `\n,"${seq}":{"n":"${m} Playlist","ql":"${playlistQL[m]}","on":true,"playlist":{"ps":[${playlistPS[m]}],"dur":[${playlistDur[m]}],"transition":[${playlistTrans[m]}],"repeat":0,"end":0,"r":1}}`;
// console.log(playListString);
result += playListString;
seq++;
}

result += "}";

//assign result and show text and save button
gId("genPresets").hidden = true;
gId("savePresetsGen").hidden = false;
gId("presetsGen").hidden = false;
gId("presetsGen").value = result;
// console.log(result);

}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Build the presets object first, then JSON.stringify – string-building is brittle

genPresets() manually concatenates JSON with lots of +=, new-line commas, and string escaping assumptions:

  • An effect name containing " or \ will break the produced JSON.
  • Re-checking presence with defaultString.includes("sx") is error-prone ("o1" matches "o10").
  • Manual separators (sep, playlistSep) are easy to mis-place and hard to maintain.

Consider:

-function genPresets() {
-  /* huge string-building logic */
-}
+function genPresets() {
+  const presets = {};
+  const playlists = {};
+
+  // 1. Generate preset objects -------------------------------------------
+  eJson.forEach(([id, name]) => {
+    if (name.includes('RSVD')) return;
+
+    const p = { n: name, mainseg: 0, seg: [{ id: 0, fx: id }] };
+    Object.assign(p.seg[0], defaultFxParams(id)); // helper that returns the sx/ix/… object
+    presets[id] = p;
+
+    tagPlaylists(playlists, id, name);           // helper that fills playlists hash
+  });
+
+  // 2. Convert playlists hash → preset-style objects ----------------------
+  let nextId = Math.max(...Object.keys(presets).map(Number)) + 1;
+  for (const [tag, { ps, dur, transition, ql }] of Object.entries(playlists)) {
+    presets[nextId] = {
+      n: `${tag} Playlist`,
+      ql,
+      on: true,
+      playlist: { ps, dur, transition, repeat: 0, end: 0, r: 1 }
+    };
+    nextId++;
+  }
+
+  // 3. Show result --------------------------------------------------------
+  gId('presetsGen').value = JSON.stringify(presets, null, 2);
+  gId('genPresets').hidden = true;
+  gId('savePresetsGen').hidden = false;
+  gId('presetsGen').hidden = false;
+}

Benefits:

  • Guaranteed valid JSON – no manual escaping.
  • Logic is decomposed into helpers (defaultFxParams, tagPlaylists) improving readability & testability.
  • Future fields are added by editing objects, not string replacements.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In wled00/data/index.js from lines 3309 to 3404, the genPresets function builds
JSON by manually concatenating strings, which risks invalid JSON if effect names
contain special characters and is error-prone due to substring checks and manual
separators. Refactor genPresets to first construct a JavaScript object
representing the presets and playlists, using helper functions for default
parameters and playlist tagging, then convert this object to a JSON string with
JSON.stringify. This ensures valid JSON output, simplifies the logic, and
improves maintainability.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@DedeHai
Copy link
Collaborator

DedeHai commented Jun 17, 2025

is this a feature that is useful for "daily use" or mainly for debugging? Not fully clear to me from the code what it actually can do.

@blazoncek
Copy link
Collaborator

I would have preferred this as an external, uploadable file and not part of the standard build.

@willmmiles
Copy link
Member

I would have preferred this as an external, uploadable file and not part of the standard build.

Hm, could it be implemented as a usermod? addToJsonInfo() permits script injection.

@netmindz
Copy link
Member Author

Generate presets and playlists to act as demo mode or during testing

Reading the description is more helpful than the code ;)

I would have preferred this as an external, uploadable file and not part of the standard build.

Hm, could it be implemented as a usermod? addToJsonInfo() permits script injection.

The issue with making a usermod is then you need to remember to add to every build

It serves many purposes, both for formal testing and also useful for users to get a feel of what is supported

e.g Want a playlist that has all the audio effects - you've got it, want a playlist that lets you see all the new PS effects, you've got it, wanting to run a soak test of all effects - you've got it

@netmindz
Copy link
Member Author

You get a playlist for each "type" of effect, 1D/2D/2F etc All 2D, AnimARTrix

@netmindz
Copy link
Member Author

netmindz commented Jun 17, 2025

Might be worth trying throwing it at copilot to see if it can refactor the JavaScript to make it more compact. As fewer WLED users use 2D than on MM night also be worth only creating the 2D items if you have a 2D setup

@willmmiles
Copy link
Member

willmmiles commented Jun 17, 2025

I would have preferred this as an external, uploadable file and not part of the standard build.

Hm, could it be implemented as a usermod? addToJsonInfo() permits script injection.

The issue with making a usermod is then you need to remember to add to every build

Yes, that's exactly the goal. If I'm understanding @blazoncek correctly, he's raising an objection to including this feature in all builds (presumably on space usage grounds). Putting it in a module makes it easy to exclude if space is tight and you don't need it for your application. Personally I'd be happy to include this as a module in the default module set for our reference build.

(Looking forward, I am still hoping to move any current core feature with a WLED_DISABLE_X option to a library module; call them "core mods" instead of "usermods", but the API is the same. The implication is that we'll have some list of core modules we include in standard builds, but allow modders with custom builds to enable/disable stuff cleanly via platformio_override.ini, and minimize/reduce the #ifdef spam in the code.)

@blazoncek
Copy link
Collaborator

Sorry for late reply. What I wanted to say is that IMO generation of presets from existing effects is not what a regular user needs.

So it does not belong into regular UI IMO.

Unfortunately we cannot have UI built in a similar fashion as object code with WLED_DISABLE_XXXX compile parameter for C++, so some other method is needed.

I'm also not sure if usermod is good way as it can't inject huge amount of text in info dialog.

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.

4 participants