@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
package/readme.md ADDED
@@ -0,0 +1,1422 @@
1
+ # @zenflux/react-commander
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.
4
+
5
+ ## Table of contents
6
+
7
+ - [Installation](#installation)
8
+ - [Quick Start](#quick-start)
9
+ - [Core Concepts](#core-concepts)
10
+ - [API Reference](#api-reference)
11
+ - [Commands](#commands)
12
+ - [Hooks](#hooks)
13
+ - [Query System](#query-system)
14
+ - [Advanced Features](#advanced-features)
15
+ - [Live Examples](#live-examples)
16
+ - [Examples](#examples)
17
+ - [Migration Guide](#migration-guide)
18
+ - [Contributing](#contributing)
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ bun add @zenflux/react-commander
24
+ ```
25
+
26
+ ## Quick Start
27
+
28
+ > **Live Demo**: See the complete budget allocation system in action at [apps-example/budget-allocation](../../apps-example//budget-allocation/)
29
+
30
+ ### 1. Define a Command
31
+
32
+ ```ts
33
+ import { CommandBase } from "@zenflux/react-commander/command-base";
34
+
35
+ type Item = { id: string; name: string };
36
+ type ItemsState = { items: Item[] };
37
+
38
+ export class SetItemName extends CommandBase<ItemsState, { id: string; name: string }> {
39
+ static getName() { return "App/ItemsList/SetName" }
40
+
41
+ protected apply(args: { id: string; name: string }) {
42
+ const items = (this.state.items ?? []).map(i =>
43
+ i.id === args.id ? { ...i, name: args.name } : i
44
+ );
45
+ return this.setState({ items });
46
+ }
47
+ }
48
+ ```
49
+
50
+ ### 2. Wrap a Component
51
+
52
+ ```tsx
53
+ import React from "react";
54
+ import { withCommands } from "@zenflux/react-commander/with-commands";
55
+ import { useCommand, useCommandState } from "@zenflux/react-commander/hooks";
56
+
57
+ type Item = { id: string; name: string };
58
+ type ItemsState = { items: Item[] };
59
+
60
+ function ItemsList() {
61
+ const setName = useCommand("App/ItemsList/SetName");
62
+ const [slice] = useCommandState<ItemsState, { items: Item[] }>(
63
+ "App/ItemsList",
64
+ s => ({ items: s.items ?? [] })
65
+ );
66
+
67
+ const renameFirst = () => {
68
+ const first = slice.items[0];
69
+ if (first) setName.run({ id: first.id, name: first.name + "!" });
70
+ };
71
+
72
+ return (
73
+ <div>
74
+ <button onClick={renameFirst}>Rename first</button>
75
+ <ul>{slice.items.map(i => <li key={i.id}>{i.name}</li>)}</ul>
76
+ </div>
77
+ );
78
+ }
79
+
80
+ export const ItemsListWithCommands = withCommands<{}, ItemsState>(
81
+ "App/ItemsList",
82
+ ItemsList,
83
+ { items: [] },
84
+ [SetItemName]
85
+ );
86
+ ```
87
+
88
+ ### 3. Add Data Fetching (Optional)
89
+
90
+ ```ts
91
+ import { QueryListModuleBase } from "@zenflux/react-commander/query/module-base";
92
+
93
+ export class ItemsQuery extends QueryListModuleBase<Item> {
94
+ static getName() { return "items" }
95
+ protected getResourceName() { return "items" }
96
+
97
+ protected registerEndpoints(): void {
98
+ this.defineEndpoint<Array<{ id: string; name: string }>, Item[]>(
99
+ "App/ItemsList",
100
+ { method: "GET", path: "v1/items", prepareData: api => api.map(x => ({ id: x.id, name: x.name })) }
101
+ );
102
+ this.register("POST", "App/ItemsList/SetName", "v1/items/set-name");
103
+ }
104
+
105
+ protected onMount(context, resource?: Item[]) {
106
+ context.setState({ ...context.getState(), items: resource ?? [] });
107
+ }
108
+ }
109
+ ```
110
+
111
+ ### 4. Bootstrap Your App
112
+
113
+ ```tsx
114
+ import React from "react";
115
+ import { QueryClient } from "@zenflux/react-commander/query/client";
116
+ import { QueryProvider } from "@zenflux/react-commander/query/provider";
117
+ import { QueryComponent } from "@zenflux/react-commander/query/component";
118
+ import { ItemsQuery } from "./items-query";
119
+ import { ItemsListWithCommands } from "./items-list";
120
+
121
+ const client = new QueryClient("https://api.example.com");
122
+ client.registerModule(ItemsQuery);
123
+
124
+ export function App() {
125
+ return (
126
+ <QueryProvider client={client}>
127
+ <QueryComponent
128
+ module={ItemsQuery}
129
+ component={ItemsListWithCommands}
130
+ props={{}}
131
+ />
132
+ </QueryProvider>
133
+ );
134
+ }
135
+ ```
136
+
137
+ ## Core Concepts
138
+
139
+ ### Commands
140
+ Commands are classes that encapsulate user actions with typed arguments and state transitions. They provide:
141
+ - **Type Safety**: Full TypeScript support for arguments and state
142
+ - **Testability**: Easy to unit test in isolation
143
+ - **Observability**: Built-in logging and analytics hooks
144
+ - **Reversibility**: Support for undo/redo patterns
145
+
146
+ ### Component Context
147
+ Each wrapped component gets a unique context with:
148
+ - **Per-instance State**: Isolated state management
149
+ - **Command Registry**: Access to registered commands
150
+ - **Lifecycle Hooks**: Mount, update, and unmount events
151
+ - **Event System**: Cross-component communication
152
+
153
+ ### Query System
154
+ A lightweight data fetching layer that provides:
155
+ - **Endpoint Declaration**: Define API routes and data transformation
156
+ - **Caching**: Automatic request deduplication and caching
157
+ - **Lifecycle Integration**: Automatic data loading and state updates
158
+ - **Type Safety**: End-to-end type safety from API to component
159
+
160
+ ## API Reference
161
+
162
+ ### Commands
163
+
164
+ #### CommandBase<TState, TArgs>
165
+
166
+ Base class for all commands.
167
+
168
+ ```ts
169
+ abstract class CommandBase<TState, TArgs = {}> {
170
+ static getName(): string
171
+ protected get state(): TState
172
+ protected setState<K extends keyof TState>(state: TState | Pick<TState, K>, cb?: (s: TState) => void): Promise<void>
173
+ protected validateArgs?(args: TArgs): void
174
+ protected apply?(args: TArgs): Promise<unknown> | unknown
175
+ static globalHook(fn: (result?: unknown, args?: TArgs) => void): void
176
+ static globalUnhook(): void
177
+ }
178
+ ```
179
+
180
+ #### withCommands(componentName, Component, [state?], commands[])
181
+
182
+ Wraps a component with command capabilities.
183
+
184
+ ```tsx
185
+ export const MyComponentWithCommands = withCommands<Props, State>(
186
+ "App/MyComponent",
187
+ MyComponent,
188
+ { initial: "state" },
189
+ [Command1, Command2]
190
+ );
191
+ ```
192
+
193
+ ### Hooks
194
+
195
+ #### useCommand(commandName, ref?)
196
+
197
+ Intelligent command adapter that resolves commands by context.
198
+
199
+ ```tsx
200
+ const setName = useCommand("App/ItemsList/SetName");
201
+ setName.run({ id: "123", name: "New Name" });
202
+
203
+ // With ref for specific instance
204
+ const itemRef = React.useRef();
205
+ const setName = useCommand("App/Item/SetName", itemRef);
206
+ ```
207
+
208
+ #### useComponent(componentName, context?, options?)
209
+
210
+ Target a specific component instance by context.
211
+
212
+ ```tsx
213
+ const item = useComponent("App/Item");
214
+ item.run("App/Item/SetName", { name: "New" });
215
+ item.getState<ItemState>();
216
+ ```
217
+
218
+ #### useCommandState(componentName, selector?, options?)
219
+
220
+ Subscribe to component state with optional selector.
221
+
222
+ ```tsx
223
+ // Basic usage
224
+ const [getState, setState, isMounted] = useCommandState<ItemState>("App/Item");
225
+
226
+ // With selector for performance
227
+ const [slice, setState, isMounted] = useCommandState<ItemState, { name: string }>(
228
+ "App/Item",
229
+ s => ({ name: s.name })
230
+ );
231
+ ```
232
+
233
+ #### useCommandHook(commandName, handler, ref?)
234
+
235
+ Declarative subscription to command events.
236
+
237
+ ```tsx
238
+ useCommandHook("App/Item/SetName", (result, args) => {
239
+ console.log("Item renamed:", args);
240
+ });
241
+ ```
242
+
243
+ #### useChildCommandHook(childComponentName, commandName, handler, opts?)
244
+
245
+ Subscribe to commands on child components.
246
+
247
+ ```tsx
248
+ useChildCommandHook("App/Item", "App/Item/SetName", (result, args) => {
249
+ console.log("Child item renamed:", args);
250
+ });
251
+ ```
252
+
253
+ ### Query System
254
+
255
+ #### QueryModuleBase<TResource>
256
+
257
+ Base class for query modules.
258
+
259
+ ```ts
260
+ abstract class QueryModuleBase<TResource> {
261
+ static getName(): string
262
+ protected getResourceName(): string
263
+ protected registerEndpoints(): void
264
+ protected defineEndpoint<TApi, TData>(name: string, cfg: { method: string; path: string; prepareData?: (api: TApi) => TData }): void
265
+ protected register(method: string, name: string, route: string | { path: string }): void
266
+ request<TResult>(name: string, args?: Record<string, unknown>): Promise<TResult>
267
+ getData<TData>(element: DCommandFunctionComponent, args?: Record<string, unknown>): Promise<TData>
268
+ }
269
+ ```
270
+
271
+ #### QueryListModuleBase<TEntity>
272
+
273
+ Specialized for list operations.
274
+
275
+ ```ts
276
+ export class ItemsQuery extends QueryListModuleBase<Item> {
277
+ static getName() { return "items"; }
278
+ protected getResourceName() { return "items"; }
279
+
280
+ protected registerEndpoints() {
281
+ this.defineEndpoint<ItemApiResponse[], Item[]>("App/ItemsList", {
282
+ method: "GET",
283
+ path: "v1/items",
284
+ prepareData: api => api.map(transformItem)
285
+ });
286
+ }
287
+ }
288
+ ```
289
+
290
+ ## Advanced Features
291
+
292
+ ### Undo/Redo Support
293
+
294
+ Every command can be made reversible by implementing inverse operations:
295
+
296
+ ```ts
297
+ export class SetItemName extends CommandBase<ItemsState, { id: string; name: string }> {
298
+ static getName() { return "App/ItemsList/SetName" }
299
+
300
+ protected apply(args: { id: string; name: string }) {
301
+ const previousName = this.state.items.find(i => i.id === args.id)?.name;
302
+ const items = this.state.items.map(i =>
303
+ i.id === args.id ? { ...i, name: args.name } : i
304
+ );
305
+ this.setState({ items });
306
+
307
+ // Return inverse for undo support
308
+ return { id: args.id, name: previousName };
309
+ }
310
+ }
311
+ ```
312
+
313
+ ### Analytics and Logging
314
+
315
+ Global hooks for analytics and auditing:
316
+
317
+ ```ts
318
+ // Global analytics
319
+ const cmds = commandsManager.get("App/ItemsList", true);
320
+ cmds["App/ItemsList/SetName"].global().globalHook((result, args) => {
321
+ analytics.track("item_renamed", { itemId: args.id, newName: args.name });
322
+ });
323
+ ```
324
+
325
+ ### Autosave
326
+
327
+ Automatic saving with debouncing:
328
+
329
+ ```ts
330
+ import { queryCreateAutoSaveManager } from "@zenflux/react-commander/query/auto-save-manager";
331
+
332
+ const autosave = queryCreateAutoSaveManager<ItemsState, { items: Item[] }>({
333
+ getKey: () => "items-list",
334
+ pickToSave: s => ({ items: s.items }),
335
+ save: async input => {
336
+ await api.fetch("POST", "v1/items/save", input);
337
+ },
338
+ debounceMs: 800,
339
+ intervalMs: 5000
340
+ });
341
+ ```
342
+
343
+ ### Testing
344
+
345
+ #### Unit Testing Commands
346
+
347
+ ```ts
348
+ test("SetItemName updates item name", async () => {
349
+ const cmd = new SetItemName({});
350
+ const holder = { state: { items: [{ id: "1", name: "Old" }] } };
351
+
352
+ cmd.options = {
353
+ state: holder.state,
354
+ setState: (s, cb) => {
355
+ holder.state = { ...holder.state, ...s };
356
+ cb?.(holder.state);
357
+ }
358
+ };
359
+
360
+ await cmd.execute({ on: () => [], listeners: () => [] } as any, { id: "1", name: "New" });
361
+ expect(holder.state.items[0].name).toBe("New");
362
+ });
363
+ ```
364
+
365
+ #### Integration Testing
366
+
367
+ ```tsx
368
+ test("rename button dispatches command", async () => {
369
+ const handler = vi.fn();
370
+ commandsManager.hookByNameScoped(
371
+ { commandName: "App/ItemsList/SetName", componentName: "App/ItemsList", ownerId: "test" },
372
+ handler
373
+ );
374
+
375
+ render(<RenameButton id="1" />);
376
+ fireEvent.click(screen.getByText("Rename"));
377
+
378
+ expect(handler).toHaveBeenCalledWith(expect.any(Object), { id: "1", name: "New Name" });
379
+ });
380
+ ```
381
+
382
+ ## Live Examples
383
+
384
+ ### Budget Allocation System
385
+
386
+ A complete, production-ready application demonstrating all `@zenflux/react-commander` features:
387
+
388
+ - **Commands**: Add, edit, remove channels with full CRUD operations
389
+ - **Query System**: Data fetching, caching, and automatic persistence
390
+ - **Cross-Component Communication**: Parent-child interactions and event handling
391
+ - **Multiple Views**: Accordion and table layouts with dynamic switching
392
+ - **Autosave**: Debounced persistence with interval-based flushing
393
+ - **Real-world Patterns**: Error handling, loading states, and user interactions
394
+
395
+ **🔗 [View Live Demo](https://github.com/ZenFlux/zenflux/tree/main/zenflux-react-app-examples/budget-allocation)**
396
+
397
+ This example showcases:
398
+ - Complex state management with typed commands
399
+ - API integration with automatic sync
400
+ - Child component orchestration
401
+ - Performance optimizations with selectors
402
+ - Production-ready error handling
403
+
404
+ ## Examples
405
+
406
+ ### Complete Budget Allocation System
407
+
408
+ This comprehensive example demonstrates all features including Commands, Query system, child components, and real-world patterns.
409
+
410
+ > **Live Demo**: [View the complete implementation](https://github.com/ZenFlux/zenflux/tree/main/zenflux-react-app-examples/budget-allocation)
411
+
412
+ #### 1. Domain Types
413
+
414
+ ```ts
415
+ // types.ts
416
+ export interface Channel {
417
+ meta: {
418
+ id: string;
419
+ name: string;
420
+ icon: string;
421
+ };
422
+ breaks?: BudgetBreak[];
423
+ }
424
+
425
+ export interface BudgetBreak {
426
+ id: string;
427
+ amount: number;
428
+ description: string;
429
+ }
430
+
431
+ export interface ChannelListState {
432
+ channels: Channel[];
433
+ selected: { [key: string]: boolean };
434
+ }
435
+
436
+ export interface ChannelListProps {
437
+ view: "accordion" | "table";
438
+ }
439
+ ```
440
+
441
+ #### 2. Commands
442
+
443
+ ```ts
444
+ // channels-commands.ts
445
+ import { CommandBase } from "@zenflux/react-commander/command-base";
446
+ import { getQueryModule } from "@zenflux/react-commander/query/provider";
447
+ import { ChannelsListQuery } from "./channels-list-query";
448
+
449
+ export class AddChannel extends CommandBase<ChannelListState> {
450
+ static getName() { return "App/ChannelsList/AddChannel" }
451
+
452
+ async apply() {
453
+ const queryModule = getQueryModule(ChannelsListQuery);
454
+ const channel = await queryModule.request("App/ChannelsList/AddChannel");
455
+ return this.setState({ channels: [...this.state.channels, channel] });
456
+ }
457
+ }
458
+
459
+ export class SetChannelName extends CommandBase<ChannelListState, { id: string; name: string }> {
460
+ static getName() { return "App/ChannelsList/SetName" }
461
+
462
+ apply(args: { id: string; name: string }) {
463
+ const channels = this.state.channels.map(c =>
464
+ c.meta.id === args.id
465
+ ? { ...c, meta: { ...c.meta, name: args.name } }
466
+ : c
467
+ );
468
+ return this.setState({ channels });
469
+ }
470
+ }
471
+
472
+ export class EditChannel extends CommandBase<ChannelListState, { channel: Channel }> {
473
+ static getName() { return "App/ChannelsList/EditRequest" }
474
+
475
+ apply(args: { channel: Channel }) {
476
+ // Logic for editing channel
477
+ return this.setState({ selected: { [args.channel.meta.id]: true } });
478
+ }
479
+ }
480
+
481
+ export class RemoveChannel extends CommandBase<ChannelListState, { channel: Channel }> {
482
+ static getName() { return "App/ChannelsList/RemoveRequest" }
483
+
484
+ apply(args: { channel: Channel }) {
485
+ const channels = this.state.channels.filter(c => c.meta.id !== args.channel.meta.id);
486
+ return this.setState({ channels });
487
+ }
488
+ }
489
+ ```
490
+
491
+ #### 3. Query Module
492
+
493
+ ```ts
494
+ // channels-list-query.ts
495
+ import { QueryListModuleBase } from "@zenflux/react-commander/query/module-base";
496
+ import { queryCreateAutoSaveManager } from "@zenflux/react-commander/query/auto-save-manager";
497
+ import commandsManager from "@zenflux/react-commander/commands-manager";
498
+
499
+ export class ChannelsListQuery extends QueryListModuleBase<Channel> {
500
+ private autosave: ReturnType<typeof queryCreateAutoSaveManager>;
501
+
502
+ constructor(client: QueryClient) {
503
+ super(client);
504
+
505
+ this.autosave = queryCreateAutoSaveManager<ChannelListState, { key: string; channels: Channel[] }>({
506
+ getKey: () => "channels-list",
507
+ pickToSave: (state) => ({
508
+ key: "channels-list",
509
+ channels: state.channels
510
+ }),
511
+ save: async (input) => {
512
+ await this.api.fetch("POST", "v1/channels/list", input);
513
+ },
514
+ debounceMs: 800,
515
+ intervalMs: 5000
516
+ });
517
+ }
518
+
519
+ static getName() { return "channels" }
520
+ protected getResourceName() { return "channels" }
521
+
522
+ protected registerEndpoints() {
523
+ this.defineEndpoint<ChannelApiResponse[], Channel[]>("App/ChannelsList", {
524
+ method: "GET",
525
+ path: "v1/channels",
526
+ prepareData: (api) => api.map(transformChannel)
527
+ });
528
+
529
+ this.register("POST", "App/ChannelsList/AddChannel", "v1/channels/create");
530
+ this.register("POST", "App/ChannelsList/SetName", "v1/channels/set-name");
531
+ }
532
+
533
+ protected onMount(context, resource?: Channel[]) {
534
+ context.setState({
535
+ ...context.getState(),
536
+ channels: resource ?? []
537
+ });
538
+
539
+ // Set up autosave on selection changes
540
+ const accordion = commandsManager.get("UI/Accordion", true);
541
+ if (accordion) {
542
+ const saveCallback = async () => {
543
+ const state = context.getState<ChannelListState>();
544
+ this.autosave.queryUpsert(state);
545
+ await this.autosave.queryFlush();
546
+ };
547
+
548
+ accordion["UI/Accordion/onSelectionAttached"].global().globalHook(saveCallback);
549
+ accordion["UI/Accordion/onSelectionDetached"].global().globalHook(saveCallback);
550
+ }
551
+
552
+ // Set up API sync for name changes
553
+ const channelsList = commandsManager.get("App/ChannelsList", true);
554
+ if (channelsList) {
555
+ channelsList["App/ChannelsList/SetName"].global().globalHook(async (_, args) => {
556
+ if (args?.id && args?.name) {
557
+ await this.request("App/ChannelsList/SetName", {
558
+ id: args.id as string,
559
+ name: args.name as string
560
+ });
561
+ }
562
+ });
563
+ }
564
+ }
565
+
566
+ protected onUnmount(context) {
567
+ this.autosave.queryFlush();
568
+ // Clean up global hooks
569
+ }
570
+ }
571
+ ```
572
+
573
+ #### 4. Main Component with Commands
574
+
575
+ ```tsx
576
+ // channels-list.tsx
577
+ import React from "react";
578
+ import { withCommands } from "@zenflux/react-commander/with-commands";
579
+ import { useCommandState } from "@zenflux/react-commander/hooks";
580
+ import { QueryComponent } from "@zenflux/react-commander/query/component";
581
+
582
+ function ChannelsList({ view }: ChannelListProps) {
583
+ const [state] = useCommandState<ChannelListState>("App/ChannelsList", s => s);
584
+
585
+ switch (view) {
586
+ case "accordion":
587
+ return <ChannelsListAccordion />;
588
+ case "table":
589
+ return <ChannelsListTable />;
590
+ default:
591
+ throw new Error(`Unknown view: ${view}`);
592
+ }
593
+ }
594
+
595
+ export const ChannelsListWithCommands = withCommands<ChannelListProps, ChannelListState>(
596
+ "App/ChannelsList",
597
+ ChannelsList,
598
+ { channels: [], selected: {} },
599
+ [AddChannel, SetChannelName, EditChannel, RemoveChannel]
600
+ );
601
+ ```
602
+
603
+ #### 5. Accordion View with Interactions
604
+
605
+ ```tsx
606
+ // channels-list-accordion.tsx
607
+ import React from "react";
608
+ import { useComponent, useCommandState, useChildCommandHook, useChildCommandRunner } from "@zenflux/react-commander/hooks";
609
+
610
+ export function ChannelsListAccordion() {
611
+ const [state, setState] = useCommandState<ChannelListState>("App/ChannelsList", s => s);
612
+ const component = useComponent("App/ChannelsList");
613
+
614
+ // Listen to child accordion item title edits
615
+ useChildCommandHook("UI/AccordionItem", "UI/AccordionItem/EditTitle", (_, args) => {
616
+ component.run("App/ChannelsList/SetName", {
617
+ id: args.itemKey,
618
+ name: args.title
619
+ });
620
+ });
621
+
622
+ // Runner for child components
623
+ const runAccordionItem = useChildCommandRunner("UI/AccordionItem", (ctx) => ctx.props.itemKey);
624
+
625
+ // Handle edit requests
626
+ useCommandHook("App/ChannelsList/EditRequest", (_, args) => {
627
+ const { channel } = args;
628
+ setState({ selected: { [channel.meta.id]: true } });
629
+
630
+ // Enable editing mode on the accordion item
631
+ runAccordionItem(channel.meta.id, "UI/AccordionItem/EditableTitle", { state: true });
632
+ });
633
+
634
+ return (
635
+ <Accordion selected={state.selected} setSelected={(selected) => setState({ selected })}>
636
+ {state.channels.map(channel => (
637
+ <AccordionItem
638
+ key={channel.meta.id}
639
+ itemKey={channel.meta.id}
640
+ heading={{ title: channel.meta.name, icon: channel.meta.icon }}
641
+ menu={{
642
+ edit: {
643
+ label: "Edit",
644
+ action: () => component.run("App/ChannelsList/EditRequest", { channel })
645
+ },
646
+ remove: {
647
+ label: "Remove",
648
+ color: "danger" as const,
649
+ action: () => component.run("App/ChannelsList/RemoveRequest", { channel })
650
+ }
651
+ }}
652
+ >
653
+ <ChannelContent channelId={channel.meta.id} meta={channel.meta} />
654
+ </AccordionItem>
655
+ ))}
656
+ </Accordion>
657
+ );
658
+ }
659
+ ```
660
+
661
+ #### 6. Table View
662
+
663
+ ```tsx
664
+ // channels-list-table.tsx
665
+ import React from "react";
666
+ import { useCommandState } from "@zenflux/react-commander/hooks";
667
+
668
+ export function ChannelsListTable() {
669
+ const [state] = useCommandState<ChannelListState>("App/ChannelsList", s => s);
670
+
671
+ const channelsWithBreaks = state.channels.filter(
672
+ channel => channel.breaks && channel.breaks.length > 0
673
+ );
674
+
675
+ return (
676
+ <div className="pt-[45px]">
677
+ {channelsWithBreaks.length === 0 ? (
678
+ <div className="pt-[15px] ps-[40px] text-slate-400 text-[11px] font-bold uppercase leading-none text-center">
679
+ There are {state.channels.length} channels, but none have budget allocation.
680
+ </div>
681
+ ) : (
682
+ channelsWithBreaks.map((channel, index) => (
683
+ <div key={index} className="h-[130px] flex flex-row items-center">
684
+ <div className="w-[220px] h-full">
685
+ <div className="pt-[15px] ps-[40px] text-slate-400 text-[11px] font-bold uppercase leading-none">
686
+ Channel #{index + 1}
687
+ </div>
688
+ <div className="pt-[30px] ps-[35px] text-slate-800 text-sm font-medium font-sans leading-[21px]">
689
+ <img src={channel.meta.icon} alt={channel.meta.name} className="inline-block mr-[10px] w-[36px] h-[36px]"/>
690
+ <span>{channel.meta.name}</span>
691
+ </div>
692
+ </div>
693
+ <div className="w-[80px] h-full border-e border-slate-300 bg-[linear-gradient(to_right,rgba(169,181,210,0.01),rgba(112,126,167,0.134))] opacity-50"/>
694
+ <ChannelItemTable $data={channel} key={channel.meta.id}/>
695
+ </div>
696
+ ))
697
+ )}
698
+ </div>
699
+ );
700
+ }
701
+ ```
702
+
703
+ #### 7. App Bootstrap
704
+
705
+ ```tsx
706
+ // app.tsx
707
+ import React from "react";
708
+ import { QueryClient } from "@zenflux/react-commander/query/client";
709
+ import { QueryProvider } from "@zenflux/react-commander/query/provider";
710
+ import { ChannelsListQuery } from "./channels-list-query";
711
+ import { ChannelsListWithCommands } from "./channels-list";
712
+
713
+ const client = new QueryClient("https://api.example.com");
714
+ client.registerModule(ChannelsListQuery);
715
+
716
+ export function App() {
717
+ return (
718
+ <QueryProvider client={client}>
719
+ <QueryComponent
720
+ module={ChannelsListQuery}
721
+ component={ChannelsListWithCommands}
722
+ props={{ view: "accordion" }}
723
+ />
724
+ </QueryProvider>
725
+ );
726
+ }
727
+ ```
728
+
729
+ #### 8. Child Component Integration
730
+
731
+ ```tsx
732
+ // channel-content.tsx
733
+ import React from "react";
734
+ import { QueryComponent } from "@zenflux/react-commander/query/component";
735
+ import { ChannelItemQuery } from "./channel-item-query";
736
+ import { ChannelItemAccordion } from "./channel-item-accordion";
737
+
738
+ const ChannelContent = React.memo<{ channelId: string; meta: Channel["meta"] }>(({ channelId, meta }) => {
739
+ return (
740
+ <QueryComponent
741
+ key={channelId}
742
+ fallback={<div className="loading">Loading...</div>}
743
+ module={ChannelItemQuery}
744
+ component={ChannelItemAccordion}
745
+ props={{ meta }}
746
+ />
747
+ );
748
+ }, (prevProps, nextProps) => prevProps.channelId === nextProps.channelId);
749
+ ```
750
+
751
+ This comprehensive example demonstrates:
752
+
753
+ - **Commands**: Add, edit, remove, and rename operations
754
+ - **Query System**: Data fetching, caching, and lifecycle management
755
+ - **Autosave**: Automatic persistence with debouncing
756
+ - **Child Components**: Cross-component communication
757
+ - **Multiple Views**: Accordion and table layouts
758
+ - **Real-world Patterns**: Error handling, loading states, and user interactions
759
+ - **Type Safety**: Full TypeScript integration throughout
760
+
761
+ ## Migration Guide
762
+
763
+ ### From Redux
764
+
765
+ 1. Replace actions with Commands
766
+ 2. Replace reducers with Command.apply methods
767
+ 3. Replace useSelector with useCommandState
768
+ 4. Replace dispatch with useCommand
769
+
770
+ ### From Context API
771
+
772
+ 1. Wrap components with withCommands
773
+ 2. Replace context consumers with useCommand/useCommandState
774
+ 3. Move state logic to Commands
775
+
776
+ ## API Reference
777
+
778
+ ### Core Classes
779
+
780
+ #### CommandBase<TState, TArgs>
781
+
782
+ Base class for all commands.
783
+
784
+ ```ts
785
+ import { CommandBase } from "@zenflux/react-commander/command-base";
786
+
787
+ abstract class CommandBase<TState = React.ComponentState, TArgs = DCommandArgs> {
788
+ static getName(): string
789
+ protected get state(): TState
790
+ protected setState<K extends keyof TState>(state: TState | Pick<TState, K>, cb?: (s: TState) => void): Promise<void>
791
+ protected validateArgs?(args: TArgs): void
792
+ protected apply?(args: TArgs): Promise<unknown> | unknown
793
+ static globalHook(fn: (result?: unknown, args?: TArgs) => void): void
794
+ static globalUnhook(): void
795
+ }
796
+ ```
797
+
798
+ #### withCommands(componentName, Component, [state?], commands[])
799
+
800
+ Higher-order component that wraps components with command capabilities.
801
+
802
+ ```ts
803
+ import { withCommands } from "@zenflux/react-commander/with-commands";
804
+
805
+ function withCommands<TProps = any, TState = undefined>(
806
+ componentName: string,
807
+ Component: DCommandFunctionComponent<TProps, TState>,
808
+ state?: TState,
809
+ commands?: DCommandNewInstanceWithArgs<TState>[]
810
+ ): DCommandFunctionComponent<TProps, TState>
811
+ ```
812
+
813
+ #### commandsManager
814
+
815
+ Central registry and dispatcher for all commands.
816
+
817
+ ```ts
818
+ import commandsManager from "@zenflux/react-commander/commands-manager";
819
+
820
+ class CommandsManager {
821
+ register(args: DCommandRegisterArgs): CommandBase[]
822
+ run(id: DCommandIdArgs, args: DCommandArgs, callback?: (result: any) => any): Promise<any>
823
+ hook(id: DCommandIdArgs, callback: (result?: any, args?: DCommandArgs) => any): DCommandHookHandle
824
+ unhook(id: DCommandIdArgs): void
825
+ unhookHandle(handle: DCommandHookHandle): void
826
+ get(componentName: string, includeGlobal?: boolean): { [commandName: string]: CommandBase }
827
+ }
828
+ ```
829
+
830
+ ### React Hooks
831
+
832
+ #### useCommand(commandName, ref?)
833
+
834
+ Intelligent command adapter that resolves commands by context.
835
+
836
+ ```ts
837
+ import { useCommand } from "@zenflux/react-commander/hooks";
838
+
839
+ function useCommand(commandName: string): UseCommandAdapter
840
+ function useCommand(commandName: string, ref: React.RefObject<any>): UseCommandAdapter | null
841
+
842
+ // Returns: { run, hook, unhook, unhookHandle?, getInternalContext }
843
+ ```
844
+
845
+ **Example:**
846
+ ```tsx
847
+ function ItemComponent({ id, name }: { id: string; name: string }) {
848
+ const setName = useCommand("App/ItemsList/SetName");
849
+ const deleteItem = useCommand("App/ItemsList/DeleteItem");
850
+
851
+ const handleRename = () => {
852
+ setName.run({ id, name: "New Name" });
853
+ };
854
+
855
+ const handleDelete = () => {
856
+ deleteItem.run({ id });
857
+ };
858
+
859
+ return (
860
+ <div>
861
+ <span>{name}</span>
862
+ <button onClick={handleRename}>Rename</button>
863
+ <button onClick={handleDelete}>Delete</button>
864
+ </div>
865
+ );
866
+ }
867
+ ```
868
+
869
+ #### useComponent(componentName, context?, options?)
870
+
871
+ Target a specific component instance by context.
872
+
873
+ ```ts
874
+ import { useComponent } from "@zenflux/react-commander/hooks";
875
+
876
+ function useComponent(
877
+ componentName: string,
878
+ context?: DCommandComponentContextProps,
879
+ options?: { silent?: boolean }
880
+ ): {
881
+ run: (commandName: string, args: DCommandArgs, callback?: (result: any) => void) => Promise<any>
882
+ hook: (commandName: string, callback: (result?: any, args?: DCommandArgs) => void) => DCommandHookHandle
883
+ unhook: (commandName: string) => void
884
+ unhookHandle: (handle: DCommandHookHandle) => void
885
+ getId: () => string
886
+ getKey: () => string
887
+ isAlive: () => boolean
888
+ getInternalContext: () => DCommandSingleComponentContext
889
+ getContext: () => DCommandComponentContextProps
890
+ getState: <TState extends React.ComponentState>() => TState
891
+ }
892
+ ```
893
+
894
+ **Example:**
895
+ ```tsx
896
+ function ItemsListToolbar() {
897
+ const itemsList = useComponent("App/ItemsList");
898
+
899
+ const handleSelectAll = () => {
900
+ if (itemsList.isAlive()) {
901
+ itemsList.run("App/ItemsList/SelectAll");
902
+ }
903
+ };
904
+
905
+ const handleClearSelected = () => {
906
+ itemsList.run("App/ItemsList/ClearSelected", {}, (result) => {
907
+ console.log(`Cleared ${result.count} items`);
908
+ });
909
+ };
910
+
911
+ const currentState = itemsList.getState<ItemsListState>();
912
+
913
+ return (
914
+ <div>
915
+ <button onClick={handleSelectAll}>Select All</button>
916
+ <button onClick={handleClearSelected}>
917
+ Clear Selected ({currentState.selectedCount})
918
+ </button>
919
+ </div>
920
+ );
921
+ }
922
+ ```
923
+
924
+ #### useCommandState(componentName, selector?, options?)
925
+
926
+ Subscribe to component state with optional selector.
927
+
928
+ ```ts
929
+ import { useCommandState } from "@zenflux/react-commander/hooks";
930
+
931
+ // Basic usage
932
+ function useCommandState<TState>(commandName: string): readonly [
933
+ () => TState,
934
+ (state: TState | ((prev: TState) => TState)) => void,
935
+ () => boolean
936
+ ]
937
+
938
+ // With selector
939
+ function useCommandState<TState, TSelector>(
940
+ commandName: string,
941
+ selector: (state: TState) => TSelector,
942
+ options?: { equalityFn?: (a: TSelector, b: TSelector) => boolean }
943
+ ): readonly [TSelector, (state: TState | ((prev: TState) => TState)) => void, () => boolean]
944
+ ```
945
+
946
+ **Example:**
947
+ ```tsx
948
+ function ItemsList() {
949
+ // Basic usage - get full state
950
+ const [getState, setState, isMounted] = useCommandState<ItemsListState>("App/ItemsList");
951
+
952
+ // With selector - only re-render when items change
953
+ const [items, setItems, isMounted] = useCommandState<ItemsListState, { items: Item[] }>(
954
+ "App/ItemsList",
955
+ state => ({ items: state.items })
956
+ );
957
+
958
+ // Custom equality function for complex objects
959
+ const [filteredItems, setFilteredItems] = useCommandState<ItemsListState, Item[]>(
960
+ "App/ItemsList",
961
+ state => state.items.filter(item => !item.archived),
962
+ { equalityFn: (a, b) => a.length === b.length && a.every((item, i) => item.id === b[i]?.id) }
963
+ );
964
+
965
+ const handleAddItem = () => {
966
+ if (isMounted()) {
967
+ setItems(prev => ({
968
+ ...prev,
969
+ items: [...prev.items, { id: Date.now().toString(), name: "New Item", archived: false }]
970
+ }));
971
+ }
972
+ };
973
+
974
+ return (
975
+ <div>
976
+ <button onClick={handleAddItem}>Add Item</button>
977
+ <ul>
978
+ {filteredItems.map(item => (
979
+ <li key={item.id}>{item.name}</li>
980
+ ))}
981
+ </ul>
982
+ </div>
983
+ );
984
+ }
985
+ ```
986
+
987
+ #### useCommandHook(commandName, handler, ref?)
988
+
989
+ Declarative subscription to command events.
990
+
991
+ ```ts
992
+ import { useCommandHook } from "@zenflux/react-commander/hooks";
993
+
994
+ function useCommandHook(
995
+ commandName: string,
996
+ handler: (result?: unknown, args?: DCommandArgs) => void,
997
+ ref?: React.RefObject<any>
998
+ ): void
999
+ ```
1000
+
1001
+ **Example:**
1002
+ ```tsx
1003
+ function ItemsAnalytics() {
1004
+ // Track item creation
1005
+ useCommandHook("App/ItemsList/AddItem", (result, args) => {
1006
+ analytics.track("item_created", {
1007
+ itemId: result.id,
1008
+ timestamp: Date.now()
1009
+ });
1010
+ });
1011
+
1012
+ // Track item updates
1013
+ useCommandHook("App/ItemsList/SetName", (result, args) => {
1014
+ analytics.track("item_renamed", {
1015
+ itemId: args.id,
1016
+ newName: args.name,
1017
+ timestamp: Date.now()
1018
+ });
1019
+ });
1020
+
1021
+ // Track with specific component instance
1022
+ const itemRef = useRef();
1023
+ useCommandHook("App/Item/DeleteItem", (result, args) => {
1024
+ console.log(`Item ${args.id} deleted from specific component`);
1025
+ }, itemRef);
1026
+
1027
+ return <div>Analytics tracking active</div>;
1028
+ }
1029
+ ```
1030
+
1031
+ #### useCommandRunner(commandName, ref?)
1032
+
1033
+ Get a memoized runner function for a specific command.
1034
+
1035
+ ```ts
1036
+ import { useCommandRunner } from "@zenflux/react-commander/hooks";
1037
+
1038
+ function useCommandRunner(
1039
+ commandName: string,
1040
+ ref?: React.RefObject<any>
1041
+ ): (args?: DCommandArgs, callback?: (result: unknown) => void) => unknown
1042
+ ```
1043
+
1044
+ **Example:**
1045
+ ```tsx
1046
+ function ItemForm({ onSubmit }: { onSubmit: (item: Item) => void }) {
1047
+ const addItem = useCommandRunner("App/ItemsList/AddItem");
1048
+ const [name, setName] = useState("");
1049
+
1050
+ const handleSubmit = (e: FormEvent) => {
1051
+ e.preventDefault();
1052
+
1053
+ addItem(
1054
+ { name, archived: false },
1055
+ (result) => {
1056
+ console.log("Item created:", result);
1057
+ onSubmit(result);
1058
+ setName("");
1059
+ }
1060
+ );
1061
+ };
1062
+
1063
+ return (
1064
+ <form onSubmit={handleSubmit}>
1065
+ <input
1066
+ value={name}
1067
+ onChange={(e) => setName(e.target.value)}
1068
+ placeholder="Add an item..."
1069
+ />
1070
+ <button type="submit">Add Item</button>
1071
+ </form>
1072
+ );
1073
+ }
1074
+
1075
+ // With ref for specific instance
1076
+ function ItemActions({ itemId }: { itemId: string }) {
1077
+ const itemRef = useRef();
1078
+ const toggleItem = useCommandRunner("App/Item/ToggleItem", itemRef);
1079
+
1080
+ const handleToggle = () => {
1081
+ toggleItem({ id: itemId });
1082
+ };
1083
+
1084
+ return <button onClick={handleToggle}>Toggle</button>;
1085
+ }
1086
+ ```
1087
+
1088
+ #### useComponentWithRef(componentName, ref)
1089
+
1090
+ Target a component instance by ref.
1091
+
1092
+ ```ts
1093
+ import { useComponentWithRef } from "@zenflux/react-commander/hooks";
1094
+
1095
+ function useComponentWithRef(
1096
+ componentName: string,
1097
+ ref: React.RefObject<any>
1098
+ ): ReturnType<typeof useComponent> | null
1099
+ ```
1100
+
1101
+ **Example:**
1102
+ ```tsx
1103
+ function ItemsList() {
1104
+ const itemRefs = useRef<{ [key: string]: React.RefObject<any> }>({});
1105
+
1106
+ return (
1107
+ <div>
1108
+ {items.map(item => {
1109
+ const itemRef = useRef();
1110
+ itemRefs.current[item.id] = itemRef;
1111
+
1112
+ return (
1113
+ <ItemComponent
1114
+ key={item.id}
1115
+ ref={itemRef}
1116
+ item={item}
1117
+ />
1118
+ );
1119
+ })}
1120
+ </div>
1121
+ );
1122
+ }
1123
+
1124
+ function ItemComponent({ item }: { item: Item }) {
1125
+ const itemRef = useRef();
1126
+ const itemComponent = useComponentWithRef("App/Item", itemRef);
1127
+
1128
+ const handleEdit = () => {
1129
+ if (itemComponent) {
1130
+ itemComponent.run("App/Item/StartEdit");
1131
+ }
1132
+ };
1133
+
1134
+ const handleDelete = () => {
1135
+ if (itemComponent) {
1136
+ itemComponent.run("App/Item/Delete", { id: item.id });
1137
+ }
1138
+ };
1139
+
1140
+ return (
1141
+ <div ref={itemRef}>
1142
+ <span>{item.name}</span>
1143
+ <button onClick={handleEdit}>Edit</button>
1144
+ <button onClick={handleDelete}>Delete</button>
1145
+ </div>
1146
+ );
1147
+ }
1148
+ ```
1149
+
1150
+ #### useChildCommandHook(childComponentName, commandName, handler, opts?)
1151
+
1152
+ Subscribe to commands on child components.
1153
+
1154
+ ```ts
1155
+ import { useChildCommandHook } from "@zenflux/react-commander/hooks";
1156
+
1157
+ function useChildCommandHook(
1158
+ childComponentName: string,
1159
+ commandName: string,
1160
+ handler: (result?: unknown, args?: DCommandArgs) => void,
1161
+ opts?: { filter?: (cmd: any) => boolean; ignoreDuplicate?: boolean }
1162
+ ): void
1163
+ ```
1164
+
1165
+ **Example:**
1166
+ ```tsx
1167
+ function ItemsList() {
1168
+ const [archivedCount, setArchivedCount] = useState(0);
1169
+
1170
+ // Listen to all child items being archived
1171
+ useChildCommandHook("App/Item", "App/Item/ToggleArchive", (result, args) => {
1172
+ if (result.archived) {
1173
+ setArchivedCount(prev => prev + 1);
1174
+ analytics.track("item_archived", { itemId: args.id });
1175
+ } else {
1176
+ setArchivedCount(prev => prev - 1);
1177
+ }
1178
+ });
1179
+
1180
+ // Listen to child items being deleted with filtering
1181
+ useChildCommandHook(
1182
+ "App/Item",
1183
+ "App/Item/DeleteItem",
1184
+ (result, args) => {
1185
+ console.log(`Item ${args.id} deleted`);
1186
+ },
1187
+ {
1188
+ filter: (cmd) => cmd.args.priority === "high",
1189
+ ignoreDuplicate: true
1190
+ }
1191
+ );
1192
+
1193
+ return (
1194
+ <div>
1195
+ <h2>Archived: {archivedCount}</h2>
1196
+ {items.map(item => (
1197
+ <ItemComponent key={item.id} item={item} />
1198
+ ))}
1199
+ </div>
1200
+ );
1201
+ }
1202
+ ```
1203
+
1204
+ #### useChildCommandRunner(childComponentName, selector)
1205
+
1206
+ Run commands on child components by key/selector.
1207
+
1208
+ ```ts
1209
+ import { useChildCommandRunner } from "@zenflux/react-commander/hooks";
1210
+
1211
+ function useChildCommandRunner(
1212
+ childComponentName: string,
1213
+ selector: (ctx: DCommandSingleComponentContext) => string
1214
+ ): (key: string, commandName: string, args: DCommandArgs) => boolean
1215
+ ```
1216
+
1217
+ **Example:**
1218
+ ```tsx
1219
+ function ItemsList() {
1220
+ const [selectedItems, setSelectedItems] = useState<string[]>([]);
1221
+
1222
+ // Runner to target specific items by ID
1223
+ const runOnItem = useChildCommandRunner("App/Item", (ctx) => ctx.props.itemId);
1224
+
1225
+ const handleSelectAll = () => {
1226
+ items.forEach(item => {
1227
+ const success = runOnItem(item.id, "App/Item/Select", { selected: true });
1228
+ if (success) {
1229
+ setSelectedItems(prev => [...prev, item.id]);
1230
+ }
1231
+ });
1232
+ };
1233
+
1234
+ const handleClearSelection = () => {
1235
+ selectedItems.forEach(itemId => {
1236
+ runOnItem(itemId, "App/Item/Select", { selected: false });
1237
+ });
1238
+ setSelectedItems([]);
1239
+ };
1240
+
1241
+ const handleArchiveSelected = () => {
1242
+ selectedItems.forEach(itemId => {
1243
+ runOnItem(itemId, "App/Item/ToggleArchive", { archived: true });
1244
+ });
1245
+ };
1246
+
1247
+ return (
1248
+ <div>
1249
+ <div>
1250
+ <button onClick={handleSelectAll}>Select All</button>
1251
+ <button onClick={handleClearSelection}>Clear Selection</button>
1252
+ <button onClick={handleArchiveSelected}>
1253
+ Archive Selected ({selectedItems.length})
1254
+ </button>
1255
+ </div>
1256
+ {items.map(item => (
1257
+ <ItemComponent key={item.id} item={item} />
1258
+ ))}
1259
+ </div>
1260
+ );
1261
+ }
1262
+ ```
1263
+
1264
+ ### Query System
1265
+
1266
+ #### QueryClient
1267
+
1268
+ Main client for query operations.
1269
+
1270
+ ```ts
1271
+ import { QueryClient } from "@zenflux/react-commander/query/client";
1272
+
1273
+ class QueryClient {
1274
+ constructor(baseUrl: string)
1275
+ registerModule<TResource extends object>(module: DQueryModuleBaseStatic<TResource>): void
1276
+ fetch<T>(method: string, path: string, data?: any, responseHandler?: (response: Response) => Promise<T>): Promise<T>
1277
+ get cache(): QueryCache
1278
+ get Component(): typeof QueryComponent
1279
+ }
1280
+ ```
1281
+
1282
+ #### QueryModuleBase<TResource>
1283
+
1284
+ Base class for query modules.
1285
+
1286
+ ```ts
1287
+ import { QueryModuleBase } from "@zenflux/react-commander/query/module-base";
1288
+
1289
+ abstract class QueryModuleBase<TResource extends object = object> {
1290
+ static getName(): string
1291
+ protected getResourceName(): string
1292
+ protected registerEndpoints(): void
1293
+ protected defineEndpoint<TApi, TData>(name: string, cfg: { method: string; path: string; prepareData?: (api: TApi) => TData }): void
1294
+ protected register(method: string, name: string, route: string | { path: string }): void
1295
+ request<TResult>(name: string, args?: Record<string, unknown>): Promise<TResult>
1296
+ getData<TData>(element: DCommandFunctionComponent, args?: Record<string, unknown>): Promise<TData>
1297
+ }
1298
+ ```
1299
+
1300
+ #### QueryListModuleBase<TEntity>
1301
+
1302
+ Specialized for list operations.
1303
+
1304
+ ```ts
1305
+ import { QueryListModuleBase } from "@zenflux/react-commander/query/list-module-base";
1306
+
1307
+ abstract class QueryListModuleBase<TEntity extends object> extends QueryModuleBase<TEntity[]> {
1308
+ // Inherits all QueryModuleBase methods
1309
+ // Provides list-specific cache keys and helpers
1310
+ }
1311
+ ```
1312
+
1313
+ #### QueryComponent
1314
+
1315
+ Suspense bridge to load module data and inject lifecycle hooks.
1316
+
1317
+ ```ts
1318
+ import { QueryComponent } from "@zenflux/react-commander/query/component";
1319
+
1320
+ class QueryComponent<TData, TProps, TResource, TState> extends React.PureComponent<DQueryComponentProps<TData, TProps, TResource, TState>>
1321
+ ```
1322
+
1323
+ #### QueryProvider
1324
+
1325
+ Provides query client to descendants.
1326
+
1327
+ ```ts
1328
+ import { QueryProvider, useQueryClient, getQueryClient, getQueryModule } from "@zenflux/react-commander/query/provider";
1329
+
1330
+ function QueryProvider(props: { client: QueryClient; children: React.ReactNode }): JSX.Element
1331
+ function useQueryClient(): QueryClient
1332
+ function getQueryClient(): QueryClient
1333
+ function getQueryModule<TResource extends object>(module: DQueryModuleBaseStatic<TResource>): QueryModuleBase<TResource>
1334
+ ```
1335
+
1336
+ ### Query Utilities
1337
+
1338
+ #### queryCreateAutoSaveManager
1339
+
1340
+ Creates an autosave manager with debouncing.
1341
+
1342
+ ```ts
1343
+ import { queryCreateAutoSaveManager } from "@zenflux/react-commander/query/auto-save-manager";
1344
+
1345
+ function queryCreateAutoSaveManager<TState extends object, TSave extends QuerySaveInput>(
1346
+ options: QueryCreateAutoSaveManagerOptions<TState, TSave>
1347
+ ): QueryAutoSaveManager<TState, TSave>
1348
+ ```
1349
+
1350
+ #### queryDiffById
1351
+
1352
+ Computes differences between two lists by ID.
1353
+
1354
+ ```ts
1355
+ import { queryDiffById } from "@zenflux/react-commander/query/list-diff";
1356
+
1357
+ function queryDiffById<T>(prev: T[], curr: T[], getId: (t: T) => string): { added: T[]; removed: T[] }
1358
+ ```
1359
+
1360
+ #### queryCreateMemoryCache
1361
+
1362
+ Creates a memory-based cache.
1363
+
1364
+ ```ts
1365
+ import { queryCreateMemoryCache } from "@zenflux/react-commander/query/cache";
1366
+
1367
+ function queryCreateMemoryCache(): QueryCache
1368
+ ```
1369
+
1370
+ ### Type Definitions
1371
+
1372
+ #### DCommandFunctionComponent<TProps, TState>
1373
+
1374
+ Type for command-enabled functional components.
1375
+
1376
+ ```ts
1377
+ import type { DCommandFunctionComponent } from "@zenflux/react-commander/definitions";
1378
+
1379
+ interface DCommandFunctionComponent<TProps = any, TState = undefined> extends React.FC<TProps> {
1380
+ (props: TProps, state?: TState): React.ReactNode
1381
+ getName?(): string
1382
+ }
1383
+ ```
1384
+
1385
+ #### DCommandSingleComponentContext
1386
+
1387
+ Context for a single component instance.
1388
+
1389
+ ```ts
1390
+ import type { DCommandSingleComponentContext } from "@zenflux/react-commander/definitions";
1391
+
1392
+ interface DCommandSingleCompzeonentContext {
1393
+ commands: { [commandName: string]: CommandBase }
1394
+ componentNameUnique: string
1395
+ componentName: string
1396
+ key: string
1397
+ props: any
1398
+ isMounted(): boolean
1399
+ getState<TState>(): TState
1400
+ setState<TState>(state: TState | ((prev: TState) => TState), callback?: (state: TState) => void): Promise<void>
1401
+ getComponentContext(): any
1402
+ emitter: EventEmitter
1403
+ lifecycleHandlers: any
1404
+ }
1405
+ ```
1406
+
1407
+ #### DCommandArgs
1408
+
1409
+ Type for command arguments.
1410
+
1411
+ ```ts
1412
+
1413
+ import type { DCommandArgs } from "@zenflux/react-commander/definitions";
1414
+
1415
+ type DCommandArgs = {
1416
+ [key: string]: unknown
1417
+ }
1418
+ ```
1419
+
1420
+ ## License
1421
+
1422
+ MIT License - see [LICENSE](LICENSE) for details.