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

Better types and tests for useKeyProps #2468

Merged
merged 10 commits into from
Dec 30, 2022
Merged
Show file tree
Hide file tree
Changes from 9 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "Better types + tests for useKeyProps",
"packageName": "@fluentui-react-native/interactive-hooks",
"email": "[email protected]",
"dependentChangeType": "patch"
}
4 changes: 2 additions & 2 deletions packages/utils/interactive-hooks/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
const { configureJest } = require('@fluentui-react-native/scripts');
module.exports = configureJest();
const { configureReactNativeJest } = require('@fluentui-react-native/scripts');
module.exports = configureReactNativeJest('win32');
5 changes: 4 additions & 1 deletion packages/utils/interactive-hooks/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,16 @@
},
"devDependencies": {
"@fluentui-react-native/eslint-config-rules": "^0.1.1",
"@fluentui-react-native/test-tools": ">=0.1.1 <1.0.0",
"@office-iss/react-native-win32": "^0.68.0",
"@types/invariant": "^2.2.0",
"@types/jest": "^26.0.0",
"@types/react": "^17.0.2",
"@types/react-native": "^0.68.0",
"react": "17.0.2",
"react-native": "^0.68.0"
"react-native": "^0.68.0",
"react-native-macos": "^0.68.0",
"react-native-windows": "^0.68.0"
},
"peerDependencies": {
"react": "17.0.2",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Pressable with useKeyProps 1`] = `
<View
accessible={true}
focusable={true}
keyUpEvents={
Array [
Object {
"key": " ",
},
Object {
"key": "Enter",
},
]
}
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onKeyDown={[Function]}
onKeyUp={[Function]}
onMouseEnter={[Function]}
onMouseLeave={[Function]}
onResponderGrant={[Function]}
onResponderMove={[Function]}
onResponderRelease={[Function]}
onResponderTerminate={[Function]}
onResponderTerminationRequest={[Function]}
onStartShouldSetResponder={[Function]}
/>
`;
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AccessibilityActionEvent, GestureResponderEvent } from 'react-native';
import { KeyPressEvent } from './Pressability/CoreEventTypes';
import { isAccessibilityActionEvent, isGestureResponderEvent, isKeyPressEvent } from './events.types';
import { KeyPressEvent } from '../useKeyProps.types';
import { isAccessibilityActionEvent, isGestureResponderEvent, isKeyPressEvent } from '../events.types';

const createMockEvent = (nativeEvent) => {
return {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as React from 'react';
import * as renderer from 'react-test-renderer';
import { Pressable } from 'react-native';
import { useKeyProps } from '../useKeyProps';
import { checkRenderConsistency, checkReRender } from '@fluentui-react-native/test-tools';
import { PressablePropsExtended } from '../usePressableState.types';

const dummyFunction = () => {
console.log('dummy');
};

// Simple wrapper function to let us use `PressablePropsExtended` to fix type errors
const PressableWithDesktopProps = (props: PressablePropsExtended) => {
return <Pressable {...props} />;
};

it('Pressable with useKeyProps', () => {
const keyboardProps = useKeyProps(dummyFunction, ' ', 'Enter');
const tree = renderer.create(<PressableWithDesktopProps {...keyboardProps} />).toJSON();
expect(tree).toMatchSnapshot();
});

it('Simple Pressable with useKeyProps rendering does not invalidate styling', () => {
const keyboardProps = useKeyProps(dummyFunction, ' ', 'Enter');
checkRenderConsistency(() => <PressableWithDesktopProps {...keyboardProps} />, 2);
});

it('Pressable with useKeyProps re-renders correctly', () => {
const keyboardProps = useKeyProps(dummyFunction, ' ', 'Enter');
checkReRender(() => <PressableWithDesktopProps {...keyboardProps} />, 2);
});
Saadnajmi marked this conversation as resolved.
Show resolved Hide resolved
4 changes: 2 additions & 2 deletions packages/utils/interactive-hooks/src/events.types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AccessibilityActionEvent, GestureResponderEvent } from 'react-native';
import { KeyPressEvent, MouseEvent } from './Pressability/CoreEventTypes';
import { AccessibilityActionEvent, GestureResponderEvent, MouseEvent } from 'react-native';
import { KeyPressEvent } from './useKeyProps.types';

export type InteractionEvent = GestureResponderEvent | MouseEvent | KeyPressEvent | AccessibilityActionEvent;

Expand Down
3 changes: 1 addition & 2 deletions packages/utils/interactive-hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ export type {
export type {
BlurEvent,
FocusEvent,
KeyPressEvent,
Layout,
LayoutEvent,
MouseEvent,
Expand All @@ -56,8 +55,8 @@ export type {
TextLayout,
TextLayoutEvent,
} from './Pressability/CoreEventTypes';
export type { KeyPressEvent, KeyCallback, KeyPressProps } from './useKeyProps.types';
export { preferKeyDownForKeyEvents, useKeyCallback, useKeyDownProps, useKeyProps, useKeyUpProps } from './useKeyProps';
export type { KeyCallback, KeyPressProps } from './useKeyProps';
export { useOnPressWithFocus } from './useOnPressWithFocus';
export type { OnPressCallback, OnPressWithFocusCallback } from './useOnPressWithFocus';
export { getAccessibilityState } from './getAccessibilityState';
18 changes: 0 additions & 18 deletions packages/utils/interactive-hooks/src/isModifierKey.ts

This file was deleted.

79 changes: 0 additions & 79 deletions packages/utils/interactive-hooks/src/useKeyProps.macos.ts

This file was deleted.

134 changes: 104 additions & 30 deletions packages/utils/interactive-hooks/src/useKeyProps.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { KeyPressEvent } from './Pressability/CoreEventTypes';
import { IHandledKeyboardEvent } from '@office-iss/react-native-win32';

export type KeyCallback = (args?: KeyPressEvent) => void;

export type KeyPressProps = {
onKeyDown?: KeyCallback;
validKeysDown?: string[]; // macOS
keyDownEvents?: IHandledKeyboardEvent[]; // win32
onKeyUp?: KeyCallback;
validKeysUp?: string[]; // macOS
keyUpEvents?: IHandledKeyboardEvent[]; // win32
};
import * as React from 'react';
import { Platform } from 'react-native';
import { memoize } from '@fluentui-react-native/memo-cache';
import { KeyCallback, KeyPressEvent, KeyPressProps } from './useKeyProps.types';

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noOp = () => {};
/**
* Verifies if nativeEvent contains modifier key.
* @param nativeEvent
* @returns `true` if one or more of modifier keys are `true`
*/
export const isModifierKey = (nativeEvent: any): boolean => {
return (
nativeEvent &&
(nativeEvent.alt ||
nativeEvent.altKey ||
nativeEvent.ctrl ||
nativeEvent.ctrlKey ||
nativeEvent.meta ||
nativeEvent.metaKey ||
nativeEvent.shift ||
nativeEvent.shiftKey)
);
};

/**
* Re-usable hook for an onKeyDown event.
Expand All @@ -23,38 +29,106 @@ const noOp = () => {};
* @returns onKeyEvent() - Callback to determine if key was pressed, if so, call userCallback
* @deprecated use the hook `useKeyProps` instead
*/
export function useKeyCallback(_userCallback?: KeyCallback, ..._keys: string[]) {
return noOp;
export function useKeyCallback(userCallback?: KeyCallback, ...keys: string[]) {
const onKeyEvent = React.useCallback(
(e: KeyPressEvent) => {
if (userCallback !== undefined && (keys === undefined || keys.includes(e.nativeEvent.key))) {
userCallback(e);
e.stopPropagation();
}
},
[keys, userCallback],
Saadnajmi marked this conversation as resolved.
Show resolved Hide resolved
);

return onKeyEvent;
}

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noOp2 = (_userCallback: KeyCallback, ..._keys: string[]) => {
return {};
};
function getKeyCallbackWorker(userCallback?: KeyCallback, ...keys: string[]) {
const onKeyEvent = (e: KeyPressEvent) => {
if (userCallback !== undefined && !isModifierKey(e.nativeEvent) && (keys === undefined || keys.includes(e.nativeEvent.key))) {
userCallback(e);
e.stopPropagation();
}
};
return onKeyEvent;
}

function getKeyUpPropsWorker(userCallback: KeyCallback, ...keys: string[]): KeyPressProps {
const keyboardProps = Platform.select({
ios: undefined,
android: undefined,
macos: {
onKeyUp: getKeyCallbackWorker(userCallback, ...keys),
validKeysUp: keys,
},
windows: {
onKeyUp: getKeyCallbackWorker(userCallback, ...keys),
keyUpEvents: keys.map((keyCode) => {
return { key: keyCode };
}),
},
// win32
default: {
onKeyUp: getKeyCallbackWorker(userCallback, ...keys),
keyUpEvents: keys.map((keyCode) => {
return { key: keyCode };
}),
},
});
return keyboardProps;
}

function getKeyDownPropsWorker(userCallback: KeyCallback, ...keys: string[]): KeyPressProps {
const keyboardProps = Platform.select({
ios: undefined,
android: undefined,
macos: {
onKeyDown: getKeyCallbackWorker(userCallback, ...keys),
validKeysDown: keys,
},
windows: {
onKeyDown: getKeyCallbackWorker(userCallback, ...keys),
keyDownEvents: keys.map((keyCode) => {
return { key: keyCode };
}),
},
// win32
default: {
onKeyDown: getKeyCallbackWorker(userCallback, ...keys),
keyDownEvents: keys.map((keyCode) => {
return { key: keyCode };
}),
},
});
return keyboardProps;
}

/**
* Re-usable hook for an onKeyUp event. noOp on unsupported platforms.
* Re-usable hook for an onKeyUp event.
* @param userCallback The function you want to be called once the key has been activated on key up
* @param keys A string of the key you want to perform some action on. If undefined, always invokes userCallback
* @returns KeyPressProps: An object containing the correct platform specific props to handle key press
* @returns KeyPressProps: An object containing the correct platform specific props to handle key press
*/
export const useKeyUpProps = noOp2;
export const useKeyUpProps = memoize(getKeyUpPropsWorker);

/**
* Re-usable hook for an onKeyDown event. noOp on unsupported platforms.
* Re-usable hook for an onKeyDown event.
* @param userCallback The function you want to be called once the key has been activated on key down
* @param keys A string of the key you want to perform some action on. If undefined, always invokes userCallback
* @returns KeyPressProps: An object containing the correct platform specific props to handle key press
*/
export const useKeyDownProps = noOp2;
export const useKeyDownProps = memoize(getKeyDownPropsWorker);

/**
* Re-usable hook for keyboard events. on macOS, this is onKeyDown, while on windows this is onKeyUp.
* @param userCallback The function you want to be called once the key has been activated on key down
* @param keys A string of the key you want to perform some action on. If undefined, always invokes userCallback
* @returns KeyPressProps: An object containing the correct platform specific props to handle key press
* @returns KeyPressProps: An object containing the correct platform specific props to handle key press
*/
export const useKeyProps = noOp2;
export const useKeyProps = memoize(getKeyUpPropsWorker);
Saadnajmi marked this conversation as resolved.
Show resolved Hide resolved

/** Exposes the behavior of useKeyProps for the current platform as a boolean */
export const preferKeyDownForKeyEvents = false;
export const preferKeyDownForKeyEvents = Platform.select({
macos: true,
default: false,
});
Loading