@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 ZenFlux
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -2,7 +2,8 @@
2
2
  "$schema": "https://raw.githubusercontent.com/SchemaStore/schemastore/master/src/schemas/json/package.json",
3
3
  "name": "@zenflux/react-commander",
4
4
  "author": "Leonid Vinikov <leonidvinikov@gmail.com> (https://github.com/iNewLegend)",
5
- "version": "0.0.16",
5
+ "license": "MIT",
6
+ "version": "0.0.18",
6
7
  "type": "module",
7
8
  "sideEffects": false,
8
9
  "types": "src/index.ts",
@@ -38,7 +39,6 @@
38
39
  "./query/definitions": "./src/query/query-definitions.ts",
39
40
  "./query/list-diff": "./src/query/query-list-diff.ts",
40
41
  "./query/module-base": "./src/query/query-module-base.ts",
41
- "./query/item-module-base": "./src/query/query-item-module-base.ts",
42
42
  "./query/list-module-base": "./src/query/query-list-module-base.ts",
43
43
  "./query/router": "./src/query/query-router.ts",
44
44
  "./query/utils": "./src/query/query-utils.ts",
@@ -48,19 +48,18 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@zenflux/core": "0.1.32",
51
+ "@zenflux/commands": "0.0.2",
52
+ "@zenflux/core": "0.2.0",
52
53
  "eventemitter3": "^5.0.1"
53
54
  },
54
55
  "devDependencies": {
55
56
  "@types/react": "^19.2.0",
56
57
  "@types/react-dom": "^19.2.0",
57
58
  "react": "^19.2.0",
58
- "react-dom": "^19.2.0",
59
- "vite": "^8.2.2"
59
+ "react-dom": "^19.2.0"
60
60
  },
61
61
  "peerDependencies": {
62
- "react": "^19.2.0",
63
- "react-dom": "^19.2.0",
64
- "vite": "^8.2.2"
62
+ "react": ">=18.3.0",
63
+ "react-dom": ">=18.3.0"
65
64
  }
66
65
  }
package/readme.md CHANGED
@@ -1,12 +1,13 @@
1
1
  # @zenflux/react-commander
2
2
 
3
- A lightweight command orchestration layer for React that separates UI from behavior through typed Commands, per-instance component context, and a central command manager. Includes a minimal Query abstraction for data fetching, caching, and lifecycle wiring.
3
+ A lightweight command orchestration layer for React that separates UI from behavior through typed Commands, per-instance component context, and `$e` ([@zenflux/commands](../zenflux-commands/readme.md)) as its command manager. Includes a minimal Query abstraction for data fetching, caching, and lifecycle wiring.
4
4
 
5
5
  ## Table of contents
6
6
 
7
7
  - [Installation](#installation)
8
8
  - [Quick Start](#quick-start)
9
9
  - [Core Concepts](#core-concepts)
10
+ - [The manager: `$e`](#the-manager-e)
10
11
  - [API Reference](#api-reference)
11
12
  - [Commands](#commands)
12
13
  - [Hooks](#hooks)
@@ -157,6 +158,46 @@ A lightweight data fetching layer that provides:
157
158
  - **Lifecycle Integration**: Automatic data loading and state updates
158
159
  - **Type Safety**: End-to-end type safety from API to component
159
160
 
161
+ ## The manager: `$e`
162
+
163
+ Every command runs through `$e`, the command system of [@zenflux/commands](../zenflux-commands/readme.md). As the first instance of a `withCommands()` component mounts, the component becomes an `$e` component of the same name, and each of its commands an `$e` command that runs the react-commander command on the instance its args name (`componentNameUnique`). So a command is run, hooked and logged as every other `$e` command:
164
+
165
+ ```ts
166
+ import { API, $e } from "@zenflux/commands";
167
+
168
+ // Before the app renders: the API every command runs through (without one, react-commander makes it as the first
169
+ // component mounts). `storePrefix` names the `$e` components' stores.
170
+ new API( { isDebug: import.meta.env.DEV, storePrefix: "my-app" } );
171
+
172
+ // From anywhere, the console too: the instance by its unique name.
173
+ $e.run( "App/ItemsList/SetName", { componentNameUnique: "App/ItemsList-:r1:", id: "1", name: "New" } );
174
+ ```
175
+
176
+ - `useCommand()`, `useComponent()` and `commandsManager.run()` add the instance for you; nothing in a component changes.
177
+ - A command's own name is its component's name and one more part (`App/ItemsList/SetName` of `App/ItemsList`), as `$e` names its commands.
178
+ - Every hook runs through `$e`'s hooks (`$e.hooks`), with the API it had: a command has one `$e` 'after' hook, registered once, which calls the hooks of the instance a run was on (`useCommandHook()`, `useChildCommandHook()`, `useCommand().hook()`, `useComponent().hook()`), found by its name, then the command's `globalHook()`s; `commandsManager.onBefore()`, `onBeforeUI()`, `onAfter()`, `onAfterUI()`, `onAfterOnce()` and `onAfterAffect()` are `$e` hooks on the command's name. A hook any other code registers in `$e` on the same name hears the same runs. A run's hook callbacks are called one after the other, each awaited, and the first that throws or rejects fails the run, as before.
179
+ - What it costs does not grow with the instances: a run finds its instance's hooks by name, a state change wakes only the instances whose own state changed, and a hook written inline is registered once for its instance, not at every render.
180
+ - An app that keeps its `$e` components itself (its user actions) declares one named as the React component, with the instances' slice in its store; react-commander then uses it, adds the commands to it and keeps the instances' state there, beside whatever else that store holds:
181
+
182
+ ```ts
183
+ import { ComponentBase, instancesStore, withInstances, valueStore } from "@zenflux/commands";
184
+
185
+ class ItemsListComponent extends ComponentBase< ReturnType< typeof instancesStore > > {
186
+ getNamespace() { return "App/ItemsList"; }
187
+ defaultStore() { return instancesStore(); } // or withInstances( valueStore( { filter: "" } ) )
188
+ }
189
+
190
+ $e.components.register( new ItemsListComponent() ); // before the app renders
191
+ ```
192
+
193
+ - Each instance's state is in its `$e` component's store (a reducer's state, @zenflux/commands' own: no @wordpress/data), by its unique name: `select( $e.components.get( "App/ItemsList" ).store ).getInstance( "App/ItemsList-:r1:" )`. The store's reducer finds what changed, so `useCommandState()` draws again only for a real change, and a selector's pick is kept while the state is the same.
194
+ - From outside a component, `useCommand()` finds its instance as it runs, one that is on the page first.
195
+ - `useSelect( ( selectFrom ) => selectFrom( store ).getX(), deps )` (from `hooks`) draws a component again as a store it read changes, for state outside an instance (an `$e` component's own); `useCommandState()` stays the hook for an instance's.
196
+ - A command added once its component's first instance mounted (a second `withCommands()` of the name, loaded later; a hot reload) is added to its `$e` component then.
197
+ - An instance's state stays across an unmount and mount of the same instance (StrictMode; a Suspense that hid it and shows it again).
198
+ - With `new API( { isDebug: true } )`, `$e.devTools` logs each run.
199
+ - React 18.3 or later, any bundler: the package reads vite's `import.meta.env` only where it is there.
200
+
160
201
  ## API Reference
161
202
 
162
203
  ### Commands
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A command run by a name that no mounted component registered.
3
+ */
4
+ export class CommandNotFound extends Error {
5
+ public constructor( command: string ) {
6
+ super( `Command: '${ command }' is not found` );
7
+ }
8
+ }
@@ -16,8 +16,6 @@ export const INTERNAL_ON_CONTEXT_STATE_UPDATED = `${ NAMESPACE }/__internalOnCon
16
16
 
17
17
  export const INTERNAL_PROPS = `${ NAMESPACE }/__internalProps`;
18
18
 
19
- export const INTERNAL_STATE_UPDATED_EVENT = `${ NAMESPACE }/__internalStateUpdated`;
20
-
21
19
  export const DEBUG_ENABLED = ( () => {
22
20
  if ( typeof window !== "undefined" ) {
23
21
  const w = window as WindowWithDebug;
@@ -28,8 +26,22 @@ export const DEBUG_ENABLED = ( () => {
28
26
  const meta = import.meta as ImportMeta & { env?: Record<string, string | undefined> };
29
27
  if ( meta.env?.ZENFLUX_DEBUG !== undefined ) return !!meta.env.ZENFLUX_DEBUG;
30
28
  }
31
- if ( typeof process !== "undefined" && process.env?.ZENFLUX_DEBUG !== undefined ) {
32
- return !!process.env.ZENFLUX_DEBUG;
29
+ if ( typeof process !== "undefined" && process.env ) {
30
+ // Any name: a consumer's `ProcessEnv` may list only its own (`NODE_ENV`).
31
+ const env: Record<string, string | undefined> = { ... process.env };
32
+ if ( env.ZENFLUX_DEBUG !== undefined ) return !!env.ZENFLUX_DEBUG;
33
33
  }
34
34
  return false;
35
35
  } )();
36
+
37
+ /**
38
+ * vite's `import.meta.env` and `import.meta.hot`, read where they may be missing: a bundler other than vite (webpack)
39
+ * gives neither, and a consumer's types may not declare them. Each read is written out as `import.meta.env` and
40
+ * `import.meta.hot`, which vite finds by their text to give them.
41
+ */
42
+
43
+ /** A development build: vite's `import.meta.env.DEV`. */
44
+ export const DEV_ENABLED = !! ( import.meta as ImportMeta & { env?: { DEV?: boolean } } ).env?.DEV;
45
+
46
+ /** vite's hot reload is on. */
47
+ export const HOT_RELOADING = !! ( import.meta as ImportMeta & { hot?: object } ).hot;
@@ -1,6 +1,7 @@
1
1
 
2
2
  import {
3
3
  DEBUG_ENABLED,
4
+ DEV_ENABLED,
4
5
  GET_INTERNAL_MATCH_SYMBOL,
5
6
  GET_INTERNAL_SYMBOL,
6
7
  REGISTER_INTERNAL_SYMBOL,
@@ -10,7 +11,8 @@ import {
10
11
 
11
12
  import { logger } from "./logger";
12
13
 
13
- import { version } from "../../package.json";
14
+ // The default export: a JSON module has no named ones to a bundler (webpack).
15
+ import packageJson from "../../package.json";
14
16
 
15
17
  import type { DCoreContext, DCoreInterface, DCoreRegisterArgs } from "./definitions";
16
18
 
@@ -49,7 +51,7 @@ function setSortedContextKeys( keys: string[] ) {
49
51
  * It provides methods to register, unregister, get and link components.
50
52
  */
51
53
  class Core implements DCoreInterface {
52
- public version = version;
54
+ public version = packageJson.version;
53
55
 
54
56
  /**
55
57
  * Registers the context for a React component.
@@ -206,9 +208,9 @@ class Core implements DCoreInterface {
206
208
  public __devDebug( ... _args: any[] ): void {
207
209
  }
208
210
 
209
- declare public __devGetContextLength: () => number;
210
- declare public __devGetContextKeys: () => string[];
211
- declare public __devGetContextValues: () => DCommandSingleComponentContext[];
211
+ public __devGetContextLength!: () => number;
212
+ public __devGetContextKeys!: () => string[];
213
+ public __devGetContextValues!: () => DCommandSingleComponentContext[];
212
214
  }
213
215
 
214
216
  const CORE_INSTANCE_KEY = Symbol.for( "@zenflux/react-commander/core-instance" );
@@ -225,7 +227,7 @@ function getOrCreateCore(): DCoreInterface {
225
227
 
226
228
  const core = getOrCreateCore();
227
229
 
228
- if ( /* from vite */ import.meta.env.DEV ) {
230
+ if ( DEV_ENABLED ) {
229
231
  if ( DEBUG_ENABLED ) {
230
232
  core.__devDebug = ( ... args: Parameters<DCoreInterface[ "__devDebug" ]> ) => {
231
233
  // Spread into `debug( caller, message, ...params )`, whose message is not optional:
@@ -1,6 +1,9 @@
1
- import EventEmitter from "eventemitter3";
1
+ // The class itself, not core's index: the index is its built bundle, with every module of it.
2
+ import { ObjectBase } from "@zenflux/core/src/bases/object-base";
2
3
 
3
- import { CommandPublic } from "@zenflux/core/src/command-bases/command-public";
4
+ import commandsManager from "@zenflux/react-commander/commands-manager";
5
+
6
+ import type EventEmitter from "eventemitter3";
4
7
 
5
8
  import type { DCommandOptions, DCommandArgs, DCommandRegisterArgs } from "@zenflux/react-commander/definitions";
6
9
 
@@ -9,14 +12,10 @@ import type React from "react";
9
12
  /**
10
13
  * Each created command is registered within the commands manager, and the instance created only once per command.
11
14
  *
12
- * Extends `CommandPublic` from `@zenflux/core` to inherit:
13
- * - `ObjectBase`: unique id, `getName()`, `getUniqueId()`, `getHierarchyNames()`
14
- * - `CommandBase`: logger, `onBeforeApply`/`onAfterApply` lifecycle hooks, `run()` method
15
- * - `CommandPublic`: semantic marker for user-facing commands
15
+ * Extends `ObjectBase` from `@zenflux/core`: a unique id, `getName()`, `getUniqueId()`, `getHierarchyNames()`. `$e`
16
+ * runs it (`execute()`): core has no command system of its own.
16
17
  */
17
- export abstract class CommandBase<TState = React.ComponentState, TArgs = DCommandArgs> extends CommandPublic {
18
- private static globalEmitter: EventEmitter = new EventEmitter();
19
-
18
+ export abstract class CommandBase<TState = React.ComponentState, TArgs = DCommandArgs> extends ObjectBase {
20
19
  public readonly commandName: string;
21
20
 
22
21
  private reactOptions: DCommandOptions<TState> = {};
@@ -29,22 +28,22 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
29
28
  return "@zenflux/react-commander";
30
29
  }
31
30
 
31
+ /**
32
+ * Hooks the command on every instance: an `$e` 'after' hook on its name.
33
+ */
32
34
  public static globalHook( callback: ( result?: any, args?: DCommandArgs ) => any ) {
33
- this.globalEmitter.on( this.getName(), callback );
35
+ commandsManager.hookGlobal( this.getName(), callback );
34
36
  }
35
37
 
36
38
  public static globalUnhook() {
37
- this.globalEmitter.listeners( this.getName() ).forEach( ( listener: any ) => {
38
- this.globalEmitter.off( this.getName(), listener );
39
- } );
39
+ commandsManager.unhookGlobal( this.getName() );
40
40
  }
41
41
 
42
42
  /**
43
- * React-commander creates command instances during registration (not per-execution),
44
- * so we pass empty args/options to core's CommandBase constructor.
43
+ * React-commander creates command instances during registration (not per-execution).
45
44
  */
46
45
  public constructor( _registerArgs: DCommandRegisterArgs ) {
47
- super( {}, {} );
46
+ super();
48
47
 
49
48
  this.commandName = ( new.target as typeof CommandBase ).getName();
50
49
  }
@@ -55,17 +54,14 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
55
54
  return global as unknown as {
56
55
  getName: typeof CommandBase.getName;
57
56
 
58
- globalEmitter: EventEmitter;
59
57
  globalHook: typeof CommandBase.globalHook;
60
58
  globalUnhook: typeof CommandBase.globalUnhook;
61
59
  };
62
60
  }
63
61
 
64
62
  /**
65
- * React-aware command execution entry point.
66
- *
67
- * Integrates core's lifecycle hooks (`onBeforeApply`/`onAfterApply`) while
68
- * preserving react-commander's event emission and state management.
63
+ * React-aware command execution entry point: `onBeforeApply()`, `apply()`, `onAfterApply()`, then the emitter's
64
+ * listeners.
69
65
  */
70
66
  public async execute( emitter: EventEmitter, args: TArgs, options?: DCommandOptions<TState> ): Promise<any> {
71
67
  if ( options ) {
@@ -74,24 +70,18 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
74
70
 
75
71
  this.validateArgs?.( args, options );
76
72
 
77
- // Core lifecycle: before
78
73
  this.onBeforeApply?.();
79
74
 
80
75
  const result = await this.apply( args as any );
81
76
 
82
- // Core lifecycle: after
83
77
  this.onAfterApply?.();
84
78
 
79
+ // Listeners on the emitter it was given: a caller's own (the hooks are `$e`'s, run by the manager's run).
85
80
  const listeners = emitter.listeners( this.commandName );
86
81
  for ( const listener of listeners ) {
87
82
  await listener( result, args );
88
83
  }
89
84
 
90
- const globalListeners = this.global().globalEmitter.listeners( this.commandName );
91
- for ( const globalListener of globalListeners ) {
92
- await globalListener( result, args );
93
- }
94
-
95
85
  this.reactOptions = {};
96
86
 
97
87
  return result;
@@ -100,9 +90,12 @@ export abstract class CommandBase<TState = React.ComponentState, TArgs = DComman
100
90
  protected validateArgs?( _args: TArgs, _options?: DCommandOptions<TState> ) {
101
91
  }
102
92
 
93
+ protected onBeforeApply?(): void;
94
+
95
+ protected onAfterApply?(): void;
96
+
103
97
  /**
104
- * Override core's `apply()` (which throws `ForceMethodImplementation`) to be
105
- * optional — react-commander commands may or may not implement apply.
98
+ * What the command does: optional, as a command may only be hooked.
106
99
  */
107
100
  protected apply( _args?: any, _options?: any ): Promise<any> | any {
108
101
  }