Skip to content

Commit

Permalink
refactor: Refactor EditableTextLabel component to use useRef
Browse files Browse the repository at this point in the history
for touchCount and touchTimeout
  • Loading branch information
kyoyadmoon committed Dec 20, 2023
1 parent a3439b8 commit f7f8e56
Showing 1 changed file with 26 additions and 12 deletions.
38 changes: 26 additions & 12 deletions packages/core/src/EditableTextLabel.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import React, { useState, useEffect, useCallback } from 'react';
import React, {
useState,
useEffect,
useCallback,
useRef,
} from 'react';
import PropTypes from 'prop-types';
import keycode from 'keycode';

Expand Down Expand Up @@ -40,18 +45,18 @@ const EditableTextLabel = React.memo(({
...labelProps
}) => {
const [inEdit, setInEdit] = useState(inEditProp || false);
const [touchCount, setTouchCount] = useState(0);
// For simulating double-touch
const [dblTouchTimeout, setDblTouchTimeout] = useState(null);
const touchCountRef = useRef(0);
const touchTimeoutRef = useRef(null);

const getEditabilityControlled = useCallback(
() => inEditProp !== undefined,
[inEditProp]
);

const resetDblTouchSimulation = () => {
setTouchCount(0);
setDblTouchTimeout(null);
touchCountRef.current = 0;
touchTimeoutRef.current = null;
};

useEffect(
Expand All @@ -63,6 +68,15 @@ const EditableTextLabel = React.memo(({
[getEditabilityControlled, inEditProp]
);

useEffect(
() => () => {
if (touchTimeoutRef.current) {
clearTimeout(touchTimeoutRef.current);
}
},
[]
);

const leaveEditModeIfNotControlled = () => {
if (!getEditabilityControlled()) {
setInEdit(false);
Expand All @@ -82,7 +96,7 @@ const EditableTextLabel = React.memo(({
};

const handleTouchEnd = (event) => {
const currentCount = touchCount + 1;
const currentCount = touchCountRef.current + 1;

if (currentCount === 2) {
// Simulates “double touch”
Expand All @@ -92,17 +106,17 @@ const EditableTextLabel = React.memo(({
}

/**
* Clears prev timeout to keep touch counts, and then
* create new timeout to reset touch counts.
*/
global.clearTimeout(dblTouchTimeout);
* Clears prev timeout to keep touch counts, and then
* create new timeout to reset touch counts.
*/
global.clearTimeout(touchTimeoutRef.current);
const resetTimeout = global.setTimeout(
resetDblTouchSimulation,
TOUCH_TIMEOUT_MS
);

setTouchCount(currentCount);
setDblTouchTimeout(resetTimeout);
touchCountRef.current = currentCount;
touchTimeoutRef.current = resetTimeout;
};

const handleInputBlur = (event) => {
Expand Down

0 comments on commit f7f8e56

Please sign in to comment.