Expose React canvas hooks with scoped selectors and resource lifecycles
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
/** One immutable source, one cached selection; no second document or operation state. */
|
||||
export type ExternalSource<S>={getSnapshot():S;subscribe(notify:()=>void):()=>void};
|
||||
export function createSelectorStore<S,T>(source:ExternalSource<S>,selector:(snapshot:S)=>T,isEqual:(a:T,b:T)=>boolean=Object.is){
|
||||
let initialized=false,snapshot:S,selection:T;
|
||||
function getSnapshot():T{
|
||||
const current=source.getSnapshot();if(initialized&&Object.is(snapshot,current))return selection;
|
||||
const next=selector(current),same=initialized&&isEqual(selection,next);
|
||||
snapshot=current;if(!same)selection=next;initialized=true;return selection;
|
||||
}
|
||||
return Object.freeze({getSnapshot,subscribe(notify:()=>void){let observed=getSnapshot();return source.subscribe(()=>{let next:T;try{next=getSnapshot();}catch{notify();return;}if(!Object.is(observed,next)){observed=next;notify();}});}});
|
||||
}
|
||||
Reference in New Issue
Block a user