@alwatr/action 9.25.0 → 9.27.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.
@@ -0,0 +1,388 @@
1
+ import {createLogger} from '@alwatr/logger';
2
+ import {createChannelSignal} from '@alwatr/signal';
3
+ import type {SubscribeResult} from '@alwatr/signal';
4
+ import type {Awaitable, VoidFunc} from '@alwatr/type-helper';
5
+
6
+ import type {Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver} from './type.js';
7
+
8
+ /**
9
+ * Parsed representation of an action attribute descriptor.
10
+ * @internal
11
+ */
12
+ interface ActionDescriptor {
13
+ readonly modifiers: ReadonlySet<string>;
14
+ readonly actionId: string;
15
+ readonly payload: string | undefined;
16
+ }
17
+
18
+ /**
19
+ * Regex parser for the `on-<eventType>` attribute syntax.
20
+ * Syntax: `actionId[:payload][; modifier1,modifier2,...]`
21
+ */
22
+ const syntaxRegex = /^(ui_[a-z0-9_-]+)(?::([^;]+))?(?:;\s*([a-z0-9_,-]+))?$/;
23
+
24
+ /**
25
+ * Service to manage declarative DOM actions, programmatic dispatch,
26
+ * modifiers, payload resolvers, and global event delegation.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import {ActionService} from '@alwatr/action';
31
+ *
32
+ * const customActionService = new ActionService();
33
+ * ```
34
+ */
35
+ export class ActionService {
36
+ /**
37
+ * Default DOM event types that cover the vast majority of interactive elements.
38
+ */
39
+ static readonly DEFAULT_DELEGATED_EVENTS: readonly string[] = ['click', 'submit', 'input', 'change'];
40
+
41
+ protected readonly logger_ = createLogger('action-service');
42
+
43
+ /**
44
+ * Internal ChannelSignal used for routing dispatched actions.
45
+ * @protected
46
+ */
47
+ protected readonly internalChannel_ = createChannelSignal<Record<string, Action>>({name: 'action-service'});
48
+
49
+ /**
50
+ * Registry mapping custom modifiers to their handlers.
51
+ * @protected
52
+ */
53
+ protected readonly modifierRegistry_ = new Map<string, ModifierHandler>();
54
+
55
+ /**
56
+ * Registry mapping custom payload resolvers to their functions.
57
+ * @protected
58
+ */
59
+ protected readonly payloadRegistry_ = new Map<string, PayloadResolver>();
60
+
61
+ /**
62
+ * Cache of parsed action descriptors to prevent redundant regex evaluation.
63
+ * @protected
64
+ */
65
+ protected readonly descriptorCache_ = new Map<string, ActionDescriptor | null>();
66
+
67
+ /**
68
+ * Tracked event types currently delegated to `document.body`.
69
+ * @protected
70
+ */
71
+ protected readonly delegatedEventTypes_ = new Set<string>();
72
+
73
+ /**
74
+ * Bound delegation handler for add/removeEventListener.
75
+ * @private
76
+ */
77
+ private readonly handleDelegatedEventBound__ = this.handleDelegatedEvent_.bind(this);
78
+
79
+ constructor() {
80
+ this.logger_.logMethod?.('constructor');
81
+ this.registerDefaultModifiersAndResolvers__();
82
+ }
83
+
84
+ /**
85
+ * Subscribes to a named action dispatched anywhere in the application.
86
+ *
87
+ * @template K - A key of ActionRecord.
88
+ * @param type - Action type or array of action types to subscribe to.
89
+ * @param handler - Callback invoked with the full Action object.
90
+ * @returns SubscribeResult containing an `unsubscribe` method.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * const sub = actionService.on('ui_open_drawer', (action) => {
95
+ * console.log(action.payload);
96
+ * });
97
+ * sub.unsubscribe();
98
+ * ```
99
+ */
100
+ on<K extends keyof ActionRecord>(type: K | K[], handler: (action: Action<K>) => Awaitable<void>): SubscribeResult {
101
+ this.logger_.logMethodArgs?.('on', {type});
102
+ if (Array.isArray(type)) {
103
+ const typeList = type as K[];
104
+ const unsubscribeList: VoidFunc[] = [];
105
+ for (const type_ of typeList) {
106
+ unsubscribeList.push(
107
+ this.internalChannel_.on(type_, handler as (action: Action) => Awaitable<void>).unsubscribe,
108
+ );
109
+ }
110
+ return {
111
+ unsubscribe: () => {
112
+ this.logger_.logMethod?.('unsubscribe');
113
+ for (const unsubscribe of unsubscribeList) {
114
+ unsubscribe();
115
+ }
116
+ unsubscribeList.length = 0;
117
+ },
118
+ };
119
+ }
120
+ return this.internalChannel_.on(type, handler as (action: Action) => Awaitable<void>);
121
+ }
122
+
123
+ /**
124
+ * Dispatches an action to all subscribers matching `action.type`.
125
+ *
126
+ * @template K - A key of ActionRecord.
127
+ * @param action - Action object containing `type` and `payload`.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * actionService.dispatch({type: 'upload_complete', payload: 'file-123'});
132
+ * ```
133
+ */
134
+ dispatch<K extends keyof ActionRecord>(action: DispatchParam<K>): void {
135
+ this.logger_.logMethodArgs?.('dispatch', action);
136
+ this.internalChannel_.dispatch(action.type, action as Action<K>);
137
+ }
138
+
139
+ /**
140
+ * Registers a custom modifier to enrich or filter actions before dispatch.
141
+ *
142
+ * @param name - Modifier name (lowercase, alphanumeric).
143
+ * @param handler - Function called when modifier is invoked.
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * actionService.registerModifier('trace', (_event, _element, action) => {
148
+ * action.meta ??= {};
149
+ * action.meta['time'] = Date.now();
150
+ * return true;
151
+ * });
152
+ * ```
153
+ */
154
+ registerModifier(name: string, handler: ModifierHandler): void {
155
+ this.logger_.logMethodArgs?.('registerModifier', {name});
156
+ if (this.modifierRegistry_.has(name)) {
157
+ this.logger_.accident('registerModifier', 'modifier_already_registered', {name});
158
+ return;
159
+ }
160
+ this.modifierRegistry_.set(name, handler);
161
+ }
162
+
163
+ /**
164
+ * Registers a custom payload resolver to map DOM state to action payload.
165
+ *
166
+ * @param name - Resolver token (by convention starting with `$`).
167
+ * @param resolver - Function yielding payload from the event and element.
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * actionService.registerPayloadResolver('$data-id', (_event, element) => {
172
+ * return element.dataset.id;
173
+ * });
174
+ * ```
175
+ */
176
+ registerPayloadResolver(name: string, resolver: PayloadResolver): void {
177
+ this.logger_.logMethodArgs?.('registerPayloadResolver', {name});
178
+ if (this.payloadRegistry_.has(name)) {
179
+ this.logger_.accident('registerPayloadResolver', 'payload_resolver_already_registered', {name});
180
+ return;
181
+ }
182
+ this.payloadRegistry_.set(name, resolver);
183
+ }
184
+
185
+ /**
186
+ * Registers global event delegation listeners on `document.body`.
187
+ *
188
+ * @param eventTypes - List of event types to delegate. Defaults to ActionService.DEFAULT_DELEGATED_EVENTS.
189
+ *
190
+ * @example
191
+ * ```ts
192
+ * actionService.setupDelegation();
193
+ * ```
194
+ */
195
+ setupDelegation(eventTypes: readonly string[] = ActionService.DEFAULT_DELEGATED_EVENTS): void {
196
+ this.logger_.logMethodArgs?.('setupDelegation', {eventTypes});
197
+ if (typeof document === 'undefined' || !document.body) {
198
+ this.logger_.incident?.('setupDelegation', 'document_body_not_found');
199
+ return;
200
+ }
201
+
202
+ for (const eventType of eventTypes) {
203
+ if (this.delegatedEventTypes_.has(eventType)) continue;
204
+ this.delegatedEventTypes_.add(eventType);
205
+ document.body.addEventListener(eventType, this.handleDelegatedEventBound__, {capture: true});
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Unregisters all global event delegation listeners.
211
+ *
212
+ * @example
213
+ * ```ts
214
+ * actionService.teardownDelegation();
215
+ * ```
216
+ */
217
+ teardownDelegation(): void {
218
+ this.logger_.logMethod?.('teardownDelegation');
219
+ if (typeof document === 'undefined' || !document.body) {
220
+ return;
221
+ }
222
+ for (const eventType of this.delegatedEventTypes_) {
223
+ document.body.removeEventListener(eventType, this.handleDelegatedEventBound__, {capture: true});
224
+ }
225
+ this.delegatedEventTypes_.clear();
226
+ this.descriptorCache_.clear();
227
+ }
228
+
229
+ /**
230
+ * Parses attribute values into action descriptor, utilizing the internal cache.
231
+ * @protected
232
+ */
233
+ protected parseDescriptor_(attributeValue: string): ActionDescriptor | null {
234
+ this.logger_.logMethodArgs?.('parseDescriptor_', {attributeValue});
235
+
236
+ const cached = this.descriptorCache_.get(attributeValue);
237
+ if (cached !== undefined) return cached;
238
+
239
+ const match = attributeValue.match(syntaxRegex);
240
+ if (!match) {
241
+ this.logger_.accident('parseDescriptor_', 'invalid_syntax', {attributeValue});
242
+ this.descriptorCache_.set(attributeValue, null);
243
+ return null;
244
+ }
245
+
246
+ const actionId = match[1]!;
247
+ const payload = match[2];
248
+ const modifierString = match[3];
249
+ const modifiers = modifierString ? new Set(modifierString.split(',').filter(Boolean)) : new Set<string>();
250
+
251
+ const descriptor: ActionDescriptor = {modifiers, actionId, payload};
252
+ this.descriptorCache_.set(attributeValue, descriptor);
253
+ return descriptor;
254
+ }
255
+
256
+ /**
257
+ * Global event delegation handler.
258
+ * @protected
259
+ */
260
+ protected handleDelegatedEvent_(event: Event): void {
261
+ const eventType = event.type;
262
+ this.logger_.logMethodArgs?.('handleDelegatedEvent_', {eventType});
263
+
264
+ const target = event.target as Element | null;
265
+ if (!target) return;
266
+
267
+ const actionAttrib = `on-${eventType}`;
268
+ const actionElement = target.closest?.(`[${actionAttrib}]`);
269
+ if (!actionElement) return;
270
+
271
+ const attributeValue = actionElement.getAttribute?.(actionAttrib)?.trim();
272
+ if (!attributeValue) {
273
+ this.logger_.accident('handleDelegatedEvent_', 'empty_attribute', {eventType, actionElement});
274
+ return;
275
+ }
276
+
277
+ if (!(actionElement instanceof HTMLElement)) {
278
+ this.logger_.accident('handleDelegatedEvent_', 'target_not_html_element', {eventType, actionElement});
279
+ return;
280
+ }
281
+
282
+ const descriptor = this.parseDescriptor_(attributeValue);
283
+ if (!descriptor) return;
284
+
285
+ this.logger_.logMethodArgs?.('handleDelegatedEvent_.action', {eventType, descriptor});
286
+
287
+ if (descriptor.modifiers.has('once')) {
288
+ actionElement.removeAttribute(actionAttrib);
289
+ }
290
+
291
+ const actionContext = actionElement.closest('[action-context]')?.getAttribute('action-context') ?? undefined;
292
+
293
+ const action: Action = {
294
+ type: descriptor.actionId as keyof ActionRecord,
295
+ context: actionContext,
296
+ payload: descriptor.payload as ActionRecord[keyof ActionRecord],
297
+ };
298
+
299
+ for (const modifier of descriptor.modifiers) {
300
+ if (modifier === 'once') continue;
301
+ const handler = this.modifierRegistry_.get(modifier);
302
+ if (!handler) {
303
+ this.logger_.accident('handleDelegatedEvent_', 'unknown_modifier', {
304
+ eventType,
305
+ modifier,
306
+ attributeValue,
307
+ descriptor,
308
+ });
309
+ return;
310
+ }
311
+ try {
312
+ if (handler(event, actionElement, action) === false) return;
313
+ } catch (error) {
314
+ this.logger_.accident('handleDelegatedEvent_', 'modifier_execution_failed', {
315
+ modifier,
316
+ error,
317
+ });
318
+ return;
319
+ }
320
+ }
321
+
322
+ if (descriptor.payload) {
323
+ const resolver = this.payloadRegistry_.get(descriptor.payload);
324
+ if (resolver) {
325
+ try {
326
+ (action as {payload: unknown}).payload = resolver(event, actionElement);
327
+ } catch (error) {
328
+ this.logger_.accident('handleDelegatedEvent_', 'payload_resolver_failed', {
329
+ resolver: descriptor.payload,
330
+ error,
331
+ });
332
+ return;
333
+ }
334
+ }
335
+ } else {
336
+ (action as {payload: unknown}).payload = undefined;
337
+ }
338
+
339
+ this.internalChannel_.dispatch(action.type, action);
340
+ }
341
+
342
+ /**
343
+ * Registers default modifiers and resolvers.
344
+ * @private
345
+ */
346
+ private registerDefaultModifiersAndResolvers__(): void {
347
+ this.logger_.logMethod?.('registerDefaultModifiersAndResolvers__');
348
+
349
+ // Built-in modifiers
350
+ this.registerModifier('prevent', (event) => {
351
+ event.preventDefault();
352
+ return true;
353
+ });
354
+
355
+ this.registerModifier('validate', (_event, element) => {
356
+ const form = element instanceof HTMLFormElement ? element : element.closest('form');
357
+ if (!form) return false;
358
+ return form.checkValidity();
359
+ });
360
+
361
+ // Built-in resolvers
362
+ this.registerPayloadResolver('$value', (_event, element) => {
363
+ return 'value' in element ? (element as {value: unknown}).value : null;
364
+ });
365
+
366
+ this.registerPayloadResolver('$formdata', (_event, element) => {
367
+ const form = element instanceof HTMLFormElement ? element : element.closest('form');
368
+ return form ? Object.fromEntries(new FormData(form)) : null;
369
+ });
370
+
371
+ this.registerPayloadResolver('$checked', (_event, element) => {
372
+ return 'checked' in element ? (element as HTMLInputElement).checked : null;
373
+ });
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Singleton instance of the ActionService.
379
+ * Ready for immediate use.
380
+ *
381
+ * @example
382
+ * ```ts
383
+ * import {actionService} from '@alwatr/action';
384
+ *
385
+ * actionService.setupDelegation();
386
+ * ```
387
+ */
388
+ export const actionService = new ActionService();
package/src/main.ts CHANGED
@@ -1,100 +1,142 @@
1
+ import type {SubscribeResult} from '@alwatr/signal';
2
+ import type {Awaitable} from '@alwatr/type-helper';
3
+
4
+ import {actionService, ActionService} from './action-service.js';
5
+ import type {Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver} from './type.js';
6
+
7
+ export {actionService, ActionService};
8
+ export type {Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver};
9
+
1
10
  /**
2
- * @alwatr/action Declarative DOM action-dispatch for Unidirectional Data Flow.
11
+ * Default DOM event types that cover the vast majority of interactive elements.
3
12
  *
4
- * Implements the **Alwatr Flux Standard Action (AFSA)** pattern: every action
5
- * flowing through the bus is a single, typed `Action<K>` object carrying
6
- * `type`, `payload`, `context`, and optional `meta`. This replaces the previous
7
- * two-argument `(id, payload)` API with a unified structure that is extensible
8
- * without breaking existing call sites.
9
- *
10
- * ## Activating `on-<eventType>` attributes
13
+ * - `click` buttons, links, checkboxes, custom interactive elements
14
+ * - `submit` form submission
15
+ * - `input` live text input, range sliders
16
+ * - `change` select boxes, checkboxes, radio buttons (fires on commit)
17
+ */
18
+ export const DEFAULT_DELEGATED_EVENTS = ActionService.DEFAULT_DELEGATED_EVENTS;
19
+
20
+ /**
21
+ * Subscribes to a named action dispatched anywhere in the application.
11
22
  *
12
- * Call `setupActionDelegation()` once at bootstrap. A single capture-phase
13
- * listener on `document.body` handles every `on-click`, `on-submit`, etc. element
14
- * including elements added dynamically after bootstrap with O(1) initialization cost.
23
+ * @template K - A key of ActionRecord.
24
+ * @param type - Action type or array of action types to subscribe to.
25
+ * @param handler - Callback invoked with the full Action object.
26
+ * @returns SubscribeResult containing an `unsubscribe` method.
15
27
  *
28
+ * @example
16
29
  * ```ts
17
- * import {setupActionDelegation, onAction} from '@alwatr/action';
30
+ * import {onAction} from '@alwatr/action';
18
31
  *
19
- * setupActionDelegation();
20
- * onAction('ui_open_drawer', (action) => openDrawer(action.payload));
32
+ * const sub = onAction('ui_open_drawer', (action) => {
33
+ * console.log(action.payload);
34
+ * });
35
+ * sub.unsubscribe();
21
36
  * ```
22
37
  *
23
- * ## Attribute syntax
38
+ * @deprecated Use `actionService.on` instead.
39
+ */
40
+ export function onAction<K extends keyof ActionRecord>(
41
+ type: K | K[],
42
+ handler: (action: Action<K>) => Awaitable<void>,
43
+ ): SubscribeResult {
44
+ return actionService.on(type, handler);
45
+ }
46
+
47
+ /**
48
+ * Dispatches an action to all subscribers matching `action.type`.
24
49
  *
25
- * ```
26
- * on-<eventType>="actionId[:payload][; modifier1,modifier2,…]"
27
- * ```
50
+ * @template K - A key of ActionRecord.
51
+ * @param action - Action object containing `type` and `payload`.
28
52
  *
29
- * ```html
30
- * <button on-click="ui_open_drawer:main">Open</button>
31
- * <input on-input="ui_search_query:$value" />
32
- * <form on-submit="ui_submit_form:$formdata; prevent,validate" novalidate>…</form>
33
- * ```
53
+ * @example
54
+ * ```ts
55
+ * import {dispatchAction} from '@alwatr/action';
34
56
  *
35
- * ## Context scoping
57
+ * dispatchAction({type: 'upload_complete', payload: 'file-123'});
58
+ * ```
36
59
  *
37
- * Wrap elements in an `[action-context]` container to scope their actions.
38
- * The delegation handler resolves the nearest ancestor and attaches its value
39
- * to `action.context`:
60
+ * @deprecated Use `actionService.dispatch` instead.
61
+ */
62
+ export function dispatchAction<K extends keyof ActionRecord>(action: DispatchParam<K>): void {
63
+ actionService.dispatch(action);
64
+ }
65
+
66
+ /**
67
+ * Registers global event delegation listeners on `document.body`.
40
68
  *
41
- * ```html
42
- * <section action-context="product-list">
43
- * <button on-click="ui_add_to_cart:42">Add</button>
44
- * </section>
45
- * ```
69
+ * @param eventTypes - List of event types to delegate. Defaults to DEFAULT_DELEGATED_EVENTS.
46
70
  *
71
+ * @example
47
72
  * ```ts
48
- * onAction('ui_add_to_cart', (action) => {
49
- * console.log(action.context); // 'product-list'
50
- * console.log(action.payload); // '42'
51
- * });
52
- * ```
73
+ * import {setupActionDelegation} from '@alwatr/action';
53
74
  *
54
- * ## Programmatic dispatch
75
+ * setupActionDelegation();
76
+ * ```
55
77
  *
56
- * Code-originated actions should not use the `ui_` prefix — that prefix is
57
- * reserved for DOM-originated actions dispatched via HTML attributes.
78
+ * @deprecated Use `actionService.setupDelegation` instead.
79
+ */
80
+ export function setupActionDelegation(eventTypes?: readonly string[]): void {
81
+ actionService.setupDelegation(eventTypes);
82
+ }
83
+
84
+ /**
85
+ * Unregisters all global event delegation listeners.
58
86
  *
87
+ * @example
59
88
  * ```ts
60
- * import {dispatchAction} from '@alwatr/action';
89
+ * import {teardownActionDelegation} from '@alwatr/action';
61
90
  *
62
- * dispatchAction({type: 'navigate', payload: '/dashboard'});
91
+ * teardownActionDelegation();
63
92
  * ```
64
93
  *
65
- * ## Registering typed actions
94
+ * @deprecated Use `actionService.teardownDelegation` instead.
95
+ */
96
+ export function teardownActionDelegation(): void {
97
+ actionService.teardownDelegation();
98
+ }
99
+
100
+ /**
101
+ * Registers a custom modifier to enrich or filter actions before dispatch.
66
102
  *
67
- * Extend `ActionRecord` via declaration merging to get full type safety:
103
+ * @param name - Modifier name (lowercase, alphanumeric).
104
+ * @param handler - Function called when modifier is invoked.
68
105
  *
106
+ * @example
69
107
  * ```ts
70
- * // src/action-record.ts
71
- * declare module '@alwatr/action' {
72
- * interface ActionRecord {
73
- * // UI-originated actions — must start with 'ui_'
74
- * 'ui_open_drawer': string;
75
- * 'ui_add_to_cart': {productId: number; qty: number};
76
- * 'ui_logout': void;
77
- *
78
- * // Code-originated actions — no 'ui_' prefix
79
- * 'upload_complete': string;
80
- * 'auth_expired': void;
81
- * }
82
- * }
108
+ * import {registerModifier} from '@alwatr/action';
109
+ *
110
+ * registerModifier('trace', (_event, _element, action) => {
111
+ * action.meta ??= {};
112
+ * action.meta['time'] = Date.now();
113
+ * return true;
114
+ * });
83
115
  * ```
84
116
  *
85
- * ## Public API
117
+ * @deprecated Use `actionService.registerModifier` instead.
118
+ */
119
+ export function registerModifier(name: string, handler: ModifierHandler): void {
120
+ actionService.registerModifier(name, handler);
121
+ }
122
+
123
+ /**
124
+ * Registers a custom payload resolver to map DOM state to action payload.
125
+ *
126
+ * @param name - Resolver token (by convention starting with `$`).
127
+ * @param resolver - Function yielding payload from the event and element.
86
128
  *
87
- * - `Action` — the AFSA object interface (`type`, `payload`, `context`, `meta`)
88
- * - `ActionRecord` — extend this interface to register typed actions
89
- * - `setupActionDelegation` / `teardownActionDelegation` — global delegation lifecycle
90
- * - `DEFAULT_DELEGATED_EVENTS` — default event types covered by delegation
91
- * - `onAction` / `dispatchAction` — subscribe to and dispatch named actions
92
- * - `registerModifier` / `registerPayloadResolver` — extend the attribute syntax
129
+ * @example
130
+ * ```ts
131
+ * import {registerPayloadResolver} from '@alwatr/action';
93
132
  *
94
- * ## Page identity
133
+ * registerPayloadResolver('$data-id', (_event, element) => {
134
+ * return element.dataset.id;
135
+ * });
136
+ * ```
95
137
  *
96
- * For page-ready signals in SSG/SSR apps, use `@alwatr/page-ready` instead.
138
+ * @deprecated Use `actionService.registerPayloadResolver` instead.
97
139
  */
98
- export * from './delegate.js';
99
- export * from './method.js';
100
- export type * from './type.js';
140
+ export function registerPayloadResolver(name: string, resolver: PayloadResolver): void {
141
+ actionService.registerPayloadResolver(name, resolver);
142
+ }