@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,637 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
3
+ import { isRecord } from "../core/messages.js";
4
+ import { readPointer } from "../core/pointer.js";
5
+ import { isChineseLanguage, surfaceLanguage } from "../controls/fieldMessages.js";
6
+ import { surfaceIsStreaming } from "../controls/actionDispatch.js";
7
+ import { actionHandler, readFallback, resolveAction } from "../core/context.js";
8
+ import { renderChildren, withFallback } from "../core/component-support.js";
9
+ import { layoutTableColumns, placeTableCells, tableGroupStarts } from "./tableLayout.js";
10
+ import { LucideIcon } from "../core/LucideIcon.js";
11
+ import { renderSurfaceLink, SurfaceLink } from "../core/SurfaceLink.js";
12
+ import { useSurfaceImage } from "../core/useSurfaceImage.js";
13
+ import { mathElement } from "./math.js";
14
+ import { validDisplayText, validImageUrl, validLinkUrl } from "./hostValues.js";
15
+ const MAX_SOURCE_LINE_NUMBER = 1_000_000;
16
+ const MAX_SOURCE_PREVIEW_LENGTH = 4_000;
17
+ const MAX_SOURCE_PREVIEW_LINES = 40;
18
+ export function splitCodePreviewLines(preview) {
19
+ const normalized = preview.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
20
+ const trimmed = normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized;
21
+ return trimmed.split("\n");
22
+ }
23
+ function positiveLineNumber(value) {
24
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_SOURCE_LINE_NUMBER) {
25
+ return undefined;
26
+ }
27
+ return value;
28
+ }
29
+ export function formatCodeLocation(path, lineStart, lineEnd) {
30
+ return lineEnd !== undefined && lineEnd > lineStart ? `${path}:${lineStart}-${lineEnd}` : `${path}:${lineStart}`;
31
+ }
32
+ export function citeSourcePillLabel(source) {
33
+ if (source.kind === "code" && source.path && source.lineStart !== undefined) {
34
+ return formatCodeLocation(source.path, source.lineStart, source.lineEnd);
35
+ }
36
+ if (source.kind === "file" && source.fileName) {
37
+ return source.fileName;
38
+ }
39
+ return source.site ?? source.title;
40
+ }
41
+ export function parseCiteSourceItem(item, fallbackIndex = 1) {
42
+ if (typeof item.id !== "string" || !item.id.trim())
43
+ return null;
44
+ const rawKind = item.kind;
45
+ const kind = rawKind === undefined ? "web" : rawKind === "web" || rawKind === "code" || rawKind === "file" ? rawKind : null;
46
+ if (!kind)
47
+ return null;
48
+ const title = validDisplayText(item.title, 200);
49
+ if (title === null)
50
+ return null;
51
+ const url = validLinkUrl(item.url) ?? undefined;
52
+ const site = validDisplayText(item.site, 120) ?? undefined;
53
+ const faviconUrl = safeImageUrl(item.faviconUrl ?? item.favicon_url) ?? undefined;
54
+ const excerpt = validDisplayText(item.excerpt, 500) ?? undefined;
55
+ const index = typeof item.index === "number" && Number.isInteger(item.index) && item.index >= 1 ? item.index : fallbackIndex;
56
+ if (kind === "web") {
57
+ if (!url)
58
+ return null;
59
+ return { id: item.id, kind, index, title, url, site: site ?? title, faviconUrl, excerpt };
60
+ }
61
+ if (kind === "code") {
62
+ const path = validDisplayText(item.path, 400);
63
+ const lineStart = positiveLineNumber(item.lineStart ?? item.line_start);
64
+ if (path === null || lineStart === undefined)
65
+ return null;
66
+ const rawLineEnd = item.lineEnd ?? item.line_end;
67
+ let lineEnd;
68
+ if (rawLineEnd !== undefined && rawLineEnd !== null) {
69
+ const parsedEnd = positiveLineNumber(rawLineEnd);
70
+ if (parsedEnd === undefined || parsedEnd < lineStart)
71
+ return null;
72
+ lineEnd = parsedEnd;
73
+ }
74
+ let preview;
75
+ let previewStartLine;
76
+ const rawPreview = item.preview;
77
+ const rawPreviewStart = item.previewStartLine ?? item.preview_start_line;
78
+ if (rawPreview !== undefined && rawPreview !== null) {
79
+ const validPreview = validDisplayText(rawPreview, MAX_SOURCE_PREVIEW_LENGTH);
80
+ const validStart = positiveLineNumber(rawPreviewStart);
81
+ if (validPreview !== null && validStart !== undefined && splitCodePreviewLines(validPreview).length <= MAX_SOURCE_PREVIEW_LINES) {
82
+ preview = validPreview;
83
+ previewStartLine = validStart;
84
+ }
85
+ }
86
+ return {
87
+ id: item.id,
88
+ kind,
89
+ index,
90
+ title,
91
+ url,
92
+ site,
93
+ faviconUrl,
94
+ excerpt,
95
+ path,
96
+ lineStart,
97
+ lineEnd,
98
+ preview,
99
+ previewStartLine,
100
+ };
101
+ }
102
+ // kind === "file"
103
+ const fileName = validDisplayText(item.fileName ?? item.file_name, 200);
104
+ if (fileName === null)
105
+ return null;
106
+ const path = validDisplayText(item.path, 400) ?? undefined;
107
+ return { id: item.id, kind, index, title, url, site, faviconUrl, excerpt, path, fileName };
108
+ }
109
+ export function buildOpenSourceEventAction(sourceId) {
110
+ return {
111
+ event: {
112
+ name: "openSource",
113
+ context: {
114
+ id: sourceId,
115
+ _littlepress: {
116
+ handler: "host",
117
+ risk: "low",
118
+ loadingBehavior: "component",
119
+ invokesModel: false,
120
+ },
121
+ },
122
+ },
123
+ };
124
+ }
125
+ export function CiteSourceIcon({ source, size, imgClassName, initialClassName, kindIconClassName, context, streaming, }) {
126
+ if (source.kind === "code") {
127
+ return (_jsx("span", { className: kindIconClassName, "aria-hidden": "true", children: _jsx(LucideIcon, { name: "file-code", size: "sm", decorative: true }) }));
128
+ }
129
+ if (source.kind === "file") {
130
+ return (_jsx("span", { className: kindIconClassName, "aria-hidden": "true", children: _jsx(LucideIcon, { name: "file-text", size: "sm", decorative: true }) }));
131
+ }
132
+ return (_jsx(HostBadgeImage, { url: source.faviconUrl, label: source.site ?? source.title, size: size, imgClassName: imgClassName, initialClassName: initialClassName, context: context, streaming: streaming }));
133
+ }
134
+ function safeImageUrl(value) {
135
+ return validImageUrl(value);
136
+ }
137
+ function monogramInitial(label) {
138
+ const trimmed = label.trim();
139
+ if (!trimmed)
140
+ return "•";
141
+ return Array.from(trimmed)[0].toUpperCase();
142
+ }
143
+ /**
144
+ * Renders a Host-supplied image through the unified Host image entry point (`context.images`
145
+ * or `context.imageLoader`). Without `imageLoader`, valid `http://`, `https://`, and
146
+ * `data:image/*` URLs render directly with `referrerPolicy="no-referrer"`; when `imageLoader`
147
+ * is supplied, returning `null` keeps the monogram placeholder and never falls back.
148
+ */
149
+ export function HostBadgeImage({ url, label, size, imgClassName, initialClassName, context, streaming, }) {
150
+ const { src, onError } = useSurfaceImage(url, context, { streaming });
151
+ if (src) {
152
+ return (_jsx("img", { className: imgClassName, src: src, alt: "", width: size, height: size, referrerPolicy: "no-referrer", onError: onError }));
153
+ }
154
+ return (_jsx("span", { className: initialClassName, "aria-hidden": "true", children: monogramInitial(label) }));
155
+ }
156
+ function readCiteSource(sourceId, dataModel) {
157
+ const list = readPointer(dataModel, "/answer/sources");
158
+ if (!Array.isArray(list))
159
+ return null;
160
+ for (let i = 0; i < list.length; i += 1) {
161
+ const item = list[i];
162
+ if (!isRecord(item) || item.id !== sourceId)
163
+ continue;
164
+ return parseCiteSourceItem(item, i + 1);
165
+ }
166
+ return null;
167
+ }
168
+ function readEntityRecord(entityId, dataModel) {
169
+ const map = readPointer(dataModel, "/answer/entities");
170
+ if (!isRecord(map))
171
+ return null;
172
+ const item = map[entityId];
173
+ if (!isRecord(item) || typeof item.name !== "string" || typeof item.category !== "string")
174
+ return null;
175
+ const fields = Array.isArray(item.fields)
176
+ ? item.fields
177
+ .filter((f) => isRecord(f) && typeof f.label === "string" && typeof f.value === "string")
178
+ .map((f) => ({ label: f.label, value: f.value }))
179
+ : undefined;
180
+ return {
181
+ id: entityId,
182
+ name: item.name,
183
+ category: item.category,
184
+ imageUrl: safeImageUrl(item.imageUrl ?? item.image_url) ?? undefined,
185
+ subtitle: typeof item.subtitle === "string" && item.subtitle.trim() ? item.subtitle : undefined,
186
+ fields: fields?.length ? fields : undefined,
187
+ url: validLinkUrl(item.url) ?? undefined,
188
+ };
189
+ }
190
+ function useInlinePopover(open, setOpen) {
191
+ const wrapperRef = useRef(null);
192
+ const triggerRef = useRef(null);
193
+ const panelRef = useRef(null);
194
+ const [offset, setOffset] = useState(null);
195
+ useLayoutEffect(() => {
196
+ if (!open) {
197
+ setOffset(null);
198
+ return;
199
+ }
200
+ const update = () => {
201
+ const trigger = triggerRef.current;
202
+ const panel = panelRef.current;
203
+ if (!trigger || !panel || typeof window === "undefined")
204
+ return;
205
+ const vw = document.documentElement?.clientWidth || window.innerWidth;
206
+ const vh = document.documentElement?.clientHeight || window.innerHeight;
207
+ if (vw <= 0 || vh <= 0)
208
+ return;
209
+ const margin = 8;
210
+ const gap = 6;
211
+ const tRect = trigger.getBoundingClientRect();
212
+ const pRect = panel.getBoundingClientRect();
213
+ const maxHeight = Math.max(120, vh - margin * 2);
214
+ const pWidth = Math.min(pRect.width || 260, Math.max(120, vw - margin * 2));
215
+ const pHeight = Math.min(pRect.height || 140, maxHeight);
216
+ const spaceBelow = vh - margin - (tRect.bottom + gap);
217
+ const spaceAbove = tRect.top - gap - margin;
218
+ const belowY = tRect.bottom + gap;
219
+ const aboveY = tRect.top - gap - pHeight;
220
+ const chosenY = spaceBelow >= pHeight
221
+ ? belowY
222
+ : spaceAbove >= pHeight
223
+ ? aboveY
224
+ : spaceBelow >= spaceAbove
225
+ ? belowY
226
+ : aboveY;
227
+ const clampedX = Math.max(margin, Math.min(tRect.left, Math.max(margin, vw - pWidth - margin)));
228
+ const clampedY = Math.max(margin, Math.min(chosenY, Math.max(margin, vh - pHeight - margin)));
229
+ setOffset({
230
+ left: Math.round(clampedX),
231
+ top: Math.round(clampedY),
232
+ maxHeight: Math.floor(maxHeight),
233
+ });
234
+ };
235
+ update();
236
+ window.addEventListener("resize", update);
237
+ window.addEventListener("scroll", update, true);
238
+ return () => {
239
+ window.removeEventListener("resize", update);
240
+ window.removeEventListener("scroll", update, true);
241
+ };
242
+ }, [open]);
243
+ useEffect(() => {
244
+ if (!open)
245
+ return;
246
+ panelRef.current?.focus({ preventScroll: true });
247
+ const onPointerDown = (event) => {
248
+ const wrapper = wrapperRef.current;
249
+ if (!wrapper)
250
+ return;
251
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [];
252
+ if (path.includes(wrapper) || (event.target instanceof Node && wrapper.contains(event.target)))
253
+ return;
254
+ setOpen(false);
255
+ };
256
+ const onKeyDown = (event) => {
257
+ if (event.key !== "Escape")
258
+ return;
259
+ event.preventDefault();
260
+ event.stopPropagation();
261
+ setOpen(false);
262
+ triggerRef.current?.focus();
263
+ };
264
+ document.addEventListener("pointerdown", onPointerDown, true);
265
+ document.addEventListener("keydown", onKeyDown, true);
266
+ return () => {
267
+ document.removeEventListener("pointerdown", onPointerDown, true);
268
+ document.removeEventListener("keydown", onKeyDown, true);
269
+ };
270
+ }, [open, setOpen]);
271
+ const closeAndReturnFocus = () => {
272
+ setOpen(false);
273
+ triggerRef.current?.focus();
274
+ };
275
+ return { wrapperRef, triggerRef, panelRef, offset, closeAndReturnFocus };
276
+ }
277
+ function CitePill({ sourceId, fallbackText, path, component, context, blockStreaming, }) {
278
+ const source = readCiteSource(sourceId, context.state?.dataModel);
279
+ const [open, setOpen] = useState(false);
280
+ const panelId = useId();
281
+ const isStreaming = blockStreaming || surfaceIsStreaming(context.state);
282
+ const zh = chinese(context);
283
+ useEffect(() => {
284
+ if (isStreaming && open)
285
+ setOpen(false);
286
+ }, [isStreaming, open]);
287
+ const { wrapperRef, triggerRef, panelRef, offset, closeAndReturnFocus } = useInlinePopover(open, setOpen);
288
+ if (!source)
289
+ return _jsx(_Fragment, { children: fallbackText });
290
+ const pillLabel = citeSourcePillLabel(source);
291
+ const iconNode = (_jsx(CiteSourceIcon, { source: source, size: 14, imgClassName: "lp-cite-favicon", initialClassName: "lp-cite-initial", kindIconClassName: "lp-cite-kind-icon", context: context, streaming: isStreaming }));
292
+ const openUrlRawAction = source.url
293
+ ? { functionCall: { call: "openUrl", args: { url: source.url } } }
294
+ : undefined;
295
+ const rawOpenSource = !source.url ? buildOpenSourceEventAction(source.id) : undefined;
296
+ const resolvedOpenSource = rawOpenSource
297
+ ? resolveAction(rawOpenSource, component, context, {}, `${path}/open`)
298
+ : undefined;
299
+ const hostAcceptsOpenSource = Boolean(!isStreaming && resolvedOpenSource && context.actionSession?.hostAccepts(resolvedOpenSource));
300
+ const openSourceAction = hostAcceptsOpenSource && rawOpenSource
301
+ ? actionHandler(rawOpenSource, component, context, {}, `${path}/open`)
302
+ : undefined;
303
+ if (isStreaming) {
304
+ return (_jsxs("span", { className: "lp-cite-pill", "data-streaming": "true", "data-source-id": source.id, "data-source-kind": source.kind, children: [iconNode, _jsx("span", { className: "lp-cite-label", children: pillLabel })] }));
305
+ }
306
+ const previewLines = source.kind === "code" && source.preview && source.previewStartLine !== undefined
307
+ ? splitCodePreviewLines(source.preview)
308
+ : null;
309
+ const highlightStart = source.lineStart ?? 1;
310
+ const highlightEnd = Math.max(highlightStart, source.lineEnd ?? highlightStart);
311
+ return (_jsxs("span", { ref: wrapperRef, className: "lp-inline-popover-anchor", "data-open": open ? "true" : "false", children: [_jsxs("button", { ref: triggerRef, type: "button", className: "lp-cite-pill", "data-source-id": source.id, "data-source-kind": source.kind, "aria-haspopup": "dialog", "aria-expanded": open, "aria-controls": open ? panelId : undefined, "aria-label": `${pillLabel}: ${source.title}`, onClick: () => setOpen((prev) => !prev), children: [iconNode, _jsx("span", { className: "lp-cite-label", children: pillLabel })] }), open ? (_jsxs("div", { ref: panelRef, id: panelId, role: "dialog", "aria-modal": "false", "aria-label": source.title, tabIndex: -1, className: "lp-inline-popover-panel", "data-source-kind": source.kind, style: offset ? { left: `${offset.left}px`, top: `${offset.top}px`, maxHeight: `${offset.maxHeight}px` } : undefined, children: [_jsxs("div", { className: "lp-inline-popover-header", children: [_jsxs("span", { className: "lp-inline-popover-source", children: [iconNode, _jsx("span", { className: "lp-inline-popover-site", children: pillLabel })] }), _jsx("button", { type: "button", className: "lp-inline-popover-close", "aria-label": zh ? "关闭" : "Close", onClick: closeAndReturnFocus, children: _jsx(LucideIcon, { name: "x", size: "sm", decorative: true }) })] }), _jsxs("div", { className: "lp-inline-popover-body", children: [_jsx("div", { className: "lp-inline-popover-title", children: source.title }), source.kind === "file" && source.path && source.path !== source.fileName ? (_jsx("div", { className: "lp-cite-file-path", children: source.path })) : null, source.excerpt ? _jsx("p", { className: "lp-inline-popover-excerpt", children: source.excerpt }) : null, previewLines && source.previewStartLine !== undefined ? (_jsx("div", { className: "lp-cite-code-preview", role: "region", "aria-label": pillLabel, children: _jsx("pre", { className: "lp-cite-code-pre", children: _jsx("code", { children: previewLines.map((line, idx) => {
312
+ const lineNumber = source.previewStartLine + idx;
313
+ const highlighted = lineNumber >= highlightStart && lineNumber <= highlightEnd;
314
+ return (_jsxs("span", { className: "lp-cite-code-line", "data-line": lineNumber, "data-highlighted": highlighted ? "true" : undefined, children: [_jsx("span", { className: "lp-cite-code-gutter", "aria-hidden": "true", children: lineNumber }), _jsx("span", { className: "lp-cite-code-text", children: line.length > 0 ? line : " " })] }, lineNumber));
315
+ }) }) }) })) : null, source.url && openUrlRawAction ? (_jsx("div", { className: "lp-inline-popover-actions", children: _jsx(SurfaceLink, { url: source.url, action: openUrlRawAction, component: component, context: context, actionKey: `${path}/open`, className: "lp-inline-popover-open", children: zh ? "打开" : "Open" }) })) : hostAcceptsOpenSource && openSourceAction ? (_jsx("div", { className: "lp-inline-popover-actions", children: _jsx("button", { type: "button", className: "lp-inline-popover-open", "data-action-key": `${path}/open`, disabled: openSourceAction.disabled === true, "aria-busy": openSourceAction.pending ? true : undefined, onClick: () => {
316
+ if (!openSourceAction.disabled)
317
+ openSourceAction();
318
+ }, children: zh ? "打开" : "Open" }) })) : null] })] })) : null] }));
319
+ }
320
+ function EntityPill({ entityId, fallbackText, path, component, context, blockStreaming, }) {
321
+ const entity = readEntityRecord(entityId, context.state?.dataModel);
322
+ const [open, setOpen] = useState(false);
323
+ const panelId = useId();
324
+ const isStreaming = blockStreaming || surfaceIsStreaming(context.state);
325
+ const zh = chinese(context);
326
+ useEffect(() => {
327
+ if (isStreaming && open)
328
+ setOpen(false);
329
+ }, [isStreaming, open]);
330
+ const { wrapperRef, triggerRef, panelRef, offset, closeAndReturnFocus } = useInlinePopover(open, setOpen);
331
+ if (!entity)
332
+ return _jsx(_Fragment, { children: fallbackText });
333
+ const rawDetailAction = {
334
+ event: {
335
+ name: "openEntityDetail",
336
+ context: {
337
+ entityId: entity.id,
338
+ name: entity.name,
339
+ category: entity.category,
340
+ ...(entity.subtitle ? { subtitle: entity.subtitle } : {}),
341
+ ...(entity.url ? { url: entity.url } : {}),
342
+ ...(entity.imageUrl ? { imageUrl: entity.imageUrl } : {}),
343
+ ...(entity.fields ? { fields: entity.fields } : {}),
344
+ },
345
+ },
346
+ };
347
+ const resolvedDetail = resolveAction(rawDetailAction, component, context, {}, `${path}/entity`);
348
+ const openUrlRawAction = entity.url
349
+ ? { functionCall: { call: "openUrl", args: { url: entity.url } } }
350
+ : undefined;
351
+ if (isStreaming) {
352
+ return (_jsx("span", { className: "lp-entity-pill", "data-streaming": "true", "data-entity-id": entity.id, children: entity.name }));
353
+ }
354
+ const handleActivate = () => {
355
+ if (resolvedDetail && context.actionSession?.hostAccepts(resolvedDetail)) {
356
+ context.actionSession.dispatch(resolvedDetail, context);
357
+ return;
358
+ }
359
+ setOpen((prev) => !prev);
360
+ };
361
+ return (_jsxs("span", { ref: wrapperRef, className: "lp-inline-popover-anchor", "data-open": open ? "true" : "false", children: [_jsx("button", { ref: triggerRef, type: "button", className: "lp-entity-pill", "data-entity-id": entity.id, "aria-haspopup": "dialog", "aria-expanded": open, "aria-controls": open ? panelId : undefined, onClick: handleActivate, children: entity.name }), open ? (_jsxs("div", { ref: panelRef, id: panelId, role: "dialog", "aria-modal": "false", "aria-label": entity.name, tabIndex: -1, className: "lp-inline-popover-panel lp-entity-card", style: offset ? { left: `${offset.left}px`, top: `${offset.top}px`, maxHeight: `${offset.maxHeight}px` } : undefined, children: [_jsxs("div", { className: "lp-inline-popover-header", children: [_jsx("span", { className: "lp-entity-card-category", children: entity.category }), _jsx("button", { type: "button", className: "lp-inline-popover-close", "aria-label": zh ? "关闭" : "Close", onClick: closeAndReturnFocus, children: _jsx(LucideIcon, { name: "x", size: "sm", decorative: true }) })] }), _jsxs("div", { className: "lp-inline-popover-body", children: [_jsxs("div", { className: "lp-entity-card-head", children: [_jsx(HostBadgeImage, { url: entity.imageUrl, label: entity.name, size: 36, imgClassName: "lp-entity-card-image", initialClassName: "lp-entity-card-initial", context: context, streaming: isStreaming }), _jsxs("div", { className: "lp-entity-card-titles", children: [_jsx("div", { className: "lp-inline-popover-title", children: entity.name }), entity.subtitle ? _jsx("div", { className: "lp-entity-card-subtitle", children: entity.subtitle }) : null] })] }), entity.fields?.length ? (_jsx("dl", { className: "lp-entity-card-fields", children: entity.fields.map((field, index) => (_jsxs("div", { className: "lp-entity-card-field", children: [_jsx("dt", { children: field.label }), _jsx("dd", { children: field.value })] }, `${field.label}-${index}`))) })) : null, entity.url && openUrlRawAction ? (_jsx("div", { className: "lp-inline-popover-actions", children: _jsx(SurfaceLink, { url: entity.url, action: openUrlRawAction, component: component, context: context, actionKey: `${path}/open`, className: "lp-inline-popover-open", children: zh ? "打开" : "Open" }) })) : null] })] })) : null] }));
362
+ }
363
+ const roles = new Set(["display", "title", "heading", "body", "caption"]);
364
+ const listComponents = new Set(["lp.list", "LPList_Default"]);
365
+ /** The bullet characters by nesting depth, the same as Compose and SwiftUI draw. */
366
+ const unorderedMarkers = ['"• "', '"◦ "', '"▪ "'];
367
+ /** Cell padding on each side, included in a measured width. */
368
+ const cellPadding = 8;
369
+ function spans(value) {
370
+ return Array.isArray(value)
371
+ ? value.filter((span) => isRecord(span) && typeof span.text === "string" && span.text.length > 0)
372
+ : [];
373
+ }
374
+ function streaming(component) {
375
+ return component.streaming === true;
376
+ }
377
+ function chinese(context) {
378
+ return isChineseLanguage(surfaceLanguage(context.state?.rendererHints));
379
+ }
380
+ /** One span: its marks nested innermost-first, a link outermost, `\n` as a line break. */
381
+ function SpanNode({ span, path, component, context, open }) {
382
+ if (isRecord(span.cite) && typeof span.cite.sourceId === "string") {
383
+ return (_jsx(CitePill, { sourceId: span.cite.sourceId, fallbackText: span.text, path: path, component: component, context: context, blockStreaming: open }));
384
+ }
385
+ if (isRecord(span.entity) && typeof span.entity.entityId === "string") {
386
+ return (_jsx(EntityPill, { entityId: span.entity.entityId, fallbackText: span.text, path: path, component: component, context: context, blockStreaming: open }));
387
+ }
388
+ const lines = span.text.split("\n");
389
+ // A typeset formula is drawn in place of its source; the source stays its accessible name.
390
+ // A formula in a link is underlined like the link's words (`lp-answer-link` below).
391
+ const linked = isRecord(span.action) && isRecord(span.action.functionCall);
392
+ const math = isRecord(span.math) && typeof span.math.tex === "string"
393
+ ? mathElement(span.math.tex, span.math.geometry, context.state?.dataModel, false, linked)
394
+ : null;
395
+ let node = math ?? lines.flatMap((line, index) => (index === 0 ? [line] : [_jsx("br", {}, `br-${index}`), line]));
396
+ const marks = new Set(span.marks ?? []);
397
+ if (marks.has("code") && !math)
398
+ node = _jsx("code", { className: "lp-inline-code", children: node });
399
+ if (marks.has("strikethrough"))
400
+ node = _jsx("s", { children: node });
401
+ if (marks.has("underline"))
402
+ node = _jsx("u", { children: node });
403
+ if (marks.has("italic"))
404
+ node = _jsx("em", { children: node });
405
+ if (marks.has("bold"))
406
+ node = _jsx("strong", { children: node });
407
+ const action = span.action;
408
+ if (!isRecord(action) || !isRecord(action.functionCall))
409
+ return _jsx(_Fragment, { children: node });
410
+ const args = isRecord(action.functionCall.args) ? action.functionCall.args : {};
411
+ const rawUrl = typeof args.url === "string" ? args.url : undefined;
412
+ const safeUrl = validLinkUrl(rawUrl);
413
+ if (!safeUrl)
414
+ return _jsx(_Fragment, { children: node });
415
+ if (open || surfaceIsStreaming(context.state)) {
416
+ return _jsx("span", { className: "lp-answer-link", "data-pending-link": "true", "aria-disabled": "true", children: node });
417
+ }
418
+ return renderSurfaceLink({
419
+ url: safeUrl,
420
+ action,
421
+ component,
422
+ context,
423
+ actionKey: path,
424
+ className: "lp-answer-link",
425
+ children: node,
426
+ });
427
+ }
428
+ function richContent(component, context, key, base) {
429
+ const open = streaming(component);
430
+ return spans(component[key]).map((span, index) => (_jsx(SpanNode, { span: span, path: `${base}/${index}`, component: component, context: context, open: open }, index)));
431
+ }
432
+ const textTones = new Set(["default", "muted", "accent", "info", "positive", "warning", "danger"]);
433
+ const textAligns = new Set(["start", "center", "end"]);
434
+ export const renderRichText = (component, context) => {
435
+ const role = typeof component.role === "string" && roles.has(component.role) ? component.role : "body";
436
+ const level = typeof component.headingLevel === "number" && component.headingLevel >= 1 && component.headingLevel <= 6
437
+ ? Math.floor(component.headingLevel)
438
+ : null;
439
+ const tone = typeof component.tone === "string" && textTones.has(component.tone) && component.tone !== "default"
440
+ ? component.tone
441
+ : undefined;
442
+ const align = typeof component.align === "string" && textAligns.has(component.align) && component.align !== "start"
443
+ ? component.align
444
+ : undefined;
445
+ const Tag = (level ? `h${level}` : role === "title" ? "h2" : "p");
446
+ const content = richContent(component, context, "content", "content");
447
+ return withFallback(component, content.length > 0, (_jsx(Tag, { className: `lp-${role} lp-rich-text`, "data-tone": tone, "data-align": align, "data-streaming": streaming(component) ? "true" : undefined, children: content })));
448
+ };
449
+ function listDepth(context) {
450
+ return context.ancestors.filter((id) => listComponents.has(context.state.components[id]?.component ?? "")).length;
451
+ }
452
+ export const renderList = (component, context) => {
453
+ const ordered = component.ordered === true;
454
+ const depth = listDepth(context);
455
+ const items = renderChildren(component, context);
456
+ const style = { listStyleType: ordered ? "decimal" : unorderedMarkers[Math.min(depth, 2)] };
457
+ const props = { className: "lp-answer-list", "data-depth": depth, style };
458
+ return withFallback(component, items.length > 0, ordered
459
+ ? _jsx("ol", { ...props, start: typeof component.start === "number" ? component.start : undefined, children: items })
460
+ : _jsx("ul", { ...props, children: items }));
461
+ };
462
+ export const renderListItem = (component, context) => {
463
+ const checked = typeof component.checked === "boolean" ? component.checked : null;
464
+ const zh = chinese(context);
465
+ return (_jsxs("li", { className: "lp-answer-list-item", "data-task": checked === null ? undefined : "true", children: [checked === null ? null : (_jsx("span", { className: "lp-task-mark", role: "img", "data-checked": checked ? "true" : "false", "aria-label": checked ? (zh ? "已完成" : "Done") : (zh ? "未完成" : "Not done"), children: checked ? _jsx(LucideIcon, { name: "check", size: "sm", decorative: true }) : null })), _jsx("div", { className: "lp-answer-list-item-body", children: renderChildren(component, context) })] }));
466
+ };
467
+ function rowsOf(value) {
468
+ return Array.isArray(value) ? value.filter(Array.isArray).map((row) => row.filter(isRecord)) : [];
469
+ }
470
+ export function tableParts(component) {
471
+ const header = rowsOf(component.header);
472
+ const body = rowsOf(component.rows);
473
+ const footer = typeof component.footerRows === "number" && Number.isInteger(component.footerRows) && component.footerRows > 0
474
+ ? Math.min(component.footerRows, body.length)
475
+ : 0;
476
+ const sections = Array.isArray(component.sectionRows)
477
+ ? [...new Set(component.sectionRows.filter((row) => typeof row === "number" && Number.isInteger(row) && row >= 0 && row < body.length - footer))].sort((a, b) => a - b)
478
+ : [];
479
+ const columns = Math.max(Array.isArray(component.columns) ? component.columns.filter(isRecord).length : 0, 1);
480
+ return { header, body, sections, footer, columns };
481
+ }
482
+ /** Each cell's place in the layout rows (header rows, then body rows); `null` for a cell not drawn. */
483
+ export function tablePlacement(parts) {
484
+ return placeTableCells(parts.columns, [...parts.header, ...parts.body], tableGroupStarts(parts.header.length, parts.sections, parts.body.length, parts.footer));
485
+ }
486
+ /**
487
+ * The table's rows as elements: `head` for `<thead>`, `bodies` for one `<tbody>` per section
488
+ * (the rows before the first section in their own), `foot` for `<tfoot>`, and `rows`, every body
489
+ * and footer row by its index in the props. The path of a link names its cell in the props,
490
+ * never its layout column.
491
+ */
492
+ export function tableRows(component, context) {
493
+ const parts = tableParts(component);
494
+ const placement = tablePlacement(parts);
495
+ const total = placement.length;
496
+ const columns = Array.isArray(component.columns) ? component.columns.filter(isRecord) : [];
497
+ const align = (cellAlign, index, span) => {
498
+ const value = cellAlign === "start" || cellAlign === "center" || cellAlign === "end"
499
+ ? cellAlign
500
+ : span > 1 ? "start" : columns[index]?.align;
501
+ return value === "center" ? "center" : value === "end" ? "end" : "start";
502
+ };
503
+ const sections = new Set(parts.sections);
504
+ const firstFooter = parts.body.length - parts.footer;
505
+ const cells = (row, rowIndex, section) => {
506
+ const layoutRow = section === "header" ? rowIndex : parts.header.length + rowIndex;
507
+ const sectionRow = section === "rows" && sections.has(rowIndex);
508
+ return row.flatMap((cell, cellIndex) => {
509
+ const place = placement[layoutRow]?.[cellIndex];
510
+ if (!place)
511
+ return [];
512
+ const style = { textAlign: align(cell.align, place.column, place.colSpan), paddingInline: cellPadding };
513
+ const content = richContent({ ...component, content: cell.content }, context, "content", `${section}/${rowIndex}/${cellIndex}/content`);
514
+ // A header cell names its column; a section cell names the rows of its <tbody>.
515
+ const Tag = section === "header" || sectionRow ? "th" : "td";
516
+ return [
517
+ _jsx(Tag, { colSpan: place.colSpan > 1 ? place.colSpan : undefined, rowSpan: place.rowSpan > 1 ? place.rowSpan : undefined, scope: section === "header" ? "col" : sectionRow ? "rowgroup" : undefined, "data-last-row": place.row + place.rowSpan === total ? "true" : undefined, style: style, children: _jsx("span", { className: "lp-table-cell-content", children: content }) }, cellIndex),
518
+ ];
519
+ });
520
+ };
521
+ const head = parts.header.map((row, index) => _jsx("tr", { children: cells(row, index, "header") }, index));
522
+ const rows = parts.body.map((row, index) => (_jsx("tr", { className: sections.has(index) ? "lp-table-section" : index >= firstFooter ? "lp-table-footer" : undefined, children: cells(row, index, "rows") }, index)));
523
+ const bodies = [];
524
+ rows.slice(0, firstFooter).forEach((row, index) => {
525
+ if (index === 0 || sections.has(index))
526
+ bodies.push([]);
527
+ bodies[bodies.length - 1].push(row);
528
+ });
529
+ return { head, bodies, foot: rows.slice(firstFooter), rows };
530
+ }
531
+ function TableBlock({ component, context }) {
532
+ const tableRef = useRef(null);
533
+ const shellRef = useRef(null);
534
+ const [widths, setWidths] = useState(null);
535
+ const parts = tableParts(component);
536
+ const signature = JSON.stringify([component.columns, component.header, component.rows, component.sectionRows, component.footerRows]);
537
+ useLayoutEffect(() => {
538
+ const table = tableRef.current;
539
+ const shell = shellRef.current;
540
+ if (!table || !shell)
541
+ return;
542
+ const groupStarts = tableGroupStarts(parts.header.length, parts.sections, parts.body.length, parts.footer);
543
+ const measure = () => {
544
+ // Measure every cell on one line, then lay the columns out with the shared rule. The
545
+ // rows are drawn already placed, so their spans are the placed ones.
546
+ table.dataset.measuring = "true";
547
+ const measured = [...table.querySelectorAll("tr")].map((row) => [...row.querySelectorAll("th, td")].map((cell) => {
548
+ const inner = cell.querySelector(".lp-table-cell-content");
549
+ return {
550
+ width: (inner?.scrollWidth ?? 0) + cellPadding * 2,
551
+ colSpan: Number(cell.getAttribute("colspan") ?? 1),
552
+ rowSpan: Number(cell.getAttribute("rowspan") ?? 1),
553
+ };
554
+ }));
555
+ delete table.dataset.measuring;
556
+ setWidths(layoutTableColumns(shell.clientWidth, parts.columns, measured, groupStarts).columnWidths);
557
+ };
558
+ measure();
559
+ if (typeof ResizeObserver === "undefined")
560
+ return;
561
+ const observer = new ResizeObserver(measure);
562
+ observer.observe(shell);
563
+ return () => observer.disconnect();
564
+ }, [signature, parts.columns]);
565
+ const total = widths?.reduce((sum, width) => sum + width, 0);
566
+ const { head, bodies, foot } = tableRows(component, context);
567
+ return (_jsx("div", { ref: shellRef, className: "lp-table-shell", "data-streaming": streaming(component) ? "true" : undefined, children: _jsxs("table", { ref: tableRef, className: "lp-table", style: widths ? { width: total, tableLayout: "fixed" } : undefined, children: [widths ? _jsx("colgroup", { children: widths.map((width, index) => _jsx("col", { style: { width } }, index)) }) : null, head.length ? _jsx("thead", { children: head }) : null, bodies.map((rows, index) => _jsx("tbody", { children: rows }, index)), foot.length ? _jsx("tfoot", { children: foot }) : null] }) }));
568
+ }
569
+ export const renderTable = (component, context) => withFallback(component, rowsOf(component.rows).length > 0, _jsx(TableBlock, { component: component, context: context }));
570
+ const tokenKinds = new Set(["keyword", "string", "number", "comment", "function", "type", "variable", "operator", "punctuation", "plain"]);
571
+ /** The code as elements: one span per token, or the plain text while streaming or when tokens do not spell it. */
572
+ export function codeBody(component) {
573
+ const code = typeof component.code === "string" ? component.code : "";
574
+ const tokens = !streaming(component) && Array.isArray(component.tokens)
575
+ ? component.tokens.filter((token) => isRecord(token) && typeof token.text === "string")
576
+ : null;
577
+ const usable = tokens && tokens.map((token) => token.text).join("") === code ? tokens : null;
578
+ return usable
579
+ ? usable.map((token, index) => _jsx("span", { className: `lp-token-${tokenKinds.has(token.kind) ? token.kind : "plain"}`, children: token.text }, index))
580
+ : code;
581
+ }
582
+ function CodeBlock({ component, context }) {
583
+ const code = typeof component.code === "string" ? component.code : "";
584
+ const language = typeof component.language === "string" ? component.language : null;
585
+ const [copied, setCopied] = useState(false);
586
+ const zh = chinese(context);
587
+ return (_jsxs("figure", { className: "lp-code-block", "data-streaming": streaming(component) ? "true" : undefined, children: [_jsxs("div", { className: "lp-code-header", children: [language ? _jsx("span", { className: "lp-code-language", children: language }) : _jsx("span", {}), _jsx("button", { type: "button", className: "lp-code-copy", "aria-label": copied ? (zh ? "已复制代码" : "Code copied") : (zh ? "复制代码" : "Copy code"), onClick: () => {
588
+ void globalThis.navigator?.clipboard?.writeText(code).then(() => setCopied(true), () => setCopied(false));
589
+ }, children: _jsx(LucideIcon, { name: copied ? "check" : "copy", size: "sm", decorative: true }) })] }), _jsx("pre", { className: "lp-code-body", children: _jsx("code", { children: codeBody(component) }) })] }));
590
+ }
591
+ export const renderCodeBlock = (component, context) => withFallback(component, typeof component.code === "string" && component.code.length > 0, _jsx(CodeBlock, { component: component, context: context }));
592
+ export const renderBlockquote = (component, context) => {
593
+ const children = renderChildren(component, context);
594
+ return withFallback(component, children.length > 0, (_jsx("blockquote", { className: "lp-blockquote", children: children })));
595
+ };
596
+ export const renderMath = (component, context) => {
597
+ const tex = typeof component.tex === "string" ? component.tex : "";
598
+ // The outlines the server typeset, or the TeX source when there are none (a Markdown answer, a
599
+ // formula it could not typeset) or they cannot be drawn.
600
+ const drawn = tex ? mathElement(tex, component.geometry, context.state?.dataModel, true) : null;
601
+ if (drawn)
602
+ return _jsx("div", { className: "lp-math", "data-typeset": "true", children: drawn });
603
+ return withFallback(component, tex.length > 0, (_jsx("div", { className: "lp-math", role: "math", "aria-label": tex, children: _jsx("code", { children: tex }) })));
604
+ };
605
+ /** Maximum inline Aegis blocks admitted per answer; additional blocks degrade to fallback text. */
606
+ export const MAX_ANSWER_AEGIS_BLOCKS = 3;
607
+ /** Stable per-rendered-instance key so repeated or shared templates count each rendered slot separately. */
608
+ export function aegisInstanceKey(componentId, renderPath) {
609
+ return renderPath ? `${renderPath}:${componentId}` : componentId;
610
+ }
611
+ export const renderAegisBlock = (component, context) => {
612
+ const artifact = isRecord(component.artifact) ? component.artifact : null;
613
+ const artifactFallback = artifact && isRecord(artifact.fallback) && typeof artifact.fallback.text === "string"
614
+ ? artifact.fallback.text
615
+ : null;
616
+ const fallbackText = readFallback(component)?.text ?? artifactFallback ?? "Interactive block unavailable.";
617
+ const title = validDisplayText(component.title, 120);
618
+ const open = component.chrome === "none";
619
+ const instanceKey = aegisInstanceKey(component.id, context.renderPath ?? "root");
620
+ const admitted = context.admittedAegisBlockIds?.has(instanceKey) ?? true;
621
+ let content;
622
+ if (surfaceIsStreaming(context.state)) {
623
+ content = (_jsx("div", { className: "lp-aegis-block-placeholder", "data-aegis-state": "streaming", "aria-busy": "true", role: "status", children: chinese(context) ? "正在准备交互内容…" : "Preparing interactive block…" }));
624
+ }
625
+ else if (!artifact || !admitted || !context.renderAegisBlock) {
626
+ content = _jsx("p", { className: "lp-body a2ui-fallback-text", "data-aegis-state": "fallback", children: fallbackText });
627
+ }
628
+ else {
629
+ const maxHeight = typeof component.maxHeight === "number" && Number.isFinite(component.maxHeight)
630
+ ? component.maxHeight
631
+ : undefined;
632
+ content = context.renderAegisBlock({ componentId: component.id, artifact, fallbackText, maxHeight });
633
+ }
634
+ if (!title && !open)
635
+ return content;
636
+ return (_jsxs("div", { className: "lp-aegis-block-frame", "data-chrome": open ? "none" : "default", children: [title && _jsx("h3", { className: "lp-aegis-block-title", children: title }), content] }));
637
+ };