Skip to content

Commit

Permalink
[docs-infra] Simplify copy logic (#41167)
Browse files Browse the repository at this point in the history
Signed-off-by: Olivier Tassinari <olivier.tassinari@gmail.com>
Co-authored-by: Flavien DELANGLE <flaviendelangle@gmail.com>
  • Loading branch information
oliviertassinari and flaviendelangle committed Feb 20, 2024
1 parent 28dfd5b commit 9e2daa4
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions docs/src/modules/utils/CodeCopy.tsx
Expand Up @@ -160,24 +160,28 @@ export function CodeCopyProvider({ children }: CodeCopyProviderProps) {
const rootNode = React.useRef<HTMLDivElement | null>(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 =
Expand Down

0 comments on commit 9e2daa4

Please sign in to comment.