Skip to content

Commit

Permalink
fix: Typography copyable not sync (#48347)
Browse files Browse the repository at this point in the history
* test: test driven

* fix: copy of stable
  • Loading branch information
zombieJ committed Apr 9, 2024
1 parent 61c8a43 commit 727aa2d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 24 deletions.
18 changes: 18 additions & 0 deletions components/typography/__tests__/copy.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -298,4 +298,22 @@ describe('Typography copy', () => {
expect(result.current?.copyLoading).toBe(false);
});
});

it('not block copy text change', () => {
const spy = jest.spyOn(copyObj, 'default');

const renderDemo = (text: string) => (
<Base copyable={{ text }} component="p">
Text
</Base>
);

const { container, rerender } = render(renderDemo('Bamboo'));
rerender(renderDemo('Light'));

fireEvent.click(container.querySelector('.ant-typography-copy')!);
expect(spy.mock.calls[0][0]).toBe('Light');

spy.mockRestore();
});
});
52 changes: 28 additions & 24 deletions components/typography/hooks/useCopyClick.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import copy from 'copy-to-clipboard';
import { useEvent } from 'rc-util';

import type { CopyConfig } from '../Base';

Expand Down Expand Up @@ -29,33 +30,36 @@ const useCopyClick = ({

React.useEffect(() => cleanCopyId, []);

// Keep copy action up to date
const onClick = useEvent(async (e?: React.MouseEvent<HTMLDivElement>) => {
e?.preventDefault();
e?.stopPropagation();
setCopyLoading(true);
try {
const text =
typeof copyConfig.text === 'function' ? await copyConfig.text() : copyConfig.text;
copy(text || String(children) || '', copyOptions);
setCopyLoading(false);

setCopied(true);

// Trigger tips update
cleanCopyId();
copyIdRef.current = setTimeout(() => {
setCopied(false);
}, 3000);

copyConfig.onCopy?.(e);
} catch (error) {
setCopyLoading(false);
throw error;
}
});

return {
copied,
copyLoading,
onClick: async (e?: React.MouseEvent<HTMLDivElement>) => {
e?.preventDefault();
e?.stopPropagation();
setCopyLoading(true);
try {
const text =
typeof copyConfig.text === 'function' ? await copyConfig.text() : copyConfig.text;
copy(text || String(children) || '', copyOptions);
setCopyLoading(false);

setCopied(true);

// Trigger tips update
cleanCopyId();
copyIdRef.current = setTimeout(() => {
setCopied(false);
}, 3000);

copyConfig.onCopy?.(e);
} catch (error) {
setCopyLoading(false);
throw error;
}
},
onClick,
};
};

Expand Down

0 comments on commit 727aa2d

Please sign in to comment.