@alwatr/action 9.11.2

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,94 @@
1
+ import { Directive } from '@alwatr/directive';
2
+ /**
3
+ * Directive that bridges a DOM event to a typed action signal.
4
+ *
5
+ * Activated automatically by the `on-action` HTML attribute when
6
+ * `registerActionDirective()` has been called before `bootstrapDirectives()`.
7
+ * You rarely need to reference this class directly.
8
+ *
9
+ * **Attribute syntax**
10
+ * ```
11
+ * on-action="eventType[.modifier…]->actionId[:payload]"
12
+ * ```
13
+ *
14
+ * - `eventType` — any standard DOM event name (e.g. `click`, `input`, `submit`).
15
+ * - `modifier` — dot-chained tokens processed before dispatch
16
+ * (`prevent`, `stop`, `validate`, `once`, `passive`, or custom).
17
+ * - `actionId` — the identifier passed to `onAction` subscribers.
18
+ * - `payload` — an optional literal string or a `$`-prefixed resolver token
19
+ * (e.g. `$value`, `$formdata`, or custom).
20
+ *
21
+ * @example
22
+ * ```html
23
+ * <!-- Dispatches 'open-drawer' with payload 'settings' on click -->
24
+ * <button on-action="click->open-drawer:settings">Settings</button>
25
+ *
26
+ * <!-- Dispatches 'search-query' with the live input value on every keystroke -->
27
+ * <input on-action="input->search-query:$value" />
28
+ *
29
+ * <!-- Prevents default, validates, then dispatches 'submit-form' with all field values -->
30
+ * <form on-action="submit.prevent.validate->submit-form:$formdata" novalidate>…</form>
31
+ * ```
32
+ */
33
+ export declare class ActionDirective extends Directive {
34
+ /**
35
+ * Parsed and validated representation of the `on-action` attribute value.
36
+ *
37
+ * Set during `init_()` after the attribute is successfully parsed against
38
+ * `syntaxRegex`. Remains `undefined` when the attribute value is invalid,
39
+ * which prevents `dispatch_` from running.
40
+ */
41
+ protected actionContext_?: {
42
+ /** The DOM event type to listen for (e.g. `'click'`, `'input'`). */
43
+ eventType: string;
44
+ /** Set of active modifier names (e.g. `{'prevent', 'once'}`). */
45
+ modifiers: ReadonlySet<string>;
46
+ /** The action identifier dispatched to `onAction` subscribers. */
47
+ actionId: string;
48
+ /** Raw payload token from the attribute (literal string or `$`-resolver key). */
49
+ payload?: string;
50
+ };
51
+ /**
52
+ * Parses the `on-action` attribute, validates modifiers, and attaches the
53
+ * DOM event listener.
54
+ *
55
+ * Called once by `Directive` after one macrotask following element discovery.
56
+ * If the attribute value is malformed or references an unknown modifier,
57
+ * an accident is logged and the directive becomes a no-op.
58
+ */
59
+ protected init_(): void;
60
+ /**
61
+ * DOM event handler: runs modifiers, resolves the payload, and dispatches
62
+ * the action signal.
63
+ *
64
+ * Execution order:
65
+ * 1. Each modifier in `actionContext_.modifiers` is called in insertion order.
66
+ * If any returns `false` the method returns early — no action is dispatched.
67
+ * 2. The raw payload token is looked up in `payloadRegistry`. If a resolver
68
+ * is found it is called and its return value replaces the token.
69
+ * 3. `dispatchAction` is called with the resolved payload.
70
+ *
71
+ * @param event - The DOM event that triggered this handler.
72
+ */
73
+ protected dispatch_(event: Event): void;
74
+ }
75
+ /**
76
+ * Registers `ActionDirective` under the `on-action` attribute name.
77
+ *
78
+ * This is a **lazy** registration: calling this function is the only way to
79
+ * opt-in to `on-action` support. If it is never called, the entire directive
80
+ * module (including `ActionDirective`) is tree-shaken from the bundle.
81
+ *
82
+ * Call it once, before `bootstrapDirectives()`, at your application entry point.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * import {registerActionDirective} from '@alwatr/action';
87
+ * import {bootstrapDirectives} from '@alwatr/directive';
88
+ *
89
+ * registerActionDirective();
90
+ * bootstrapDirectives();
91
+ * ```
92
+ */
93
+ export declare const registerActionDirective: () => void;
94
+ //# sourceMappingURL=directive.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directive.d.ts","sourceRoot":"","sources":["../src/directive.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,SAAS,EAAC,MAAM,mBAAmB,CAAC;AA4B3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,eAAgB,SAAQ,SAAS;IAC5C;;;;;;OAMG;IACH,SAAS,CAAC,cAAc,CAAC,EAAE;QACzB,oEAAoE;QACpE,SAAS,EAAE,MAAM,CAAC;QAClB,iEAAiE;QACjE,SAAS,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;QAC/B,kEAAkE;QAClE,QAAQ,EAAE,MAAM,CAAC;QACjB,iFAAiF;QACjF,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;IAEF;;;;;;;OAOG;cACgB,KAAK,IAAI,IAAI;IAsDhC;;;;;;;;;;;;OAYG;IACH,SAAS,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;CAqBxC;AAID;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,uBAAuB,YAA8C,CAAC"}
package/dist/lib.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The shape of every payload carried by the internal action signal.
3
+ *
4
+ * `actionId` identifies which action was dispatched (e.g. `'open-drawer'`).
5
+ * `actionPayload` is the optional value attached to the action — defaults to
6
+ * `string` but can be narrowed to any type via the generic parameter `T`.
7
+ *
8
+ * @template T The type of the action payload. Defaults to `string`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * // Typed payload for a cart action
13
+ * const payload: ActionSignalPayload<{productId: number; qty: number}> = {
14
+ * actionId: 'add-to-cart',
15
+ * actionPayload: {productId: 42, qty: 1},
16
+ * };
17
+ * ```
18
+ */
19
+ export interface ActionSignalPayload<T = string> {
20
+ actionId: string;
21
+ actionPayload?: T;
22
+ }
23
+ /**
24
+ * Module-scoped logger for `@alwatr/action`.
25
+ * Scoped to `'alwatr-action'` so log lines are easy to filter in the console.
26
+ *
27
+ * @internal
28
+ */
29
+ export declare const logger_: import("@alwatr/logger").AlwatrLogger;
30
+ /**
31
+ * The single shared event signal that carries every dispatched action.
32
+ *
33
+ * All `ActionDirective` instances write to this signal via `dispatchAction`,
34
+ * and all `onAction` subscriptions read from it. Using one central signal keeps
35
+ * the pub/sub wiring minimal and makes the action flow easy to trace.
36
+ *
37
+ * The payload is typed as `ActionSignalPayload<unknown>` at the signal level;
38
+ * individual subscribers narrow the type through the `onAction` generic.
39
+ *
40
+ * @internal — not part of the public API; use `onAction` / `dispatchAction` instead.
41
+ */
42
+ export declare const internalSignal_: import("@alwatr/signal").EventSignal<ActionSignalPayload<unknown>>;
43
+ //# sourceMappingURL=lib.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,mBAAmB,CAAC,CAAC,GAAG,MAAM;IAC7C,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,CAAC,CAAC;CACnB;AAED;;;;;GAKG;AACH,eAAO,MAAM,OAAO,uCAAgC,CAAC;AAErD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,oEAA2E,CAAC"}
package/dist/main.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @alwatr/action — Declarative DOM action-dispatch for Unidirectional Data Flow.
3
+ *
4
+ * Public API surface:
5
+ * - `onAction` / `dispatchAction` — subscribe to and dispatch named actions
6
+ * - `registerActionDirective` — opt-in to `on-action` HTML attribute support
7
+ * - `registerPageIdDirective` — opt-in to `page-id` HTML attribute support
8
+ * - `registerModifier` / `registerPayloadResolver` — extend the directive syntax
9
+ * - `ActionDirective` / `PageIdDirective` — directive classes (advanced use)
10
+ * - `ActionSignalPayload` — payload type carried by the internal signal
11
+ */
12
+ export * from './method.js';
13
+ export * from './directive.js';
14
+ export * from './page-id.js';
15
+ export type { ActionSignalPayload } from './lib.js';
16
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,cAAc,CAAC;AAC7B,YAAY,EAAC,mBAAmB,EAAC,MAAM,UAAU,CAAC"}
package/dist/main.js ADDED
@@ -0,0 +1,5 @@
1
+ /* 📦 @alwatr/action v9.11.2 */
2
+ import{createLogger as S}from"@alwatr/logger";import{createEventSignal as V}from"@alwatr/signal";var J=S("alwatr-action"),Y=V({name:"alwatr-action"});var H=new Map,N=new Map;H.set("prevent",(M)=>{return M.preventDefault(),!0});H.set("stop",(M)=>{return M.stopPropagation(),!0});H.set("validate",function(){let M=this.element_ instanceof HTMLFormElement?this.element_:this.element_.closest("form");if(!M)return this.logger_.accident("validate_modifier","no_form_found",{element:this.element_}),!1;return M.checkValidity()});N.set("$value",function(){return"value"in this.element_?this.element_.value:null});N.set("$formdata",function(){let M=this.element_ instanceof HTMLFormElement?this.element_:this.element_.closest("form");return M?Object.fromEntries(new FormData(M).entries()):null});function k(M,q){return J.logMethodArgs?.("onAction",{actionId:M}),Y.subscribe((G)=>{if(G.actionId===M)J.logMethodArgs?.("onAction.invoke",{actionId:M,payload:G.actionPayload}),q(G.actionPayload)})}function X(M,q){J.logMethodArgs?.("dispatchAction",{actionId:M,actionPayload:q}),Y.dispatch({actionId:M,actionPayload:q})}function w(M,q){if(J.logMethodArgs?.("registerModifier",{name:M}),H.has(M))J.accident("registerModifier","modifier_already_registered",{name:M});H.set(M,q)}function D(M,q){if(J.logMethodArgs?.("registerPayloadResolver",{name:M}),N.has(M))J.accident("registerPayloadResolver","payload_resolver_already_registered",{name:M});N.set(M,q)}import{lazyDirective as C,Directive as L}from"@alwatr/directive";var z=/^([a-z0-9.-]+)->([a-z0-9-]+)(?::(.+))?$/;class F extends L{actionContext_;init_(){this.logger_.logMethodArgs?.("init_",{attributeValue:this.attributeValue});let M=this.attributeValue.trim().match(z);if(!M){this.logger_.accident("init_","invalid_syntax",{attributeValue:this.attributeValue});return}let[q,...G]=M[1].split("."),Q=M[2],W=M[3];if(!q){this.logger_.accident("init_","invalid_syntax",{attributeValue:this.attributeValue});return}let K=new Set;for(let U of G){if(!H.has(U)&&U!=="once"&&U!=="passive"){this.logger_.accident("init_","invalid_modifier",{attributeValue:this.attributeValue,modifier:U});return}K.add(U)}if(K.has("prevent")&&K.has("passive"))this.logger_.accident("init_","conflicting_modifiers_prevent_passive",{attributeValue:this.attributeValue});this.actionContext_={eventType:q,modifiers:K,actionId:Q,payload:W};let Z={once:K.has("once"),passive:K.has("passive")&&!K.has("prevent")},B=this.dispatch_.bind(this);this.element_.addEventListener(q,B,Z),this.addDestroyHook(()=>{this.element_.removeEventListener(q,B,Z)})}dispatch_(M){this.logger_.logMethodArgs?.("dispatch_",{eventType:M.type,actionId:this.actionContext_?.actionId});let q=this.actionContext_;for(let Q of q.modifiers){let W=H.get(Q);if(W&&W.call(this,M)===!1)return}let G=q.payload;if(G){let Q=N.get(G);if(Q)G=Q.call(this,M)}X(q.actionId,G)}}var u=C("on-action",F);import{Directive as j,lazyDirective as E}from"@alwatr/directive";class O extends j{init_(){let M=this.attributeValue.trim();if(this.logger_.logMethodArgs?.("init_",{pageId:M}),!M){this.logger_.accident("init_","empty_page_id");return}X("page-ready",M),this.destroy()}}var h=E("page-id",O);export{D as registerPayloadResolver,h as registerPageIdDirective,w as registerModifier,u as registerActionDirective,k as onAction,X as dispatchAction,O as PageIdDirective,F as ActionDirective};
3
+
4
+ //# debugId=78292B0ADE08B5FA64756E2164756E21
5
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,14 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib.ts", "../src/registry.ts", "../src/method.ts", "../src/directive.ts", "../src/page-id.ts"],
4
+ "sourcesContent": [
5
+ "import {createLogger} from '@alwatr/logger';\nimport {createEventSignal} from '@alwatr/signal';\n\n/**\n * The shape of every payload carried by the internal action signal.\n *\n * `actionId` identifies which action was dispatched (e.g. `'open-drawer'`).\n * `actionPayload` is the optional value attached to the action — defaults to\n * `string` but can be narrowed to any type via the generic parameter `T`.\n *\n * @template T The type of the action payload. Defaults to `string`.\n *\n * @example\n * ```ts\n * // Typed payload for a cart action\n * const payload: ActionSignalPayload<{productId: number; qty: number}> = {\n * actionId: 'add-to-cart',\n * actionPayload: {productId: 42, qty: 1},\n * };\n * ```\n */\nexport interface ActionSignalPayload<T = string> {\n actionId: string;\n actionPayload?: T;\n}\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 single shared event signal that carries every dispatched action.\n *\n * All `ActionDirective` instances write to this signal via `dispatchAction`,\n * and all `onAction` subscriptions read from it. Using one central signal keeps\n * the pub/sub wiring minimal and makes the action flow easy to trace.\n *\n * The payload is typed as `ActionSignalPayload<unknown>` at the signal level;\n * individual subscribers narrow the type through the `onAction` generic.\n *\n * @internal — not part of the public API; use `onAction` / `dispatchAction` instead.\n */\nexport const internalSignal_ = createEventSignal<ActionSignalPayload<unknown>>({name: 'alwatr-action'});\n",
6
+ "import type {ActionDirective} from './directive.js';\n\n// ─── Type Definitions ────────────────────────────────────────────────────────\n\n/**\n * A modifier handler attached to an `on-action` directive.\n *\n * Called with the directive instance as `this` and the triggering DOM `event`.\n * Return `true` to allow the action to proceed, or `false` to cancel it.\n * Returning `false` is the only way a modifier can veto a dispatch.\n *\n * @example\n * ```ts\n * // A modifier that only allows the action when the element is not disabled\n * const notDisabledHandler: ModifierHandler = function () {\n * return !(this.element_ as HTMLButtonElement).disabled;\n * };\n * ```\n */\nexport type ModifierHandler = (this: ActionDirective, event: Event) => boolean;\n\n/**\n * A payload resolver attached to an `on-action` directive.\n *\n * Called with the directive instance as `this` and the triggering DOM `event`\n * at dispatch time. The return value becomes the `actionPayload` of the\n * dispatched action. Use this to compute dynamic payloads from the DOM state.\n *\n * @example\n * ```ts\n * // A resolver that returns the element's dataset id\n * const dataIdResolver: PayloadResolver = function () {\n * return (this.element_ as HTMLElement).dataset.id ?? null;\n * };\n * ```\n */\nexport type PayloadResolver = (this: ActionDirective, event: Event) => unknown;\n\n// ─── Registries ──────────────────────────────────────────────────────────────\n\n/**\n * Registry of all named modifier handlers.\n *\n * Keys are modifier names used in the `on-action` attribute syntax\n * (e.g. `click.prevent->action-id`). Values are `ModifierHandler` functions.\n * Populated at module load with built-in modifiers; extended at runtime via\n * `registerModifier`.\n *\n * @internal\n */\nexport const modifierRegistry = new Map<string, ModifierHandler>();\n\n/**\n * Registry of all named payload resolvers.\n *\n * Keys are resolver tokens used in the `on-action` attribute syntax\n * (e.g. `click->action-id:$value`). Values are `PayloadResolver` functions.\n * Populated at module load with built-in resolvers; extended at runtime via\n * `registerPayloadResolver`.\n *\n * @internal\n */\nexport const payloadRegistry = new Map<string, PayloadResolver>();\n\n// ─── Built-in Modifiers ───────────────────────────────────────────────────────\n\n/**\n * `prevent` — calls `event.preventDefault()` before dispatching.\n *\n * Use it to suppress the browser's default behaviour (e.g. form submission,\n * link navigation, context menu).\n *\n * @example `<form on-action=\"submit.prevent->submit-form\">`\n */\nmodifierRegistry.set('prevent', (event) => {\n event.preventDefault();\n return true;\n});\n\n/**\n * `stop` — calls `event.stopPropagation()` before dispatching.\n *\n * Prevents the event from bubbling further up the DOM tree. Useful when a\n * child element should handle a click without triggering a parent's listener.\n *\n * @example `<button on-action=\"click.stop->select-item:42\">`\n */\nmodifierRegistry.set('stop', (event) => {\n event.stopPropagation();\n return true;\n});\n\n/**\n * `validate` — cancels the dispatch if the nearest `<form>` fails validation.\n *\n * Looks for a `<form>` ancestor (or the element itself if it is a form) and\n * calls `checkValidity()`. If the form is invalid the action is not dispatched,\n * allowing native constraint-validation UI to surface errors. If no form is\n * found the dispatch is also cancelled and an accident is logged.\n *\n * Pair with `.prevent` on `submit` events to avoid page reloads:\n *\n * @example `<form on-action=\"submit.prevent.validate->submit-form\" novalidate>`\n */\nmodifierRegistry.set('validate', function () {\n const form = this.element_ instanceof HTMLFormElement ? this.element_ : this.element_.closest('form');\n if (!form) {\n this.logger_.accident('validate_modifier', 'no_form_found', {element: this.element_});\n return false;\n }\n return form.checkValidity();\n});\n\n// ─── Built-in Payload Resolvers ───────────────────────────────────────────────\n\n/**\n * `$value` — resolves to the element's `.value` property at dispatch time.\n *\n * Works with any element that exposes a `value` property: `<input>`,\n * `<textarea>`, `<select>`. Returns `null` for elements without `.value`.\n *\n * @example `<input on-action=\"input->search-query:$value\" />`\n */\npayloadRegistry.set('$value', function () {\n return 'value' in this.element_ ? (this.element_ as {value: unknown}).value : null;\n});\n\n/**\n * `$formdata` — resolves to a plain object of all fields in the nearest `<form>`.\n *\n * Collects entries via `FormData` and converts them to a `Record<string, FormDataEntryValue>`.\n * Looks for a `<form>` ancestor (or the element itself). Returns `null` when no\n * form is found.\n *\n * @example `<form on-action=\"submit.prevent.validate->submit-form\">`\n * ```ts\n * onAction<Record<string, FormDataEntryValue>>('submit-form', (data) => {\n * console.log(data); // {username: 'ali', password: '…'}\n * });\n * ```\n */\npayloadRegistry.set('$formdata', function () {\n const form = this.element_ instanceof HTMLFormElement ? this.element_ : this.element_.closest('form');\n return form ? Object.fromEntries(new FormData(form).entries()) : null;\n});\n",
7
+ "import {internalSignal_, logger_} from './lib.js';\nimport type {SubscribeResult} from '@alwatr/signal';\nimport {modifierRegistry, payloadRegistry, type ModifierHandler, type PayloadResolver} from './registry.js';\n\n// Re-export extension types so consumers can import them from the package root.\nexport type {ModifierHandler, PayloadResolver};\n\n// ─── Core Action API ──────────────────────────────────────────────────────────\n\n/**\n * Subscribes to a named action dispatched anywhere in the application.\n *\n * The handler is invoked every time `dispatchAction(actionId, payload)` is\n * called — whether from an `on-action` directive or from code — and the\n * `actionId` matches. Multiple subscribers for the same `actionId` are all\n * notified in subscription order.\n *\n * The generic parameter `T` narrows the type of the received payload.\n * Defaults to `string`, which covers the common case of attribute-driven\n * literal payloads.\n *\n * @param actionId - The action identifier to listen for (e.g. `'open-drawer'`).\n * @param handler - Callback invoked with the resolved payload each time the\n * action is dispatched. `payload` is `undefined` when the\n * action was dispatched without a value.\n * @returns A `SubscribeResult` with an `unsubscribe()` method for cleanup.\n *\n * @example — basic string payload\n * ```ts\n * import {onAction} from '@alwatr/action';\n *\n * const sub = onAction('open-drawer', (panel) => {\n * openDrawer(panel); // panel === 'settings'\n * });\n *\n * // Stop listening when the component is destroyed\n * sub.unsubscribe();\n * ```\n *\n * @example — typed object payload\n * ```ts\n * import {onAction} from '@alwatr/action';\n *\n * onAction<{productId: number; qty: number}>('add-to-cart', (item) => {\n * cartService.add(item!.productId, item!.qty);\n * });\n * ```\n */\nexport function onAction<T = string>(actionId: string, handler: (payload?: T) => void): SubscribeResult {\n logger_.logMethodArgs?.('onAction', {actionId});\n return internalSignal_.subscribe((signal) => {\n if (signal.actionId === actionId) {\n logger_.logMethodArgs?.('onAction.invoke', {actionId, payload: signal.actionPayload});\n handler(signal.actionPayload as T);\n }\n });\n}\n\n/**\n * Dispatches a named action to all `onAction` subscribers with a matching `actionId`.\n *\n * This is the programmatic counterpart to the `on-action` HTML attribute.\n * Use it when you need to trigger an action from code rather than from a DOM\n * event (e.g. after an async operation completes, or from a service layer).\n *\n * The generic parameter `T` types the payload. Omit it to default to `string`.\n *\n * @param actionId - The action identifier (e.g. `'navigate'`).\n * @param actionPayload - Optional value passed to every matching subscriber.\n *\n * @example — dispatch without payload\n * ```ts\n * import {dispatchAction} from '@alwatr/action';\n *\n * dispatchAction('logout');\n * ```\n *\n * @example — dispatch with a typed payload\n * ```ts\n * import {dispatchAction} from '@alwatr/action';\n *\n * dispatchAction('navigate', '/dashboard');\n * dispatchAction<{code: number}>('show-error', {code: 404});\n * ```\n */\nexport function dispatchAction<T = string>(actionId: string, actionPayload?: T): void {\n logger_.logMethodArgs?.('dispatchAction', {actionId, actionPayload});\n internalSignal_.dispatch({actionId, actionPayload});\n}\n\n// ─── Extension API ────────────────────────────────────────────────────────────\n\n/**\n * Registers a custom modifier that can be used in `on-action` attribute syntax.\n *\n * A modifier is a dot-chained token placed after the event type\n * (e.g. `click.mymod->action-id`). Its handler runs before the payload is\n * resolved and the action is dispatched. Returning `false` cancels the dispatch.\n *\n * Built-in modifiers (`prevent`, `stop`, `validate`, `once`, `passive`) are\n * always available. 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 dots or arrows).\n * @param handler - The `ModifierHandler` function bound to the directive instance.\n *\n * @example — a `confirm` modifier that shows a browser dialog\n * ```ts\n * import {registerModifier} from '@alwatr/action';\n *\n * registerModifier('confirm', function () {\n * return window.confirm('Are you sure?');\n * });\n * ```\n * ```html\n * <button on-action=\"click.confirm->delete-item:42\">Delete</button>\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-action` attribute syntax.\n *\n * A payload resolver is a colon-suffixed token in the attribute value\n * (e.g. `click->action-id:$mytoken`). Its function is called at dispatch time\n * with the directive instance as `this` and the DOM event as the argument.\n * The return value becomes the `actionPayload` passed to `onAction` subscribers.\n *\n * Built-in resolvers (`$value`, `$formdata`) are always available. This function\n * 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 - The `PayloadResolver` function bound to the directive instance.\n *\n * @example — a `$checked` resolver for checkbox state\n * ```ts\n * import {registerPayloadResolver} from '@alwatr/action';\n *\n * registerPayloadResolver('$checked', function () {\n * return (this.element_ as HTMLInputElement).checked;\n * });\n * ```\n * ```html\n * <input type=\"checkbox\" on-action=\"change->toggle-feature:$checked\" />\n * ```\n *\n * @example — a `$dataset-id` resolver for data attributes\n * ```ts\n * registerPayloadResolver('$dataset-id', function () {\n * return (this.element_ as HTMLElement).dataset.id ?? null;\n * });\n * ```\n * ```html\n * <li on-action=\"click->select-item:$dataset-id\" data-id=\"42\">Item</li>\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",
8
+ "import {lazyDirective, Directive} from '@alwatr/directive';\nimport {modifierRegistry, payloadRegistry} from './registry.js';\nimport {dispatchAction} from './method.js';\n\n// ─── Attribute Syntax Parser ──────────────────────────────────────────────────\n\n/**\n * Regex that parses the `on-action` attribute value into its three segments.\n *\n * Full syntax: `eventType[.modifier…]->actionId[:payload]`\n *\n * | Capture group | Matches | Example |\n * | ------------- | ------------------------------------------- | -------------------- |\n * | 1 | Event type + optional dot-chained modifiers | `click.prevent.once` |\n * | 2 | Action identifier | `open-drawer` |\n * | 3 | Optional payload token or literal | `main` / `$value` |\n *\n * @example\n * ```\n * 'click.prevent.once->open-drawer:main' → ['click.prevent.once', 'open-drawer', 'main']\n * 'input->search-query:$value' → ['input', 'search-query', '$value']\n * 'submit.prevent->submit-form' → ['submit.prevent', 'submit-form', undefined]\n * ```\n */\nconst syntaxRegex = /^([a-z0-9.-]+)->([a-z0-9-]+)(?::(.+))?$/;\n\n// ─── Directive Class ──────────────────────────────────────────────────────────\n\n/**\n * Directive that bridges a DOM event to a typed action signal.\n *\n * Activated automatically by the `on-action` HTML attribute when\n * `registerActionDirective()` has been called before `bootstrapDirectives()`.\n * You rarely need to reference this class directly.\n *\n * **Attribute syntax**\n * ```\n * on-action=\"eventType[.modifier…]->actionId[:payload]\"\n * ```\n *\n * - `eventType` — any standard DOM event name (e.g. `click`, `input`, `submit`).\n * - `modifier` — dot-chained tokens processed before dispatch\n * (`prevent`, `stop`, `validate`, `once`, `passive`, or custom).\n * - `actionId` — the identifier passed to `onAction` subscribers.\n * - `payload` — an optional literal string or a `$`-prefixed resolver token\n * (e.g. `$value`, `$formdata`, or custom).\n *\n * @example\n * ```html\n * <!-- Dispatches 'open-drawer' with payload 'settings' on click -->\n * <button on-action=\"click->open-drawer:settings\">Settings</button>\n *\n * <!-- Dispatches 'search-query' with the live input value on every keystroke -->\n * <input on-action=\"input->search-query:$value\" />\n *\n * <!-- Prevents default, validates, then dispatches 'submit-form' with all field values -->\n * <form on-action=\"submit.prevent.validate->submit-form:$formdata\" novalidate>…</form>\n * ```\n */\nexport class ActionDirective extends Directive {\n /**\n * Parsed and validated representation of the `on-action` attribute value.\n *\n * Set during `init_()` after the attribute is successfully parsed against\n * `syntaxRegex`. Remains `undefined` when the attribute value is invalid,\n * which prevents `dispatch_` from running.\n */\n protected actionContext_?: {\n /** The DOM event type to listen for (e.g. `'click'`, `'input'`). */\n eventType: string;\n /** Set of active modifier names (e.g. `{'prevent', 'once'}`). */\n modifiers: ReadonlySet<string>;\n /** The action identifier dispatched to `onAction` subscribers. */\n actionId: string;\n /** Raw payload token from the attribute (literal string or `$`-resolver key). */\n payload?: string;\n };\n\n /**\n * Parses the `on-action` attribute, validates modifiers, and attaches the\n * DOM event listener.\n *\n * Called once by `Directive` after one macrotask following element discovery.\n * If the attribute value is malformed or references an unknown modifier,\n * an accident is logged and the directive becomes a no-op.\n */\n protected override init_(): void {\n this.logger_.logMethodArgs?.('init_', {attributeValue: this.attributeValue});\n\n const match = this.attributeValue.trim().match(syntaxRegex);\n\n if (!match) {\n this.logger_.accident('init_', 'invalid_syntax', {attributeValue: this.attributeValue});\n return;\n }\n\n const [eventType, ...modifierList] = match[1].split('.');\n const actionId = match[2];\n const payload = match[3] as string | undefined;\n\n if (!eventType) {\n this.logger_.accident('init_', 'invalid_syntax', {attributeValue: this.attributeValue});\n return;\n }\n\n // Validate every modifier token against the registry (built-in native\n // options 'once' and 'passive' are handled separately by the listener).\n const modifiers = new Set<string>();\n for (const modifier of modifierList) {\n if (!modifierRegistry.has(modifier) && modifier !== 'once' && modifier !== 'passive') {\n this.logger_.accident('init_', 'invalid_modifier', {attributeValue: this.attributeValue, modifier});\n return;\n }\n modifiers.add(modifier);\n }\n\n // 'prevent' and 'passive' are mutually exclusive: a passive listener cannot\n // call preventDefault(). Log an accident but continue — 'prevent' wins.\n if (modifiers.has('prevent') && modifiers.has('passive')) {\n this.logger_.accident('init_', 'conflicting_modifiers_prevent_passive', {attributeValue: this.attributeValue});\n }\n\n this.actionContext_ = {eventType, modifiers, actionId, payload};\n\n // Bind once so the same function reference is used for both add and remove.\n const listenerOptions: AddEventListenerOptions = {\n once: modifiers.has('once'),\n // 'passive' is only meaningful when 'prevent' is absent.\n passive: modifiers.has('passive') && !modifiers.has('prevent'),\n };\n\n const boundDispatch = this.dispatch_.bind(this);\n this.element_.addEventListener(eventType, boundDispatch, listenerOptions);\n // Register cleanup so the listener is removed when the directive is destroyed\n // (e.g. when the element is removed from the DOM via autoDestructDirectives).\n this.addDestroyHook(() => {\n this.element_.removeEventListener(eventType, boundDispatch, listenerOptions);\n });\n }\n\n /**\n * DOM event handler: runs modifiers, resolves the payload, and dispatches\n * the action signal.\n *\n * Execution order:\n * 1. Each modifier in `actionContext_.modifiers` is called in insertion order.\n * If any returns `false` the method returns early — no action is dispatched.\n * 2. The raw payload token is looked up in `payloadRegistry`. If a resolver\n * is found it is called and its return value replaces the token.\n * 3. `dispatchAction` is called with the resolved payload.\n *\n * @param event - The DOM event that triggered this handler.\n */\n protected dispatch_(event: Event): void {\n this.logger_.logMethodArgs?.('dispatch_', {eventType: event.type, actionId: this.actionContext_?.actionId});\n\n const context = this.actionContext_!;\n\n // Step 1 — run modifiers; any returning false cancels the dispatch.\n for (const mod of context.modifiers) {\n const handler = modifierRegistry.get(mod);\n if (handler && handler.call(this, event) === false) return;\n }\n\n // Step 2 — resolve dynamic payload tokens (e.g. '$value', '$formdata').\n let payload: unknown = context.payload;\n if (payload) {\n const resolver = payloadRegistry.get(payload as string);\n if (resolver) payload = resolver.call(this, event);\n }\n\n // Step 3 — dispatch the action to all onAction subscribers.\n dispatchAction(context.actionId, payload);\n }\n}\n\n// ─── Lazy Registration ────────────────────────────────────────────────────────\n\n/**\n * Registers `ActionDirective` under the `on-action` attribute name.\n *\n * This is a **lazy** registration: calling this function is the only way to\n * opt-in to `on-action` support. If it is never called, the entire directive\n * module (including `ActionDirective`) is tree-shaken from the bundle.\n *\n * Call it once, before `bootstrapDirectives()`, at your application entry point.\n *\n * @example\n * ```ts\n * import {registerActionDirective} from '@alwatr/action';\n * import {bootstrapDirectives} from '@alwatr/directive';\n *\n * registerActionDirective();\n * bootstrapDirectives();\n * ```\n */\nexport const registerActionDirective = lazyDirective('on-action', ActionDirective);\n",
9
+ "import {Directive, lazyDirective} from '@alwatr/directive';\nimport {dispatchAction} from './method.js';\n\n// ─── Directive Class ──────────────────────────────────────────────────────────\n\n/**\n * Directive that announces the current page identity as an action signal.\n *\n * Activated by the `page-id` HTML attribute. On bootstrap the directive reads\n * the attribute value as the page identifier, dispatches a `'page-ready'`\n * action with that value as the payload, and immediately self-destructs — no\n * persistent listener is registered.\n *\n * Typical placement is on the `<body>` or the top-level page container so that\n * any part of the application can react to route changes by subscribing to the\n * `'page-ready'` action via `onAction`.\n *\n * @example\n * ```html\n * <!-- Dispatches dispatchAction('page-ready', 'home') on bootstrap -->\n * <body page-id=\"home\">…</body>\n * ```\n */\nexport class PageIdDirective extends Directive {\n /**\n * Reads the `page-id` attribute value, dispatches `'page-ready'` with it as\n * the payload, then destroys the directive.\n *\n * Logs an accident and returns early if the attribute value is empty.\n */\n protected override init_(): void {\n const pageId = this.attributeValue.trim();\n this.logger_.logMethodArgs?.('init_', {pageId});\n\n if (!pageId) {\n this.logger_.accident('init_', 'empty_page_id');\n return;\n }\n\n dispatchAction('page-ready', pageId);\n this.destroy();\n }\n}\n\n// ─── Lazy Registration ────────────────────────────────────────────────────────\n\n/**\n * Registers `PageIdDirective` under the `page-id` attribute name.\n *\n * This is a **lazy** registration: calling this function is the only way to\n * opt-in to `page-id` support. If it is never called, the entire directive\n * module is tree-shaken from the bundle.\n *\n * Call it once, before `bootstrapDirectives()`, at your application entry point.\n *\n * @example\n * ```ts\n * import {registerPageIdDirective, onAction} from '@alwatr/action';\n * import {bootstrapDirectives} from '@alwatr/directive';\n *\n * registerPageIdDirective();\n * bootstrapDirectives();\n *\n * // React to every page change\n * onAction('page-ready', (pageId) => {\n * console.log('navigated to:', pageId); // e.g. 'home', 'about', 'product-detail'\n * });\n * ```\n *\n * ```html\n * <body page-id=\"home\">…</body>\n * ```\n */\nexport const registerPageIdDirective = lazyDirective('page-id', PageIdDirective);\n"
10
+ ],
11
+ "mappings": "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",
12
+ "debugId": "78292B0ADE08B5FA64756E2164756E21",
13
+ "names": []
14
+ }
@@ -0,0 +1,141 @@
1
+ import type { SubscribeResult } from '@alwatr/signal';
2
+ import { type ModifierHandler, type PayloadResolver } from './registry.js';
3
+ export type { ModifierHandler, PayloadResolver };
4
+ /**
5
+ * Subscribes to a named action dispatched anywhere in the application.
6
+ *
7
+ * The handler is invoked every time `dispatchAction(actionId, payload)` is
8
+ * called — whether from an `on-action` directive or from code — and the
9
+ * `actionId` matches. Multiple subscribers for the same `actionId` are all
10
+ * notified in subscription order.
11
+ *
12
+ * The generic parameter `T` narrows the type of the received payload.
13
+ * Defaults to `string`, which covers the common case of attribute-driven
14
+ * literal payloads.
15
+ *
16
+ * @param actionId - The action identifier to listen for (e.g. `'open-drawer'`).
17
+ * @param handler - Callback invoked with the resolved payload each time the
18
+ * action is dispatched. `payload` is `undefined` when the
19
+ * action was dispatched without a value.
20
+ * @returns A `SubscribeResult` with an `unsubscribe()` method for cleanup.
21
+ *
22
+ * @example — basic string payload
23
+ * ```ts
24
+ * import {onAction} from '@alwatr/action';
25
+ *
26
+ * const sub = onAction('open-drawer', (panel) => {
27
+ * openDrawer(panel); // panel === 'settings'
28
+ * });
29
+ *
30
+ * // Stop listening when the component is destroyed
31
+ * sub.unsubscribe();
32
+ * ```
33
+ *
34
+ * @example — typed object payload
35
+ * ```ts
36
+ * import {onAction} from '@alwatr/action';
37
+ *
38
+ * onAction<{productId: number; qty: number}>('add-to-cart', (item) => {
39
+ * cartService.add(item!.productId, item!.qty);
40
+ * });
41
+ * ```
42
+ */
43
+ export declare function onAction<T = string>(actionId: string, handler: (payload?: T) => void): SubscribeResult;
44
+ /**
45
+ * Dispatches a named action to all `onAction` subscribers with a matching `actionId`.
46
+ *
47
+ * This is the programmatic counterpart to the `on-action` HTML attribute.
48
+ * Use it when you need to trigger an action from code rather than from a DOM
49
+ * event (e.g. after an async operation completes, or from a service layer).
50
+ *
51
+ * The generic parameter `T` types the payload. Omit it to default to `string`.
52
+ *
53
+ * @param actionId - The action identifier (e.g. `'navigate'`).
54
+ * @param actionPayload - Optional value passed to every matching subscriber.
55
+ *
56
+ * @example — dispatch without payload
57
+ * ```ts
58
+ * import {dispatchAction} from '@alwatr/action';
59
+ *
60
+ * dispatchAction('logout');
61
+ * ```
62
+ *
63
+ * @example — dispatch with a typed payload
64
+ * ```ts
65
+ * import {dispatchAction} from '@alwatr/action';
66
+ *
67
+ * dispatchAction('navigate', '/dashboard');
68
+ * dispatchAction<{code: number}>('show-error', {code: 404});
69
+ * ```
70
+ */
71
+ export declare function dispatchAction<T = string>(actionId: string, actionPayload?: T): void;
72
+ /**
73
+ * Registers a custom modifier that can be used in `on-action` attribute syntax.
74
+ *
75
+ * A modifier is a dot-chained token placed after the event type
76
+ * (e.g. `click.mymod->action-id`). Its handler runs before the payload is
77
+ * resolved and the action is dispatched. Returning `false` cancels the dispatch.
78
+ *
79
+ * Built-in modifiers (`prevent`, `stop`, `validate`, `once`, `passive`) are
80
+ * always available. This function lets you add domain-specific ones.
81
+ *
82
+ * Registering the same name twice logs an accident and overwrites the previous
83
+ * handler — avoid duplicate registrations in production code.
84
+ *
85
+ * @param name - The modifier token (lowercase, no dots or arrows).
86
+ * @param handler - The `ModifierHandler` function bound to the directive instance.
87
+ *
88
+ * @example — a `confirm` modifier that shows a browser dialog
89
+ * ```ts
90
+ * import {registerModifier} from '@alwatr/action';
91
+ *
92
+ * registerModifier('confirm', function () {
93
+ * return window.confirm('Are you sure?');
94
+ * });
95
+ * ```
96
+ * ```html
97
+ * <button on-action="click.confirm->delete-item:42">Delete</button>
98
+ * ```
99
+ */
100
+ export declare function registerModifier(name: string, handler: ModifierHandler): void;
101
+ /**
102
+ * Registers a custom payload resolver that can be used in `on-action` attribute syntax.
103
+ *
104
+ * A payload resolver is a colon-suffixed token in the attribute value
105
+ * (e.g. `click->action-id:$mytoken`). Its function is called at dispatch time
106
+ * with the directive instance as `this` and the DOM event as the argument.
107
+ * The return value becomes the `actionPayload` passed to `onAction` subscribers.
108
+ *
109
+ * Built-in resolvers (`$value`, `$formdata`) are always available. This function
110
+ * lets you add domain-specific ones.
111
+ *
112
+ * Registering the same name twice logs an accident and overwrites the previous
113
+ * resolver — avoid duplicate registrations in production code.
114
+ *
115
+ * @param name - The resolver token (should start with `$` by convention).
116
+ * @param resolver - The `PayloadResolver` function bound to the directive instance.
117
+ *
118
+ * @example — a `$checked` resolver for checkbox state
119
+ * ```ts
120
+ * import {registerPayloadResolver} from '@alwatr/action';
121
+ *
122
+ * registerPayloadResolver('$checked', function () {
123
+ * return (this.element_ as HTMLInputElement).checked;
124
+ * });
125
+ * ```
126
+ * ```html
127
+ * <input type="checkbox" on-action="change->toggle-feature:$checked" />
128
+ * ```
129
+ *
130
+ * @example — a `$dataset-id` resolver for data attributes
131
+ * ```ts
132
+ * registerPayloadResolver('$dataset-id', function () {
133
+ * return (this.element_ as HTMLElement).dataset.id ?? null;
134
+ * });
135
+ * ```
136
+ * ```html
137
+ * <li on-action="click->select-item:$dataset-id" data-id="42">Item</li>
138
+ * ```
139
+ */
140
+ export declare function registerPayloadResolver(name: string, resolver: PayloadResolver): void;
141
+ //# sourceMappingURL=method.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"method.d.ts","sourceRoot":"","sources":["../src/method.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAoC,KAAK,eAAe,EAAE,KAAK,eAAe,EAAC,MAAM,eAAe,CAAC;AAG5G,YAAY,EAAC,eAAe,EAAE,eAAe,EAAC,CAAC;AAI/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAgB,QAAQ,CAAC,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,IAAI,GAAG,eAAe,CAQtG;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,cAAc,CAAC,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,CAAC,GAAG,IAAI,CAGpF;AAID;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,IAAI,CAM7E;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,GAAG,IAAI,CAMrF"}
@@ -0,0 +1,57 @@
1
+ import { Directive } from '@alwatr/directive';
2
+ /**
3
+ * Directive that announces the current page identity as an action signal.
4
+ *
5
+ * Activated by the `page-id` HTML attribute. On bootstrap the directive reads
6
+ * the attribute value as the page identifier, dispatches a `'page-ready'`
7
+ * action with that value as the payload, and immediately self-destructs — no
8
+ * persistent listener is registered.
9
+ *
10
+ * Typical placement is on the `<body>` or the top-level page container so that
11
+ * any part of the application can react to route changes by subscribing to the
12
+ * `'page-ready'` action via `onAction`.
13
+ *
14
+ * @example
15
+ * ```html
16
+ * <!-- Dispatches dispatchAction('page-ready', 'home') on bootstrap -->
17
+ * <body page-id="home">…</body>
18
+ * ```
19
+ */
20
+ export declare class PageIdDirective extends Directive {
21
+ /**
22
+ * Reads the `page-id` attribute value, dispatches `'page-ready'` with it as
23
+ * the payload, then destroys the directive.
24
+ *
25
+ * Logs an accident and returns early if the attribute value is empty.
26
+ */
27
+ protected init_(): void;
28
+ }
29
+ /**
30
+ * Registers `PageIdDirective` under the `page-id` attribute name.
31
+ *
32
+ * This is a **lazy** registration: calling this function is the only way to
33
+ * opt-in to `page-id` support. If it is never called, the entire directive
34
+ * module is tree-shaken from the bundle.
35
+ *
36
+ * Call it once, before `bootstrapDirectives()`, at your application entry point.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * import {registerPageIdDirective, onAction} from '@alwatr/action';
41
+ * import {bootstrapDirectives} from '@alwatr/directive';
42
+ *
43
+ * registerPageIdDirective();
44
+ * bootstrapDirectives();
45
+ *
46
+ * // React to every page change
47
+ * onAction('page-ready', (pageId) => {
48
+ * console.log('navigated to:', pageId); // e.g. 'home', 'about', 'product-detail'
49
+ * });
50
+ * ```
51
+ *
52
+ * ```html
53
+ * <body page-id="home">…</body>
54
+ * ```
55
+ */
56
+ export declare const registerPageIdDirective: () => void;
57
+ //# sourceMappingURL=page-id.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-id.d.ts","sourceRoot":"","sources":["../src/page-id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAgB,MAAM,mBAAmB,CAAC;AAK3D;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,eAAgB,SAAQ,SAAS;IAC5C;;;;;OAKG;cACgB,KAAK,IAAI,IAAI;CAYjC;AAID;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,uBAAuB,YAA4C,CAAC"}
@@ -0,0 +1,56 @@
1
+ import type { ActionDirective } from './directive.js';
2
+ /**
3
+ * A modifier handler attached to an `on-action` directive.
4
+ *
5
+ * Called with the directive instance as `this` and the triggering DOM `event`.
6
+ * Return `true` to allow the action to proceed, or `false` to cancel it.
7
+ * Returning `false` is the only way a modifier can veto a dispatch.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * // A modifier that only allows the action when the element is not disabled
12
+ * const notDisabledHandler: ModifierHandler = function () {
13
+ * return !(this.element_ as HTMLButtonElement).disabled;
14
+ * };
15
+ * ```
16
+ */
17
+ export type ModifierHandler = (this: ActionDirective, event: Event) => boolean;
18
+ /**
19
+ * A payload resolver attached to an `on-action` directive.
20
+ *
21
+ * Called with the directive instance as `this` and the triggering DOM `event`
22
+ * at dispatch time. The return value becomes the `actionPayload` of the
23
+ * dispatched action. Use this to compute dynamic payloads from the DOM state.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * // A resolver that returns the element's dataset id
28
+ * const dataIdResolver: PayloadResolver = function () {
29
+ * return (this.element_ as HTMLElement).dataset.id ?? null;
30
+ * };
31
+ * ```
32
+ */
33
+ export type PayloadResolver = (this: ActionDirective, event: Event) => unknown;
34
+ /**
35
+ * Registry of all named modifier handlers.
36
+ *
37
+ * Keys are modifier names used in the `on-action` attribute syntax
38
+ * (e.g. `click.prevent->action-id`). Values are `ModifierHandler` functions.
39
+ * Populated at module load with built-in modifiers; extended at runtime via
40
+ * `registerModifier`.
41
+ *
42
+ * @internal
43
+ */
44
+ export declare const modifierRegistry: Map<string, ModifierHandler>;
45
+ /**
46
+ * Registry of all named payload resolvers.
47
+ *
48
+ * Keys are resolver tokens used in the `on-action` attribute syntax
49
+ * (e.g. `click->action-id:$value`). Values are `PayloadResolver` functions.
50
+ * Populated at module load with built-in resolvers; extended at runtime via
51
+ * `registerPayloadResolver`.
52
+ *
53
+ * @internal
54
+ */
55
+ export declare const payloadRegistry: Map<string, PayloadResolver>;
56
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,gBAAgB,CAAC;AAIpD;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,IAAI,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC;AAE/E;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,IAAI,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC;AAI/E;;;;;;;;;GASG;AACH,eAAO,MAAM,gBAAgB,8BAAqC,CAAC;AAEnE;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,8BAAqC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,85 @@
1
+ {
2
+ "name": "@alwatr/action",
3
+ "version": "9.11.2",
4
+ "description": "Declarative DOM action-dispatch — bridge HTML attributes to typed signal handlers.",
5
+ "license": "MPL-2.0",
6
+ "author": "S. Ali Mihandoost <ali.mihandoost@gmail.com> (https://ali.mihandoost.com)",
7
+ "type": "module",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Alwatr/alwatr",
11
+ "directory": "pkg/nanolib/action"
12
+ },
13
+ "homepage": "https://github.com/Alwatr/alwatr/tree/next/pkg/nanolib/action#readme",
14
+ "bugs": "https://github.com/Alwatr/alwatr/issues",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/main.d.ts",
18
+ "import": "./dist/main.js",
19
+ "default": "./dist/main.js"
20
+ }
21
+ },
22
+ "sideEffects": false,
23
+ "dependencies": {
24
+ "@alwatr/directive": "9.11.2",
25
+ "@alwatr/logger": "9.11.2",
26
+ "@alwatr/signal": "9.11.2"
27
+ },
28
+ "devDependencies": {
29
+ "@alwatr/nano-build": "9.10.1",
30
+ "@alwatr/standard": "9.11.2",
31
+ "@alwatr/type-helper": "9.11.2",
32
+ "@happy-dom/global-registrator": "^20.9.0",
33
+ "typescript": "^6.0.3"
34
+ },
35
+ "scripts": {
36
+ "b": "bun run build",
37
+ "build": "bun run build:ts && bun run build:es",
38
+ "build:es": "nano-build --preset=module-web src/main.ts",
39
+ "build:ts": "tsc --build",
40
+ "cl": "bun run clean",
41
+ "clean": "rm -rfv dist *.tsbuildinfo",
42
+ "format": "prettier --write \"src/**/*.ts\"",
43
+ "lint": "eslint src/ --ext .ts",
44
+ "t": "bun run test",
45
+ "test": "ALWATR_DEBUG=0 bun test",
46
+ "w": "bun run watch",
47
+ "watch": "bun run watch:ts & bun run watch:es",
48
+ "watch:es": "bun run build:es --watch",
49
+ "watch:ts": "bun run build:ts --watch --preserveWatchOutput"
50
+ },
51
+ "files": [
52
+ "dist",
53
+ "src/**/*.ts",
54
+ "!src/**/*.test.ts",
55
+ "README.md",
56
+ "LICENSE"
57
+ ],
58
+ "publishConfig": {
59
+ "access": "public"
60
+ },
61
+ "keywords": [
62
+ "action",
63
+ "alwatr",
64
+ "browser-api",
65
+ "declarative-ui",
66
+ "decorator",
67
+ "directive",
68
+ "dom",
69
+ "esm",
70
+ "event",
71
+ "frontend",
72
+ "javascript",
73
+ "lightweight",
74
+ "module",
75
+ "nanolib",
76
+ "signal",
77
+ "spa",
78
+ "typescript",
79
+ "ui-library",
80
+ "unidirectional-data-flow",
81
+ "vanilla-js",
82
+ "web-development"
83
+ ],
84
+ "gitHead": "ad72dc5b615ab443b1f7e2616ec647574bb04cf5"
85
+ }