Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
Expand Up @@ -10,6 +10,7 @@ export const useStyles = makeStyles(
const gridStyle: { root: any } = {
root: {
flex: 1,
touchAction: 'none',
boxSizing: 'border-box',
position: 'relative',
border: `1px solid ${borderColor}`,
Expand Down
145 changes: 142 additions & 3 deletions packages/grid/_modules_/grid/hooks/features/useColumnResize.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,48 @@ import { COL_RESIZE_START, COL_RESIZE_STOP } from '../../constants/eventsConstan
import { HEADER_CELL_CSS_CLASS } from '../../constants/cssClassesConstants';
import { findCellElementsFromCol } from '../../utils';
import { ApiRef } from '../../models';
import { CursorCoordinates } from '../../models/api/columnReorderApi';

const MIN_COL_WIDTH = 50;
let cachedSupportsTouchActionNone = false;

// 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.
function doesSupportTouchActionNone(): boolean {
if (!cachedSupportsTouchActionNone) {
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): CursorCoordinates | boolean {
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,
};
}

// TODO improve experience for last column
export const useColumnResize = (columnsRef: React.RefObject<HTMLDivElement>, apiRef: ApiRef) => {
Expand All @@ -18,6 +58,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,19 +151,117 @@ export const useColumnResize = (columnsRef: React.RefObject<HTMLDivElement>, api
doc.addEventListener('mouseup', handleResizeMouseUp);
});

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 as CursorCoordinates).x -
colElementRef.current!.getBoundingClientRect().left;
newWidth = Math.max(MIN_COL_WIDTH, newWidth);

updateWidth(newWidth);
});

const handleTouchStart = useEventCallback((event) => {
// If touch-action: none; is not supported we need to prevent the scroll manually.
colElementRef.current = event.target.closest(`.${HEADER_CELL_CSS_CLASS}`) as HTMLDivElement;

// Let the event bubble if the target is not a col separator
if (!colElementRef.current) return;

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 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(() => {
const doc = ownerDocument(apiRef.current.rootElementRef!.current as HTMLElement);
doc.addEventListener('touchstart', handleTouchStart, {
passive: doesSupportTouchActionNone(),
});

return () => {
doc.removeEventListener('touchstart', handleTouchStart);

clearTimeout(stopResizeEventTimeout.current);
stopListening();
};
}, [stopListening]);
}, [stopListening, apiRef, handleTouchStart]);

return React.useMemo(() => ({ onMouseDown: handleMouseDown }), [handleMouseDown]);
return React.useMemo(
() => ({
onMouseDown: handleMouseDown,
}),
[handleMouseDown],
);
};
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,
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