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

slider onchange event improvement #4921

Merged
merged 3 commits into from
Oct 14, 2024
Merged
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
32 changes: 21 additions & 11 deletions app/packages/core/src/plugins/SchemaIO/components/SliderView.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
import {
Box,
FormControl,
Expand All @@ -9,10 +8,11 @@ import {
TextField,
Typography,
} from "@mui/material";
import FieldWrapper from "./FieldWrapper";
import { autoFocus, getComponentProps } from "../utils";
import { debounce, isNumber, throttle } from "lodash";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useKey } from "../hooks";
import { isNumber } from "lodash";
import { autoFocus, getComponentProps } from "../utils";
import FieldWrapper from "./FieldWrapper";

type ValueFormat = "flt" | "%";

Expand Down Expand Up @@ -146,13 +146,23 @@ export default function SliderView(props) {
finalValue = ((max - min) / 100) * finalValue;
}

onChange(
path,
isMin
? [parseFloat(finalValue), parseFloat(data?.[1] || max)]
: [parseFloat(data?.[0] || min), parseFloat(finalValue)],
schema
);
const updateValue = () => {
onChange(
path,
isMin
? [parseFloat(finalValue), parseFloat(data?.[1] || max)]
: [parseFloat(data?.[0] || min), parseFloat(finalValue)],
schema
);
};

// Throttle the onChange action to once every 300ms
const throttledUpdate = throttle(updateValue, 300);

// Debounce for 200ms to ensure final typing before triggering update
const debouncedUpdate = debounce(throttledUpdate, 200);

debouncedUpdate();
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Refactor debouncing and throttling implementation for effectiveness

Defining throttledUpdate and debouncedUpdate inside the handleKeyDown function creates new instances on every key press, which means the debouncing and throttling won't work as intended. Additionally, applying debouncing and throttling to the Enter key event is unnecessary since it's a discrete action.

To effectively limit the number of times onChange is called due to user input, consider applying debouncing to the handleInputChange function or the onChange handler of the input fields. This way, the debounced functions are maintained across renders and are only created once.

Suggested refactor: Apply debouncing to input change handlers

Move the debouncing logic outside of the handleKeyDown function and apply it to the input change handlers using useCallback and useRef. Here's how you can modify the code:

+import React, { useEffect, useMemo, useRef, useState, useCallback } from "react";

+// Define the debounced update function using useCallback
+const debouncedUpdate = useCallback(
+  debounce((finalValue, isMin) => {
+    onChange(
+      path,
+      isMin
+        ? [parseFloat(finalValue), parseFloat(data?.[1] || max)]
+        : [parseFloat(data?.[0] || min), parseFloat(finalValue)],
+      schema
+    );
+  }, 200),
+  [onChange, path, data, min, max, schema]
+);

 const handleInputChange = (e, isMin: boolean) => {
   const value = e.target.value;

   if (!value) {
     isMin ? setMinText("") : setMaxText("");
   } else if (unit === "%") {
     const percentageValue = parseInt(value);
     if (percentageValue >= 0 && percentageValue <= 100) {
       isMin
         ? setMinText(percentageValue.toFixed())
         : setMaxText(percentageValue.toFixed());
     }
   } else {
     const floatValue = parseFloat(value);
     if (!isNaN(floatValue)) {
       isMin ? setMinText(value) : setMaxText(value);
     }
   }

+  // Call the debounced update function
+  let finalValue = value;
+  if (unit === "%") {
+    finalValue = ((max - min) / 100) * finalValue;
+  }
+  debouncedUpdate(finalValue, isMin);
 };

-const handleKeyDown = (e, isMin: boolean) => {
-  if (e.key === "Enter") {
-    let finalValue = e.target.value;
-    if (!finalValue) return;
-
-    if (unit === "%") {
-      finalValue = ((max - min) / 100) * finalValue;
-    }
-
-    const updateValue = () => {
-      onChange(
-        path,
-        isMin
-          ? [parseFloat(finalValue), parseFloat(data?.[1] || max)]
-          : [parseFloat(data?.[0] || min), parseFloat(finalValue)],
-        schema
-      );
-    };
-
-    // Throttle the onChange action to once every 300ms
-    const throttledUpdate = throttle(updateValue, 300);
-
-    // Debounce for 200ms to ensure final typing before triggering update
-    const debouncedUpdate = debounce(throttledUpdate, 200);
-
-    debouncedUpdate();
-  }
-};

+// Remove the handleKeyDown function if it's no longer needed

This refactor moves the debouncing logic to the handleInputChange function, which is called on every input change. The debounced function debouncedUpdate is memoized using useCallback, ensuring it retains state across renders and effective debouncing is applied.

Committable suggestion was skipped due to low confidence.

};

Expand Down
Loading