@littlepress/renderer-web 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +20 -0
  3. package/README.md +229 -2
  4. package/dist/answer/answerComponents.d.ts +107 -0
  5. package/dist/answer/answerComponents.js +637 -0
  6. package/dist/answer/download.d.ts +63 -0
  7. package/dist/answer/download.js +109 -0
  8. package/dist/answer/downloadExport.d.ts +44 -0
  9. package/dist/answer/downloadExport.js +266 -0
  10. package/dist/answer/hostValues.d.ts +28 -0
  11. package/dist/answer/hostValues.js +379 -0
  12. package/dist/answer/mapComponent.d.ts +6 -0
  13. package/dist/answer/mapComponent.js +213 -0
  14. package/dist/answer/math.d.ts +57 -0
  15. package/dist/answer/math.js +168 -0
  16. package/dist/answer/surfaceStream.d.ts +51 -0
  17. package/dist/answer/surfaceStream.js +260 -0
  18. package/dist/answer/tableLayout.d.ts +42 -0
  19. package/dist/answer/tableLayout.js +89 -0
  20. package/dist/controls/ActionFeedback.d.ts +5 -0
  21. package/dist/controls/ActionFeedback.js +43 -0
  22. package/dist/controls/actionDispatch.d.ts +51 -0
  23. package/dist/controls/actionDispatch.js +211 -0
  24. package/dist/controls/actionOutcome.generated.d.ts +64 -0
  25. package/dist/controls/actionOutcome.generated.js +64 -0
  26. package/dist/controls/calculationPublisher.d.ts +14 -0
  27. package/dist/controls/calculationPublisher.js +6 -0
  28. package/dist/controls/calculations.d.ts +20 -0
  29. package/dist/controls/calculations.generated.d.ts +73 -0
  30. package/dist/controls/calculations.generated.js +85 -0
  31. package/dist/controls/calculations.js +208 -0
  32. package/dist/controls/controlState.d.ts +84 -0
  33. package/dist/controls/controlState.js +256 -0
  34. package/dist/controls/fieldMessages.d.ts +41 -0
  35. package/dist/controls/fieldMessages.js +81 -0
  36. package/dist/controls/fieldValidation.d.ts +19 -0
  37. package/dist/controls/fieldValidation.js +98 -0
  38. package/dist/controls/formComponents.d.ts +23 -0
  39. package/dist/controls/formComponents.js +738 -0
  40. package/dist/controls/formProgress.d.ts +63 -0
  41. package/dist/controls/formProgress.js +122 -0
  42. package/dist/controls/inputDrafts.d.ts +55 -0
  43. package/dist/controls/inputDrafts.js +183 -0
  44. package/dist/controls/inputValidation.d.ts +33 -0
  45. package/dist/controls/inputValidation.js +119 -0
  46. package/dist/controls/localWrites.d.ts +9 -0
  47. package/dist/controls/localWrites.js +29 -0
  48. package/dist/core/A2uiSurface.d.ts +13 -0
  49. package/dist/core/A2uiSurface.js +15 -0
  50. package/dist/core/AtlasIcon.d.ts +18 -0
  51. package/dist/core/AtlasIcon.js +22 -0
  52. package/dist/core/AtlasMedia.d.ts +22 -0
  53. package/dist/core/AtlasMedia.js +45 -0
  54. package/dist/core/Carousel.d.ts +61 -0
  55. package/dist/core/Carousel.js +183 -0
  56. package/dist/core/CoreMedia.d.ts +19 -0
  57. package/dist/core/CoreMedia.js +25 -0
  58. package/dist/core/FoundationA2uiSurface.d.ts +86 -0
  59. package/dist/core/FoundationA2uiSurface.js +440 -0
  60. package/dist/core/ImagePreview.d.ts +42 -0
  61. package/dist/core/ImagePreview.js +73 -0
  62. package/dist/core/LucideIcon.d.ts +19 -0
  63. package/dist/core/LucideIcon.js +42 -0
  64. package/dist/core/SurfaceLink.d.ts +35 -0
  65. package/dist/core/SurfaceLink.js +60 -0
  66. package/dist/core/appearance/aegis.d.ts +49 -0
  67. package/dist/core/appearance/aegis.js +34 -0
  68. package/dist/core/appearance/colour.d.ts +24 -0
  69. package/dist/core/appearance/colour.js +103 -0
  70. package/dist/core/appearance/css.d.ts +17 -0
  71. package/dist/core/appearance/css.js +153 -0
  72. package/dist/core/appearance/presets.generated.d.ts +4 -0
  73. package/dist/core/appearance/presets.generated.js +1184 -0
  74. package/dist/core/appearance/react.d.ts +29 -0
  75. package/dist/core/appearance/react.js +110 -0
  76. package/dist/core/appearance/resolve.d.ts +76 -0
  77. package/dist/core/appearance/resolve.js +127 -0
  78. package/dist/core/appearance/textScale.d.ts +11 -0
  79. package/dist/core/appearance/textScale.js +51 -0
  80. package/dist/core/appearance/theme.d.ts +138 -0
  81. package/dist/core/appearance/theme.js +274 -0
  82. package/dist/core/baseComponents.d.ts +53 -0
  83. package/dist/core/baseComponents.js +480 -0
  84. package/dist/core/binding.d.ts +46 -0
  85. package/dist/core/binding.js +118 -0
  86. package/dist/core/bundle.d.ts +23 -0
  87. package/dist/core/bundle.js +75 -0
  88. package/dist/core/catalog/catalog-index.generated.d.ts +44 -0
  89. package/dist/core/catalog/catalog-index.generated.js +79 -0
  90. package/dist/core/catalog/icons.generated.d.ts +6 -0
  91. package/dist/core/catalog/icons.generated.js +1788 -0
  92. package/dist/core/catalog.d.ts +6 -0
  93. package/dist/core/catalog.generated.d.ts +50 -0
  94. package/dist/core/catalog.generated.js +2174 -0
  95. package/dist/core/catalog.js +8 -0
  96. package/dist/core/chartRows.d.ts +7 -0
  97. package/dist/core/chartRows.js +38 -0
  98. package/dist/core/component-support.d.ts +39 -0
  99. package/dist/core/component-support.js +127 -0
  100. package/dist/core/components/actions.d.ts +4 -0
  101. package/dist/core/components/actions.js +21 -0
  102. package/dist/core/components/cards.d.ts +9 -0
  103. package/dist/core/components/cards.js +227 -0
  104. package/dist/core/components/charts.d.ts +18 -0
  105. package/dist/core/components/charts.js +412 -0
  106. package/dist/core/components/comparisonTable.d.ts +50 -0
  107. package/dist/core/components/comparisonTable.js +89 -0
  108. package/dist/core/components/content.d.ts +13 -0
  109. package/dist/core/components/content.js +108 -0
  110. package/dist/core/components/seriesCharts.d.ts +531 -0
  111. package/dist/core/components/seriesCharts.js +1053 -0
  112. package/dist/core/components/stepFlow.d.ts +7 -0
  113. package/dist/core/components/stepFlow.js +13 -0
  114. package/dist/core/components.full.d.ts +10 -0
  115. package/dist/core/components.full.js +41 -0
  116. package/dist/core/context.d.ts +207 -0
  117. package/dist/core/context.js +172 -0
  118. package/dist/core/coverage.d.ts +30 -0
  119. package/dist/core/coverage.js +93 -0
  120. package/dist/core/foundation.d.ts +21 -0
  121. package/dist/core/foundation.js +22 -0
  122. package/dist/core/fullTheme.d.ts +5 -0
  123. package/dist/core/fullTheme.js +9 -0
  124. package/dist/core/iconNodes.generated.d.ts +7 -0
  125. package/dist/core/iconNodes.generated.js +5 -0
  126. package/dist/core/lucideIcons.d.ts +5 -0
  127. package/dist/core/lucideIcons.js +7 -0
  128. package/dist/core/messages.d.ts +111 -0
  129. package/dist/core/messages.js +134 -0
  130. package/dist/core/pointer.d.ts +17 -0
  131. package/dist/core/pointer.js +104 -0
  132. package/dist/core/registry.d.ts +12 -0
  133. package/dist/core/registry.js +114 -0
  134. package/dist/core/runtime.d.ts +8 -0
  135. package/dist/core/runtime.js +6 -0
  136. package/dist/core/state.d.ts +73 -0
  137. package/dist/core/state.js +274 -0
  138. package/dist/core/surfaceMotion.d.ts +5 -0
  139. package/dist/core/surfaceMotion.js +46 -0
  140. package/dist/core/theme.d.ts +5 -0
  141. package/dist/core/theme.js +7 -0
  142. package/dist/core/useSurfaceImage.d.ts +20 -0
  143. package/dist/core/useSurfaceImage.js +65 -0
  144. package/dist/graph/RelationshipGraph.d.ts +14 -0
  145. package/dist/graph/RelationshipGraph.js +206 -0
  146. package/dist/graph/model.d.ts +20 -0
  147. package/dist/graph/model.js +36 -0
  148. package/dist/graph/program/assets.d.ts +3 -0
  149. package/dist/graph/program/assets.js +3 -0
  150. package/dist/graph/program/bridge.d.ts +6 -0
  151. package/dist/graph/program/bridge.generated.d.ts +136 -0
  152. package/dist/graph/program/bridge.generated.js +1 -0
  153. package/dist/graph/program/bridge.js +24 -0
  154. package/dist/graph/program/bridge.schema.json +717 -0
  155. package/dist/graph/program/bridgeValidator.cjs +2 -0
  156. package/dist/graph/program/bridgeValidator.d.cts +4 -0
  157. package/dist/graph/program/runner.d.ts +1 -0
  158. package/dist/graph/program/runner.html +2193 -0
  159. package/dist/graph/program/runner.js +157 -0
  160. package/dist/graph/program/runtime-manifest.json +1 -0
  161. package/dist/graph/program/view.d.ts +11 -0
  162. package/dist/graph/program/view.js +210 -0
  163. package/dist/graph/program/worker.d.ts +1 -0
  164. package/dist/graph/program/worker.js +2186 -0
  165. package/dist/index.d.ts +20 -0
  166. package/dist/index.js +45 -0
  167. package/dist/internal/dsh.d.ts +4 -0
  168. package/dist/internal/dsh.js +3 -0
  169. package/dist/internal/relationship-graph.d.ts +4 -0
  170. package/dist/internal/relationship-graph.js +7202 -0
  171. package/dist/page/layoutComponents.d.ts +6 -0
  172. package/dist/page/layoutComponents.js +123 -0
  173. package/dist/page/layoutGeometry.d.ts +68 -0
  174. package/dist/page/layoutGeometry.js +174 -0
  175. package/dist/page/pageFormat.d.ts +34 -0
  176. package/dist/page/pageFormat.js +119 -0
  177. package/dist/page/printFit.d.ts +81 -0
  178. package/dist/page/printFit.js +338 -0
  179. package/dist/react/index.d.ts +5 -0
  180. package/dist/react/index.js +2 -0
  181. package/dist/report/locate.d.ts +42 -0
  182. package/dist/report/locate.js +34 -0
  183. package/dist/styles/renderer.css +4580 -0
  184. package/licenses/LUCIDE-LICENSE.txt +43 -0
  185. package/licenses/QUICKJS-EMSCRIPTEN-LICENSE.txt +21 -0
  186. package/licenses/QUICKJS-VARIANT-LICENSE.txt +47 -0
  187. package/package.json +68 -3
@@ -0,0 +1,738 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { resolveStringList, resolveValue, } from "../core/binding.js";
4
+ import { readPointer } from "../core/pointer.js";
5
+ import { firstInvalidPanelIndex, formatSliderValue, formSubmitIsEnabled, inputEntryHints, normalizeControlOptions, normalizeSliderMarks, selectVisibleSliderMarkLabels, } from "./controlState.js";
6
+ import { surfaceIsStreaming } from "./actionDispatch.js";
7
+ import { formKeyOf, renderedFieldKey, toggleAvailableChoice, validateControlValue } from "./inputDrafts.js";
8
+ import { fieldCopy, fieldErrorMessage, isChineseLanguage, surfaceLanguage } from "./fieldMessages.js";
9
+ import { formProgressCopy, formSubmitState, requiredFieldsLeftCopy, requiredShown, validateForm } from "./formProgress.js";
10
+ import { LucideIcon, isLucideIconName } from "../core/LucideIcon.js";
11
+ import { actionIsBlocked, childContext, resolveAction, } from "../core/context.js";
12
+ import { accessibilityLabel, numberValue, renderChildren, surfaceLocale, text, withFallback, } from "../core/baseComponents.js";
13
+ import { RenderComponent } from "../core/registry.js";
14
+ const inputTypes = new Set(["text", "email", "tel", "url", "number", "date", "time", "datetime-local", "textarea", "password"]);
15
+ const boundedInputTypes = new Set(["date", "time", "datetime-local"]);
16
+ // `key` marks the field's wrapper so A2uiSurface can find it again after a discard.
17
+ function controlIdentity(component, context) {
18
+ return {
19
+ key: renderedFieldKey(context.state, context.ancestors, component, context.itemId),
20
+ fieldId: typeof component.fieldId === "string" ? component.fieldId : component.id,
21
+ path: typeof component.valuePath === "string" && component.valuePath.startsWith("/data/")
22
+ ? component.valuePath
23
+ : null,
24
+ };
25
+ }
26
+ function describedBy(...ids) {
27
+ const present = ids.filter((id) => Boolean(id));
28
+ return present.length > 0 ? present.join(" ") : undefined;
29
+ }
30
+ export function isControlDisabled(component, context) {
31
+ return component.disabled === true || surfaceIsStreaming(context.state);
32
+ }
33
+ /**
34
+ * The local message a field shows. Inside a form, a field the user has not changed shows none
35
+ * until the form refuses a submit; a stale draft always says so, since only an edit leaves one.
36
+ */
37
+ function shownError(local, key, context) {
38
+ const form = context.form;
39
+ if (!local || !form || form.showErrors || form.touched.has(key) || local.errorCode === "draft_unavailable")
40
+ return local;
41
+ return null;
42
+ }
43
+ export function emitInputChange(component, context, fieldId, path, value, valid, errorCode) {
44
+ if (!path || surfaceIsStreaming(context.state))
45
+ return;
46
+ context.form?.touch(renderedFieldKey(context.state, context.ancestors, component, context.itemId));
47
+ context.onInputChange?.({
48
+ surfaceId: context.state.surfaceId,
49
+ componentId: component.id,
50
+ component: component.component,
51
+ fieldId,
52
+ path,
53
+ ...(context.itemId ? { itemId: context.itemId } : {}),
54
+ value,
55
+ valid,
56
+ errorCode,
57
+ });
58
+ }
59
+ function scheduleFirstInvalidFocus(event) {
60
+ const firstInvalid = event.currentTarget.querySelector("input:invalid, select:invalid, textarea:invalid");
61
+ if (firstInvalid !== event.target)
62
+ return;
63
+ event.preventDefault();
64
+ const focus = () => firstInvalid.focus();
65
+ if (typeof requestAnimationFrame === "function")
66
+ requestAnimationFrame(focus);
67
+ else
68
+ queueMicrotask(focus);
69
+ }
70
+ function RequiredMark() {
71
+ return _jsx("span", { "aria-hidden": "true", children: "*" });
72
+ }
73
+ function InputField({ component, context }) {
74
+ const generatedId = useId();
75
+ const controlRef = useRef(null);
76
+ const { fieldId, path, key } = controlIdentity(component, context);
77
+ const label = text(component, "label", context);
78
+ const value = path ? readPointer(context.binding.dataModel, path) : null;
79
+ const currentValue = typeof value === "string" || typeof value === "number" ? String(value) : "";
80
+ // leadingIcon, placeholder and hint are declared on lp.input-field; the native
81
+ // renderers already show all three.
82
+ const icon = text(component, "leadingIcon", context);
83
+ const placeholder = text(component, "placeholder", context);
84
+ const hint = text(component, "hint", context);
85
+ const declaredInputType = inputTypes.has(String(component.inputType)) ? String(component.inputType) : "text";
86
+ const secret = declaredInputType === "password";
87
+ const inputType = component.validation === "integer" && !secret ? "text" : declaredInputType;
88
+ // A password shows as dots until the person asks to see it; the toggle never reads it out.
89
+ const [revealed, setRevealed] = useState(false);
90
+ const compositionInProgress = useRef(false);
91
+ const [compositionText, setCompositionText] = useState(null);
92
+ const min = boundedInputTypes.has(inputType) && typeof component.min === "string" ? component.min : undefined;
93
+ const max = boundedInputTypes.has(inputType) && typeof component.max === "string" ? component.max : undefined;
94
+ const local = validateControlValue(component, context.binding, currentValue, context.valueFunctions, context.state.dataModel);
95
+ // The Host's own verdict on the value, such as "already registered". Compose and SwiftUI
96
+ // draw it the same way. It never blocks submission: the Host checks the submitted value
97
+ // again, and a stale message must not trap the user.
98
+ const hostError = text(component, "error", context)?.trim() || null;
99
+ const shown = shownError(local, key, context);
100
+ const errorMessage = shown ? fieldErrorMessage(shown, component, surfaceLocale(context)) : hostError;
101
+ const controlId = `${generatedId}-${fieldId}`;
102
+ const hintId = hint ? `${controlId}-hint` : null;
103
+ const errorId = errorMessage ? `${controlId}-error` : null;
104
+ useEffect(() => {
105
+ controlRef.current?.setCustomValidity(local ? fieldErrorMessage(local, component, surfaceLocale(context)) : "");
106
+ }, [local?.message]);
107
+ // The keyboard follows what the field accepts; see `inputEntryHints`.
108
+ const hints = inputEntryHints(inputType, component.validation);
109
+ const disabled = isControlDisabled(component, context);
110
+ const lastNotifiedValue = useRef(null);
111
+ useLayoutEffect(() => { lastNotifiedValue.current = null; }, [currentValue, key]);
112
+ const commitValue = (nextValue) => {
113
+ if (disabled)
114
+ return;
115
+ if (nextValue === currentValue || nextValue === lastNotifiedValue.current)
116
+ return;
117
+ lastNotifiedValue.current = nextValue;
118
+ const next = validateControlValue(component, context.binding, nextValue, context.valueFunctions, context.state.dataModel);
119
+ emitInputChange(component, context, fieldId, path, nextValue, next === null, next?.errorCode ?? null);
120
+ };
121
+ const sharedProps = {
122
+ inputMode: hints.inputMode,
123
+ autoComplete: hints.autoComplete,
124
+ autoCapitalize: hints.autoCapitalize,
125
+ spellCheck: hints.spellCheck,
126
+ ref: (node) => { controlRef.current = node; },
127
+ id: controlId,
128
+ name: fieldId,
129
+ value: compositionText ?? currentValue,
130
+ placeholder: placeholder ?? undefined,
131
+ required: requiredShown(component),
132
+ disabled,
133
+ "aria-invalid": Boolean(errorMessage),
134
+ "aria-describedby": describedBy(hintId, errorId),
135
+ "aria-errormessage": errorId ?? undefined,
136
+ onChange: (event) => {
137
+ const nextValue = event.currentTarget.value;
138
+ if (compositionInProgress.current) {
139
+ setCompositionText(nextValue);
140
+ return;
141
+ }
142
+ commitValue(nextValue);
143
+ },
144
+ onCompositionStart: () => {
145
+ compositionInProgress.current = true;
146
+ setCompositionText(currentValue);
147
+ },
148
+ onCompositionEnd: (event) => {
149
+ if (!compositionInProgress.current)
150
+ return;
151
+ compositionInProgress.current = false;
152
+ setCompositionText(null);
153
+ commitValue(event.currentTarget.value);
154
+ },
155
+ };
156
+ return withFallback(component, Boolean(label && path), (_jsxs("div", { className: "lp-field", "data-invalid": errorMessage ? "true" : undefined, "data-a2ui-field": key, children: [_jsxs("label", { className: "lp-field-label", htmlFor: controlId, children: [label, requiredShown(component) ? _jsx(RequiredMark, {}) : null] }), _jsxs("span", { className: "lp-field-shell", children: [isLucideIconName(icon) ? _jsx(LucideIcon, { name: icon, size: "sm", tone: "muted" }) : null, inputType === "textarea" ? (_jsx("textarea", { ...sharedProps, onInput: sharedProps.onChange, rows: typeof component.rows === "number" && Number.isInteger(component.rows) && component.rows >= 2 && component.rows <= 12
157
+ ? component.rows
158
+ : 4 })) : (_jsx("input", { ...sharedProps, onInput: sharedProps.onChange, type: secret && revealed ? "text" : inputType, min: min, max: max })), secret ? (_jsx(PasswordToggle, { controlId: controlId, revealed: revealed, disabled: disabled, context: context, onToggle: () => setRevealed((shown) => !shown) })) : null] }), hint ? _jsx("span", { id: hintId ?? undefined, className: "lp-field-hint", children: hint }) : null, errorMessage ? (
159
+ // A Host error arrives after the user acted, so it is announced when it appears;
160
+ // local messages follow typing and are read through aria-describedby instead.
161
+ _jsx("span", { id: errorId ?? undefined, className: "lp-field-error", role: shown ? undefined : "alert", children: errorMessage })) : null] })));
162
+ }
163
+ /**
164
+ * Shows or hides a password field's value. Its name says what pressing it does, so a screen
165
+ * reader hears "Show password" or "Hide password" and never the value itself.
166
+ */
167
+ export function PasswordToggle({ controlId, revealed, disabled, context, onToggle }) {
168
+ const copy = fieldCopy(surfaceLocale(context));
169
+ return (_jsx("button", { type: "button", className: "lp-field-reveal", "aria-controls": controlId, "aria-label": revealed ? copy.hidePassword : copy.showPassword, disabled: disabled, onClick: onToggle, children: _jsx(LucideIcon, { name: revealed ? "eye-off" : "eye", size: "sm", decorative: true }) }));
170
+ }
171
+ export const renderInputField = (component, context) => _jsx(InputField, { component: component, context: context });
172
+ function selectionCopy(context) {
173
+ const chinese = isChineseLanguage(surfaceLanguage(context.state.rendererHints));
174
+ return chinese ? {
175
+ clear: "清除选择", empty: "请选择", unavailable: "原选择已不可用",
176
+ recovery: "原选择已不可用。请选择其他选项,或清除选择。",
177
+ requiredRecovery: "原选择已不可用。请选择其他选项。",
178
+ clearRecovery: "原选择已不可用。请清除选择。",
179
+ gone: "原选择已不可用。",
180
+ } : {
181
+ clear: "Clear selection", empty: "Choose an option", unavailable: "Unavailable selection",
182
+ recovery: "This selection is no longer available. Choose another option or clear the selection.",
183
+ requiredRecovery: "This selection is no longer available. Choose another option.",
184
+ clearRecovery: "This selection is no longer available. Clear the selection.",
185
+ gone: "This selection is no longer available.",
186
+ };
187
+ }
188
+ function choiceValidation(component, context, value) {
189
+ const error = validateControlValue(component, context.binding, value, context.valueFunctions, context.state.dataModel);
190
+ if (error?.errorCode !== "draft_unavailable")
191
+ return error;
192
+ const copy = selectionCopy(context);
193
+ // Name only the ways out this field offers; with no option left to pick, the surface's
194
+ // status offers to discard the change.
195
+ const pickable = normalizeControlOptions(resolveValue(component.options, context.binding, context.valueFunctions)).some(option => !option.disabled);
196
+ const required = component.required === true;
197
+ return { errorCode: "draft_unavailable", message: pickable
198
+ ? required ? copy.requiredRecovery : copy.recovery
199
+ : required ? copy.gone : copy.clearRecovery };
200
+ }
201
+ function SelectControl({ component, context }) {
202
+ const generatedId = useId();
203
+ const controlRef = useRef(null);
204
+ const copy = selectionCopy(context);
205
+ const { fieldId, path, key } = controlIdentity(component, context);
206
+ const label = text(component, "label", context);
207
+ const placeholder = text(component, "placeholder", context);
208
+ const options = normalizeControlOptions(resolveValue(component.options, context.binding, context.valueFunctions));
209
+ const bound = path ? readPointer(context.binding.dataModel, path) : null;
210
+ const currentValue = typeof bound === "string" ? bound : "";
211
+ const required = component.required === true;
212
+ const disabled = isControlDisabled(component, context);
213
+ const local = choiceValidation(component, context, currentValue);
214
+ const shown = shownError(local, key, context);
215
+ const controlId = `${generatedId}-${fieldId}`;
216
+ const errorId = shown ? `${controlId}-error` : null;
217
+ useEffect(() => { controlRef.current?.setCustomValidity(local?.message ?? ""); }, [local?.message]);
218
+ return withFallback(component, Boolean(label && path), (_jsxs("div", { className: "lp-field", "data-invalid": shown ? "true" : undefined, "data-a2ui-field": key, children: [_jsxs("label", { className: "lp-field-label", htmlFor: controlId, children: [label, requiredShown(component) ? _jsx(RequiredMark, {}) : null] }), _jsx("span", { className: "lp-field-shell", children: _jsxs("select", { ref: controlRef, id: controlId, name: fieldId, value: currentValue, required: requiredShown(component), disabled: disabled, "aria-invalid": Boolean(shown), "aria-describedby": errorId ?? undefined, "aria-errormessage": errorId ?? undefined, onChange: (event) => {
219
+ if (disabled)
220
+ return;
221
+ const nextValue = event.currentTarget.value;
222
+ const next = validateControlValue(component, context.binding, nextValue, context.valueFunctions, context.state.dataModel);
223
+ emitInputChange(component, context, fieldId, path, nextValue, next === null, next?.errorCode ?? null);
224
+ }, children: [!required || placeholder || currentValue === "" ? _jsx("option", { value: "", children: placeholder ?? copy.empty }) : null, currentValue && !options.some(option => option.value === currentValue) ? _jsx("option", { value: currentValue, disabled: true, children: copy.unavailable }) : null, options.map((option) => (_jsx("option", { value: option.value, disabled: option.disabled, children: option.label }, option.value)))] }) }), !required && currentValue !== "" ? _jsx("button", { type: "button", className: "lp-btn ghost", disabled: disabled, "aria-label": `${copy.clear}: ${label}`, onClick: () => {
225
+ if (disabled)
226
+ return;
227
+ controlRef.current?.focus();
228
+ emitInputChange(component, context, fieldId, path, "", true, null);
229
+ }, children: copy.clear }) : null, shown ? _jsx("span", { id: errorId ?? undefined, className: "lp-field-error", children: shown.message }) : null] })));
230
+ }
231
+ function CheckboxControl({ component, context }) {
232
+ const generatedId = useId();
233
+ const { fieldId, path, key } = controlIdentity(component, context);
234
+ const label = text(component, "label", context);
235
+ const bound = path ? readPointer(context.binding.dataModel, path) : null;
236
+ const checked = bound === true;
237
+ const required = requiredShown(component);
238
+ const disabled = isControlDisabled(component, context);
239
+ const lineThrough = component.lineThrough === true && checked;
240
+ const local = shownError(validateControlValue(component, context.binding, checked, context.valueFunctions, context.state.dataModel), key, context);
241
+ const controlId = `${generatedId}-${fieldId}`;
242
+ const errorId = local ? `${controlId}-error` : null;
243
+ return withFallback(component, Boolean(label && path), (_jsxs("div", { className: "lp-field lp-check-field", "data-invalid": local ? "true" : undefined, "data-a2ui-field": key, children: [_jsxs("span", { className: "lp-check-option", "data-line-through": lineThrough ? "true" : undefined, children: [_jsx("input", { id: controlId, name: fieldId, type: "checkbox", checked: checked, required: required, disabled: disabled, "aria-invalid": Boolean(local), "aria-describedby": errorId ?? undefined, "aria-errormessage": errorId ?? undefined, onChange: (event) => {
244
+ if (disabled)
245
+ return;
246
+ const nextValue = event.currentTarget.checked;
247
+ const next = validateControlValue(component, context.binding, nextValue, context.valueFunctions, context.state.dataModel);
248
+ emitInputChange(component, context, fieldId, path, nextValue, next === null, next?.errorCode ?? null);
249
+ } }), _jsxs("label", { htmlFor: controlId, children: [label, required ? _jsx(RequiredMark, {}) : null] })] }), local ? _jsx("span", { id: errorId ?? undefined, className: "lp-field-error", children: local.message }) : null] })));
250
+ }
251
+ function ChoiceGroup({ component, context }) {
252
+ const generatedId = useId();
253
+ const groupRef = useRef(null);
254
+ const copy = selectionCopy(context);
255
+ const firstInputRef = useRef(null);
256
+ const { fieldId, path, key } = controlIdentity(component, context);
257
+ const label = text(component, "label", context);
258
+ const options = normalizeControlOptions(resolveValue(component.options, context.binding, context.valueFunctions));
259
+ const bound = path ? readPointer(context.binding.dataModel, path) : null;
260
+ const multiple = component.multiple === true;
261
+ const segmented = !multiple && component.variant === "segmented";
262
+ const currentList = Array.isArray(bound) ? bound.filter((entry) => typeof entry === "string") : [];
263
+ const currentSingle = typeof bound === "string" ? bound : "";
264
+ const required = component.required === true;
265
+ const disabled = isControlDisabled(component, context);
266
+ const local = choiceValidation(component, context, multiple ? currentList : currentSingle);
267
+ const shown = shownError(local, key, context);
268
+ const errorId = shown ? `${generatedId}-${fieldId}-error` : null;
269
+ const validationIndex = options.findIndex((option) => !option.disabled);
270
+ // Runs after every render: the element carrying the error changes when options are refreshed.
271
+ useEffect(() => {
272
+ firstInputRef.current?.setCustomValidity(local?.message ?? "");
273
+ });
274
+ return withFallback(component, Boolean(label && path), (_jsxs("fieldset", { ref: groupRef, tabIndex: -1, className: "lp-field lp-choice-group", "data-variant": segmented ? "segmented" : undefined, "data-a2ui-field": key, disabled: disabled, "aria-invalid": Boolean(shown), "aria-describedby": errorId ?? undefined, children: [_jsxs("legend", { className: "lp-field-label", children: [label, requiredShown(component) ? _jsx(RequiredMark, {}) : null] }), _jsx("div", { className: segmented ? "lp-segmented-options" : "lp-choice-options", children: options.map((option, index) => {
275
+ const optionId = `${generatedId}-${fieldId}-${index}`;
276
+ const checked = multiple ? currentList.includes(option.value) : currentSingle === option.value;
277
+ const optionDisabled = disabled || option.disabled;
278
+ if (segmented) {
279
+ return (_jsxs("label", { htmlFor: optionId, className: "lp-segmented-option", "data-selected": checked ? "true" : undefined, "data-disabled": optionDisabled ? "true" : undefined, children: [_jsx("input", { ref: index === validationIndex ? firstInputRef : undefined, id: optionId, className: "lp-segmented-input", name: fieldId, type: "radio", value: option.value, checked: checked, required: requiredShown(component), disabled: optionDisabled, "aria-describedby": errorId ?? undefined, onChange: () => {
280
+ if (disabled)
281
+ return;
282
+ const next = validateControlValue(component, context.binding, option.value, context.valueFunctions, context.state.dataModel);
283
+ emitInputChange(component, context, fieldId, path, option.value, next === null, next?.errorCode ?? null);
284
+ } }), _jsx("span", { children: option.label })] }, option.value));
285
+ }
286
+ return (_jsxs("span", { className: "lp-check-option", children: [_jsx("input", { ref: index === validationIndex ? firstInputRef : undefined, id: optionId, name: fieldId, type: multiple ? "checkbox" : "radio", value: option.value, checked: checked, required: !multiple && requiredShown(component), disabled: optionDisabled, "aria-describedby": errorId ?? undefined, onChange: (event) => {
287
+ if (disabled)
288
+ return;
289
+ const nextValue = multiple
290
+ ? toggleAvailableChoice(component, context.binding, currentList, option.value, event.currentTarget.checked, context.valueFunctions, context.state.dataModel)
291
+ : option.value;
292
+ const next = validateControlValue(component, context.binding, nextValue, context.valueFunctions, context.state.dataModel);
293
+ emitInputChange(component, context, fieldId, path, nextValue, next === null, next?.errorCode ?? null);
294
+ } }), _jsx("label", { htmlFor: optionId, children: option.label })] }, option.value));
295
+ }) }), !required && (!segmented || local?.errorCode === "draft_unavailable") && (multiple ? currentList.length > 0 : currentSingle !== "") ? _jsx("button", { type: "button", className: "lp-btn ghost", disabled: disabled, "aria-label": `${copy.clear}: ${label}`, onClick: () => {
296
+ if (disabled)
297
+ return;
298
+ // An all-disabled group still has a stable focus target after the button disappears.
299
+ if (firstInputRef.current)
300
+ firstInputRef.current.focus();
301
+ else
302
+ groupRef.current?.focus();
303
+ emitInputChange(component, context, fieldId, path, multiple ? [] : "", true, null);
304
+ }, children: copy.clear }) : null, shown ? _jsx("span", { id: errorId ?? undefined, className: "lp-field-error", children: shown.message }) : null] })));
305
+ }
306
+ function SliderControl({ component, context }) {
307
+ const generatedId = useId();
308
+ const controlRef = useRef(null);
309
+ const { fieldId, path, key } = controlIdentity(component, context);
310
+ const label = text(component, "label", context);
311
+ const min = numberValue(component, "min", context) ?? 0;
312
+ const max = numberValue(component, "max", context) ?? 100;
313
+ const step = numberValue(component, "step", context) ?? 1;
314
+ const bound = path ? readPointer(context.binding.dataModel, path) : null;
315
+ const currentValue = typeof bound === "number" && Number.isFinite(bound) ? bound : min;
316
+ const disabled = isControlDisabled(component, context);
317
+ const marks = normalizeSliderMarks(resolveValue(component.marks, context.binding, context.valueFunctions), min, max);
318
+ const valueDisplay = formatSliderValue(currentValue, marks);
319
+ const local = validateControlValue(component, context.binding, currentValue, context.valueFunctions, context.state.dataModel);
320
+ const shown = shownError(local, key, context);
321
+ const valid = shown === null;
322
+ const controlId = `${generatedId}-${fieldId}`;
323
+ const errorId = shown ? `${controlId}-error` : null;
324
+ useEffect(() => { controlRef.current?.setCustomValidity(local?.message ?? ""); }, [local?.message]);
325
+ return withFallback(component, Boolean(label && path), (_jsxs("div", { className: "lp-field lp-slider-field", "data-invalid": shown ? "true" : undefined, "data-a2ui-field": key, children: [_jsxs("span", { className: "lp-slider-label-row", children: [_jsx("label", { className: "lp-field-label", htmlFor: controlId, children: label }), _jsx("output", { htmlFor: controlId, children: valueDisplay })] }), _jsx("input", { ref: controlRef, id: controlId, className: "lp-slider", style: { "--lp-range-progress": `${valid ? (currentValue - min) / (max - min) * 100 : 0}%` }, name: fieldId, type: "range", min: min, max: max, step: step, value: currentValue, disabled: disabled, "aria-invalid": !valid, "aria-valuetext": !valid ? `${valueDisplay}. ${shown?.message}` : valueDisplay !== String(currentValue) ? valueDisplay : undefined, "aria-describedby": errorId ?? undefined, "aria-errormessage": errorId ?? undefined, onChange: (event) => {
326
+ if (disabled)
327
+ return;
328
+ const nextValue = event.currentTarget.valueAsNumber;
329
+ const next = validateControlValue(component, context.binding, nextValue, context.valueFunctions, context.state.dataModel);
330
+ emitInputChange(component, context, fieldId, path, nextValue, next === null, next?.errorCode ?? null);
331
+ } }), marks.length > 0 ? _jsx(SliderMarks, { marks: marks, currentValue: currentValue }) : null, shown ? _jsx("span", { id: errorId ?? undefined, className: "lp-field-error", children: shown.message }) : null] })));
332
+ }
333
+ function SliderMarks({ marks, currentValue }) {
334
+ const containerRef = useRef(null);
335
+ const probeRefs = useRef([]);
336
+ const marksKey = marks.map((mark) => `${mark.value}:${mark.label ?? ""}`).join("|");
337
+ const [measured, setMeasured] = useState({ key: "", containerWidth: 0, widths: [] });
338
+ useLayoutEffect(() => {
339
+ const container = containerRef.current;
340
+ if (!container)
341
+ return;
342
+ const measure = () => {
343
+ const containerWidth = container.getBoundingClientRect().width;
344
+ const widths = marks.map((mark, index) => {
345
+ if (!mark.label)
346
+ return 0;
347
+ const node = probeRefs.current[index];
348
+ return node ? Math.ceil(node.getBoundingClientRect().width) + 2 : 0;
349
+ });
350
+ setMeasured((previous) => {
351
+ if (previous.key === marksKey
352
+ && Math.abs(previous.containerWidth - containerWidth) < 0.5
353
+ && previous.widths.length === widths.length
354
+ && previous.widths.every((value, idx) => value === widths[idx])) {
355
+ return previous;
356
+ }
357
+ return { key: marksKey, containerWidth, widths };
358
+ });
359
+ };
360
+ measure();
361
+ const cleanups = [];
362
+ if (typeof ResizeObserver !== "undefined") {
363
+ const observer = new ResizeObserver(measure);
364
+ observer.observe(container);
365
+ for (let index = 0; index < marks.length; index += 1) {
366
+ const probe = probeRefs.current[index];
367
+ if (probe)
368
+ observer.observe(probe);
369
+ }
370
+ cleanups.push(() => observer.disconnect());
371
+ }
372
+ if (typeof MutationObserver !== "undefined") {
373
+ const surfaceRoot = container.closest(".a2ui-surface") ?? document.documentElement;
374
+ const mutationObserver = new MutationObserver(measure);
375
+ mutationObserver.observe(surfaceRoot, { attributes: true, attributeFilter: ["style", "class", "data-pack"] });
376
+ if (surfaceRoot !== document.documentElement && document.documentElement) {
377
+ mutationObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["style", "class"] });
378
+ }
379
+ cleanups.push(() => mutationObserver.disconnect());
380
+ }
381
+ if (typeof document !== "undefined" && document.fonts?.ready) {
382
+ let active = true;
383
+ void document.fonts.ready.then(() => { if (active)
384
+ measure(); });
385
+ cleanups.push(() => { active = false; });
386
+ }
387
+ return () => { for (const cleanup of cleanups)
388
+ cleanup(); };
389
+ }, [marks, marksKey]);
390
+ const hasLabels = marks.some((mark) => Boolean(mark.label));
391
+ const ready = measured.key === marksKey && measured.containerWidth > 0 && measured.widths.length === marks.length;
392
+ const placement = ready
393
+ ? selectVisibleSliderMarkLabels(marks.map((mark, index) => ({
394
+ ratio: mark.ratio,
395
+ width: measured.widths[index] ?? 0,
396
+ active: Math.abs(mark.value - currentValue) <= 1e-9,
397
+ })), measured.containerWidth, 8, 9)
398
+ : null;
399
+ return (_jsxs("div", { ref: containerRef, className: "lp-slider-marks", "aria-hidden": "true", children: [hasLabels ? (_jsx("div", { className: "lp-slider-mark-probe", children: marks.map((mark, index) => (mark.label ? (_jsx("span", { ref: (node) => { probeRefs.current[index] = node; }, className: "lp-slider-mark-probe-item", children: mark.label }, mark.value)) : null)) })) : null, _jsx("div", { className: "lp-slider-mark-ticks", children: marks.map((mark) => {
400
+ const active = Math.abs(mark.value - currentValue) <= 1e-9;
401
+ return (_jsx("span", { className: "lp-slider-mark-tick", style: { "--lp-mark-ratio": String(mark.ratio) }, "data-value": String(mark.value), "data-active": active ? "true" : undefined }, mark.value));
402
+ }) }), hasLabels && (!placement || placement.visible.size > 0) ? (_jsx("div", { className: "lp-slider-mark-labels", children: marks.map((mark, index) => {
403
+ if (!mark.label)
404
+ return null;
405
+ if (placement && !placement.visible.has(index))
406
+ return null;
407
+ const active = Math.abs(mark.value - currentValue) <= 1e-9;
408
+ const edge = mark.ratio <= 0.01 ? "start" : mark.ratio >= 0.99 ? "end" : undefined;
409
+ const placedLeft = placement?.lefts.get(index);
410
+ return (_jsx("span", { className: "lp-slider-mark-label", style: placedLeft !== undefined
411
+ ? { left: `${placedLeft}px` }
412
+ : { "--lp-mark-ratio": String(mark.ratio) }, "data-value": String(mark.value), "data-active": active ? "true" : undefined, "data-edge": placedLeft === undefined ? edge : undefined, "data-placed": placedLeft !== undefined ? "true" : undefined, children: mark.label }, mark.value));
413
+ }) })) : null] }));
414
+ }
415
+ function isPromiseLike(value) {
416
+ return (typeof value === "object" || typeof value === "function")
417
+ && value !== null
418
+ && "then" in value
419
+ && typeof value.then === "function";
420
+ }
421
+ /** Moves focus to a field by its draft key, when native validity did not already move it. */
422
+ function focusField(form, key) {
423
+ const wrapper = Array.from(form.querySelectorAll("[data-a2ui-field]")).find((node) => node.dataset.a2uiField === key);
424
+ wrapper?.querySelector("input:not(:disabled), select:not(:disabled), textarea:not(:disabled)")?.focus();
425
+ }
426
+ /**
427
+ * The form's progress line: what is drawn, and a polite live region read in its place. The
428
+ * region's words change only when the count of done or counted required fields changes, so a
429
+ * screen reader hears each change once and nothing while the user types within a field.
430
+ */
431
+ function FormProgress({ done, total, locale, visible }) {
432
+ const copy = formProgressCopy(done, total, locale);
433
+ return (_jsxs(_Fragment, { children: [visible ? _jsx("p", { className: "lp-form-progress", "data-complete": done === total ? "true" : undefined, "aria-hidden": "true", children: copy.shown }) : null, _jsx("span", { className: "lp-visually-hidden", "aria-live": "polite", "aria-atomic": "true", children: visible ? copy.spoken : "" })] }));
434
+ }
435
+ function FormControl({ component, context }) {
436
+ const generatedId = useId();
437
+ const [pending, setPending] = useState(false);
438
+ const [failed, setFailed] = useState(false);
439
+ const [showErrors, setShowErrors] = useState(false);
440
+ const [touched, setTouched] = useState(() => new Set());
441
+ const touch = useCallback((key) => {
442
+ setTouched((previous) => previous.has(key) ? previous : new Set(previous).add(key));
443
+ }, []);
444
+ const feedback = useMemo(() => ({ showErrors, touched, touch }), [showErrors, touched, touch]);
445
+ const title = text(component, "title", context);
446
+ const submitLabel = text(component, "submitLabel", context);
447
+ const disabled = isControlDisabled(component, context);
448
+ const action = resolveAction(component.submitAction, component, context);
449
+ const dispatchBlocked = Boolean(action && context.actionSession?.blocked(action, context));
450
+ // Only a stale draft pauses the form; invalid fields keep the submit available and are
451
+ // caught when it is pressed.
452
+ const paused = actionIsBlocked(component.submitAction, component, context);
453
+ const titleId = title ? `${generatedId}-title` : undefined;
454
+ const statusId = `${generatedId}-status`;
455
+ const leftId = `${generatedId}-left`;
456
+ const nested = context.ancestors.some((id) => {
457
+ const name = context.state.components[id]?.component;
458
+ return name === "lp.form" || name === "LPForm_Default";
459
+ });
460
+ if (nested) {
461
+ return _jsx("div", { className: "lp-form", "data-a2ui-component": component.component, "data-a2ui-form": formKeyOf(component.id, context.itemId), children: renderChildren(component, context) });
462
+ }
463
+ // The one result the progress line, the submit button and the submit itself all read.
464
+ const validation = validateForm(context.state, component, context.binding, context.ancestors, context.itemId, context.valueFunctions);
465
+ const left = validation.requiredTotal - validation.requiredDone;
466
+ const locale = surfaceLocale(context);
467
+ const submit = formSubmitState(!dispatchBlocked && formSubmitIsEnabled({ hasSubmitAction: Boolean(action), disabled, pending, paused }), validation);
468
+ // Missing required fields mute the button without disabling it: pressing it shows what is missing.
469
+ const incomplete = submit === "incomplete";
470
+ return withFallback(component, Boolean(submitLabel && action), (_jsxs("form", { className: "lp-form", "data-a2ui-form": formKeyOf(component.id, context.itemId), noValidate: true, "aria-labelledby": titleId, "aria-label": title ? undefined : accessibilityLabel(component, context), "aria-describedby": pending || failed ? statusId : undefined, "aria-busy": pending || Boolean(action && context.actionSession?.pending(action, context)), onInvalidCapture: scheduleFirstInvalidFocus, onSubmit: (event) => {
471
+ event.preventDefault();
472
+ if (pending || dispatchBlocked || !action || paused || disabled)
473
+ return;
474
+ const form = event.currentTarget;
475
+ // Native validity carries the same messages (each control sets it from the same rule)
476
+ // and moves focus to the first failing field, opening its tab.
477
+ const nativelyValid = form.checkValidity();
478
+ if (validation.firstInvalid || !nativelyValid) {
479
+ setShowErrors(true);
480
+ if (nativelyValid && validation.firstInvalid)
481
+ focusField(form, validation.firstInvalid.key);
482
+ return;
483
+ }
484
+ if (context.actionSession) {
485
+ context.actionSession.dispatch(action, context);
486
+ return;
487
+ }
488
+ setFailed(false);
489
+ try {
490
+ const result = context.onAction(action);
491
+ if (isPromiseLike(result)) {
492
+ setPending(true);
493
+ void Promise.resolve(result).then(() => setPending(false), () => {
494
+ setPending(false);
495
+ setFailed(true);
496
+ });
497
+ }
498
+ }
499
+ catch {
500
+ setFailed(true);
501
+ }
502
+ }, children: [title ? _jsx("h2", { id: titleId, className: "lp-heading", children: title }) : null, component.progress === true ? (_jsx(FormProgress, { done: validation.requiredDone, total: validation.requiredTotal, locale: locale, visible: validation.requiredTotal > 0 })) : null, _jsxs("fieldset", { className: "lp-form-fields", disabled: disabled || pending, children: [renderChildren(component, { ...context, form: feedback }), _jsx("button", { type: "submit", className: "lp-btn", "data-incomplete": incomplete ? "true" : undefined, "aria-describedby": incomplete ? leftId : undefined, disabled: submit === "unavailable", children: submitLabel }), incomplete ? _jsx("span", { id: leftId, hidden: true, children: requiredFieldsLeftCopy(left, locale) }) : null] }), pending ? _jsx("span", { id: statusId, className: "lp-field-hint", role: "status", children: "Submitting\u2026" }) : null, failed ? _jsx("span", { id: statusId, className: "lp-field-error", role: "alert", children: "Submission failed. Try again." }) : null] })));
503
+ }
504
+ function TabsControl({ component, context }) {
505
+ const generatedId = useId();
506
+ const tabRefs = useRef([]);
507
+ const panelRefs = useRef([]);
508
+ const childIds = Array.isArray(component.children)
509
+ ? component.children.filter((entry) => typeof entry === "string")
510
+ : [];
511
+ const labels = resolveStringList(component.labels, context.binding, context.valueFunctions);
512
+ const tabCount = Math.min(childIds.length, labels.length);
513
+ const initialIndex = typeof component.initialIndex === "number"
514
+ && Number.isInteger(component.initialIndex)
515
+ && component.initialIndex >= 0
516
+ && component.initialIndex < tabCount
517
+ ? component.initialIndex
518
+ : 0;
519
+ const [activeIndex, setActiveIndex] = useState(initialIndex);
520
+ const safeIndex = activeIndex < tabCount ? activeIndex : 0;
521
+ const streaming = surfaceIsStreaming(context.state);
522
+ const variant = component.variant === "segmented" ? "segmented" : undefined;
523
+ useEffect(() => {
524
+ if (activeIndex >= tabCount && tabCount > 0)
525
+ setActiveIndex(0);
526
+ }, [activeIndex, tabCount]);
527
+ const complete = tabCount > 0 && tabCount === childIds.length && tabCount === labels.length;
528
+ const activateAndFocus = (index) => {
529
+ if (streaming)
530
+ return;
531
+ setActiveIndex(index);
532
+ tabRefs.current[index]?.focus();
533
+ };
534
+ const handleKeyDown = (event, index) => {
535
+ if (streaming)
536
+ return;
537
+ let next = null;
538
+ if (event.key === "ArrowRight")
539
+ next = (index + 1) % tabCount;
540
+ if (event.key === "ArrowLeft")
541
+ next = (index - 1 + tabCount) % tabCount;
542
+ if (event.key === "Home")
543
+ next = 0;
544
+ if (event.key === "End")
545
+ next = tabCount - 1;
546
+ if (next === null)
547
+ return;
548
+ event.preventDefault();
549
+ activateAndFocus(next);
550
+ };
551
+ return withFallback(component, complete, (_jsxs("section", { className: "lp-tabs", "data-variant": variant, "aria-label": accessibilityLabel(component, context), onInvalidCapture: (event) => {
552
+ if (!(event.target instanceof HTMLElement))
553
+ return;
554
+ const firstInvalid = event.target.closest("form")?.querySelector("input:invalid, select:invalid, textarea:invalid") ?? null;
555
+ const index = firstInvalidPanelIndex(panelRefs.current, event.target, firstInvalid);
556
+ if (index !== null)
557
+ setActiveIndex(index);
558
+ }, children: [_jsx("div", { className: "lp-tab-list", role: "tablist", "aria-label": accessibilityLabel(component, context) ?? "Tabs", children: labels.map((label, index) => {
559
+ const selected = index === safeIndex;
560
+ return (_jsx("button", { ref: (node) => { tabRefs.current[index] = node; }, id: `${generatedId}-tab-${index}`, type: "button", className: "lp-tab", role: "tab", "aria-selected": selected, "aria-controls": `${generatedId}-panel-${index}`, disabled: streaming, tabIndex: selected ? 0 : -1, onClick: () => { if (!streaming)
561
+ setActiveIndex(index); }, onKeyDown: (event) => handleKeyDown(event, index), children: label }, `${childIds[index]}-${label}`));
562
+ }) }), childIds.map((childId, index) => {
563
+ const inactive = index !== safeIndex;
564
+ return (_jsx("div", { ref: (node) => {
565
+ panelRefs.current[index] = node;
566
+ if (node)
567
+ node.inert = inactive;
568
+ }, id: `${generatedId}-panel-${index}`, className: "lp-tab-panel", role: "tabpanel", "aria-labelledby": `${generatedId}-tab-${index}`, hidden: inactive, children: _jsx(RenderComponent, { componentId: childId, context: childContext(context, component.id, undefined, index) }) }, childId));
569
+ })] })));
570
+ }
571
+ const popoverPlacements = new Set(["top", "bottom", "start", "end"]);
572
+ const popoverTriggerVariants = new Set(["solid", "soft", "outline", "ghost"]);
573
+ const popoverTriggerIntents = new Set(["ink", "accent", "ghost", "danger"]);
574
+ const popoverTriggerSizes = new Set(["sm", "md", "lg"]);
575
+ function PopoverControl({ component, context }) {
576
+ const generatedId = useId();
577
+ const wrapperRef = useRef(null);
578
+ const triggerRef = useRef(null);
579
+ const panelRef = useRef(null);
580
+ const childIds = Array.isArray(component.children)
581
+ ? component.children.filter((entry) => typeof entry === "string")
582
+ : [];
583
+ const complete = childIds.length === 2;
584
+ const triggerId = childIds[0] ?? "";
585
+ const contentId = childIds[1] ?? "";
586
+ const streaming = surfaceIsStreaming(context.state);
587
+ const [open, setOpen] = useState(false);
588
+ const [panelOffset, setPanelOffset] = useState(null);
589
+ const zh = isChineseLanguage(surfaceLanguage(context.state?.rendererHints));
590
+ const placement = typeof component.placement === "string" && popoverPlacements.has(component.placement)
591
+ ? component.placement
592
+ : "bottom";
593
+ const explicitLabel = typeof component.label === "string" && component.label.trim().length > 0
594
+ ? component.label.trim()
595
+ : null;
596
+ const dialogLabel = explicitLabel ?? accessibilityLabel(component, context) ?? (zh ? "详情" : "Details");
597
+ const closeLabel = typeof component.closeLabel === "string" && component.closeLabel.trim().length > 0
598
+ ? component.closeLabel.trim()
599
+ : (zh ? "关闭" : "Close");
600
+ const explicitTriggerVariant = typeof component.triggerVariant === "string" && popoverTriggerVariants.has(component.triggerVariant)
601
+ ? component.triggerVariant
602
+ : undefined;
603
+ const triggerIntent = typeof component.triggerIntent === "string" && popoverTriggerIntents.has(component.triggerIntent)
604
+ ? component.triggerIntent
605
+ : undefined;
606
+ const triggerVariant = explicitTriggerVariant
607
+ ?? (triggerIntent === "danger" ? "outline" : triggerIntent === "ghost" ? "ghost" : triggerIntent ? "solid" : "outline");
608
+ const triggerSize = typeof component.triggerSize === "string" && popoverTriggerSizes.has(component.triggerSize)
609
+ ? component.triggerSize
610
+ : "md";
611
+ useEffect(() => {
612
+ if (streaming && open)
613
+ setOpen(false);
614
+ }, [open, streaming]);
615
+ useLayoutEffect(() => {
616
+ if (!open) {
617
+ setPanelOffset(null);
618
+ return;
619
+ }
620
+ const updatePosition = () => {
621
+ const wrapper = wrapperRef.current;
622
+ const trigger = triggerRef.current;
623
+ const panel = panelRef.current;
624
+ if (!wrapper || !trigger || !panel || typeof window === "undefined")
625
+ return;
626
+ const vw = document.documentElement?.clientWidth || window.innerWidth;
627
+ const vh = document.documentElement?.clientHeight || window.innerHeight;
628
+ if (vw <= 0 || vh <= 0)
629
+ return;
630
+ const margin = 8;
631
+ const gap = 8;
632
+ const wRect = wrapper.getBoundingClientRect();
633
+ const tRect = trigger.getBoundingClientRect();
634
+ const pRect = panel.getBoundingClientRect();
635
+ const maxHeight = Math.max(120, vh - margin * 2);
636
+ const pWidth = Math.min(pRect.width, Math.max(120, vw - margin * 2));
637
+ const pHeight = Math.min(pRect.height, maxHeight);
638
+ const rtl = typeof window.getComputedStyle === "function" && window.getComputedStyle(wrapper).direction === "rtl";
639
+ const placeCoords = (side) => {
640
+ if (side === "top")
641
+ return { x: rtl ? tRect.right - pWidth : tRect.left, y: tRect.top - gap - pHeight };
642
+ if (side === "bottom")
643
+ return { x: rtl ? tRect.right - pWidth : tRect.left, y: tRect.bottom + gap };
644
+ const isLeft = (side === "start" && !rtl) || (side === "end" && rtl);
645
+ return { x: isLeft ? tRect.left - gap - pWidth : tRect.right + gap, y: tRect.top };
646
+ };
647
+ const fits = (coords) => coords.x >= margin && coords.x + pWidth <= vw - margin && coords.y >= margin && coords.y + pHeight <= vh - margin;
648
+ const fallbacks = {
649
+ start: ["start", "end", "bottom", "top"],
650
+ end: ["end", "start", "bottom", "top"],
651
+ top: ["top", "bottom", "end", "start"],
652
+ bottom: ["bottom", "top", "end", "start"],
653
+ };
654
+ const order = fallbacks[placement] ?? fallbacks.bottom;
655
+ let chosen = placeCoords(order[0]);
656
+ for (const side of order) {
657
+ const candidate = placeCoords(side);
658
+ if (fits(candidate)) {
659
+ chosen = candidate;
660
+ break;
661
+ }
662
+ }
663
+ // If horizontal placement still overflows both sides (e.g. 320px viewport), prefer vertical below/above before clamping.
664
+ if ((placement === "start" || placement === "end") && (chosen.x < margin || chosen.x + pWidth > vw - margin)) {
665
+ const below = placeCoords("bottom");
666
+ const above = placeCoords("top");
667
+ chosen = below.y + pHeight <= vh - margin || below.y >= above.y ? below : above;
668
+ }
669
+ const clampedX = Math.max(margin, Math.min(chosen.x, Math.max(margin, vw - pWidth - margin)));
670
+ const clampedY = Math.max(margin, Math.min(chosen.y, Math.max(margin, vh - pHeight - margin)));
671
+ setPanelOffset({
672
+ left: Math.round(clampedX - wRect.left),
673
+ top: Math.round(clampedY - wRect.top),
674
+ maxHeight: Math.floor(maxHeight),
675
+ });
676
+ };
677
+ updatePosition();
678
+ window.addEventListener("resize", updatePosition);
679
+ window.addEventListener("scroll", updatePosition, true);
680
+ return () => {
681
+ window.removeEventListener("resize", updatePosition);
682
+ window.removeEventListener("scroll", updatePosition, true);
683
+ };
684
+ }, [open, placement]);
685
+ useEffect(() => {
686
+ if (!open)
687
+ return;
688
+ panelRef.current?.focus({ preventScroll: true });
689
+ const onPointerDown = (event) => {
690
+ const wrapper = wrapperRef.current;
691
+ if (!wrapper)
692
+ return;
693
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [];
694
+ if (path.includes(wrapper) || (event.target instanceof Node && wrapper.contains(event.target)))
695
+ return;
696
+ setOpen(false);
697
+ };
698
+ const onKeyDown = (event) => {
699
+ if (event.key !== "Escape")
700
+ return;
701
+ event.preventDefault();
702
+ event.stopPropagation();
703
+ setOpen(false);
704
+ triggerRef.current?.focus();
705
+ };
706
+ document.addEventListener("pointerdown", onPointerDown, true);
707
+ document.addEventListener("keydown", onKeyDown, true);
708
+ return () => {
709
+ document.removeEventListener("pointerdown", onPointerDown, true);
710
+ document.removeEventListener("keydown", onKeyDown, true);
711
+ };
712
+ }, [open]);
713
+ const closeAndReturnFocus = () => {
714
+ setOpen(false);
715
+ triggerRef.current?.focus();
716
+ };
717
+ const panelId = `${generatedId}-popover-panel`;
718
+ const resolvedIntent = triggerIntent ?? (triggerVariant === "solid" ? "accent" : triggerVariant === "ghost" ? "ghost" : "ink");
719
+ const triggerClasses = [
720
+ "lp-btn",
721
+ "lp-popover-trigger",
722
+ resolvedIntent,
723
+ triggerVariant === "outline" ? "outline" : triggerVariant === "soft" ? "soft" : "",
724
+ triggerSize !== "md" ? `lp-btn-${triggerSize}` : "",
725
+ ].filter(Boolean).join(" ");
726
+ return withFallback(component, complete, (_jsxs("div", { ref: wrapperRef, className: "lp-popover", "data-open": open ? "true" : "false", "data-placement": placement, children: [_jsx("button", { ref: triggerRef, type: "button", className: triggerClasses, "data-variant": triggerVariant, "data-intent": resolvedIntent, "data-size": triggerSize, "aria-haspopup": "dialog", "aria-expanded": open, "aria-controls": open ? panelId : undefined, disabled: streaming, onClick: () => {
727
+ if (streaming)
728
+ return;
729
+ setOpen((previous) => !previous);
730
+ }, children: _jsx("span", { className: "lp-popover-trigger-body", children: _jsx(RenderComponent, { componentId: triggerId, context: childContext(context, component.id, undefined, 0) }) }) }), open ? (_jsxs("div", { ref: panelRef, id: panelId, role: "dialog", "aria-modal": "false", "aria-label": dialogLabel, tabIndex: -1, className: "lp-popover-panel", "data-placement": placement, style: panelOffset ? { left: `${panelOffset.left}px`, top: `${panelOffset.top}px`, right: "auto", bottom: "auto", margin: 0, maxHeight: `${panelOffset.maxHeight}px` } : undefined, children: [_jsxs("div", { className: "lp-popover-header", children: [explicitLabel ? _jsx("span", { className: "lp-popover-title", children: explicitLabel }) : _jsx("span", {}), _jsx("button", { type: "button", className: "lp-popover-close", "aria-label": closeLabel, onClick: closeAndReturnFocus, children: _jsx(LucideIcon, { name: "x", size: "sm", decorative: true }) })] }), _jsx("div", { className: "lp-popover-body", children: _jsx(RenderComponent, { componentId: contentId, context: childContext(context, component.id, undefined, 1) }) })] })) : null] })));
731
+ }
732
+ export const renderSelect = (component, context) => _jsx(SelectControl, { component: component, context: context });
733
+ export const renderCheckbox = (component, context) => _jsx(CheckboxControl, { component: component, context: context });
734
+ export const renderChoiceGroup = (component, context) => _jsx(ChoiceGroup, { component: component, context: context });
735
+ export const renderSlider = (component, context) => _jsx(SliderControl, { component: component, context: context });
736
+ export const renderForm = (component, context) => _jsx(FormControl, { component: component, context: context });
737
+ export const renderTabs = (component, context) => _jsx(TabsControl, { component: component, context: context });
738
+ export const renderPopover = (component, context) => _jsx(PopoverControl, { component: component, context: context });