Skip to content

Commit

Permalink
[Console] Add option to disable keyboard shortcuts (#128887)
Browse files Browse the repository at this point in the history
* Get editor instance to settings modal

* Add disable keyboard shortcuts feature

* Update editor.test.tsx

* Refactor

* Address comments

Co-authored-by: Muhammad Ibragimov <muhammad.ibragimov@elastic.co>
  • Loading branch information
mibragimov and Muhammad Ibragimov committed Apr 13, 2022
1 parent 04acd49 commit 35d575c
Show file tree
Hide file tree
Showing 12 changed files with 191 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,13 @@ export function HelpPanel(props: Props) {
defaultMessage="Select the currently selected or the top most term in auto-complete menu"
/>
</dd>
<dt>Ctrl/Cmd + L</dt>
<dd>
<FormattedMessage
id="console.helpPage.keyboardCommands.goToLineNumberDescription"
defaultMessage="Go to line number"
/>
</dd>
<dt>Esc</dt>
<dd>
<FormattedMessage
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import {
} from '@elastic/eui';

import { DevToolsSettings } from '../../services';
import { unregisterCommands } from '../containers/editor/legacy/console_editor/keyboard_shortcuts';
import type { SenseEditor } from '../models';

export type AutocompleteOptions = 'fields' | 'indices' | 'templates';

Expand Down Expand Up @@ -62,6 +64,7 @@ interface Props {
onClose: () => void;
refreshAutocompleteSettings: (selectedSettings: DevToolsSettings['autocomplete']) => void;
settings: DevToolsSettings;
editorInstance: SenseEditor | null;
}

export function DevToolsSettingsModal(props: Props) {
Expand All @@ -74,7 +77,10 @@ export function DevToolsSettingsModal(props: Props) {
const [polling, setPolling] = useState(props.settings.polling);
const [pollInterval, setPollInterval] = useState(props.settings.pollInterval);
const [tripleQuotes, setTripleQuotes] = useState(props.settings.tripleQuotes);
const [historyDisabled, setHistoryDisabled] = useState(props.settings.historyDisabled);
const [isHistoryDisabled, setIsHistoryDisabled] = useState(props.settings.isHistoryDisabled);
const [isKeyboardShortcutsDisabled, setIsKeyboardShortcutsDisabled] = useState(
props.settings.isKeyboardShortcutsDisabled
);

const autoCompleteCheckboxes = [
{
Expand Down Expand Up @@ -134,7 +140,8 @@ export function DevToolsSettingsModal(props: Props) {
polling,
pollInterval,
tripleQuotes,
historyDisabled,
isHistoryDisabled,
isKeyboardShortcutsDisabled,
});
}

Expand All @@ -145,6 +152,21 @@ export function DevToolsSettingsModal(props: Props) {
setPollInterval(sanitizedValue);
}, []);

const toggleKeyboardShortcuts = useCallback(
(isDisabled: boolean) => {
if (props.editorInstance) {
unregisterCommands(props.editorInstance);
setIsKeyboardShortcutsDisabled(isDisabled);
}
},
[props.editorInstance]
);

const toggleSavingToHistory = useCallback(
(isDisabled: boolean) => setIsHistoryDisabled(isDisabled),
[]
);

// It only makes sense to show polling options if the user needs to fetch any data.
const pollingFields =
fields || indices || templates ? (
Expand All @@ -160,7 +182,7 @@ export function DevToolsSettingsModal(props: Props) {
<FormattedMessage
id="console.settingsPage.refreshingDataDescription"
defaultMessage="Console refreshes autocomplete suggestions by querying Elasticsearch.
Less frequent refresh is recommended to reduce bandwith costs."
Less frequent refresh is recommended to reduce bandwidth costs."
/>
}
>
Expand Down Expand Up @@ -267,15 +289,34 @@ export function DevToolsSettingsModal(props: Props) {
}
>
<EuiSwitch
checked={historyDisabled}
id="historyDisabled"
checked={isHistoryDisabled}
label={
<FormattedMessage
defaultMessage="Disable saving requests to history"
id="console.settingsPage.savingRequestsToHistoryMessage"
/>
}
onChange={(e) => setHistoryDisabled(e.target.checked)}
onChange={(e) => toggleSavingToHistory(e.target.checked)}
/>
</EuiFormRow>

<EuiFormRow
label={
<FormattedMessage
id="console.settingsPage.keyboardShortcutsLabel"
defaultMessage="Keyboard shortcuts"
/>
}
>
<EuiSwitch
checked={isKeyboardShortcutsDisabled}
label={
<FormattedMessage
defaultMessage="Disable keyboard shortcuts"
id="console.settingsPage.disableKeyboardShortcutsMessage"
/>
}
onChange={(e) => toggleKeyboardShortcuts(e.target.checked)}
/>
</EuiFormRow>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,17 @@ import { Panel, PanelsContainer } from '../../containers';
import { Editor as EditorUI, EditorOutput } from './legacy/console_editor';
import { StorageKeys } from '../../../services';
import { useEditorReadContext, useServicesContext, useRequestReadContext } from '../../contexts';
import type { SenseEditor } from '../../models';

const INITIAL_PANEL_WIDTH = 50;
const PANEL_MIN_WIDTH = '100px';

interface Props {
loading: boolean;
setEditorInstance: (instance: SenseEditor) => void;
}

export const Editor = memo(({ loading }: Props) => {
export const Editor = memo(({ loading, setEditorInstance }: Props) => {
const {
services: { storage },
} = useServicesContext();
Expand Down Expand Up @@ -61,7 +63,10 @@ export const Editor = memo(({ loading }: Props) => {
{loading ? (
<EditorContentSpinner />
) : (
<EditorUI initialTextValue={currentTextObject.text} />
<EditorUI
initialTextValue={currentTextObject.text}
setEditorInstance={setEditorInstance}
/>
)}
</Panel>
<Panel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('Legacy (Ace) Console Editor Component Smoke Test', () => {
<ServicesContextProvider value={mockedAppContextValue}>
<RequestContextProvider>
<EditorContextProvider settings={{} as unknown as DevToolsSettings}>
<Editor initialTextValue="" />
<Editor initialTextValue="" setEditorInstance={() => {}} />
</EditorContextProvider>
</RequestContextProvider>
</ServicesContextProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@ import { autoIndent, getDocumentation } from '../console_menu_actions';
import { subscribeResizeChecker } from '../subscribe_console_resize_checker';
import { applyCurrentSettings } from './apply_editor_settings';
import { registerCommands } from './keyboard_shortcuts';
import type { SenseEditor } from '../../../../models/sense_editor';

const { useUIAceKeyboardMode } = ace;

export interface EditorProps {
initialTextValue: string;
setEditorInstance: (instance: SenseEditor) => void;
}

interface QueryParams {
Expand All @@ -62,7 +64,7 @@ const DEFAULT_INPUT_VALUE = `GET _search

const inputId = 'ConAppInputTextarea';

function EditorUI({ initialTextValue }: EditorProps) {
function EditorUI({ initialTextValue, setEditorInstance }: EditorProps) {
const {
services: { history, notifications, settings: settingsService, esHostService, http },
docLinkVersion,
Expand Down Expand Up @@ -225,12 +227,22 @@ function EditorUI({ initialTextValue }: EditorProps) {
}, [settings]);

useEffect(() => {
registerCommands({
senseEditor: editorInstanceRef.current!,
sendCurrentRequestToES,
openDocumentation,
});
}, [sendCurrentRequestToES, openDocumentation]);
const { isKeyboardShortcutsDisabled } = settings;
if (!isKeyboardShortcutsDisabled) {
registerCommands({
senseEditor: editorInstanceRef.current!,
sendCurrentRequestToES,
openDocumentation,
});
}
}, [sendCurrentRequestToES, openDocumentation, settings]);

useEffect(() => {
const { current: editor } = editorInstanceRef;
if (editor) {
setEditorInstance(editor);
}
}, [setEditorInstance]);

return (
<div style={abs} data-test-subj="console-application" className="conApp">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ interface Actions {
openDocumentation: () => void;
}

const COMMANDS = {
SEND_TO_ELASTICSEARCH: 'send to Elasticsearch',
OPEN_DOCUMENTATION: 'open documentation',
AUTO_INDENT_REQUEST: 'auto indent request',
MOVE_TO_PREVIOUS_REQUEST: 'move to previous request start or end',
MOVE_TO_NEXT_REQUEST: 'move to next request start or end',
GO_TO_LINE: 'gotoline',
};

export function registerCommands({
senseEditor,
sendCurrentRequestToES,
Expand All @@ -28,39 +37,59 @@ export function registerCommands({

coreEditor.registerKeyboardShortcut({
keys: { win: 'Ctrl-Enter', mac: 'Command-Enter' },
name: 'send to Elasticsearch',
fn: () => sendCurrentRequestToES(),
name: COMMANDS.SEND_TO_ELASTICSEARCH,
fn: () => {
sendCurrentRequestToES();
},
});

coreEditor.registerKeyboardShortcut({
name: 'open documentation',
name: COMMANDS.OPEN_DOCUMENTATION,
keys: { win: 'Ctrl-/', mac: 'Command-/' },
fn: () => {
openDocumentation();
},
});

coreEditor.registerKeyboardShortcut({
name: 'auto indent request',
name: COMMANDS.AUTO_INDENT_REQUEST,
keys: { win: 'Ctrl-I', mac: 'Command-I' },
fn: () => {
throttledAutoIndent();
},
});

coreEditor.registerKeyboardShortcut({
name: 'move to previous request start or end',
name: COMMANDS.MOVE_TO_PREVIOUS_REQUEST,
keys: { win: 'Ctrl-Up', mac: 'Command-Up' },
fn: () => {
senseEditor.moveToPreviousRequestEdge();
},
});

coreEditor.registerKeyboardShortcut({
name: 'move to next request start or end',
name: COMMANDS.MOVE_TO_NEXT_REQUEST,
keys: { win: 'Ctrl-Down', mac: 'Command-Down' },
fn: () => {
senseEditor.moveToNextRequestEdge(false);
},
});

coreEditor.registerKeyboardShortcut({
name: COMMANDS.GO_TO_LINE,
keys: { win: 'Ctrl-L', mac: 'Command-L' },
fn: (editor) => {
const line = parseInt(prompt('Enter line number') ?? '', 10);
if (!isNaN(line)) {
editor.gotoLine(line);
}
},
});
}

export function unregisterCommands(senseEditor: SenseEditor) {
const coreEditor = senseEditor.getCoreEditor();
Object.values(COMMANDS).forEach((command) => {
coreEditor.unregisterKeyboardShortcut(command);
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { useServicesContext, useEditorReadContext, useRequestReadContext } from
import { useDataInit } from '../../hooks';

import { getTopNavConfig } from './get_top_nav';
import type { SenseEditor } from '../../models/sense_editor';

export function Main() {
const {
Expand All @@ -46,6 +47,8 @@ export function Main() {
const [showSettings, setShowSettings] = useState(false);
const [showHelp, setShowHelp] = useState(false);

const [editorInstance, setEditorInstance] = useState<SenseEditor | null>(null);

const renderConsoleHistory = () => {
return editorsReady ? <ConsoleHistory close={() => setShowHistory(false)} /> : null;
};
Expand Down Expand Up @@ -108,7 +111,7 @@ export function Main() {
</EuiFlexItem>
{showingHistory ? <EuiFlexItem grow={false}>{renderConsoleHistory()}</EuiFlexItem> : null}
<EuiFlexItem>
<Editor loading={!done} />
<Editor loading={!done} setEditorInstance={setEditorInstance} />
</EuiFlexItem>
</EuiFlexGroup>

Expand All @@ -121,7 +124,9 @@ export function Main() {
/>
) : null}

{showSettings ? <Settings onClose={() => setShowSettings(false)} /> : null}
{showSettings ? (
<Settings onClose={() => setShowSettings(false)} editorInstance={editorInstance} />
) : null}

{showHelp ? <HelpPanel onClose={() => setShowHelp(false)} /> : null}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { AutocompleteOptions, DevToolsSettingsModal } from '../components';
import { retrieveAutoCompleteInfo } from '../../lib/mappings/mappings';
import { useServicesContext, useEditorActionContext } from '../contexts';
import { DevToolsSettings, Settings as SettingsService } from '../../services';
import type { SenseEditor } from '../models';

const getAutocompleteDiff = (
newSettings: DevToolsSettings,
Expand Down Expand Up @@ -70,9 +71,10 @@ const fetchAutocompleteSettingsIfNeeded = (

export interface Props {
onClose: () => void;
editorInstance: SenseEditor | null;
}

export function Settings({ onClose }: Props) {
export function Settings({ onClose, editorInstance }: Props) {
const {
services: { settings, http },
} = useServicesContext();
Expand Down Expand Up @@ -102,6 +104,7 @@ export function Settings({ onClose }: Props) {
refreshAutocompleteSettings(http, settings, selectedSettings)
}
settings={settings.toJSON()}
editorInstance={editorInstance}
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ export const useSendCurrentRequestToES = () => {
const results = await sendRequestToES({ http, requests });

let saveToHistoryError: undefined | Error;
const { historyDisabled } = settings.toJSON();
const { isHistoryDisabled } = settings.toJSON();

if (!historyDisabled) {
if (!isHistoryDisabled) {
results.forEach(({ request: { path, method, data } }) => {
try {
history.addToHistory(path, method, data);
Expand Down Expand Up @@ -81,7 +81,7 @@ export const useSendCurrentRequestToES = () => {
notifications.toasts.remove(toast);
},
onDisableSavingToHistory: () => {
settings.setHistoryDisabled(true);
settings.setIsHistoryDisabled(true);
notifications.toasts.remove(toast);
},
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,11 @@ export class LegacyCoreEditor implements CoreEditor {
});
}

unregisterKeyboardShortcut(command: string) {
// @ts-ignore
this.editor.commands.removeCommand(command);
}

legacyUpdateUI(range: Range) {
if (!this.$actions) {
return;
Expand Down
Loading

0 comments on commit 35d575c

Please sign in to comment.