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

fix: ColorPicker default clear value should change if set #48450

Merged
merged 3 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 26 additions & 0 deletions components/color-picker/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -698,4 +698,30 @@ describe('ColorPicker', () => {
container.querySelector('.ant-color-picker-trigger .ant-color-picker-clear'),
).toBeFalsy();
});

describe('default clearValue should be changed', () => {
const Demo = () => {
const [color, setColor] = useState<string>('');
useEffect(() => {
setColor('#1677ff');
}, []);
return <ColorPicker value={color} allowClear />;
};

it('normal', () => {
const { container } = render(<Demo />);

expect(container.querySelector('.ant-color-picker-clear')).toBeFalsy();
});

it('strict', () => {
const { container } = render(
<React.StrictMode>
<Demo />
</React.StrictMode>,
);

expect(container.querySelector('.ant-color-picker-clear')).toBeFalsy();
});
});
});
9 changes: 9 additions & 0 deletions components/color-picker/hooks/useColorState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { Color } from '../color';
import type { ColorValueType } from '../interface';
import { generateColor } from '../util';

const INIT_COLOR_REF = {} as ColorValueType;

function hasValue(value?: ColorValueType) {
return value !== undefined;
}
Expand Down Expand Up @@ -33,7 +35,14 @@ const useColorState = (
prevColor.current = color;
};

const prevValue = useRef<ColorValueType | undefined>(INIT_COLOR_REF);
useEffect(() => {
// `useEffect` will be executed twice in strict mode even if the deps are the same
// So we compare the value manually to avoid unnecessary update
if (prevValue.current === value) {
return;
}
prevValue.current = value;
if (hasValue(value)) {
const newColor = generateColor(value || '');
if (prevColor.current.cleared === true) {
Expand Down