From e351feb9dc84cf36e7ee4f7895f72534cdc9e0ff Mon Sep 17 00:00:00 2001 From: Jordan Eldredge Date: Thu, 5 Dec 2019 22:38:29 -0800 Subject: [PATCH] Refactor ResizeTarget to use hooks --- js/components/ResizeTarget.tsx | 56 ++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/js/components/ResizeTarget.tsx b/js/components/ResizeTarget.tsx index 04348c37..0e73ff72 100644 --- a/js/components/ResizeTarget.tsx +++ b/js/components/ResizeTarget.tsx @@ -1,4 +1,4 @@ -import React from "react"; +import React, { useState, useEffect } from "react"; import { WINDOW_RESIZE_SEGMENT_WIDTH, WINDOW_RESIZE_SEGMENT_HEIGHT, @@ -13,16 +13,17 @@ interface Props { id?: string; } -export default class ResizeTarget extends React.Component { - handleMouseDown = (e: React.MouseEvent) => { - // Prevent dragging from highlighting text. - e.preventDefault(); - const [width, height] = this.props.currentSize; - const mouseStart = { - x: e.clientX, - y: e.clientY, - }; - +export default function ResizeTarget(props: Props) { + const { currentSize, setWindowSize, widthOnly, ...passThroughProps } = props; + const [mouseDown, setMouseDown] = useState(false); + const [mouseStart, setMouseStart] = useState( + null + ); + useEffect(() => { + if (mouseDown === false || mouseStart == null) { + return; + } + const [width, height] = currentSize; const handleMove = (ee: MouseEvent) => { const x = ee.clientX - mouseStart.x; const y = ee.clientY - mouseStart.y; @@ -32,28 +33,37 @@ export default class ResizeTarget extends React.Component { width + Math.round(x / WINDOW_RESIZE_SEGMENT_WIDTH) ); - const newHeight = this.props.widthOnly + const newHeight = widthOnly ? width : Math.max(0, height + Math.round(y / WINDOW_RESIZE_SEGMENT_HEIGHT)); const newSize: Size = [newWidth, newHeight]; - this.props.setWindowSize(newSize); + props.setWindowSize(newSize); }; window.addEventListener("mousemove", handleMove); - window.addEventListener("mouseup", () => { + + const handleMouseUp = () => setMouseDown(false); + window.addEventListener("mouseup", handleMouseUp); + + return () => { window.removeEventListener("mousemove", handleMove); + window.removeEventListener("mouseup", handleMouseUp); + }; + // We pruposefully close over the props from when the mouse went down + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [mouseStart, mouseDown]); + + const handleMouseDown = (e: React.MouseEvent) => { + // Prevent dragging from highlighting text. + e.preventDefault(); + setMouseStart({ + x: e.clientX, + y: e.clientY, }); + setMouseDown(true); }; - render() { - const { - currentSize, - setWindowSize, - widthOnly, - ...passThroughProps - } = this.props; - return
; - } + return
; }