@alwatr/action 9.26.0 → 9.28.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.
- package/README.md +103 -208
- package/dist/action-service.d.ts +178 -0
- package/dist/action-service.d.ts.map +1 -0
- package/dist/main.d.ts +92 -69
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +3 -3
- package/dist/main.js.map +5 -7
- package/package.json +2 -2
- package/src/action-service.ts +397 -0
- package/src/main.ts +116 -69
- package/dist/delegate.d.ts +0 -126
- package/dist/delegate.d.ts.map +0 -1
- package/dist/lib_.d.ts +0 -24
- package/dist/lib_.d.ts.map +0 -1
- package/dist/method.d.ts +0 -169
- package/dist/method.d.ts.map +0 -1
- package/dist/registry_.d.ts +0 -24
- package/dist/registry_.d.ts.map +0 -1
- package/src/delegate.ts +0 -359
- package/src/lib_.ts +0 -27
- package/src/method.ts +0 -219
- package/src/registry_.ts +0 -109
package/dist/main.d.ts
CHANGED
|
@@ -1,101 +1,124 @@
|
|
|
1
|
+
import type { SubscribeResult } from '@alwatr/signal';
|
|
2
|
+
import type { Awaitable } from '@alwatr/type-helper';
|
|
3
|
+
import { actionService, ActionService } from './action-service.js';
|
|
4
|
+
import type { Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver } from './type.js';
|
|
5
|
+
export { actionService, ActionService };
|
|
6
|
+
export type { Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver };
|
|
1
7
|
/**
|
|
2
|
-
*
|
|
8
|
+
* Default DOM event types that cover the vast majority of interactive elements.
|
|
3
9
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
* - `click` — buttons, links, checkboxes, custom interactive elements
|
|
11
|
+
* - `submit` — form submission
|
|
12
|
+
* - `input` — live text input, range sliders
|
|
13
|
+
* - `change` — select boxes, checkboxes, radio buttons (fires on commit)
|
|
14
|
+
*/
|
|
15
|
+
export declare const DEFAULT_DELEGATED_EVENTS: readonly string[];
|
|
16
|
+
/**
|
|
17
|
+
* Subscribes to a named action dispatched anywhere in the application.
|
|
11
18
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
19
|
+
* @template K - A key of ActionRecord.
|
|
20
|
+
* @param type - Action type or array of action types to subscribe to.
|
|
21
|
+
* @param handler - Callback invoked with the full Action object.
|
|
22
|
+
* @returns SubscribeResult containing an `unsubscribe` method.
|
|
15
23
|
*
|
|
24
|
+
* @example
|
|
16
25
|
* ```ts
|
|
17
|
-
* import {
|
|
26
|
+
* import {onAction} from '@alwatr/action';
|
|
18
27
|
*
|
|
19
|
-
*
|
|
20
|
-
* onAction('ui_open_drawer', (action) =>
|
|
28
|
+
* // Subscribe to multiple action types
|
|
29
|
+
* const sub = onAction(['ui_open_drawer', 'ui_close_drawer'], (action) => {
|
|
30
|
+
* console.log(action.type, action.payload);
|
|
31
|
+
* });
|
|
32
|
+
* sub.unsubscribe();
|
|
21
33
|
* ```
|
|
22
34
|
*
|
|
23
|
-
*
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
*
|
|
35
|
+
* @deprecated Use `actionService.on` instead.
|
|
36
|
+
*/
|
|
37
|
+
export declare function onAction<K extends keyof ActionRecord>(type: K | K[], handler: (action: Action<K>) => Awaitable<void>): SubscribeResult;
|
|
38
|
+
/**
|
|
39
|
+
* Dispatches an action to all subscribers matching `action.type`.
|
|
28
40
|
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* <input on-input="ui_search_query:$value" />
|
|
32
|
-
* <form on-submit="ui_submit_form:$formdata; prevent,validate" novalidate>…</form>
|
|
33
|
-
* ```
|
|
41
|
+
* @template K - A key of ActionRecord.
|
|
42
|
+
* @param action - Action object containing `type` and `payload`.
|
|
34
43
|
*
|
|
35
|
-
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* import {dispatchAction} from '@alwatr/action';
|
|
36
47
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* to `action.context`:
|
|
48
|
+
* // Dispatches a typed action (payload is required)
|
|
49
|
+
* dispatchAction({type: 'upload_complete', payload: 'file-123'});
|
|
40
50
|
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
* <button on-click="ui_add_to_cart:42">Add</button>
|
|
44
|
-
* </section>
|
|
51
|
+
* // Dispatches a void action (payload can be omitted)
|
|
52
|
+
* dispatchAction({type: 'auth_expired'});
|
|
45
53
|
* ```
|
|
46
54
|
*
|
|
55
|
+
* @deprecated Use `actionService.dispatch` instead.
|
|
56
|
+
*/
|
|
57
|
+
export declare function dispatchAction<K extends keyof ActionRecord>(action: DispatchParam<K>): void;
|
|
58
|
+
/**
|
|
59
|
+
* Registers global event delegation listeners on `document.body`.
|
|
60
|
+
*
|
|
61
|
+
* @param eventTypes - List of event types to delegate. Defaults to DEFAULT_DELEGATED_EVENTS.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
47
64
|
* ```ts
|
|
48
|
-
*
|
|
49
|
-
* console.log(action.context); // 'product-list'
|
|
50
|
-
* console.log(action.payload); // '42'
|
|
51
|
-
* });
|
|
52
|
-
* ```
|
|
65
|
+
* import {setupActionDelegation} from '@alwatr/action';
|
|
53
66
|
*
|
|
54
|
-
*
|
|
67
|
+
* setupActionDelegation();
|
|
68
|
+
* ```
|
|
55
69
|
*
|
|
56
|
-
*
|
|
57
|
-
|
|
70
|
+
* @deprecated Use `actionService.setupDelegation` instead.
|
|
71
|
+
*/
|
|
72
|
+
export declare function setupActionDelegation(eventTypes?: readonly string[]): void;
|
|
73
|
+
/**
|
|
74
|
+
* Unregisters all global event delegation listeners.
|
|
58
75
|
*
|
|
76
|
+
* @example
|
|
59
77
|
* ```ts
|
|
60
|
-
* import {
|
|
78
|
+
* import {teardownActionDelegation} from '@alwatr/action';
|
|
61
79
|
*
|
|
62
|
-
*
|
|
80
|
+
* teardownActionDelegation();
|
|
63
81
|
* ```
|
|
64
82
|
*
|
|
65
|
-
*
|
|
83
|
+
* @deprecated Use `actionService.teardownDelegation` instead.
|
|
84
|
+
*/
|
|
85
|
+
export declare function teardownActionDelegation(): void;
|
|
86
|
+
/**
|
|
87
|
+
* Registers a custom modifier to enrich or filter actions before dispatch.
|
|
66
88
|
*
|
|
67
|
-
*
|
|
89
|
+
* @param name - Modifier name (lowercase, alphanumeric).
|
|
90
|
+
* @param handler - Function called when modifier is invoked.
|
|
68
91
|
*
|
|
92
|
+
* @example
|
|
69
93
|
* ```ts
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* // Code-originated actions — no 'ui_' prefix
|
|
79
|
-
* 'upload_complete': string;
|
|
80
|
-
* 'auth_expired': void;
|
|
81
|
-
* }
|
|
82
|
-
* }
|
|
94
|
+
* import {registerModifier} from '@alwatr/action';
|
|
95
|
+
*
|
|
96
|
+
* registerModifier('trace', (_event, _element, action) => {
|
|
97
|
+
* action.meta ??= {};
|
|
98
|
+
* action.meta['time'] = Date.now();
|
|
99
|
+
* return true;
|
|
100
|
+
* });
|
|
83
101
|
* ```
|
|
84
102
|
*
|
|
85
|
-
*
|
|
103
|
+
* @deprecated Use `actionService.registerModifier` instead.
|
|
104
|
+
*/
|
|
105
|
+
export declare function registerModifier(name: string, handler: ModifierHandler): void;
|
|
106
|
+
/**
|
|
107
|
+
* Registers a custom payload resolver to map DOM state to action payload.
|
|
108
|
+
*
|
|
109
|
+
* @param name - Resolver token (by convention starting with `$`).
|
|
110
|
+
* @param resolver - Function yielding payload from the event and element.
|
|
86
111
|
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
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
|
|
112
|
+
* @example
|
|
113
|
+
* ```ts
|
|
114
|
+
* import {registerPayloadResolver} from '@alwatr/action';
|
|
93
115
|
*
|
|
94
|
-
*
|
|
116
|
+
* registerPayloadResolver('$data-id', (_event, element) => {
|
|
117
|
+
* return element.dataset.id;
|
|
118
|
+
* });
|
|
119
|
+
* ```
|
|
95
120
|
*
|
|
96
|
-
*
|
|
121
|
+
* @deprecated Use `actionService.registerPayloadResolver` instead.
|
|
97
122
|
*/
|
|
98
|
-
export
|
|
99
|
-
export * from './method.js';
|
|
100
|
-
export type * from './type.js';
|
|
123
|
+
export declare function registerPayloadResolver(name: string, resolver: PayloadResolver): void;
|
|
101
124
|
//# sourceMappingURL=main.d.ts.map
|
package/dist/main.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,qBAAqB,CAAC;AAEnD,OAAO,EAAC,aAAa,EAAE,aAAa,EAAC,MAAM,qBAAqB,CAAC;AACjE,OAAO,KAAK,EAAC,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,eAAe,EAAC,MAAM,WAAW,CAAC;AAErG,OAAO,EAAC,aAAa,EAAE,aAAa,EAAC,CAAC;AACtC,YAAY,EAAC,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,eAAe,EAAC,CAAC;AAEpF;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,mBAAyC,CAAC;AAE/E;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,YAAY,EACnD,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,EACb,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,IAAI,CAAC,GAC9C,eAAe,CAEjB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,YAAY,EAAE,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,IAAI,CAE3F;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAE1E;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAE/C;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,IAAI,CAE7E;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,GAAG,IAAI,CAErF"}
|
package/dist/main.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/* 📦 @alwatr/action v9.
|
|
2
|
-
import{createLogger as
|
|
1
|
+
/* 📦 @alwatr/action v9.28.0 */
|
|
2
|
+
import{createLogger as k}from"@alwatr/logger";import{createChannelSignal as F}from"@alwatr/signal";var I=/^(ui_[a-z0-9_-]+)(?::([^;]+))?(?:;\s*([a-z0-9_,-]+))?$/;class X{static DEFAULT_DELEGATED_EVENTS=["click","submit","input","change"];logger_=k("action-service");internalChannel_=F({name:"action-service"});modifierRegistry_=new Map;payloadRegistry_=new Map;descriptorCache_=new Map;delegatedEventTypes_=new Set;handleDelegatedEventBound__=this.handleDelegatedEvent_.bind(this);constructor(){this.logger_.logMethod?.("constructor"),this.registerDefaultModifiersAndResolvers__()}on(q,z){if(this.logger_.logMethodArgs?.("on",{type:q}),Array.isArray(q)){let B=q,J=[];for(let G of B)J.push(this.internalChannel_.on(G,z).unsubscribe);return{unsubscribe:()=>{this.logger_.logMethod?.("unsubscribe");for(let G of J)G();J.length=0}}}return this.internalChannel_.on(q,z)}dispatch(q){this.logger_.logMethodArgs?.("dispatch",q),this.internalChannel_.dispatch(q.type,q)}registerModifier(q,z){if(this.logger_.logMethodArgs?.("registerModifier",{name:q}),this.modifierRegistry_.has(q)){this.logger_.accident("registerModifier","modifier_already_registered",{name:q});return}this.modifierRegistry_.set(q,z)}registerPayloadResolver(q,z){if(this.logger_.logMethodArgs?.("registerPayloadResolver",{name:q}),this.payloadRegistry_.has(q)){this.logger_.accident("registerPayloadResolver","payload_resolver_already_registered",{name:q});return}this.payloadRegistry_.set(q,z)}setupDelegation(q=X.DEFAULT_DELEGATED_EVENTS){if(this.logger_.logMethodArgs?.("setupDelegation",{eventTypes:q}),typeof document>"u"||!document.body){this.logger_.incident?.("setupDelegation","document_body_not_found");return}for(let z of q){if(this.delegatedEventTypes_.has(z))continue;this.delegatedEventTypes_.add(z),document.body.addEventListener(z,this.handleDelegatedEventBound__,{capture:!0})}}teardownDelegation(){if(this.logger_.logMethod?.("teardownDelegation"),typeof document>"u"||!document.body)return;for(let q of this.delegatedEventTypes_)document.body.removeEventListener(q,this.handleDelegatedEventBound__,{capture:!0});this.delegatedEventTypes_.clear(),this.descriptorCache_.clear()}parseDescriptor_(q){this.logger_.logMethodArgs?.("parseDescriptor_",{attributeValue:q});let z=this.descriptorCache_.get(q);if(z!==void 0)return z;let B=q.match(I);if(!B)return this.logger_.accident("parseDescriptor_","invalid_syntax",{attributeValue:q}),this.descriptorCache_.set(q,null),null;let J=B[1],G=B[2],Q=B[3],Y={modifiers:Q?new Set(Q.split(",").filter(Boolean)):new Set,actionId:J,payload:G};return this.descriptorCache_.set(q,Y),Y}handleDelegatedEvent_(q){let z=q.type;this.logger_.logMethodArgs?.("handleDelegatedEvent_",{eventType:z});let B=q.target;if(!B)return;let J=`on-${z}`,G=B.closest?.(`[${J}]`);if(!G)return;let Q=G.getAttribute?.(J)?.trim();if(!Q){this.logger_.accident("handleDelegatedEvent_","empty_attribute",{eventType:z,actionElement:G});return}if(!(G instanceof HTMLElement)){this.logger_.accident("handleDelegatedEvent_","target_not_html_element",{eventType:z,actionElement:G});return}let H=this.parseDescriptor_(Q);if(!H)return;if(this.logger_.logMethodArgs?.("handleDelegatedEvent_.action",{eventType:z,descriptor:H}),H.modifiers.has("once"))G.removeAttribute(J);let Y=G.closest("[action-context]")?.getAttribute("action-context")??void 0,W={type:H.actionId,context:Y,payload:H.payload};for(let K of H.modifiers){if(K==="once")continue;let Z=this.modifierRegistry_.get(K);if(!Z){this.logger_.accident("handleDelegatedEvent_","unknown_modifier",{eventType:z,modifier:K,attributeValue:Q,descriptor:H});return}try{if(Z(q,G,W)===!1)return}catch(j){this.logger_.accident("handleDelegatedEvent_","modifier_execution_failed",{modifier:K,error:j});return}}if(H.payload){let K=this.payloadRegistry_.get(H.payload);if(K)try{W.payload=K(q,G)}catch(Z){this.logger_.accident("handleDelegatedEvent_","payload_resolver_failed",{resolver:H.payload,error:Z});return}}else W.payload=void 0;this.internalChannel_.dispatch(W.type,W)}registerDefaultModifiersAndResolvers__(){this.logger_.logMethod?.("registerDefaultModifiersAndResolvers__"),this.registerModifier("prevent",(q)=>{return q.preventDefault(),!0}),this.registerModifier("validate",(q,z)=>{let B=z instanceof HTMLFormElement?z:z.closest("form");if(!B)return!1;return B.checkValidity()}),this.registerPayloadResolver("$value",(q,z)=>{return"value"in z?z.value:null}),this.registerPayloadResolver("$formdata",(q,z)=>{let B=z instanceof HTMLFormElement?z:z.closest("form");return B?Object.fromEntries(new FormData(B)):null}),this.registerPayloadResolver("$checked",(q,z)=>{return"checked"in z?z.checked:null})}}var N=new X;var D=X.DEFAULT_DELEGATED_EVENTS;function _(q,z){return N.on(q,z)}function $(q){N.dispatch(q)}function P(q){N.setupDelegation(q)}function w(){N.teardownDelegation()}function x(q,z){N.registerModifier(q,z)}function L(q,z){N.registerPayloadResolver(q,z)}export{w as teardownActionDelegation,P as setupActionDelegation,L as registerPayloadResolver,x as registerModifier,_ as onAction,$ as dispatchAction,N as actionService,D as DEFAULT_DELEGATED_EVENTS,X as ActionService};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=4D2180C09EEB93E964756E2164756E21
|
|
5
5
|
//# sourceMappingURL=main.js.map
|
package/dist/main.js.map
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/
|
|
3
|
+
"sources": ["../src/action-service.ts", "../src/main.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import {createLogger} from '@alwatr/logger';\nimport {createChannelSignal} from '@alwatr/signal';\nimport type {Action} from './type.js';\n\n/**\n * Module-scoped logger for `@alwatr/action`.\n * Scoped to `'alwatr-action'` so log lines are easy to filter in the console.\n *\n * @internal\n */\nexport const logger_ = createLogger('alwatr-action');\n\n/**\n * The internal action channel — a `ChannelSignal` keyed by action `type`.\n *\n * Each message on this channel is a full `Action` object (AFSA), not just a\n * raw payload. Subscribers registered via `onAction('foo', handler)` receive\n * the entire `Action<'foo'>` so they have access to `context`, `meta`, and\n * `payload` in one place.\n *\n * Uses `ChannelSignal` for O(1) routing: dispatching action `'A'` performs a\n * single `Map.get('A')` lookup and invokes only the handlers registered for\n * that specific type — never handlers for `'B'`, `'C'`, etc.\n *\n * @internal — not part of the public API; use `onAction` / `dispatchAction` instead.\n */\nexport const internalChannel_ = createChannelSignal<Record<string, Action>>({name: 'alwatr-action'});\n",
|
|
6
|
-
"import type {ModifierHandler, PayloadResolver} from './type.js';\n\n/**\n *
|
|
7
|
-
"/**\n * @file delegate.ts\n *\n * Global Event Delegation engine for `@alwatr/action`.\n *\n * ## Why delegation instead of per-element listeners?\n *\n * The classic directive approach attaches one `addEventListener` per element.\n * With 100 buttons on a page, that means 100 listener registrations at boot\n * time — O(N) initialization cost, O(N) memory for listener references, and\n * zero support for elements added after bootstrap.\n *\n * This module implements the global delegation pattern:\n * - A single listener per event type is attached to `document.body` with\n * `capture: true` (so it fires even for non-bubbling events).\n * - When an event fires, the handler walks up the DOM from `event.target`\n * using `closest()` to find the nearest element with an `on-<eventType>`\n * attribute (e.g. `on-click`, `on-submit`).\n * - The nearest `[action-context]` ancestor is also resolved and attached to\n * the `Action` object as `context` — enabling the same action type to be\n * scoped to different UI regions.\n * - Modifiers run with access to the mutable `Action` object so they can\n * enrich `meta` before the action reaches subscribers.\n * - `dispatchAction` is called with the fully assembled `Action` object.\n *\n * ## Complexity\n *\n * | Metric | Per-element listeners | Global delegation |\n * | --------------- | --------------------- | ----------------- |\n * | Boot time | O(N elements) | O(1) — 1 loop |\n * | Memory | O(N listeners) | O(1) — 1 handler |\n * | Dynamic content | Requires re-bootstrap | Works out-of-box |\n * | `once` modifier | Native option | Manual tracking |\n *\n * ## Trade-offs vs. the directive approach\n *\n * - `passive` is not supported as a per-element option (all delegated listeners\n * are non-passive so that `prevent` can call `preventDefault()`).\n * - `stop` stops further bubbling but the delegation handler has already\n * captured the event at `body` level — it does not prevent other delegation\n * handlers from running on the same element.\n * - `once` is emulated by removing the attribute after first fire.\n */\n\nimport {internalChannel_, logger_} from './lib_.js';\nimport {modifierRegistry, payloadRegistry} from './registry_.js';\nimport type {Action, ActionRecord} from './type.js';\n\n// ─── Syntax Parser ────────────────────────────────────────────────────────────\n\n/**\n * Parses the `on-<eventType>` attribute value into its segments.\n *\n * Syntax: `actionId[:payload][; modifier1,modifier2,…]`\n *\n * The event type is encoded in the **attribute name** itself (`on-click`,\n * `on-submit`, etc.) rather than inside the value. This makes the HTML more\n * readable and aligns with native event attribute conventions.\n *\n * | Capture group | Matches | Example |\n * | ------------- | -------------------------------------- | -------------------------- |\n * | 1 | Action identifier | `ui_open_drawer` |\n * | 2 | Optional payload token or literal | `main_menu` / `$value` |\n * | 3 | Optional comma-separated modifier list | `prevent,validate` |\n *\n * @example\n * ```\n * 'ui_close_drawer'\n * → actionId='ui_close_drawer', payload=undefined, modifiers={}\n *\n * 'ui_open_drawer:main_menu'\n * → actionId='ui_open_drawer', payload='main_menu', modifiers={}\n *\n * 'ui_submit_form:$formdata; prevent,validate'\n * → actionId='ui_submit_form', payload='$formdata', modifiers={'prevent','validate'}\n * ```\n */\nconst syntaxRegex = /^(ui_[a-z0-9_-]+)(?::([^;]+))?(?:;\\s*([a-z0-9_,-]+))?$/;\n\n// ─── Parsed Action Descriptor ─────────────────────────────────────────────────\n\n/**\n * Parsed and cached representation of a single `on-<eventType>` attribute value.\n *\n * Does not store `eventType` — the caller always has it from `event.type`,\n * and the attribute name already encodes it (e.g. `on-click`), so storing it\n * here would be redundant. This also keeps the cache key simple: just the raw\n * attribute value string, with no composite key needed.\n */\ninterface ActionDescriptor {\n /** Set of active modifier names (e.g. `{'prevent', 'once'}`). */\n readonly modifiers: ReadonlySet<string>;\n /** The action identifier dispatched to `onAction` subscribers. */\n readonly actionId: string;\n /** Raw payload token from the attribute (literal string or $-resolver key). */\n readonly payload: string | undefined;\n}\n\n/**\n * Cache for parsed `on-<eventType>` attribute values.\n *\n * Attribute strings are typically repeated across many elements (e.g. every\n * \"add to cart\" button shares the same `on-click` value). Caching the parsed\n * descriptor avoids redundant regex work on every event.\n *\n * The cache key is the raw attribute value string. No composite key with\n * event type is needed because the attribute name already encodes the event\n * type — `on-click=\"ui_open_drawer\"` and `on-submit=\"ui_open_drawer\"` are two\n * separate attributes with the same value string, but they are read from\n * different attribute names and never collide in this cache.\n *\n * @internal\n */\nconst descriptorCache__ = new Map<string, ActionDescriptor | null>();\n\n/**\n * Parses an `on-<eventType>` attribute value into an `ActionDescriptor`.\n *\n * Returns `null` when the syntax is invalid. Results are cached by the raw\n * attribute value string so repeated calls for the same value are O(1).\n *\n * @internal\n */\nfunction parseDescriptor__(attributeValue: string): ActionDescriptor | null {\n logger_.logMethodArgs?.('parseDescriptor__', {attributeValue});\n\n const cached = descriptorCache__.get(attributeValue);\n // Explicit `undefined` check: `null` means \"already parsed and invalid\".\n if (cached !== undefined) return cached;\n\n const match = attributeValue.match(syntaxRegex);\n if (!match) {\n logger_.accident('parseDescriptor__', 'invalid_syntax', {attributeValue});\n descriptorCache__.set(attributeValue, null);\n return null;\n }\n\n const actionId = match[1];\n const payload: string | undefined = match[2];\n // match[3] is the raw modifier list string, e.g. \"prevent,validate\"\n const modifierString = match[3];\n const modifiers: Set<string> = modifierString ? new Set(modifierString.split(',').filter(Boolean)) : new Set();\n const descriptor: ActionDescriptor = {modifiers, actionId, payload};\n\n descriptorCache__.set(attributeValue, descriptor);\n return descriptor;\n}\n\n// ─── Core Delegation Handler ──────────────────────────────────────────────────\n\n/**\n * Central event handler attached to `document.body` for every delegated event type.\n *\n * Execution flow for each incoming event:\n * 1. Walk up from `event.target` to find the nearest element with an\n * `on-<eventType>` attribute (e.g. `on-click`, `on-submit`).\n * 2. Parse (or retrieve from cache) the `ActionDescriptor` for that attribute.\n * 3. Resolve `context` from the nearest `[action-context]` ancestor.\n * 4. Build a mutable `Action` object with `type`, `payload` (raw), and `context`.\n * 5. Run each modifier in order with access to the mutable `Action`; if any\n * returns `false`, abort.\n * 6. Resolve the payload token (literal or $-resolver) and assign to `action.payload`.\n * 7. Call `dispatchAction(action)` with the fully assembled object.\n *\n * @internal\n */\nfunction handleDelegatedEvent__(event: Event): void {\n const eventType = event.type;\n logger_.logMethodArgs?.('handleDelegatedEvent__', {eventType});\n\n const target = event.target as Element | null;\n if (!target) return;\n\n // Attribute name encodes the event type: on-click, on-submit, etc.\n const actionAttrib = `on-${eventType}`;\n\n // Walk up the DOM to find the closest element with the matching on-<eventType> attribute.\n const actionElement = target.closest?.(`[${actionAttrib}]`);\n if (!actionElement) return;\n\n const attributeValue = actionElement.getAttribute?.(actionAttrib)?.trim();\n if (!attributeValue) {\n logger_.accident('handleDelegatedEvent__', 'empty_attribute', {eventType, actionElement});\n return;\n }\n\n if (!(actionElement instanceof HTMLElement)) {\n logger_.accident('handleDelegatedEvent__', 'target_not_html_element', {eventType, actionElement});\n return;\n }\n\n const descriptor = parseDescriptor__(attributeValue);\n if (!descriptor) return;\n\n logger_.logMethodArgs?.('handleDelegatedEvent__.action', {eventType, descriptor});\n\n // Step 1: handle `once` modifier — remove attribute before running other modifiers\n // so that even if a modifier aborts, the element will not fire again.\n if (descriptor.modifiers.has('once')) {\n actionElement.removeAttribute(actionAttrib);\n }\n\n // Step 2: resolve `context` from the nearest [action-context] ancestor.\n // Walk up from the action element itself (inclusive) to find the context scope.\n // This allows the action element itself to carry action-context if needed.\n const actionContext = actionElement.closest('[action-context]')?.getAttribute('action-context') ?? undefined;\n\n // Step 3: build the mutable Action object.\n // `payload` starts as the raw token string; it will be resolved in step 5.\n // Modifiers in step 4 may mutate `meta` to attach cross-cutting data.\n const action: Action = {\n type: descriptor.actionId as keyof ActionRecord,\n context: actionContext,\n // Payload is temporarily set to the raw token; resolved below after modifiers run.\n payload: descriptor.payload as ActionRecord[keyof ActionRecord],\n };\n\n // Step 4: run modifiers — each receives the mutable action so it can enrich meta.\n for (const modifier of descriptor.modifiers) {\n if (modifier === 'once') continue; // handled above\n const handler = modifierRegistry.get(modifier);\n if (!handler) {\n logger_.accident('handleDelegatedEvent__', 'unknown_modifier', {eventType, modifier, attributeValue, descriptor});\n return; // unknown modifier — abort to avoid silent misbehavior\n }\n if (handler(event, actionElement, action) === false) return;\n }\n\n // Step 5: resolve payload — replace raw token with the actual value.\n // If the raw token starts with '$', look it up in the payload resolver registry.\n // Otherwise treat it as a literal string payload.\n if (descriptor.payload) {\n const resolver = payloadRegistry.get(descriptor.payload);\n if (resolver) {\n // Cast needed: payload is typed as ActionRecord[K] but we're building generically.\n (action as {payload: unknown}).payload = resolver(event, actionElement);\n }\n // else: keep the literal string already set on action.payload\n } else {\n // No payload token in the attribute — set to undefined.\n (action as {payload: unknown}).payload = undefined;\n }\n\n // Step 6: dispatch the fully assembled Action object.\n internalChannel_.dispatch(action.type, action);\n}\n\n// ─── Setup ────────────────────────────────────────────────────────────────────\n\n/**\n * The set of event types currently delegated to `document.body`.\n *\n * Tracked so that `setupActionDelegation` is idempotent — calling it multiple\n * times with the same event types does not register duplicate listeners.\n *\n * @internal\n */\nconst delegatedEventTypes__ = new Set<string>();\n\n/**\n * Default DOM event types that cover the vast majority of interactive elements.\n *\n * - `click` — buttons, links, checkboxes, custom interactive elements\n * - `submit` — form submission\n * - `input` — live text input, range sliders\n * - `change` — select boxes, checkboxes, radio buttons (fires on commit)\n *\n * Pass additional types to `setupActionDelegation` when your app uses other\n * events (e.g. `'keydown'`, `'pointerup'`).\n */\nexport const DEFAULT_DELEGATED_EVENTS: readonly string[] = ['click', 'submit', 'input', 'change'];\n\n/**\n * Registers global event delegation for `on-<eventType>` attributes.\n *\n * Attaches a single `capture`-phase listener on `document.body` for each\n * event type in `eventTypes`. All processing — context resolution, modifier\n * execution, payload resolution, and `dispatchAction` — happens inside that\n * one handler.\n *\n * **Call this once at application bootstrap**, before any user interaction.\n * Subsequent calls with the same event types are no-ops (idempotent).\n *\n * ### Why `capture: true`?\n *\n * Capture-phase listeners fire before bubble-phase listeners and also catch\n * events that do not bubble (e.g. `focus`, `blur`). This ensures the delegation\n * handler always runs, even when a child element calls `stopPropagation()`.\n *\n * ### Dynamic content\n *\n * Because the listener lives on `document.body`, any element added to the DOM\n * after this call — via `innerHTML`, `lit-html`, a framework renderer, or\n * server-sent HTML — is automatically covered. No re-bootstrap is needed.\n *\n * ### Context scoping\n *\n * Wrap a group of elements in a `[action-context]` container to scope their\n * actions. The delegation handler automatically resolves the nearest ancestor\n * and attaches its value to `action.context`:\n *\n * ```html\n * <section action-context=\"product-list\">\n * <button on-click=\"ui_add_to_cart:42\">Add</button>\n * </section>\n * ```\n *\n * ```ts\n * onAction('ui_add_to_cart', (action) => {\n * console.log(action.context); // 'product-list'\n * });\n * ```\n *\n * @param eventTypes - Event types to delegate. Defaults to `DEFAULT_DELEGATED_EVENTS`.\n *\n * @example — minimal bootstrap\n * ```ts\n * import {setupActionDelegation, onAction} from '@alwatr/action';\n *\n * // One call activates the entire page.\n * setupActionDelegation();\n *\n * onAction('ui_open_drawer', (action) => openDrawer(action.payload));\n * ```\n *\n * @example — with extra event types\n * ```ts\n * import {setupActionDelegation, DEFAULT_DELEGATED_EVENTS} from '@alwatr/action';\n *\n * setupActionDelegation([...DEFAULT_DELEGATED_EVENTS, 'keydown', 'pointerup']);\n * ```\n */\nexport function setupActionDelegation(eventTypes: readonly string[] = DEFAULT_DELEGATED_EVENTS): void {\n logger_.logMethodArgs?.('setupActionDelegation', {eventTypes});\n\n for (const eventType of eventTypes) {\n if (delegatedEventTypes__.has(eventType)) continue; // already registered — skip\n delegatedEventTypes__.add(eventType);\n // capture: true — fires before bubble-phase listeners and catches non-bubbling events.\n document.body.addEventListener(eventType, handleDelegatedEvent__, {capture: true});\n }\n}\n\n/**\n * Removes all global delegation listeners registered by `setupActionDelegation`.\n *\n * Useful in test environments where each test needs a clean slate, or in\n * micro-frontend setups where a sub-app is unmounted.\n *\n * After calling this, `setupActionDelegation` can be called again to re-register.\n */\nexport function teardownActionDelegation(): void {\n logger_.logMethod?.('teardownActionDelegation');\n for (const eventType of delegatedEventTypes__) {\n document.body.removeEventListener(eventType, handleDelegatedEvent__, {capture: true});\n }\n delegatedEventTypes__.clear();\n descriptorCache__.clear();\n}\n",
|
|
8
|
-
"import type {Awaitable, VoidFunc} from '@alwatr/type-helper';\nimport type {SubscribeResult} from '@alwatr/signal';\n\nimport {internalChannel_, logger_} from './lib_.js';\nimport {modifierRegistry, payloadRegistry} from './registry_.js';\nimport type {Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver} from './type.js';\n\n// ─── Core Action API ──────────────────────────────────────────────────────────\n\n/**\n * Subscribes to a named action dispatched anywhere in the application.\n *\n * `type` must be a key of `ActionRecord`. The handler receives the full\n * `Action<K>` object — giving access to `payload`, `context`, and `meta`\n * in one place. No manual generic annotation is needed; the compiler infers\n * the correct `payload` type from `ActionRecord`:\n *\n * ```ts\n * // ActionRecord declares: 'ui_add_to_cart': {productId: number; qty: number}\n * onAction('ui_add_to_cart', (action) => {\n * cartService.add(action.payload.productId, action.payload.qty); // fully typed\n * console.log(action.context); // e.g. 'product-list' (from DOM) or undefined\n * });\n * ```\n *\n * Passing an action name not declared in `ActionRecord` is a **compile error**.\n * Register new actions by extending `ActionRecord` via declaration merging:\n *\n * ```ts\n * // src/action-record.ts\n * declare module '@alwatr/action' {\n * interface ActionRecord {\n * 'ui_open_drawer': string;\n * }\n * }\n * ```\n *\n * Internally delegates to `ChannelSignal.on()` for **O(1) routing** — dispatching\n * action `'A'` never invokes handlers registered for action `'B'`.\n *\n * @param type - A key of `ActionRecord`.\n * @param handler - Callback invoked with the full `Action<K>` on each dispatch.\n * @returns A `SubscribeResult` with an `unsubscribe()` method for cleanup.\n *\n * @example\n * ```ts\n * import {onAction} from '@alwatr/action';\n *\n * const sub = onAction('ui_page_ready', (action) => {\n * router.setPage(action.payload); // payload: string — inferred from ActionRecord\n * });\n *\n * sub.unsubscribe(); // stop listening when no longer needed\n * ```\n */\nexport function onAction<K extends keyof ActionRecord>(\n type: K | K[],\n handler: (action: Action<K>) => Awaitable<void>,\n): SubscribeResult {\n logger_.logMethodArgs?.('onAction', {type});\n // The internal channel stores Action<any>; we cast to Action<K> here because\n // the channel key guarantees the type matches — only Action<K> objects are\n // ever dispatched under key K.\n if (Array.isArray(type)) {\n const typeList = type as K[];\n const unsubscribeList: VoidFunc[] = [];\n for (const type_ of typeList) {\n unsubscribeList.push(internalChannel_.on(type_, handler as (action: Action) => Awaitable<void>).unsubscribe);\n }\n return {\n unsubscribe: () => {\n for (const unsubscribe of unsubscribeList) {\n unsubscribe();\n }\n unsubscribeList.length = 0;\n },\n };\n }\n // else single type\n return internalChannel_.on(type, handler as (action: Action) => Awaitable<void>);\n}\n\n/**\n * Dispatches an action to all `onAction` subscribers with a matching `type`.\n *\n * Accepts a full `Action<K>` object. The `payload` field is automatically\n * typed from `ActionRecord[K]` — passing the wrong shape is a **compile error**:\n *\n * ```ts\n * // ActionRecord declares: 'ui_add_to_cart': {productId: number; qty: number}\n * dispatchAction({type: 'ui_add_to_cart', payload: {productId: 42, qty: 1}}); // ✅\n * dispatchAction({type: 'ui_add_to_cart', payload: 'wrong'}); // ❌ compile error\n * dispatchAction({type: 'unknown_action', payload: 'x'}); // ❌ compile error\n * ```\n *\n * The `context` and `meta` fields are optional. When dispatching from code\n * (not from the DOM), omit `context` — it is only meaningful for DOM-originated\n * actions where an `[action-context]` ancestor exists.\n *\n * Use `dispatchAction` when triggering an action from code — e.g. after an\n * async operation, from a service layer, or in tests. For DOM-driven actions,\n * use the `on-<eventType>` HTML attribute with `setupActionDelegation`.\n *\n * @param action - A full `Action<K>` object with at minimum `type` and `payload`.\n *\n * @example — with payload (code-originated action — no 'ui_' prefix)\n * ```ts\n * import {dispatchAction} from '@alwatr/action';\n *\n * dispatchAction({type: 'navigate', payload: '/dashboard'});\n * dispatchAction({type: 'upload_complete', payload: fileId});\n * ```\n *\n * @example — void payload (payload field is optional and can be omitted entirely)\n * ```ts\n * dispatchAction({type: 'auth_expired'});\n * // or explicitly:\n * dispatchAction({type: 'auth_expired', payload: undefined});\n * ```\n *\n * @example — with context and meta\n * ```ts\n * dispatchAction({\n * type: 'slider_change',\n * payload: 75,\n * context: 'volume_slider',\n * meta: {traceId: 'abc-123'},\n * });\n * ```\n */\nexport function dispatchAction<K extends keyof ActionRecord>(action: DispatchParam<K>): void {\n logger_.logMethodArgs?.('dispatchAction', action);\n internalChannel_.dispatch(action.type, action as Action<K>);\n}\n\n// ─── Extension API ────────────────────────────────────────────────────────────\n\n/**\n * Registers a custom modifier that can be used in `on-<eventType>` attribute syntax.\n *\n * A modifier is a comma-separated token placed after the `;` separator\n * (e.g. `on-click=\"action-id; mymod\"`). Its handler runs before the payload is\n * resolved and the action is dispatched. Returning `false` cancels the dispatch.\n *\n * The handler also receives the **mutable** `action` object being built, so it\n * can attach data to `action.meta` before the action reaches subscribers.\n *\n * Built-in modifiers (`prevent`, `validate`, `once`) are always available.\n * This function lets you add domain-specific ones.\n *\n * Registering the same name twice logs an accident and overwrites the previous\n * handler — avoid duplicate registrations in production code.\n *\n * @param name - The modifier token (lowercase, no special characters).\n * @param handler - A `ModifierHandler` receiving `(event, element, action)`.\n *\n * @example — a `confirm` modifier that shows a browser dialog\n * ```ts\n * import {registerModifier} from '@alwatr/action';\n *\n * registerModifier('confirm', () => window.confirm('Are you sure?'));\n * ```\n * ```html\n * <button on-click=\"ui_delete_item:42; confirm\">Delete</button>\n * ```\n *\n * @example — a `trace` modifier that stamps a trace ID into meta\n * ```ts\n * registerModifier('trace', (_event, _element, action) => {\n * action.meta ??= {};\n * action.meta['traceId'] = crypto.randomUUID();\n * return true;\n * });\n * ```\n */\nexport function registerModifier(name: string, handler: ModifierHandler): void {\n logger_.logMethodArgs?.('registerModifier', {name});\n if (modifierRegistry.has(name)) {\n logger_.accident('registerModifier', 'modifier_already_registered', {name});\n }\n modifierRegistry.set(name, handler);\n}\n\n/**\n * Registers a custom payload resolver that can be used in `on-<eventType>` attribute syntax.\n *\n * A payload resolver is a colon-prefixed token in the attribute value\n * (e.g. `on-click=\"action-id:$mytoken\"`). Its function is called at dispatch time\n * with the DOM event and the element. The return value becomes the `payload`\n * field of the `Action` object passed to `onAction` subscribers.\n *\n * Built-in resolvers (`$value`, `$formdata`, `$checked`) are always available.\n * This function lets you add domain-specific ones.\n *\n * Registering the same name twice logs an accident and overwrites the previous\n * resolver — avoid duplicate registrations in production code.\n *\n * @param name - The resolver token (should start with `$` by convention).\n * @param resolver - A `PayloadResolver` receiving `(event, element)`.\n *\n * @example — a `$data-id` resolver that reads a data attribute\n * ```ts\n * import {registerPayloadResolver} from '@alwatr/action';\n *\n * registerPayloadResolver('$data-id', (_event, element) => {\n * return (element as HTMLElement).dataset.id ?? null;\n * });\n * ```\n * ```html\n * <button on-click=\"ui_select_item:$data-id\" data-id=\"42\">Select</button>\n * ```\n */\nexport function registerPayloadResolver(name: string, resolver: PayloadResolver): void {\n logger_.logMethodArgs?.('registerPayloadResolver', {name});\n if (payloadRegistry.has(name)) {\n logger_.accident('registerPayloadResolver', 'payload_resolver_already_registered', {name});\n }\n payloadRegistry.set(name, resolver);\n}\n"
|
|
5
|
+
"import {createLogger} from '@alwatr/logger';\nimport {createChannelSignal} from '@alwatr/signal';\nimport type {SubscribeResult} from '@alwatr/signal';\nimport type {Awaitable, VoidFunc} from '@alwatr/type-helper';\n\nimport type {Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver} from './type.js';\n\n/**\n * Parsed representation of an action attribute descriptor.\n * @internal\n */\ninterface ActionDescriptor {\n readonly modifiers: ReadonlySet<string>;\n readonly actionId: string;\n readonly payload: string | undefined;\n}\n\n/**\n * Regex parser for the `on-<eventType>` attribute syntax.\n * Syntax: `actionId[:payload][; modifier1,modifier2,...]`\n */\nconst syntaxRegex = /^(ui_[a-z0-9_-]+)(?::([^;]+))?(?:;\\s*([a-z0-9_,-]+))?$/;\n\n/**\n * Service to manage declarative DOM actions, programmatic dispatch,\n * modifiers, payload resolvers, and global event delegation.\n *\n * @example\n * ```ts\n * import {ActionService} from '@alwatr/action';\n *\n * const customActionService = new ActionService();\n * ```\n */\nexport class ActionService {\n /**\n * Default DOM event types that cover the vast majority of interactive elements.\n */\n static readonly DEFAULT_DELEGATED_EVENTS: readonly string[] = ['click', 'submit', 'input', 'change'];\n\n protected readonly logger_ = createLogger('action-service');\n\n /**\n * Internal ChannelSignal used for routing dispatched actions.\n * @protected\n */\n protected readonly internalChannel_ = createChannelSignal<Record<string, Action>>({name: 'action-service'});\n\n /**\n * Registry mapping custom modifiers to their handlers.\n * @protected\n */\n protected readonly modifierRegistry_ = new Map<string, ModifierHandler>();\n\n /**\n * Registry mapping custom payload resolvers to their functions.\n * @protected\n */\n protected readonly payloadRegistry_ = new Map<string, PayloadResolver>();\n\n /**\n * Cache of parsed action descriptors to prevent redundant regex evaluation.\n * @protected\n */\n protected readonly descriptorCache_ = new Map<string, ActionDescriptor | null>();\n\n /**\n * Tracked event types currently delegated to `document.body`.\n * @protected\n */\n protected readonly delegatedEventTypes_ = new Set<string>();\n\n /**\n * Bound delegation handler for add/removeEventListener.\n * @private\n */\n private readonly handleDelegatedEventBound__ = this.handleDelegatedEvent_.bind(this);\n\n constructor() {\n this.logger_.logMethod?.('constructor');\n this.registerDefaultModifiersAndResolvers__();\n }\n\n /**\n * Subscribes to a named action dispatched anywhere in the application.\n *\n * @template K - A key of ActionRecord.\n * @param type - Action type or array of action types to subscribe to.\n * @param handler - Callback invoked with the full Action object.\n * @returns SubscribeResult containing an `unsubscribe` method.\n *\n * @example\n * ```ts\n * // Subscribe to a single action\n * const sub1 = actionService.on('ui_open_drawer', (action) => {\n * console.log(action.payload);\n * });\n *\n * // Subscribe to multiple action types\n * const sub2 = actionService.on(['ui_open_drawer', 'ui_close_drawer'], (action) => {\n * console.log(action.type, action.payload);\n * });\n * ```\n */\n on<K extends keyof ActionRecord>(type: K | K[], handler: (action: Action<K>) => Awaitable<void>): SubscribeResult {\n this.logger_.logMethodArgs?.('on', {type});\n if (Array.isArray(type)) {\n const typeList = type as K[];\n const unsubscribeList: VoidFunc[] = [];\n for (const type_ of typeList) {\n unsubscribeList.push(\n this.internalChannel_.on(type_, handler as (action: Action) => Awaitable<void>).unsubscribe,\n );\n }\n return {\n unsubscribe: () => {\n this.logger_.logMethod?.('unsubscribe');\n for (const unsubscribe of unsubscribeList) {\n unsubscribe();\n }\n unsubscribeList.length = 0;\n },\n };\n }\n return this.internalChannel_.on(type, handler as (action: Action) => Awaitable<void>);\n }\n\n /**\n * Dispatches an action to all subscribers matching `action.type`.\n *\n * @template K - A key of ActionRecord.\n * @param action - Action object containing `type` and `payload`.\n *\n * @example\n * ```ts\n * // Dispatches a typed action (payload is required)\n * actionService.dispatch({type: 'upload_complete', payload: 'file-123'});\n *\n * // Dispatches a void action (payload can be omitted)\n * actionService.dispatch({type: 'auth_expired'});\n * ```\n */\n dispatch<K extends keyof ActionRecord>(action: DispatchParam<K>): void {\n this.logger_.logMethodArgs?.('dispatch', action);\n this.internalChannel_.dispatch(action.type, action as Action<K>);\n }\n\n /**\n * Registers a custom modifier to enrich or filter actions before dispatch.\n *\n * @param name - Modifier name (lowercase, alphanumeric).\n * @param handler - Function called when modifier is invoked.\n *\n * @example\n * ```ts\n * actionService.registerModifier('trace', (_event, _element, action) => {\n * action.meta ??= {};\n * action.meta['time'] = Date.now();\n * return true;\n * });\n * ```\n */\n registerModifier(name: string, handler: ModifierHandler): void {\n this.logger_.logMethodArgs?.('registerModifier', {name});\n if (this.modifierRegistry_.has(name)) {\n this.logger_.accident('registerModifier', 'modifier_already_registered', {name});\n return;\n }\n this.modifierRegistry_.set(name, handler);\n }\n\n /**\n * Registers a custom payload resolver to map DOM state to action payload.\n *\n * @param name - Resolver token (by convention starting with `$`).\n * @param resolver - Function yielding payload from the event and element.\n *\n * @example\n * ```ts\n * actionService.registerPayloadResolver('$data-id', (_event, element) => {\n * return element.dataset.id;\n * });\n * ```\n */\n registerPayloadResolver(name: string, resolver: PayloadResolver): void {\n this.logger_.logMethodArgs?.('registerPayloadResolver', {name});\n if (this.payloadRegistry_.has(name)) {\n this.logger_.accident('registerPayloadResolver', 'payload_resolver_already_registered', {name});\n return;\n }\n this.payloadRegistry_.set(name, resolver);\n }\n\n /**\n * Registers global event delegation listeners on `document.body`.\n *\n * @param eventTypes - List of event types to delegate. Defaults to ActionService.DEFAULT_DELEGATED_EVENTS.\n *\n * @example\n * ```ts\n * actionService.setupDelegation();\n * ```\n */\n setupDelegation(eventTypes: readonly string[] = ActionService.DEFAULT_DELEGATED_EVENTS): void {\n this.logger_.logMethodArgs?.('setupDelegation', {eventTypes});\n if (typeof document === 'undefined' || !document.body) {\n this.logger_.incident?.('setupDelegation', 'document_body_not_found');\n return;\n }\n\n for (const eventType of eventTypes) {\n if (this.delegatedEventTypes_.has(eventType)) continue;\n this.delegatedEventTypes_.add(eventType);\n document.body.addEventListener(eventType, this.handleDelegatedEventBound__, {capture: true});\n }\n }\n\n /**\n * Unregisters all global event delegation listeners.\n *\n * @example\n * ```ts\n * actionService.teardownDelegation();\n * ```\n */\n teardownDelegation(): void {\n this.logger_.logMethod?.('teardownDelegation');\n if (typeof document === 'undefined' || !document.body) {\n return;\n }\n for (const eventType of this.delegatedEventTypes_) {\n document.body.removeEventListener(eventType, this.handleDelegatedEventBound__, {capture: true});\n }\n this.delegatedEventTypes_.clear();\n this.descriptorCache_.clear();\n }\n\n /**\n * Parses attribute values into action descriptor, utilizing the internal cache.\n * @protected\n */\n protected parseDescriptor_(attributeValue: string): ActionDescriptor | null {\n this.logger_.logMethodArgs?.('parseDescriptor_', {attributeValue});\n\n const cached = this.descriptorCache_.get(attributeValue);\n if (cached !== undefined) return cached;\n\n const match = attributeValue.match(syntaxRegex);\n if (!match) {\n this.logger_.accident('parseDescriptor_', 'invalid_syntax', {attributeValue});\n this.descriptorCache_.set(attributeValue, null);\n return null;\n }\n\n const actionId = match[1]!;\n const payload = match[2];\n const modifierString = match[3];\n const modifiers = modifierString ? new Set(modifierString.split(',').filter(Boolean)) : new Set<string>();\n\n const descriptor: ActionDescriptor = {modifiers, actionId, payload};\n this.descriptorCache_.set(attributeValue, descriptor);\n return descriptor;\n }\n\n /**\n * Global event delegation handler.\n * @protected\n */\n protected handleDelegatedEvent_(event: Event): void {\n const eventType = event.type;\n this.logger_.logMethodArgs?.('handleDelegatedEvent_', {eventType});\n\n const target = event.target as Element | null;\n if (!target) return;\n\n const actionAttrib = `on-${eventType}`;\n const actionElement = target.closest?.(`[${actionAttrib}]`);\n if (!actionElement) return;\n\n const attributeValue = actionElement.getAttribute?.(actionAttrib)?.trim();\n if (!attributeValue) {\n this.logger_.accident('handleDelegatedEvent_', 'empty_attribute', {eventType, actionElement});\n return;\n }\n\n if (!(actionElement instanceof HTMLElement)) {\n this.logger_.accident('handleDelegatedEvent_', 'target_not_html_element', {eventType, actionElement});\n return;\n }\n\n const descriptor = this.parseDescriptor_(attributeValue);\n if (!descriptor) return;\n\n this.logger_.logMethodArgs?.('handleDelegatedEvent_.action', {eventType, descriptor});\n\n if (descriptor.modifiers.has('once')) {\n actionElement.removeAttribute(actionAttrib);\n }\n\n const actionContext = actionElement.closest('[action-context]')?.getAttribute('action-context') ?? undefined;\n\n const action: Action = {\n type: descriptor.actionId as keyof ActionRecord,\n context: actionContext,\n payload: descriptor.payload as ActionRecord[keyof ActionRecord],\n };\n\n for (const modifier of descriptor.modifiers) {\n if (modifier === 'once') continue;\n const handler = this.modifierRegistry_.get(modifier);\n if (!handler) {\n this.logger_.accident('handleDelegatedEvent_', 'unknown_modifier', {\n eventType,\n modifier,\n attributeValue,\n descriptor,\n });\n return;\n }\n try {\n if (handler(event, actionElement, action) === false) return;\n } catch (error) {\n this.logger_.accident('handleDelegatedEvent_', 'modifier_execution_failed', {\n modifier,\n error,\n });\n return;\n }\n }\n\n if (descriptor.payload) {\n const resolver = this.payloadRegistry_.get(descriptor.payload);\n if (resolver) {\n try {\n (action as {payload: unknown}).payload = resolver(event, actionElement);\n } catch (error) {\n this.logger_.accident('handleDelegatedEvent_', 'payload_resolver_failed', {\n resolver: descriptor.payload,\n error,\n });\n return;\n }\n }\n } else {\n (action as {payload: unknown}).payload = undefined;\n }\n\n this.internalChannel_.dispatch(action.type, action);\n }\n\n /**\n * Registers default modifiers and resolvers.\n * @private\n */\n private registerDefaultModifiersAndResolvers__(): void {\n this.logger_.logMethod?.('registerDefaultModifiersAndResolvers__');\n\n // Built-in modifiers\n this.registerModifier('prevent', (event) => {\n event.preventDefault();\n return true;\n });\n\n this.registerModifier('validate', (_event, element) => {\n const form = element instanceof HTMLFormElement ? element : element.closest('form');\n if (!form) return false;\n return form.checkValidity();\n });\n\n // Built-in resolvers\n this.registerPayloadResolver('$value', (_event, element) => {\n return 'value' in element ? (element as {value: unknown}).value : null;\n });\n\n this.registerPayloadResolver('$formdata', (_event, element) => {\n const form = element instanceof HTMLFormElement ? element : element.closest('form');\n return form ? Object.fromEntries(new FormData(form)) : null;\n });\n\n this.registerPayloadResolver('$checked', (_event, element) => {\n return 'checked' in element ? (element as HTMLInputElement).checked : null;\n });\n }\n}\n\n/**\n * Singleton instance of the ActionService.\n * Ready for immediate use.\n *\n * @example\n * ```ts\n * import {actionService} from '@alwatr/action';\n *\n * actionService.setupDelegation();\n * ```\n */\nexport const actionService = new ActionService();\n",
|
|
6
|
+
"import type {SubscribeResult} from '@alwatr/signal';\nimport type {Awaitable} from '@alwatr/type-helper';\n\nimport {actionService, ActionService} from './action-service.js';\nimport type {Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver} from './type.js';\n\nexport {actionService, ActionService};\nexport type {Action, ActionRecord, DispatchParam, ModifierHandler, PayloadResolver};\n\n/**\n * Default DOM event types that cover the vast majority of interactive elements.\n *\n * - `click` — buttons, links, checkboxes, custom interactive elements\n * - `submit` — form submission\n * - `input` — live text input, range sliders\n * - `change` — select boxes, checkboxes, radio buttons (fires on commit)\n */\nexport const DEFAULT_DELEGATED_EVENTS = ActionService.DEFAULT_DELEGATED_EVENTS;\n\n/**\n * Subscribes to a named action dispatched anywhere in the application.\n *\n * @template K - A key of ActionRecord.\n * @param type - Action type or array of action types to subscribe to.\n * @param handler - Callback invoked with the full Action object.\n * @returns SubscribeResult containing an `unsubscribe` method.\n *\n * @example\n * ```ts\n * import {onAction} from '@alwatr/action';\n *\n * // Subscribe to multiple action types\n * const sub = onAction(['ui_open_drawer', 'ui_close_drawer'], (action) => {\n * console.log(action.type, action.payload);\n * });\n * sub.unsubscribe();\n * ```\n *\n * @deprecated Use `actionService.on` instead.\n */\nexport function onAction<K extends keyof ActionRecord>(\n type: K | K[],\n handler: (action: Action<K>) => Awaitable<void>,\n): SubscribeResult {\n return actionService.on(type, handler);\n}\n\n/**\n * Dispatches an action to all subscribers matching `action.type`.\n *\n * @template K - A key of ActionRecord.\n * @param action - Action object containing `type` and `payload`.\n *\n * @example\n * ```ts\n * import {dispatchAction} from '@alwatr/action';\n *\n * // Dispatches a typed action (payload is required)\n * dispatchAction({type: 'upload_complete', payload: 'file-123'});\n *\n * // Dispatches a void action (payload can be omitted)\n * dispatchAction({type: 'auth_expired'});\n * ```\n *\n * @deprecated Use `actionService.dispatch` instead.\n */\nexport function dispatchAction<K extends keyof ActionRecord>(action: DispatchParam<K>): void {\n actionService.dispatch(action);\n}\n\n/**\n * Registers global event delegation listeners on `document.body`.\n *\n * @param eventTypes - List of event types to delegate. Defaults to DEFAULT_DELEGATED_EVENTS.\n *\n * @example\n * ```ts\n * import {setupActionDelegation} from '@alwatr/action';\n *\n * setupActionDelegation();\n * ```\n *\n * @deprecated Use `actionService.setupDelegation` instead.\n */\nexport function setupActionDelegation(eventTypes?: readonly string[]): void {\n actionService.setupDelegation(eventTypes);\n}\n\n/**\n * Unregisters all global event delegation listeners.\n *\n * @example\n * ```ts\n * import {teardownActionDelegation} from '@alwatr/action';\n *\n * teardownActionDelegation();\n * ```\n *\n * @deprecated Use `actionService.teardownDelegation` instead.\n */\nexport function teardownActionDelegation(): void {\n actionService.teardownDelegation();\n}\n\n/**\n * Registers a custom modifier to enrich or filter actions before dispatch.\n *\n * @param name - Modifier name (lowercase, alphanumeric).\n * @param handler - Function called when modifier is invoked.\n *\n * @example\n * ```ts\n * import {registerModifier} from '@alwatr/action';\n *\n * registerModifier('trace', (_event, _element, action) => {\n * action.meta ??= {};\n * action.meta['time'] = Date.now();\n * return true;\n * });\n * ```\n *\n * @deprecated Use `actionService.registerModifier` instead.\n */\nexport function registerModifier(name: string, handler: ModifierHandler): void {\n actionService.registerModifier(name, handler);\n}\n\n/**\n * Registers a custom payload resolver to map DOM state to action payload.\n *\n * @param name - Resolver token (by convention starting with `$`).\n * @param resolver - Function yielding payload from the event and element.\n *\n * @example\n * ```ts\n * import {registerPayloadResolver} from '@alwatr/action';\n *\n * registerPayloadResolver('$data-id', (_event, element) => {\n * return element.dataset.id;\n * });\n * ```\n *\n * @deprecated Use `actionService.registerPayloadResolver` instead.\n */\nexport function registerPayloadResolver(name: string, resolver: PayloadResolver): void {\n actionService.registerPayloadResolver(name, resolver);\n}\n"
|
|
9
7
|
],
|
|
10
|
-
"mappings": ";AAAA,uBAAQ,uBACR,8BAAQ,
|
|
11
|
-
"debugId": "
|
|
8
|
+
"mappings": ";AAAA,uBAAQ,uBACR,8BAAQ,uBAoBR,IAAM,EAAc,yDAab,MAAM,CAAc,OAIT,0BAA8C,CAAC,QAAS,SAAU,QAAS,QAAQ,EAEhF,QAAU,EAAa,gBAAgB,EAMvC,iBAAmB,EAA4C,CAAC,KAAM,gBAAgB,CAAC,EAMvF,kBAAoB,IAAI,IAMxB,iBAAmB,IAAI,IAMvB,iBAAmB,IAAI,IAMvB,qBAAuB,IAAI,IAM7B,4BAA8B,KAAK,sBAAsB,KAAK,IAAI,EAEnF,WAAW,EAAG,CACZ,KAAK,QAAQ,YAAY,aAAa,EACtC,KAAK,uCAAuC,EAwB9C,EAAgC,CAAC,EAAe,EAAkE,CAEhH,GADA,KAAK,QAAQ,gBAAgB,KAAM,CAAC,MAAI,CAAC,EACrC,MAAM,QAAQ,CAAI,EAAG,CACvB,IAAM,EAAW,EACX,EAA8B,CAAC,EACrC,QAAW,KAAS,EAClB,EAAgB,KACd,KAAK,iBAAiB,GAAG,EAAO,CAA8C,EAAE,WAClF,EAEF,MAAO,CACL,YAAa,IAAM,CACjB,KAAK,QAAQ,YAAY,aAAa,EACtC,QAAW,KAAe,EACxB,EAAY,EAEd,EAAgB,OAAS,EAE7B,EAEF,OAAO,KAAK,iBAAiB,GAAG,EAAM,CAA8C,EAkBtF,QAAsC,CAAC,EAAgC,CACrE,KAAK,QAAQ,gBAAgB,WAAY,CAAM,EAC/C,KAAK,iBAAiB,SAAS,EAAO,KAAM,CAAmB,EAkBjE,gBAAgB,CAAC,EAAc,EAAgC,CAE7D,GADA,KAAK,QAAQ,gBAAgB,mBAAoB,CAAC,MA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B,QAAU,KACvE,EAEL,CAaO,IAAM,EAAgB,IAAI,EC3X1B,IAAM,EAA2B,EAAc,yBAuB/C,SAAS,CAAsC,CACpD,EACA,EACiB,CACjB,OAAO,EAAc,GAAG,EAAM,CAAO,EAsBhC,SAAS,CAA4C,CAAC,EAAgC,CAC3F,EAAc,SAAS,CAAM,EAiBxB,SAAS,CAAqB,CAAC,EAAsC,CAC1E,EAAc,gBAAgB,CAAU,EAenC,SAAS,CAAwB,EAAS,CAC/C,EAAc,mBAAmB,EAsB5B,SAAS,CAAgB,CAAC,EAAc,EAAgC,CAC7E,EAAc,iBAAiB,EAAM,CAAO,EAoBvC,SAAS,CAAuB,CAAC,EAAc,EAAiC,CACrF,EAAc,wBAAwB,EAAM,CAAQ",
|
|
9
|
+
"debugId": "4D2180C09EEB93E964756E2164756E21",
|
|
12
10
|
"names": []
|
|
13
11
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/action",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.28.0",
|
|
4
4
|
"description": "Declarative DOM action-dispatch — bridge HTML attributes to typed signal handlers.",
|
|
5
5
|
"license": "MPL-2.0",
|
|
6
6
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
|
|
@@ -80,5 +80,5 @@
|
|
|
80
80
|
"vanilla-js",
|
|
81
81
|
"web-development"
|
|
82
82
|
],
|
|
83
|
-
"gitHead": "
|
|
83
|
+
"gitHead": "d60f1d986e5ff44f871d38231f1f2be60833140b"
|
|
84
84
|
}
|