2022-02-03 18:55:38 +01:00
|
|
|
import React, { useEffect } from 'react';
|
2022-03-18 14:08:49 +01:00
|
|
|
import find from 'lodash/find';
|
2022-01-24 19:27:30 +01:00
|
|
|
import Mousetrap from 'mousetrap';
|
2022-03-18 14:08:49 +01:00
|
|
|
import { saveRequest } from 'providers/ReduxStore/slices/collections';
|
|
|
|
import { requestSaved } from 'providers/ReduxStore/slices/tabs';
|
|
|
|
import { useSelector, useDispatch } from 'react-redux';
|
2022-01-24 19:27:30 +01:00
|
|
|
|
|
|
|
export const HotkeysContext = React.createContext();
|
|
|
|
|
|
|
|
export const HotkeysProvider = props => {
|
2022-03-18 14:08:49 +01:00
|
|
|
const dispatch = useDispatch();
|
|
|
|
const tabs = useSelector((state) => state.tabs.tabs);
|
|
|
|
const activeTabUid = useSelector((state) => state.tabs.activeTabUid);
|
2022-03-15 20:30:35 +01:00
|
|
|
|
2022-01-24 19:27:30 +01:00
|
|
|
useEffect(() => {
|
|
|
|
Mousetrap.bind(['command+s', 'ctrl+s'], (e) => {
|
|
|
|
console.log("Save hotkey");
|
|
|
|
|
2022-03-18 14:08:49 +01:00
|
|
|
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-03-15 20:30:35 +01:00
|
|
|
|
2022-01-24 19:27:30 +01:00
|
|
|
return false; // this stops the event bubbling
|
|
|
|
});
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
Mousetrap.unbind(['command+s', 'ctrl+s']);
|
|
|
|
};
|
2022-03-18 14:08:49 +01:00
|
|
|
}, [activeTabUid, tabs, saveRequest, requestSaved]);
|
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;
|