Skip to content

Commit

Permalink
Implement 'isEnabled' Config Option (#9)
Browse files Browse the repository at this point in the history
* Remove check

* Implement listen prop

* Extend docs

* Fix build

* Rename 'listen' -> 'isEnabled'
  • Loading branch information
PauloMFJ authored Mar 20, 2023
1 parent f393c47 commit 6c29558
Show file tree
Hide file tree
Showing 9 changed files with 15,246 additions and 7,056 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"extends": "./node_modules/@buildinams/lint/react-typescript"
"extends": "./node_modules/@buildinams/lint/eslint/react-typescript"
}
2 changes: 1 addition & 1 deletion .github/workflows/publish-npm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Publish NPM

on:
release:
types: [created]
types: [published]

jobs:
test:
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ const elementRef = useRef<HTMLDivElement>(null);
useKeydown("Enter", () => {}, { target: elementRef });
```

## Conditionally Listening to Events

You can conditionally listen to events by passing a `isEnabled` prop the config object. This accepts a `boolean` value, and will only listen to events if the value is `true` (default). For example:

```tsx
import useKeydown from "@buildinams/use-keydown";

const [isEnabled, setIsEnabled] = useState(false);

useKeydown("Enter", () => {}, { isEnabled });
```

## Requirements

This library requires a minimum React version of `17.0.0`.
Expand Down
22,188 changes: 15,159 additions & 7,029 deletions package-lock.json

Large diffs are not rendered by default.

22 changes: 11 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@buildinams/use-keydown",
"description": "React hook for listening to custom keydown events.",
"version": "0.1.3",
"version": "0.2.0",
"license": "MIT",
"author": "Build in Amsterdam <[email protected]> (https://www.buildinamsterdam.com/)",
"main": "dist/index.js",
Expand Down Expand Up @@ -44,20 +44,20 @@
},
"devDependencies": {
"@babel/preset-env": "^7.20.2",
"@babel/preset-typescript": "^7.18.6",
"@buildinams/lint": "^0.0.3",
"@testing-library/react": "^13.4.0",
"@types/jest": "^29.2.5",
"@types/node": "^18.11.18",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.10",
"@babel/preset-typescript": "^7.21.0",
"@buildinams/lint": "^0.2.1",
"@testing-library/react": "^14.0.0",
"@types/jest": "^29.5.0",
"@types/node": "^18.15.3",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"babel": "^6.23.0",
"jest": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"jest": "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
"npm-run-all": "^4.1.5",
"react-dom": "^18.0.0",
"ts-jest": "^29.0.3",
"ts-node": "^10.9.1",
"typescript": "^4.9.4"
"typescript": "^4.9.5"
}
}
24 changes: 12 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const handleEventTargetKeydown = (
*
* @param config - Optional configuration object.
* @param config.target - Lets you specify a dom node or ref you want to attach the event listener to. Defaults to `window`.
* @param config.isEnabled - Lets you specify whether to listen for events or not. Defaults to `true`.
*
* @example
* useKeydown("KeyA", (event) => console.log(event));
Expand Down Expand Up @@ -109,21 +110,20 @@ const useKeydown = (
}, [keyCode, onChange]);

useEffect(() => {
const eventTarget = getEventTargetFromTarget(config?.target);
if (config?.isEnabled ?? true) {
const eventTarget = getEventTargetFromTarget(config?.target);

const eventHandler = (baseEvent: Event) => {
// As user can pass in a custom 'target', we need to check if the event is
// a 'KeyboardEvent' before we can safely access the 'event.code' property
const event = baseEvent as KeyboardEvent;
if (event.code) handleEventTargetKeydown(eventTarget, event);
};
const eventHandler = (event: KeyboardEvent) => {
if (event.code) handleEventTargetKeydown(eventTarget, event);
};

addListener(eventTarget, listenerRef, eventHandler);
addListener(eventTarget, listenerRef, eventHandler);

return () => {
removeListener(eventTarget, listenerRef);
};
}, [config?.target]);
return () => {
removeListener(eventTarget, listenerRef);
};
}
}, [config?.isEnabled, config?.target]);
};

export default useKeydown;
Expand Down
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export interface Config {
* Defaults to `window`.
*/
target?: Target;

/**
* This can be used to conditionally enable / disable the event listener.
* Defaults to `true`.
*/
isEnabled?: boolean;
}

export type EventHandler = (baseEvent: Event) => void;
Expand Down
45 changes: 43 additions & 2 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,16 @@ interface MockComponentProps {
keyCode: string | string[];
onChange: OnChangeEvent;
target?: Target;
isEnabled?: boolean;
}

const MockComponent = ({ keyCode, onChange, target }: MockComponentProps) => {
useKeydown(keyCode, onChange, { target });
const MockComponent = ({
keyCode,
onChange,
target,
isEnabled,
}: MockComponentProps) => {
useKeydown(keyCode, onChange, { target, isEnabled });
return <div />;
};

Expand All @@ -20,6 +26,10 @@ describe("The hook", () => {
jest.spyOn(window, "removeEventListener");
});

afterEach(() => {
jest.restoreAllMocks();
});

it("adds event listener on mount", () => {
render(<MockComponent keyCode="KeyG" onChange={jest.fn()} />);

Expand Down Expand Up @@ -191,4 +201,35 @@ describe("The hook", () => {
expect.objectContaining({ code: "KeyA" })
);
});

it("doesn't add event listener if listen is set to 'false' on mount", () => {
render(
<MockComponent keyCode="KeyG" onChange={jest.fn()} isEnabled={false} />
);

expect(window.addEventListener).not.toHaveBeenCalledWith(
"keydown",
expect.any(Function)
);
});

it("removes event listener if listen set to 'false' after mount", () => {
const { rerender } = render(
<MockComponent keyCode="KeyG" onChange={jest.fn()} />
);

expect(window.addEventListener).toHaveBeenCalledWith(
"keydown",
expect.any(Function)
);

rerender(
<MockComponent keyCode="KeyG" onChange={jest.fn()} isEnabled={false} />
);

expect(window.removeEventListener).toHaveBeenCalledWith(
"keydown",
expect.any(Function)
);
});
});
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"strictFunctionTypes": false,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
Expand Down

0 comments on commit 6c29558

Please sign in to comment.