Skip to content

Commit 421234b

Browse files
committedApr 21, 2023
fix: fix the issue that the copy button listener may fail. (#220)
1 parent bf60089 commit 421234b

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed
 

‎core/src/plugins/useCopied.tsx

+20-7
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,34 @@
11
import copyTextToClipboard from '@uiw/copy-to-clipboard';
2-
import { useCallback, useEffect } from 'react';
2+
import { useEffect } from 'react';
3+
4+
function getParentElement(target: EventTarget | null): null | HTMLElement {
5+
if (!target) return null;
6+
const dom = target as HTMLElement;
7+
if (dom.dataset.code && dom.classList.contains('copied')) {
8+
return dom;
9+
}
10+
if (dom.parentElement) {
11+
return getParentElement(dom.parentElement);
12+
}
13+
return null;
14+
}
315

416
export function useCopied(container: React.RefObject<HTMLDivElement>) {
5-
const handle = useCallback((event: Event) => {
6-
const target = (event.currentTarget || event.target) as HTMLDivElement;
17+
const handle = (event: Event) => {
18+
const target = getParentElement(event.target);
19+
if (!target) return;
720
target.classList.add('active');
821
copyTextToClipboard(target.dataset.code as string, function () {
922
setTimeout(() => {
1023
target.classList.remove('active');
1124
}, 2000);
1225
});
13-
}, []);
26+
};
1427
useEffect(() => {
15-
const btns = container.current?.querySelectorAll('div.copied[data-code]');
16-
btns && Array.from(btns).forEach((elm) => elm.addEventListener('click', handle, false));
28+
container.current?.removeEventListener('click', handle, false);
29+
container.current?.addEventListener('click', handle, false);
1730
return () => {
18-
btns && Array.from(btns).forEach((elm) => elm.removeEventListener('click', handle, false));
31+
container.current?.removeEventListener('click', handle, false);
1932
};
2033
// eslint-disable-next-line react-hooks/exhaustive-deps
2134
}, [container]);

0 commit comments

Comments
 (0)
Please sign in to comment.