Skip to content

Conversation

jiji-hoon96
Copy link

@jiji-hoon96 jiji-hoon96 commented Sep 2, 2025

  • Fixed sorting logic in RowSorting.ts to properly clear existing multi-sort when clicking without shift key
  • Added comprehensive tests to verify the fix works correctly
  • Ensures single column click replaces all existing sorts
  • Maintains existing behavior for shift+click multi-sort

Fixes #6070

Summary by CodeRabbit

  • New Features

    • Simplified column sorting: a regular click now replaces existing multi-column sorts with the clicked column; if only one column is sorted, clicking toggles its direction. Shift-click still preserves/extends multi-sort.
  • Tests

    • Added comprehensive tests for sorting interactions, covering single-click replace, shift-click multi-sort, direction toggling, and toggle handler behavior.

- Fixed sorting logic in RowSorting.ts to properly clear existing multi-sort when clicking without shift key
- Added comprehensive tests to verify the fix works correctly
- Ensures single column click replaces all existing sorts
- Maintains existing behavior for shift+click multi-sort

Fixes TanStack#6070
Copy link

coderabbitai bot commented Sep 2, 2025

Walkthrough

Refactors non-multi-sort behavior in RowSorting to clear existing multi-column sorts on normal clicks unless exactly one sort exists, in which case it toggles that column. Adds a new Vitest test suite validating single- and multi-sort transitions, shift vs non-shift clicks, and handler behavior.

Changes

Cohort / File(s) Summary
Row sorting logic update
packages/table-core/src/features/RowSorting.ts
Adjusts non-shift click logic: toggles only when exactly one sort exists for the same column; otherwise replaces to single-column sort. Adds inline comments clarifying behavior.
Sorting behavior tests
packages/table-core/tests/RowSorting.test.ts
New Vitest suite covering: clearing multi-sort on non-shift click, preserving with shift, single-sort toggling, replacing multi-sort on different column non-shift click, and getToggleSortingHandler with/without shift.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as ColumnHeader
  participant Table as Table Core
  participant RS as RowSorting

  User->>UI: Click column header (with/without Shift)
  UI->>Table: onClick({ columnId, shiftKey })
  Table->>RS: toggleSorting(columnId, shiftKey)

  alt shiftKey = true (multi-sort)
    RS->>Table: Add/Toggle column in sorting array (preserve others)
  else shiftKey = false (single-sort)
    alt existing sorts length == 1 and same column
      RS->>Table: Toggle sort direction for column
    else existing sorts length != 1 or different column
      RS->>Table: Replace sorting with [column] only
    end
  end

  Table-->>UI: Updated sorting state
  UI-->>User: Re-rendered rows with new order
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Ensure multi-sort is removed when clicking a column header without Shift after a multi-sort is active (#6070)
Preserve multi-sort when Shift-clicking additional columns (#6070)

Poem

I twitch my ears at columns tall,
A single tap—away they fall!
Shift held tight, a duo sings,
Without it, only one takes wings.
Sorting burrows neat and bright—
Click, click—the rows align just right. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/table-core/src/features/RowSorting.ts (1)

369-372: Pass the multi flag to getNextSortingOrder to respect enableMultiRemove

Without passing multi, removal in multi-sort mode may be allowed even when enableMultiRemove is false.

-      const nextSortingOrder = column.getNextSortingOrder()
+      const nextSortingOrder = column.getNextSortingOrder(multi)
🧹 Nitpick comments (3)
packages/table-core/src/features/RowSorting.ts (2)

375-376: Remove unused variable existingIndex

Minor cleanup; it’s computed but never used.

-        const existingIndex = old?.findIndex(d => d.id === column.id)

391-396: Refresh the comment to reflect the refined behavior

After the fix above, “always replace” is no longer accurate when nextSortingOrder is false; we now “remove”. Tweak the comment accordingly.

packages/table-core/tests/RowSorting.test.ts (1)

27-206: Add a test to respect enableMultiRemove=false with shift toggles

Ensures getNextSortingOrder receives multi=true and honors the gating.

Proposed test:

it('does not remove sort on shift toggle when enableMultiRemove is false', () => {
  let sorting = [
    { id: 'firstName', desc: false }, // first sort dir for strings is 'asc'
    { id: 'lastName', desc: true },
  ]

  const table = createTable<Person>({
    data: defaultData,
    columns: defaultColumns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onStateChange() {},
    renderFallbackValue: '',
    state: { sorting },
    enableMultiRemove: false,
    onSortingChange: updater => {
      sorting = typeof updater === 'function' ? updater(sorting) : updater
    },
  })

  const firstName = table.getColumn('firstName')
  firstName?.toggleSorting(undefined, true) // shift toggle

  // Should toggle to 'desc' (not remove), and keep lastName
  expect(sorting).toEqual([
    { id: 'firstName', desc: true },
    { id: 'lastName', desc: true },
  ])
})
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9c62cf2 and 00287bd.

📒 Files selected for processing (2)
  • packages/table-core/src/features/RowSorting.ts (1 hunks)
  • packages/table-core/tests/RowSorting.test.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/table-core/tests/RowSorting.test.ts (3)
packages/table-core/src/core/table.ts (1)
  • createTable (283-527)
packages/table-core/src/utils/getCoreRowModel.ts (1)
  • getCoreRowModel (5-82)
packages/table-core/src/utils/getSortedRowModel.ts (1)
  • getSortedRowModel (5-121)
🔇 Additional comments (7)
packages/table-core/tests/RowSorting.test.ts (7)

27-58: LGTM: verifies clearing multi-sort on simple click

This test accurately captures the intended UX regression and the fix. Nice.


60-88: LGTM: shift+click multi-sort path preserved

Covers additive behavior; assertions look good.


90-114: LGTM: single-sort toggling works

Good sanity check for the non-multi path.


115-142: LGTM: replacing multi-sort by clicking a different column

Confirms the primary UX expectation.


144-173: Handler test is solid; relies on inferred first sort direction

Looks correct given age is numeric (desc first). No change needed.


175-206: LGTM: handler with shift maintains existing sorts

Covers the event-based multi path.


27-206: Add test for cycling to “none” in multi-sort clear scenario
Ensure toggling a column transitions to an empty sort array when the next state is “none” during a multi→single click. Example to add at packages/table-core/tests/RowSorting.test.ts:

it('clears to no sorting when next order is remove on normal click', () => {
  // age defaults to 'desc' first; set it to 'asc' so next is 'none'
  let sorting = [
    { id: 'age', desc: false }, // asc
    { id: 'lastName', desc: true },
  ]

  const table = createTable<Person>({
    data: defaultData,
    columns: defaultColumns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onStateChange() {},
    renderFallbackValue: '',
    state: { sorting },
    onSortingChange: updater => {
      sorting = typeof updater === 'function' ? updater(sorting) : updater
    },
  })

  const ageColumn = table.getColumn('age')
  ageColumn?.toggleSorting(undefined, false) // normal click

  expect(sorting).toEqual([]) // should remove all sorts
})

Comment on lines +391 to 399
// Normal mode - always replace when not in multi-sort mode
// This ensures that clicking without shift key clears existing multi-sort
if (existingSorting && old?.length === 1) {
// Only one column sorted, so we can toggle
sortAction = 'toggle'
} else {
// Multiple columns sorted or no existing sort, replace all
sortAction = 'replace'
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Honor “remove” (none) state when clearing multi-sort with a normal click

When nextSortingOrder is false (enableSortingRemoval path), the non-multi branch always “replace”s and ends up forcing a sort with desc=false instead of removing sorting entirely. That breaks the expected cycle 'desc' → 'asc' → 'none' in the multi→single transition.

Apply this diff to respect the remove state:

-          // Normal mode - always replace when not in multi-sort mode
-          // This ensures that clicking without shift key clears existing multi-sort
-          if (existingSorting && old?.length === 1) {
-            // Only one column sorted, so we can toggle
-            sortAction = 'toggle'
-          } else {
-            // Multiple columns sorted or no existing sort, replace all
-            sortAction = 'replace'
-          }
+          // Normal mode - clear existing multi-sort on simple click
+          if (existingSorting && old?.length === 1) {
+            // Only one column sorted, so we can toggle
+            sortAction = 'toggle'
+          } else {
+            // Multiple columns sorted or no existing sort
+            // If next state is "remove", clear all sorting rather than forcing a sort
+            sortAction =
+              !hasManualValue && nextSortingOrder === false ? 'remove' : 'replace'
+          }
📝 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
// Normal mode - always replace when not in multi-sort mode
// This ensures that clicking without shift key clears existing multi-sort
if (existingSorting && old?.length === 1) {
// Only one column sorted, so we can toggle
sortAction = 'toggle'
} else {
// Multiple columns sorted or no existing sort, replace all
sortAction = 'replace'
}
// Normal mode - clear existing multi-sort on simple click
if (existingSorting && old?.length === 1) {
// Only one column sorted, so we can toggle
sortAction = 'toggle'
} else {
// Multiple columns sorted or no existing sort
// If next state is "remove", clear all sorting rather than forcing a sort
sortAction =
!hasManualValue && nextSortingOrder === false ? 'remove' : 'replace'
}
🤖 Prompt for AI Agents
In packages/table-core/src/features/RowSorting.ts around lines 391 to 399, the
non-multi branch always sets sortAction = 'replace' which forces a sort instead
of honoring the "remove" (none) state when nextSortingOrder is false; change the
logic so that when existingSorting && old?.length === 1 you choose between
'toggle' and 'remove' based on nextSortingOrder (i.e., if nextSortingOrder ===
false use 'remove', otherwise use 'toggle'), and otherwise keep 'replace' for
multi/no-existing-sort cases so the desc→asc→none cycle is preserved during
multi→single transitions.

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.

Multi sort doesn't get removed when clicking on other column header without shift key
1 participant