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(tree-select): [tree-select] add data init and optimize demo docs #2538

Merged
merged 3 commits into from
Nov 21, 2024

Conversation

kagol
Copy link
Member

@kagol kagol commented Nov 20, 2024

PR

主要解决 tree-select 的以下问题:

  • 折叠标签demo:初始化有问题,应该显示 label,实际显示的是 value(场景1选择一个选项,场景2/3显示异常,尺寸/禁用demo同样能复现,本质是缺少数据初始化的逻辑) -- 主要是迁移之前 select 组件中关于 tree 相关的函数逻辑到 tree-select 组件中
  • 尺寸demo:没有按照从大到小的顺序排列
  • 禁用demo:单选、多选的初始化有问题 -- 同 1

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)

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:

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

Release Notes

  • New Features

    • Default selected values for the tiny-tree-select component updated to improve user experience with pre-selected nodes.
    • Enhanced filtering and selection capabilities in the tree selection component.
  • Bug Fixes

    • Adjustments made to ensure correct initialization of selected values across various tree select components.
  • Documentation

    • Improved clarity in template bindings for better understanding of component functionality.

@kagol kagol added the enhancement New feature or request label Nov 20, 2024
Copy link

coderabbitai bot commented Nov 20, 2024

Walkthrough

The pull request introduces several modifications across various Vue component files related to the tree-select functionality. Key changes include updates to the default values for the value property in multiple components, altering the initial selections for the tiny-tree-select component. Additionally, new functions are added to the tree-select module, enhancing its capabilities for filtering, selection handling, and data transformation. The template structure remains mostly intact, with some reordering of components and bindings to improve clarity and functionality.

Changes

File Path Change Summary
examples/sites/demos/pc/app/tree-select/basic-usage-composition-api.vue Updated value from '' to 4.
examples/sites/demos/pc/app/tree-select/basic-usage.vue Updated value from '' to 10.
examples/sites/demos/pc/app/tree-select/collapse-tags-composition-api.vue Updated value from ref([]) to ref([9, 6]).
examples/sites/demos/pc/app/tree-select/collapse-tags.vue Updated value from [] to [9, 6].
examples/sites/demos/pc/app/tree-select/multiple-composition-api.vue Updated value from ref([]) to ref([9, 6]).
examples/sites/demos/pc/app/tree-select/multiple.vue Updated value from [] to [9, 6].
examples/sites/demos/pc/app/tree-select/size-composition-api.vue Reordered <tiny-tree-select> components; no other changes.
examples/sites/demos/pc/app/tree-select/size.vue Reordered <tiny-tree-select> components; no other changes.
packages/renderless/src/tree-select/index.ts Added functions: filter, nodeClick, check, getTreeData, getPluginOption, getCheckedData, mounted.
packages/renderless/src/tree-select/vue.ts Added imports and updated function signatures; restructured api export.
packages/vue/src/tree-select/src/pc.vue Adjusted order of bindings in template; no changes to props or methods.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant TinyTreeSelect
    participant TreeSelectAPI

    User->>TinyTreeSelect: Select a node
    TinyTreeSelect->>TreeSelectAPI: nodeClick()
    TreeSelectAPI-->>TinyTreeSelect: Update selected data
    TinyTreeSelect->>User: Display updated selection
Loading

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • zzcr

Poem

🐰 In the garden of trees, where selections bloom,
A rabbit hops in, dispelling the gloom.
With values now set, from four to ten,
The tiny tree select is ready again!
So click and explore, let choices take flight,
In this vibrant tree world, all feels just right! 🌳✨


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.

@kagol kagol changed the title feat(tree-select): add data init and optimize demo docs feat(tree-select): [tree-select] add data init and optimize demo docs Nov 20, 2024
Copy link

[e2e-test-warn]
The component to be tested is missing.

The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug".

Please make sure you've read our contributing guide

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.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (8)
examples/sites/demos/pc/app/tree-select/multiple-composition-api.vue (1)

9-9: Consider adding comments to explain the pre-selected values.

Adding a brief comment explaining why these specific nodes are pre-selected would improve the demo's documentation and make it more maintainable.

+// Pre-select "三级 1-1-1" (9) and "二级 2-2" (6) to demonstrate multiple selection
const value = ref([9, 6])
examples/sites/demos/pc/app/tree-select/basic-usage.vue (1)

14-14: Consider adding a comment to explain the pre-selected value

To improve maintainability, consider adding a comment explaining that 10 corresponds to "三级 1-1-2" and why this specific node was chosen as the default selection.

+      // Pre-select "三级 1-1-2" node to demonstrate initial state
       value: 10,
examples/sites/demos/pc/app/tree-select/multiple.vue (1)

14-14: Consider adding comments to explain pre-selected values

To improve demo documentation, consider adding a comment explaining why these specific nodes are pre-selected and what they demonstrate.

+      // Pre-select nodes from different levels (level 3 and level 2) 
+      // to demonstrate hierarchical multiple selection capability
       value: [9, 6],
examples/sites/demos/pc/app/tree-select/collapse-tags-composition-api.vue (1)

20-20: LGTM! Consider adding a comment explaining the initial selection.

The initial value [9, 6] is well-chosen for demonstrating tag collapsing functionality, as it includes both a deep-nested selection and a long-text selection.

Consider adding a comment explaining the selection:

+// Initialize with "三级 1-1-1" and a long text node to demonstrate tag collapsing
const value = ref([9, 6])
examples/sites/demos/pc/app/tree-select/size.vue (1)

7-8: Further optimize the size demonstration order

While the reordering is a step in the right direction, consider these improvements for better clarity and user experience:

  1. Since 'default' and 'medium' sizes are equivalent, consider removing one to avoid redundancy
  2. Maintain a clear size progression from largest to smallest

Consider this structure:

-    <p>medium</p>
-    <tiny-tree-select v-model="value" size="medium" multiple :tree-op="treeOp"></tiny-tree-select>
-    <p>默认</p>
-    <tiny-tree-select v-model="value" multiple :tree-op="treeOp"></tiny-tree-select>
-    <p>small</p>
-    <tiny-tree-select v-model="value" size="small" multiple :tree-op="treeOp"> </tiny-tree-select>
-    <p>mini</p>
-    <tiny-tree-select v-model="value" size="mini" multiple :tree-op="treeOp"> </tiny-tree-select>
+    <p>默认 (Medium)</p>
+    <tiny-tree-select v-model="value" multiple :tree-op="treeOp"></tiny-tree-select>
+    <p>Small</p>
+    <tiny-tree-select v-model="value" size="small" multiple :tree-op="treeOp"> </tiny-tree-select>
+    <p>Mini</p>
+    <tiny-tree-select v-model="value" size="mini" multiple :tree-op="treeOp"> </tiny-tree-select>
examples/sites/demos/pc/app/tree-select/collapse-tags.vue (1)

25-25: Consider adding comments to explain the pre-selected values.

To improve maintainability, consider adding a comment explaining that these values were chosen to demonstrate collapsible behavior with varied label lengths (short: "三级 1-1-1" and long: OpenTiny description).

+      // Pre-selected values to demonstrate collapsible behavior:
+      // 9: "三级 1-1-1" (short label)
+      // 6: "OpenTiny..." (long label)
       value: [9, 6],
packages/vue/src/tree-select/src/pc.vue (1)

19-25: Consider adding test cases for the filter and node selection functionality.

The addition of filter-node-method and node-click handler enhances the component's functionality. To ensure reliability:

  1. Add test cases for filtering behavior
  2. Add test cases for node selection in both single and multiple modes
  3. Document the expected behavior in the component's documentation
packages/renderless/src/tree-select/index.ts (1)

3-5: Ensure consistency in code comments language

The code comments are currently written in Chinese. For consistency and to accommodate international collaboration, please translate the comments into English.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d8d1075 and 88a9325.

📒 Files selected for processing (11)
  • examples/sites/demos/pc/app/tree-select/basic-usage-composition-api.vue (1 hunks)
  • examples/sites/demos/pc/app/tree-select/basic-usage.vue (1 hunks)
  • examples/sites/demos/pc/app/tree-select/collapse-tags-composition-api.vue (1 hunks)
  • examples/sites/demos/pc/app/tree-select/collapse-tags.vue (1 hunks)
  • examples/sites/demos/pc/app/tree-select/multiple-composition-api.vue (1 hunks)
  • examples/sites/demos/pc/app/tree-select/multiple.vue (1 hunks)
  • examples/sites/demos/pc/app/tree-select/size-composition-api.vue (1 hunks)
  • examples/sites/demos/pc/app/tree-select/size.vue (1 hunks)
  • packages/renderless/src/tree-select/index.ts (3 hunks)
  • packages/renderless/src/tree-select/vue.ts (2 hunks)
  • packages/vue/src/tree-select/src/pc.vue (1 hunks)
🧰 Additional context used
🪛 Biome
packages/renderless/src/tree-select/vue.ts

[error] 9-9: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (16)
examples/sites/demos/pc/app/tree-select/basic-usage-composition-api.vue (1)

9-9: LGTM! Verify the default selection.

The initialization of value to 4 is valid and corresponds to "二级 1-1" in the tree structure. This change aligns with the PR objectives to fix initialization issues.

examples/sites/demos/pc/app/tree-select/multiple-composition-api.vue (1)

9-9: LGTM! Please verify the pre-selected values.

The initialization with [9, 6] (corresponding to "三级 1-1-1" and "二级 2-2") aligns with the PR objectives to fix initialization issues. Please verify that these specific values effectively demonstrate the intended multiple selection behavior in the demo.

examples/sites/demos/pc/app/tree-select/basic-usage.vue (1)

14-14: LGTM! Initialization improvement

The change from empty string to 10 provides a better demonstration of the component by showing a pre-selected state. This value corresponds to the "三级 1-1-2" node, which is a good choice for demonstrating the tree-select's capabilities.

examples/sites/demos/pc/app/tree-select/multiple.vue (1)

14-14: LGTM! Pre-selected values improve demo clarity

The initialization with [9, 6] effectively demonstrates the multiple selection capability by pre-selecting "三级 1-1-1" and "二级 2-2" nodes.

packages/renderless/src/tree-select/vue.ts (4)

1-3: LGTM! Imports and exports are well-organized.

The new utility imports align with the PR objectives to fix initialization issues, and the API surface remains stable despite reordering.


5-5: LGTM! Appropriate lifecycle hook addition.

Adding onMounted to the function signature is a good change that supports proper component initialization.


18-25: LGTM! Well-structured API composition.

The API object is properly composed with all necessary methods, and each method receives appropriate dependencies. The new methods support the PR objectives for improving initialization and optimization.


Line range hint 28-34: Consider watch cleanup in component unmount.

While the watch implementation is correct, consider whether cleanup is needed when the component unmounts, especially if the watch might affect external state or resources.

examples/sites/demos/pc/app/tree-select/size-composition-api.vue (1)

Line range hint 1-65: Implementation looks good overall!

The component follows Vue 3 best practices using the Composition API, has proper type definitions, and maintains consistent styling.

examples/sites/demos/pc/app/tree-select/collapse-tags.vue (1)

25-25: LGTM! Initialization fixes the collapsible label demo issue.

The pre-selected values [9, 6] properly demonstrate the component's behavior with both short and long labels, effectively testing the collapsible functionality.

packages/vue/src/tree-select/src/pc.vue (3)

7-9: LGTM! Props ordering change looks good.

The reordering of filterable and multiple props maintains functionality while improving consistency.


14-16: Verify initialization behavior in all scenarios.

The changes to current-node-key and default-checked-keys look correct and should address the initialization issues mentioned in the PR objectives. However, please verify the behavior in:

  • Single selection mode
  • Multiple selection mode
  • When switching between modes

Line range hint 1-29: Add tests and update documentation as mentioned in PR objectives.

The implementation looks good, but as noted in the PR objectives, tests and documentation updates are still pending. Please ensure:

  1. Add unit tests for the modified initialization logic
  2. Update component documentation to reflect the changes
  3. Add examples demonstrating proper usage in different scenarios (single/multiple selection, filtering)

Would you like help with generating test cases or documentation updates?

packages/renderless/src/tree-select/index.ts (3)

121-127: Verify that state.selected is properly defined

In getCheckedData, when state.selected is not an array, the code accesses state.selected[props.valueField]. If state.selected is undefined or does not have the props.valueField property, this could cause a runtime error. Please verify that state.selected is properly defined and contains the expected properties.


138-158: Initialize initialNodes properly in multiple selection

In the multiple selection block, if api.getPluginOption(value) returns an empty array, concatenating it to initialNodes may not include the expected nodes. Ensure that initialNodes accumulates all valid nodes, and handle cases where option could be empty to prevent unintended behavior.


101-107: ⚠️ Potential issue

Handle potential undefined selNode in getPluginOption

In getPluginOption, if no matching node is found, selNode will be undefined. Accessing selNode.currentLabel without checking can lead to runtime errors. Please ensure selNode is defined before accessing its properties.

Apply this diff to handle undefined selNode:

const selNode = find(sourceData, (item) => item[valueField] === value)
const items = []

if (selNode) {
  selNode.currentLabel = selNode[textField]
  items.push(selNode)
}
+ else {
+   // Handle the case when selNode is undefined, if necessary
+ }

Likely invalid or redundant comment.

Comment on lines +9 to +14
childrenName: computed(() => (props.treeOp.props && props.treeOp.props.children) || 'children'),
currentKey: props.modelValue,
defaultCheckedKeys: [],
remoteData: [],
treeData: props.treeOp.data,
value: computed(() => props.modelValue)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve props access safety with optional chaining.

The childrenName computed property should use optional chaining to safely handle cases where props.treeOp.props might be undefined.

-    childrenName: computed(() => (props.treeOp.props && props.treeOp.props.children) || 'children'),
+    childrenName: computed(() => props.treeOp.props?.children || 'children'),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
childrenName: computed(() => (props.treeOp.props && props.treeOp.props.children) || 'children'),
currentKey: props.modelValue,
defaultCheckedKeys: [],
remoteData: [],
treeData: props.treeOp.data,
value: computed(() => props.modelValue)
childrenName: computed(() => props.treeOp.props?.children || 'children'),
currentKey: props.modelValue,
defaultCheckedKeys: [],
remoteData: [],
treeData: props.treeOp.data,
value: computed(() => props.modelValue)
🧰 Tools
🪛 Biome

[error] 9-9: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Comment on lines +7 to +8
<p>small</p>
<tiny-tree-select v-model="value" size="small" multiple :tree-op="treeOp"> </tiny-tree-select>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reorder size variants from largest to smallest

The current order of size variants doesn't follow a logical progression. To improve user comprehension, consider reordering the components from largest to smallest size:

  1. medium
  2. default
  3. small
  4. mini

Apply this reordering to match the PR objective of displaying options from large to small:

  <p>medium</p>
  <tiny-tree-select v-model="value" size="medium" multiple :tree-op="treeOp"></tiny-tree-select>
  <p>默认</p>
  <tiny-tree-select v-model="value" multiple :tree-op="treeOp"></tiny-tree-select>
- <p>small</p>
- <tiny-tree-select v-model="value" size="small" multiple :tree-op="treeOp"> </tiny-tree-select>
  <p>mini</p>
  <tiny-tree-select v-model="value" size="mini" multiple :tree-op="treeOp"> </tiny-tree-select>
+ <p>small</p>
+ <tiny-tree-select v-model="value" size="small" multiple :tree-op="treeOp"> </tiny-tree-select>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<p>small</p>
<tiny-tree-select v-model="value" size="small" multiple :tree-op="treeOp"> </tiny-tree-select>
<p>medium</p>
<tiny-tree-select v-model="value" size="medium" multiple :tree-op="treeOp"></tiny-tree-select>
<p>默认</p>
<tiny-tree-select v-model="value" multiple :tree-op="treeOp"></tiny-tree-select>
<p>mini</p>
<tiny-tree-select v-model="value" size="mini" multiple :tree-op="treeOp"> </tiny-tree-select>
<p>small</p>
<tiny-tree-select v-model="value" size="small" multiple :tree-op="treeOp"> </tiny-tree-select>

Comment on lines +72 to +79
data.forEach((node) => {
node.pId = pId
nodes.push(node)

if (node[state.childrenName] && node[state.childrenName].length > 0) {
getChild(node[state.childrenName], node[props.valueField])
}
})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid mutating input data in getTreeData function

The getTreeData function mutates the input data by assigning node.pId = pId. This could lead to unexpected side effects if the original data is used elsewhere. Consider creating a new node object to prevent data mutation.

Apply this diff to avoid mutating the input data:

const getChild = (data, pId) => {
  data.forEach((node) => {
+   const newNode = { ...node, pId }
+   nodes.push(newNode)
    nodes.push(node)
-   node.pId = pId
-   nodes.push(node)
-   if (node[state.childrenName] && node[state.childrenName].length > 0) {
+   if (newNode[state.childrenName] && newNode[state.childrenName].length > 0) {
      getChild(newNode[state.childrenName], newNode[props.valueField])
    }
  })
}

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

Comment on lines +136 to +171
if (!state.value || state.value.length === 0) return

if (props.multiple) {
let initialNodes = []
if (Array.isArray(state.value)) {
state.value.forEach((value) => {
const option = api.getPluginOption(value)
initialNodes = initialNodes.concat(option)
})
}

vm.$refs.baseSelectRef.updateSelectedData(
initialNodes.map((node) => {
return {
...node,
currentLabel: node[props.textField],
value: node[props.valueField],
isTree: true
}
})
)

state.defaultCheckedKeys = api.getCheckedData()[0]
} else {
const data = api.getPluginOption(state.value)[0]
vm.$refs.baseSelectRef.updateSelectedData({
...data,
currentLabel: data[props.textField],
value: data[props.valueField],
state: {
currentLabel: data[props.textField]
}
})

state.currentKey = data[props.valueField]
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Safely handle undefined data in mounted function

In the mounted function, api.getPluginOption(state.value) may return an empty array if no matching node is found, resulting in data being undefined. Accessing properties of data without checking could lead to runtime errors. Please ensure data is defined before proceeding.

Apply this diff to handle potential undefined data:

const data = api.getPluginOption(state.value)[0]
+ if (data) {
  vm.$refs.baseSelectRef.updateSelectedData({
    ...data,
    currentLabel: data[props.textField],
    value: data[props.valueField],
    state: {
      currentLabel: data[props.textField]
    }
  })

  state.currentKey = data[props.valueField]
+ } else {
+   // Handle the case when data is undefined
+ }

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants