20 lines
1.0 KiB
TypeScript
20 lines
1.0 KiB
TypeScript
"use client";
|
|
|
|
import {useCallback,useEffect,useRef} from 'react';
|
|
import {useStoreApi,useUpdateNodeInternals} from '@xyflow/react';
|
|
import {createNodeInternalsBatch} from '@/lib/canvas-bindings/node-internals';
|
|
|
|
// useStoreApi wraps the API per hook. Its shared getState function identifies the
|
|
// actual store, separating canvases even when they render the same project.
|
|
const batches=new WeakMap<object,ReturnType<typeof createNodeInternalsBatch>>();
|
|
export function useNodeInternalsUpdate(id:string){
|
|
const scope=useStoreApi().getState,update=useUpdateNodeInternals();
|
|
const lease=useRef<ReturnType<ReturnType<typeof createNodeInternalsBatch>['acquire']>|undefined>(undefined);
|
|
useEffect(()=>{
|
|
let batch=batches.get(scope);if(!batch){batch=createNodeInternalsBatch(update);batches.set(scope,batch);}
|
|
const owner=batch.acquire(id);lease.current=owner;
|
|
return()=>{owner.dispose();if(lease.current===owner)lease.current=undefined;};
|
|
},[scope,update,id]);
|
|
return useCallback(()=>lease.current?.invalidate(),[]);
|
|
}
|