[Refactor] Unify and encapsulate slider UI logic into useSliderLogic hook. Part 1.
This commit is contained in:
@@ -200,4 +200,66 @@ export const useConfigFunctions = (Category) => {
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||
|
||||
export const useSliderLogic = ({
|
||||
current_value,
|
||||
setterFunction,
|
||||
postUpdateAction,
|
||||
min,
|
||||
max,
|
||||
step = 1,
|
||||
hidden_label_values
|
||||
}) => {
|
||||
const [ui_value, setUiValue] = useState(current_value.data);
|
||||
|
||||
const labelFormatter = useCallback((value) => {
|
||||
if (hidden_label_values && hidden_label_values.includes(value)) {
|
||||
return "";
|
||||
}
|
||||
return value;
|
||||
}, [hidden_label_values]);
|
||||
|
||||
const marks = useMemo(() => {
|
||||
return createMarks(min, max, step, labelFormatter);
|
||||
}, [min, max, step, labelFormatter]);
|
||||
|
||||
const onchangeFunction = useCallback((value) => {
|
||||
setUiValue(value);
|
||||
}, []);
|
||||
|
||||
const onchangeCommittedFunction = useCallback((value) => {
|
||||
setterFunction(value);
|
||||
}, [setterFunction]);
|
||||
|
||||
useEffect(() => {
|
||||
if (current_value.data !== ui_value) {
|
||||
setUiValue(current_value.data);
|
||||
}
|
||||
if (postUpdateAction) {
|
||||
postUpdateAction();
|
||||
}
|
||||
}, [current_value.data]);
|
||||
|
||||
return {
|
||||
ui_value,
|
||||
onchangeFunction,
|
||||
onchangeCommittedFunction,
|
||||
marks,
|
||||
};
|
||||
};
|
||||
|
||||
const createMarks = (min, max, step = 1, labelFormatter = (value) => value) => {
|
||||
const marks = [];
|
||||
let current_value = min;
|
||||
while (current_value <= max) {
|
||||
const fixedValue = parseFloat(current_value.toFixed(1));
|
||||
const label = labelFormatter(fixedValue);
|
||||
marks.push({ value: fixedValue, label: `${label}` });
|
||||
current_value += step;
|
||||
}
|
||||
return marks;
|
||||
};
|
||||
@@ -13,4 +13,9 @@ export { useHotkeys } from "./config_page_setter/hotkeys/useHotkeys.js";
|
||||
export { useSupporters } from "./config_page_setter/supporters/useSupporters.js";
|
||||
export { usePlugins } from "./config_page_setter/plugins/usePlugins.js";
|
||||
|
||||
export { useSettingBoxScrollPosition } from "./config_page_setter/_aux/useSettingBoxScrollPosition.js";
|
||||
export { useSettingBoxScrollPosition } from "./config_page_setter/_aux/useSettingBoxScrollPosition.js";
|
||||
|
||||
|
||||
export {
|
||||
useSliderLogic,
|
||||
} from "./config_page_setter/useSettingsLogics.js";
|
||||
Reference in New Issue
Block a user