bruno/renderer/providers/Hotkeys/index.js

82 lines
2.5 KiB
JavaScript
Raw Normal View History

2022-02-03 18:55:38 +01:00
import React, { useEffect } from 'react';
import find from 'lodash/find';
2022-01-24 19:27:30 +01:00
import Mousetrap from 'mousetrap';
import { useSelector, useDispatch } from 'react-redux';
2022-03-18 18:05:12 +01:00
import { saveRequest, sendRequest } from 'providers/ReduxStore/slices/collections';
import { requestSaved } from 'providers/ReduxStore/slices/tabs';
import { findCollectionByUid, findItemInCollection } from 'utils/collections';
2022-01-24 19:27:30 +01:00
export const HotkeysContext = React.createContext();
export const HotkeysProvider = props => {
const dispatch = useDispatch();
const tabs = useSelector((state) => state.tabs.tabs);
2022-03-18 18:05:12 +01:00
const collections = useSelector((state) => state.collections.collections);
const activeTabUid = useSelector((state) => state.tabs.activeTabUid);
2022-03-18 18:05:12 +01:00
// save hotkey
2022-01-24 19:27:30 +01:00
useEffect(() => {
Mousetrap.bind(['command+s', 'ctrl+s'], (e) => {
if(activeTabUid) {
const activeTab = find(tabs, (t) => t.uid === activeTabUid);
if(activeTab) {
// todo: these dispatches need to be chained and errors need to be handled
dispatch(saveRequest(activeTab.uid, activeTab.collectionUid));
dispatch(requestSaved({
itemUid: activeTab.uid
}))
}
}
2022-01-24 19:27:30 +01:00
return false; // this stops the event bubbling
});
return () => {
Mousetrap.unbind(['command+s', 'ctrl+s']);
};
}, [activeTabUid, tabs, saveRequest, requestSaved]);
2022-01-24 19:27:30 +01:00
2022-03-18 18:05:12 +01:00
// send request (ctrl/cmd + enter)
useEffect(() => {
Mousetrap.bind(['ctrl+command', 'ctrl+enter'], (e) => {
if(activeTabUid) {
const activeTab = find(tabs, (t) => t.uid === activeTabUid);
if(activeTab) {
const collection = findCollectionByUid(collections, activeTab.collectionUid);
if(collection) {
const item = findItemInCollection(collection, activeTab.uid);
if(item) {
dispatch(sendRequest(item, collection.uid));
}
}
}
}
return false; // this stops the event bubbling
});
return () => {
2022-03-18 21:44:59 +01:00
Mousetrap.unbind(['ctrl+command', 'ctrl+enter']);
2022-03-18 18:05:12 +01:00
};
}, [activeTabUid, tabs, saveRequest, requestSaved, collections]);
2022-01-24 19:27:30 +01:00
return (
2022-02-03 18:55:38 +01:00
<HotkeysContext.Provider {...props} value='hotkey'>
2022-01-24 19:27:30 +01:00
{props.children}
</HotkeysContext.Provider>
);
};
export const useHotkeys = () => {
const context = React.useContext(HotkeysContext);
if (!context) {
throw new Error(`useHotkeys must be used within a HotkeysProvider`);
}
return context;
}
export default HotkeysProvider;