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

fix: slot should extra params #919

Open
wants to merge 3 commits into
base: refactor/develop
Choose a base branch
from

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented Dec 4, 2024

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

区块出码增加插槽传参解析

当前区块如果有插槽和传参,schema 片段可能是这样的:

{
  "children": [
	  {
	    "componentName": "Slot",
     	"props":  {
             // 插槽名称
             "name": "test"
            // 往插槽参数里面的传参
            "params": [
               {
                   "name":  "testData",
                   "value": {
                      "type": "JSExpression",
                      "value": "this.state.testData"
                   }
                }
            ]
        }
	  }
  ]
}

如果不处理,会默认出码成:

<template>
	<slot name="testData" :params=[{ name: "testData", value:  state.testData }]>
    </slot>
</template>

需要增加处理插槽传参,出码成为:

<template>
	<slot name="testData" :testData="state.testData">
    </slot>
</template>

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new function to enhance the handling of slot parameters in template generation.
    • Added new JSON schema files for components, defining their structure and child components.
    • Created new Vue single-file components that utilize slot parameters and support internationalization.
  • Bug Fixes

    • Improved logic for the TinyGrid component to handle properties more effectively.
  • Documentation

    • Updated method signatures to reflect new functionality while maintaining existing parameters.

Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

Walkthrough

The changes involve the addition of a new function, handleSlotParams, to the generateTemplate.js file and the incorporation of this function into the genSetupSFC.js file of the Vue generator package. The handleSlotParams function processes slot parameters when generating single-file components (SFCs). Additionally, the defaultGenTemplateHooks and defaultAttributeHook arrays are updated to include this new hook, enhancing the handling of attributes and slot parameters during template generation.

Changes

File Path Change Summary
packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js - Added import of handleSlotParams.
- Updated defaultGenTemplateHooks to include handleSlotParams.
- Modified genSFCWithDefaultPlugin to incorporate handleSlotParams in defaultAttributeHook.
packages/vue-generator/src/generator/vue/sfc/generateTemplate.js - Added new function handleSlotParams to process params for 'Slot' components.
- Modified handleTinyGrid to check for data and fetchData properties.
packages/vue-generator/test/testcases/sfc/slotParams/block.schema.json - Added new schema file defining a component named "Block" with state and child components.
packages/vue-generator/test/testcases/sfc/slotParams/expected/slotParamsBlock.vue - Introduced new Vue component with template, script, and style sections for slot handling.
packages/vue-generator/test/testcases/sfc/slotParams/expected/slotParamsPage.vue - Introduced new Vue component utilizing a named slot to render data.
packages/vue-generator/test/testcases/sfc/slotParams/page.schema.json - Created new JSON schema file for a Vue component named "Page" with child components.
packages/vue-generator/test/testcases/sfc/slotParams/slotParams.test.js - Added new test file with test cases for SFC generation based on schemas.

Possibly related PRs

  • fix: slot params missing double quote #605: This PR addresses a bug related to slot parameters, which may connect to the changes in handleSlotParams introduced in the main PR, as both involve handling slot parameters in Vue components.
  • fix:table slot edit params should not get alert #802: This PR modifies the validation and handling of slot parameters in a Vue component, which relates to the main PR's focus on enhancing slot parameter handling through the new handleSlotParams function.
  • fix: parse template name error #880: This PR modifies the genTemplatePlugin function, which may relate to the overall template generation process discussed in the main PR, particularly in how templates are processed and generated with slot parameters.
  • fix: sync material to cli #921: This PR involves updates to UI components and their configurations, which could be relevant to the changes in template generation and slot handling in the main PR, as both aim to enhance component functionality.

Suggested labels

ready_for_review

Suggested reviewers

  • hexqi
  • rhlin

Poem

In the garden of code, new hooks take flight,
handleSlotParams shines, making templates bright.
With each little change, our SFCs grow,
Attributes dance, as the features flow.
Hops of delight, in each line we write,
A rabbit's cheer for the code's new light! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 00d4f0d and 89c088f.

📒 Files selected for processing (1)
  • packages/vue-generator/test/testcases/sfc/slotParams/page.schema.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/vue-generator/test/testcases/sfc/slotParams/page.schema.json

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>, please review it.
    • Generate unit testing code for this file.
    • 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 generate unit testing code 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 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 generate unit testing code.
    • @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.

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 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.

@github-actions github-actions bot added bug Something isn't working refactor-main refactor/develop branch feature labels Dec 4, 2024
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

🧹 Outside diff range and nitpick comments (2)
packages/vue-generator/src/generator/vue/sfc/generateTemplate.js (2)

139-155: Consider adding documentation and unit tests

This new function handles an important aspect of slot parameter processing but lacks documentation and tests.

  1. Add JSDoc documentation explaining:

    • Function purpose
    • Expected input format
    • Side effects (props mutation)
    • Example usage
  2. Add unit tests covering:

    • Valid parameter processing
    • Invalid input handling
    • Edge cases (empty params, duplicate names)

Would you like me to help generate the documentation and unit test cases?


139-155: Consider a more functional approach

The current implementation mutates the props object directly. Consider a more functional approach that returns a new props object.

-export const handleSlotParams = (schemaData) => {
+export const handleSlotParams = (schemaData) => {
+  const { componentName, props } = schemaData.schema
+
+  if (componentName !== 'Slot' || !props?.params || !Array.isArray(props.params)) {
+    return
+  }
+
+  const newProps = { ...props }
+  delete newProps.params
+
+  props.params.forEach((paramItem) => {
+    const { name, value } = paramItem || {}
+    if (name && value) {
+      newProps[name] = value
+    }
+  })
+
+  schemaData.schema.props = newProps
+}

This approach:

  1. Makes the mutation more explicit
  2. Makes it easier to track changes
  3. Follows functional programming principles
  4. Makes the code more testable
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7d0956f and 19c83f2.

📒 Files selected for processing (2)
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (2 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateTemplate.js (1 hunks)
🔇 Additional comments (2)
packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (2)

9-10: LGTM: Import of new slot params handler

The import of handleSlotParams is correctly added alongside other template generation hooks.


217-217: Verify hook execution order

handleSlotParams is placed at the beginning of the defaultAttributeHook array, meaning it will execute before other attribute hooks. Please confirm this ordering is intentional, as it could affect how subsequent hooks process the modified props.

✅ Verification successful

Let me gather more information about the hook execution order and slot parameter handling.


Let me check how the other hooks interact with props to understand if the ordering is critical.


Based on the gathered information, I can now provide the final response:

The placement of handleSlotParams at the beginning is correct and intentional

The hook ordering is appropriate because:

  1. handleSlotParams transforms slot parameters into direct props and removes the params property
  2. Subsequent hooks like handleTinyGrid, handleJsxModelValueUpdate, and handleConditionAttrHook work with the transformed props structure
  3. No other hooks depend on or expect the original params structure to be present
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if other hooks depend on or modify slot params
# Look for any references to slot params in other attribute hooks

rg -l "props\.params" --type js

Length of output: 145


Script:

#!/bin/bash
# Check the implementation of handleSlotParams and other attribute hooks
ast-grep --pattern 'const handleSlotParams = $_'

# Look for the defaultAttributeHook array definition and its contents
ast-grep --pattern 'const defaultAttributeHook = $_'

# Check for any direct references to handleSlotParams
rg "handleSlotParams" -A 3 --type js

Length of output: 4140


Script:

#!/bin/bash
# Check implementations of subsequent hooks that might depend on props
ast-grep --pattern 'const handleTinyGrid = $_'
ast-grep --pattern 'const handleJsxModelValueUpdate = $_'
ast-grep --pattern 'const handleConditionAttrHook = $_'

# Look for any modifications to props in these hooks
rg "props\." -A 2 -B 2 packages/vue-generator/src/generator/vue/sfc/generateTemplate.js

Length of output: 9257

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

🧹 Outside diff range and nitpick comments (9)
packages/vue-generator/test/testcases/sfc/slotParams/expected/slotParamsPage.vue (5)

4-5: Consider adding null checks for slot props

The template directly accesses testData.name without checking if testData exists. Consider adding a defensive check to handle cases where the slot prop might be undefined.

-        <span>{{ testData.name }}</span></template
+        <span>{{ testData?.name }}</span></template

12-13: Optimize Vue imports

defineProps and defineEmits are already available in the script setup scope without explicit imports. Additionally, they're being imported twice (via vue namespace and directly).

-import * as vue from 'vue'
-import { defineProps, defineEmits } from 'vue'
+import { inject, reactive } from 'vue'

17-19: Remove unnecessary empty definitions

Since both props and emit are empty, these definitions can be omitted unless they're required by the lowcode framework.


22-25: Consider consolidating wrap calls

Multiple wrap calls with different objects might be consolidated into a single call. Also, the empty reactive state appears unused.

-wrap({ stores })
-
-const state = vue.reactive({})
-wrap({ state })
+const state = vue.reactive({})
+wrap({ stores, state })

27-27: Remove empty style block

Consider removing the empty scoped style block to reduce file size and improve readability.

packages/vue-generator/test/testcases/sfc/slotParams/page.schema.json (1)

24-34: Enhance test coverage for slot parameter expressions.

The current test only verifies simple property access (testData.name). Consider adding test cases for:

  • Complex expressions using slot parameters
  • Multiple slot parameters in a single expression
  • Method calls on slot parameters
  • Destructured slot parameters
packages/vue-generator/test/testcases/sfc/slotParams/block.schema.json (1)

3-8: Consider data type and i18n improvements for personData.

The state structure could be improved in several ways:

  1. Age should be a number instead of string: "age": 20
  2. Personal information is hardcoded in Chinese, consider using i18n keys
  "state": {
    "personData": {
-     "name": "李华",
-     "age": "20",
+     "name": "{{ t('person.name') }}",
+     "age": 20,
      "address": "china"
    }
  }
packages/vue-generator/test/testcases/sfc/slotParams/expected/slotParamsBlock.vue (2)

3-3: Use i18n for hardcoded text.

Replace hardcoded Chinese text with i18n translation.

-    <span>请开启插槽</span>
+    <span>{{ t('slots.enable') }}</span>

11-13: Optimize imports.

The code imports defineProps and defineEmits separately even though they're available from the main Vue import.

import * as vue from 'vue'
-import { defineProps, defineEmits } from 'vue'
import { I18nInjectionKey } from 'vue-i18n'
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 19c83f2 and 00d4f0d.

📒 Files selected for processing (6)
  • packages/vue-generator/src/generator/vue/sfc/generateTemplate.js (1 hunks)
  • packages/vue-generator/test/testcases/sfc/slotParams/block.schema.json (1 hunks)
  • packages/vue-generator/test/testcases/sfc/slotParams/expected/slotParamsBlock.vue (1 hunks)
  • packages/vue-generator/test/testcases/sfc/slotParams/expected/slotParamsPage.vue (1 hunks)
  • packages/vue-generator/test/testcases/sfc/slotParams/page.schema.json (1 hunks)
  • packages/vue-generator/test/testcases/sfc/slotParams/slotParams.test.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/vue-generator/src/generator/vue/sfc/generateTemplate.js
🔇 Additional comments (5)
packages/vue-generator/test/testcases/sfc/slotParams/expected/slotParamsPage.vue (1)

1-27: Verify test coverage for slot parameters

Since this is a test case for a bug fix related to slot parameters, ensure that edge cases are covered in the test suite.

✅ Verification successful

Test coverage for slot parameters is adequate

The test suite demonstrates comprehensive coverage for slot parameters:

  • Tests both block and page components
  • Verifies slot parameter passing with realistic data (testData with nested properties)
  • Includes snapshot testing for both components
  • Covers the complete flow from schema to rendered component

The implementation correctly handles:

  • Named slots with parameters (#test="{ testData }")
  • Reactive state binding to slot props (:testData="state.personData")
  • Component composition with slot content
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related test cases to ensure comprehensive coverage
echo "Searching for related slot parameter test cases..."
rg -l "slotParams" --type vue --type js packages/vue-generator/test/

# Check for potential error handling tests
echo "Checking for error handling test cases..."
rg -l "test.*error.*slot|test.*invalid.*slot" packages/vue-generator/test/

Length of output: 377


Script:

#!/bin/bash
# Search for related slot parameter test cases with correct file extensions
echo "Searching for related slot parameter test cases..."
fd . packages/vue-generator/test/ -e vue -e js -x rg -l "slotParams" {}

# Check test files containing slot-related tests
echo "Checking slot-related test files..."
fd . packages/vue-generator/test/ -e vue -e js -x rg -l "slot" {}

# Look for test configuration or test suite files
echo "Checking test suite files..."
fd . packages/vue-generator/test/ -e js -x rg -l "describe.*slot|test.*slot" {}

Length of output: 1310


Script:

#!/bin/bash
# Let's examine the content of the slot parameter test file to verify coverage
echo "Content of slot parameter test file:"
cat packages/vue-generator/test/testcases/sfc/slotParams/slotParams.test.js

# Check the test components to understand test scenarios
echo -e "\nContent of test components:"
cat packages/vue-generator/test/testcases/sfc/slotParams/expected/slotParamsBlock.vue

Length of output: 1666

packages/vue-generator/test/testcases/sfc/slotParams/page.schema.json (3)

1-8: Consider expanding test coverage with non-empty component properties.

While this serves as a minimal test case, consider adding variations with non-empty state, methods, props, or lifecycle hooks to ensure the slot parameter handling works correctly with other component features.


9-14: Verify slot behavior with component props.

The BlockSlotParams component has empty props. Consider adding test cases that verify slot parameter behavior when the component also has props to ensure there are no naming conflicts or scope issues.


15-23: Add test cases for multiple slot parameters.

The current test only covers a single slot parameter. Consider adding test cases for:

  • Multiple parameters in a single slot
  • Multiple slots with different parameters
  • Nested slots with parameters

This would ensure the handleSlotParams function handles all scenarios correctly.

packages/vue-generator/test/testcases/sfc/slotParams/block.schema.json (1)

31-41: Verify slot parameter binding syntax.

The slot parameter binding uses this.state.personData, but in Vue 3's composition API context, this might not be available. Ensure this expression works correctly in the generated component.

@chilingling chilingling added the ready_for_review This PR requires more reviews label Dec 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working ready_for_review This PR requires more reviews refactor-main refactor/develop branch feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants