Skip to content

Commit

Permalink
fix: useKeyMap unmount removes keys (3778)
Browse files Browse the repository at this point in the history
  • Loading branch information
patomation committed Sep 22, 2024
1 parent e7915d8 commit 2b8e9e8
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
31 changes: 31 additions & 0 deletions packages/graphiql-react/src/editor/__tests__/hooks.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { renderHook } from '@testing-library/react';
import { useKeyMap } from '../hooks';
import { CodeMirrorEditor, KeyMap } from '../types';

describe('hooks', () => {
describe('useKeyMap', () => {
it('works correctly', () => {
type KeyMap = Record<string, typeof jest.fn>;
let keys: KeyMap = {};
const editor: Pick<CodeMirrorEditor, 'addKeyMap' | 'removeKeyMap'> = {
addKeyMap: jest.fn(keyMap => {
keys = { ...keys, ...(keyMap as KeyMap) };
}),
removeKeyMap: jest.fn((key: string) => {
delete keys[key];
}),
};
const callback = jest.fn();
const { unmount } = renderHook(() =>
useKeyMap(
editor as unknown as CodeMirrorEditor,
['foo', 'bar'],
callback,
),
);
expect(Object.keys(keys).length).toBe(2);
unmount();
expect(Object.keys(keys).length).toBe(0);
});
});
});
10 changes: 7 additions & 3 deletions packages/graphiql-react/src/editor/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,12 @@ export function useKeyMap(
if (!editor) {
return;
}
for (const key of keys) {
editor.removeKeyMap(key);
}
const handleRemoveKeys = () => {
for (const key of keys) {
editor.removeKeyMap(key);
}
};
handleRemoveKeys();

if (callback) {
const keyMap: Record<string, EmptyCallback> = {};
Expand All @@ -147,6 +150,7 @@ export function useKeyMap(
}
editor.addKeyMap(keyMap);
}
return handleRemoveKeys;
}, [editor, keys, callback]);
}

Expand Down

0 comments on commit 2b8e9e8

Please sign in to comment.