From 9e2daa432cf2fa15f86811dcb3e5232656da870e Mon Sep 17 00:00:00 2001 From: Olivier Tassinari Date: Tue, 20 Feb 2024 20:48:03 +0100 Subject: [PATCH] [docs-infra] Simplify copy logic (#41167) Signed-off-by: Olivier Tassinari Co-authored-by: Flavien DELANGLE --- docs/src/modules/utils/CodeCopy.tsx | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/src/modules/utils/CodeCopy.tsx b/docs/src/modules/utils/CodeCopy.tsx index de5f21450ef5cd..68bd9de869c65a 100644 --- a/docs/src/modules/utils/CodeCopy.tsx +++ b/docs/src/modules/utils/CodeCopy.tsx @@ -160,24 +160,28 @@ export function CodeCopyProvider({ children }: CodeCopyProviderProps) { const rootNode = React.useRef(null); React.useEffect(() => { document.addEventListener('keydown', (event) => { - if (hasNativeSelection(event.target as HTMLTextAreaElement)) { - // Skip if user is highlighting a text. - return; - } - // event.key === 'c' is not enough as alt+c can lead to ©, ç, or other characters on macOS. - // event.code === 'KeyC' is not enough as event.code assume a QWERTY keyboard layout which would - // be wrong with a Dvorak keyboard (as if pressing J). - const isModifierKeyPressed = event.ctrlKey || event.metaKey || event.altKey; - if (String.fromCharCode(event.keyCode) !== 'C' || !isModifierKeyPressed) { + if (!rootNode.current) { return; } - if (!rootNode.current) { + + // Skip if user is highlighting a text. + if (hasNativeSelection(event.target as HTMLTextAreaElement)) { return; } - const copyBtn = rootNode.current.querySelector('.MuiCode-copy') as HTMLButtonElement | null; - if (!copyBtn) { + + // Skip if it's not a copy keyboard event + if ( + !( + (event.ctrlKey || event.metaKey) && + event.key.toLowerCase() === 'c' && + !event.shiftKey && + !event.altKey + ) + ) { return; } + + const copyBtn = rootNode.current.querySelector('.MuiCode-copy') as HTMLButtonElement; const initialEventAction = copyBtn.getAttribute('data-ga-event-action'); // update the 'data-ga-event-action' on the button to track keyboard interaction copyBtn.dataset.gaEventAction =