UNPKG

2.31 kBTypeScriptView Raw
1/*
2 * Copyright 2021 Palantir Technologies, Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import * as React from "react";
18
19import * as Errors from "../../common/errors";
20import { isNodeEnv } from "../../common/utils";
21import { HotkeyConfig, useHotkeys, UseHotkeysOptions } from "../../hooks";
22
23/** Identical to the return type of `useHotkeys` hook. */
24export interface HotkeysTarget2RenderProps {
25 handleKeyDown: React.KeyboardEventHandler<HTMLElement>;
26 handleKeyUp: React.KeyboardEventHandler<HTMLElement>;
27}
28
29export interface HotkeysTarget2Props {
30 /**
31 * Render prop which receives the same callback handlers generated by the `useHotkeys` hook.
32 * If your hotkey definitions are all global, you may supply an element instead.
33 */
34 children: JSX.Element | ((props: HotkeysTarget2RenderProps) => JSX.Element);
35
36 /** Hotkey definitions. */
37 hotkeys: HotkeyConfig[];
38
39 /** Hook customization options. */
40 options?: UseHotkeysOptions;
41}
42
43/**
44 * Utility component which allows consumers to use the new `useHotkeys` hook inside
45 * React component classes. The implementation simply passes through to the hook.
46 */
47export const HotkeysTarget2 = ({ children, hotkeys, options }: HotkeysTarget2Props): JSX.Element => {
48 const { handleKeyDown, handleKeyUp } = useHotkeys(hotkeys, options);
49
50 // run props validation
51 React.useEffect(() => {
52 if (!isNodeEnv("production")) {
53 if (typeof children !== "function" && hotkeys.some(h => !h.global)) {
54 console.error(Errors.HOTKEYS_TARGET2_CHILDREN_LOCAL_HOTKEYS);
55 }
56 }
57 }, [hotkeys]);
58
59 if (typeof children === "function") {
60 return children({ handleKeyDown, handleKeyUp });
61 } else {
62 return children;
63 }
64};