@saga-a2ui/lit 0.0.0-stage → 0.7.7-rc.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @saga-a2ui/lit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lit renderer integration for SAGA A2UI. Entry points: the root mounts an application's own A2UI catalog; `/actions` attaches actions to rendered controls; `/faithful-card` supplies the optional FaithfulCard element. Components is optional for own-catalog rendering and required for FaithfulCard.
4
+
5
+ Applications connecting Lit to MCP normally install `@saga-a2ui/lit-mcp-stack` and the Lit peer, and import from the stack only. Lower-level integrations may use this renderer directly with matching SAGA packages.
6
+
7
+ Requires Node >=22.12.0 and a TypeScript-aware bundler; exports are TypeScript source. Apache-2.0, with dependency licenses retained separately.
8
+
9
+ Release candidates use the npm `next` tag. Pin exact published SAGA versions. At the consumer root, override `@a2ui/markdown-it` to `0.2.1`; keep A2UI's Zod 3 and MCP's Zod 4 contexts separate.
10
+
11
+ See [public installation](https://github.com/MachineWisdomAI/saga-a2ui/blob/main/docs/public-install.md) and [release preparation](https://github.com/MachineWisdomAI/saga-a2ui/blob/main/docs/release-packages.md). Source versions and candidate tarballs do not establish registry availability.
package/package.json CHANGED
@@ -1,6 +1 @@
1
- {
2
- "name": "@saga-a2ui/lit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {"name":"@saga-a2ui/lit","private":false,"description":"Lit binding for SAGA A2UI: mounts a core message session's surface with an application's own catalog and owns its disposal, with the optional /actions control and instance host and the optional /faithful-card element","license":"Apache-2.0","type":"module","exports":{".":"./src/index.ts","./actions":"./src/actions/index.ts","./faithful-card":"./src/faithful-card/index.ts"},"files":["src","!src/**/*.test.ts","!src/**/*.test-support.ts"],"scripts":{"typecheck":"tsc --noEmit"},"dependencies":{"@a2ui/lit":"0.13.0","@a2ui/web_core":"0.13.0","@saga-a2ui/core":"0.7.7-rc.1","lit":"^3.3.3"},"peerDependencies":{"@saga-a2ui/components":"0.7.7-rc.1"},"peerDependenciesMeta":{"@saga-a2ui/components":{"optional":true}},"devDependencies":{"@saga-a2ui/components":"0.7.7-rc.1","typescript":"^5.9.0","vitest":"^5.0.4"},"version":"0.7.7-rc.1","engines":{"node":">=22.12.0"},"repository":{"type":"git","url":"https://github.com/MachineWisdomAI/saga-a2ui.git","directory":"packages/lit"},"publishConfig":{"access":"public","tag":"next"}}
@@ -0,0 +1,238 @@
1
+ import { A2uiSurface, type LitComponentApi } from '@a2ui/lit/v0_9';
2
+ import type { Catalog, Subscription, SurfaceModel } from '@a2ui/web_core/v0_9';
3
+ import {
4
+ a2uiV0_9Decoder,
5
+ createMessageSession,
6
+ type IngestFailure,
7
+ type IngestResult,
8
+ type MessageSession,
9
+ type SurfaceLayout,
10
+ type SurfaceUpdateFailure,
11
+ } from '@saga-a2ui/core/protocols/a2ui/v0_9';
12
+ import { LitElement, html, nothing } from 'lit';
13
+ import { createRef, ref } from 'lit/directives/ref.js';
14
+
15
+ export type A2uiSession = MessageSession<LitComponentApi>;
16
+
17
+ /** One presentation of a surface by an app element: what an optional integration needs to know. */
18
+ export interface A2uiSurfaceMount {
19
+ /** The app element presenting the surface. */
20
+ readonly owner: Element;
21
+ readonly surface: SurfaceModel<LitComponentApi>;
22
+ /** The one `<a2ui-surface>` the owner rendered for this presentation, once it has rendered. */
23
+ readonly mount: () => Element | undefined;
24
+ }
25
+
26
+ /**
27
+ * An optional integration that owns per-presentation state, such as the action host of
28
+ * `@saga-a2ui/lit/actions`. The app element starts it for each surface it presents and ends it when
29
+ * that presentation ends. This package defines only the seam, so an application that supplies
30
+ * none carries none of the integration's code.
31
+ */
32
+ export interface A2uiActions {
33
+ /**
34
+ * Starts the integration for one presentation, before the surface renders, and returns the
35
+ * function that ends it. Throwing means the integration could not start: the element then
36
+ * shows its safe fallback and does not render the surface.
37
+ */
38
+ begin(mount: A2uiSurfaceMount): () => void;
39
+ }
40
+
41
+ /** Why `updateData` changed nothing. `message` is plain text that is safe to display. */
42
+ export interface A2uiUpdateFailure {
43
+ readonly kind: SurfaceUpdateFailure['kind'] | IngestFailure['kind'];
44
+ readonly message: string;
45
+ }
46
+
47
+ export type A2uiUpdateResult =
48
+ | { readonly ok: true }
49
+ | { readonly ok: false; readonly failure: A2uiUpdateFailure };
50
+
51
+ export interface A2uiAppDependencies<TData> {
52
+ /**
53
+ * The catalog the surface's components come from. The element builds a fresh session over it
54
+ * on each connect, with the SDK's A2UI decoder, so an application never constructs one.
55
+ */
56
+ readonly catalog: Catalog<LitComponentApi>;
57
+ /** The one surface this element presents: its identity, its data type and how it opens. */
58
+ readonly layout: SurfaceLayout<TData>;
59
+ /** Optional. Started per presented surface and ended with it, on every exit. */
60
+ readonly actions?: A2uiActions;
61
+ /**
62
+ * Optional and advanced; an ordinary application leaves it out. Replaces the default session
63
+ * on each connect, for an application that must observe or wrap the session it is given
64
+ * `catalog`. The element owns and disposes what this returns.
65
+ */
66
+ readonly createSession?: (catalog: Catalog<LitComponentApi>) => A2uiSession;
67
+ }
68
+
69
+ // `a2ui-surface` is defined by importing upstream's A2uiSurface. This package renders it, so this
70
+ // is the one place that import is relied on.
71
+ void A2uiSurface;
72
+
73
+ /**
74
+ * Builds a custom-element class that presents one A2UI surface from a core message session.
75
+ * The application supplies the catalog and the layout and defines the tag; subclass
76
+ * the result to add application chrome or wiring.
77
+ *
78
+ * Lifecycle: connecting creates a session, subscribes, and opens the layout. Disconnecting
79
+ * unsubscribes and disposes the session, so a reconnected element starts fresh and nothing from
80
+ * the retired session can reach the page. The element only presents results: decoding and
81
+ * validation live in the layout and the session.
82
+ *
83
+ * Data: `updateData(data)` validates against the layout and applies it as an A2UI data update. It
84
+ * changes what the mounted controls show without remounting them, so their action bindings and
85
+ * focus survive. A rejected update (invalid data, an element that is not connected, a disposed
86
+ * session) returns a failure and changes nothing: the surface, its data and its fallback state
87
+ * stay as they were. The element has no notion of selection.
88
+ *
89
+ * Failure: a layout the session cannot open (for example a root component the catalog lacks)
90
+ * shows a safe fallback instead of a blank surface.
91
+ *
92
+ * Actions: when `actions` is supplied it starts before each surface is first rendered and ends
93
+ * when that surface is deleted, replaced, or the element disconnects (before the session is
94
+ * disposed). If it cannot start, the surface is not rendered and a safe fallback shows until the
95
+ * surface is created again.
96
+ *
97
+ * Catalog components are custom elements the application defines with `defineElements`.
98
+ */
99
+ export function createA2uiAppElement<TData>(deps: A2uiAppDependencies<TData>) {
100
+ class A2uiApp extends LitElement {
101
+ // Reactive state is declared with `static properties` and `declare`, not with decorators: this
102
+ // package ships TypeScript source that each application compiles with its own settings, and
103
+ // decorator syntax is only valid under the settings the workspace happens to use.
104
+ static override properties = {
105
+ surface: { state: true },
106
+ failure: { state: true },
107
+ presentationFailure: { state: true },
108
+ };
109
+ declare private surface?: SurfaceModel<LitComponentApi>;
110
+ declare private failure?: string;
111
+ declare private presentationFailure?: string;
112
+
113
+ private session?: A2uiSession;
114
+ private subscriptions: Subscription[] = [];
115
+ private endPresentation?: () => void;
116
+ private readonly mount = createRef<Element>();
117
+
118
+ /**
119
+ * Replaces the surface's data. (Not named `update`: Lit's `ReactiveElement.update` is the
120
+ * render lifecycle method of every element built on it.) Validated against the layout, then applied in place: no
121
+ * remount, so the rendered controls, their action bindings and focus survive. Never throws;
122
+ * a rejection returns a failure and leaves data, identity and any fallback unchanged.
123
+ */
124
+ updateData(data: TData): A2uiUpdateResult {
125
+ const messages = deps.layout.update(data);
126
+ if (!messages.ok) return { ok: false, failure: messages.failure };
127
+ return (
128
+ this.session?.ingest(messages.messages) ?? {
129
+ ok: false,
130
+ failure: {
131
+ kind: 'rejected',
132
+ message: 'The app is not connected.',
133
+ },
134
+ }
135
+ );
136
+ }
137
+
138
+ /**
139
+ * Applies unchecked protocol input to the current session, and shows the safe fallback when
140
+ * the session rejects it. Not part of the application contract (use `updateData`): it is for a
141
+ * subclass that relays protocol messages it did not author, such as a host that forwards
142
+ * server-supplied A2UI. Never throws for bad input. Messages applied before a rejection stay
143
+ * applied (there is no atomic rollback); the next input the session accepts clears the
144
+ * fallback.
145
+ */
146
+ protected ingest(input: unknown): IngestResult {
147
+ const result = this.session?.ingest(input) ?? {
148
+ ok: false as const,
149
+ failure: {
150
+ kind: 'rejected' as const,
151
+ message: 'The app is not connected.',
152
+ },
153
+ };
154
+ this.failure = result.ok ? undefined : result.failure.message;
155
+ return result;
156
+ }
157
+
158
+ private present(surface: SurfaceModel<LitComponentApi>) {
159
+ this.closePresentation();
160
+ this.presentationFailure = undefined;
161
+ if (deps.actions) {
162
+ try {
163
+ this.endPresentation = deps.actions.begin({
164
+ owner: this,
165
+ surface,
166
+ mount: () => this.mount.value,
167
+ });
168
+ } catch {
169
+ this.presentationFailure =
170
+ 'The actions for this content could not be attached.';
171
+ return;
172
+ }
173
+ }
174
+ // Lit renders the surface later, so any setup the integration ran is in place by then.
175
+ this.surface = surface;
176
+ }
177
+
178
+ private closePresentation() {
179
+ const end = this.endPresentation;
180
+ this.endPresentation = undefined;
181
+ end?.();
182
+ }
183
+
184
+ connectedCallback() {
185
+ super.connectedCallback();
186
+ const session =
187
+ deps.createSession?.(deps.catalog) ??
188
+ createMessageSession({
189
+ catalogs: [deps.catalog],
190
+ decoder: a2uiV0_9Decoder,
191
+ });
192
+ this.session = session;
193
+ this.subscriptions = [
194
+ session.onSurfaceCreated((surface) => {
195
+ if (surface.id === deps.layout.surfaceId) this.present(surface);
196
+ }),
197
+ session.onSurfaceDeleted((id) => {
198
+ if (id !== deps.layout.surfaceId) return;
199
+ this.closePresentation();
200
+ this.presentationFailure = undefined;
201
+ this.surface = undefined;
202
+ }),
203
+ ];
204
+ this.ingest(deps.layout.opening);
205
+ }
206
+
207
+ disconnectedCallback() {
208
+ super.disconnectedCallback();
209
+ for (const subscription of this.subscriptions) subscription.unsubscribe();
210
+ this.subscriptions = [];
211
+ // The presentation ends before the session it depends on is disposed.
212
+ this.closePresentation();
213
+ this.session?.dispose();
214
+ this.session = undefined;
215
+ this.surface = undefined;
216
+ this.failure = undefined;
217
+ this.presentationFailure = undefined;
218
+ }
219
+
220
+ render() {
221
+ // Failure text is only ever a Lit text binding, so it stays inert.
222
+ const failure = this.failure ?? this.presentationFailure;
223
+ if (failure !== undefined) {
224
+ return html`<div role="alert" data-testid="failure">
225
+ Could not render this content:
226
+ <span data-testid="failure-detail">${failure}</span>
227
+ </div>`;
228
+ }
229
+ return this.surface
230
+ ? html`<a2ui-surface
231
+ ${ref(this.mount)}
232
+ .surface=${this.surface}
233
+ ></a2ui-surface>`
234
+ : nothing;
235
+ }
236
+ }
237
+ return A2uiApp;
238
+ }
@@ -0,0 +1,130 @@
1
+ import { A2uiLitElement, type LitComponentApi } from '@a2ui/lit/v0_9';
2
+ import {
3
+ componentKind,
4
+ type InstanceEvent,
5
+ type OpenInstance,
6
+ } from '@saga-a2ui/core/actions';
7
+ import { html, nothing } from 'lit';
8
+ import { ActionButtonApi } from '@saga-a2ui/core/actions/action-button-schema';
9
+ import { hostOf } from './mount-owner.js';
10
+
11
+ /** The event an `ActionButton` delivers: the instance's data scope plus the DOM click. */
12
+ export type ActionButtonActivation = InstanceEvent<Event>;
13
+
14
+ export interface ActionButtonEvents {
15
+ readonly activate: ActionButtonActivation;
16
+ }
17
+
18
+ /** The kind token application setup passes to `getById` and `watchById`. */
19
+ export const ActionButton = componentKind<ActionButtonEvents>('ActionButton');
20
+
21
+ /**
22
+ * One element class serves every instance of the kind. The instance belongs to the element
23
+ * together with the component model and data path it currently shows: the directive reuses
24
+ * elements, and parents replace `context` on every render, so neither alone is an identity.
25
+ *
26
+ * Upstream decides when a binding changed: `willUpdate` keeps the controller while the same
27
+ * component is shown at the same path and calls `createController()` otherwise, which is the
28
+ * supported seam this override uses. It never relies on `element.node`, which stays unset under
29
+ * `a2ui-surface`.
30
+ *
31
+ * The control has no upstream `action`, so its single click handler is the only activation site.
32
+ * Do not add another click listener to a rendered button as a shortcut: for an upstream Button it
33
+ * would run in addition to the Button's own action.
34
+ */
35
+ export class ActionButtonElement extends A2uiLitElement<
36
+ typeof ActionButtonApi
37
+ > {
38
+ protected readonly api = ActionButtonApi;
39
+ #instance: OpenInstance<ActionButtonEvents> | undefined;
40
+
41
+ protected override createController() {
42
+ this.#retire();
43
+ const controller = super.createController();
44
+ this.#open();
45
+ return controller;
46
+ }
47
+
48
+ override connectedCallback() {
49
+ super.connectedCallback();
50
+ // Reconnecting keeps upstream's controller, so no createController call opens a new instance.
51
+ if (this.controller) this.#open();
52
+ }
53
+
54
+ override disconnectedCallback() {
55
+ super.disconnectedCallback();
56
+ this.#retire();
57
+ }
58
+
59
+ #open() {
60
+ if (this.#instance) return;
61
+ const context = this.context;
62
+ const { surface, path } = context.dataContext;
63
+ // `DataContext.surface` is optional in the 0.13.0 types: without it the control stays unbound.
64
+ if (!surface) return;
65
+ const host = hostOf(this, surface);
66
+ if (!host) return; // not presented by an app element with actions: stay unbound
67
+ const model = context.componentModel;
68
+ // A fresh pull on every call, never a stored answer. Each line closes a different window: the
69
+ // element left the document; the model was removed, replaced or its surface disposed; a parent
70
+ // already gave this element another component's context before its willUpdate has run.
71
+ const isLive = () =>
72
+ this.isConnected &&
73
+ surface.componentsModel.get(model.id) === model &&
74
+ this.context.componentModel === model &&
75
+ this.context.dataContext.path === path;
76
+ this.#instance = host.open<ActionButtonEvents>({
77
+ kind: ActionButton,
78
+ componentId: model.id,
79
+ dataPath: path,
80
+ events: ['activate'],
81
+ isLive,
82
+ // This instance's own scope, not this.context, which a same-tag reuse may already have replaced.
83
+ read: (dataPath) =>
84
+ isLive()
85
+ ? context.dataContext.resolveDynamicValue<unknown>({ path: dataPath })
86
+ : undefined,
87
+ // The runtime holds this only while an invocation is not settled. `DataModel.subscribe` calls
88
+ // back synchronously inside `set` and also for an ancestor or descendant of the scope's path;
89
+ // the microtask lets the whole change finish before the runtime reads the application's
90
+ // subject, so an A, B, A inside one call stack is not seen, and it runs before the next click.
91
+ // A subject that reads state outside the data model gets no wake-up here, only the runtime's
92
+ // own checkpoints.
93
+ watchScope: (revalidate) => {
94
+ const subscription = surface.dataModel.subscribe(path, () =>
95
+ queueMicrotask(revalidate),
96
+ );
97
+ return () => subscription.unsubscribe();
98
+ },
99
+ });
100
+ }
101
+
102
+ #retire() {
103
+ this.#instance?.retire();
104
+ this.#instance = undefined;
105
+ }
106
+
107
+ protected override render() {
108
+ const props = this.controller?.props;
109
+ if (!props) return nothing;
110
+ return html`<button
111
+ type="button"
112
+ ?disabled=${props.isValid === false}
113
+ @click=${this.#onClick}
114
+ >
115
+ ${props.child ? this.renderNode(props.child) : nothing}
116
+ </button>`;
117
+ }
118
+
119
+ #onClick = (event: Event) => {
120
+ if (this.controller?.props?.isValid === false) return; // the same check the upstream Button makes
121
+ this.#instance?.activate('activate', event);
122
+ };
123
+ }
124
+
125
+ /** The catalog entry. An application lists it in its own catalog and passes it to `defineElements`. */
126
+ export const actionButtonEntry = {
127
+ ...ActionButtonApi,
128
+ tagName: 'saga-action-button',
129
+ element: ActionButtonElement,
130
+ } satisfies LitComponentApi;
@@ -0,0 +1,12 @@
1
+ // Optional Lit integration for direct action attachment. An application that lists none of this
2
+ // in its catalog carries none of it: the main `@saga-a2ui/lit` entry does not import this module.
3
+ export {
4
+ ActionButton,
5
+ ActionButtonElement,
6
+ actionButtonEntry,
7
+ } from './action-button.js';
8
+ export type {
9
+ ActionButtonActivation,
10
+ ActionButtonEvents,
11
+ } from './action-button.js';
12
+ export { createLitActions, type LitActionsOptions } from './lit-actions.js';