2024-06-27 03:41:31 +08:00
|
|
|
import { createContext, useCallback, useState } from "react";
|
2024-03-11 01:24:19 +08:00
|
|
|
|
|
|
|
export const TransformContext = createContext(null);
|
|
|
|
|
|
|
|
export default function TransformContextProvider({ children }) {
|
2024-06-27 03:41:31 +08:00
|
|
|
const [transform, setTransformInternal] = useState({
|
2024-03-11 01:24:19 +08:00
|
|
|
zoom: 1,
|
|
|
|
pan: { x: 0, y: 0 },
|
|
|
|
});
|
|
|
|
|
2024-06-27 03:41:31 +08:00
|
|
|
/**
|
|
|
|
* @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>
|
|
|
|
);
|
|
|
|
}
|