Skip to content

Commit 4e2f7ff

Browse files
fix: prevent keydown event when pressing escape to close autocomplete dialogs (#2824)
* fix: prevent keydown event when pressing escape to close autocomplete dialogs * Fix changeset * Colocate variable closer to usage
1 parent 11f3f62 commit 4e2f7ff

3 files changed

Lines changed: 60 additions & 0 deletions

File tree

.changeset/wicked-jars-push.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@graphiql/react': patch
3+
---
4+
5+
fix: prevent key down events when pressing escape to close autocomplete dialogs

packages/graphiql-react/src/editor/query-editor.tsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,25 @@ export function useQueryEditor(
223223
}
224224
});
225225

226+
let showingHints = false;
227+
228+
// fired whenever a hint dialog opens
229+
newEditor.on('startCompletion', () => {
230+
showingHints = true;
231+
});
232+
233+
// the codemirror hint extension fires this anytime the dialog is closed
234+
// via any method (e.g. focus blur, escape key, ...)
235+
newEditor.on('endCompletion', () => {
236+
showingHints = false;
237+
});
238+
239+
newEditor.on('keydown', (editorInstance, event) => {
240+
if (event.key === 'Escape' && showingHints) {
241+
event.stopPropagation();
242+
}
243+
});
244+
226245
newEditor.on('beforeChange', (editorInstance, change) => {
227246
// The update function is only present on non-redo, non-undo events.
228247
if (change.origin === 'paste') {
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
describe('GraphiQL keyboard interactions', () => {
2+
it('Does not prevent the escape key from being handled outside the editor', () => {
3+
cy.visit('/');
4+
const mockFn = cy.stub().as('escapeHandler');
5+
cy.document().then(doc => {
6+
doc.addEventListener('keydown', event => {
7+
if (event.key === 'Escape') {
8+
mockFn();
9+
}
10+
});
11+
});
12+
13+
cy.get('.graphiql-query-editor textarea').type('{esc}', { force: true });
14+
15+
cy.get('@escapeHandler').should('have.been.called');
16+
});
17+
18+
it('Does prevent the escape key from being handled outside the editor if closing the autocomplete dialog', () => {
19+
cy.visit('/').wait(3000);
20+
const mockFn = cy.stub().as('escapeHandler');
21+
cy.document().then(doc => {
22+
doc.addEventListener('keydown', event => {
23+
if (event.key === 'Escape') {
24+
mockFn();
25+
}
26+
});
27+
});
28+
29+
cy.get('.graphiql-query-editor textarea')
30+
.type('{\n t', { force: true })
31+
.wait(500)
32+
.type('{esc}');
33+
34+
cy.get('@escapeHandler').should('not.have.been.called');
35+
});
36+
});

0 commit comments

Comments
 (0)