Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions packages/components/select/__tests__/select-check-all.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import React from 'react';
import { cleanup, fireEvent, render } from '@test/utils';

import { Select } from '..';

const flush = () =>
new Promise((resolve) => {
setTimeout(resolve, 0);
});

describe('Select', () => {
// 弹层是 teleport 到 body 的,render 的 container 里看不到,
// 只能查 document。不清理的话残留节点会串到后面的用例(E-001)。
afterEach(() => {
cleanup();
document.body.innerHTML = '';
});

describe('scenarios', () => {
describe('check all', () => {
it('re-selects every option after one option is unchecked', async () => {
const options = [
{ label: 'All', checkAll: true },
{ label: 'Apple', value: 'apple' },
{ label: 'Orange', value: 'orange' },
{ label: 'Banana', value: 'banana' },
];
const calls: any[] = [];
const { container } = render(
<Select
multiple
options={options}
onChange={(v: any) => {
calls.push(v);
}}
/>,
);
await flush();
fireEvent.click(container.querySelector('input'));
await flush();

const optionEl = (text: string) =>
[...document.querySelectorAll('.t-select-option')].find((el) => el.textContent.includes(text));

expect(optionEl('All')).toBeTruthy();
fireEvent.click(optionEl('All'));
await flush();
expect(calls[calls.length - 1]).toEqual(['apple', 'orange', 'banana']);

fireEvent.click(optionEl('Orange'));
await flush();
expect(calls[calls.length - 1]).toEqual(['apple', 'banana']);

fireEvent.click(optionEl('All'));
await flush();
expect(calls[calls.length - 1]).toEqual(['apple', 'orange', 'banana']);
});
});
});
});
10 changes: 8 additions & 2 deletions packages/components/select/base/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,13 @@ const Select = forwardRefWithStatics(

let checkAllValue: SelectValue[];

if (checkAll) {
// 以当前 value 为准计算全选方向,避免 Option 内部状态与外部 value 不同步时反向操作
const isOptionSelected = (opt: SelectOption) =>
currentValues.some((item) => isSameOptionValue(item, get(opt, valueKey), valueKey));
const allEnabledSelected = enabledOptions.length > 0 && enabledOptions.every(isOptionSelected);
const shouldCheckAll = enabledOptions.length > 0 ? !allEnabledSelected : checkAll;

if (shouldCheckAll) {
const enabledValues = enabledOptions.map((opt) => (isObjectType ? opt : get(opt, valueKey)));
checkAllValue = [...preservedValues, ...enabledValues];
} else {
Expand All @@ -180,7 +186,7 @@ const Select = forwardRefWithStatics(

onChange?.(checkAllValue, {
e,
trigger: checkAll ? 'check' : 'uncheck',
trigger: shouldCheckAll ? 'check' : 'uncheck',
selectedOptions: currentSelectedOptions,
});
},
Expand Down
Loading