@zenflux/react-commander 0.0.16 → 0.0.18

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.
@@ -138,6 +138,11 @@ export interface DCommandIdArgs {
138
138
  /**
139
139
  * Interface `DCommandArgs` - This interface defines the structure for the arguments provided to commands
140
140
  **/
141
+ /**
142
+ * A callback of a command's hook (`onBefore()`, `onAfter()`...): what the command ran with, and its result.
143
+ */
144
+ export type DCommandCallback = ( args?: any, options?: any ) => any;
145
+
141
146
  export type DCommandArgs = {
142
147
  [ key: string | number | symbol ]: any
143
148
  };
@@ -8,4 +8,5 @@ export { useCommandRunner } from "./use-command/use-command-runner";
8
8
  export { useCommandHook } from "./use-command/use-command-hook";
9
9
  export { useChildCommandHook } from "./use-child-command/use-child-command-hook";
10
10
  export { useChildCommandRunner } from "./use-child-command/use-child-command-runner";
11
-
11
+ export { useSelect } from "./use-select";
12
+ export type { SelectFrom } from "./use-select";
@@ -14,31 +14,28 @@ export function useChildCommandHook(
14
14
  ) {
15
15
  const children = useCommanderChildrenComponents( childComponentName );
16
16
 
17
+ // The latest handler, called through one that stays: a handler written inline is new at every render, and the
18
+ // children are hooked once, not again each time.
19
+ const handlerRef = React.useRef( handler );
20
+ handlerRef.current = handler;
21
+
22
+ const optsRef = React.useRef( opts );
23
+ optsRef.current = opts;
24
+
17
25
  React.useEffect( () => {
18
26
  const disposers: Array<() => void> = [];
19
27
 
20
- const alive = children.filter( cmd => {
21
- try {
22
- return typeof cmd.isAlive === "function" ? cmd.isAlive() : true;
23
- } catch {
24
- return false;
25
- }
26
- } );
28
+ children.forEach( ( cmd ) => {
29
+ if ( optsRef.current?.filter && ! optsRef.current.filter( cmd ) ) return;
30
+ if ( ! cmd.isAlive() ) return;
27
31
 
28
- alive.forEach( ( cmd ) => {
29
- if ( opts?.filter && !opts.filter( cmd ) ) return;
30
- if ( cmd.isAlive && !cmd.isAlive() ) return;
31
- cmd.hook( commandName, handler );
32
- disposers.push( () => {
33
- try {
34
- if ( cmd.isAlive && cmd.isAlive() ) cmd.unhook( commandName );
35
- } catch {}
36
- } );
32
+ const handle = cmd.hook( commandName, ( result, args ) => handlerRef.current( result, args ) );
33
+
34
+ if ( handle ) disposers.push( handle.dispose );
37
35
  } );
38
36
 
39
37
  return () => {
40
- disposers.forEach( d => d() );
38
+ disposers.forEach( ( dispose ) => dispose() );
41
39
  };
42
- }, [ children.map( c => c.getId() ).join( "|" ), commandName, handler ] );
40
+ }, [ children.map( c => c.getId() ).join( "|" ), commandName ] );
43
41
  }
44
-
@@ -1,4 +1,3 @@
1
-
2
1
  import React from "react";
3
2
 
4
3
  import { useCommand } from "./use-command";
@@ -12,12 +11,25 @@ export function useCommandHook(
12
11
  ) {
13
12
  const cmd = useCommand( commandName, ref as React.RefObject<any> );
14
13
 
14
+ // The latest handler, called through one that stays: a handler written inline is new at every render, and the
15
+ // hook is registered once for the instance, not again each time.
16
+ const handlerRef = React.useRef( handler );
17
+ handlerRef.current = handler;
18
+
19
+ const cmdRef = React.useRef( cmd );
20
+ cmdRef.current = cmd;
21
+
22
+ const instance = cmd?.getInternalContext()?.componentNameUnique ?? null;
23
+
15
24
  React.useEffect( () => {
16
- if ( ! cmd ) return;
17
- cmd.hook( handler );
25
+ const hooked = cmdRef.current;
26
+
27
+ if ( ! hooked ) return;
28
+
29
+ hooked.hook( ( result, args ) => handlerRef.current( result, args ) );
30
+
18
31
  return () => {
19
- cmd.unhook();
32
+ hooked.unhook();
20
33
  };
21
- }, [ cmd, handler ] );
34
+ }, [ commandName, instance, !! cmd ] );
22
35
  }
23
-
@@ -1,10 +1,10 @@
1
1
 
2
2
  import React from "react";
3
3
 
4
- import { shallowEqual } from "../utils";
4
+ import { useSelectedState } from "../utils";
5
5
 
6
6
  import core from "../../_internal/core";
7
- import { INTERNAL_STATE_UPDATED_EVENT, GET_INTERNAL_MATCH_SYMBOL } from "../../_internal/constants";
7
+ import { GET_INTERNAL_MATCH_SYMBOL } from "../../_internal/constants";
8
8
 
9
9
  function resolveInternalContextByRef( componentName: string, ref: React.RefObject<Element | null> ) {
10
10
  try {
@@ -51,58 +51,7 @@ function useCommandStateWithRefSelectorInternal<TState, TSelector>(
51
51
  setInternalContext( resolveInternalContextByRef( componentName, ref ) );
52
52
  }, [ componentName, ref.current ] );
53
53
 
54
- const selectorRef = React.useRef( selector );
55
- selectorRef.current = selector;
56
-
57
- const equalityFn = options?.equalityFn ?? ( shallowEqual as ( a: TSelector, b: TSelector ) => boolean );
58
-
59
- const valueRef = React.useRef<TSelector | null>( internalContext ? selector( internalContext.getState<TState>() ) : null );
60
- const onChangeRef = React.useRef<( () => void ) | null>( null );
61
-
62
- const handlerRef = React.useRef<( () => void ) | null>( null );
63
-
64
- React.useEffect( () => {
65
- if ( ! internalContext ) return;
66
-
67
- if ( ! handlerRef.current ) {
68
- const handleStateChange = () => {
69
- const currentState = internalContext.getState<TState>();
70
- const newValue = selectorRef.current( currentState );
71
-
72
- if ( valueRef.current === null || ! equalityFn( valueRef.current, newValue ) ) {
73
- valueRef.current = newValue;
74
-
75
- if ( onChangeRef.current ) {
76
- onChangeRef.current();
77
- }
78
- }
79
- };
80
-
81
- handlerRef.current = handleStateChange;
82
- internalContext.emitter.on( INTERNAL_STATE_UPDATED_EVENT, handleStateChange );
83
- }
84
-
85
- return () => {
86
- if ( handlerRef.current ) {
87
- internalContext.emitter.off( INTERNAL_STATE_UPDATED_EVENT, handlerRef.current );
88
- handlerRef.current = null;
89
- }
90
- };
91
- }, [ internalContext, componentName ] );
92
-
93
- const subscribe = React.useCallback( ( onChange: () => void ) => {
94
- onChangeRef.current = onChange;
95
-
96
- return () => {
97
- onChangeRef.current = null;
98
- };
99
- }, [ componentName ] );
100
-
101
- const getSnapshot = React.useCallback( () => {
102
- return valueRef.current;
103
- }, [] );
104
-
105
- const selectedState = React.useSyncExternalStore( subscribe, getSnapshot, getSnapshot );
54
+ const selectedState = useSelectedState<TState, TSelector>( internalContext, selector, options?.equalityFn );
106
55
 
107
56
  if ( ! internalContext ) {
108
57
  return null;
@@ -1,12 +1,12 @@
1
1
 
2
- import React from "react";
3
-
4
2
  import { useCommand } from "./use-command";
5
3
 
6
- import { getSafeContext, shallowEqual } from "../utils";
4
+ import { getSafeContext, useSelectedState } from "../utils";
7
5
 
8
6
  import core from "../../_internal/core";
9
- import { INTERNAL_STATE_UPDATED_EVENT, GET_INTERNAL_SYMBOL } from "../../_internal/constants";
7
+ import { GET_INTERNAL_SYMBOL } from "../../_internal/constants";
8
+
9
+ import type React from "react";
10
10
 
11
11
  function resolveInternalContext( name: string ) {
12
12
  const cmd = useCommand( name );
@@ -46,59 +46,10 @@ function useCommandStateSelectorInternal<TState, TSelector>(
46
46
  throw new Error( `useCommandState(\"${ commandName }\") cannot resolve internal context` );
47
47
  }
48
48
 
49
- const selectorRef = React.useRef( selector );
50
- selectorRef.current = selector;
51
-
52
- const equalityFn = options?.equalityFn ?? ( shallowEqual as unknown as ( a: TSelector, b: TSelector ) => boolean );
53
-
54
- const valueRef = React.useRef<TSelector>( selector( internalContext.getState<TState>() ) );
55
- const onChangeRef = React.useRef<( () => void ) | null>( null );
56
-
57
- const handlerRef = React.useRef<( () => void ) | null>( null );
58
-
59
- if ( ! handlerRef.current ) {
60
- const handleStateChange = () => {
61
- const currentState = internalContext.getState<TState>();
62
- const newValue = selectorRef.current( currentState );
63
-
64
- if ( ! equalityFn( valueRef.current, newValue ) ) {
65
- valueRef.current = newValue;
66
-
67
- if ( onChangeRef.current ) {
68
- onChangeRef.current();
69
- }
70
- }
71
- };
72
-
73
- handlerRef.current = handleStateChange;
74
- internalContext.emitter.on( INTERNAL_STATE_UPDATED_EVENT, handleStateChange );
75
- }
76
-
77
- React.useEffect( () => {
78
- return () => {
79
- if ( handlerRef.current ) {
80
- internalContext.emitter.off( INTERNAL_STATE_UPDATED_EVENT, handlerRef.current );
81
- handlerRef.current = null;
82
- }
83
- };
84
- }, [ internalContext, commandName ] );
85
-
86
- const subscribe = React.useCallback( ( onChange: () => void ) => {
87
- onChangeRef.current = onChange;
88
-
89
- return () => {
90
- onChangeRef.current = null;
91
- };
92
- }, [ commandName ] );
93
-
94
- const getSnapshot = React.useCallback( () => {
95
- return valueRef.current;
96
- }, [] );
97
-
98
- const selectedState = React.useSyncExternalStore( subscribe, getSnapshot, getSnapshot );
49
+ const selected = useSelectedState<TState, TSelector>( internalContext, selector, options?.equalityFn );
99
50
 
100
51
  return [
101
- selectedState as TSelector,
52
+ selected,
102
53
  internalContext.setState<TState>,
103
54
  internalContext.isMounted,
104
55
  ] as const;
@@ -186,28 +186,6 @@ export function useCommand( commandName: string, ref?: React.RefObject<any> ) {
186
186
  return createAdapterFromId( id, () => internal );
187
187
  };
188
188
 
189
- const getAdapterByName = (): UseCommandAdapter | null => {
190
- const mapped = commandsManager.getComponentName( commandName );
191
- if ( ! mapped ) { debug( "byName", commandName, "no-mapped" ); return null; }
192
-
193
- try {
194
- const contexts = core[ GET_INTERNAL_MATCH_SYMBOL ]( mapped + "*" ) as Array<any>;
195
- for ( let i = contexts.length - 1 ; i >= 0 ; i-- ) {
196
- const ctx = contexts[ i ];
197
- if ( ctx.commands && ctx.commands[ commandName ] ) {
198
- const id: DCommandIdArgs = { commandName, componentName: ctx.componentName, componentNameUnique: ctx.componentNameUnique };
199
- debug( "byName", commandName, "resolved", id );
200
- return createAdapterFromId(
201
- id,
202
- () => core[ GET_INTERNAL_SYMBOL ]( ctx.componentNameUnique ),
203
- );
204
- }
205
- }
206
- } catch { debug( "byName", commandName, "error" ); return null; }
207
- debug( "byName", commandName, "none" );
208
- return null;
209
- };
210
-
211
189
  const getAdapterInRef = (): UseCommandAdapter | null => {
212
190
  if ( ! ref?.current ) { debug( "inRef", commandName, "no-ref" ); return null; }
213
191
 
@@ -232,14 +210,17 @@ export function useCommand( commandName: string, ref?: React.RefObject<any> ) {
232
210
  const mapped = commandsManager.getComponentName( commandName );
233
211
  if ( ! mapped ) { debug( "onDemand", commandName, "no-mapped" ); return null; }
234
212
  try {
235
- const contexts = core[ GET_INTERNAL_MATCH_SYMBOL ]( mapped + "*" );
236
- for ( let i = contexts.length - 1 ; i >= 0 ; i-- ) {
237
- const ctx = contexts[ i ];
238
- if ( ctx.commands && ctx.commands[ commandName ] ) {
239
- const id = { commandName, componentName: ctx.componentName, componentNameUnique: ctx.componentNameUnique } as DCommandIdArgs;
240
- debug( "onDemand", commandName, "resolved", id );
241
- return id;
242
- }
213
+ const contexts = core[ GET_INTERNAL_MATCH_SYMBOL ]( mapped + "*" )
214
+ .filter( ( ctx ) => ctx.commands && ctx.commands[ commandName ] );
215
+
216
+ // An instance on the page first: a render React threw away registered its context too and never
217
+ // unmounts, and the contexts are in the order of their names, not of their making.
218
+ const ctx = [ ... contexts ].reverse().find( ( candidate ) => candidate.isMounted() ) ?? contexts[ contexts.length - 1 ];
219
+
220
+ if ( ctx ) {
221
+ const id = { commandName, componentName: ctx.componentName, componentNameUnique: ctx.componentNameUnique } as DCommandIdArgs;
222
+ debug( "onDemand", commandName, "resolved", id );
223
+ return id;
243
224
  }
244
225
  debug( "onDemand", commandName, "none" );
245
226
  return null;
@@ -253,8 +234,8 @@ export function useCommand( commandName: string, ref?: React.RefObject<any> ) {
253
234
  };
254
235
 
255
236
  const adapter = ref
256
- ? ( getAdapterInRef() || getAdapterByName() || getAdapterOnDemand() )
257
- : ( getAdapterInCurrentContext() || getAdapterByName() || getAdapterOnDemand() );
237
+ ? ( getAdapterInRef() || getAdapterOnDemand() )
238
+ : ( getAdapterInCurrentContext() || getAdapterOnDemand() );
258
239
 
259
240
  return adapter;
260
241
  }
@@ -0,0 +1,73 @@
1
+ import React from "react";
2
+
3
+ import { select } from "@zenflux/commands";
4
+
5
+ import { shallowEqual } from "./utils";
6
+
7
+ import type { Store, StoreConfig } from "@zenflux/commands";
8
+
9
+ /**
10
+ * `select()`, as `useSelect()` hands it to its callback: it reads a store and remembers it, so the hook listens to
11
+ * every store it read.
12
+ */
13
+ export type SelectFrom = typeof select;
14
+
15
+ /**
16
+ * What a callback picks from `$e`'s stores, drawn again as one of the stores it read changes:
17
+ * `useSelect( ( selectFrom ) => selectFrom( $e.components.get( "hello" ).store ).getAnswers(), [] )`.
18
+ *
19
+ * The pick is made again only when one of those stores has another state, or `deps` changed; a pick equal to the last
20
+ * (shallowly) keeps the last one's identity, so React draws nothing for it.
21
+ */
22
+ export function useSelect<TResult>( mapSelect: ( selectFrom: SelectFrom ) => TResult, deps: React.DependencyList ): TResult {
23
+ const last = React.useRef<{ result: TResult; states: Map<Store, object>; deps: React.DependencyList } | null>( null );
24
+
25
+ const [ stores, setStores ] = React.useState<Store[]>( [] );
26
+
27
+ const mapSelectRef = React.useRef( mapSelect );
28
+ mapSelectRef.current = mapSelect;
29
+
30
+ const getSnapshot = (): TResult => {
31
+ const previous = last.current;
32
+
33
+ // Nothing it read changed, nor its deps: the same pick.
34
+ if ( previous &&
35
+ previous.deps.length === deps.length && previous.deps.every( ( dep, index ) => Object.is( dep, deps[ index ] ) ) &&
36
+ [ ... previous.states ].every( ( [ store, state ] ) => store.getState() === state ) ) {
37
+ return previous.result;
38
+ }
39
+
40
+ const states = new Map<Store, object>();
41
+
42
+ const result = mapSelectRef.current( <TConfig extends StoreConfig>( store: Store<TConfig> ) => {
43
+ states.set( store, store.getState() );
44
+
45
+ return select( store );
46
+ } );
47
+
48
+ last.current = {
49
+ result: previous && shallowEqual( previous.result as Record<string, unknown>, result as Record<string, unknown> ) ? previous.result : result,
50
+ states,
51
+ deps,
52
+ };
53
+
54
+ return last.current.result;
55
+ };
56
+
57
+ const result = React.useSyncExternalStore( React.useCallback( ( onChange: () => void ) => {
58
+ const unsubscribes = stores.map( ( store ) => store.subscribe( onChange ) );
59
+
60
+ return () => unsubscribes.forEach( ( unsubscribe ) => unsubscribe() );
61
+ }, [ stores ] ), getSnapshot, getSnapshot );
62
+
63
+ // The stores it read this time: listen to them, when they are others than those it listens to.
64
+ const read = [ ... ( last.current?.states.keys() ?? [] ) ];
65
+
66
+ React.useEffect( () => {
67
+ if ( read.length !== stores.length || read.some( ( store, index ) => store !== stores[ index ] ) ) {
68
+ setStores( read );
69
+ }
70
+ } );
71
+
72
+ return result;
73
+ }
@@ -6,13 +6,14 @@ import { useComponent } from "./use-component/use-component";
6
6
  import { ComponentIdContext } from "../commands-context";
7
7
  import commandsManager from "../commands-manager";
8
8
 
9
- import type { DCommandComponentContextProps } from "../definitions";
9
+ import type { DCommandComponentContextProps, DCommandSingleComponentContext } from "../definitions";
10
10
 
11
11
  export { getSafeContext } from "./use-component/use-component";
12
12
 
13
13
  export function shallowEqual<T extends Record<string, unknown>>( a: T, b: T ): boolean {
14
- if ( a === b ) return true;
15
- if ( ! a || ! b ) return false;
14
+ if ( Object.is( a, b ) ) return true;
15
+ // Two values that are not objects are equal only as the same value: two numbers have no keys to compare.
16
+ if ( typeof a !== "object" || typeof b !== "object" || ! a || ! b ) return false;
16
17
 
17
18
  const aKeys = Object.keys( a );
18
19
  const bKeys = Object.keys( b );
@@ -26,6 +27,49 @@ export function shallowEqual<T extends Record<string, unknown>>( a: T, b: T ): b
26
27
  return true;
27
28
  }
28
29
 
30
+ /**
31
+ * What a selector picks of an instance's state, drawn again as it changes: read from the instance's `$e` component's
32
+ * store, which tells of real changes only. Null while there is no instance (a ref not attached yet).
33
+ */
34
+ export function useSelectedState<TState, TSelector>(
35
+ internalContext: DCommandSingleComponentContext | null,
36
+ selector: ( state: TState ) => TSelector,
37
+ equalityFn: ( a: TSelector, b: TSelector ) => boolean = shallowEqual as ( a: TSelector, b: TSelector ) => boolean,
38
+ ): TSelector {
39
+ const selected = React.useRef<{ state: TState; selector: ( state: TState ) => TSelector; value: TSelector } | null>( null );
40
+
41
+ const subscribe = React.useCallback(
42
+ ( onChange: () => void ) => internalContext
43
+ ? commandsManager.subscribeState( internalContext.componentName, internalContext.componentNameUnique, onChange )
44
+ : () => {},
45
+ [ internalContext ],
46
+ );
47
+
48
+ const getSnapshot = () => {
49
+ if ( ! internalContext ) {
50
+ return null as TSelector;
51
+ }
52
+
53
+ const state = internalContext.getState<TState>(),
54
+ last = selected.current;
55
+
56
+ // The store keeps a state's identity until it changes: the same state and selector pick the same, with no
57
+ // need to pick again (a selector that builds a new object each time would otherwise never settle).
58
+ if ( last && last.state === state && last.selector === selector ) {
59
+ return last.value;
60
+ }
61
+
62
+ const next = selector( state );
63
+
64
+ // An equal pick keeps its identity, so React does not draw again for it.
65
+ selected.current = { state, selector, value: last && equalityFn( last.value, next ) ? last.value : next };
66
+
67
+ return selected.current.value;
68
+ };
69
+
70
+ return React.useSyncExternalStore( subscribe, getSnapshot, getSnapshot );
71
+ }
72
+
29
73
  export function useCommanderChildrenComponents(
30
74
  componentName: string,
31
75
  onChildrenUpdate?: ( commands: ReturnType<typeof useComponent>[] ) => ( () => void ) | void,
@@ -34,26 +78,13 @@ export function useCommanderChildrenComponents(
34
78
 
35
79
  const [ childrenComponents, setChildrenComponents ] = React.useState<ReturnType<typeof useComponent>[]>( [] );
36
80
 
37
- function getDescendantsKeys( context: DCommandComponentContextProps ) {
38
- let keys: string[] = [];
39
-
40
- if ( context.children ) {
41
- for ( const key in context.children ) {
42
- keys.push( key );
43
-
44
- keys = keys.concat( getDescendantsKeys( context.children[ key ] ) );
45
- }
46
- }
47
-
48
- return keys.join( "-" );
49
- }
81
+ const childrenIds = React.useRef( "" );
50
82
 
83
+ // After every render: the children attach to the component's context as they lay out, after it rendered and
84
+ // before its effects run, so what it held as it rendered is not yet them (a list's items that came with new props).
51
85
  React.useEffect( () => {
52
- const children = componentContext.children;
53
-
54
- if ( ! children ) {
55
- throw new Error( `Current component: '${ componentContext.getComponentName() }' cannot find: '${ componentName }' children` );
56
- }
86
+ // None yet: an empty list draws before its first item.
87
+ const children = componentContext.children ?? {};
57
88
 
58
89
  const newChildrenComponents: ReturnType<typeof useComponent>[] = [];
59
90
 
@@ -77,14 +108,16 @@ export function useCommanderChildrenComponents(
77
108
 
78
109
  loopChildren( children );
79
110
 
80
- setChildrenComponents( newChildrenComponents );
111
+ const ids = newChildrenComponents.map( ( child ) => child.getId() ).join( "|" );
81
112
 
82
- const callback = onChildrenUpdate?.( newChildrenComponents );
113
+ if ( ids !== childrenIds.current ) {
114
+ childrenIds.current = ids;
83
115
 
84
- return () => {
85
- callback?.();
86
- };
87
- }, [ getDescendantsKeys( componentContext ) ] );
116
+ setChildrenComponents( newChildrenComponents );
117
+ }
118
+ } );
119
+
120
+ React.useEffect( () => onChildrenUpdate?.( childrenComponents ), [ childrenComponents ] );
88
121
 
89
122
  return childrenComponents;
90
123
  }
package/src/index.ts CHANGED
@@ -4,6 +4,5 @@ export * from "@zenflux/react-commander/commands-context";
4
4
  export * from "@zenflux/react-commander/commands-provider";
5
5
  export * from "@zenflux/react-commander/with-commands";
6
6
  export * from "@zenflux/react-commander/hooks";
7
- export * from "@zenflux/react-commander/definitions";
7
+ export type * from "@zenflux/react-commander/definitions";
8
8
  export * from "@zenflux/react-commander/constants";
9
- export * from "@zenflux/react-commander/core";