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: select table cell to set attributes #440

Merged
merged 2 commits into from
Dec 16, 2024

Conversation

liuchuzhang
Copy link
Contributor

@liuchuzhang liuchuzhang commented Dec 16, 2024

Changes Overview

Implementation Approach

Testing Done

Verification Steps

Additional Notes

Checklist

  • I have created a changeset for this PR if necessary.
  • My changes do not break the library.
  • I have added tests where applicable.
  • I have followed the project guidelines.
  • I have fixed any lint issues.

Related Issues

Close #438

Summary by CodeRabbit

  • New Features

    • Introduced a menu property to the CellProperty class, enhancing its functionality with a specific identifier.
    • Added a menu property to the TableProperty class, providing a distinct identifier for table-related actions.
    • Enabled users to select a table cell and set its attributes, enhancing table editing capabilities.
  • Bug Fixes

    • Simplified the logic in the isDisabled method for better performance regarding table node selection.
  • Improvements

    • Enhanced the getModalContentElem method to improve how properties are set based on selected cells in the editor.

Copy link

changeset-bot bot commented Dec 16, 2024

🦋 Changeset detected

Latest commit: ccc359d

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@wangeditor-next/table-module Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

The changes involve modifications to the CellProperty and TableProperty classes in the table module. A new menu property is introduced to both classes, with CellProperty having a value of 'cell' and TableProperty having a value of 'table'. The TableProperty class's getModalContentElem method is enhanced to support batch selection and setting of cell properties, allowing for more flexible cell property modifications.

Changes

File Change Summary
packages/table-module/src/module/menu/CellProperty.ts Added readonly menu = 'cell' property
packages/table-module/src/module/menu/TableProperty.ts - Added readonly menu: string = 'table' property
- Modified import statements
- Updated getModalContentElem method to support batch cell property setting

Assessment against linked issues

Objective Addressed Explanation
Batch cell property setting [#438]
Support cell alignment modification No specific implementation for alignment modification is detailed.
Support border property modification No specific implementation for border property modification is detailed.
Support background color modification No specific implementation for background color modification is detailed.

Poem

🐰 Hop, hop, through tables we go,
Cells selected, properties in tow,
Batch magic with a rabbit's flair,
Transforming grids without a care!
Code leaps forward, spreadsheets gleam! 🎉


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.

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

🧹 Nitpick comments (2)
packages/table-module/src/module/menu/TableProperty.ts (2)

9-9: Consider importing types for better type safety

The import of EDITOR_TO_SELECTION suggests it's a WeakMap. Consider importing its type for better type safety.

-import { Editor, Transforms } from 'slate'
+import { Editor, Transforms, NodeEntry } from 'slate'
 
 // ... other imports ...
-import { EDITOR_TO_SELECTION } from '../weak-maps'
+import type { EditorSelectionMap } from '../weak-maps'
+import { EDITOR_TO_SELECTION } from '../weak-maps'

Also applies to: 21-21


189-193: Optimize performance for bulk operations

The nested forEach loops for applying properties to selected cells could be optimized.

Consider using a more efficient approach:

-        selection.forEach(row => {
-          row.forEach(cell => {
-            Transforms.setNodes(editor, props, { at: cell[0][1] })
-          })
-        })
+        // Batch update all selected cells at once
+        const cellPaths = selection.flat().map(cell => cell[0][1])
+        Transforms.setNodes(editor, props, { at: cellPaths })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9ea9a73 and 2bc8bcf.

📒 Files selected for processing (2)
  • packages/table-module/src/module/menu/CellProperty.ts (1 hunks)
  • packages/table-module/src/module/menu/TableProperty.ts (4 hunks)
🔇 Additional comments (3)
packages/table-module/src/module/menu/CellProperty.ts (1)

19-20: LGTM: Clean implementation of menu identifier

The addition of the menu property with value 'cell' is well-integrated with the parent TableProperty class's selection handling mechanism.

packages/table-module/src/module/menu/TableProperty.ts (2)

34-35: LGTM: Clear menu identifier implementation

The menu property addition provides a clear identifier for distinguishing between table and cell property operations.


186-196: Verify the selection state persistence

The code relies on EDITOR_TO_SELECTION to maintain selection state. We should verify its lifecycle management.

✅ Verification successful

Based on the search results, I can now generate the final response:

Selection state is properly managed through WeakMap lifecycle

The codebase shows proper lifecycle management of the EDITOR_TO_SELECTION WeakMap:

  • Selection state is set in withSelection plugin when operations are applied
  • Selection is cleaned up via delete() in TableCursor.clearSelection()
  • WeakMap usage ensures automatic cleanup when editor is garbage collected
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for WeakMap usage and cleanup
rg -A 5 "EDITOR_TO_SELECTION" 

# Look for selection cleanup on editor state changes
ast-grep --pattern 'EDITOR_TO_SELECTION.delete($_)'

Length of output: 12068

Comment on lines +186 to +196
const selection = EDITOR_TO_SELECTION.get(editor)

if (this.menu === 'cell' && !!selection?.length) {
selection.forEach(row => {
row.forEach(cell => {
Transforms.setNodes(editor, props, { at: cell[0][1] })
})
})
} else {
Transforms.setNodes(editor, props, { at: path })
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and type safety for selection operations

The selection handling code needs additional safety checks:

  1. Missing null/undefined check for EDITOR_TO_SELECTION.get(editor)
  2. No type validation for selection data structure
  3. No error handling for failed transformations

Consider implementing these safety measures:

-      const selection = EDITOR_TO_SELECTION.get(editor)
+      const selection = EDITOR_TO_SELECTION.get(editor) ?? null
+      
+      try {
         if (this.menu === 'cell' && !!selection?.length) {
+          // Validate selection structure
+          if (!Array.isArray(selection) || !selection.every(row => Array.isArray(row))) {
+            throw new Error('Invalid selection structure')
+          }
+
           selection.forEach(row => {
             row.forEach(cell => {
+              if (!Array.isArray(cell?.[0]?.[1])) {
+                throw new Error('Invalid cell path')
+              }
               Transforms.setNodes(editor, props, { at: cell[0][1] })
             })
           })
         } else {
           Transforms.setNodes(editor, props, { at: path })
         }
+      } catch (error) {
+        console.error('Failed to apply table properties:', error)
+        // Consider showing user feedback
+      }
📝 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
const selection = EDITOR_TO_SELECTION.get(editor)
if (this.menu === 'cell' && !!selection?.length) {
selection.forEach(row => {
row.forEach(cell => {
Transforms.setNodes(editor, props, { at: cell[0][1] })
})
})
} else {
Transforms.setNodes(editor, props, { at: path })
}
const selection = EDITOR_TO_SELECTION.get(editor) ?? null
try {
if (this.menu === 'cell' && !!selection?.length) {
// Validate selection structure
if (!Array.isArray(selection) || !selection.every(row => Array.isArray(row))) {
throw new Error('Invalid selection structure')
}
selection.forEach(row => {
row.forEach(cell => {
if (!Array.isArray(cell?.[0]?.[1])) {
throw new Error('Invalid cell path')
}
Transforms.setNodes(editor, props, { at: cell[0][1] })
})
})
} else {
Transforms.setNodes(editor, props, { at: path })
}
} catch (error) {
console.error('Failed to apply table properties:', error)
// Consider showing user feedback
}

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

🧹 Nitpick comments (1)
.changeset/warm-garlics-wave.md (1)

5-5: Enhance the changeset description

The current description is too brief. Consider adding:

  • Detailed explanation of the new feature
  • Usage examples
  • Any changes to existing APIs
  • Migration steps if applicable

Here's a suggested template:

feat: select table cell to set attributes

This change introduces the ability to select table cells and modify their attributes:
- Feature: [describe the main functionality]
- Usage: [provide example code]
- API Changes: [list any API modifications]
- Migration: [if applicable]
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2bc8bcf and ccc359d.

📒 Files selected for processing (1)
  • .changeset/warm-garlics-wave.md (1 hunks)

Comment on lines +1 to +3
---
"@wangeditor-next/table-module": patch
---
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider using "minor" instead of "patch" version bump

According to semantic versioning (semver), new features should increment the minor version, while patch versions are reserved for backwards-compatible bug fixes. Since this change introduces a new feature for table cell attribute selection, it should use a "minor" bump instead.

Apply this diff to fix the version bump:

---
-"@wangeditor-next/table-module": patch
+"@wangeditor-next/table-module": minor
---
📝 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
---
"@wangeditor-next/table-module": patch
---
---
"@wangeditor-next/table-module": minor
---

@cycleccc cycleccc merged commit d0bb5fc into wangeditor-next:master Dec 16, 2024
2 checks passed
@liuchuzhang liuchuzhang deleted the feat/table-attr branch December 17, 2024 00:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

希望表格可以批量选中单元格设置属性
2 participants