Expose React canvas hooks with scoped selectors and resource lifecycles

This commit is contained in:
2026-11-09 17:34:56 +08:00
parent d7b3321df1
commit 575b5a9256
18 changed files with 259 additions and 25 deletions
+11
View File
@@ -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();}});}});
}