@ue-too/board-react-adapter 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +2 -0
- package/index.js.map +6 -1
- package/package.json +3 -3
package/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import{useCallback as S,useEffect as I,useRef as L}from"react";import{Board as T}from"@ue-too/board";import{createContext as U,useCallback as O,useContext as V,useEffect as $,useMemo as Y,useRef as A,useSyncExternalStore as q}from"react";import{jsxDEV as j}from"react/jsx-dev-runtime";function P(G){let H=N(),J=G==="position"?"pan":G==="zoomLevel"?"zoom":"rotate",_=A(null);return q((K)=>H.camera.on(J,K),()=>{if(G==="position"){let K=H.camera.position,Q=_.current;if(Q&&Q.x===K.x&&Q.y===K.y)return Q;let X={...K};return _.current=X,X}return H.camera[G]})}function f(){let G=N();return Y(()=>{let J=G.getCameraRig();return{panByViewPort:(_)=>{J.panByViewPort(_)},panByWorld:(_)=>{J.panByWorld(_)},panToWorld:(_)=>{J.panToWorld(_)},panToViewPort:(_)=>{J.panToViewPort(_)},zoomToAtViewPort:(_,K)=>{J.zoomToAt(_,K)},zoomToAtWorld:(_,K)=>{J.zoomToAtWorld(_,K)},zoomTo:(_)=>{J.zoomTo(_)},zoomBy:(_)=>{J.zoomBy(_)},rotateTo:(_)=>{J.rotateTo(_)},rotateBy:(_)=>{J.rotateBy(_)}}},[G])}function w(){let G=N(),H=A(null);return q((J)=>{return G.camera.on("all",J)},()=>{let J=G.camera.position,_=G.camera.rotation,K=G.camera.zoomLevel,Q=H.current;if(Q&&Q.position.x===J.x&&Q.position.y===J.y&&Q.rotation===_&&Q.zoomLevel===K)return Q;let X={position:{...J},rotation:_,zoomLevel:K};return H.current=X,X})}function v(G){let H=N();$(()=>{H.cameraMux=G},[G,H])}function b(){let G=N(),H=O((J)=>{G.inputOrchestrator.processInputEvent(J)},[G]);return $(()=>{return G.disableEventListeners(),()=>{G.enableEventListeners()}},[G]),{processInputEvent:H}}var W=U(null);function Z({children:G}){let H=Y(()=>new T,[]);return j(W.Provider,{value:H,children:G},void 0,!1,void 0,this)}function N(){let G=V(W);if(G==null)throw Error("Board Provider not found");return G}function p(){return N().camera}function u(){let G=N();return q((H)=>G.onCanvasDimensionChange(H),()=>{return G.canvasDimensions})}function h(){let G=N();return O((H)=>{return G.convertWindowPoint2WorldCoord(H)},[G])}function m(G){let H=N();$(()=>{H.kmtParser=G},[G,H])}function d(G){let H=N();$(()=>{H.touchParser=G},[G,H])}function D(G){let H=L(null);I(()=>{let J=(_)=>{G(_),H.current=requestAnimationFrame(J)};return H.current=requestAnimationFrame(J),()=>{if(H.current)cancelAnimationFrame(H.current)}},[G])}function M(G){let H=N(),J=S((_)=>{H.step(_);let K=H.context;if(K==null){console.warn("Canvas context not available");return}G?.(_,K)},[G,H]);D(J)}import{PointCal as JG}from"@ue-too/math";import{jsxDEV as NG}from"react/jsx-dev-runtime";import{CanvasProxy as z}from"@ue-too/board";import{useState as C,useCallback as y}from"react";function F(){let[G,H]=C(()=>new z);return G}function YG(){let G=F(),H=y((J)=>{if(J==null){G.tearDown();return}G.attach(J)},[G]);return{canvasProxy:G,refCallback:H}}export{d as useCustomTouchEventParser,m as useCustomKMTEventParser,b as useCustomInputHandling,v as useCustomCameraMux,h as useCoordinateConversion,YG as useCanvasProxyWithRef,F as useCanvasProxy,u as useCanvasDimension,f as useCameraInput,P as useBoardCameraState,p as useBoardCamera,N as useBoard,M as useAnimationFrameWithBoard,D as useAnimationFrame,w as useAllBoardCameraState,Z as BoardProvider};
|
|
2
2
|
|
|
3
3
|
//# debugId=6B2CEE4C23D45A0964756E2164756E21
|
|
4
|
+
|
|
5
|
+
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": [
|
|
3
|
+
"sources": [
|
|
4
|
+
"useAnimationFrame.ts",
|
|
5
|
+
"useBoardify.tsx",
|
|
6
|
+
"Board.tsx",
|
|
7
|
+
"useCanvasProxy.ts"
|
|
8
|
+
],
|
|
4
9
|
"sourcesContent": [
|
|
5
10
|
"import { useCallback, useEffect, useRef } from 'react';\nimport { useBoard } from './useBoardify';\n\n/**\n * Hook to run a callback on every animation frame.\n *\n * @remarks\n * This hook uses `requestAnimationFrame` to execute a callback repeatedly for smooth animations.\n * The animation loop starts when the component mounts and stops when it unmounts, automatically\n * cleaning up the animation frame request.\n *\n * **Performance Note**: The callback is called on every frame, so ensure your callback is\n * optimized to avoid performance issues. The callback dependency should be stable to prevent\n * restarting the animation loop unnecessarily.\n *\n * @param callback - Function to call on each animation frame, receives the current timestamp\n *\n * @example\n * ```tsx\n * function AnimatedComponent() {\n * const [rotation, setRotation] = useState(0);\n *\n * useAnimationFrame((timestamp) => {\n * // Rotate 45 degrees per second\n * setRotation((prev) => prev + (Math.PI / 4) * (1 / 60));\n * });\n *\n * return <div style={{ transform: `rotate(${rotation}rad)` }}>Spinning!</div>;\n * }\n * ```\n *\n * @category Hooks\n * @see {@link useAnimationFrameWithBoard} for board-integrated animation loop\n */\nexport function useAnimationFrame(callback: (timestamp: number) => void) {\n const animationFrameRef = useRef<number | null>(null);\n\n useEffect(() => {\n const step = (timestamp: number) => {\n callback(timestamp);\n animationFrameRef.current = requestAnimationFrame(step);\n };\n\n // Start the animation loop\n animationFrameRef.current = requestAnimationFrame(step);\n\n // Cleanup function\n return () => {\n if (animationFrameRef.current) {\n cancelAnimationFrame(animationFrameRef.current);\n }\n };\n }, [callback]);\n}\n\n/**\n * Hook to run an animation loop integrated with the Board's step function.\n *\n * @remarks\n * This hook automatically calls `board.step(timestamp)` on every frame to update the board's\n * camera transform, then invokes your callback with the timestamp and canvas context.\n * This is the recommended way to implement drawing logic for board-based applications.\n *\n * The hook handles:\n * - Calling `board.step()` to update camera transforms\n * - Providing the canvas context for drawing\n * - Warning if context is not available\n * - Cleaning up the animation loop on unmount\n *\n * **Typical Usage Pattern**:\n * 1. Board calls `step()` to update transforms\n * 2. Your callback draws on the canvas\n * 3. Browser paints the frame\n * 4. Repeat next frame\n *\n * @param callback - Optional function to call after board.step(), receives timestamp and canvas context\n *\n * @example\n * ```tsx\n * function MyBoard() {\n * useAnimationFrameWithBoard((timestamp, ctx) => {\n * // Draw a rectangle at world position (0, 0)\n * ctx.fillStyle = 'red';\n * ctx.fillRect(0, 0, 100, 100);\n *\n * // Draw a circle that moves\n * const x = Math.sin(timestamp / 1000) * 200;\n * const y = Math.cos(timestamp / 1000) * 200;\n * ctx.fillStyle = 'blue';\n * ctx.beginPath();\n * ctx.arc(x, y, 20, 0, Math.PI * 2);\n * ctx.fill();\n * });\n *\n * return <Board width={800} height={600} />;\n * }\n * ```\n *\n * @category Hooks\n * @see {@link useAnimationFrame} for generic animation frame hook\n */\nexport function useAnimationFrameWithBoard(callback?: (timestamp: number, ctx: CanvasRenderingContext2D) => void) {\n\n const board = useBoard();\n\n const animationCallback = useCallback((timestamp: number) => {\n board.step(timestamp);\n const ctx = board.context;\n if (ctx == undefined) {\n console.warn('Canvas context not available');\n return;\n }\n callback?.(timestamp, ctx);\n }, [callback, board]);\n\n useAnimationFrame(animationCallback);\n}\n",
|
|
6
11
|
"import {Board as Boardify, KMTEventParser, KmtInputStateMachine, OutputEvent, TouchEventParser} from \"@ue-too/board\";\nimport {createContext, useCallback, useContext, useEffect, useMemo, useRef, useSyncExternalStore} from \"react\";\nimport { CameraMux, CameraState } from \"@ue-too/board/camera\";\nimport { Point } from \"@ue-too/math\";\n\n/**\n * Maps camera state keys to their corresponding event names.\n * @internal\n */\ntype StateToEventKey<K extends keyof CameraState> =\n K extends \"position\" ? \"pan\" : K extends \"zoomLevel\" ? \"zoom\" : \"rotate\";\n\n/**\n * Hook to subscribe to a specific camera state property with automatic re-rendering.\n *\n * @remarks\n * This hook uses React's `useSyncExternalStore` to efficiently subscribe to camera state changes.\n * It only triggers re-renders when the specified property actually changes, and uses caching\n * to maintain referential equality for object values (like position).\n *\n * **Performance**: The hook is optimized to prevent unnecessary re-renders by:\n * - Caching object values (position) to maintain referential equality\n * - Using `useSyncExternalStore` for efficient subscription management\n * - Only subscribing to the specific state property needed\n *\n * @typeParam K - Key of the camera state to subscribe to\n * @param state - The camera state property to track (\"position\", \"rotation\", or \"zoomLevel\")\n * @returns The current value of the specified camera state property\n *\n * @example\n * ```tsx\n * function CameraInfo() {\n * const position = useBoardCameraState('position');\n * const rotation = useBoardCameraState('rotation');\n * const zoomLevel = useBoardCameraState('zoomLevel');\n *\n * return (\n * <div>\n * Position: {position.x}, {position.y}<br/>\n * Rotation: {rotation}<br/>\n * Zoom: {zoomLevel}\n * </div>\n * );\n * }\n * ```\n *\n * @category Hooks\n * @see {@link useAllBoardCameraState} for subscribing to all camera state at once\n */\nexport function useBoardCameraState<K extends keyof CameraState>(state: K): CameraState[K] {\n const board = useBoard();\n const stateKey = (state === \"position\" ? \"pan\" : state === \"zoomLevel\" ? \"zoom\" : \"rotate\") as StateToEventKey<K>;\n const cachedPositionRef = useRef<{ x: number; y: number } | null>(null);\n\n return useSyncExternalStore(\n (cb) => board.camera.on(stateKey, cb),\n () => {\n // For position (object), we need to cache to avoid creating new objects\n if (state === \"position\") {\n const currentPosition = board.camera.position;\n const cached = cachedPositionRef.current;\n \n if (cached && cached.x === currentPosition.x && cached.y === currentPosition.y) {\n // Return cached snapshot to maintain referential equality\n return cached as CameraState[K];\n }\n \n // Cache the new position object\n const newPosition = {...currentPosition};\n cachedPositionRef.current = newPosition;\n return newPosition as CameraState[K];\n }\n \n // For primitive values (rotation, zoomLevel), return directly\n // Object.is works correctly for primitives\n return board.camera[state] as CameraState[K];\n },\n );\n}\n\n/**\n * Hook to get camera control functions for programmatic camera manipulation.\n *\n * @remarks\n * This hook provides a stable set of functions to control the camera programmatically.\n * The functions are memoized and only recreate when the board instance changes.\n *\n * All camera operations go through the camera rig, which enforces boundaries,\n * restrictions, and other constraints configured on the board.\n *\n * @returns Object containing camera control functions:\n * - `panToWorld` - Pan camera to a world position\n * - `panToViewPort` - Pan camera to a viewport position\n * - `zoomTo` - Set camera zoom to specific level\n * - `zoomBy` - Adjust camera zoom by delta\n * - `rotateTo` - Set camera rotation to specific angle\n * - `rotateBy` - Adjust camera rotation by delta\n *\n * @example\n * ```tsx\n * function CameraControls() {\n * const { panToWorld, zoomTo, rotateTo } = useCameraInput();\n *\n * return (\n * <div>\n * <button onClick={() => panToWorld({ x: 0, y: 0 })}>\n * Center Camera\n * </button>\n * <button onClick={() => zoomTo(1.0)}>\n * Reset Zoom\n * </button>\n * <button onClick={() => rotateTo(0)}>\n * Reset Rotation\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * @category Hooks\n */\nexport function useCameraInput(){\n const board = useBoard();\n\n const test = useMemo(()=>{\n const cameraRig = board.getCameraRig();\n\n return {\n panByViewPort: (delta: Point) => {\n cameraRig.panByViewPort(delta);\n },\n panByWorld: (delta: Point) => {\n cameraRig.panByWorld(delta);\n },\n panToWorld: (worldPosition: Point) => {\n cameraRig.panToWorld(worldPosition);\n },\n panToViewPort: (viewPortPosition: Point) => {\n cameraRig.panToViewPort(viewPortPosition);\n },\n zoomToAtViewPort: (zoomLevel: number, at: Point) => {\n cameraRig.zoomToAt(zoomLevel, at);\n },\n zoomToAtWorld: (zoomLevel: number, at: Point) => {\n cameraRig.zoomToAtWorld(zoomLevel, at);\n },\n zoomTo: (zoomLevel: number) => {\n cameraRig.zoomTo(zoomLevel);\n },\n zoomBy: (zoomDelta: number) => {\n cameraRig.zoomBy(zoomDelta);\n },\n rotateTo: (rotation: number) => {\n cameraRig.rotateTo(rotation);\n },\n rotateBy: (rotationDelta: number) => {\n cameraRig.rotateBy(rotationDelta);\n }\n }\n\n }, [board]);\n\n return test;\n}\n\n/**\n * Hook to subscribe to all camera state properties with automatic re-rendering.\n *\n * @remarks\n * This hook provides a snapshot of all camera state (position, rotation, zoomLevel) and\n * re-renders only when any of these values change. It's more efficient than using multiple\n * {@link useBoardCameraState} calls when you need all state properties.\n *\n * **Performance**: The hook uses snapshot caching to maintain referential equality when\n * values haven't changed, preventing unnecessary re-renders in child components.\n *\n * @returns Object containing:\n * - `position` - Current camera position {x, y}\n * - `rotation` - Current camera rotation in radians\n * - `zoomLevel` - Current camera zoom level\n *\n * @example\n * ```tsx\n * function CameraStateDisplay() {\n * const { position, rotation, zoomLevel } = useAllBoardCameraState();\n *\n * return (\n * <div>\n * <h3>Camera State</h3>\n * <p>Position: ({position.x.toFixed(2)}, {position.y.toFixed(2)})</p>\n * <p>Rotation: {rotation.toFixed(2)} rad</p>\n * <p>Zoom: {zoomLevel.toFixed(2)}x</p>\n * </div>\n * );\n * }\n * ```\n *\n * @category Hooks\n * @see {@link useBoardCameraState} for subscribing to individual state properties\n */\nexport function useAllBoardCameraState() {\n const board = useBoard();\n const cachedSnapshotRef = useRef<{\n position: { x: number; y: number };\n rotation: number;\n zoomLevel: number;\n } | null>(null);\n\n return useSyncExternalStore(\n (cb) => { return board.camera.on(\"all\", cb) },\n () => {\n const currentPosition = board.camera.position;\n const currentRotation = board.camera.rotation;\n const currentZoomLevel = board.camera.zoomLevel;\n\n // Check if values actually changed\n const cached = cachedSnapshotRef.current;\n if (\n cached &&\n cached.position.x === currentPosition.x &&\n cached.position.y === currentPosition.y &&\n cached.rotation === currentRotation &&\n cached.zoomLevel === currentZoomLevel\n ) {\n // Return cached snapshot to maintain referential equality\n return cached;\n }\n\n // Create new snapshot only when values changed\n const newSnapshot = {\n position: {...currentPosition},\n rotation: currentRotation,\n zoomLevel: currentZoomLevel,\n };\n cachedSnapshotRef.current = newSnapshot;\n return newSnapshot;\n },\n )\n}\n\n/**\n * Hook to set a custom camera multiplexer on the board.\n *\n * @remarks\n * This hook allows you to replace the board's default camera mux with a custom implementation.\n * Useful when you need custom input coordination, animation control, or state-based input blocking.\n *\n * The camera mux is updated whenever the provided `cameraMux` instance changes.\n *\n * @param cameraMux - Custom camera mux implementation to use\n *\n * @example\n * ```tsx\n * function CustomMuxBoard() {\n * const myCustomMux = useMemo(() => {\n * return createCameraMuxWithAnimationAndLock(camera);\n * }, []);\n *\n * useCustomCameraMux(myCustomMux);\n *\n * return <Board />;\n * }\n * ```\n *\n * @category Hooks\n * @see {@link CameraMux} from @ue-too/board for camera mux interface\n */\nexport function useCustomCameraMux(cameraMux: CameraMux) {\n const board = useBoard();\n\n useEffect(()=>{\n board.cameraMux = cameraMux;\n }, [cameraMux, board]);\n}\n\n/**\n * The custom input handling logic is before everything else. To use this hook, you would need to handle the event from the canvas and pass down the result to the `processInputEvent` function. \n * @returns Object containing the `processInputEvent` function\n * @example\n * ```typescript\n * const { processInputEvent } = useCustomInputHandling();\n * \n * const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {\n * // custom logic to determine the user input\n * \n * // if the user input is valid, pass it to the `processInputEvent` function\n * // e.g. pass the pan event down the input handling system\n * processInputEvent({\n * type: \"pan\",\n * delta: {\n * x: 10,\n * y: 10,\n * },\n * });\n * }\n * ```\n */\nexport function useCustomInputHandling(){\n const board = useBoard();\n\n const processInputEvent = useCallback((input: OutputEvent) => {\n board.inputOrchestrator.processInputEvent(input);\n }, [board]);\n\n useEffect(()=>{\n board.disableEventListeners();\n\n return () => {\n board.enableEventListeners();\n };\n }, [board])\n\n return {\n processInputEvent\n };\n}\n\n\n\n/**\n * React context for sharing a Board instance across components.\n * @internal\n */\nconst BoardContext = createContext<Boardify | null>(null);\n\n/**\n * Provider component for sharing a Board instance across the component tree.\n *\n * @remarks\n * This component creates a single Board instance and makes it available to all child\n * components via the {@link useBoard} hook. This is the recommended way to use the\n * board in React applications when you need to access it from multiple components.\n *\n * The board instance is created once when the provider mounts and persists for the\n * lifetime of the provider.\n *\n * @param props - Component props\n * @param props.children - Child components that will have access to the board\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <BoardProvider>\n * <Board width={800} height={600} />\n * <CameraControls />\n * <CameraStateDisplay />\n * </BoardProvider>\n * );\n * }\n * ```\n *\n * @category Components\n * @see {@link useBoard} for accessing the board instance\n */\nexport function BoardProvider({children}: {children: React.ReactNode}) {\n const board = useMemo(() => new Boardify(), []);\n return <BoardContext.Provider value={board}>{children}</BoardContext.Provider>;\n}\n\n/**\n * Hook to access the Board instance from context.\n *\n * @remarks\n * This hook retrieves the Board instance provided by {@link BoardProvider}.\n * It must be used within a component that is a descendant of BoardProvider,\n * otherwise it will throw an error.\n *\n * @returns The Board instance from context\n * @throws Error if used outside of BoardProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const board = useBoard();\n *\n * useEffect(() => {\n * // Configure board\n * board.camera.boundaries = { min: { x: -1000, y: -1000 }, max: { x: 1000, y: 1000 } };\n * }, [board]);\n *\n * return <div>Board ready</div>;\n * }\n * ```\n *\n * @category Hooks\n * @see {@link BoardProvider} for providing the board instance\n */\nexport function useBoard() {\n const board = useContext(BoardContext);\n if (board == null) {\n throw new Error('Board Provider not found');\n }\n return board;\n}\n\n/**\n * Hook to access the camera instance from the Board context.\n *\n * @remarks\n * This is a convenience hook that returns the camera from the board instance.\n * Equivalent to calling `useBoard().camera` but more concise.\n *\n * @returns The camera instance from the board\n * @throws Error if used outside of BoardProvider\n *\n * @example\n * ```tsx\n * function CameraConfig() {\n * const camera = useBoardCamera();\n *\n * useEffect(() => {\n * camera.setMinZoomLevel(0.5);\n * camera.setMaxZoomLevel(4.0);\n * }, [camera]);\n *\n * return null;\n * }\n * ```\n *\n * @category Hooks\n * @see {@link useBoard} for accessing the full board instance\n */\nexport function useBoardCamera() {\n const board = useBoard();\n return board.camera;\n}\n\nexport function useCanvasDimension() {\n const board = useBoard();\n\n return useSyncExternalStore((cb) => board.onCanvasDimensionChange(cb), ()=> {\n return board.canvasDimensions\n });\n}\n\nexport function useCoordinateConversion() {\n const board = useBoard();\n return useCallback((pointInWindow: Point)=>{\n return board.convertWindowPoint2WorldCoord(pointInWindow);\n }, [board]);\n}\n\n\nexport function useCustomKMTEventParser(eventParser: KMTEventParser) {\n const board = useBoard();\n\n useEffect(()=>{\n board.kmtParser = eventParser;\n }, [eventParser, board]);\n}\n\nexport function useCustomTouchEventParser(eventParser: TouchEventParser) {\n const board = useBoard();\n\n useEffect(()=>{\n board.touchParser = eventParser;\n }, [eventParser, board]);\n}\n",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ue-too/board-react-adapter",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.14.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/ue-too/ue-too.git"
|
|
@@ -23,8 +23,8 @@
|
|
|
23
23
|
"types": "./index.d.ts",
|
|
24
24
|
"module": "./index.js",
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@ue-too/board": "^0.
|
|
27
|
-
"@ue-too/math": "^0.
|
|
26
|
+
"@ue-too/board": "^0.14.0",
|
|
27
|
+
"@ue-too/math": "^0.14.0"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {
|
|
30
30
|
"react": "^19.0.1",
|