Skip to content

Conversation

@gene9831
Copy link
Collaborator

@gene9831 gene9831 commented Mar 18, 2025

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

【注意】此pr基于 #1221

大纲树支持快捷键,功能与画布保持一致

What is the current behavior?

大纲树不支持快捷键

What is the new behavior?

大纲树支持快捷键

  • 复制粘贴(支持多选) ctrl+cctrl+v
    copy-paste

  • 其他按键(支持多选)如delete
    delete

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced multi-selection on the canvas for smoother selection and toggling between single and multiple items.
    • Improved keyboard interactions with refined hotkey registration and clipboard paste operations.
    • Upgraded tree view component to support multiple active rows for clearer selection feedback.
    • Introduced new computed properties for better state management in components.
    • Added new API functions for managing multi-selection and keyboard events.
  • Refactor

    • Streamlined state management and reactivity across components to ensure more intuitive and responsive interactions.
    • Consolidated multi-selection logic for improved clarity and efficiency.
  • Style

    • Updated focus styling on interactive panels for a cleaner visual experience.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 18, 2025

Walkthrough

The changes update several files across the canvas container and tree plugins. New functions and API properties are added to manage multi-selection and keyboard interactions. The multi-selection logic is refactored by removing caching and single selection state, replacing it with a toggle and refresh mechanism. Vue components update variable names, computed properties, props, and event handling—including click and clipboard paste events—to support enhanced state management and hotkey event registration.

Changes

File(s) Change Summary
packages/canvas/container/index.js Added new imports and updated the exported object to include an api property with useMultiSelect, registerHotkeyEvent, and removeHotkeyEvent.
packages/canvas/container/src/CanvasContainer.vue Renamed variables, introduced computed properties (computedSelectState, updated multiStateLength), removed a watch function, and added control key checks.
packages/canvas/container/src/composables/useMultiSelect.js
packages/canvas/container/src/container.js
Refactored multi-selection logic by removing caching and single-selection state; added toggleMultiSelection and refreshSelectionState; updated functions such as selectNode, clearMultiSelection, and updateRect.
packages/canvas/container/src/keyboard.js Modified handleClipboardPaste to accept an event parameter, centralized clipboard data retrieval, and adjusted key handling logic.
packages/canvas/container/src/components/CanvasAction.vue
packages/canvas/container/src/components/CanvasDivider.vue
packages/canvas/container/src/components/CanvasResizeBorder.vue
Added a conditional check to exit early in CanvasAction.vue, inserted a comment in CanvasDivider.vue, and introduced a new selectState prop in CanvasResizeBorder.vue.
packages/plugins/tree/src/DraggableTree.vue
packages/plugins/tree/src/Main.vue
Modified active row detection to support multiple active rows; updated click event handlers to include the event parameter; added computed property selectedIds, panelRef, and lifecycle hooks for hotkey event management.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CC as CanvasContainer
    participant MS as useMultiSelect
    participant C as Container

    U->>CC: Click event (with/without Ctrl)
    CC->>CC: Check if Ctrl key is pressed
    alt Multiple selection allowed
        CC->>MS: toggleMultiSelection(selectState, isMultiple=true)
        MS-->>CC: Update multiSelectedStates
        CC->>C: refreshSelectionState()
    else Single selection
        CC->>MS: toggleMultiSelection(selectState, isMultiple=false)
        MS-->>CC: Update selection state
    end
Loading
sequenceDiagram
    participant U as User
    participant KB as Keyboard
    participant C as Container
    participant CB as Clipboard

    U->>KB: Paste shortcut (Ctrl+V)
    KB->>C: handleClipboardPaste(event)
    C->>CB: getClipboardSchema(event)
    alt Valid clipboard data
        CB-->>C: Return nodeList, schema, parent
        C->>C: Process paste operation
    else Data missing
        C-->>KB: Early return
    end
Loading

Possibly related PRs

  • feat: enhance canvas foundation capabilities #1055: The changes in the main PR are related to those in the retrieved PR as both involve enhancements to multi-selection functionality and modifications to the CanvasContainer.vue component, specifically in how selection states are managed and utilized.
  • fix: the display is abnormal when clicking back on multiple selected nodes #1201: The changes in the main PR are related to the modifications in the CanvasContainer.vue file of the retrieved PR, specifically regarding the handling of the multiSelectedStates and the toggleMultiSelection function, which are both central to the selection state management.
  • feat: add canvas route bar #967: The changes in the main PR are related to the modifications in the useMultiSelect composable, which is directly utilized in the main PR's updates to the CanvasContainer.vue file, specifically in the management of multi-selection states.

Suggested labels

refactor-main

Suggested reviewers

  • hexqi
  • chilingling

Poem

I’m a little rabbit, hopping with glee,
Code changes abound, as clear as can be.
Multi-selects and hotkeys now lead the way,
In every function, they brighten the day.
With a carrot in hand, I celebrate our spree!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4eb8886 and 5fc89b9.

📒 Files selected for processing (1)
  • packages/canvas/container/src/keyboard.js (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (7)
packages/canvas/container/src/keyboard.js (7)

118-131: Improved clipboard paste handling

The refactoring of handleClipboardPaste to accept an event parameter instead of explicit schema information makes the function more self-contained and cohesive. The added validations for empty nodeList and missing selection state are good defensive programming practices.


149-150: Good use of WeakMap for event filters

Using a WeakMap is an appropriate choice for storing DOM-related event filters, as it allows for proper garbage collection when DOM elements are no longer referenced elsewhere.


152-156: Consistent event filtering implementation

The event filtering mechanism is consistently implemented across both clipboard and keyboard event handlers. This provides a clean way to control event processing based on context.

Also applies to: 174-179


163-163: Updated function call matches new signature

The call to handleClipboardPaste now correctly passes only the event parameter, aligning with the updated function signature.


183-185: Improved conditional handling for arrow keys

The explicit else clause ensures arrow key handling only triggers when modifier keys (Ctrl/Cmd) aren't pressed, preventing unintended side effects when using shortcut combinations.


194-194: Good cleanup of event filter references

Removing entries from the WeakMap when unregistering event handlers prevents potential memory leaks and is a good practice.


197-204: Enhanced hotkey registration with options pattern

The function signature update to accept an options object follows good API design practices by:

  1. Making the function more extensible for future options
  2. Providing a clean mechanism for optional parameters
  3. Using proper validation before storing the event filter

This change enables the outline tree hotkey support mentioned in the PR objectives.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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 the enhancement New feature or request label Mar 18, 2025
@gene9831 gene9831 added this to the v2.4.0 milestone Mar 18, 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: 1

🧹 Nitpick comments (1)
packages/canvas/container/src/composables/useMultiSelect.js (1)

38-53: Added essential refresh function for selection states.

The new refreshSelectionState function is a critical addition that ensures the visual representation of selected nodes stays accurate by updating their position and dimension properties. This is particularly important for multi-selection when the DOM might change.

One suggestion for potential improvement:

 const refreshSelectionState = () => {
   multiSelectedStates.value = multiSelectedStates.value.map((state) => {
     const element = querySelectById(state.id) || getDocument().body
+    // Consider adding a check if the element actually exists before getting its rect
+    // This could prevent issues if an element was removed from the DOM
     const { top, left, width, height } = getRect(element)

     return {
       ...state,
       top,
       left,
       width,
       height
     }
   })

   return multiSelectedStates.value
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7297076 and 81abca7.

📒 Files selected for processing (10)
  • packages/canvas/container/index.js (1 hunks)
  • packages/canvas/container/src/CanvasContainer.vue (6 hunks)
  • packages/canvas/container/src/components/CanvasAction.vue (1 hunks)
  • packages/canvas/container/src/components/CanvasDivider.vue (1 hunks)
  • packages/canvas/container/src/components/CanvasResizeBorder.vue (3 hunks)
  • packages/canvas/container/src/composables/useMultiSelect.js (1 hunks)
  • packages/canvas/container/src/container.js (5 hunks)
  • packages/canvas/container/src/keyboard.js (3 hunks)
  • packages/plugins/tree/src/DraggableTree.vue (4 hunks)
  • packages/plugins/tree/src/Main.vue (6 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/canvas/container/src/container.js (1)
packages/canvas/container/src/composables/useMultiSelect.js (6) (6)
  • useMultiSelect (7:65)
  • useMultiSelect (7:65)
  • clearMultiSelection (55:57)
  • toggleMultiSelection (14:36)
  • multiSelectedStates (5:5)
  • refreshSelectionState (38:53)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (34)
packages/canvas/container/src/components/CanvasAction.vue (1)

487-490: Good performance optimization for watchPostEffect

Adding an early return condition for watchPostEffect when showQuickAction is false prevents unnecessary DOM operations and style calculations. This optimization is especially important for rendering performance when many elements are being selected/deselected.

The comment clearly explains the rationale: allowing watchPostEffect to monitor showQuickAction for reactivity while preventing unnecessary processing.

packages/canvas/container/index.js (2)

2-3: LGTM: Importing hotkey and multi-select functionality

Importing these functions is necessary to support the feature described in the PR title - enabling outline tree hotkey support similar to canvas.


8-9: Good API exposure for hotkey and multi-select functionality

Exposing these functions through the module's API allows other components to access the multi-selection and hotkey functionality in a clean, standardized way.

This change enables the outline tree to leverage the same hotkey and multi-selection capabilities as the canvas, creating a consistent user experience across both interfaces.

packages/canvas/container/src/components/CanvasResizeBorder.vue (3)

19-22: LGTM: Adding selectState as a prop

Adding the selectState as a prop improves component encapsulation and makes dependencies explicit, following Vue best practices.

This refactoring aligns with the PR's goals of making the outline tree work like canvas by standardizing how selection state is passed.


124-124: Correctly using selectState from props

Updated to use the selectState from props instead of an imported value, maintaining consistency with the prop change.


152-153: LGTM: Updated watch function to observe props.selectState

The watch function now correctly observes the selectState prop, ensuring the resize border updates when the selection changes.

packages/plugins/tree/src/DraggableTree.vue (5)

12-12: Multi-selection support added in template.

The condition has been updated to check if a row's ID is included in the activesComputed array instead of using a direct equality check with a single active ID. This change enables support for multiple active rows in the tree.


19-19: Event parameter added to click handler.

The click event is now passed to the handler, which will allow parent components to detect modifier keys (like Ctrl/Cmd) for multi-selection functionality.


63-66: New actives prop added for multi-selection.

A new prop actives has been added with an array type, allowing the component to receive multiple active IDs instead of just a single active ID. This is essential for implementing multi-selection functionality.


89-96: Computed property added for backward compatibility.

The activesComputed property intelligently handles both the legacy single active state and the new multi-selection state. It returns an array with the single active ID if props.active exists and props.actives is empty, otherwise it returns props.actives.


211-212: Updated click handler to pass event to parent.

The handleClickRow method now accepts and forwards the event object to the parent component, which is necessary for detecting modifier keys for multi-selection.

packages/plugins/tree/src/Main.vue (6)

2-2: Plugin panel made keyboard-focusable for hotkey support.

The panel now has a tabindex="0" attribute and a ref="panelRef" for registering hotkey event handlers. These attributes are essential for enabling keyboard interaction with the outline tree.


16-16: Updated tree binding for multi-selection.

The :active prop has been replaced with :actives="selectedIds", which passes an array of selected IDs to enable multi-selection in the tree component.


41-41: Added imports and API for multi-selection and hotkeys.

New imports include lifecycle hooks and APIs for multi-selection and hotkey event handling. The selectedIds computed property transforms the multi-selection state into an array of IDs that the tree component can use.

Also applies to: 75-78


209-213: Enhanced click handler for multi-selection support.

The handleClickRow function now checks for Ctrl/Cmd key presses to support multi-selection. When a modifier key is pressed, the third parameter is passed to selectNode, enabling toggle selection behavior.


220-232: Added hotkey event registration.

Lifecycle hooks register and remove hotkey event handlers on the panel element, ensuring that keyboard shortcuts work when the outline tree has focus. This implementation matches the behavior of the canvas.


258-260: Removed outline for focused panel.

Added CSS to remove the default focus outline while still maintaining keyboard accessibility. This ensures a clean visual appearance without sacrificing functionality.

packages/canvas/container/src/keyboard.js (3)

118-131: Improved clipboard paste handling.

The handleClipboardPaste function has been refactored to:

  1. Accept an event parameter instead of explicit node, schema, and parent parameters
  2. Extract clipboard data directly from the event using getClipboardSchema
  3. Add validation to check if there's clipboard data and a selected state before proceeding
  4. Get the schema and parent from the last selected state

This change streamlines clipboard handling and improves error checking.


155-155: Updated clipboard event handler call.

The call to handleClipboardPaste now passes only the event object, aligned with the function's new signature.


169-171: Fixed keyboard handler logic.

The handlerArrow call is now correctly placed in the else block, ensuring arrow key handling only occurs when modifier keys are not pressed. This fixes a potential conflict between shortcut keys and navigation keys.

packages/canvas/container/src/container.js (5)

122-122: Incorporated multi-selection APIs.

The component now uses the multi-selection API from the useMultiSelect composable, providing a more consistent way to handle multiple selections across the application.


132-132: Updated clear selection logic.

The clearSelect function now uses clearMultiSelection() instead of resetting a single select state, making the selection clearing mechanism more consistent with the multi-selection approach.


393-418: Refactored selection rectangle handling for multi-selection.

The setSelectRect function has been completely refactored to:

  1. Build a selection state object with all necessary properties
  2. Use toggleMultiSelection to handle adding/removing the selection from the multi-selection state
  3. Support an isMultiple flag to enable toggle behavior for multi-selection

This change centralizes selection logic and makes it consistent across the application.


424-429: Added special handling for multi-selection in rect updates.

When multiple items are selected, updateRect now calls refreshSelectionState() to update all selection rectangles, rather than only updating a single selection. This ensures all selection indicators remain accurate.


734-776: Enhanced node selection with multi-selection support.

The selectNode function has been updated to:

  1. Accept an isMultiple parameter to support Ctrl/Cmd+click selection toggling
  2. Set the canvas state differently based on whether there's a single selection or multiple selections
  3. Return different values based on the selection state
  4. Emit consistent selection events

This comprehensive update enables multi-selection while maintaining backward compatibility.

packages/canvas/container/src/CanvasContainer.vue (6)

2-2: Variable naming consistency improvement.

Good change to use a more specific variable name state instead of multiState in the v-for loop and component prop. This enhances code readability and consistency.

Also applies to: 6-6


17-18: Improved state management with computed property.

Great refactoring by replacing the direct selectState with computedSelectState. This computed property provides a more reactive approach to determining the selection state based on the multi-selection array length.


110-113: Enhanced state reactivity with computed property.

Good conversion of multiStateLength from a direct assignment to a computed property. This ensures that the length is always up-to-date when multiSelectedStates changes.


114-120: Well-implemented fallback logic in computed property.

The computedSelectState computed property properly handles different selection states:

  1. Returns the first selected state when exactly one item is selected
  2. Falls back to initialRectState when multiple or no items are selected

This provides consistent behavior for components that expect a single selection state.


132-138: Added multi-selection support with modifier keys.

Good implementation of modifier key detection (isCtrlKey) to support multi-selection, which aligns with standard UX patterns in design tools. The code now checks if Ctrl (or Cmd on Mac) is pressed and passes this information to the selectNode function.


328-328: Updated component exports with new computed property.

Correctly updated the returned properties to include computedSelectState, ensuring the new property is available to the template.

packages/canvas/container/src/composables/useMultiSelect.js (3)

1-2: Cleaner imports with better focus.

Good practice to import only the specific functions needed from the container module. This makes dependencies clearer and can help with tree-shaking.


8-36: Well-implemented toggle selection functionality.

The revised toggleMultiSelection function effectively handles both single and multi-selection modes:

  • For multi-selection (when isMultiple=true), it toggles the node in/out of the selection array
  • For single selection, it replaces the entire selection with just the provided node
  • It also includes good validation to handle invalid state objects

This unified approach simplifies the selection API while supporting both selection modes.


62-62: Updated exported functions to include the new refresh capability.

Correctly updated the returned API to include the new refreshSelectionState function, making it available to consumers of this composable.

hexqi
hexqi previously approved these changes Mar 19, 2025
@hexqi hexqi merged commit 20c3b07 into opentiny:develop Mar 19, 2025
1 check passed
@gene9831 gene9831 deleted the feat/outline-tree-multile-selection branch March 20, 2025 01:17
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