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

[DataGrid] Add touch support on column resize #537

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Expand Up @@ -10,6 +10,7 @@ export const useStyles = makeStyles(
const gridStyle: { root: any } = {
root: {
flex: 1,
touchAction: 'none',
oliviertassinari marked this conversation as resolved.
Show resolved Hide resolved
boxSizing: 'border-box',
position: 'relative',
border: `1px solid ${borderColor}`,
Expand Down
133 changes: 131 additions & 2 deletions packages/grid/_modules_/grid/hooks/features/useColumnResize.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export const useColumnResize = (columnsRef: React.RefObject<HTMLDivElement>, api
const colCellElementsRef = React.useRef<NodeListOf<Element>>();
const initialOffset = React.useRef<number>();
const stopResizeEventTimeout = React.useRef<number>();
const touchId = React.useRef<number>();

const updateWidth = (newWidth: number) => {
logger.debug(`Updating width to ${newWidth} for col ${colDefRef.current!.field}`);
Expand Down Expand Up @@ -110,12 +111,134 @@ export const useColumnResize = (columnsRef: React.RefObject<HTMLDivElement>, api
doc.addEventListener('mouseup', handleResizeMouseUp);
});

// TODO: remove support for Safari < 13.
// https://caniuse.com/#search=touch-action
//
// Safari, on iOS, supports touch action since v13.
// Over 80% of the iOS phones are compatible
// in August 2020.
let cachedSupportsTouchActionNone;
function doesSupportTouchActionNone() {
oliviertassinari marked this conversation as resolved.
Show resolved Hide resolved
if (cachedSupportsTouchActionNone === undefined) {
const element = document.createElement('div');
element.style.touchAction = 'none';
document.body.appendChild(element);
cachedSupportsTouchActionNone = window.getComputedStyle(element).touchAction === 'none';
element.parentElement!.removeChild(element);
}
return cachedSupportsTouchActionNone;
}

function trackFinger(event, currentTouchId) {
oliviertassinari marked this conversation as resolved.
Show resolved Hide resolved
if (currentTouchId !== undefined && event.changedTouches) {
for (let i = 0; i < event.changedTouches.length; i += 1) {
const touch = event.changedTouches[i];
if (touch.identifier === currentTouchId) {
return {
x: touch.clientX,
y: touch.clientY,
};
}
}

return false;
}

return {
x: event.clientX,
y: event.clientY,
};
}

const handleTouchEnd = useEventCallback((nativeEvent) => {
const finger = trackFinger(nativeEvent, touchId.current);

if (!finger) {
return;
}

// eslint-disable-next-line @typescript-eslint/no-use-before-define
stopListening();

apiRef.current!.updateColumn(colDefRef.current as ColDef);

clearTimeout(stopResizeEventTimeout.current);
stopResizeEventTimeout.current = setTimeout(() => {
apiRef.current.publishEvent(COL_RESIZE_STOP);
});

logger.debug(
`Updating col ${colDefRef.current!.field} with new width: ${colDefRef.current!.width}`,
);
});

const handleTouchMove = useEventCallback((nativeEvent) => {
const finger = trackFinger(nativeEvent, touchId.current);
if (!finger) {
return;
}

// Cancel move in case some other element consumed a touchmove event and it was not fired.
if (nativeEvent.type === 'mousemove' && nativeEvent.buttons === 0) {
handleTouchEnd(nativeEvent);
return;
}

let newWidth =
initialOffset.current + finger.x - colElementRef.current!.getBoundingClientRect().left;
newWidth = Math.max(MIN_COL_WIDTH, newWidth);

updateWidth(newWidth);
});

const handleTouchStart = useEventCallback((event: React.TouchEvent<HTMLElement>) => {
// If touch-action: none; is not supported we need to prevent the scroll manually.
DanailH marked this conversation as resolved.
Show resolved Hide resolved
if (!doesSupportTouchActionNone()) {
event.preventDefault();
}

const touch = event.changedTouches[0];
if (touch != null) {
// A number that uniquely identifies the current finger in the touch session.
touchId.current = touch.identifier;
}
// const finger = trackFinger(event, touchId.current);

colElementRef.current = event.currentTarget.closest(
`.${HEADER_CELL_CSS_CLASS}`,
) as HTMLDivElement;
const field = colElementRef.current.getAttribute('data-field') as string;
const colDef = apiRef.current.getColumnFromField(field);

logger.debug(`Start Resize on col ${colDef.field}`);
apiRef.current.publishEvent(COL_RESIZE_START, { field });

colDefRef.current = colDef;
colElementRef.current = columnsRef.current!.querySelector(
`[data-field="${colDef.field}"]`,
) as HTMLDivElement;

colCellElementsRef.current = findCellElementsFromCol(colElementRef.current) as NodeListOf<
Element
>;

initialOffset.current =
(colDefRef.current.width as number) -
(touch.clientX - colElementRef.current!.getBoundingClientRect().left);

const doc = ownerDocument(event.currentTarget as HTMLElement);
doc.addEventListener('touchmove', handleTouchMove);
doc.addEventListener('touchend', handleTouchEnd);
});

const stopListening = React.useCallback(() => {
const doc = ownerDocument(apiRef.current.rootElementRef!.current as HTMLElement);
doc.body.style.removeProperty('cursor');
doc.removeEventListener('mousemove', handleResizeMouseMove);
doc.removeEventListener('mouseup', handleResizeMouseUp);
}, [apiRef, handleResizeMouseMove, handleResizeMouseUp]);
doc.removeEventListener('touchmove', handleTouchMove);
doc.removeEventListener('touchend', handleTouchEnd);
}, [apiRef, handleResizeMouseMove, handleResizeMouseUp, handleTouchMove, handleTouchEnd]);

React.useEffect(() => {
return () => {
Expand All @@ -124,5 +247,11 @@ export const useColumnResize = (columnsRef: React.RefObject<HTMLDivElement>, api
};
}, [stopListening]);

return React.useMemo(() => ({ onMouseDown: handleMouseDown }), [handleMouseDown]);
return React.useMemo(
oliviertassinari marked this conversation as resolved.
Show resolved Hide resolved
() => ({
onMouseDown: handleMouseDown,
onTouchStart: handleTouchStart,
oliviertassinari marked this conversation as resolved.
Show resolved Hide resolved
}),
[handleMouseDown, handleTouchStart],
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const useVirtualRows = (
const paginationState = useGridSelector<PaginationState>(apiRef, paginationSelector);
const totalRowCount = useGridSelector<number>(apiRef, rowCountSelector);

const [scrollTo] = useScrollFn(apiRef, renderingZoneRef, colRef);
const [scrollTo] = useScrollFn(renderingZoneRef, colRef);
const [renderedColRef, updateRenderedCols] = useVirtualColumns(options, apiRef);

const setRenderingState = React.useCallback(
Expand Down
1 change: 0 additions & 1 deletion packages/grid/_modules_/grid/hooks/utils/useScrollFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { ScrollFn, ScrollParams } from '../../models/params/scrollParams';
import { useLogger } from './useLogger';

export function useScrollFn(
apiRef: any,
DanailH marked this conversation as resolved.
Show resolved Hide resolved
renderingZoneElementRef: React.RefObject<HTMLDivElement>,
columnHeadersElementRef: React.RefObject<HTMLDivElement>,
): [ScrollFn] {
Expand Down
2 changes: 1 addition & 1 deletion packages/storybook/src/stories/grid-resize.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const ResizeSmallDataset = () => {
Switch sizes
</button>
</div>
<div style={{ width: size.width, height: size.height, display: 'flex' }}>
<div style={{ width: size.width, height: size.height }}>
<XGrid rows={data.rows} columns={data.columns} />
</div>
</React.Fragment>
Expand Down