Skip to content

Commit

Permalink
fix: ColorPicker default clear value should change if set (#48450)
Browse files Browse the repository at this point in the history
* fix: ColorPicker default clear value should change if set

* chore: code clean

---------

Co-authored-by: afc163 <afc163@gmail.com>
  • Loading branch information
MadCcc and afc163 committed Apr 16, 2024
1 parent 8e076f1 commit 0a7e225
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
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

0 comments on commit 0a7e225

Please sign in to comment.