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

React resize handle #65

Merged
merged 16 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
1 change: 1 addition & 0 deletions packages/react-resize-handle/.storybook/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const config: StorybookConfig = {
stories: ['../stories/**/index.stories.@(js|jsx|ts|tsx|mdx)'],
addons: [
'@nx/react/plugins/storybook',
'@storybook/addon-actions',
{
name: '@storybook/addon-storysource',
options: {
Expand Down
1 change: 1 addition & 0 deletions packages/react-resize-handle/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"private": true,
"peerDependencies": {
"@fluentui/react-components": ">=9.35.1 <10.0.0",
"@fluentui/react-utilities": ">=9.15.1 <10.0.0",
"@types/react": ">=16.8.0 <19.0.0",
"@types/react-dom": ">=16.8.0 <19.0.0",
"react": ">=16.8.0 <19.0.0",
Expand Down
81 changes: 81 additions & 0 deletions packages/react-resize-handle/src/hooks/useKeyboardHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { useEventCallback, useFluent } from '@fluentui/react-components';
import * as React from 'react';
import { GrowDirection, SupportedKeys } from '../types';
import { elementDimension } from '../utils/index';

export type UseKeyboardHandlerOptions = {
onValueChange: (value: number) => void;
elementRef: React.RefObject<HTMLElement>;
growDirection: GrowDirection;
};

const DEFAULT_STEP = 20;

const multipliers: Record<
GrowDirection,
Partial<Record<SupportedKeys, number>>
> = {
end: {
ArrowRight: 1,
ArrowLeft: -1,
},
start: {
ArrowRight: -1,
ArrowLeft: 1,
},
up: {
ArrowUp: 1,
ArrowDown: -1,
},
down: {
ArrowUp: -1,
ArrowDown: 1,
},
};

function isSupportedKey(
growDirection: GrowDirection,
key: string
): key is SupportedKeys {
return (
Object.prototype.hasOwnProperty.call(multipliers, growDirection) &&
Object.prototype.hasOwnProperty.call(multipliers[growDirection], key)
);
}

export const useKeyboardHandler = (options: UseKeyboardHandlerOptions) => {
const { elementRef, onValueChange, growDirection } = options;
const { dir } = useFluent();

const onKeyDown = useEventCallback((event: KeyboardEvent) => {
let newValue = elementDimension(elementRef.current, growDirection);

if (isSupportedKey(growDirection, event.key)) {
const multiplier = multipliers[growDirection][event.key] ?? 1;
const directionMultiplier =
dir === 'rtl' && ['start', 'end'].includes(growDirection) ? -1 : 1;

newValue += multiplier * DEFAULT_STEP * directionMultiplier;
}

onValueChange(Math.round(newValue));
});

const attachHandlers = React.useCallback(
(node: HTMLElement) => {
node.addEventListener('keydown', onKeyDown);
},
[onKeyDown]
);
const detachHandlers = React.useCallback(
(node: HTMLElement) => {
node.removeEventListener('keydown', onKeyDown);
},
[onKeyDown]
);

return {
attachHandlers,
detachHandlers,
};
};
137 changes: 137 additions & 0 deletions packages/react-resize-handle/src/hooks/useMouseHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { useFluent, useEventCallback } from '@fluentui/react-components';
import {
getEventClientCoords,
NativeTouchOrMouseEvent,
isMouseEvent,
isTouchEvent,
} from '@fluentui/react-utilities';
import * as React from 'react';
import { GrowDirection } from '../types';
import { elementDimension } from '../utils';

export type UseMouseHandlerParams = {
onDown?: (event: NativeTouchOrMouseEvent) => void;
onMove?: (event: NativeTouchOrMouseEvent) => void;
elementRef: React.RefObject<HTMLElement>;
growDirection: GrowDirection;
onValueChange: (value: number) => void;
onDragEnd?: (e: NativeTouchOrMouseEvent) => void;
onDragStart?: (e: NativeTouchOrMouseEvent) => void;
};

export function useMouseHandler(params: UseMouseHandlerParams) {
const { targetDocument, dir } = useFluent();
const targetWindow = targetDocument?.defaultView;

const dragStartOriginCoords = React.useRef({ clientX: 0, clientY: 0 });
const { growDirection, onValueChange, elementRef } = params;

const initialElementSize = React.useRef(
elementDimension(elementRef.current, growDirection)
);

const recalculatePosition = useEventCallback(
(event: NativeTouchOrMouseEvent) => {
const { clientX, clientY } = getEventClientCoords(event);
const deltaCoords = [
clientX - dragStartOriginCoords.current.clientX,
clientY - dragStartOriginCoords.current.clientY,
];

let newValue = initialElementSize.current;

switch (growDirection) {
case 'end':
newValue += deltaCoords[0] * (dir === 'rtl' ? -1 : 1);
break;
case 'start':
newValue -= deltaCoords[0] * (dir === 'rtl' ? -1 : 1);
break;
case 'up':
newValue -= deltaCoords[1];
break;
case 'down':
newValue += deltaCoords[1];
break;
}

onValueChange(Math.round(newValue));

// If, after resize, the element size is different than the value we set, that we have reached the boundary
// and the element size is controlled by something else (minmax, clamp, max, min css functions etc.)
// In this case, we need to update the value to the actual element size so that the css var and a11y props
// reflect the reality.
const elSize = elementDimension(elementRef.current, growDirection);
if (elSize !== newValue) {
onValueChange(elSize);
}
}
);

const onDrag = useEventCallback((event: NativeTouchOrMouseEvent) => {
targetWindow?.requestAnimationFrame(() => recalculatePosition(event));
});

const onDragEnd = useEventCallback((event: NativeTouchOrMouseEvent) => {
if (isMouseEvent(event)) {
targetDocument?.removeEventListener('mouseup', onDragEnd);
targetDocument?.removeEventListener('mousemove', onDrag);
}

if (isTouchEvent(event)) {
targetDocument?.removeEventListener('touchend', onDragEnd);
targetDocument?.removeEventListener('touchmove', onDrag);
}

params.onDragEnd?.(event);
});

const onPointerDown = useEventCallback((event: NativeTouchOrMouseEvent) => {
dragStartOriginCoords.current = getEventClientCoords(event);
initialElementSize.current = elementDimension(
elementRef.current,
growDirection
);

if (event.defaultPrevented) {
return;
}

if (isMouseEvent(event)) {
// ignore other buttons than primary mouse button
if (event.target !== event.currentTarget || event.button !== 0) {
return;
}
targetDocument?.addEventListener('mouseup', onDragEnd);
targetDocument?.addEventListener('mousemove', onDrag);
}

if (isTouchEvent(event)) {
targetDocument?.addEventListener('touchend', onDragEnd);
targetDocument?.addEventListener('touchmove', onDrag);
}

params.onDragStart?.(event);
});

const attachHandlers = React.useCallback(
(node: HTMLElement) => {
node.addEventListener('mousedown', onPointerDown);
node.addEventListener('touchstart', onPointerDown);
},
[onPointerDown]
);

const detachHandlers = React.useCallback(
(node: HTMLElement) => {
node.removeEventListener('mousedown', onPointerDown);
node.removeEventListener('touchstart', onPointerDown);
},
[onPointerDown]
);

return {
attachHandlers,
detachHandlers,
};
}
Loading
Loading