Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 19 additions & 15 deletions docs/src/modules/utils/CodeCopy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,30 +160,34 @@ 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.
if (!rootNode.current) {
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) {

// Skip if user is highlighting a text.
if (hasNativeSelection(event.target as HTMLTextAreaElement)) {
return;
}
if (!rootNode.current) {

// 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 | null;
if (!copyBtn) {
return;
}
const initialEventAction = copyBtn.getAttribute('data-ga-event-action');
const initialEventAction = copyBtn!.getAttribute('data-ga-event-action');
// update the 'data-ga-event-action' on the button to track keyboard interaction
copyBtn.dataset.gaEventAction =
copyBtn!.dataset.gaEventAction =
initialEventAction?.replace('click', 'keyboard') || 'copy-keyboard';
copyBtn.click(); // let the GA setup in GoogleAnalytics.js do the job
copyBtn.dataset.gaEventAction = initialEventAction!; // reset the 'data-ga-event-action' back to initial
copyBtn!.click(); // let the GA setup in GoogleAnalytics.js do the job
copyBtn!.dataset.gaEventAction = initialEventAction!; // reset the 'data-ga-event-action' back to initial
});
}, []);
return (
Expand Down