-
-
Notifications
You must be signed in to change notification settings - Fork 9
Module: support button, new rows, nested tables #1
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
Conversation
Docs ==== - some changes UI == - MultiInput: add button - Array.svelte: add localDefinition - WIP - Module.svelte: remove Array bind value - WIP Server ===== - FileService: add TAG - Module: add TAG, UpdatedItem: replace index by getParendIndex/Name , compareRecursive: refactor to catch more cases - ModuleAnimations: add right fields to scripts array, refactored onUpdate
WalkthroughThis pull request updates documentation, UI, and core module code. Documentation now uses relative paths and updated file references. In the UI components, state handling and event callbacks have been improved. Core module code standardizes logging through new TAG macros and introduces new methods for recursive JSON data comparison and parent property extraction. Additionally, battery build flags in the configuration file have been commented out. Changes
Sequence Diagram(s)sequenceDiagram
participant User as User
participant MI as MultiInput Component
participant CB as onChange Callback
User->>MI: Click button
MI->>MI: Check if value is null
alt Value is null
MI->>MI: Set value = 1
else Value exists
MI->>MI: Increment value by 1
end
MI->>CB: Invoke onChange(event)
sequenceDiagram
participant Trigger as External Trigger
participant Mod as Module
participant MS as ModuleState
participant Log as Logging (TAG)
Trigger->>Mod: Trigger update
Mod->>MS: Call compareRecursive(parent, oldData, newData)
MS->>MS: Retrieve parent info via getParentName/getParentIndex
MS->>Log: Log differences with TAG
MS-->>Mod: Return comparison results
Mod->>Log: Log update outcome using TAG
Poem
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 (13)
docs/esp32sveltekit.md (1)
10-11: Updated Image Source Paths
The imagesrcattributes have been updated from a subdirectory reference (./media/) to a parent directory reference (../media/). This change appears to be aligned with the updated directory structure. Please verify that the images are indeed located relative to the new path.docs/general/gettingstarted.md (1)
50-50: Browser Cache Advisory Note Added
Notifying users about potential caching/max-age issues in the UI is helpful. This note directs developers to clear the browser cache if changes are not visible immediately. Consider detailing common scenarios or linking to troubleshooting tips if issues persist.docs/custom/module/demo.md (2)
11-14: Updated Server Reference to ModuleDemo.h
Replacing previous file references with[ModuleDemo.h](/src/custom/ModuleDemo.h)clarifies which header governs the module demo functionality. Double-check that the absolute path (starting with/) aligns with how links are resolved in your repository; a relative path might be preferable if consistency with other doc links is desired.
15-18: Simplified UI Section Content
The UI section now simply displays “Generated.” If this is intended as a placeholder for autogenerated content, consider adding a brief explanatory note or a link to additional details so users know what to expect.interface/src/lib/components/custom/MultiInput.svelte (1)
138-138: Enhanced button functionality with auto-increment behaviorThe button now intelligently handles null values and increments existing values, improving the user experience. This matches the PR objective of adding new button functionality to the MultiInput component.
However, consider adding a comment explaining this behavior for future maintenance:
- <button class="btn btn-primary" type="button" on:click={(event:any) => {if (value==null) value = 1; else value++; onChange(event)}} + <!-- Auto-increments value or initializes it to 1 if null --> + <button class="btn btn-primary" type="button" on:click={(event:any) => {if (value==null) value = 1; else value++; onChange(event)}}src/custom/ModuleDemo.h (1)
17-17: Consider adding clarifying comment for TAG macroThe TAG macro is now defined with the moon emoji, which is consistent with other files in the codebase. Consider adding a brief comment explaining its purpose for better maintainability.
-#define TAG "🌙" +// Define module tag for consistent logging +#define TAG "🌙"interface/src/lib/components/custom/Array.svelte (3)
44-47: Introduced local definition state variableGood introduction of a local definition state variable to manage component-specific definition data. However, the commented-out console.log statement could be removed entirely rather than left as commented code.
let localDefinition: any = $state([]); -// console.log("Array property", property, data, definition, changeOnInput, data[property.name], value1, value2);
50-52: Local definition assignment and loggingThe code now properly assigns the nested definition to the local state variable and logs it. This helps with debugging but consider making the log conditional based on a debug flag for production code.
localDefinition = definition[i].n; -console.log("localDefinition", property.name, definition[i].n) +// Only log in development mode +if (import.meta.env.DEV) { + console.log("localDefinition", property.name, definition[i].n); +}
72-75: Updated loop to use localDefinitionThe loop now correctly iterates over
localDefinitionwhich aligns with the changes made above. However, this loop structure seems complex and potentially inefficient - it's searching for a property with the same name aspropertyNamewithinlocalDefinition, butlocalDefinitionshould already be the relevant subset.-for (let i = 0; i < localDefinition.length; i++) { - let property = localDefinition[i]; - if (property.name == propertyName) { - console.log("addItem def", propertyName, property) - for (let i=0; i < property.n.length; i++) { - let propertyN = property.n[i]; - // console.log("propertyN", propertyN) - dataEditable[propertyN.name] = propertyN.default; - } - } +// Initialize with defaults directly from localDefinition +for (let i = 0; i < localDefinition.length; i++) { + let propertyN = localDefinition[i]; + if (import.meta.env.DEV) { + console.log("addItem def propertyN", propertyN); + } + dataEditable[propertyN.name] = propertyN.default; }interface/src/routes/custom/module/Module.svelte (2)
38-38: Removed definition loggingCommented out the console.log statement for debugging purposes. Consider removing it entirely rather than leaving commented code.
-// console.log("definition", definition)
98-98: Added data logging in inputChangedAdded console logging which helps with debugging but should be conditional in production.
-console.log(moduleName, data); +// Only log in development mode +if (import.meta.env.DEV) { + console.log(moduleName, data); +}src/custom/Module.cpp (2)
214-224: Added helper methods for property accessAdded two new methods to
UpdatedItemclass:
getParentIndex(): Extracts the index from the parent property stringgetParentName(): Extracts the name from the parent property stringThese methods improve encapsulation and provide a cleaner way to access parent properties in array items. Consider adding parameter validation and error handling for cases where the parent string format doesn't match expectations.
int UpdatedItem::getParentIndex(int depth) { int indexFrom = parent.indexOf("["); int indexTo = parent.indexOf("]"); + // Validate indices to avoid substring errors + if (indexFrom == -1 || indexTo == -1 || indexFrom >= indexTo) { + ESP_LOGW(TAG, "Invalid parent format for index extraction: %s", parent.c_str()); + return -1; + } return parent.substring(indexFrom+1, indexTo).toInt(); } String UpdatedItem::getParentName(int depth) { int indexFrom = parent.indexOf("["); + // Validate index to avoid substring errors + if (indexFrom == -1) { + ESP_LOGW(TAG, "Invalid parent format for name extraction: %s", parent.c_str()); + return parent; + } int indexTo = parent.indexOf("]"); return parent.substring(0, indexFrom);
214-224: Implement depth parameter functionalityThe methods
getParentIndex()andgetParentName()accept adepthparameter but don't use it. This parameter could be useful for handling nested arrays or objects with multiple levels of depth.Consider implementing the depth functionality to support nested structures:
int UpdatedItem::getParentIndex(int depth) { + // Find the nth occurrence of brackets based on depth + int currentDepth = 0; + int currentPos = 0; + int indexFrom = -1; + int indexTo = -1; + + while (currentDepth <= depth && currentPos < parent.length()) { + indexFrom = parent.indexOf("[", currentPos); + if (indexFrom == -1) break; + + indexTo = parent.indexOf("]", indexFrom); + if (indexTo == -1) break; + + if (currentDepth == depth) { + return parent.substring(indexFrom+1, indexTo).toInt(); + } + + currentPos = indexTo + 1; + currentDepth++; + } + + ESP_LOGW(TAG, "Could not find index at depth %d in %s", depth, parent.c_str()); + return -1; }Is handling nested arrays with multiple levels needed in the current codebase? If not, you might consider removing the unused parameter to avoid confusion.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
docs/custom/module/animations.md(1 hunks)docs/custom/module/demo.md(1 hunks)docs/custom/modules.md(5 hunks)docs/esp32sveltekit.md(1 hunks)docs/general/gettingstarted.md(1 hunks)interface/src/lib/components/custom/Array.svelte(4 hunks)interface/src/lib/components/custom/MultiInput.svelte(1 hunks)interface/src/routes/custom/module/Module.svelte(3 hunks)platformio.ini(1 hunks)src/custom/FilesService.cpp(8 hunks)src/custom/FilesService.h(1 hunks)src/custom/Module.cpp(9 hunks)src/custom/Module.h(3 hunks)src/custom/ModuleAnimations.h(9 hunks)src/custom/ModuleDemo.h(3 hunks)src/main.cpp(1 hunks)
🧰 Additional context used
🧬 Code Definitions (3)
src/custom/FilesService.cpp (2)
lib/framework/ESP32SvelteKit.h (1)
ESPFS(102-105)src/custom/Module.h (1)
state(50-50)
src/custom/ModuleAnimations.h (3)
src/custom/Module.h (4)
FT_ENABLED(61-61)updatedItem(70-70)root(51-51)root(68-68)lib/framework/ESP32SvelteKit.h (1)
_socket(117-120)src/custom/FilesService.h (1)
root(34-34)
src/custom/Module.cpp (3)
src/custom/Module.h (5)
root(51-51)root(68-68)state(50-50)parent(48-48)updatedItem(70-70)src/custom/ModuleDemo.h (4)
root(32-67)root(32-32)updatedItem(69-72)updatedItem(69-69)src/custom/ModuleAnimations.h (4)
root(86-143)root(86-86)updatedItem(145-157)updatedItem(145-145)
🔇 Additional comments (31)
platformio.ini (1)
64-65: Battery Configuration Disabled for ESP32-S3 DevKit
The battery-related build flags have been commented out with an explanation for theesp32-s3-devkitc-1-n16r8venvironment. This change is clear and well-documented; please confirm that any logic depending on these settings in the firmware or documentation is updated accordingly.src/custom/FilesService.h (1)
23-23: Addition of Logging Tag Macro
The new#define TAG "🌙"macro standardizes log outputs for FilesService. This is a clear and useful addition for consistent logging across modules.docs/custom/module/demo.md (1)
9-10: Updated Relative Module Link in Technical Section
Changing the link to point to[Modules](../modules/)makes the reference relative and consistent with the overall documentation structure. Verify that the relative path correctly resolves in all deployment contexts.docs/custom/module/animations.md (3)
20-20: Documentation path references updated correctlyThe change from absolute URL to relative path improves maintainability when documentation is moved or hosted in different locations.
24-24: Module reference updated to reflect actual implementationThe reference has been updated from
Instances.handInstances.cpptoModuleAnimations.h, which better aligns with the actual codebase organization.
28-28: UI reference simplifiedChanged from a specific file reference to simply "Generated", which is more accurate if the UI components are auto-generated.
src/main.cpp (1)
93-93:Details
❓ Verification inconclusive
Standardized logging with TAG constant
The logging statement now uses the
TAGconstant instead of a hardcoded string, which improves consistency with other modules mentioned in the PR objectives.
🏁 Script executed:
#!/bin/bash # Verify that TAG is properly defined somewhere accessible to main.cpp rg -A 1 "^#define TAG" --include="*.h"Length of output: 482
Logging Standardization: Using the TAG Constant
The logging statement in
src/main.cppnow leverages theTAGconstant instead of a hardcoded string, which improves consistency across modules. However, please note that the original verification command failed due to an unsupported option. To verify thatTAGis properly defined in an accessible header file, please re-run the verification with the updated command:#!/bin/bash # Verify that TAG is properly defined somewhere accessible to main.cpp rg -A 1 "^#define TAG" -g "*.h"Ensure that the header file declaring
TAGis correctly included for use insrc/main.cpp.src/custom/FilesService.cpp (2)
50-50: Commented out redundant loggingRemoved unnecessary logging that was adding noise to the log output.
76-76:Details
✅ Verification successful
Standardized logging with TAG constant throughout FilesService
All logging statements now use the
TAGparameter, which aligns with the PR objective of adding a TAG to the FileService. This improves log readability and consistency across the codebase.Also applies to: 99-99, 113-113, 120-120, 135-135, 138-138, 143-143, 152-152, 163-163, 210-210
🏁 Script executed:
#!/bin/bash # Verify that TAG is properly defined in the FilesService.h header rg -A 1 "^#define TAG" --include="FilesService.h"Length of output: 491
Standardized logging achieved using the TAG constant
The changes now consistently use the
TAGconstant in logging statements—for example,ESP_LOGI(TAG, "");at line 76 insrc/custom/FilesService.cppand similarly at lines 99, 113, 120, 135, 138, 143, 152, 163, and 210. This fulfills the PR objective of enhancing log consistency and readability.However, please manually verify that the
TAGconstant is correctly defined in thesrc/custom/FilesService.hheader file. Running the revised script above should display the expected definition. If it does not, further investigation is required.
🏁 Script executed:
#!/bin/bash # Revised command to verify that TAG is properly defined in the FilesService.h header. # This command explicitly targets the header file instead of using --include. rg -A 1 '^#define TAG' src/custom/FilesService.hLength of output: 190
Standardized Logging Verified – Consistent TAG Usage
The logging statements across
src/custom/FilesService.cppnow consistently use theTAGconstant. We verified thatTAGis correctly defined insrc/custom/FilesService.has#define TAG "🌙", matching the PR objective and ensuring uniform log readability. Please manually confirm this definition’s correctness during your next review.
- FilesService.h now defines the logging constant:
#define TAG "🌙"- FilesService.cpp logging calls (e.g., at line 76 and others: 99, 113, 120, 135, 138, 143, 152, 163, 210) consistently use
TAG.src/custom/ModuleDemo.h (2)
29-29: Improved logging with TAGGood change to use the TAG macro instead of an empty string, making log messages more identifiable.
71-72: Improved error message formatThe log message format has been improved by removing the array index parameter and using parent/name format instead. This matches the new approach using
getParentName()method.interface/src/lib/components/custom/Array.svelte (1)
202-202: Updated Array component propsThe component now correctly passes
localDefinitionto child Array components, ensuring consistent use of the local state. However, the binding approach has changed -bind:value1was removed while keepingvalue2. Make sure this doesn't break the two-way data binding functionality.Please verify that removing the
bind:value1property doesn't break functionality. The current approach passesvalue2without binding, which might prevent updates from propagating back up to the parent component.src/custom/Module.h (3)
15-15: Added consistent TAG macroGood addition of the TAG macro with the moon emoji, which standardizes logging across the module files.
33-36:Details
✅ Verification successful
Improved parent reference handling
Excellent improvement replacing a direct index with methods to retrieve parent information. This provides more flexibility and encapsulation.
However, these method declarations need implementations. Please ensure they're implemented in a corresponding .cpp file.
🏁 Script executed:
#!/bin/bash # Check if implementations exist for the new methods rg "int UpdatedItem::getParentIndex" -A 5 rg "String UpdatedItem::getParentName" -A 5Length of output: 690
Verification Complete: Implementations Confirmed
Excellent improvement on parent reference handling. The implementations for both
getParentIndexandgetParentNamehave been correctly provided insrc/custom/Module.cpp:
int UpdatedItem::getParentIndex(int depth)is implemented.String UpdatedItem::getParentName(int depth)is implemented.No further modifications are needed.
48-48:Details
✅ Verification successful
Added recursive comparison method
Good addition of the
compareRecursivemethod which will improve JSON data comparison functionality.
🏁 Script executed:
#!/bin/bash # Check for the implementation of the compareRecursive method rg "void ModuleState::compareRecursive" -A 10Length of output: 1153
Recursive Comparison Method Verified
The declaration of
compareRecursiveinsrc/custom/Module.hand its implementation insrc/custom/Module.cpphave been confirmed. The method correctly collects keys from both JSON objects, applies a recursive comparison using a lambda to handle unique keys, and properly triggers further comparison when values differ. The overall functionality to improve JSON data comparison is well implemented.interface/src/routes/custom/module/Module.svelte (1)
150-150:Details
❓ Verification inconclusive
Removed bind:value1 from Array component
The binding for value1 has been removed, which might affect two-way data binding. This change aligns with modifications in Array.svelte but needs verification to ensure it doesn't break data updates.
Please verify that the Array component still correctly updates the parent data object after removing the
bind:value1property. Consider testing by:
- Adding an item to an array
- Checking if the parent data is updated
- Ensuring changes propagate to the server when saved
🌐 Web query:
What is the correct way to bind arrays in Svelte components?💡 Result:
To correctly bind arrays in Svelte components, use these techniques depending on your scenario:
For Form Elements and Grouped Inputs
Use
bind:groupwith radio buttons, checkboxes, or multiple selects to manage array data:<script> let fillings = $state([]); </script> <!-- Checkbox group binding --> <input type="checkbox" bind:group={fillings} value="Rice"> <input type="checkbox" bind:group={fillings} value="Cheese">Changes automatically update the bound array[1][2][6]. For multiple selects:
<select multiple bind:value={selectedItems}> {#each options as option} <option value={option}>{option}</option> {/each} </select>Each Block Bindings
Bind directly to array element properties when rendering lists:
{#each todos as todo} <input type="checkbox" bind:checked={todo.done} > <input type="text" bind:value={todo.text} > {/each}This maintains reactivity for individual array elements[10][8].
Component Element References
To access DOM nodes/components in loops:
- Array index binding:
{#each items as item, i} <div bind:this={elementArray[i]}>{item}</div> {/each}- Object hashtable binding (better for dynamic lists):
{#each items as item (item.id)} <Component bind:this={componentRefs[item.id]} /> {/each}Works with both DOM elements and Svelte components[4][6].
Between Components
For parent-child component array binding:
- In child component:
<script> let { items = $bindable([]) } = $props(); </script>- In parent:
<Child bind:items={parentArray} />Must explicitly mark bindable props with
$bindable[1][3].Key Considerations
- Use
$state()for arrays requiring reactivity[9]- Avoid direct array mutations - prefer immutable patterns
- With derived arrays, use
$derivedor consider computed properties- For complex array interactions, use stores for state management
These patterns maintain reactivity while providing clear data flow semantics. For most array binding needs,
bind:groupand each-block property bindings cover the majority of use cases, with component references providing lower-level control when needed[1][2][6][10].Citations:
- 1: https://svelte.dev/docs/svelte/bind
- 2: https://dev.to/joeljaison394/unlocking-the-power-of-svelte-mastering-bindings-70l
- 3: https://flaviocopes.com/svelte-bindings/
- 4: https://jamesmcgrath.net/array-of-elements-svelte/
- 5: https://www.youtube.com/watch?v=AXwgpUvLiwk
- 6: https://www.sveltesociety.dev/recipes/component-recipes/getting-references-to-components-in-each-blocks
- 7: https://svelte.dev/playground/468f0b8fb9b14d60b31c80d144e5b93e?version=3.22.3
- 8: sveltejs/svelte#9687
- 9: sveltejs/svelte#11861
- 10: https://svelte.dev/tutorial/svelte/each-block-bindings
Action Required: Verify Two-Way Binding in Array Component
The removal of
bind:value1in the<Array>component appears to follow updated Svelte binding practices. Although modern Svelte patterns advocate using explicit parent–child bindings (e.g. viabind:itemsor individual property bindings based on context), please verify that the reactivity and two-way data flow remain intact. Specifically, ensure that:
- Adding an item to an array correctly updates the parent
dataobject.- Changes are reflected and propagate as expected (including server updates on save).
- Overall component reactivity isn’t compromised despite the removal of
bind:value1.Based on current Svelte guidance for array bindings, this change is likely intentional; however, manual testing covering the scenarios above is recommended.
docs/custom/modules.md (2)
29-29: Improved logging with standardized TAGThe logging statement now uses
TAGmacro for consistent logging across the module system. This makes it easier to identify log messages from different modules.
68-80: EnhancedonUpdatemethod with better encapsulationThe
onUpdatemethod has been improved with:
- Better encapsulation by using
getParentName()andgetParentIndex()methods instead of directly accessing properties- Consistent logging with the defined TAG
- More descriptive variable naming (e.g.,
index)These changes align with the updates in the actual implementation files and demonstrate the proper way to handle updates in module classes.
src/custom/ModuleAnimations.h (10)
20-20: Added standard logging TAGAdding a standardized tag for logging (
🌟) improves log readability and makes it easier to filter logs by module in the console.
46-46: Enhanced constructor loggingAdded more informative logging in the constructor using the new TAG.
52-56: Improved FastLED initialization with logging and reduced brightnessThe FastLED initialization now sets the brightness to a lower default value (10 instead of the previous value), which is a safer starting point. Added clear logging about the LED configuration.
63-63: Enhanced file update handler loggingAdded more informative logging in the file update handler with file path information.
73-73: Improved file update loggingEnhanced logging for file updates that trigger animation recompilation.
87-87: Added logging to setupDefinitionAdded logging statement at the beginning of the setupDefinition method to track method execution.
93-93: Reduced default brightness valueChanged the default brightness value from the previous value to 10, which is more appropriate for initial setup and safer for power consumption.
150-153: Improved data access with proper encapsulationUpdated the animation handler to use
getParentName()andgetParentIndex()methods instead of directly accessing properties. This improves encapsulation and code maintainability.
148-148: Enhanced logging in onUpdate methodImproved logging in the onUpdate method with more descriptive messages and consistent use of TAG.
Also applies to: 156-156
200-200: Enhanced compileAndRun method loggingAdded more detailed and standardized logging throughout the compileAndRun method to improve debugging capabilities.
Also applies to: 217-217, 226-228
src/custom/Module.cpp (3)
14-14: Added standard logging TAGAdding a standardized tag for logging (
🌙) improves log readability and makes it easier to filter logs by module in the console.
33-33: Standardized logging with TAGUpdated all logging statements to consistently use the defined TAG, improving log readability and making it easier to identify messages from different modules.
Also applies to: 38-38, 51-51, 95-95, 153-153, 165-165, 211-211
56-88: Enhanced recursive JSON comparison logicThe
compareRecursivemethod has been significantly improved to better handle complex JSON structures:
- Now collects unique keys from both old and new data for thorough comparison
- Handles arrays more robustly, including automatically adding new objects when needed
- Uses clear variable names and better organized code structure
- Provides more detailed logging for easier debugging
This enhancement will better support detecting changes in nested data structures.
Docs
UI
Server
Summary by CodeRabbit