@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,168 @@
1
+ import { createElement } from "react";
2
+ import { isRecord } from "../core/messages.js";
3
+ import { readPointer } from "../core/pointer.js";
4
+ const NUMBER = /^-?\d+(?:\.\d+)?$/;
5
+ const GLYPH_ID = /^[A-Za-z0-9]+-[A-Za-z]+\.[0-9a-f]{1,6}$/;
6
+ const ARITY = { M: 2, L: 2, C: 6, Z: 0 };
7
+ /** Room kept above and below an inline formula for ink past its box (CJK glyphs, overshoot). */
8
+ export const MATH_INK_ALLOWANCE_EM = 0.12;
9
+ /** Formulas are drawn this much larger than the text around them, as KaTeX does. */
10
+ export const MATH_SCALE = 1.21;
11
+ /** Parsed outlines by their source text; an answer names each glyph many times. */
12
+ const outlines = new Map();
13
+ const MAX_CACHED_OUTLINES = 4096;
14
+ /** The path data of one `f` element, or null when it is not exactly M/L/C/Z with numbers. */
15
+ export function fillPath(element) {
16
+ const tokens = element.split(" ");
17
+ if (tokens[0] !== "f" || tokens.length < 4)
18
+ return null;
19
+ let index = 1;
20
+ while (index < tokens.length) {
21
+ const arity = ARITY[tokens[index]];
22
+ if (arity === undefined)
23
+ return null;
24
+ for (let k = 1; k <= arity; k++)
25
+ if (!NUMBER.test(tokens[index + k] ?? ""))
26
+ return null;
27
+ index += arity + 1;
28
+ }
29
+ return tokens.slice(1).join(" ");
30
+ }
31
+ function outline(source) {
32
+ let parsed = outlines.get(source);
33
+ if (parsed === undefined) {
34
+ parsed = fillPath(source);
35
+ if (outlines.size >= MAX_CACHED_OUTLINES)
36
+ outlines.clear();
37
+ outlines.set(source, parsed);
38
+ }
39
+ return parsed;
40
+ }
41
+ function finite(value, low, high) {
42
+ return typeof value === "number" && Number.isFinite(value) && value >= low && value <= high;
43
+ }
44
+ /** The formula ready to draw, or null when the geometry or a glyph it names is missing or malformed. */
45
+ export function parseMathGeometry(value, dataModel) {
46
+ if (!isRecord(value) || typeof value.paths !== "string" || !value.paths)
47
+ return null;
48
+ const { width, height, depth } = value;
49
+ if (!finite(width, 0, 200) || !finite(height, -50, 50) || !finite(depth, -50, 50) || height + depth <= 0)
50
+ return null;
51
+ const glyphPath = isRecord(value.glyphs) && typeof value.glyphs.path === "string" ? value.glyphs.path : null;
52
+ const dictionary = glyphPath?.startsWith("/") ? readPointer(dataModel, glyphPath) : undefined;
53
+ const elements = [];
54
+ for (const element of value.paths.split("|")) {
55
+ if (element.startsWith("f ")) {
56
+ const d = fillPath(element);
57
+ if (!d)
58
+ return null;
59
+ elements.push({ d });
60
+ continue;
61
+ }
62
+ const [kind, id, x, y, scale = "1", ...rest] = element.split(" ");
63
+ if (kind !== "g" || rest.length || !GLYPH_ID.test(id ?? "") || ![x, y, scale].every((part) => NUMBER.test(part ?? "")))
64
+ return null;
65
+ const source = isRecord(dictionary) ? dictionary[id] : undefined;
66
+ const d = typeof source === "string" ? outline(source) : null;
67
+ if (!d)
68
+ return null;
69
+ elements.push({ d, transform: scale === "1" ? `translate(${x} ${y})` : `translate(${x} ${y}) scale(${scale})` });
70
+ }
71
+ return { width, height, depth, elements };
72
+ }
73
+ /** Room kept left and right for ink past the box (italic overhang), inside the scroll region. */
74
+ export const MATH_SIDE_ALLOWANCE_EM = 0.15;
75
+ /** Wider than its region: the formula scrolls, and a keyboard can reach it to scroll. */
76
+ export function syncScrollable(node) {
77
+ if (node.scrollWidth > node.clientWidth + 1)
78
+ node.tabIndex = 0;
79
+ else
80
+ node.removeAttribute("tabindex");
81
+ }
82
+ let resizes = null;
83
+ function watchWidth() {
84
+ let current = null;
85
+ return (node) => {
86
+ if (typeof ResizeObserver === "undefined") {
87
+ if (node)
88
+ syncScrollable(node);
89
+ return;
90
+ }
91
+ resizes ??= new ResizeObserver((entries) => entries.forEach((entry) => syncScrollable(entry.target)));
92
+ if (current)
93
+ resizes.unobserve(current);
94
+ current = node;
95
+ if (node) {
96
+ syncScrollable(node);
97
+ resizes.observe(node);
98
+ }
99
+ };
100
+ }
101
+ /**
102
+ * A formula that is (part of) a link is underlined like the link's words, so the link does not rely
103
+ * on colour alone: a bar as thick as a text underline (1/15 of the text size), below the formula's
104
+ * depth or the text's descent, whichever is lower, with a small gap. All in the formula's em.
105
+ */
106
+ export const MATH_LINK_UNDERLINE_DESCENT_EM = 0.2 / MATH_SCALE;
107
+ export const MATH_LINK_UNDERLINE_GAP_EM = 0.06;
108
+ export const MATH_LINK_UNDERLINE_THICKNESS_EM = 1 / 15 / MATH_SCALE;
109
+ /** Where a linked formula's underline starts below its baseline, in its em. */
110
+ export function mathLinkUnderline(depth) {
111
+ return Math.max(depth, MATH_LINK_UNDERLINE_DESCENT_EM) + MATH_LINK_UNDERLINE_GAP_EM;
112
+ }
113
+ /**
114
+ * The formula as inline SVG with the TeX as its accessible name, or null to show the TeX instead.
115
+ * The formula is its own box, never wider than the line it sits in: a wider one scrolls sideways
116
+ * inside that box (focusable then, so a keyboard can scroll it) instead of widening the page.
117
+ * The box keeps `MATH_INK_ALLOWANCE_EM` free above and below, so an inline formula never runs into
118
+ * the next line, and `MATH_SIDE_ALLOWANCE_EM` at the sides inside negative margins, so the text
119
+ * around it is spaced as before. Its bottom edge sits that far below the depth, which puts the
120
+ * formula's baseline on the text's. `display` centres a block formula on its own line.
121
+ */
122
+ export function mathElement(tex, geometry, dataModel, display, link = false) {
123
+ const drawn = parseMathGeometry(geometry, dataModel);
124
+ if (!drawn)
125
+ return null;
126
+ const total = drawn.height + drawn.depth;
127
+ const underline = link ? mathLinkUnderline(drawn.depth) : 0;
128
+ // Room kept below the depth for the underline, past the ink allowance there already.
129
+ const room = link ? Math.max(0, underline + MATH_LINK_UNDERLINE_THICKNESS_EM - drawn.depth - MATH_INK_ALLOWANCE_EM) : 0;
130
+ const paths = drawn.elements.map((element, index) => createElement("path", { key: index, d: element.d, transform: element.transform }));
131
+ if (link) {
132
+ paths.push(createElement("rect", {
133
+ key: "underline", className: "lp-math-underline", x: 0, y: drawn.height + underline,
134
+ width: drawn.width, height: MATH_LINK_UNDERLINE_THICKNESS_EM,
135
+ }));
136
+ }
137
+ const svg = createElement("svg", {
138
+ xmlns: "http://www.w3.org/2000/svg",
139
+ width: `${drawn.width}em`,
140
+ height: `${total}em`,
141
+ viewBox: `0 0 ${drawn.width} ${total}`,
142
+ fill: "currentColor",
143
+ "aria-hidden": "true",
144
+ focusable: "false",
145
+ style: { display: "block", overflow: "visible" },
146
+ }, paths);
147
+ return createElement("span", {
148
+ className: display ? "lp-math-formula lp-math-display" : "lp-math-formula",
149
+ role: "img",
150
+ "aria-label": tex,
151
+ "data-math-depth": drawn.depth,
152
+ ref: watchWidth(),
153
+ style: {
154
+ fontSize: `${MATH_SCALE}em`,
155
+ display: "inline-block",
156
+ maxWidth: "100%",
157
+ overflowX: "auto",
158
+ overflowY: "hidden",
159
+ padding: room
160
+ ? `${MATH_INK_ALLOWANCE_EM}em ${MATH_SIDE_ALLOWANCE_EM}em ${MATH_INK_ALLOWANCE_EM + room}em`
161
+ : `${MATH_INK_ALLOWANCE_EM}em ${MATH_SIDE_ALLOWANCE_EM}em`,
162
+ margin: `0 ${-MATH_SIDE_ALLOWANCE_EM}em`,
163
+ // A box that scrolls sits on the line by its bottom edge: move that down by the depth and
164
+ // the room below it.
165
+ verticalAlign: `${-(drawn.depth + MATH_INK_ALLOWANCE_EM + room)}em`,
166
+ },
167
+ }, svg);
168
+ }
@@ -0,0 +1,51 @@
1
+ import { type A2uiSurfaceState, type ApplyMessagesOptions } from "../core/state.ts";
2
+ export type SnapshotReason =
3
+ /** No snapshot has been shown yet. */
4
+ "no_snapshot"
5
+ /** The update is for another surface than the one shown. */
6
+ | "surface_mismatch"
7
+ /** The update starts from another revision than the one shown: one went missing. */
8
+ | "base_mismatch"
9
+ /** What arrived failed validation, or changes more than the Widget of an answer already done. */
10
+ | "invalid_update";
11
+ /** What a snapshot or an update did to the surface a stream shows. */
12
+ export type SurfaceStreamResult =
13
+ /** Validated and committed; the surface draws `revision` on the next render. */
14
+ {
15
+ status: "applied";
16
+ revision: number;
17
+ }
18
+ /** Not newer than the `revision` shown (a late or repeated one); nothing changed. */
19
+ | {
20
+ status: "ignored";
21
+ revision: number;
22
+ }
23
+ /** Nothing changed; the Host should send a whole snapshot. */
24
+ | {
25
+ status: "needs_snapshot";
26
+ reason: SnapshotReason;
27
+ };
28
+ export type SurfaceStream = {
29
+ /**
30
+ * Shows a whole `SurfaceArtifact` (an object, or its JSON text). One of another surface
31
+ * replaces what is shown; one of the same surface replaces it in place when its `revision`
32
+ * is newer. Once the answer is done, a snapshot of it is taken only if it changes nothing
33
+ * but the Widget, and is refused with `invalid_update` otherwise (do not send it again); to
34
+ * show the whole answer anew, use a new stream.
35
+ */
36
+ snapshot(artifact: unknown): SurfaceStreamResult;
37
+ /**
38
+ * Applies a `SurfaceUpdate` (an object, or its JSON text) to the surface shown. It must be
39
+ * for that surface and start from the revision shown. Once the answer is done, an update may
40
+ * change only its Widget (as a Widget refresh does).
41
+ */
42
+ update(update: unknown): SurfaceStreamResult;
43
+ /** The surface drawn now, or null before the first snapshot. */
44
+ getState(): A2uiSurfaceState | null;
45
+ /** The revision drawn now, or null before the first snapshot. */
46
+ getRevision(): number | null;
47
+ /** Called after each `applied`; returns the unsubscribe function. */
48
+ subscribe(listener: () => void): () => void;
49
+ };
50
+ /** A stream for one place on the page; `options` are those of `applyMessages`. */
51
+ export declare function createSurfaceStream(options?: ApplyMessagesOptions): SurfaceStream;
@@ -0,0 +1,260 @@
1
+ /**
2
+ * One surface a Host keeps current with a snapshot and then only updates.
3
+ *
4
+ * A whole answer is streamed this way: the first compile result is the `snapshot` (a
5
+ * `SurfaceArtifact`), and each later one arrives as a `SurfaceUpdate`, the messages that
6
+ * changed from `base_revision` to `revision`. The same rules as `LittlePressSurfaceStream` in
7
+ * Compose and SwiftUI: neither call changes what is shown unless it returns `applied`; on
8
+ * `needs_snapshot` the Host sends a whole snapshot (also after a reconnect or a reload);
9
+ * `ignored` needs nothing. Once the answer is done, only its Widget can still change.
10
+ *
11
+ * Every message, in a snapshot or an update, gets the same checks as on the native SDKs and
12
+ * is folded onto the state already shown; earlier messages are not replayed.
13
+ */
14
+ import { readLocalA2uiArtifact } from "../core/bundle.js";
15
+ import { isChildTemplate, isRecord, readMessageKind } from "../core/messages.js";
16
+ import { parsePointer } from "../core/pointer.js";
17
+ import { applyMessages, createEmptyA2uiState, } from "../core/state.js";
18
+ const MAX_DEPTH = 48;
19
+ const MAX_POINTER_LENGTH = 1024;
20
+ const MAX_POINTER_SEGMENTS = 32;
21
+ const MAX_COMPONENT_ID_LENGTH = 160;
22
+ function parse(value) {
23
+ if (typeof value !== "string")
24
+ return value;
25
+ try {
26
+ return JSON.parse(value);
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ function readRevision(value) {
33
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
34
+ }
35
+ function withinDepth(value, depth = 0) {
36
+ if (depth > MAX_DEPTH)
37
+ return false;
38
+ if (Array.isArray(value))
39
+ return value.every((entry) => withinDepth(entry, depth + 1));
40
+ if (isRecord(value))
41
+ return Object.values(value).every((entry) => withinDepth(entry, depth + 1));
42
+ return true;
43
+ }
44
+ function validPointer(path) {
45
+ return path.length <= MAX_POINTER_LENGTH && path.split("/").length <= MAX_POINTER_SEGMENTS
46
+ && parsePointer(path) !== null && !/~(?![01])/u.test(path);
47
+ }
48
+ /**
49
+ * A write may replace an array item or add the next one, never leave a gap: the renderer
50
+ * would otherwise grow an array of any length from one short write past its end.
51
+ */
52
+ function writesWithoutGap(model, path) {
53
+ let current = model;
54
+ for (const segment of parsePointer(path) ?? []) {
55
+ const index = /^\d+$/u.test(segment) ? Number(segment) : null;
56
+ if (Array.isArray(current) || (!isRecord(current) && index !== null)) {
57
+ const length = Array.isArray(current) ? current.length : 0;
58
+ if (index === null || index > length)
59
+ return false;
60
+ current = Array.isArray(current) ? current[index] : undefined;
61
+ }
62
+ else {
63
+ current = isRecord(current) ? current[segment] : undefined;
64
+ }
65
+ }
66
+ return true;
67
+ }
68
+ /** Issues that refuse a message: all but a component drawn as a placeholder. */
69
+ function hardIssues(issues) {
70
+ return issues.filter((issue) => issue.kind !== "unsupported_component").length;
71
+ }
72
+ /**
73
+ * Checks one message as a bundle message is checked, then folds it onto `state`; null when it
74
+ * fails. Only the first message of a snapshot creates the surface.
75
+ */
76
+ function fold(state, message, first, options) {
77
+ if (!isRecord(message) || message.version !== "v1.0" || Object.keys(message).length !== 2)
78
+ return null;
79
+ const kind = readMessageKind(message);
80
+ if (kind !== "createSurface" && kind !== "updateComponents" && kind !== "updateDataModel")
81
+ return null;
82
+ if (first !== (kind === "createSurface"))
83
+ return null;
84
+ const payload = message[kind];
85
+ if (typeof payload.surfaceId !== "string" || payload.surfaceId.length === 0)
86
+ return null;
87
+ if (!first && payload.surfaceId !== state.surfaceId)
88
+ return null;
89
+ if (kind === "updateDataModel") {
90
+ if (!("value" in payload) || (payload.path !== undefined && typeof payload.path !== "string"))
91
+ return null;
92
+ const path = payload.path ?? "";
93
+ if (!validPointer(path) || (payload.value !== null && !writesWithoutGap(state.dataModel, path)))
94
+ return null;
95
+ }
96
+ else {
97
+ if (!Array.isArray(payload.components))
98
+ return null;
99
+ const ids = new Set();
100
+ for (const component of payload.components) {
101
+ if (!isRecord(component) || typeof component.id !== "string" || typeof component.component !== "string")
102
+ return null;
103
+ if (component.id.length === 0 || component.id.length > MAX_COMPONENT_ID_LENGTH || component.component.length === 0)
104
+ return null;
105
+ if (ids.has(component.id))
106
+ return null;
107
+ ids.add(component.id);
108
+ }
109
+ }
110
+ const next = applyMessages(state, [message], options);
111
+ if (hardIssues(next.issues) > (first ? 0 : hardIssues(state.issues)) || !withinDepth(next.dataModel))
112
+ return null;
113
+ return next;
114
+ }
115
+ /** Folds `messages` onto `state`; null when any fails or the result has no root to draw. */
116
+ function foldAll(state, messages, creates, options) {
117
+ let next = state;
118
+ for (const [index, message] of messages.entries()) {
119
+ next = fold(next, message, creates && index === 0, options);
120
+ if (!next)
121
+ return null;
122
+ }
123
+ return !next.deleted && next.components.root ? next : null;
124
+ }
125
+ function answerState(state) {
126
+ const runtime = isRecord(state.dataModel) ? state.dataModel.runtimeState : undefined;
127
+ return isRecord(runtime) ? runtime.answerState : undefined;
128
+ }
129
+ const inWidget = (id) => id.startsWith("w.");
130
+ const inData = (path) => path === "/data" || path.startsWith("/data/");
131
+ /** Whether every message changes only the Widget that follows a done answer. */
132
+ function onlyWidget(messages) {
133
+ return messages.every((message) => {
134
+ if (!isRecord(message))
135
+ return false;
136
+ const components = isRecord(message.updateComponents) ? message.updateComponents.components : undefined;
137
+ if (Array.isArray(components)) {
138
+ return components.every((component) => isRecord(component) && typeof component.id === "string" && inWidget(component.id));
139
+ }
140
+ const path = isRecord(message.updateDataModel) ? message.updateDataModel.path : undefined;
141
+ return typeof path === "string" && inData(path);
142
+ });
143
+ }
144
+ function same(a, b) {
145
+ if (Object.is(a, b))
146
+ return true;
147
+ if (Array.isArray(a) || Array.isArray(b)) {
148
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((entry, index) => same(entry, b[index]));
149
+ }
150
+ if (!isRecord(a) || !isRecord(b))
151
+ return false;
152
+ const keys = Object.keys(a);
153
+ return keys.length === Object.keys(b).length && keys.every((key) => key in b && same(a[key], b[key]));
154
+ }
155
+ /** The tree drawn from the root, without the Widget's `w.` components. */
156
+ function drawnAnswer(state) {
157
+ const visit = (id, path) => {
158
+ const component = state.components[id];
159
+ if (!component || path.has(id))
160
+ return { missing: id };
161
+ const inner = new Set(path).add(id);
162
+ const { children, ...props } = component;
163
+ const drawn = Array.isArray(children)
164
+ ? children.filter((child) => typeof child === "string" && !inWidget(child)).map((child) => visit(child, inner))
165
+ : isChildTemplate(children)
166
+ ? { ...children, template: inWidget(children.componentId) ? null : visit(children.componentId, inner) }
167
+ : children;
168
+ return { ...props, children: drawn };
169
+ };
170
+ return state.rootComponentId ? visit(state.rootComponentId, new Set()) : null;
171
+ }
172
+ /**
173
+ * Whether `next` is `current` with at most its Widget changed: the catalog, the renderer hints
174
+ * (style pack, mode, frame), the tree drawn outside the `w.` components and the data model
175
+ * outside `/data` are the same. The drawn tree, not every component ever sent, since an update
176
+ * may leave a component no longer drawn that a fresh snapshot of the same answer does not carry.
177
+ */
178
+ function differsOnlyInWidget(current, next) {
179
+ const model = (state) => {
180
+ if (!isRecord(state.dataModel))
181
+ return state.dataModel;
182
+ const rest = { ...state.dataModel };
183
+ delete rest.data;
184
+ return rest;
185
+ };
186
+ return next.surfaceId === current.surfaceId && next.catalogId === current.catalogId
187
+ && same(next.rendererHints, current.rendererHints)
188
+ && same(drawnAnswer(next), drawnAnswer(current)) && same(model(next), model(current));
189
+ }
190
+ /** A stream for one place on the page; `options` are those of `applyMessages`. */
191
+ export function createSurfaceStream(options = {}) {
192
+ let shown = null;
193
+ let revision = null;
194
+ const listeners = new Set();
195
+ function commit(next, nextRevision) {
196
+ shown = next;
197
+ revision = nextRevision;
198
+ for (const listener of [...listeners])
199
+ listener();
200
+ return { status: "applied", revision: nextRevision };
201
+ }
202
+ function readSnapshot(value) {
203
+ if (!isRecord(value) || !withinDepth(value) || !readLocalA2uiArtifact(value) || !Array.isArray(value.messages))
204
+ return null;
205
+ // A bundle without a revision is revision 0, as on the native SDKs.
206
+ const nextRevision = value.revision === undefined ? 0 : readRevision(value.revision);
207
+ if (nextRevision === null)
208
+ return null;
209
+ const state = foldAll(createEmptyA2uiState(), value.messages, true, options);
210
+ return state ? { state, revision: nextRevision } : null;
211
+ }
212
+ return {
213
+ snapshot(input) {
214
+ const next = readSnapshot(parse(input));
215
+ if (!next)
216
+ return { status: "needs_snapshot", reason: shown ? "invalid_update" : "no_snapshot" };
217
+ if (shown && revision !== null && shown.surfaceId === next.state.surfaceId) {
218
+ if (next.revision <= revision)
219
+ return { status: "ignored", revision };
220
+ // The same rule as an update: a done answer is final, only its Widget can change.
221
+ if (answerState(shown) === "done" && !differsOnlyInWidget(shown, next.state)) {
222
+ return { status: "needs_snapshot", reason: "invalid_update" };
223
+ }
224
+ }
225
+ return commit(next.state, next.revision);
226
+ },
227
+ update(input) {
228
+ if (!shown || revision === null)
229
+ return { status: "needs_snapshot", reason: "no_snapshot" };
230
+ const update = parse(input);
231
+ if (!isRecord(update) || update.contract_version !== "1.0" || !withinDepth(update)) {
232
+ return { status: "needs_snapshot", reason: "invalid_update" };
233
+ }
234
+ const base = readRevision(update.base_revision);
235
+ const target = readRevision(update.revision);
236
+ const messages = update.messages;
237
+ if (typeof update.surface_id !== "string" || update.surface_id.length === 0 || base === null || target === null
238
+ || target <= base || !Array.isArray(messages) || messages.length === 0) {
239
+ return { status: "needs_snapshot", reason: "invalid_update" };
240
+ }
241
+ if (update.surface_id !== shown.surfaceId)
242
+ return { status: "needs_snapshot", reason: "surface_mismatch" };
243
+ if (target <= revision)
244
+ return { status: "ignored", revision };
245
+ if (base !== revision)
246
+ return { status: "needs_snapshot", reason: "base_mismatch" };
247
+ // A done answer is final; only the Host's refresh of the Widget after it still changes it.
248
+ if (answerState(shown) === "done" && !onlyWidget(messages))
249
+ return { status: "needs_snapshot", reason: "invalid_update" };
250
+ const next = foldAll(shown, messages, false, options);
251
+ return next ? commit(next, target) : { status: "needs_snapshot", reason: "invalid_update" };
252
+ },
253
+ getState: () => shown,
254
+ getRevision: () => revision,
255
+ subscribe(listener) {
256
+ listeners.add(listener);
257
+ return () => { listeners.delete(listener); };
258
+ },
259
+ };
260
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The LPTable_Default layout rule, shared word for word with Compose and SwiftUI
3
+ * (`contracts/fixtures/renderer/table-layout.json`). Inputs are measured single-line widths
4
+ * that already include a cell's horizontal padding, so the rule is a pure function. Row
5
+ * heights are left to the browser's table layout; the native renderers apply the fixture's
6
+ * `rowCases` themselves.
7
+ */
8
+ export declare const minColumnWidth = 48;
9
+ export declare const maxColumnWidth = 280;
10
+ export type MeasuredCell = {
11
+ width: number;
12
+ colSpan?: number;
13
+ rowSpan?: number;
14
+ };
15
+ export type TableLayout = {
16
+ columnWidths: number[];
17
+ scroll: boolean;
18
+ wrapped: Array<[number, number]>;
19
+ };
20
+ /** Where a cell is drawn: its first row and column and how many of each it covers. */
21
+ export type PlacedCell = {
22
+ row: number;
23
+ column: number;
24
+ rowSpan: number;
25
+ colSpan: number;
26
+ };
27
+ /**
28
+ * Places each cell as HTML does, within the table: row by row, in the next column no
29
+ * row-spanning cell above has taken. A `colSpan` stops before a taken column and at the last
30
+ * column, a `rowSpan` at the last row of its group (`groupStarts`: the first body row, each
31
+ * section row, the first footer row), and a cell with no column left is not drawn (`null`).
32
+ */
33
+ export declare function placeTableCells(columns: number, rows: readonly (readonly {
34
+ colSpan?: unknown;
35
+ rowSpan?: unknown;
36
+ }[])[], groupStarts?: readonly number[]): Array<Array<PlacedCell | null>>;
37
+ /**
38
+ * The rows where a span's group starts, counted over the header rows followed by the body
39
+ * rows: the first body row, each section row and the first footer row.
40
+ */
41
+ export declare function tableGroupStarts(headerRows: number, sectionRows: readonly number[], bodyRows: number, footerRows: number): number[];
42
+ export declare function layoutTableColumns(container: number, columns: number, rows: readonly (readonly MeasuredCell[])[], groupStarts?: readonly number[]): TableLayout;
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The LPTable_Default layout rule, shared word for word with Compose and SwiftUI
3
+ * (`contracts/fixtures/renderer/table-layout.json`). Inputs are measured single-line widths
4
+ * that already include a cell's horizontal padding, so the rule is a pure function. Row
5
+ * heights are left to the browser's table layout; the native renderers apply the fixture's
6
+ * `rowCases` themselves.
7
+ */
8
+ export const minColumnWidth = 48;
9
+ export const maxColumnWidth = 280;
10
+ function count(value) {
11
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(1, Math.floor(value)) : 1;
12
+ }
13
+ /**
14
+ * Places each cell as HTML does, within the table: row by row, in the next column no
15
+ * row-spanning cell above has taken. A `colSpan` stops before a taken column and at the last
16
+ * column, a `rowSpan` at the last row of its group (`groupStarts`: the first body row, each
17
+ * section row, the first footer row), and a cell with no column left is not drawn (`null`).
18
+ */
19
+ export function placeTableCells(columns, rows, groupStarts = []) {
20
+ const starts = [...new Set(groupStarts)].filter((start) => start > 0 && start < rows.length).sort((a, b) => a - b);
21
+ const taken = new Set();
22
+ return rows.map((row, rowIndex) => {
23
+ const end = starts.find((start) => start > rowIndex) ?? rows.length;
24
+ let column = 0;
25
+ return row.map((cell) => {
26
+ while (column < columns && taken.has(`${rowIndex}:${column}`))
27
+ column += 1;
28
+ if (column >= columns)
29
+ return null;
30
+ let colSpan = Math.min(count(cell.colSpan), columns - column);
31
+ for (let step = 1; step < colSpan; step += 1) {
32
+ if (taken.has(`${rowIndex}:${column + step}`)) {
33
+ colSpan = step;
34
+ break;
35
+ }
36
+ }
37
+ const rowSpan = Math.min(count(cell.rowSpan), end - rowIndex);
38
+ for (let down = 0; down < rowSpan; down += 1) {
39
+ for (let across = 0; across < colSpan; across += 1)
40
+ taken.add(`${rowIndex + down}:${column + across}`);
41
+ }
42
+ const placed = { row: rowIndex, column, rowSpan, colSpan };
43
+ column += colSpan;
44
+ return placed;
45
+ });
46
+ });
47
+ }
48
+ /**
49
+ * The rows where a span's group starts, counted over the header rows followed by the body
50
+ * rows: the first body row, each section row and the first footer row.
51
+ */
52
+ export function tableGroupStarts(headerRows, sectionRows, bodyRows, footerRows) {
53
+ const starts = headerRows > 0 ? [headerRows] : [];
54
+ for (const row of sectionRows)
55
+ starts.push(headerRows + row);
56
+ if (footerRows > 0)
57
+ starts.push(headerRows + bodyRows - footerRows);
58
+ return starts;
59
+ }
60
+ export function layoutTableColumns(container, columns, rows, groupStarts = []) {
61
+ const placed = placeTableCells(columns, rows, groupStarts).flatMap((row, rowIndex) => row.flatMap((cell, cellIndex) => (cell ? [{ ...cell, width: rows[rowIndex][cellIndex].width }] : [])));
62
+ const widths = Array.from({ length: columns }, (_, column) => {
63
+ const own = placed.filter(cell => cell.colSpan === 1 && cell.column === column).map(cell => cell.width);
64
+ return Math.min(Math.max(own.length ? Math.max(...own) : minColumnWidth, minColumnWidth), maxColumnWidth);
65
+ });
66
+ // Spanning cells in placement order: header rows first, then body rows, each left to right.
67
+ for (const cell of placed) {
68
+ if (cell.colSpan === 1)
69
+ continue;
70
+ const need = Math.min(cell.width, maxColumnWidth * cell.colSpan);
71
+ const end = cell.column + cell.colSpan;
72
+ const have = widths.slice(cell.column, end).reduce((sum, width) => sum + width, 0);
73
+ if (need > have) {
74
+ const extra = (need - have) / cell.colSpan;
75
+ for (let column = cell.column; column < end; column += 1)
76
+ widths[column] += extra;
77
+ }
78
+ }
79
+ const total = widths.reduce((sum, width) => sum + width, 0);
80
+ const scroll = total > container;
81
+ const final = total > 0 && total < container ? widths.map(width => width * container / total) : widths;
82
+ const wrapped = [];
83
+ for (const cell of placed) {
84
+ const given = final.slice(cell.column, cell.column + cell.colSpan).reduce((sum, width) => sum + width, 0);
85
+ if (cell.width > given + 1e-9)
86
+ wrapped.push([cell.row, cell.column]);
87
+ }
88
+ return { columnWidths: final, scroll, wrapped };
89
+ }
@@ -0,0 +1,5 @@
1
+ import type { RenderContext } from "../core/context.ts";
2
+ export declare function ActionFeedback({ context, scope }: {
3
+ context: RenderContext;
4
+ scope: string;
5
+ }): import("react/jsx-runtime").JSX.Element | null;
@@ -0,0 +1,43 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useLayoutEffect, useRef } from "react";
3
+ import { isChineseLanguage, surfaceLanguage } from "./fieldMessages.js";
4
+ const rowTapComponents = new Set(["lp.stack", "LPStack_Default", "lp.card", "LPCard_Default"]);
5
+ function ExecutionFeedback({ record, session, zh }) {
6
+ const statusRef = useRef(null);
7
+ const returnFocus = useRef(false);
8
+ const outcome = record.outcome;
9
+ useLayoutEffect(() => {
10
+ // The query button disappears on confirmation. Keep keyboard users at the result,
11
+ // unless they deliberately moved focus elsewhere while the query was running.
12
+ if (returnFocus.current && outcome?.status !== "unknown" && !record.pending) {
13
+ statusRef.current?.focus();
14
+ returnFocus.current = false;
15
+ }
16
+ }, [outcome, record.pending]);
17
+ const pending = record.pending || record.querying;
18
+ const hidden = record.pending && record.action.metadata.loadingBehavior === "none";
19
+ // A tappable composed row already dims and spins while it works (R7); its "Working…" is
20
+ // announced but not drawn, so the rows below do not jump.
21
+ const rowTap = rowTapComponents.has(record.action.component);
22
+ const announceOnly = pending && rowTap;
23
+ const text = record.querying ? (zh ? "正在查询原操作的结果…" : "Checking the original operation…")
24
+ : record.pending ? (zh ? "正在处理…" : "Working…")
25
+ : outcome?.status === "succeeded" ? outcome.message
26
+ : outcome?.status === "cancelled" ? (zh ? "操作已取消。" : "The operation was cancelled.")
27
+ : outcome?.status === "failed" ? (outcome.code === "action_unavailable"
28
+ ? (zh ? "此 App 无法执行这个操作。" : "This action is unavailable in this app.")
29
+ : outcome.message) + (outcome.retryable ? (zh ? "你可以重新执行。" : " You can try the action again.") : "")
30
+ : zh ? "结果尚未确认,请先查询或到原业务系统确认,避免重复执行。" : "The result is unknown. Check it here or in the original app before acting again.";
31
+ return _jsxs("div", { className: hidden || announceOnly ? "lp-visually-hidden" : "lp-action-feedback", "data-action-status": pending ? "pending" : outcome?.status, children: [_jsx("p", { ref: statusRef, tabIndex: -1, role: "status", "aria-live": "polite", "aria-atomic": "true", children: hidden ? "" : text }), outcome?.status === "unknown" && record.queryable ? _jsx("button", { type: "button", className: "lp-btn ghost", "aria-disabled": record.querying, onBlur: () => { returnFocus.current = false; }, onClick: event => {
32
+ returnFocus.current = event.currentTarget.matches(":focus");
33
+ session.recover(record.key);
34
+ }, children: zh ? "查询结果" : "Check result" }) : null] });
35
+ }
36
+ export function ActionFeedback({ context, scope }) {
37
+ const session = context.actionSession;
38
+ if (!session)
39
+ return null;
40
+ const zh = isChineseLanguage(surfaceLanguage(context.state.rendererHints));
41
+ return _jsx(_Fragment, { children: [...session.records.values()].filter(record => record.scope === scope)
42
+ .map(record => _jsx(ExecutionFeedback, { record: record, session: session, zh: zh }, record.key)) });
43
+ }