@object-ui/core 3.0.2 → 3.1.0

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 (79) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +6 -0
  3. package/dist/actions/ActionEngine.d.ts +98 -0
  4. package/dist/actions/ActionEngine.js +222 -0
  5. package/dist/actions/UndoManager.d.ts +80 -0
  6. package/dist/actions/UndoManager.js +193 -0
  7. package/dist/actions/index.d.ts +2 -0
  8. package/dist/actions/index.js +2 -0
  9. package/dist/adapters/ApiDataSource.d.ts +2 -1
  10. package/dist/adapters/ApiDataSource.js +25 -0
  11. package/dist/adapters/ValueDataSource.d.ts +2 -1
  12. package/dist/adapters/ValueDataSource.js +99 -3
  13. package/dist/data-scope/ViewDataProvider.d.ts +143 -0
  14. package/dist/data-scope/ViewDataProvider.js +153 -0
  15. package/dist/data-scope/index.d.ts +1 -0
  16. package/dist/data-scope/index.js +1 -0
  17. package/dist/evaluator/ExpressionEvaluator.d.ts +7 -0
  18. package/dist/evaluator/ExpressionEvaluator.js +19 -0
  19. package/dist/index.d.ts +5 -0
  20. package/dist/index.js +5 -0
  21. package/dist/protocols/DndProtocol.d.ts +84 -0
  22. package/dist/protocols/DndProtocol.js +113 -0
  23. package/dist/protocols/KeyboardProtocol.d.ts +93 -0
  24. package/dist/protocols/KeyboardProtocol.js +108 -0
  25. package/dist/protocols/NotificationProtocol.d.ts +71 -0
  26. package/dist/protocols/NotificationProtocol.js +99 -0
  27. package/dist/protocols/ResponsiveProtocol.d.ts +73 -0
  28. package/dist/protocols/ResponsiveProtocol.js +158 -0
  29. package/dist/protocols/SharingProtocol.d.ts +71 -0
  30. package/dist/protocols/SharingProtocol.js +124 -0
  31. package/dist/protocols/index.d.ts +12 -0
  32. package/dist/protocols/index.js +12 -0
  33. package/dist/utils/debug-collector.d.ts +59 -0
  34. package/dist/utils/debug-collector.js +73 -0
  35. package/dist/utils/debug.d.ts +37 -2
  36. package/dist/utils/debug.js +62 -3
  37. package/dist/utils/expand-fields.d.ts +40 -0
  38. package/dist/utils/expand-fields.js +68 -0
  39. package/dist/utils/extract-records.d.ts +16 -0
  40. package/dist/utils/extract-records.js +32 -0
  41. package/dist/utils/normalize-quick-filter.d.ts +29 -0
  42. package/dist/utils/normalize-quick-filter.js +66 -0
  43. package/package.json +3 -3
  44. package/src/__tests__/protocols/DndProtocol.test.ts +186 -0
  45. package/src/__tests__/protocols/KeyboardProtocol.test.ts +177 -0
  46. package/src/__tests__/protocols/NotificationProtocol.test.ts +142 -0
  47. package/src/__tests__/protocols/ResponsiveProtocol.test.ts +176 -0
  48. package/src/__tests__/protocols/SharingProtocol.test.ts +188 -0
  49. package/src/actions/ActionEngine.ts +268 -0
  50. package/src/actions/UndoManager.ts +215 -0
  51. package/src/actions/__tests__/ActionEngine.test.ts +206 -0
  52. package/src/actions/__tests__/UndoManager.test.ts +320 -0
  53. package/src/actions/index.ts +2 -0
  54. package/src/adapters/ApiDataSource.ts +27 -0
  55. package/src/adapters/ValueDataSource.ts +109 -3
  56. package/src/adapters/__tests__/ValueDataSource.test.ts +147 -0
  57. package/src/data-scope/ViewDataProvider.ts +282 -0
  58. package/src/data-scope/__tests__/ViewDataProvider.test.ts +270 -0
  59. package/src/data-scope/index.ts +8 -0
  60. package/src/evaluator/ExpressionEvaluator.ts +22 -0
  61. package/src/evaluator/__tests__/ExpressionEvaluator.test.ts +31 -1
  62. package/src/index.ts +5 -0
  63. package/src/protocols/DndProtocol.ts +184 -0
  64. package/src/protocols/KeyboardProtocol.ts +185 -0
  65. package/src/protocols/NotificationProtocol.ts +159 -0
  66. package/src/protocols/ResponsiveProtocol.ts +210 -0
  67. package/src/protocols/SharingProtocol.ts +185 -0
  68. package/src/{index.test.ts → protocols/index.ts} +5 -7
  69. package/src/utils/__tests__/debug-collector.test.ts +102 -0
  70. package/src/utils/__tests__/debug.test.ts +52 -1
  71. package/src/utils/__tests__/expand-fields.test.ts +120 -0
  72. package/src/utils/__tests__/extract-records.test.ts +50 -0
  73. package/src/utils/__tests__/normalize-quick-filter.test.ts +123 -0
  74. package/src/utils/debug-collector.ts +100 -0
  75. package/src/utils/debug.ts +87 -6
  76. package/src/utils/expand-fields.ts +76 -0
  77. package/src/utils/extract-records.ts +33 -0
  78. package/src/utils/normalize-quick-filter.ts +78 -0
  79. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,268 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ /**
10
+ * @object-ui/core - Action Engine
11
+ *
12
+ * Declarative action dispatch engine. Manages action registration,
13
+ * event-to-action mapping, location-based filtering, keyboard shortcuts,
14
+ * and bulk operation support.
15
+ *
16
+ * Replaces callback-based patterns with a schema-driven pipeline:
17
+ * ActionSchema[] → ActionEngine → ActionRunner → ActionResult
18
+ */
19
+
20
+ import { ActionRunner, type ActionDef, type ActionContext, type ActionResult } from './ActionRunner';
21
+
22
+ /** Action location types (from @objectstack/spec) */
23
+ export type ActionLocation =
24
+ | 'list_toolbar'
25
+ | 'list_item'
26
+ | 'record_header'
27
+ | 'record_more'
28
+ | 'record_related'
29
+ | 'global_nav';
30
+
31
+ /** Registered action with metadata */
32
+ export interface RegisteredAction {
33
+ action: ActionDef;
34
+ locations: ActionLocation[];
35
+ /** Keyboard shortcut (e.g., 'ctrl+s', 'meta+k') */
36
+ shortcut?: string;
37
+ /** Whether this action supports bulk operations */
38
+ bulkEnabled?: boolean;
39
+ /** Priority for ordering (lower = first) */
40
+ priority?: number;
41
+ }
42
+
43
+ /** Event-to-action mapping */
44
+ export interface ActionMapping {
45
+ /** Event name (e.g., 'row:click', 'toolbar:save', 'keyboard:ctrl+s') */
46
+ event: string;
47
+ /** Action name to execute */
48
+ actionName: string;
49
+ /** Optional condition expression */
50
+ condition?: string;
51
+ }
52
+
53
+ /** Keyboard shortcut handler */
54
+ export interface ShortcutBinding {
55
+ /** Key combination (e.g., 'ctrl+s', 'meta+k', 'shift+n') */
56
+ keys: string;
57
+ /** Action name to trigger */
58
+ actionName: string;
59
+ }
60
+
61
+ /** Normalize a shortcut string for comparison (lowercase, trimmed, sorted parts) */
62
+ function normalizeShortcut(keys: string): string {
63
+ return keys.toLowerCase().split('+').map(k => k.trim()).sort().join('+');
64
+ }
65
+
66
+ export class ActionEngine {
67
+ private actions = new Map<string, RegisteredAction>();
68
+ private mappings: ActionMapping[] = [];
69
+ private shortcuts: ShortcutBinding[] = [];
70
+ private normalizedShortcutMap = new Map<string, string>();
71
+ private runner: ActionRunner;
72
+
73
+ constructor(context: ActionContext = {}) {
74
+ this.runner = new ActionRunner(context);
75
+ }
76
+
77
+ /** Get the underlying ActionRunner for handler configuration */
78
+ getRunner(): ActionRunner {
79
+ return this.runner;
80
+ }
81
+
82
+ /** Register a single action */
83
+ registerAction(action: ActionDef, options?: {
84
+ locations?: ActionLocation[];
85
+ shortcut?: string;
86
+ bulkEnabled?: boolean;
87
+ priority?: number;
88
+ }): void {
89
+ const name = action.name || action.type || '';
90
+ if (!name) throw new Error('Action must have a name or type');
91
+
92
+ this.actions.set(name, {
93
+ action,
94
+ locations: options?.locations || [],
95
+ shortcut: options?.shortcut,
96
+ bulkEnabled: options?.bulkEnabled ?? false,
97
+ priority: options?.priority ?? 100,
98
+ });
99
+
100
+ // Auto-register keyboard shortcut
101
+ if (options?.shortcut) {
102
+ this.shortcuts.push({ keys: options.shortcut, actionName: name });
103
+ this.normalizedShortcutMap.set(normalizeShortcut(options.shortcut), name);
104
+ }
105
+ }
106
+
107
+ /** Register multiple actions from an ActionSchema array */
108
+ registerActions(actions: ActionDef[]): void {
109
+ for (const action of actions) {
110
+ this.registerAction(action, {
111
+ locations: (action as any).locations,
112
+ shortcut: (action as any).shortcut,
113
+ bulkEnabled: (action as any).bulkEnabled,
114
+ });
115
+ }
116
+ }
117
+
118
+ /** Unregister an action by name */
119
+ unregisterAction(name: string): void {
120
+ const registered = this.actions.get(name);
121
+ if (registered?.shortcut) {
122
+ this.normalizedShortcutMap.delete(normalizeShortcut(registered.shortcut));
123
+ }
124
+ this.actions.delete(name);
125
+ this.shortcuts = this.shortcuts.filter(s => s.actionName !== name);
126
+ this.mappings = this.mappings.filter(m => m.actionName !== name);
127
+ }
128
+
129
+ /** Add an event-to-action mapping */
130
+ addMapping(mapping: ActionMapping): void {
131
+ this.mappings.push(mapping);
132
+ }
133
+
134
+ /** Get actions available at a specific location, sorted by priority */
135
+ getActionsForLocation(location: ActionLocation): ActionDef[] {
136
+ return Array.from(this.actions.values())
137
+ .filter(ra => ra.locations.includes(location))
138
+ .sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100))
139
+ .map(ra => ra.action);
140
+ }
141
+
142
+ /** Get actions that support bulk operations */
143
+ getBulkActions(): ActionDef[] {
144
+ return Array.from(this.actions.values())
145
+ .filter(ra => ra.bulkEnabled)
146
+ .sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100))
147
+ .map(ra => ra.action);
148
+ }
149
+
150
+ /** Get all registered keyboard shortcuts */
151
+ getShortcuts(): ShortcutBinding[] {
152
+ return [...this.shortcuts];
153
+ }
154
+
155
+ /** Get a registered action by name */
156
+ getAction(name: string): ActionDef | undefined {
157
+ return this.actions.get(name)?.action;
158
+ }
159
+
160
+ /** Execute an action by name */
161
+ async executeAction(name: string, contextOverride?: Partial<ActionContext>): Promise<ActionResult> {
162
+ const registered = this.actions.get(name);
163
+ if (!registered) {
164
+ return { success: false, error: `Action not found: ${name}` };
165
+ }
166
+
167
+ if (contextOverride) {
168
+ this.runner.updateContext(contextOverride);
169
+ }
170
+
171
+ return this.runner.execute(registered.action);
172
+ }
173
+
174
+ /** Dispatch an event — finds mapped actions and executes them */
175
+ async dispatch(event: string, contextOverride?: Partial<ActionContext>): Promise<ActionResult[]> {
176
+ const matchingMappings = this.mappings.filter(m => m.event === event);
177
+
178
+ if (matchingMappings.length === 0) {
179
+ return [];
180
+ }
181
+
182
+ const results: ActionResult[] = [];
183
+ for (const mapping of matchingMappings) {
184
+ // Check condition if present
185
+ if (mapping.condition) {
186
+ const evaluator = this.runner.getEvaluator();
187
+ const shouldRun = evaluator.evaluateCondition(mapping.condition);
188
+ if (!shouldRun) continue;
189
+ }
190
+
191
+ const result = await this.executeAction(mapping.actionName, contextOverride);
192
+ results.push(result);
193
+ }
194
+
195
+ return results;
196
+ }
197
+
198
+ /** Handle a keyboard shortcut event — returns true if handled */
199
+ async handleShortcut(keys: string, contextOverride?: Partial<ActionContext>): Promise<ActionResult | null> {
200
+ const actionName = this.normalizedShortcutMap.get(normalizeShortcut(keys));
201
+ if (!actionName) return null;
202
+
203
+ return this.executeAction(actionName, contextOverride);
204
+ }
205
+
206
+ /** Execute a bulk operation on multiple records */
207
+ async executeBulk(
208
+ actionName: string,
209
+ records: Record<string, any>[],
210
+ options?: { parallel?: boolean; continueOnError?: boolean }
211
+ ): Promise<{ total: number; succeeded: number; failed: number; results: ActionResult[] }> {
212
+ const registered = this.actions.get(actionName);
213
+ if (!registered) {
214
+ return { total: 0, succeeded: 0, failed: 0, results: [{ success: false, error: `Action not found: ${actionName}` }] };
215
+ }
216
+ if (!registered.bulkEnabled) {
217
+ return { total: 0, succeeded: 0, failed: 0, results: [{ success: false, error: `Action ${actionName} does not support bulk operations` }] };
218
+ }
219
+
220
+ const results: ActionResult[] = [];
221
+ let succeeded = 0;
222
+ let failed = 0;
223
+
224
+ if (options?.parallel) {
225
+ const promises = records.map(record => {
226
+ this.runner.updateContext({ record, selectedRecords: records });
227
+ return this.runner.execute(registered.action);
228
+ });
229
+ const settled = await Promise.allSettled(promises);
230
+ for (const r of settled) {
231
+ if (r.status === 'fulfilled') {
232
+ results.push(r.value);
233
+ if (r.value.success) succeeded++;
234
+ else failed++;
235
+ } else {
236
+ results.push({ success: false, error: r.reason?.message || 'Unknown error' });
237
+ failed++;
238
+ }
239
+ }
240
+ } else {
241
+ for (const record of records) {
242
+ this.runner.updateContext({ record, selectedRecords: records });
243
+ const result = await this.runner.execute(registered.action);
244
+ results.push(result);
245
+ if (result.success) succeeded++;
246
+ else {
247
+ failed++;
248
+ if (!options?.continueOnError) break;
249
+ }
250
+ }
251
+ }
252
+
253
+ return { total: records.length, succeeded, failed, results };
254
+ }
255
+
256
+ /** Update the action context */
257
+ updateContext(context: Partial<ActionContext>): void {
258
+ this.runner.updateContext(context);
259
+ }
260
+
261
+ /** Clear all registered actions and mappings */
262
+ clear(): void {
263
+ this.actions.clear();
264
+ this.mappings = [];
265
+ this.shortcuts = [];
266
+ this.normalizedShortcutMap.clear();
267
+ }
268
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ /**
10
+ * @object-ui/core - Undo Manager
11
+ *
12
+ * Global undo/redo system for CRUD operations. Class-based singleton
13
+ * pattern for use from ActionRunner, React hooks, and standalone contexts.
14
+ * Maintains bounded history stacks with subscriber notifications.
15
+ */
16
+
17
+ /** Represents a single undoable CRUD operation. */
18
+ export interface UndoableOperation {
19
+ id: string;
20
+ type: 'create' | 'update' | 'delete';
21
+ objectName: string;
22
+ recordId: string;
23
+ timestamp: number;
24
+ description: string;
25
+ /** Data needed to undo: for create=recordId, for update=previousData, for delete=fullRecord */
26
+ undoData: Record<string, unknown>;
27
+ /** Data needed to redo: for create=newData, for update=newData, for delete=recordId */
28
+ redoData: Record<string, unknown>;
29
+ }
30
+
31
+ export interface UndoManagerOptions {
32
+ /** Maximum number of operations to retain in history. @default 50 */
33
+ maxHistory?: number;
34
+ }
35
+
36
+ /** Type guard validating the required shape of a persisted UndoableOperation. */
37
+ function isValidOperation(op: unknown): op is UndoableOperation {
38
+ if (typeof op !== 'object' || op === null) return false;
39
+ const o = op as Record<string, unknown>;
40
+ return (
41
+ typeof o.id === 'string' &&
42
+ typeof o.type === 'string' &&
43
+ typeof o.objectName === 'string' &&
44
+ typeof o.recordId === 'string' &&
45
+ typeof o.timestamp === 'number'
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Manages undo/redo stacks for CRUD operations.
51
+ *
52
+ * Designed as a framework-agnostic class so it can be used from
53
+ * ActionRunner, React hooks, or any other consumer.
54
+ */
55
+ export class UndoManager {
56
+ private undoStack: UndoableOperation[] = [];
57
+ private redoStack: UndoableOperation[] = [];
58
+ private readonly maxHistory: number;
59
+ private listeners: Set<() => void> = new Set();
60
+
61
+ constructor(options?: UndoManagerOptions) {
62
+ this.maxHistory = options?.maxHistory ?? 50;
63
+ }
64
+
65
+ /** Record an undoable operation. Clears the redo stack. */
66
+ push(operation: UndoableOperation): void {
67
+ this.undoStack.push(operation);
68
+ if (this.undoStack.length > this.maxHistory) {
69
+ this.undoStack.shift();
70
+ }
71
+ this.redoStack = [];
72
+ this.notify();
73
+ }
74
+
75
+ /** Peek at the next undoable operation without removing it. */
76
+ peekUndo(): UndoableOperation | undefined {
77
+ return this.undoStack[this.undoStack.length - 1];
78
+ }
79
+
80
+ /** Peek at the next redoable operation without removing it. */
81
+ peekRedo(): UndoableOperation | undefined {
82
+ return this.redoStack[this.redoStack.length - 1];
83
+ }
84
+
85
+ /** Pop the last operation from the undo stack and move it to redo. */
86
+ popUndo(): UndoableOperation | undefined {
87
+ const op = this.undoStack.pop();
88
+ if (op) {
89
+ this.redoStack.push(op);
90
+ this.notify();
91
+ }
92
+ return op;
93
+ }
94
+
95
+ /** Pop the last operation from the redo stack and move it to undo. */
96
+ popRedo(): UndoableOperation | undefined {
97
+ const op = this.redoStack.pop();
98
+ if (op) {
99
+ this.undoStack.push(op);
100
+ this.notify();
101
+ }
102
+ return op;
103
+ }
104
+
105
+ /** Clear all undo and redo history. */
106
+ clear(): void {
107
+ this.undoStack = [];
108
+ this.redoStack = [];
109
+ this.notify();
110
+ }
111
+
112
+ get canUndo(): boolean { return this.undoStack.length > 0; }
113
+ get canRedo(): boolean { return this.redoStack.length > 0; }
114
+ get undoCount(): number { return this.undoStack.length; }
115
+ get redoCount(): number { return this.redoStack.length; }
116
+
117
+ /** Subscribe to state changes. Returns an unsubscribe function. */
118
+ subscribe(listener: () => void): () => void {
119
+ this.listeners.add(listener);
120
+ return () => this.listeners.delete(listener);
121
+ }
122
+
123
+ /** Get a shallow copy of the undo history (for developer tools). */
124
+ getHistory(): UndoableOperation[] { return [...this.undoStack]; }
125
+
126
+ /** Get a shallow copy of the redo history (for developer tools). */
127
+ getRedoHistory(): UndoableOperation[] { return [...this.redoStack]; }
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // Batch operations
131
+ // ---------------------------------------------------------------------------
132
+
133
+ /** Push multiple operations as one atomic unit. Clears the redo stack. */
134
+ pushBatch(operations: UndoableOperation[]): void {
135
+ if (operations.length === 0) return;
136
+ this.undoStack.push(...operations);
137
+ // Trim from the front if we exceed maxHistory
138
+ if (this.undoStack.length > this.maxHistory) {
139
+ this.undoStack.splice(0, this.undoStack.length - this.maxHistory);
140
+ }
141
+ this.redoStack = [];
142
+ this.notify();
143
+ }
144
+
145
+ /** Pop `count` operations from the undo stack and move them to redo (LIFO order). */
146
+ popUndoBatch(count: number): UndoableOperation[] {
147
+ const actual = Math.min(count, this.undoStack.length);
148
+ if (actual === 0) return [];
149
+ const ops = this.undoStack.splice(this.undoStack.length - actual, actual);
150
+ // Preserve LIFO order on the redo stack (last undone goes on top)
151
+ this.redoStack.push(...ops);
152
+ this.notify();
153
+ return ops;
154
+ }
155
+
156
+ /** Pop `count` operations from the redo stack and move them to undo (LIFO order). */
157
+ popRedoBatch(count: number): UndoableOperation[] {
158
+ const actual = Math.min(count, this.redoStack.length);
159
+ if (actual === 0) return [];
160
+ const ops = this.redoStack.splice(this.redoStack.length - actual, actual);
161
+ this.undoStack.push(...ops);
162
+ this.notify();
163
+ return ops;
164
+ }
165
+
166
+ // ---------------------------------------------------------------------------
167
+ // Persistence (localStorage)
168
+ // ---------------------------------------------------------------------------
169
+
170
+ private static readonly STORAGE_KEY = 'objectui:undo-history';
171
+
172
+ /** Persist the current undo/redo stacks to localStorage. */
173
+ saveToStorage(): void {
174
+ try {
175
+ const payload = JSON.stringify({
176
+ undoStack: this.undoStack,
177
+ redoStack: this.redoStack,
178
+ });
179
+ localStorage.setItem(UndoManager.STORAGE_KEY, payload);
180
+ } catch {
181
+ // localStorage may be unavailable (SSR, quota exceeded, etc.)
182
+ }
183
+ }
184
+
185
+ /** Restore undo/redo stacks from localStorage (no-op when unavailable). */
186
+ loadFromStorage(): void {
187
+ try {
188
+ if (typeof localStorage === 'undefined') return;
189
+ const raw = localStorage.getItem(UndoManager.STORAGE_KEY);
190
+ if (!raw) return;
191
+ const parsed = JSON.parse(raw) as {
192
+ undoStack?: UndoableOperation[];
193
+ redoStack?: UndoableOperation[];
194
+ };
195
+ if (Array.isArray(parsed.undoStack)) {
196
+ this.undoStack = parsed.undoStack.filter(isValidOperation);
197
+ }
198
+ if (Array.isArray(parsed.redoStack)) {
199
+ this.redoStack = parsed.redoStack.filter(isValidOperation);
200
+ }
201
+ // Enforce maxHistory in case persisted state used a different limit
202
+ if (this.undoStack.length > this.maxHistory) {
203
+ this.undoStack.splice(0, this.undoStack.length - this.maxHistory);
204
+ }
205
+ this.notify();
206
+ } catch {
207
+ // Silently ignore parse errors or missing storage
208
+ }
209
+ }
210
+
211
+ private notify(): void { this.listeners.forEach((fn) => fn()); }
212
+ }
213
+
214
+ /** Global singleton instance. */
215
+ export const globalUndoManager = new UndoManager();
@@ -0,0 +1,206 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { describe, it, expect, beforeEach } from 'vitest';
10
+ import { ActionEngine } from '../ActionEngine';
11
+ import type { ActionDef } from '../ActionRunner';
12
+
13
+ describe('ActionEngine', () => {
14
+ let engine: ActionEngine;
15
+
16
+ beforeEach(() => {
17
+ engine = new ActionEngine({ data: { status: 'active' } });
18
+ });
19
+
20
+ describe('registerAction', () => {
21
+ it('registers an action by name', () => {
22
+ engine.registerAction({ name: 'save', type: 'api', endpoint: '/save' });
23
+ expect(engine.getAction('save')).toBeDefined();
24
+ expect(engine.getAction('save')?.type).toBe('api');
25
+ });
26
+
27
+ it('throws if action has no name or type', () => {
28
+ expect(() => engine.registerAction({} as ActionDef)).toThrow('Action must have a name or type');
29
+ });
30
+
31
+ it('registers with locations', () => {
32
+ engine.registerAction(
33
+ { name: 'delete', type: 'api' },
34
+ { locations: ['record_header', 'list_item'] }
35
+ );
36
+ expect(engine.getActionsForLocation('record_header')).toHaveLength(1);
37
+ expect(engine.getActionsForLocation('list_toolbar')).toHaveLength(0);
38
+ });
39
+
40
+ it('auto-registers keyboard shortcuts', () => {
41
+ engine.registerAction(
42
+ { name: 'save', type: 'api' },
43
+ { shortcut: 'ctrl+s' }
44
+ );
45
+ expect(engine.getShortcuts()).toHaveLength(1);
46
+ expect(engine.getShortcuts()[0].keys).toBe('ctrl+s');
47
+ });
48
+ });
49
+
50
+ describe('registerActions', () => {
51
+ it('registers multiple actions from array', () => {
52
+ engine.registerActions([
53
+ { name: 'save', type: 'api', endpoint: '/save' },
54
+ { name: 'delete', type: 'api', endpoint: '/delete' },
55
+ ]);
56
+ expect(engine.getAction('save')).toBeDefined();
57
+ expect(engine.getAction('delete')).toBeDefined();
58
+ });
59
+ });
60
+
61
+ describe('unregisterAction', () => {
62
+ it('removes action and its shortcuts/mappings', () => {
63
+ engine.registerAction({ name: 'save', type: 'api' }, { shortcut: 'ctrl+s' });
64
+ engine.addMapping({ event: 'toolbar:save', actionName: 'save' });
65
+
66
+ engine.unregisterAction('save');
67
+
68
+ expect(engine.getAction('save')).toBeUndefined();
69
+ expect(engine.getShortcuts()).toHaveLength(0);
70
+ });
71
+ });
72
+
73
+ describe('getActionsForLocation', () => {
74
+ it('returns actions sorted by priority', () => {
75
+ engine.registerAction({ name: 'delete', type: 'api' }, { locations: ['list_toolbar'], priority: 200 });
76
+ engine.registerAction({ name: 'create', type: 'modal' }, { locations: ['list_toolbar'], priority: 10 });
77
+ engine.registerAction({ name: 'export', type: 'api' }, { locations: ['list_toolbar'], priority: 100 });
78
+
79
+ const actions = engine.getActionsForLocation('list_toolbar');
80
+ expect(actions).toHaveLength(3);
81
+ expect(actions[0].name).toBe('create');
82
+ expect(actions[1].name).toBe('export');
83
+ expect(actions[2].name).toBe('delete');
84
+ });
85
+ });
86
+
87
+ describe('getBulkActions', () => {
88
+ it('returns only bulk-enabled actions', () => {
89
+ engine.registerAction({ name: 'delete', type: 'api' }, { bulkEnabled: true });
90
+ engine.registerAction({ name: 'edit', type: 'modal' }, { bulkEnabled: false });
91
+
92
+ expect(engine.getBulkActions()).toHaveLength(1);
93
+ expect(engine.getBulkActions()[0].name).toBe('delete');
94
+ });
95
+ });
96
+
97
+ describe('dispatch', () => {
98
+ it('executes mapped actions for an event', async () => {
99
+ engine.registerAction({ name: 'log', type: 'script', execute: '"logged"' });
100
+ engine.addMapping({ event: 'row:click', actionName: 'log' });
101
+
102
+ const results = await engine.dispatch('row:click');
103
+ expect(results).toHaveLength(1);
104
+ expect(results[0].success).toBe(true);
105
+ });
106
+
107
+ it('returns empty array for unmapped events', async () => {
108
+ const results = await engine.dispatch('unknown:event');
109
+ expect(results).toEqual([]);
110
+ });
111
+
112
+ it('skips actions when mapping condition is false', async () => {
113
+ engine = new ActionEngine({ data: { status: 'locked' } });
114
+ engine.registerAction({ name: 'edit', type: 'script', execute: '"edited"' });
115
+ engine.addMapping({
116
+ event: 'row:click',
117
+ actionName: 'edit',
118
+ condition: '${data.status === "active"}'
119
+ });
120
+
121
+ const results = await engine.dispatch('row:click');
122
+ expect(results).toHaveLength(0);
123
+ });
124
+ });
125
+
126
+ describe('handleShortcut', () => {
127
+ it('executes action for matching shortcut', async () => {
128
+ engine.registerAction(
129
+ { name: 'save', type: 'script', execute: '"saved"' },
130
+ { shortcut: 'ctrl+s' }
131
+ );
132
+
133
+ const result = await engine.handleShortcut('ctrl+s');
134
+ expect(result).not.toBeNull();
135
+ expect(result?.success).toBe(true);
136
+ });
137
+
138
+ it('normalizes shortcut key order', async () => {
139
+ engine.registerAction(
140
+ { name: 'save', type: 'script', execute: '"saved"' },
141
+ { shortcut: 'ctrl+shift+s' }
142
+ );
143
+
144
+ // Different order should still match
145
+ const result = await engine.handleShortcut('shift+ctrl+s');
146
+ expect(result).not.toBeNull();
147
+ expect(result?.success).toBe(true);
148
+ });
149
+
150
+ it('returns null for unregistered shortcut', async () => {
151
+ const result = await engine.handleShortcut('ctrl+z');
152
+ expect(result).toBeNull();
153
+ });
154
+ });
155
+
156
+ describe('executeBulk', () => {
157
+ it('executes action on multiple records sequentially', async () => {
158
+ engine.registerAction(
159
+ { name: 'approve', type: 'script', execute: '"approved"' },
160
+ { bulkEnabled: true }
161
+ );
162
+
163
+ const result = await engine.executeBulk('approve', [
164
+ { id: '1', name: 'Record 1' },
165
+ { id: '2', name: 'Record 2' },
166
+ ]);
167
+
168
+ expect(result.total).toBe(2);
169
+ expect(result.succeeded).toBe(2);
170
+ expect(result.failed).toBe(0);
171
+ });
172
+
173
+ it('fails if action is not bulk-enabled', async () => {
174
+ engine.registerAction({ name: 'edit', type: 'modal' }, { bulkEnabled: false });
175
+
176
+ const result = await engine.executeBulk('edit', [{ id: '1' }]);
177
+ expect(result.results[0].success).toBe(false);
178
+ expect(result.results[0].error).toContain('does not support bulk');
179
+ });
180
+
181
+ it('fails if action is not found', async () => {
182
+ const result = await engine.executeBulk('nonexistent', [{ id: '1' }]);
183
+ expect(result.results[0].success).toBe(false);
184
+ });
185
+ });
186
+
187
+ describe('executeAction', () => {
188
+ it('returns error for unknown action', async () => {
189
+ const result = await engine.executeAction('nonexistent');
190
+ expect(result.success).toBe(false);
191
+ expect(result.error).toContain('Action not found');
192
+ });
193
+ });
194
+
195
+ describe('clear', () => {
196
+ it('removes all actions, mappings, and shortcuts', () => {
197
+ engine.registerAction({ name: 'save', type: 'api' }, { shortcut: 'ctrl+s' });
198
+ engine.addMapping({ event: 'test', actionName: 'save' });
199
+
200
+ engine.clear();
201
+
202
+ expect(engine.getAction('save')).toBeUndefined();
203
+ expect(engine.getShortcuts()).toHaveLength(0);
204
+ });
205
+ });
206
+ });