Skip to content
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

Refactor: :each with variables #14

Merged
merged 5 commits into from
Feb 16, 2024
Merged

Refactor: :each with variables #14

merged 5 commits into from
Feb 16, 2024

Conversation

jorenrui
Copy link
Contributor

@jorenrui jorenrui commented Feb 16, 2024

Description

  • Fixed the :each to replace the variables properly instead of using a plain replace all.
  • Add scoped-variables for each items.

Usage

The :each statement is used to loop through an array and render a template for each item.

<script>
  items = ['Tag 1', 'Tag 2', 'Tag 3', 'Tag 4']
</script>

<ul :each="item in items">
  <li :text="item"></li>
</ul>

<ul :each="item, index in items">
  <li :text="item"></li>
</ul>

You can also use complex variables for the :each statement:

<script>
  items = [
    { name: 'Tag 1', id: 1 },
    { name: 'Tag 2', id: 2 },
    { name: 'Tag 3', id: 3 },
    { name: 'Tag 4', id: 4 },
  ]
</script>

<ul :each="item in items">
  <li :text="item.name"></li>
</ul>

Summary by CodeRabbit

  • New Features
    • Added state property to Entity class for improved state management.
    • Introduced methods for handling ':each.item' attribute, enhancing data binding and DOM updates.
    • Expanded interpret method to accept _scope parameter for variable scope flexibility.
  • Bug Fixes
    • Corrected value comparison logic within arrays to ensure accurate data handling.
  • Documentation
    • Updated readme with examples and explanations of the :each statement for better developer understanding.
📦 Published PR as canary version: 1.0.1-canary.14.c08dc9f.0

✨ Test out this PR locally via:

npm install tonic-minijs@1.0.1-canary.14.c08dc9f.0
# or 
yarn add tonic-minijs@1.0.1-canary.14.c08dc9f.0

@jorenrui jorenrui self-assigned this Feb 16, 2024
Copy link

coderabbitai bot commented Feb 16, 2024

Walkthrough

The updates encompass a multitude of enhancements across the board, focusing on refining data structures for better UI dynamics, enriching class functionalities with state management and element relationship handling, and improving syntax interpretation for more robust scripting capabilities. These changes collectively aim to elevate user interaction with the UI and streamline developer experience in scripting and UI manipulation.

Changes

Files Change Summary
lib/entity.js
lib/entity/attributes.js
Added state property to Entity class. Modified setting of element.dataset in setAsParent method. Added methods for attribute checks like isInsideEachEl, getEachEl, and more. Updated variable handling and filtering logic. Enhanced interpret method for passing this.state to the engine. Improved element relationship handling for ':each.item' attribute.
lib/generators/interpreter.js
lib/generators/lexer.js
Updated interpret method for flexible variable passing. Fixed array comparison issue and added destructuring support in Vue.js directives.
lib/main.js Introduced a new variable for Entity instance creation and conditional disposal based on element relationship check.
readme.md Added detailed explanation and examples for the ':each' statement.

🐰✨
Changes afoot in the code we weave,
Enhancing the web, in which we believe.
From dynamic UIs to scripts that sing,
A leap forward, in the digital spring.
Celebrate we shall, with bytes and bits,
For in our world, creativity never quits.
🌟🐇

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit-tests for this file.
  • 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 generate unit tests for this file.
    • @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 generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between d0074c8 and 74e23af.
Files selected for processing (7)
  • index.html (3 hunks)
  • lib/entity.js (6 hunks)
  • lib/entity/attributes.js (4 hunks)
  • lib/generators/interpreter.js (2 hunks)
  • lib/generators/lexer.js (1 hunks)
  • lib/main.js (1 hunks)
  • readme.md (1 hunks)
Additional comments: 16
lib/generators/interpreter.js (2)
  • 38-45: The addition of the _scope parameter in the interpret method of the Interpreter class enhances flexibility in variable passing and scope management. This change allows for dynamic scope adjustments during interpretation, which is a significant improvement for handling scoped variables within templates or loops. Ensure that all calls to interpret throughout the codebase have been updated to include this new parameter where necessary.
  • 62-65: Similarly, the interpret method in the ClassInterpreter class now accepts an _scope parameter, aligning with the changes made in the Interpreter class. This consistency across both classes ensures a unified approach to scope management and variable passing, facilitating more complex data handling scenarios. As with the Interpreter class, verify that calls to this method are updated accordingly.
lib/main.js (1)
  • 94-95: The introduction of a conditional check to dispose of an entity if it is inside an :each loop (entity.isInsideEachEl()) is a thoughtful addition for optimizing resource management. This ensures that entities created within loops that are no longer needed are properly disposed of, preventing potential memory leaks and ensuring efficient resource utilization. It's important to ensure that the isInsideEachEl method accurately identifies entities within :each loops for this mechanism to work as intended.
lib/entity.js (3)
  • 14-14: The addition of the state property to the Entity class is a significant enhancement for state management within entities. This allows for more granular control and manipulation of entity-specific data, facilitating complex data handling scenarios. Ensure that the state property is properly initialized and managed throughout the entity's lifecycle.
  • 37-43: The isInsideEachEl method is a crucial addition for identifying entities within :each loops. This method enhances the framework's ability to manage entities and resources efficiently, especially in dynamic rendering scenarios. It's important to ensure that this method accurately identifies entities within :each loops, considering various nesting and scoping scenarios.
  • 45-51: The getClosestEl method, which retrieves the closest element matching a specified attribute, is a valuable utility for navigating and manipulating the DOM in relation to the entity. This method's implementation, particularly its handling of attribute selectors, demonstrates attention to detail in ensuring compatibility with complex DOM structures. Verify that this method performs as expected in various use cases, including nested and complex DOM scenarios.
lib/entity/attributes.js (3)
  • 12-12: The addition of the ':each.item' attribute to the list of custom attributes is a significant enhancement for handling item-level data within :each loops. This allows for more precise and dynamic rendering of templates based on loop data, supporting both simple and complex variable structures. Ensure that this attribute is properly handled and documented to facilitate its effective use.
  • 90-115: The evaluateEachItem method, introduced to handle the evaluation of the ':each.item' attribute, is a key addition for enabling dynamic DOM updates based on loop data. This method's implementation, particularly its handling of dataset attributes and JSON parsing, demonstrates a thoughtful approach to managing item-level data within loops. Ensure that error handling and data parsing within this method are robust to prevent issues in complex rendering scenarios.
  • 220-232: The updates to the evaluateEach method to handle the ':each.item' attribute, including the parsing and removal of this attribute, are well-implemented. These changes enable more complex data handling and rendering scenarios within loops, enhancing the framework's flexibility and utility. It's important to ensure that these updates work seamlessly with existing functionality and do not introduce regressions in handling other attributes or loop scenarios.
lib/generators/lexer.js (1)
  • 40-45: The fix for the issue with value comparison within arrays and the addition of support for destructuring assignments are significant improvements to the lexer's functionality. These changes enhance the lexer's ability to accurately parse and handle expressions and directives, particularly in scenarios involving complex data structures and assignments. Ensure that these changes are thoroughly tested to verify their correctness and compatibility with existing functionality.
readme.md (1)
  • 241-274: The documentation for the :each statement is well-written and provides clear examples of how to use the statement with both simple arrays and arrays of objects. This addition will greatly help users understand how to leverage the :each statement for dynamic content rendering. It's important to ensure that the examples provided are tested and work as expected in the MiniJS framework to maintain the accuracy of the documentation.
index.html (5)
  • 61-102: The change from a simple array of strings to an array of objects for regions is a significant improvement. It allows for more detailed information about each region to be stored and displayed, such as images and alt text. This change enhances the UI's ability to provide a richer user experience by dynamically rendering images based on the selected region. However, ensure that all instances in the codebase that previously relied on the simple array structure have been updated to work with the new object structure to prevent any issues.
  • 411-437: The implementation of the :each directive to dynamically render region buttons based on the new data structure is well done. It effectively utilizes the properties of each region object to set the image source, alt text, and click event handler. This approach maintains a clean separation of concerns by keeping the template declarative and leveraging the framework's reactivity system. However, ensure that the click event handler properly updates the application state to reflect the selected region and triggers any necessary UI updates or side effects.
  • 408-448: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [445-467]

The search results rendering logic appears to be well-implemented, dynamically displaying destinations based on the user's input. However, it's important to ensure that the filteredDestinations array is correctly updated based on the search query and that the selectedDestination management logic correctly handles user interactions such as mouseover and click events. Additionally, consider adding accessibility attributes to improve the usability of the search results list for screen reader users.

  • 819-819: The addition of a new tab for "Team Members" in the active state example is a good enhancement. Ensure that the corresponding content for this tab is properly managed and displayed when the tab is active. It's also important to verify that the active state management logic correctly updates when different tabs are selected, providing a seamless user experience.
  • 58-107: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1-1]

The overall structure and organization of the HTML document are well-maintained, with clear separation between different sections and components. However, it's crucial to ensure that all JavaScript interactions are robust and handle edge cases gracefully. For example, when dealing with user inputs or asynchronous operations, consider adding error handling mechanisms to improve the resilience of the application.

@jorenrui jorenrui changed the title Refactor: :each with variables Refactor: :each with variables [NOT DONE YET] Feb 16, 2024
@jorenrui jorenrui marked this pull request as draft February 16, 2024 06:04
@jorenrui jorenrui marked this pull request as ready for review February 16, 2024 09:49
@jorenrui jorenrui merged commit c08dc9f into main Feb 16, 2024
1 check passed
@jorenrui jorenrui deleted the jr.feature/each-directive branch February 16, 2024 09:49
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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 74e23af and c535282.
Files selected for processing (2)
  • lib/entity.js (7 hunks)
  • lib/entity/attributes.js (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • lib/entity/attributes.js
Additional comments: 15
lib/entity.js (15)
  • 14-14: The addition of the state property to the Entity class is a significant enhancement. It's crucial to ensure that this state object is properly managed and updated throughout the entity's lifecycle to avoid stale or inconsistent state data.
  • 26-26: Modifying the dataset to include a mini.uuid is a good approach for uniquely identifying elements. However, ensure that this UUID is consistently used and managed across the application to prevent any potential conflicts or misuse.
  • 37-42: The isInsideEachEl method introduces logic to determine if the current element is inside an :each block. It's important to verify that this method accurately reflects the intended behavior, especially in nested :each scenarios.
  • 45-46: The getEachEl method simplifies the process of finding the closest :each element. Ensure that this method is robust against various DOM structures and nesting levels.
  • 49-53: The getEachItemEl method is crucial for identifying the :each.item element. It's important to ensure that this method correctly handles cases where the current element itself has the :each.item attribute or is nested within another :each.item.
  • 56-60: The isInsideEachItem method's logic appears to be sound, but it's essential to test this method thoroughly, especially in complex DOM structures with nested :each and :each.item elements.
  • 63-64: The isEachItem method is straightforward and should work as expected. However, it's always good practice to include unit tests for such methods to ensure their reliability.
  • 67-70: The isEachItemEvaluated method checks if an :each.item has been evaluated. This method's correctness is crucial for the proper functioning of dynamic rendering. Ensure that the attribute and its value are consistently managed across the application.
  • 74-78: The getClosestEl method uses a custom attribute selector that includes escaping for special characters. This is a good practice, but ensure that the escaping logic covers all potential special characters that might be used in attribute names.
  • 102-107: The filtering logic in _getVariablesFromAttributes method has been adjusted to exclude variables that are part of the entity's state or are native functions. This is a critical change for security and correctness. Ensure that this logic is thoroughly tested, especially for edge cases where variable names might conflict with global objects or functions.
  • 132-137: Similar to the previous comment, the _getVariablesFromEvents method's filtering logic has been updated. It's essential to ensure consistency and correctness in how variables are handled across different parts of the application.
  • 208-208: The interpret method now passes this.state to the engine, which is a significant change in how state is managed and passed around. It's crucial to ensure that the engine correctly handles this state object without causing unintended side effects or data leaks.
  • 213-220: The getParent method has been modified to use getClosestEl for finding the parent node. This change should improve the method's accuracy in identifying the correct parent entity. However, ensure that this does not introduce any regressions in scenarios where the parent entity's identification is critical.
  • 244-256: The logic in initChildren for initializing or disposing of child entities based on their relationship with :each elements is complex. It's important to ensure that this logic correctly handles all cases, especially with nested :each and :each.item elements, to prevent any initialization issues.
  • 262-272: The handling of :each.item elements in initChildren includes setting the attribute to true and cleaning up dataset entries starting with mini.each:. This is a crucial part of managing dynamic content, but ensure that this does not inadvertently affect other parts of the application relying on similar dataset keys.

@jorenrui jorenrui changed the title Refactor: :each with variables [NOT DONE YET] Refactor: :each with variables Feb 16, 2024
Copy link

🚀 PR was released in v1.0.1 🚀

@github-actions github-actions bot added the released This has been released in npm label Feb 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
released This has been released in npm
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant