Skip to content

Commit 2dab8e7

Browse files
authored
Merge pull request #428 from eccenca/bugfix/codeEdiorTrap-CMEM-7687
Add a hint explaining how to leave the editor
2 parents 1d17f89 + b5cd2f4 commit 2dab8e7

8 files changed

Lines changed: 419 additions & 43 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p
88

99
### Added
1010

11+
- `<CodeEditor />`
12+
- documents the built-in Escape then Tab sequence for moving focus out of the editor when Tab is configured to indent
13+
- shows a compact keyboard navigation hint in a bottom CodeMirror panel when Tab is configured to indent
14+
- `keyboardHint` accepts a custom string or element for localized instructions, the default instruction is marked as English
1115
- `<Switch />`
1216
- `noDrag` parameter: Add the `nodrag` class to the Switch element. Default: `true`
1317
- `<Markdown />`

‎src/components/AutoSuggestion/AutoSuggestion.scss‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@
3131
background-color: $eccgui-color-textfield-background;
3232
}
3333

34-
.#{$eccgui}-singlelinecodeeditor {
35-
padding: 0;
34+
.#{$eccgui}-codeeditor.#{$eccgui}-singlelinecodeeditor {
35+
height: auto;
36+
padding: 2px;
3637

3738
[class^="cm-theme"] {
3839
width: 100%;
@@ -45,8 +46,7 @@
4546
}
4647

4748
.cm-editor {
48-
top: 1px;
49-
height: calc(#{$eccgui-size-textfield-height-regular} - 2px);
49+
height: auto;
5050
padding: 0;
5151
margin: 0;
5252
overflow: hidden;
@@ -61,6 +61,7 @@
6161

6262
.cm-scroller {
6363
height: 100%;
64+
min-height: calc(#{$eccgui-size-textfield-height-regular} - 2px);
6465
padding: 0;
6566
margin: 0;
6667
overflow: auto hidden !important;

‎src/components/AutoSuggestion/AutoSuggestion.tsx‎

Lines changed: 39 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ export const CodeAutocompleteField = ({
221221
const currentCm = React.useRef<EditorView>(undefined);
222222
currentCm.current = cm;
223223
const isFocused = React.useRef(false);
224+
const suggestionsDismissed = React.useRef(false);
224225
const autoSuggestionDivRef = React.useRef<HTMLDivElement>(null);
225226
/** Mutable editor state, since this needs to be current in scope of the SingleLineEditorComponent. */
226227
const [editorState] = React.useState<{
@@ -229,6 +230,15 @@ export const CodeAutocompleteField = ({
229230
cm?: EditorView;
230231
dropdownShown: boolean;
231232
}>({ index: 0, suggestions: [], dropdownShown: false });
233+
234+
const setDropdownShown = React.useCallback(
235+
(shown: boolean) => {
236+
editorState.dropdownShown = shown;
237+
setShouldShowDropdown(shown);
238+
},
239+
[editorState],
240+
);
241+
232242
/** This is for the AutoSuggestionList component in order to re-render. */
233243
const [focusedIndex, setFocusedIndex] = React.useState(0);
234244
const selectedTextRanges = React.useRef<IRange[]>([]);
@@ -266,10 +276,6 @@ export const CodeAutocompleteField = ({
266276
typeof editorState?.cm?.dispatch === "function" ? editorState?.cm?.dispatch : () => {}
267277
) as EditorView["dispatch"];
268278

269-
React.useEffect(() => {
270-
editorState.dropdownShown = shouldShowDropdown;
271-
}, [shouldShowDropdown, editorState]);
272-
273279
// Handle replacement highlighting
274280
useEffect(() => {
275281
if (highlightedElement && cm) {
@@ -331,7 +337,7 @@ export const CodeAutocompleteField = ({
331337
suggestionResponse?.replacementResults?.length === 1 &&
332338
!suggestionResponse?.replacementResults[0]?.replacements?.length
333339
) {
334-
setShouldShowDropdown(false);
340+
setDropdownShown(false);
335341
}
336342
if (suggestionResponse?.replacementResults?.length) {
337343
suggestionResponse.replacementResults.forEach(
@@ -352,7 +358,7 @@ export const CodeAutocompleteField = ({
352358
setSuggestions([]);
353359
}
354360
setCurrentIndex(0);
355-
}, [suggestionResponse, editorState]);
361+
}, [suggestionResponse, editorState, setDropdownShown]);
356362

357363
const getOffsetRange = (cm: EditorView, from: number, to: number) => {
358364
if (!cm) return { fromOffset: 0, toOffset: 0 };
@@ -462,8 +468,8 @@ export const CodeAutocompleteField = ({
462468
cursorPosition.current = cursor - offsetFromFirstLine;
463469
// cursor change is fired after onChange, so we put the auto-complete logic here
464470
//get value at line
465-
if (isFocused.current) {
466-
setShouldShowDropdown(true);
471+
if (isFocused.current && !suggestionsDismissed.current) {
472+
setDropdownShown(true);
467473
handleEditorInputChange.cancel();
468474
handleEditorInputChange(value.current, cursorPosition.current);
469475
}
@@ -480,6 +486,20 @@ export const CodeAutocompleteField = ({
480486
};
481487

482488
const handleInputEditorKeyPress = (event: KeyboardEvent) => {
489+
if (event.key === OVERWRITTEN_KEYS.Escape) {
490+
if (editorState.dropdownShown) {
491+
suggestionsDismissed.current = true;
492+
493+
event.preventDefault();
494+
handleEscapePressed();
495+
}
496+
// A closed dropdown lets CodeMirror handle Escape so the next Tab can leave the editor.
497+
return true;
498+
}
499+
if (event.key === OVERWRITTEN_KEYS.Tab && !editorState.dropdownShown) {
500+
return true;
501+
}
502+
suggestionsDismissed.current = false;
483503
const overWrittenKeys: Array<string> = Object.values(OVERWRITTEN_KEYS);
484504
if (overWrittenKeys.includes(event.key) && (useTabForCompletions || event.key !== OVERWRITTEN_KEYS.Tab)) {
485505
//don't prevent when enter should create new line (multiline config) and dropdown isn't shown
@@ -498,7 +518,7 @@ export const CodeAutocompleteField = ({
498518

499519
const closeDropDown = () => {
500520
setHighlightedElement(undefined);
501-
setShouldShowDropdown(false);
521+
setDropdownShown(false);
502522
};
503523

504524
const handleDropdownChange = (selectedSuggestion: CodeAutocompleteFieldSuggestionWithReplacementInfo) => {
@@ -525,19 +545,20 @@ export const CodeAutocompleteField = ({
525545
}
526546
};
527547

528-
const handleInputEditorClear = () => {
529-
dispatch({
530-
changes: { from: 0, to: cm?.state.doc.length, insert: "" },
548+
const handleInputEditorClear = React.useCallback(() => {
549+
currentCm.current?.dispatch({
550+
changes: { from: 0, to: currentCm.current.state.doc.length, insert: "" },
531551
});
532552
cursorPosition.current = 0;
533553
handleChange("");
534-
cm?.focus();
535-
};
554+
currentCm.current?.focus();
555+
}, [handleChange]);
536556

537557
const handleInputFocus = (focusState: boolean) => {
538558
onFocusChange?.(focusState);
539559
if (focusState) {
540-
setShouldShowDropdown(true);
560+
suggestionsDismissed.current = false;
561+
setDropdownShown(true);
541562
} else {
542563
closeDropDown();
543564
}
@@ -556,6 +577,7 @@ export const CodeAutocompleteField = ({
556577
};
557578

558579
const handleInputMouseDown = React.useCallback((editor: EditorView) => {
580+
suggestionsDismissed.current = false;
559581
const cursor = editorState.cm?.state.selection.main.head;
560582
const currentLine = editorState.cm?.state.doc.lineAt(cursor ?? 0).number;
561583
const clickedLine = editor?.state.doc.lineAt(cursor ?? 0).number;
@@ -670,6 +692,7 @@ export const CodeAutocompleteField = ({
670692
showScrollBar,
671693
multiline,
672694
handleInputMouseDown,
695+
height,
673696
readOnly,
674697
effectiveIntent,
675698
]);
@@ -711,7 +734,7 @@ export const CodeAutocompleteField = ({
711734
{!!value.current && (
712735
<span className={BlueprintClassNames.INPUT_ACTION} ref={inputActionsDisplayed}>
713736
<IconButton
714-
data-test-id={"value-path-clear-btn"}
737+
data-test-id="value-path-clear-btn"
715738
name="operation-clear"
716739
text={clearIconText}
717740
disabled={readOnly}

‎src/components/AutoSuggestion/tests/AutoSuggestion.test.tsx‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import React from "react";
2-
import { render } from "@testing-library/react";
2+
import { EditorView } from "@codemirror/view";
3+
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
34

45
import "@testing-library/jest-dom";
56

@@ -49,4 +50,70 @@ describe("AutoSuggestion", () => {
4950
const { getByText } = render(<AutoSuggestion {...props} />);
5051
expect(getByText(props.label!)).toBeTruthy();
5152
});
53+
54+
it.each([false, true])("updates the container height (multiline: %s)", (multiline) => {
55+
const { container, rerender } = render(<AutoSuggestion {...props} multiline={multiline} height={120} />);
56+
const editorContainer = container.querySelector<HTMLElement>(".eccgui-codeeditor");
57+
expect(editorContainer).toHaveStyle({ height: "120px" });
58+
59+
rerender(<AutoSuggestion {...props} multiline={multiline} height="10rem" />);
60+
expect(editorContainer).toHaveStyle({ height: "10rem" });
61+
62+
rerender(<AutoSuggestion {...props} multiline={multiline} />);
63+
expect(editorContainer?.style.height).toBe("");
64+
});
65+
66+
it.each([
67+
{ multiline: false, useTabForCompletions: false },
68+
{ multiline: false, useTabForCompletions: true },
69+
{ multiline: true, useTabForCompletions: false },
70+
{ multiline: true, useTabForCompletions: true },
71+
])(
72+
"separates closing suggestions from Escape then Tab navigation ($multiline, $useTabForCompletions)",
73+
async ({ multiline, useTabForCompletions }) => {
74+
render(
75+
<AutoSuggestion
76+
{...props}
77+
initialValue="value"
78+
mode="json"
79+
multiline={multiline}
80+
useTabForCompletions={useTabForCompletions}
81+
autoCompletionRequestDelay={0}
82+
fetchSuggestions={(inputString, cursorPosition) => ({
83+
inputString,
84+
cursorPosition,
85+
replacementResults: [
86+
{
87+
replacementInterval: { from: 0, length: 5 },
88+
extractedQuery: "",
89+
replacements: [{ value: "completion" }],
90+
},
91+
],
92+
})}
93+
/>,
94+
);
95+
const editor = screen.getByRole("textbox");
96+
act(() => editor.focus());
97+
expect(await screen.findByText("completion")).toBeVisible();
98+
const view = EditorView.findFromDOM(editor);
99+
act(() => view?.dispatch({ selection: { anchor: 0, head: 5 } }));
100+
const initialContent = editor.textContent;
101+
102+
// With suggestions open, Escape only closes the dropdown.
103+
expect(fireEvent.keyDown(editor, { key: "Escape", code: "Escape", keyCode: 27 })).toBe(false);
104+
105+
await waitFor(() => expect(screen.queryByText("completion")).not.toBeInTheDocument());
106+
expect(editor).toHaveFocus();
107+
expect(editor.textContent).toBe(initialContent);
108+
109+
expect(fireEvent.keyDown(editor, { key: "Tab", code: "Tab", keyCode: 9 })).toBe(false);
110+
const contentAfterIndent = editor.textContent;
111+
expect(contentAfterIndent).not.toBe(initialContent);
112+
113+
// Once the dropdown is closed, Escape enables CodeMirror's temporary tab-focus mode.
114+
expect(fireEvent.keyDown(editor, { key: "Escape", code: "Escape", keyCode: 27 })).toBe(true);
115+
expect(fireEvent.keyDown(editor, { key: "Tab", code: "Tab", keyCode: 9 })).toBe(true);
116+
expect(editor.textContent).toBe(contentAfterIndent);
117+
},
118+
);
52119
});

‎src/extensions/codemirror/CodeMirror.stories.tsx‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ import React from "react";
22
import { Meta, StoryFn } from "@storybook/react";
33

44
import { helpersArgTypes } from "../../../.storybook/helpers";
5+
import { FieldItem } from "../../components/Form/FieldItem";
56

67
import { CodeEditor } from "./CodeMirror";
7-
import { FieldItem } from "../../components/Form/FieldItem";
88

99
export default {
1010
title: "Extensions/CodeEditor",
@@ -22,8 +22,8 @@ export default {
2222

2323
let forcedUpdateKey = 0; // @see https://github.com/storybookjs/storybook/issues/13375#issuecomment-1291011856
2424
const TemplateFull: StoryFn<typeof CodeEditor> = (args) => (
25-
<FieldItem labelProps={{ text: "Code input", hidden: true }} key={++forcedUpdateKey} >
26-
<CodeEditor {...args}/>
25+
<FieldItem labelProps={{ text: "Code input", hidden: true }} key={++forcedUpdateKey}>
26+
<CodeEditor {...args} />
2727
</FieldItem>
2828
);
2929

@@ -34,6 +34,30 @@ BasicExample.args = {
3434
defaultValue: '{ json: "true" }',
3535
};
3636

37+
export const LongContent = TemplateFull.bind({});
38+
LongContent.args = {
39+
name: "long-json-input",
40+
mode: "json",
41+
tabIntentStyle: "tab",
42+
height: "20rem",
43+
wrapLines: false,
44+
defaultValue: JSON.stringify(
45+
{
46+
name: "Product catalog",
47+
products: Array.from({ length: 30 }, (_, index) => ({
48+
id: `product-${index + 1}`,
49+
name: `Product ${index + 1}`,
50+
description:
51+
"A detailed product description containing specifications, available options, delivery information, and care instructions. This intentionally long line makes it possible to check horizontal scrolling alongside the keyboard navigation hint.",
52+
available: index % 3 !== 0,
53+
tags: ["catalog", "featured", "online"],
54+
})),
55+
},
56+
null,
57+
2,
58+
),
59+
};
60+
3761
export const MarkdownWithToolbar = TemplateFull.bind({});
3862
MarkdownWithToolbar.args = {
3963
name: "mdinput",

0 commit comments

Comments
 (0)