drawDB/src/context/TransformContext.jsx

46 lines
1.2 KiB
React
Raw Normal View History

import { createContext, useCallback, useState } from "react";
2024-03-11 01:24:19 +08:00
export const TransformContext = createContext(null);
export default function TransformContextProvider({ children }) {
const [transform, setTransformInternal] = useState({
2024-03-11 01:24:19 +08:00
zoom: 1,
pan: { x: 0, y: 0 },
});
/**
* @type {typeof setTransformInternal}
*/
const setTransform = useCallback(
(actionOrValue) => {
const findFirstNumber = (...values) =>
values.find((value) => typeof value === "number" && !isNaN(value));
setTransformInternal((prev) => {
if (typeof actionOrValue === "function") {
actionOrValue = actionOrValue(prev);
}
return {
zoom: clamp(
findFirstNumber(actionOrValue.zoom, prev.zoom, 1),
0.02,
5,
),
pan: {
x: findFirstNumber(actionOrValue.pan?.x, prev.pan?.x, 0),
y: findFirstNumber(actionOrValue.pan?.y, prev.pan?.y, 0),
},
};
});
},
[setTransformInternal],
);
2024-03-11 01:24:19 +08:00
return (
<TransformContext.Provider value={{ transform, setTransform }}>
{children}
</TransformContext.Provider>
);
}