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

feat: tinyvue grid slot generate code to template #756

Merged
merged 3 commits into from
Feb 18, 2025

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented Aug 26, 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

【问题描述】
如 issue #754 所描述,当表格组件使用插槽并为插槽里面的组件添加样式时,页面预览以及下载代码后,为插槽里面的组件添加的样式无法生效。

【问题分析】
vue setup 中的 jsx,无法自动添加 scoped id,但是添加的样式却是默认是 scoped id 的。导致样式无法应用。

【解决方案】
tinyvue grid 组件有插槽时,不直接在 setup 组件中生成 jsx,而是将表格列配置作为 tiny-grid-column 生成到 template 中。

即从生成 jsx :

<template>
	<tiny-grid  :fetchData={ api: fetchData }  :columns="state.columns">
   </tiny-grid>
</template>
<script setup>
	const state = reactive({
        columns: [
        {
            field: 'city',
            slots: {
              default: ({ row }, h) => (
                //  这里的样式类不生效
                 <div  className="test-class">
                      { row.city }
                  </div>
              )
            }
         }
       ]
    })
</script>
<style scoped>
.test-class {
  color: red;
}
</style>

改成生成代码为:

<template>
	<tiny-grid  :fetchData={ api: fetchData } >
      <tiny-grid-column field="city">
          <template #default="{ row }">
              <div class="test-class">{{ row.city }}</div>
          </template>
     </tiny-grid-column>
   </tiny-grid>
</template>
<script setup>

</script>
<style scoped>
.test-class {
  color: red;
}
</style>

What is the current behavior?

Issue Number: #754

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Introduced a dedicated grid column component that enables a more modular and customizable table layout.
    • Enhanced grid configurations to support explicit, interactive column definitions for data presentation.
  • Refactor

    • Streamlined the grid template and mapping logic, offering improved clarity and dynamic configuration for a refined user experience.

Copy link
Contributor

coderabbitai bot commented Aug 26, 2024

Walkthrough

This pull request introduces modifications to the Vue generator's component generation process, specifically enhancing the handling of TinyGrid components and their columns. Key changes include adjusting hooks for component generation, transforming slot and column handling with new functions, and updating component mappings to support a more flexible definition of grid columns. These alterations span multiple files, impacting both the generation logic and the associated test cases.

Changes

File Change Summary
packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js Moved handleTinyGrid from defaultAttributeHook to defaultComponentHooks
packages/vue-generator/src/generator/vue/sfc/generateTemplate.js Added new functions: transformSlots, transformColumnToChildren, columnHasSlots; Updated import and slot handling logic
packages/vue-generator/test/testcases/sfc/case01/componentsMap.json Added new component mapping for TinyGridColumn
packages/vue-generator/test/testcases/sfc/case01/expected/FormTable.vue Restructured grid columns using explicit tiny-grid-column components
packages/vue-generator/test/testcases/sfc/slotModelValue/page.schema.json Updated state structure to centralize column definitions
designer-demo/public/mock/bundle.json Added new component definition for TinyGridColumn
mockServer/src/assets/json/appinfo.json Added new entry for TinyGridColumn with various properties
mockServer/src/mock/get/app-center/v1/apps/schema/918.json Added new component declaration for TinyGridColumn in componentsMap
packages/engine-cli/template/designer/public/mock/bundle.json Added new component entry for TinyGridColumn

Possibly related PRs

  • fix: slot should extra params #919: The changes in the main PR are related to those in the retrieved PR as both modify the genSFCWithDefaultPlugin function in genSetupSFC.js, with the main PR adjusting hooks for component generation and the retrieved PR adding a new hook for handling slot parameters.
  • feat:preview multi page structured data transfer and nested display #978: The changes in the main PR are related to the modifications in the genSFCWithDefaultPlugin function, which also appears in the retrieved PR, indicating a direct connection at the code level.

Suggested labels

bug

Suggested reviewers

  • hexqi
  • rhlin

Poem

🐰 Hopping through code with glee,
Tiny Grid columns now set free!
Slots transformed, hooks rearranged,
Vue generation, beautifully changed!
A rabbit's dance of pure delight! 🎉


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@chilingling chilingling force-pushed the feat/tinyvueGridGenCode branch from 7ee5602 to 1ba0e01 Compare January 8, 2025 07:49
@chilingling chilingling marked this pull request as ready for review January 13, 2025 12:54
@github-actions github-actions bot added enhancement New feature or request refactor-main refactor/develop branch feature labels Jan 13, 2025
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 (6)
packages/vue-generator/src/generator/vue/sfc/generateTemplate.js (4)

70-89: Robustness in transformSlots function

The transformSlots function effectively transforms slot configurations. However, consider adding a check to ensure that value within the slots is defined to prevent potential undefined issues in value?.params and value?.value.

Apply this diff to include default values:

        return {
          componentName: 'template',
          props: {
            slot: {
              name: key,
-             params: value?.params || ''
+             params: (value && value.params) || ''
            }
          },
-         children: value?.value
+         children: (value && value.value) || ''
        }

91-93: Consistent return values in transformColumnToChildren

When columns is not an array, the function returns undefined. For consistency and to avoid unexpected behavior in calling functions, consider returning an empty array instead.

Apply this diff:

-  if (!Array.isArray(columns)) {
-    return
-  }
+  if (!Array.isArray(columns)) {
+    return []
+  }

96-110: Avoid mutation of input objects

In transformColumnToChildren, you are destructuring item and modifying restItem. To prevent side effects, it's better to create a deep copy of item before modification.

Apply this diff to clone item:

  const res = columns.map((item) => {
+   const clonedItem = { ...item }
    const { slots, ...restItem } = clonedItem
    let children = []
    if (slots) {
      children = transformSlots(slots)
    }
    return {
      componentName: 'TinyGridColumn',
      props: restItem,
      children
    }
  })

116-123: Optimize columnHasSlots function

The columnHasSlots function can return early upon finding the first column with slots. It's already efficient, but you can use the some method for cleaner code.

Apply this diff:

-const columnHasSlots = (columns) => {
-  for (const columnItem of columns) {
-    if (columnItem.slots && typeof columnItem.slots === 'object' && Object.keys(columnItem.slots).length > 0) {
-      return true
-    }
-  }
-  return false
-}
+const columnHasSlots = (columns) => {
+  return columns.some(
+    (columnItem) =>
+      columnItem.slots &&
+      typeof columnItem.slots === 'object' &&
+      Object.keys(columnItem.slots).length > 0
+  )
+}
packages/vue-generator/test/testcases/sfc/slotModelValue/page.schema.json (2)

15-48: Consider adding validation for numeric input.

The employees field uses TinyNumeric but lacks input validation beyond the step constraint.

Consider adding min/max constraints and validation:

  "componentName": "TinyNumeric",
  "props": {
    "allow-empty": true,
    "placeholder": "请输入",
    "controlsPosition": "right",
    "step": 1,
+   "min": 0,
+   "max": 999999,
    "modelValue": {

74-79: Implement proper change handlers.

The onChange handlers only log to console without actual implementation.

Would you like me to help implement proper change handlers for both numeric and text inputs? This should include:

  • Data validation
  • State updates
  • Error handling

Also applies to: 35-40

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a14a508 and 8fe57a9.

📒 Files selected for processing (6)
  • packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (1 hunks)
  • packages/vue-generator/src/generator/vue/sfc/generateTemplate.js (3 hunks)
  • packages/vue-generator/test/testcases/sfc/case01/componentsMap.json (1 hunks)
  • packages/vue-generator/test/testcases/sfc/case01/expected/FormTable.vue (2 hunks)
  • packages/vue-generator/test/testcases/sfc/slotModelValue/expected/slotModelValueTest.vue (1 hunks)
  • packages/vue-generator/test/testcases/sfc/slotModelValue/page.schema.json (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/vue-generator/test/testcases/sfc/slotModelValue/expected/slotModelValueTest.vue
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (7)
packages/vue-generator/src/generator/vue/sfc/generateTemplate.js (2)

13-13: Ensure getImportMap is properly utilized

You have imported getImportMap at line 13, but please verify that it's correctly utilized in the code to prevent any unused imports.


158-175: Validate deletion of props.columns after transformation

After transforming props.columns to children components, you delete props.columns. Ensure that props.columns is not used elsewhere in the codebase after this deletion to prevent unintended side effects.

Run the following script to search for usages of props.columns after this point:

✅ Verification successful

props.columns deletion is properly implemented

The deletion of props.columns is safe as it occurs:

  • After all its usages are complete
  • Only when slots transformation is performed
  • Within a properly scoped context
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if `props.columns` is used after deletion in `handleTinyGrid`.

# Search for `props.columns` in files excluding `generateTemplate.js`
rg "props\.columns" --glob '!generateTemplate.js'

Length of output: 603


Script:

#!/bin/bash
# Check usage of props.columns within generateTemplate.js
rg "props\.columns" packages/vue-generator/src/generator/vue/sfc/generateTemplate.js -A 2 -B 2

# Check the function context where deletion occurs
ast-grep --pattern 'function $FUNC($_) {
  $$$
  delete props.columns
  $$$
}'

Length of output: 714

packages/vue-generator/src/generator/vue/sfc/genSetupSFC.js (1)

214-214: Confirm the placement of handleTinyGrid in defaultComponentHooks

Moving handleTinyGrid from defaultAttributeHook to defaultComponentHooks changes when this hook is executed. Ensure this change aligns with the intended hook execution order and that it doesn't affect other component processing logic.

packages/vue-generator/test/testcases/sfc/case01/expected/FormTable.vue (1)

57-58: Ensure TinyIconDel is correctly defined

Verify that TinyIconDel is properly imported and initialized to avoid runtime errors when rendering the icon.

packages/vue-generator/test/testcases/sfc/case01/componentsMap.json (1)

30-36: LGTM! Verify component version compatibility.

The addition of TinyGridColumn component follows the established patterns and aligns with the grid slot generation feature.

Run this script to verify the version compatibility with other @opentiny/vue components:

✅ Verification successful

Version compatibility verified ✓

The TinyGridColumn component uses version ^3.10.0, which is consistent with all other @opentiny/vue components in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check version compatibility across @opentiny/vue components
# Expect: All components should use the same version

rg -g '*.json' '"@opentiny/vue"' | grep '"version"' | sort | uniq -c

Length of output: 70


Script:

#!/bin/bash
# Find all componentsMap.json files and extract package + version info for @opentiny/vue
fd componentsMap.json --exec sh -c 'echo "=== $1 ==="; jq -r ".[] | select(.package == \"@opentiny/vue\") | \"\(.componentName): \(.version)\"" {}' sh {}

Length of output: 396

packages/vue-generator/test/testcases/sfc/slotModelValue/page.schema.json (2)

2-90: LGTM! Well-structured state management for grid columns.

The move to state-based column management improves maintainability and reusability.


119-122: Implement error handling for undefined state.columns.

The JSExpression accessing state.columns lacks error handling.

Consider adding a default empty array to prevent runtime errors:

  "columns": {
    "type": "JSExpression",
-   "value": "state.columns"
+   "value": "state.columns || []"
  },

@chilingling chilingling force-pushed the feat/tinyvueGridGenCode branch from 8fe57a9 to 172f3fb Compare February 8, 2025 02:24
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

🧹 Nitpick comments (2)
packages/engine-cli/template/designer/public/mock/bundle.json (2)

10181-10201: Missing component configuration properties.

The component configuration is missing several important properties that would help define its behavior and integration capabilities.

Add the following configuration properties:

"configure": {
  "loop": true,
  "condition": true,
  "styles": true,
  "isContainer": false,
  "isModal": false,
  "nestingRule": {
    "childWhitelist": "",
-   "parentWhitelist": "",
+   "parentWhitelist": ["TinyGrid"],
    "descendantBlacklist": "",
    "ancestorWhitelist": ""
  },
+ "shortcuts": {
+   "properties": ["field", "title", "width"]
+ },
+ "rootSelector": ".tiny-grid-column",
  "isNullNode": false,
  "isLayout": false
}

10155-10159: Enhance component metadata.

The component metadata could be improved with more descriptive information.

{
  "icon": "grid",
  "name": {
    "zh_CN": "表格行"
  },
+ "description": "TinyVue Grid的列组件,用于定义表格的列配置,支持自定义渲染、排序、过滤等功能",
+ "docUrl": "https://opentiny.design/tiny-vue/zh-CN/component/grid",
+ "screenshot": "",
+ "tags": "grid,table,column",
+ "keywords": "表格,列,grid column"
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8fe57a9 and 172f3fb.

📒 Files selected for processing (4)
  • designer-demo/public/mock/bundle.json (1 hunks)
  • mockServer/src/assets/json/appinfo.json (1 hunks)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json (1 hunks)
  • packages/engine-cli/template/designer/public/mock/bundle.json (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (6)
mockServer/src/assets/json/appinfo.json (1)

26959-27006: New Component Entry for TinyGridColumn

This new JSON block introduces the "TinyGridColumn" component into the application configuration. Please verify that:

  • All required keys (icon, name, component, description, etc.) are consistent with similar component entries.
  • The "schema" field’s "properties" is currently an empty array. Confirm that this type (array) is intended, as other components might use an object/dictionary here.
  • The "docUrl", "tags", and "keywords" are empty. If documentation or additional metadata becomes available soon, consider updating these fields.
  • The configuration flags (e.g., "loop", "condition", "styles", etc.) and the "nestingRule" structure are aligned with project standards for component definitions.
mockServer/src/mock/get/app-center/v1/apps/schema/918.json (1)

1907-1913: New TinyGridColumn Entry: Verify Consistency and Integration.
The new component mapping for "TinyGridColumn" is correctly structured—all required keys ("componentName", "package", "exportName", "destructuring", "version") are present and formatted consistently with the existing mappings in this file. Please confirm that version "0.1.16" is the intended release for this update and that downstream generators and templates properly reference this component.

designer-demo/public/mock/bundle.json (3)

10155-10202: New TinyGridColumn component added with minimal configuration.

A new component TinyGridColumn has been added to the bundle with empty schema properties and events. This aligns with the PR objective of introducing grid slot generation code to template.

Key observations:

  • The component is properly registered with the correct npm package info
  • The schema is intentionally left empty, likely to be populated based on usage
  • Basic configuration like loop, condition, styles etc. are set appropriately

10181-10201: Component configuration follows best practices.

The component configuration follows the standard pattern used by other components in the bundle:

  • Proper loop and condition flags
  • Styles enabled
  • Container flag set appropriately
  • Modal flag disabled
  • Nesting rules defined
  • Root selector specified
  • Context menu actions configured

10167-10170: Verify npm package configuration.

The npm package configuration needs verification to ensure the correct package name and export name are used:

packages/engine-cli/template/designer/public/mock/bundle.json (1)

10155-10202: Verify component integration with TinyGrid.

Need to verify that this new component properly integrates with the existing TinyGrid component.

@hexqi hexqi added this to the v2.3.0 milestone Feb 14, 2025
@hexqi hexqi merged commit 11f9244 into opentiny:refactor/develop Feb 18, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request refactor-main refactor/develop branch feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants