@zenflux/react-commander 0.0.1-dev

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.
Files changed (33) hide show
  1. package/package.json +61 -0
  2. package/readme.md +1422 -0
  3. package/src/_internal/constants.ts +18 -0
  4. package/src/_internal/core.ts +208 -0
  5. package/src/_internal/definitions.ts +47 -0
  6. package/src/command-base.ts +106 -0
  7. package/src/commands-context.ts +20 -0
  8. package/src/commands-manager.ts +357 -0
  9. package/src/commands-provider.tsx +37 -0
  10. package/src/definitions.ts +165 -0
  11. package/src/hooks/index.ts +10 -0
  12. package/src/hooks/use-child-command/use-child-command-hook.ts +44 -0
  13. package/src/hooks/use-child-command/use-child-command-runner.ts +32 -0
  14. package/src/hooks/use-command/use-command-hook.ts +23 -0
  15. package/src/hooks/use-command/use-command-runner.ts +16 -0
  16. package/src/hooks/use-command/use-command-state.ts +132 -0
  17. package/src/hooks/use-command/use-command.ts +260 -0
  18. package/src/hooks/use-component/use-component-with-ref.ts +30 -0
  19. package/src/hooks/use-component/use-component.ts +56 -0
  20. package/src/hooks/utils.ts +90 -0
  21. package/src/index.ts +9 -0
  22. package/src/query/query-auto-save-manager.ts +54 -0
  23. package/src/query/query-cache.ts +91 -0
  24. package/src/query/query-client.tsx +67 -0
  25. package/src/query/query-component.tsx +101 -0
  26. package/src/query/query-definitions.ts +32 -0
  27. package/src/query/query-list-diff.ts +8 -0
  28. package/src/query/query-list-module-base.ts +20 -0
  29. package/src/query/query-module-base.ts +200 -0
  30. package/src/query/query-provider.tsx +47 -0
  31. package/src/query/query-router.ts +85 -0
  32. package/src/query/query-utils.ts +30 -0
  33. package/src/with-commands.tsx +363 -0
@@ -0,0 +1,357 @@
1
+
2
+ import { GET_INTERNAL_SYMBOL } from "./_internal/constants.js";
3
+
4
+ import core from "./_internal/core.js";
5
+
6
+ import type { CommandBase } from "@zenflux/react-commander/command-base";
7
+
8
+ import type {
9
+ DCommandArgs,
10
+ DCommandHookHandle,
11
+ DCommandIdArgs,
12
+ DCommandNewInstanceWithArgs,
13
+ DCommandRegisterArgs,
14
+ DCommandSingleComponentContext
15
+ } from "@zenflux/react-commander/definitions";
16
+
17
+ class CommandsManager {
18
+ private commands: {
19
+ [ componentName: string ]: {
20
+ [ commandName: string ]: CommandBase
21
+ };
22
+ } = {};
23
+
24
+ private scopedHooks: {
25
+ [ componentNameUnique: string ]: {
26
+ [ commandName: string ]: Array<{ ownerId: string; original: ( result?: any, args?: DCommandArgs ) => any; wrapped: ( result?: any, args?: DCommandArgs ) => any; }>
27
+ }
28
+ } = {};
29
+
30
+ private commandToComponentMap: {
31
+ [ commandName: string ]: string;
32
+ } = {};
33
+
34
+ public register( args: DCommandRegisterArgs ) {
35
+ const { componentName, commands } = args;
36
+
37
+ if ( this.commands[ componentName ] ) {
38
+ }
39
+
40
+ const createdCommands: CommandBase[] = [];
41
+
42
+ if ( ! this.commands[ componentName ] ) {
43
+ this.commands[ componentName ] = {};
44
+ }
45
+
46
+ commands.forEach( ( command ) => {
47
+ const commandName = ( command as unknown as typeof CommandBase ).getName();
48
+ const commandInstance = new ( command as unknown as DCommandNewInstanceWithArgs )( args );
49
+
50
+ this.commands[ componentName ][ commandName ] = commandInstance;
51
+ this.commandToComponentMap[ commandName ] = componentName;
52
+
53
+ createdCommands.push( commandInstance );
54
+ } );
55
+
56
+ return createdCommands;
57
+ }
58
+
59
+ public async run( id: DCommandIdArgs, args: DCommandArgs, callback?: ( result: any ) => any ) {
60
+ const { componentNameUnique, componentName, commandName } = id;
61
+
62
+ const command = this.commands[ componentName ]?.[ commandName ];
63
+
64
+ if ( ! command ) {
65
+ throw new Error( `Command '${ commandName }' not registered for component '${ componentName }'` );
66
+ }
67
+
68
+ console.log( `Commands.run() '${ commandName }' for component '${ componentNameUnique }'`, args );
69
+
70
+ const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique );
71
+
72
+ let executionResult;
73
+
74
+ if ( singleComponentContext.getState ) {
75
+ executionResult = await command.execute( singleComponentContext.emitter, args, {
76
+ state: singleComponentContext.getState(),
77
+ setState: singleComponentContext.setState,
78
+ } );
79
+ } else {
80
+ executionResult = await command.execute( singleComponentContext.emitter, args );
81
+ }
82
+
83
+ if ( callback ) {
84
+ callback( executionResult );
85
+ }
86
+
87
+ return executionResult;
88
+ }
89
+
90
+ public unregister( componentName: string ) {
91
+ this.unhookWithinComponent( componentName );
92
+
93
+ // Clean up command to component mapping
94
+ Object.keys( this.commandToComponentMap ).forEach( commandName => {
95
+ if ( this.commandToComponentMap[ commandName ] === componentName ) {
96
+ delete this.commandToComponentMap[ commandName ];
97
+ }
98
+ } );
99
+
100
+ delete this.commands[ componentName ];
101
+ }
102
+
103
+ public hook( id: DCommandIdArgs, callback: ( result?: any, args?: DCommandArgs ) => any, options?: {
104
+ __ignoreDuplicatedHookError?: boolean;
105
+ } ) {
106
+ const { componentNameUnique, componentName, commandName } = id;
107
+
108
+ if ( ! this.commands[ componentName ] ) {
109
+ throw new Error( `Component '${ componentName }' not registered` );
110
+ }
111
+
112
+ const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique ) as DCommandSingleComponentContext;
113
+
114
+ // Check if id exist within the component context
115
+ if ( ! singleComponentContext.commands[ commandName ] ) {
116
+ throw new Error( `Command '${ commandName }' not registered for component '${ componentNameUnique }'` );
117
+ }
118
+
119
+ const listeners = singleComponentContext.emitter.listeners( commandName );
120
+
121
+ if ( ! options?.__ignoreDuplicatedHookError ) {
122
+ // Check if the same callback is already registered
123
+ if ( listeners.length > 0 && listeners.find( l => l.name === callback.name ) ) {
124
+ console.warn(
125
+ `Probably duplicated hook in '${ commandName }'\n` +
126
+ `callback '${ callback.name }()' already hooked for component '${ componentNameUnique }'` +
127
+ "The hook will be ignored, to avoid this error bound the callback or pass options: { __ignoreDuplicatedHookError: true }"
128
+ );
129
+
130
+ return;
131
+ }
132
+ }
133
+
134
+ singleComponentContext.emitter.on( commandName, callback );
135
+
136
+ return {
137
+ componentNameUnique,
138
+ commandName,
139
+ callback,
140
+ dispose: () => {
141
+ singleComponentContext.emitter.off( commandName, callback );
142
+ }
143
+ };
144
+ }
145
+
146
+ public hookScoped( id: DCommandIdArgs, ownerId: string, callback: ( result?: any, args?: DCommandArgs ) => any ): DCommandHookHandle {
147
+ const { componentNameUnique, componentName, commandName } = id;
148
+
149
+ if ( ! this.commands[ componentName ] ) {
150
+ throw new Error( `Component '${ componentName }' not registered` );
151
+ }
152
+
153
+ const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique ) as DCommandSingleComponentContext;
154
+
155
+ if ( ! singleComponentContext.commands[ commandName ] ) {
156
+ throw new Error( `Command '${ commandName }' not registered for component '${ componentNameUnique }'` );
157
+ }
158
+ const wrapped = ( result?: any, args?: DCommandArgs ) => callback( result, args );
159
+ singleComponentContext.emitter.on( commandName, wrapped );
160
+
161
+ if ( ! this.scopedHooks[ componentNameUnique ] ) this.scopedHooks[ componentNameUnique ] = {} as any;
162
+ if ( ! this.scopedHooks[ componentNameUnique ][ commandName ] ) this.scopedHooks[ componentNameUnique ][ commandName ] = [];
163
+
164
+ this.scopedHooks[ componentNameUnique ][ commandName ].push( { ownerId, original: callback, wrapped } );
165
+
166
+ const handle: DCommandHookHandle = {
167
+ componentNameUnique,
168
+ commandName,
169
+ ownerId,
170
+ dispose: () => this.unhookHandle( handle )
171
+ };
172
+
173
+ return handle;
174
+ }
175
+
176
+ public unhook( id: DCommandIdArgs ) {
177
+ const { componentNameUnique, componentName, commandName } = id;
178
+
179
+ if ( ! this.commands[ componentName ] ) {
180
+ throw new Error( `Component '${ componentName }' not registered` );
181
+ }
182
+
183
+ // @ts-ignore - If it hot reloads then skip the error
184
+ const shouldSilentError = !! typeof import.meta.hot?.hmrClient.pruneMap.size;
185
+
186
+ const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique, shouldSilentError ) as DCommandSingleComponentContext;
187
+
188
+ if ( ! singleComponentContext && shouldSilentError ) {
189
+ return;
190
+ }
191
+
192
+ // Check if id exist within the component context
193
+ if ( ! singleComponentContext.commands[ commandName ] ) {
194
+ throw new Error( `Command '${ commandName }' not registered for component '${ componentNameUnique }'` );
195
+ }
196
+
197
+ singleComponentContext.emitter.removeAllListeners( commandName );
198
+
199
+ if ( this.scopedHooks[ componentNameUnique ] && this.scopedHooks[ componentNameUnique ][ commandName ] ) {
200
+ delete this.scopedHooks[ componentNameUnique ][ commandName ];
201
+ }
202
+ }
203
+
204
+ public unhookHandle( handle: DCommandHookHandle ) {
205
+ const { componentNameUnique, commandName, ownerId } = handle;
206
+ const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique, true ) as DCommandSingleComponentContext;
207
+ if ( ! singleComponentContext ) return;
208
+
209
+ const records = this.scopedHooks[ componentNameUnique ]?.[ commandName ];
210
+ if ( ! records ) return;
211
+
212
+ const remaining: typeof records = [];
213
+ records.forEach( ( record ) => {
214
+ if ( record.ownerId === ownerId ) {
215
+ singleComponentContext.emitter.off( commandName, record.wrapped );
216
+ } else {
217
+ remaining.push( record );
218
+ }
219
+ } );
220
+
221
+ this.scopedHooks[ componentNameUnique ][ commandName ] = remaining;
222
+ }
223
+
224
+ public unhookWithinComponent( componentNameUnique: string ) {
225
+ const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique, true ) as DCommandSingleComponentContext;
226
+
227
+ singleComponentContext && Object.keys( singleComponentContext.commands ).forEach( ( commandName ) => {
228
+ singleComponentContext.emitter.removeAllListeners( commandName );
229
+ } );
230
+
231
+ delete this.scopedHooks[ componentNameUnique ];
232
+ }
233
+
234
+ public get( componentName: string, shouldSilentError = false ) {
235
+ if ( ! shouldSilentError && ! this.commands[ componentName ] ) {
236
+ throw new Error( `Component '${ componentName }' not registered` );
237
+ }
238
+
239
+ return this.commands[ componentName ];
240
+ }
241
+
242
+ public getComponentName( commandName: string ) {
243
+ return this.commandToComponentMap[ commandName ];
244
+ }
245
+
246
+ public getCommands() {
247
+ return this.commands;
248
+ }
249
+
250
+ public isHooked( id: DCommandIdArgs ) {
251
+ const { componentNameUnique, commandName } = id;
252
+
253
+ const singleComponentContext = core[ GET_INTERNAL_SYMBOL ]( componentNameUnique, true ) as DCommandSingleComponentContext;
254
+
255
+ if ( ! singleComponentContext ) {
256
+ return false;
257
+ }
258
+
259
+ const listeners = singleComponentContext.emitter.listeners( commandName );
260
+
261
+ return listeners.length > 0;
262
+ }
263
+
264
+ public resolveId( commandName: string, componentName: string, index = 0 ): DCommandIdArgs {
265
+ const contexts = core.__devGetContextValues?.() || [];
266
+ const matches = contexts.filter( c => c.componentName === componentName && !!c.commands[ commandName ] );
267
+ const ctx = matches[ index ];
268
+ if ( ! ctx ) throw new Error( `Command '${ commandName }' for component '${ componentName }' not found` );
269
+ return { commandName, componentName, componentNameUnique: ctx.componentNameUnique };
270
+ }
271
+
272
+ public runByName( commandName: string, componentName: string, args: DCommandArgs ) {
273
+ const id = this.resolveId( commandName, componentName );
274
+ return this.run( id, args );
275
+ }
276
+
277
+ public hookByNameScoped( params: { commandName: string; componentName: string; ownerId: string }, callback: ( result?: any, args?: DCommandArgs ) => any ) {
278
+ const id = this.resolveId( params.commandName, params.componentName );
279
+ return this.hookScoped( id, params.ownerId, callback );
280
+ }
281
+
282
+ public isContextRegistered( componentNameUnique: string ) {
283
+ return !! core[ GET_INTERNAL_SYMBOL ]( componentNameUnique, true );
284
+ }
285
+
286
+ public devShowComponents() {
287
+ console.group( "🔧 CommandsManager Dev Info" );
288
+
289
+ console.log( "📋 Registered Commands:" );
290
+ Object.entries( this.commands ).forEach( ( [ componentName, commands ] ) => {
291
+ console.group( ` ${ componentName }` );
292
+ Object.keys( commands ).forEach( commandName => {
293
+ console.log( ` - ${ commandName }` );
294
+ } );
295
+ console.groupEnd();
296
+ } );
297
+
298
+ console.log( "🗺️ Command to Component Mapping:" );
299
+ Object.entries( this.commandToComponentMap ).forEach( ( [ commandName, componentName ] ) => {
300
+ console.log( ` ${ commandName } → ${ componentName }` );
301
+ } );
302
+
303
+ console.log( "🔗 Scoped Hooks:" );
304
+ Object.entries( this.scopedHooks ).forEach( ( [ componentNameUnique, commandHooks ] ) => {
305
+ console.group( ` ${ componentNameUnique }` );
306
+ Object.entries( commandHooks ).forEach( ( [ commandName, hooks ] ) => {
307
+ console.log( ` ${ commandName }: ${ hooks.length } hook(s)` );
308
+ hooks.forEach( ( hook, index ) => {
309
+ console.log( ` [${ index }] owner: ${ hook.ownerId }` );
310
+ } );
311
+ } );
312
+ console.groupEnd();
313
+ } );
314
+
315
+ console.log( "🌐 Non-Scoped Hooks:" );
316
+ const contextKeys = core.__devGetContextKeys();
317
+ contextKeys.forEach( key => {
318
+ const context = core[ GET_INTERNAL_SYMBOL ]( key, true );
319
+ const hasNonScopedHooks = Object.keys( context.commands ).some( commandName => {
320
+ const listeners = context.emitter.listeners( commandName );
321
+ return listeners.length > 0;
322
+ } );
323
+
324
+ if ( hasNonScopedHooks ) {
325
+ console.group( ` ${ key }` );
326
+ Object.keys( context.commands ).forEach( commandName => {
327
+ const listeners = context.emitter.listeners( commandName );
328
+ if ( listeners.length > 0 ) {
329
+ console.log( ` ${ commandName }: ${ listeners.length } listener(s)` );
330
+ listeners.forEach( ( listener, index ) => {
331
+ console.log( ` [${ index }] ${ listener.name || "anonymous" }` );
332
+ } );
333
+ }
334
+ } );
335
+ console.groupEnd();
336
+ }
337
+ } );
338
+
339
+ console.log( "🏗️ Core Context:" );
340
+ console.log( ` Total components: ${ contextKeys.length }` );
341
+ contextKeys.forEach( key => {
342
+ const context = core[ GET_INTERNAL_SYMBOL ]( key, true );
343
+ console.log( ` ${ key }: ${ context.commands.length } command(s)` );
344
+ } );
345
+
346
+ console.groupEnd();
347
+ }
348
+ }
349
+
350
+ export const commands = new CommandsManager();
351
+
352
+ if ( ( import.meta as ImportMeta & { env?: { DEV?: boolean } } ).env?.DEV ) {
353
+ ( window as any ).$$commands = commands;
354
+ ( window as any ).$$dev = () => commands.devShowComponents();
355
+ }
356
+
357
+ export default commands;
@@ -0,0 +1,37 @@
1
+ import React from "react";
2
+
3
+ import { ComponentIdContext } from "@zenflux/react-commander/commands-context";
4
+
5
+ import type { DCommandComponentContextProps } from "@zenflux/react-commander/definitions";
6
+
7
+ /**
8
+ * Function `ComponentIdProvider()` - This function is used to provide a context that contains
9
+ * properties relevant to the component's unique identification within a tree-like structure.
10
+ * It wraps its children with the `ComponentIdContext.Provider`, passing the provided `context`
11
+ * value down the component tree. This allows any descendant components to access and share the
12
+ * structural state and hierarchical relationships defined in `DCommandComponentContextProps`.
13
+ *
14
+ * The purpose of `ComponentIdProvider` is to establish a consistent context environment for
15
+ * the components that are working within a command-oriented architecture, ensuring that each
16
+ * component can retrieve and manage relationships and dependencies via the shared context.
17
+ *
18
+ * Usage Example:
19
+ * ```typescript jsx
20
+ * return (
21
+ * <ComponentIdProvider context={ context }>
22
+ * <WrappedComponent { ...props } ref={ componentRef } $$key={ performance.now() }/>
23
+ * </ComponentIdProvider>
24
+ * );
25
+ * ```
26
+ **/
27
+ export function ComponentIdProvider( props: {
28
+ children: React.ReactNode;
29
+ context: DCommandComponentContextProps,
30
+ } ) {
31
+ const { children, context } = props;
32
+ return (
33
+ <ComponentIdContext.Provider value={ context }>
34
+ { children }
35
+ </ComponentIdContext.Provider>
36
+ );
37
+ }
@@ -0,0 +1,165 @@
1
+ import type React from "react";
2
+
3
+ import type { EventEmitter } from "eventemitter3";
4
+
5
+ import type { CommandBase } from "@zenflux/react-commander/command-base";
6
+
7
+ /**
8
+ * Type `DCommandFunctionComponent` - This type defines the structure of a functional component that integrates with the command system.
9
+ * The component will have access to command-related properties and methods, enhancing its interactivity and state management capabilities.
10
+ *
11
+ * Why it's called `DCommandFunctionComponent`:
12
+ *
13
+ * - `FunctionComponent` denotes that this is a functional (rather than class-based) React component.
14
+ * - The `DCommand` prefix indicates that this component is integrated with command functionalities within the project.
15
+ *
16
+ * Main points:
17
+ *
18
+ * - Ensures that functional components can seamlessly interact with the command system.
19
+ * - Used in the `withCommands` higher-order function to enhance components with command-related features.
20
+ * - Supports generic props (`TProps`) and state (`TState`) to accommodate various use cases.
21
+ * - Promotes reusability and flexibility for components that need command capabilities.
22
+ *
23
+ * Sugar, e.g `ComponentType.getName` not `ComponentInstance`
24
+ **/
25
+ export interface DCommandFunctionComponent<TProps = any, TState = undefined> extends React.FC<TProps> {
26
+ ( props: TProps, state?: TState ): React.ReactNode;
27
+
28
+ getName?(): string;
29
+ displayName?: string;
30
+ }
31
+
32
+ /**
33
+ * Interface `DCommandSingleComponentContext` - This interface is named `SingleComponentContext`
34
+ * because it represents the context specifically for a single command component within the application.
35
+ * This context is isolated to handle the state, properties, and event management pertinent to one
36
+ * distinct component instance. Specifically, it includes:
37
+ *
38
+ * - `commands`: A dictionary mapping command names to their respective `CommandBase` instances,
39
+ * facilitating command execution within this particular component.
40
+ *
41
+ * - `componentNameUnique`: A unique identifier for the component instance, ensuring distinct context
42
+ * management even among multiple instances of the same component.
43
+ *
44
+ * - `componentName`: The general name of the component, which might not be unique across different instances.
45
+ *
46
+ * - `key`: Utilized for identifying list items in React, helping maintain consistent identity across renders.
47
+ *
48
+ * - `props`: This encompasses all props passed to the component, including children, ensuring the component
49
+ * receives all necessary data.
50
+ *
51
+ * - `isMounted()`: A method to check whether the component is currently mounted, aiding in lifecycle management.
52
+ *
53
+ * - `getState`: A generic method returning the current state of the component, promoting state encapsulation.
54
+ *
55
+ * - `setState`: Facilitates updating the component state with optional callbacks post state mutation.
56
+ *
57
+ * - `getComponentContext`: Returns additional context properties specific to the component, enhancing encapsulation.
58
+ *
59
+ * - `emitter`: An instance of `EventEmitter` used for managing and emitting events within the component scope.
60
+ *
61
+ * - `lifecycleHandlers`: Contains handlers for different lifecycle events of the component, supporting comprehensive
62
+ * lifecycle management and providing hooks for extending component behavior.
63
+ *
64
+ * This focus on a single component ensures that all interactions, state changes, and events are accurately and
65
+ * efficiently managed within the bounds of that component's context, reducing the risk of errors and simplifying
66
+ * the debugging and maintenance process.
67
+ **/
68
+ export interface DCommandSingleComponentContext {
69
+ commands: {
70
+ [ commandName: string ]: CommandBase
71
+ };
72
+ componentNameUnique: string;
73
+ componentName: string;
74
+
75
+ key: React.Key;
76
+ props: React.PropsWithChildren<any>;
77
+
78
+ isMounted(): boolean;
79
+
80
+ getState: <TState>() => TState
81
+ setState<TState, K extends keyof TState = keyof TState>(
82
+ state: ( TState | null ) | ( Pick<TState, K> | TState | null ),
83
+ callback?: ( state: TState ) => void,
84
+ ): void;
85
+
86
+ getComponentContext: () => DCommandComponentContextProps;
87
+
88
+ emitter: EventEmitter;
89
+
90
+ lifecycleHandlers: any,
91
+ }
92
+
93
+ /**
94
+ * Interface `DCommandComponentContextProps` - This interface outlines the context properties
95
+ * for a command component within the application. It focuses on hierarchical relationships and
96
+ * structural state, allowing components to maintain and manage tree-like dependencies.
97
+ *
98
+ * `DCommandComponentContextProps` is about managing a component's place and
99
+ * relationships within a component hierarchy, ensuring structural context and inheritance, while
100
+ * `DCommandSingleComponentContext` isolates the state and event management specific to one
101
+ * standalone component. Their naming reflects these purposes: "SingleComponentContext" focuses
102
+ * on an individual component's context, and "ComponentContextProps" denotes the properties needed
103
+ * to manage a component within a broader structure.
104
+ **/
105
+ export interface DCommandComponentContextProps {
106
+ isSet: boolean;
107
+
108
+ children?: { [ nameUnique: string ]: DCommandComponentContextProps };
109
+ parent?: DCommandComponentContextProps;
110
+
111
+ getNameUnique: () => string;
112
+ getComponentName(): string;
113
+ getComponentRef(): React.RefObject<any>;
114
+ }
115
+
116
+ /**
117
+ * Interface `DCommandRegisterArgs` - This interface defines the arguments required for registering a command.
118
+ **/
119
+ export interface DCommandRegisterArgs {
120
+ commands: DCommandNewInstanceWithArgs[];
121
+ componentName: string;
122
+ }
123
+
124
+ /**
125
+ * Interface `DCommandIdArgs` - This interface defines the structure for identifying a specific command.
126
+ * These identifiers enable the precise targeting and execution of commands within the system.
127
+ **/
128
+ export interface DCommandIdArgs {
129
+ // TODO: I dont really need all of them.
130
+ componentNameUnique: string;
131
+ componentName: string;
132
+ commandName: string;
133
+ }
134
+
135
+ /**
136
+ * Interface `DCommandArgs` - This interface defines the structure for the arguments provided to commands
137
+ **/
138
+ export type DCommandArgs = {
139
+ [ key: string | number | symbol ]: any
140
+ };
141
+
142
+ /**
143
+ * Interface `DCommandOptions` - This interface defines additional options that can be passed to a command when it is executed.
144
+ **/
145
+ export interface DCommandOptions<TState> {
146
+ state?: React.ComponentState;
147
+ setState?: <K extends keyof TState>(
148
+ state: ( ( prevState: Readonly<TState> ) => Pick<TState, K> | TState | null ) | ( Pick<TState, K> | TState | null ),
149
+ callback?: ( state: TState ) => void,
150
+ ) => void;
151
+ }
152
+
153
+ export type DCommandNewInstanceWithArgs<TState = undefined> = ( new ( args: DCommandRegisterArgs ) => CommandBase<TState> );
154
+
155
+ /**
156
+ * Handle returned by scoped hook registration, allowing precise unsubscription
157
+ * of the listener that was added by a specific owner.
158
+ */
159
+ export interface DCommandHookHandle {
160
+ componentNameUnique: string;
161
+ commandName: string;
162
+ ownerId: string;
163
+ dispose: () => void;
164
+ }
165
+
@@ -0,0 +1,10 @@
1
+
2
+ export { useCommand } from "./use-command/use-command.js";
3
+ export { useComponent } from "./use-component/use-component.js";
4
+ export { useCommandState } from "./use-command/use-command-state.js";
5
+ export { useComponentWithRef } from "./use-component/use-component-with-ref.js";
6
+ export { useCommandRunner } from "./use-command/use-command-runner.js";
7
+ export { useCommandHook } from "./use-command/use-command-hook.js";
8
+ export { useChildCommandHook } from "./use-child-command/use-child-command-hook.js";
9
+ export { useChildCommandRunner } from "./use-child-command/use-child-command-runner.js";
10
+
@@ -0,0 +1,44 @@
1
+
2
+ import React from "react";
3
+
4
+ import { useCommanderChildrenComponents } from "../utils.js";
5
+
6
+ import type { useComponent } from "../use-component/use-component.js";
7
+ import type { DCommandArgs } from "../../definitions.js";
8
+
9
+ export function useChildCommandHook(
10
+ childComponentName: string,
11
+ commandName: string,
12
+ handler: ( result?: unknown, args?: DCommandArgs ) => void,
13
+ opts?: { filter?: ( ctx: ReturnType<typeof useComponent> ) => boolean; ignoreDuplicate?: boolean }
14
+ ) {
15
+ const children = useCommanderChildrenComponents( childComponentName );
16
+
17
+ React.useEffect( () => {
18
+ const disposers: Array<() => void> = [];
19
+
20
+ const alive = children.filter( cmd => {
21
+ try {
22
+ return typeof cmd.isAlive === "function" ? cmd.isAlive() : true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ } );
27
+
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
+ } );
37
+ } );
38
+
39
+ return () => {
40
+ disposers.forEach( d => d() );
41
+ };
42
+ }, [ children.map( c => c.getId() ).join( "|" ), commandName, handler ] );
43
+ }
44
+
@@ -0,0 +1,32 @@
1
+
2
+ import React from "react";
3
+
4
+ import { useCommanderChildrenComponents } from "../utils.js";
5
+
6
+ import type { DCommandArgs, DCommandSingleComponentContext } from "../../definitions.js";
7
+
8
+ export function useChildCommandRunner(
9
+ childComponentName: string,
10
+ selector: ( ctx: DCommandSingleComponentContext ) => string
11
+ ) {
12
+ const children = useCommanderChildrenComponents( childComponentName );
13
+
14
+ const getByKey = React.useCallback( ( key: string ) => {
15
+ for ( const cmd of children ) {
16
+ const ctx = cmd.getInternalContext();
17
+ const k = selector( ctx );
18
+ if ( k === key ) return cmd;
19
+ }
20
+ return null;
21
+ }, [ children, selector ] );
22
+
23
+ const run = React.useCallback( ( key: string, commandName: string, args: DCommandArgs ) => {
24
+ const cmd = getByKey( key );
25
+ if ( !cmd ) return false;
26
+ cmd.run( commandName, args );
27
+ return true;
28
+ }, [ getByKey ] );
29
+
30
+ return run;
31
+ }
32
+
@@ -0,0 +1,23 @@
1
+
2
+ import React from "react";
3
+
4
+ import { useCommand } from "./use-command.js";
5
+
6
+ import type { DCommandArgs } from "../../definitions.js";
7
+
8
+ export function useCommandHook(
9
+ commandName: string,
10
+ handler: ( result?: unknown, args?: DCommandArgs ) => void,
11
+ ref?: React.RefObject<any>,
12
+ ) {
13
+ const cmd = useCommand( commandName, ref as React.RefObject<any> );
14
+
15
+ React.useEffect( () => {
16
+ if ( ! cmd ) return;
17
+ cmd.hook( handler );
18
+ return () => {
19
+ cmd.unhook();
20
+ };
21
+ }, [ cmd, handler ] );
22
+ }
23
+
@@ -0,0 +1,16 @@
1
+
2
+ import React from "react";
3
+
4
+ import { useCommand } from "./use-command.js";
5
+
6
+ import type { DCommandArgs } from "../../definitions.js";
7
+
8
+ export function useCommandRunner( commandName: string, ref?: React.RefObject<any> ) {
9
+ const cmd = ref ? useCommand( commandName, ref ) : useCommand( commandName );
10
+
11
+ return React.useCallback( ( args: DCommandArgs = {}, callback?: ( result: unknown ) => void ) => {
12
+ if ( ! cmd ) return;
13
+ return cmd.run( args, callback );
14
+ }, [ cmd ] );
15
+ }
16
+