Skip to content
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

Macro: #3713 - Hot keys for toolbar buttons are not implemented in Macromoleculas view #3836

Merged
merged 5 commits into from
Jan 5, 2024
Merged
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
25 changes: 23 additions & 2 deletions packages/ketcher-core/src/application/editor/Editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import ZoomTool from './tools/Zoom';
import { Coordinates } from './shared/coordinates';
import {
editorEvents,
hotkeysConfiguration,
renderersEvents,
resetEditorEvents,
} from 'application/editor/editorEvents';
Expand All @@ -26,6 +27,7 @@ import { MacromoleculesConverter } from 'application/editor/MacromoleculesConver
import { BaseMonomer } from 'domain/entities/BaseMonomer';
import { ketcherProvider } from 'application/utils';
import { SnakeMode } from './modes/internal';
import { initHotKeys, keyNorm } from '../../utilities/keynorm';

interface ICoreEditorConstructorParams {
theme;
Expand All @@ -51,6 +53,7 @@ export class CoreEditor {
// private lastEvent: Event | undefined;
private tool?: Tool | BaseTool;
private micromoleculesEditor: Editor;
private hotKeyEventHandler: (event: unknown) => void = () => {};

constructor({ theme, canvas }: ICoreEditorConstructorParams) {
this.theme = theme;
Expand All @@ -61,6 +64,7 @@ export class CoreEditor {
this.renderersContainer = new RenderersManager({ theme });
this.drawingEntitiesManager = new DrawingEntitiesManager();
this.domEventSetup();
this.setupHotKeysEvents();
this.canvasOffset = this.canvas.getBoundingClientRect();
this.zoomTool = ZoomTool.initInstance(this.drawingEntitiesManager);
// eslint-disable-next-line @typescript-eslint/no-this-alias
Expand All @@ -74,6 +78,22 @@ export class CoreEditor {
return editor;
}

private handleHotKeyEvents(event) {
const keySettings = hotkeysConfiguration;
const hotKeys = initHotKeys(keySettings);
const shortcutKey = keyNorm.lookup(hotKeys, event);

if (keySettings[shortcutKey] && keySettings[shortcutKey].handler) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can simplify

if (keySettings[shortcutKey]?.handler)

keySettings[shortcutKey].handler(this);
event.preventDefault();
}
}

setupHotKeysEvents() {
this.hotKeyEventHandler = (event) => this.handleHotKeyEvents(event);
document.addEventListener('keydown', this.hotKeyEventHandler);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just simply?

setupHotKeysEvents() {
  document.addEventListener('keydown', this. handleHotKeyEvents);
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope, because we need to bind 'this' to hotKeyEventHandler method. And this.hotKeyEventHandler.bind(this) also didn't work because it returns another function and it did not clear event listener in this case.

}

private subscribeEvents() {
this.events.selectMonomer.add((monomer) => this.onSelectMonomer(monomer));
this.events.selectPreset.add((preset) => this.onSelectRNAPreset(preset));
Expand Down Expand Up @@ -104,7 +124,7 @@ export class CoreEditor {
}
}

private onSelectTool(tool: string) {
public onSelectTool(tool: string) {
this.selectTool(tool);
}

Expand Down Expand Up @@ -140,7 +160,7 @@ export class CoreEditor {
this.renderersContainer.update(command);
}

private onSelectHistory(name: HistoryOperationType) {
public onSelectHistory(name: HistoryOperationType) {
const history = new EditorHistory(this);
if (name === 'undo') {
history.undo();
Expand All @@ -164,6 +184,7 @@ export class CoreEditor {
for (const eventName in this.events) {
this.events[eventName].handlers = [];
}
document.removeEventListener('keydown', this.hotKeyEventHandler);
}

get trackedDomEvents() {
Expand Down
62 changes: 62 additions & 0 deletions packages/ketcher-core/src/application/editor/editorEvents.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Subscription } from 'subscription';
import { ToolEventHandlerName } from 'application/editor/tools/Tool';
import { CoreEditor } from 'application/editor/Editor';
import ZoomTool from 'application/editor/tools/Zoom';

export let editorEvents;

Expand Down Expand Up @@ -44,3 +46,63 @@ export const renderersEvents: ToolEventHandlerName[] = [
'mouseLeaveDrawingEntity',
'mouseUpMonomer',
];

export const hotkeysConfiguration = {
exit: {
shortcut: ['Shift+Tab', 'Escape'],
handler: (editor: CoreEditor) => {
editor.events.selectTool.dispatch('select-rectangle');
},
},
undo: {
shortcut: ['Ctrl+z', 'Meta+z'],
handler: (editor: CoreEditor) => {
editor.onSelectHistory('undo');
},
},
redo: {
shortcut: ['Mod+Ctrl+Z', 'Ctrl+Y', 'Mod+Meta+Z', 'Meta+y'],
handler: (editor: CoreEditor) => {
editor.onSelectHistory('redo');
},
},
erase: {
shortcut: ['Delete', 'Backspace'],
handler: (editor: CoreEditor) => {
editor.events.selectTool.dispatch('erase');
},
},
clear: {
shortcut: ['Ctrl+Del', 'Ctrl+Backspace', 'Meta+Del', 'Meta+Backspace'],
handler: (editor: CoreEditor) => {
editor.events.selectTool.dispatch('clear');
editor.events.selectTool.dispatch('select-rectangle');
},
},
'zoom-plus': {
shortcut: ['Ctrl+=', 'Meta+='],
handler: () => {
ZoomTool.instance.zoomIn();
},
},
'zoom-minus': {
shortcut: ['Ctrl+-', 'Meta+-'],
handler: () => {
ZoomTool.instance.zoomOut();
},
},
'zoom-reset': {
shortcut: ['Ctrl+0', 'Meta+0'],
handler: () => {
ZoomTool.instance.resetZoom();
},
},
'select-all': {
shortcut: ['Ctrl+a', 'Meta+a'],
handler: (editor: CoreEditor) => {
const modelChanges =
editor.drawingEntitiesManager.selectAllDrawingEntities();
editor.renderersContainer.update(modelChanges);
},
},
};
23 changes: 19 additions & 4 deletions packages/ketcher-core/src/application/editor/tools/Zoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,16 +259,31 @@ class ZoomTool implements BaseTool {
};
}

private get zoomStep() {
return 0.1;
}

public zoomIn(zoomStep = this.zoomStep) {
this.zoom?.scaleTo(this.canvasWrapper, this.zoomLevel + zoomStep);
}

public zoomOut(zoomStep = this.zoomStep) {
this.zoom?.scaleTo(this.canvasWrapper, this.zoomLevel - zoomStep);
}

public resetZoom() {
this.zoom?.transform(this.canvasWrapper, new ZoomTransform(1, 0, 0));
}

initMenuZoom() {
const zoomStep = 0.1;
select('.zoom-in').on('click', () => {
this.zoom?.scaleTo(this.canvasWrapper, this.zoomLevel + zoomStep);
this.zoomIn();
});
select('.zoom-out').on('click', () => {
this.zoom?.scaleTo(this.canvasWrapper, this.zoomLevel - zoomStep);
this.zoomOut();
});
select('.zoom-reset').on('click', () => {
this.zoom?.transform(this.canvasWrapper, new ZoomTransform(1, 0, 0));
this.resetZoom();
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,20 @@ export class DrawingEntitiesManager {
return command;
}

public selectAllDrawingEntities() {
const command = new Command();

this.allEntities.forEach(([, drawingEntity]) => {
if (!drawingEntity.selected) {
drawingEntity.turnOnSelection();
const operation = new DrawingEntitySelectOperation(drawingEntity);
command.addOperation(operation);
}
});

return command;
}

public moveDrawingEntityModelChange(
drawingEntity: DrawingEntity,
offset?: Vec2,
Expand Down
1 change: 1 addition & 0 deletions packages/ketcher-core/src/utilities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ export * from './b64toBlob';
export * from './notifyRequestCompleted';
export * from './KetcherLogger';
export * from './SettingsManager';
export * from './keynorm';
Original file line number Diff line number Diff line change
Expand Up @@ -86,19 +86,45 @@ export function isControlKey(event) {
return mac ? event.metaKey : event.ctrlKey;
}

// TODO rename and unify after moving all hotkeys to core editor
// to handle all events in same way and to have same structure for all hotkey configs
function keyNorm(obj) {
if (obj instanceof KeyboardEvent)
// eslint-disable-line no-undef
return normalizeKeyEvent(...arguments); // eslint-disable-line prefer-rest-params
if (obj instanceof KeyboardEvent) {
return normalizeKeyEvent(obj);
}

return typeof obj === 'object' ? normalizeKeyMap(obj) : normalizeKeyName(obj);
}

function setHotKey(key, actName, hotKeys) {
if (Array.isArray(hotKeys[key])) hotKeys[key].push(actName);
else hotKeys[key] = [actName];
}

export function initHotKeys(actions) {
const hotKeys = {};
let act;

Object.keys(actions).forEach((actName) => {
act = actions[actName];
if (!act.shortcut) return;

if (Array.isArray(act.shortcut)) {
act.shortcut.forEach((key) => {
setHotKey(key, actName, hotKeys);
});
} else {
setHotKey(act.shortcut, actName, hotKeys);
}
});

return keyNorm(hotKeys);
}

function lookup(map, event) {
let name = rusToEng(KN.keyName(event), event);
if (name === 'Add') name = '+'; // numpad '+' and '-'
if (name === 'Subtract') name = '-';

const isChar = name.length === 1 && name !== ' ';
let res = map[modifiers(name, event, !isChar)];
let baseName;
Expand All @@ -111,4 +137,4 @@ function lookup(map, event) {

keyNorm.lookup = lookup;

export default keyNorm;
export { keyNorm };
24 changes: 12 additions & 12 deletions packages/ketcher-polymer-editor-react/src/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,6 @@ function Editor({ theme, togglerComponent }: EditorProps) {
const editor = useAppSelector(selectEditor);
const activeTool = useAppSelector(selectEditorActiveTool);
const isLoading = useLoading();
let keyboardEventListener;
const [isMonomerLibraryHidden, setIsMonomerLibraryHidden] = useState(false);
const monomers = useAppSelector(selectMonomers);

Expand All @@ -157,7 +156,6 @@ function Editor({ theme, togglerComponent }: EditorProps) {
dispatch(destroyEditor(null));
dispatch(loadMonomerLibrary([]));
dispatch(clearFavorites());
document.removeEventListener('keydown', keyboardEventListener);
};
}, [dispatch]);

Expand All @@ -182,6 +180,12 @@ function Editor({ theme, togglerComponent }: EditorProps) {
);

useEffect(() => {
const handler = (toolName: string) => {
if (toolName !== activeTool) {
dispatch(selectTool(toolName));
}
};

if (editor) {
editor.events.error.add((errorText) => {
dispatch(openErrorTooltip(errorText));
Expand All @@ -197,17 +201,13 @@ function Editor({ theme, togglerComponent }: EditorProps) {
}),
),
);

if (!keyboardEventListener) {
keyboardEventListener = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
dispatch(selectTool('select-rectangle'));
editor.events.selectTool.dispatch('select-rectangle');
}
};
document.addEventListener('keydown', keyboardEventListener);
}
editor.events.selectTool.add(handler);
}

return () => {
dispatch(selectTool(null));
editor?.events.selectTool.remove(handler);
};
}, [editor]);

const handleOpenPreview = useCallback((e) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@
import { Component, createRef } from 'react';
import clsx from 'clsx';
import classes from './cliparea.module.less';
import { KetcherLogger, notifyRequestCompleted } from 'ketcher-core';
import { isControlKey } from '../../data/convert/keynorm';
import {
KetcherLogger,
notifyRequestCompleted,
isControlKey,
} from 'ketcher-core';
import { isClipboardAPIAvailable, notifyCopyCut } from './clipboardUtils';

const ieCb = window.clipboardData;
Expand Down
30 changes: 3 additions & 27 deletions packages/ketcher-react/src/script/ui/state/hotkeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,13 @@ import {
MolSerializer,
runAsyncAction,
SettingsManager,
keyNorm,
initHotKeys,
} from 'ketcher-core';
import { debounce, isEqual } from 'lodash/fp';
import { load, onAction, removeStructAction } from './shared';

import actions from '../action';
import keyNorm from '../data/convert/keynorm';
import { isIE } from 'react-device-detect';
import {
selectAbbreviationLookupValue,
Expand All @@ -49,7 +50,7 @@ import { handleHotkeyOverItem } from './handleHotkeysOverItem';

export function initKeydownListener(element) {
return function (dispatch, getState) {
const hotKeys = initHotKeys();
const hotKeys = initHotKeys(actions);
element.addEventListener('keydown', (event) =>
keyHandle(dispatch, getState, hotKeys, event),
);
Expand Down Expand Up @@ -230,31 +231,6 @@ function getHoveredItem(
return Object.keys(hoveredItem).length ? hoveredItem : null;
}

function setHotKey(key, actName, hotKeys) {
if (Array.isArray(hotKeys[key])) hotKeys[key].push(actName);
else hotKeys[key] = [actName];
}

function initHotKeys() {
const hotKeys = {};
let act;

Object.keys(actions).forEach((actName) => {
act = actions[actName];
if (!act.shortcut) return;

if (Array.isArray(act.shortcut)) {
act.shortcut.forEach((key) => {
setHotKey(key, actName, hotKeys);
});
} else {
setHotKey(act.shortcut, actName, hotKeys);
}
});

return keyNorm(hotKeys);
}

function checkGroupOnTool(group, actionTool) {
let index = group.indexOf(actionTool.tool);

Expand Down
Loading