Skip to content

Commit

Permalink
fix(a11y): lose focus after activating share button
Browse files Browse the repository at this point in the history
  • Loading branch information
ChristiaanScheermeijer authored and AntonLantukh committed Apr 22, 2024
1 parent fa8c142 commit 1cd135e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/ui-react/src/utils/clipboard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { copyToClipboard } from './clipboard';

document.execCommand = vi.fn();
const execCommandMocked = vi.mocked(document.execCommand);

describe('clipboard', () => {
test('copies text to clipboard', () => {
copyToClipboard('text to copy');

expect(execCommandMocked).toHaveBeenCalledWith('copy');
});

test('restores focus to the last active element', () => {
// create a test button
const button = document.createElement('button');
button.textContent = 'share';

document.body.appendChild(button);

button.focus();

// document.activeElement = '';
copyToClipboard('text to copy');

expect(document.activeElement).toEqual(button);
document.body.removeChild(button);
});
});
2 changes: 2 additions & 0 deletions packages/ui-react/src/utils/clipboard.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export const copyToClipboard = (value: string): void => {
const focusedElement = document.activeElement as HTMLElement;
const inputElement = document.createElement('input');
inputElement.style.zIndex = '-10';
inputElement.style.position = 'absolute';
Expand All @@ -9,4 +10,5 @@ export const copyToClipboard = (value: string): void => {
document.execCommand('copy');
inputElement.blur();
document.body.removeChild(inputElement);
focusedElement?.focus();
};

0 comments on commit 1cd135e

Please sign in to comment.