Skip to content

[#3444] Add keyboard shortcut update functionality #3445

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions client/modules/IDE/components/Editor/contexts.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import { createContext, useState } from 'react';
import { metaKey } from '../../../../utils/metaKey';

export const EditorKeyMapsContext = createContext();

export function EditorKeyMapProvider({ children }) {
const [keyMaps, setKeyMaps] = useState({
tidy: `Shift-${metaKey}-F`,
findPersistent: `${metaKey}-F`,
findPersistentNext: `${metaKey}-G`,
findPersistentPrev: `Shift-${metaKey}-G`,
colorPicker: `${metaKey}-K`
});

const updateKeyMap = (key, value) => {
if (key in keyMaps) {
setKeyMaps((prevKeyMaps) => ({
...prevKeyMaps,
[key]: value
}));
}
};

return (
<EditorKeyMapsContext.Provider value={{ keyMaps, updateKeyMap }}>
{children}
</EditorKeyMapsContext.Provider>
);
}

EditorKeyMapProvider.propTypes = {
children: PropTypes.node.isRequired
};

export const useEditorKeyMap = () => {
const context = useContext(EditorKeyMapsContext);
if (!context) {
throw new Error(
'useEditorKeyMap must be used within a EditorKeyMapProvider'
);
}
return context;
};
81 changes: 51 additions & 30 deletions client/modules/IDE/components/Editor/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ import UnsavedChangesIndicator from '../UnsavedChangesIndicator';
import { EditorContainer, EditorHolder } from './MobileEditor';
import { FolderIcon } from '../../../../common/icons';
import IconButton from '../../../../common/IconButton';
import { EditorKeyMapsContext } from './contexts';

emmet(CodeMirror);

Expand Down Expand Up @@ -104,6 +105,7 @@ class Editor extends React.Component {
this.showFind = this.showFind.bind(this);
this.showReplace = this.showReplace.bind(this);
this.getContent = this.getContent.bind(this);
this.updateKeyMaps = this.updateKeyMaps.bind(this);
}

componentDidMount() {
Expand Down Expand Up @@ -153,36 +155,9 @@ class Editor extends React.Component {

delete this._cm.options.lint.options.errors;

const replaceCommand =
metaKey === 'Ctrl' ? `${metaKey}-H` : `${metaKey}-Option-F`;
this._cm.setOption('extraKeys', {
Tab: (cm) => {
if (!cm.execCommand('emmetExpandAbbreviation')) return;
// might need to specify and indent more?
const selection = cm.doc.getSelection();
if (selection.length > 0) {
cm.execCommand('indentMore');
} else {
cm.replaceSelection(' '.repeat(INDENTATION_AMOUNT));
}
},
Enter: 'emmetInsertLineBreak',
Esc: 'emmetResetAbbreviation',
[`Shift-Tab`]: false,
[`${metaKey}-Enter`]: () => null,
[`Shift-${metaKey}-Enter`]: () => null,
[`${metaKey}-F`]: 'findPersistent',
[`Shift-${metaKey}-F`]: this.tidyCode,
[`${metaKey}-G`]: 'findPersistentNext',
[`Shift-${metaKey}-G`]: 'findPersistentPrev',
[replaceCommand]: 'replace',
// Cassie Tarakajian: If you don't set a default color, then when you
// choose a color, it deletes characters inline. This is a
// hack to prevent that.
[`${metaKey}-K`]: (cm, event) =>
cm.state.colorpicker.popup_color_picker({ length: 0 }),
[`${metaKey}-.`]: 'toggleComment' // Note: most adblockers use the shortcut ctrl+.
});
const { keyMaps } = this.context;

this.updateKeyMaps(keyMaps);

this.initializeDocuments(this.props.files);
this._cm.swapDoc(this._docs[this.props.file.id]);
Expand Down Expand Up @@ -236,6 +211,16 @@ class Editor extends React.Component {
}

componentDidUpdate(prevProps) {
const currentKeyMaps = this.context?.keyMaps;
const prevKeyMaps = this.prevKeyMapsRef?.current;

if (
prevKeyMaps &&
JSON.stringify(currentKeyMaps) !== JSON.stringify(prevKeyMaps)
) {
this.updateKeyMaps(currentKeyMaps);
}
this.prevKeyMapsRef = { current: currentKeyMaps };
if (this.props.file.id !== prevProps.file.id) {
const fileMode = this.getFileMode(this.props.file.name);
if (fileMode === 'javascript') {
Expand Down Expand Up @@ -515,6 +500,42 @@ class Editor extends React.Component {
});
}

updateKeyMaps(keyMaps) {
const replaceCommand =
metaKey === 'Ctrl' ? `${metaKey}-H` : `${metaKey}-Option-F`;

this._cm.setOption('extraKeys', {
Tab: (cm) => {
if (!cm.execCommand('emmetExpandAbbreviation')) return;
// might need to specify and indent more?
const selection = cm.doc.getSelection();
if (selection.length > 0) {
cm.execCommand('indentMore');
} else {
cm.replaceSelection(' '.repeat(INDENTATION_AMOUNT));
}
},
Enter: 'emmetInsertLineBreak',
Esc: 'emmetResetAbbreviation',
[`Shift-Tab`]: false,
[`${metaKey}-Enter`]: () => null,
[`Shift-${metaKey}-Enter`]: () => null,
[`${keyMaps.findPersistent}`]: 'findPersistent',
[`${keyMaps.tidy}`]: this.tidyCode,
[`${keyMaps.findPersistentNext}`]: 'findPersistentNext',
[`${keyMaps.findPersistentPrev}`]: 'findPersistentPrev',
[replaceCommand]: 'replace',
// Cassie Tarakajian: If you don't set a default color, then when you
// choose a color, it deletes characters inline. This is a
// hack to prevent that.
[`${keyMaps.colorPicker}`]: (cm, event) =>
cm.state.colorpicker.popup_color_picker({ length: 0 }),
[`${metaKey}-.`]: 'toggleComment' // Note: most adblockers use the shortcut ctrl+.
});
}

static contextType = EditorKeyMapsContext;

render() {
const editorSectionClass = classNames({
editor: true,
Expand Down
138 changes: 138 additions & 0 deletions client/modules/IDE/components/KeyboardShortcutItem.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import React, { useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { useEditorKeyMap } from './Editor/contexts';

function KeyboardShortcutItem({ desc, keyName }) {
const [edit, setEdit] = useState(false);
const pressedKeyCombination = useRef({});
const inputRef = useRef(null);
const { updateKeyMap, keyMaps } = useEditorKeyMap();

if (!Object.keys(keyMaps).includes(keyName)) {
return null;
}

const cancelEdit = () => {
setEdit(false);
pressedKeyCombination.current = {};
inputRef.current.innerText = keyMaps[keyName];
};

const handleEdit = (state, key) => {
setEdit(state);
if (!state) {
updateKeyMap(key, inputRef.current.innerText);
cancelEdit();
}
};

const handleKeyDown = (event) => {
if (!edit) return;
event.preventDefault();
event.stopPropagation();
let { key } = event;
if (key === 'Control') {
key = 'Ctrl';
}
if (key === ' ') {
key = 'Space';
}
if (key.length === 1 && key.match(/[a-z]/i)) {
key = key.toUpperCase();
}

pressedKeyCombination.current[key] = true;

const allKeys = Object.keys(pressedKeyCombination.current).filter(
(k) => !['Shift', 'Ctrl', 'Alt'].includes(k)
);

if (event.altKey) {
allKeys.unshift('Alt');
}
if (event.ctrlKey) {
allKeys.unshift('Ctrl');
}
if (event.shiftKey) {
allKeys.unshift('Shift');
}

event.currentTarget.innerText = allKeys.join('-');
};

const handleKeyUp = (event) => {
if (!edit) return;
event.preventDefault();
event.stopPropagation();
let { key } = event;
if (key === 'Control') {
key = 'Ctrl';
}
if (key === ' ') {
key = 'Space';
}
if (key.length === 1 && key.match(/[a-z]/i)) {
key = key.toUpperCase();
}

delete pressedKeyCombination.current[key];
};

return (
<li className="keyboard-shortcut-item">
<button
type="button"
title="edit shortcut"
className="keyboard-shortcut__edit"
style={{
display: edit ? 'none' : 'block'
}}
onClick={() => handleEdit(true, keyName)}
>
&#x270E;
</button>
<button
type="button"
title="cancel shortcut edit"
className="keyboard-shortcut__edit"
style={{
display: !edit ? 'none' : 'block'
}}
onClick={cancelEdit}
>
&#10799;
</button>
<button
type="button"
title="save shortcut"
className="keyboard-shortcut__edit"
style={{
display: !edit ? 'none' : 'block'
}}
onClick={() => handleEdit(false, keyName)}
>
&#10003;
</button>
<span
className="keyboard-shortcut__command"
role="textbox"
ref={inputRef}
tabIndex={0}
contentEditable={edit}
suppressContentEditableWarning
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
>
{keyMaps[keyName]}
</span>
<span>{desc}</span>
</li>
);
}

KeyboardShortcutItem.propTypes = {
desc: PropTypes.string.isRequired,
keyName: PropTypes.string.isRequired
};

export default KeyboardShortcutItem;
48 changes: 22 additions & 26 deletions client/modules/IDE/components/KeyboardShortcutModal.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { metaKeyName, metaKey } from '../../../utils/metaKey';
import KeyboardShortcutItem from './KeyboardShortcutItem';

function KeyboardShortcutModal() {
const { t } = useTranslation();

const replaceCommand =
metaKey === 'Ctrl' ? `${metaKeyName} + H` : `${metaKeyName} + ⌥ + F`;
const newFileCommand =
Expand All @@ -25,28 +27,22 @@ function KeyboardShortcutModal() {
.
</p>
<ul className="keyboard-shortcuts__list">
<li className="keyboard-shortcut-item">
<span className="keyboard-shortcut__command">
{metaKeyName} + Shift + F
</span>
<span>{t('KeyboardShortcuts.CodeEditing.Tidy')}</span>
</li>
<li className="keyboard-shortcut-item">
<span className="keyboard-shortcut__command">{metaKeyName} + F</span>
<span>{t('KeyboardShortcuts.CodeEditing.FindText')}</span>
</li>
<li className="keyboard-shortcut-item">
<span className="keyboard-shortcut__command">{metaKeyName} + G</span>
<span>{t('KeyboardShortcuts.CodeEditing.FindNextTextMatch')}</span>
</li>
<li className="keyboard-shortcut-item">
<span className="keyboard-shortcut__command">
{metaKeyName} + Shift + G
</span>
<span>
{t('KeyboardShortcuts.CodeEditing.FindPreviousTextMatch')}
</span>
</li>
<KeyboardShortcutItem
desc={t('KeyboardShortcuts.CodeEditing.Tidy')}
keyName="tidy"
/>
<KeyboardShortcutItem
desc={t('KeyboardShortcuts.CodeEditing.FindText')}
keyName="findPersistent"
/>
<KeyboardShortcutItem
desc={t('KeyboardShortcuts.CodeEditing.FindNextTextMatch')}
keyName="findPersistentNext"
/>
<KeyboardShortcutItem
desc={t('KeyboardShortcuts.CodeEditing.FindPreviousTextMatch')}
keyName="findPersistentPrev"
/>
<li className="keyboard-shortcut-item">
<span className="keyboard-shortcut__command">{replaceCommand}</span>
<span>{t('KeyboardShortcuts.CodeEditing.ReplaceTextMatch')}</span>
Expand All @@ -67,10 +63,10 @@ function KeyboardShortcutModal() {
<span className="keyboard-shortcut__command">{metaKeyName} + .</span>
<span>{t('KeyboardShortcuts.CodeEditing.CommentLine')}</span>
</li>
<li className="keyboard-shortcut-item">
<span className="keyboard-shortcut__command">{metaKeyName} + K</span>
<span>{t('KeyboardShortcuts.CodeEditing.ColorPicker')}</span>
</li>
<KeyboardShortcutItem
desc={t('KeyboardShortcuts.CodeEditing.ColorPicker')}
keyName="colorPicker"
/>
<li className="keyboard-shortcut-item">
<span className="keyboard-shortcut__command">{newFileCommand}</span>
<span>{t('KeyboardShortcuts.CodeEditing.CreateNewFile')}</span>
Expand Down
Loading