From 828e80b8be13173e27de960b40629c6fad2da11e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 30 Jan 2026 09:07:21 +0000 Subject: [PATCH 1/6] Initial plan From 782fe171a3a55e0069548ebba5000ef8ba141a81 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 30 Jan 2026 09:13:59 +0000 Subject: [PATCH 2/6] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E9=80=8F=E8=A7=86?= =?UTF-8?q?=E8=A1=A8=E7=BB=84=E5=86=85=E6=8E=92=E5=BA=8F=E5=9C=A8=E6=8C=87?= =?UTF-8?q?=E6=A0=87=E6=95=B0=E6=8D=AE=E4=B8=BA=20null=20=E6=97=B6?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E5=BC=82=E5=B8=B8=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alexzjt <9548248+Alexzjt@users.noreply.github.com> --- .../__tests__/unit/utils/sort-action-spec.ts | 34 +++++++++++++++++++ packages/s2-core/src/utils/sort-action.ts | 18 +++++++--- 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts b/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts index 59ef2ac5ce..2c8373ceaa 100644 --- a/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts +++ b/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts @@ -127,6 +127,40 @@ describe('Sort Action Test', () => { ), ).toEqual(['3', 2, '-', undefined]); + // 测试 null 值排序,升序时 null 在前,降序时 null 在后 + const dataNullAsc = createCellData([null, 2, '3', 0]); + + expect( + unwrapCellData(sortAction(dataNullAsc, 'ASC', 'a') as CellData[]), + ).toEqual([null, 0, 2, '3']); + + const dataNullDesc = createCellData([null, 2, '3', 0]); + + expect( + unwrapCellData(sortAction(dataNullDesc, 'DESC', 'a') as CellData[]), + ).toEqual(['3', 2, 0, null]); + + // 测试同时包含多个 null 值的情况(issue #3306 的场景) + const dataMultiNull = createCellData([null, null, 0, 9, 0, -1]); + const resultAsc = unwrapCellData( + sortAction(dataMultiNull, 'ASC', 'a') as CellData[], + ); + + // 升序时 null 值应该在最前面 + expect(resultAsc[0]).toBeNull(); + expect(resultAsc[1]).toBeNull(); + expect(resultAsc.slice(2)).toEqual([-1, 0, 0, 9]); + + const dataMultiNullDesc = createCellData([null, null, 0, 9, 0, -1]); + const resultDesc = unwrapCellData( + sortAction(dataMultiNullDesc, 'DESC', 'a') as CellData[], + ); + + // 降序时 null 值应该在最后面 + expect(resultDesc[4]).toBeNull(); + expect(resultDesc[5]).toBeNull(); + expect(resultDesc.slice(0, 4)).toEqual([9, 0, 0, -1]); + const data6 = createCellData(['', 2, '3']); expect( diff --git a/packages/s2-core/src/utils/sort-action.ts b/packages/s2-core/src/utils/sort-action.ts index da5ccf36b0..045c0ad42e 100644 --- a/packages/s2-core/src/utils/sort-action.ts +++ b/packages/s2-core/src/utils/sort-action.ts @@ -55,7 +55,6 @@ export const sortAction = ( key?: string, ) => { const sort = isAscSort(sortMethod!) ? 1 : -1; - const specialValues = ['-', undefined]; return list?.sort((pre, next) => { let a = pre as string | number; @@ -64,17 +63,26 @@ export const sortAction = ( if (key) { a = (pre as CellData).getValueByField(key) as string | number; b = (next as CellData).getValueByField(key) as string | number; - if (canConvertToNumber(a) && canConvertToNumber(b)) { - return (Number(a) - Number(b)) * sort; + + const aIsSpecial = isNil(a) || a === '-'; + const bIsSpecial = isNil(b) || b === '-'; + + // 处理特殊值(null, undefined, '-'):升序时在前,降序时在后 + if (aIsSpecial && bIsSpecial) { + return 0; } - if (a && specialValues?.includes(a?.toString())) { + if (aIsSpecial) { return -sort; } - if (Number(a) && specialValues?.includes(b?.toString())) { + if (bIsSpecial) { return sort; } + + if (canConvertToNumber(a) && canConvertToNumber(b)) { + return (Number(a) - Number(b)) * sort; + } } // 没有参数 key 时,需要理解成按字典序(首字母)进行排序,用于排维度值的。(我也不理解为啥要把这两个逻辑写在一起,很容易误解 From d87373db6464876900a7517b240eb7d14081e6b7 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 30 Jan 2026 09:17:54 +0000 Subject: [PATCH 3/6] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E4=B8=AD=20createCellData=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E7=9A=84=E7=B1=BB=E5=9E=8B=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alexzjt <9548248+Alexzjt@users.noreply.github.com> --- packages/s2-core/__tests__/unit/utils/sort-action-spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts b/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts index 2c8373ceaa..f3cd70df4a 100644 --- a/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts +++ b/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts @@ -64,7 +64,7 @@ describe('Sort Action Test', () => { }); test('sort action with object arr', () => { - function createCellData(list: (number | string | undefined)[]) { + function createCellData(list: (number | string | undefined | null)[]) { return list.map((a) => new CellData({ a }, 'a')); } From 0c077b036a8cf65d91f7e177466de53cf2e9f858 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 30 Jan 2026 14:53:21 +0000 Subject: [PATCH 4/6] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20nullsPlacement?= =?UTF-8?q?=20=E9=85=8D=E7=BD=AE=E9=A1=B9=EF=BC=8C=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E7=A9=BA=E5=80=BC=E6=8E=92=E5=BA=8F?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alexzjt <9548248+Alexzjt@users.noreply.github.com> --- .../__tests__/unit/utils/sort-action-spec.ts | 101 ++++++++++++++++-- .../s2-core/src/common/interface/basic.ts | 16 +++ packages/s2-core/src/utils/sort-action.ts | 50 +++++++-- s2-site/common/sort-param.en.md | 31 ++++++ s2-site/common/sort-param.zh.md | 31 ++++++ s2-site/docs/manual/basic/sort/basic.zh.md | 1 + 6 files changed, 212 insertions(+), 18 deletions(-) diff --git a/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts b/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts index f3cd70df4a..4bdba8db65 100644 --- a/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts +++ b/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts @@ -101,13 +101,15 @@ describe('Sort Action Test', () => { const data4 = createCellData(['-', 2, '3']); + // 默认 nullsPlacement='last',特殊值始终在最后 expect( unwrapCellData(sortAction(data4, 'ASC', 'a') as CellData[]), - ).toEqual(['-', 2, '3']); + ).toEqual([2, '3', '-']); expect( unwrapCellData(sortAction(data4, 'DESC', 'a') as CellData[]), ).toEqual(['3', 2, '-']); + // 默认 nullsPlacement='last',空值始终在最后 expect( unwrapCellData( sortAction( @@ -116,7 +118,7 @@ describe('Sort Action Test', () => { 'a', ) as CellData[], ), - ).toEqual([undefined, '-', 2, '3']); + ).toEqual([2, '3', '-', undefined]); expect( unwrapCellData( sortAction( @@ -127,12 +129,12 @@ describe('Sort Action Test', () => { ), ).toEqual(['3', 2, '-', undefined]); - // 测试 null 值排序,升序时 null 在前,降序时 null 在后 + // 测试 null 值排序,默认 nullsPlacement='last',无论升降序,null 都在最后 const dataNullAsc = createCellData([null, 2, '3', 0]); expect( unwrapCellData(sortAction(dataNullAsc, 'ASC', 'a') as CellData[]), - ).toEqual([null, 0, 2, '3']); + ).toEqual([0, 2, '3', null]); const dataNullDesc = createCellData([null, 2, '3', 0]); @@ -141,22 +143,23 @@ describe('Sort Action Test', () => { ).toEqual(['3', 2, 0, null]); // 测试同时包含多个 null 值的情况(issue #3306 的场景) + // 默认行为:null 始终在最后 const dataMultiNull = createCellData([null, null, 0, 9, 0, -1]); const resultAsc = unwrapCellData( sortAction(dataMultiNull, 'ASC', 'a') as CellData[], ); - // 升序时 null 值应该在最前面 - expect(resultAsc[0]).toBeNull(); - expect(resultAsc[1]).toBeNull(); - expect(resultAsc.slice(2)).toEqual([-1, 0, 0, 9]); + // 升序时 null 值应该在最后面(默认 nullsPlacement='last') + expect(resultAsc[4]).toBeNull(); + expect(resultAsc[5]).toBeNull(); + expect(resultAsc.slice(0, 4)).toEqual([-1, 0, 0, 9]); const dataMultiNullDesc = createCellData([null, null, 0, 9, 0, -1]); const resultDesc = unwrapCellData( sortAction(dataMultiNullDesc, 'DESC', 'a') as CellData[], ); - // 降序时 null 值应该在最后面 + // 降序时 null 值应该在最后面(默认 nullsPlacement='last') expect(resultDesc[4]).toBeNull(); expect(resultDesc[5]).toBeNull(); expect(resultDesc.slice(0, 4)).toEqual([9, 0, 0, -1]); @@ -165,11 +168,89 @@ describe('Sort Action Test', () => { expect( unwrapCellData(sortAction(data6, 'ASC', 'a') as CellData[]), - ).toEqual(['', 2, '3']); + ).toEqual([2, '3', '']); expect( unwrapCellData(sortAction(data6, 'DESC', 'a') as CellData[]), ).toEqual(['3', 2, '']); }); + + test('sort action with nullsPlacement option', () => { + function createCellData(list: (number | string | undefined | null)[]) { + return list.map((a) => new CellData({ a }, 'a')); + } + + function unwrapCellData(cellDataList: CellData[]) { + return cellDataList.map((cell) => cell[VALUE_FIELD]); + } + + const testData = [null, 2, '3', 0, undefined]; + + // nullsPlacement='last' (默认值) - 空值始终在最后 + expect( + unwrapCellData( + sortAction( + createCellData(testData), + 'ASC', + 'a', + 'last', + ) as CellData[], + ), + ).toEqual([0, 2, '3', null, undefined]); + expect( + unwrapCellData( + sortAction( + createCellData(testData), + 'DESC', + 'a', + 'last', + ) as CellData[], + ), + ).toEqual(['3', 2, 0, null, undefined]); + + // nullsPlacement='first' - 空值始终在最前 + expect( + unwrapCellData( + sortAction( + createCellData(testData), + 'ASC', + 'a', + 'first', + ) as CellData[], + ), + ).toEqual([null, undefined, 0, 2, '3']); + expect( + unwrapCellData( + sortAction( + createCellData(testData), + 'DESC', + 'a', + 'first', + ) as CellData[], + ), + ).toEqual([null, undefined, '3', 2, 0]); + + // nullsPlacement='auto' - 与 'last' 行为相同 + expect( + unwrapCellData( + sortAction( + createCellData(testData), + 'ASC', + 'a', + 'auto', + ) as CellData[], + ), + ).toEqual([0, 2, '3', null, undefined]); + expect( + unwrapCellData( + sortAction( + createCellData(testData), + 'DESC', + 'a', + 'auto', + ) as CellData[], + ), + ).toEqual(['3', 2, 0, null, undefined]); + }); }); }); diff --git a/packages/s2-core/src/common/interface/basic.ts b/packages/s2-core/src/common/interface/basic.ts index da0ef29f9e..a85712272b 100644 --- a/packages/s2-core/src/common/interface/basic.ts +++ b/packages/s2-core/src/common/interface/basic.ts @@ -221,6 +221,14 @@ export interface Totals { col?: Total; } +/** + * 空值排序位置 + * - 'first': 空值排在最前 + * - 'last': 空值排在最后 + * - 'auto': 与 'last' 相同,空值始终在后 + */ +export type NullsPlacement = 'first' | 'last' | 'auto'; + export interface Sort { /** 字段 id */ sortFieldId: string; @@ -239,6 +247,14 @@ export interface Sort { /** 组内排序用来显示icon */ type?: string; + + /** + * 空值排序位置 + * - 'first': 空值永远排在最前 + * - 'last': 空值永远排在最后(默认值) + * - 'auto': 与 'last' 相同,空值始终在后 + */ + nullsPlacement?: NullsPlacement; } export interface SortFuncParam extends Sort { diff --git a/packages/s2-core/src/utils/sort-action.ts b/packages/s2-core/src/utils/sort-action.ts index 045c0ad42e..5f44800520 100644 --- a/packages/s2-core/src/utils/sort-action.ts +++ b/packages/s2-core/src/utils/sort-action.ts @@ -20,7 +20,12 @@ import { QueryDataType, TOTAL_VALUE, } from '../common/constant'; -import type { Fields, SortMethod, SortParam } from '../common/interface'; +import type { + Fields, + NullsPlacement, + SortMethod, + SortParam, +} from '../common/interface'; import type { PivotDataSet, Query } from '../data-set'; import type { CellData } from '../data-set/cell-data'; import type { @@ -48,14 +53,31 @@ export const isDescSort = (sortMethod: SortMethod) => * @param list - 待排序数组 * @param sortMethod - 升、降序 * @param key - 根据key数值排序,如果有key代表根据维度值排序,故按数字排,如果没有按照字典排 + * @param nullsPlacement - 空值排序位置,默认为 'last'(空值永远在最后) */ export const sortAction = ( list: (number | string)[] | CellData[], sortMethod?: SortMethod, key?: string, + nullsPlacement: NullsPlacement = 'last', ) => { const sort = isAscSort(sortMethod!) ? 1 : -1; + // 计算空值的排序方向 + // 'first': 空值始终在前 (返回 -1) + // 'last': 空值始终在后 (返回 1) + // 'auto': 与 'last' 行为相同,升降序都在后 + const getNullsSortDirection = () => { + if (nullsPlacement === 'first') { + return -1; + } + + // 'last' 和 'auto' 都是空值在最后 + return 1; + }; + + const nullsSortDirection = getNullsSortDirection(); + return list?.sort((pre, next) => { let a = pre as string | number; let b = next as string | number; @@ -67,17 +89,17 @@ export const sortAction = ( const aIsSpecial = isNil(a) || a === '-'; const bIsSpecial = isNil(b) || b === '-'; - // 处理特殊值(null, undefined, '-'):升序时在前,降序时在后 + // 处理特殊值(null, undefined, '-') if (aIsSpecial && bIsSpecial) { return 0; } if (aIsSpecial) { - return -sort; + return nullsSortDirection; } if (bIsSpecial) { - return sort; + return -nullsSortDirection; } if (canConvertToNumber(a) && canConvertToNumber(b)) { @@ -92,10 +114,10 @@ export const sortAction = ( } if (a) { - return sort; + return -nullsSortDirection; } - return -sort; + return nullsSortDirection; }); }; @@ -198,7 +220,13 @@ export const sortByFunc = (params: SortActionParams): string[] => { const sortByMethod = (params: SortActionParams): string[] => { const { sortParam, measureValues, originValues, dataSet } = params; - const { sortByMeasure, query, sortFieldId, sortMethod } = sortParam!; + const { + sortByMeasure, + query, + sortFieldId, + sortMethod, + nullsPlacement = 'last', + } = sortParam!; const { rows = [], columns = [] } = dataSet!.fields; const isInRows = rows?.includes(sortFieldId); let result; @@ -208,6 +236,7 @@ const sortByMethod = (params: SortActionParams): string[] => { measureValues!, sortMethod, sortByMeasure === TOTAL_VALUE ? query?.[EXTRA_FIELD] : sortByMeasure, + nullsPlacement, ); const fields = ( @@ -220,7 +249,12 @@ const sortByMethod = (params: SortActionParams): string[] => { dimensions as CellData[], ); } else { - result = sortAction(measureValues!, sortMethod) as string[]; + result = sortAction( + measureValues!, + sortMethod, + undefined, + nullsPlacement, + ) as string[]; } return mergeDataWhenASC(result, originValues!, isAscSort(sortMethod!)); diff --git a/s2-site/common/sort-param.en.md b/s2-site/common/sort-param.en.md index a3ee19e66b..8b67527b60 100644 --- a/s2-site/common/sort-param.en.md +++ b/s2-site/common/sort-param.en.md @@ -16,6 +16,37 @@ Function description: sorting configuration | query | Filter criteria, narrow the sort range such as: `{city:'白山'}` | `Record` | - | | | type | Sorting within the group is used to display the icon (for pivot tables) | `string` | - | | | sortFunc | Function for custom sorting | (params: [SortFuncParam](#sortfuncparam) ) => `string[]` | - | | +| nullsPlacement | Position of null values in sorting | `'first' \| 'last' \| 'auto'` | `'last'` | | + +#### nullsPlacement + +Configuration for the position of null values (`null`, `undefined`, `'-'`, empty string) in sorting: + +| Value | Description | +| --- | --- | +| `'first'` | Null values always at the beginning | +| `'last'` | Null values always at the end (**default**, industry best practice) | +| `'auto'` | Same as `'last'`, null values are always at the end | + +:::info{title="Note"} + +1. When a custom `sortFunc` is provided, the sorting logic is fully controlled by `sortFunc`, and `nullsPlacement` configuration has no effect +2. The default value `'last'` aligns with the behavior of mainstream spreadsheet applications like Excel and Google Sheets, which is more intuitive for users + +::: + +```ts +const s2DataConfig = { + sortParams: [ + { + sortFieldId: 'price', + sortMethod: 'DESC', + // Null values always at the end (default behavior) + nullsPlacement: 'last', + }, + ], +}; +``` #### SortFuncParam diff --git a/s2-site/common/sort-param.zh.md b/s2-site/common/sort-param.zh.md index f07fe33051..d2e0b4e2cd 100644 --- a/s2-site/common/sort-param.zh.md +++ b/s2-site/common/sort-param.zh.md @@ -16,6 +16,37 @@ order: 7 | query | 筛选条件,缩小排序范围 如 :`{city:'白山'}` | `Record` | - | | | type | 组内排序用来显示 icon (透视表适用) | `string` | - | | | sortFunc | 自定义排序的 function | (params: [SortFuncParam](#sortfuncparam)) => `string[]` | - | | +| nullsPlacement | 空值排序位置 | `'first' \| 'last' \| 'auto'` | `'last'` | | + +#### nullsPlacement + +空值(`null`、`undefined`、`'-'`、空字符串)排序位置配置: + +| 值 | 说明 | +| --- | --- | +| `'first'` | 空值永远排在最前 | +| `'last'` | 空值永远排在最后(**默认值**,业界最佳实践) | +| `'auto'` | 与 `'last'` 相同,空值始终在后 | + +:::info{title="说明"} + +1. 当用户自定义了 `sortFunc` 时,排序逻辑完全由 `sortFunc` 接管,`nullsPlacement` 配置不生效 +2. 默认值 `'last'` 符合 Excel、Google Sheets 等主流电子表格的行为,更符合用户直觉 + +::: + +```ts +const s2DataConfig = { + sortParams: [ + { + sortFieldId: 'price', + sortMethod: 'DESC', + // 空值永远排在最后(默认行为) + nullsPlacement: 'last', + }, + ], +}; +``` #### SortFuncParam diff --git a/s2-site/docs/manual/basic/sort/basic.zh.md b/s2-site/docs/manual/basic/sort/basic.zh.md index 42456235d8..9d5df7f665 100644 --- a/s2-site/docs/manual/basic/sort/basic.zh.md +++ b/s2-site/docs/manual/basic/sort/basic.zh.md @@ -23,6 +23,7 @@ S2 支持对表格数据进行多种形式的排序,如行/列头维值根据 | query | 筛选条件,缩小排序范围 如 :`{ city: '成都' }` | `object` | - | | | type | 组内排序用来显示 icon(透视表适用) | `string` | - | | | sortFunc | 自定义排序的 function | `(v: SortFuncParam) => Array` | - | | +| nullsPlacement | 空值排序位置 | `'first'` \| `'last'` \| `'auto'` | `'last'` | | ```ts import { EXTRA_FIELD } from "@antv/s2"; From cde958afa8547aba9615cbcb786633a47c1855e5 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 30 Jan 2026 15:06:28 +0000 Subject: [PATCH 5/6] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=20nullsPlacement?= =?UTF-8?q?=3D'auto'=20=E7=9A=84=E8=A1=8C=E4=B8=BA=EF=BC=88=E5=8D=87?= =?UTF-8?q?=E5=BA=8F=E7=A9=BA=E5=80=BC=E5=9C=A8=E5=89=8D=EF=BC=8C=E9=99=8D?= =?UTF-8?q?=E5=BA=8F=E7=A9=BA=E5=80=BC=E5=9C=A8=E5=90=8E=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alexzjt <9548248+Alexzjt@users.noreply.github.com> --- .../s2-core/__tests__/unit/utils/sort-action-spec.ts | 4 ++-- packages/s2-core/src/common/interface/basic.ts | 4 ++-- packages/s2-core/src/utils/sort-action.ts | 10 ++++++++-- s2-site/common/sort-param.en.md | 2 +- s2-site/common/sort-param.zh.md | 2 +- 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts b/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts index 4bdba8db65..c3b0b49529 100644 --- a/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts +++ b/packages/s2-core/__tests__/unit/utils/sort-action-spec.ts @@ -229,7 +229,7 @@ describe('Sort Action Test', () => { ), ).toEqual([null, undefined, '3', 2, 0]); - // nullsPlacement='auto' - 与 'last' 行为相同 + // nullsPlacement='auto' - 升序时空值在前,降序时空值在后 expect( unwrapCellData( sortAction( @@ -239,7 +239,7 @@ describe('Sort Action Test', () => { 'auto', ) as CellData[], ), - ).toEqual([0, 2, '3', null, undefined]); + ).toEqual([null, undefined, 0, 2, '3']); expect( unwrapCellData( sortAction( diff --git a/packages/s2-core/src/common/interface/basic.ts b/packages/s2-core/src/common/interface/basic.ts index a85712272b..4e589c11cf 100644 --- a/packages/s2-core/src/common/interface/basic.ts +++ b/packages/s2-core/src/common/interface/basic.ts @@ -225,7 +225,7 @@ export interface Totals { * 空值排序位置 * - 'first': 空值排在最前 * - 'last': 空值排在最后 - * - 'auto': 与 'last' 相同,空值始终在后 + * - 'auto': 升序时空值在前,降序时空值在后 */ export type NullsPlacement = 'first' | 'last' | 'auto'; @@ -252,7 +252,7 @@ export interface Sort { * 空值排序位置 * - 'first': 空值永远排在最前 * - 'last': 空值永远排在最后(默认值) - * - 'auto': 与 'last' 相同,空值始终在后 + * - 'auto': 升序时空值在前,降序时空值在后 */ nullsPlacement?: NullsPlacement; } diff --git a/packages/s2-core/src/utils/sort-action.ts b/packages/s2-core/src/utils/sort-action.ts index 5f44800520..dd53a52a7b 100644 --- a/packages/s2-core/src/utils/sort-action.ts +++ b/packages/s2-core/src/utils/sort-action.ts @@ -62,17 +62,23 @@ export const sortAction = ( nullsPlacement: NullsPlacement = 'last', ) => { const sort = isAscSort(sortMethod!) ? 1 : -1; + const isAsc = isAscSort(sortMethod!); // 计算空值的排序方向 // 'first': 空值始终在前 (返回 -1) // 'last': 空值始终在后 (返回 1) - // 'auto': 与 'last' 行为相同,升降序都在后 + // 'auto': 升序时空值在前,降序时空值在后 const getNullsSortDirection = () => { if (nullsPlacement === 'first') { return -1; } - // 'last' 和 'auto' 都是空值在最后 + if (nullsPlacement === 'auto') { + // auto: 升序 → 空值在前(-1),降序 → 空值在后(1) + return isAsc ? -1 : 1; + } + + // 'last': 空值始终在最后 return 1; }; diff --git a/s2-site/common/sort-param.en.md b/s2-site/common/sort-param.en.md index 8b67527b60..d338a54f9e 100644 --- a/s2-site/common/sort-param.en.md +++ b/s2-site/common/sort-param.en.md @@ -26,7 +26,7 @@ Configuration for the position of null values (`null`, `undefined`, `'-'`, empty | --- | --- | | `'first'` | Null values always at the beginning | | `'last'` | Null values always at the end (**default**, industry best practice) | -| `'auto'` | Same as `'last'`, null values are always at the end | +| `'auto'` | Ascending: null values at the beginning; Descending: null values at the end | :::info{title="Note"} diff --git a/s2-site/common/sort-param.zh.md b/s2-site/common/sort-param.zh.md index d2e0b4e2cd..a5fa56c0f1 100644 --- a/s2-site/common/sort-param.zh.md +++ b/s2-site/common/sort-param.zh.md @@ -26,7 +26,7 @@ order: 7 | --- | --- | | `'first'` | 空值永远排在最前 | | `'last'` | 空值永远排在最后(**默认值**,业界最佳实践) | -| `'auto'` | 与 `'last'` 相同,空值始终在后 | +| `'auto'` | 升序时空值在前,降序时空值在后 | :::info{title="说明"} From 056f702aa7c6a14f1c1ce0bac7d83db4d4ce23d4 Mon Sep 17 00:00:00 2001 From: zjt Date: Sat, 31 Jan 2026 21:49:00 +0800 Subject: [PATCH 6/6] =?UTF-8?q?fix:=20=E6=8F=90=E4=BE=9B=E6=9B=B4=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E7=9A=84=E5=85=A8=E5=B1=80=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../s2-core/__tests__/bugs/issue-725-spec.ts | 1 + .../unit/sheet-type/pivot-sheet-spec.ts | 86 ++++++++++++++++++- .../s2-core/src/sheet-type/pivot-sheet.ts | 9 ++ packages/s2-core/src/utils/sort-action.ts | 10 +-- s2-site/common/sort-param.zh.md | 15 ++++ s2-site/docs/manual/basic/sort/basic.zh.md | 21 +++++ 6 files changed, 136 insertions(+), 6 deletions(-) diff --git a/packages/s2-core/__tests__/bugs/issue-725-spec.ts b/packages/s2-core/__tests__/bugs/issue-725-spec.ts index c80ad53757..0f5edbc702 100644 --- a/packages/s2-core/__tests__/bugs/issue-725-spec.ts +++ b/packages/s2-core/__tests__/bugs/issue-725-spec.ts @@ -24,6 +24,7 @@ describe('Group Sort When Have Same Child Measure', () => { sortFieldId: 'type', sortByMeasure: 'cost', sortMethod: 'asc', + nullsPlacement: 'first', }, ], }); diff --git a/packages/s2-core/__tests__/unit/sheet-type/pivot-sheet-spec.ts b/packages/s2-core/__tests__/unit/sheet-type/pivot-sheet-spec.ts index 2f4d9a437a..272ccf042f 100644 --- a/packages/s2-core/__tests__/unit/sheet-type/pivot-sheet-spec.ts +++ b/packages/s2-core/__tests__/unit/sheet-type/pivot-sheet-spec.ts @@ -21,7 +21,7 @@ import { PivotSheet, SpreadSheet } from '@/sheet-type'; import { BaseTooltip } from '@/ui/tooltip'; import { customMerge, setupDataConfig } from '@/utils'; import { Canvas, CanvasEvent } from '@antv/g'; -import { cloneDeep, last } from 'lodash'; +import { cloneDeep, last, merge } from 'lodash'; import dataCfg from 'tests/data/simple-data.json'; import { waitForRender } from 'tests/util'; import { createPivotSheet, getContainer, sleep } from 'tests/util/helpers'; @@ -1350,6 +1350,90 @@ describe('PivotSheet Tests', () => { sheet.destroy(); }); + + // https://github.com/antvis/S2/issues/3308 + it('should use previous defined nullsPlacement in sortParams', async () => { + const layoutDataCfg: S2DataConfig = customMerge(originalDataCfg, { + fields: { + rows: ['province'], + columns: [], + }, + sortParams: [ + { + sortFieldId: 'province', + sortMethod: 'DESC', + nullsPlacement: 'first', + }, + ], + } as unknown as S2DataConfig); + + const sheet = new PivotSheet(getContainer(), layoutDataCfg, { + width: 400, + height: 200, + }); + + await sheet.render(); + + const provinceNode = sheet.facet.getRowNodes()[0]; + + // trigger group sort + await sheet.groupSortByMethod('ASC', provinceNode); + + // should match previous defined nullsPlacement + expect(sheet.dataCfg.sortParams).toMatchObject([ + { + sortFieldId: 'province', + sortMethod: 'ASC', + nullsPlacement: 'first', + }, + ]); + + sheet.destroy(); + }); + + it('should use wildcard defined nullsPlacement in sortParams', async () => { + const layoutDataCfg = merge({}, cloneDeep(originalDataCfg), { + fields: { + rows: ['province'], + columns: ['city'], + values: ['price'], + valueInCols: true, + }, + sortParams: [ + { + sortFieldId: '*', + nullsPlacement: 'first', + }, + ], + } as unknown as S2DataConfig); + + const sheet = new PivotSheet(getContainer(), layoutDataCfg, { + width: 400, + height: 200, + }); + + await sheet.render(); + + const provinceNode = sheet.facet.getRowNodes()[0]; + + // trigger group sort + await sheet.groupSortByMethod('ASC', provinceNode); + + // should match previous defined nullsPlacement + expect(sheet.dataCfg.sortParams).toMatchObject([ + { + sortFieldId: '*', + nullsPlacement: 'first', + }, + { + sortFieldId: 'city', + sortMethod: 'ASC', + nullsPlacement: 'first', + }, + ]); + + sheet.destroy(); + }); }); test('should emit destroy event', async () => { diff --git a/packages/s2-core/src/sheet-type/pivot-sheet.ts b/packages/s2-core/src/sheet-type/pivot-sheet.ts index 46ad79535b..47589974e9 100644 --- a/packages/s2-core/src/sheet-type/pivot-sheet.ts +++ b/packages/s2-core/src/sheet-type/pivot-sheet.ts @@ -161,11 +161,20 @@ export class PivotSheet extends SpreadSheet { } const sortFieldId = isString(sortField) ? sortField : sortField!.field; + const currentSortParam = this.dataCfg.sortParams?.find( + (item) => + item?.sortFieldId === sortFieldId || item?.sortFieldId === sortValue, + ); + const wildcardSortParam = this.dataCfg.sortParams?.find( + (item) => item?.sortFieldId === '*', + ); const sortParam: SortParam = { sortFieldId, sortMethod, sortByMeasure: sortValue, query: sortQuery, + nullsPlacement: + currentSortParam?.nullsPlacement ?? wildcardSortParam?.nullsPlacement, }; const prevSortParams = this.dataCfg.sortParams?.filter( (item) => item?.sortFieldId !== sortField, diff --git a/packages/s2-core/src/utils/sort-action.ts b/packages/s2-core/src/utils/sort-action.ts index dd53a52a7b..914f61cf24 100644 --- a/packages/s2-core/src/utils/sort-action.ts +++ b/packages/s2-core/src/utils/sort-action.ts @@ -92,8 +92,8 @@ export const sortAction = ( a = (pre as CellData).getValueByField(key) as string | number; b = (next as CellData).getValueByField(key) as string | number; - const aIsSpecial = isNil(a) || a === '-'; - const bIsSpecial = isNil(b) || b === '-'; + const aIsSpecial = isNil(a) || a === '-' || a === ''; + const bIsSpecial = isNil(b) || b === '-' || b === ''; // 处理特殊值(null, undefined, '-') if (aIsSpecial && bIsSpecial) { @@ -268,7 +268,7 @@ const sortByMethod = (params: SortActionParams): string[] => { const processSort = (params: SortActionParams): string[] => { const { sortParam, originValues = [], measureValues, dataSet } = params; - const { sortFunc, sortMethod, sortBy } = sortParam!; + const { sortFunc, sortMethod, sortBy: sortList } = sortParam!; let result = originValues; const sortActionParams = { @@ -280,9 +280,9 @@ const processSort = (params: SortActionParams): string[] => { if (sortFunc) { result = sortByFunc(sortActionParams); - } else if (sortBy) { + } else if (sortList) { // 自定义列表 - result = sortByCustom({ sortByValues: sortBy, originValues }); + result = sortByCustom({ sortByValues: sortList, originValues }); } else if (isAscSort(sortMethod!) || isDescSort(sortMethod!)) { // 如果是升序,需要将无数据的项放到前面 result = sortByMethod(sortActionParams); diff --git a/s2-site/common/sort-param.zh.md b/s2-site/common/sort-param.zh.md index a5fa56c0f1..f677022e52 100644 --- a/s2-site/common/sort-param.zh.md +++ b/s2-site/common/sort-param.zh.md @@ -46,6 +46,21 @@ const s2DataConfig = { }, ], }; + +const globalNullsConfig = { + sortParams: [ + // 使用通配符 * 配置全局空值策略,所有字段默认空值在前 + { + sortFieldId: '*', + nullsPlacement: 'first', + }, + // 特殊字段覆盖:price 字段空值在后 + { + sortFieldId: 'price', + nullsPlacement: 'last', + }, + ], +}; ``` #### SortFuncParam diff --git a/s2-site/docs/manual/basic/sort/basic.zh.md b/s2-site/docs/manual/basic/sort/basic.zh.md index 9d5df7f665..fe97e0a26b 100644 --- a/s2-site/docs/manual/basic/sort/basic.zh.md +++ b/s2-site/docs/manual/basic/sort/basic.zh.md @@ -236,6 +236,27 @@ const s2DataConfig = { 📊 查看 demo [自定义排序](/examples/analysis/sort#custom-sort-func)。 +### 5. 空值位置配置(nullsPlacement) + +支持配置空值(`null`、`undefined`、`'-'`、空字符串)在排序中的位置。 + +- `'first'`: 空值永远排在最前 +- `'last'`: 空值永远排在最后(**默认值**) +- `'auto'`: 升序时空值在前,降序时空值在后 + +支持通过 `sortFieldId: '*'` 配置通配符,作为全局默认策略,**通配符配置优先级低于特定字段配置**。 + +```ts +const s2DataConfig = { + sortParams: [ + // 1. 全局配置:所有字段空值默认在前 + { sortFieldId: '*', nullsPlacement: 'first' }, + // 2. 单独配置:city 字段空值在后(优先级更高) + { sortFieldId: 'city', nullsPlacement: 'last' }, + ] +} +``` + ## 优先级 1. `sortParams` 里的条件优先级高于原始数据