@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.
- package/LICENSE +202 -0
- package/NOTICE +20 -0
- package/README.md +229 -2
- package/dist/answer/answerComponents.d.ts +107 -0
- package/dist/answer/answerComponents.js +637 -0
- package/dist/answer/download.d.ts +63 -0
- package/dist/answer/download.js +109 -0
- package/dist/answer/downloadExport.d.ts +44 -0
- package/dist/answer/downloadExport.js +266 -0
- package/dist/answer/hostValues.d.ts +28 -0
- package/dist/answer/hostValues.js +379 -0
- package/dist/answer/mapComponent.d.ts +6 -0
- package/dist/answer/mapComponent.js +213 -0
- package/dist/answer/math.d.ts +57 -0
- package/dist/answer/math.js +168 -0
- package/dist/answer/surfaceStream.d.ts +51 -0
- package/dist/answer/surfaceStream.js +260 -0
- package/dist/answer/tableLayout.d.ts +42 -0
- package/dist/answer/tableLayout.js +89 -0
- package/dist/controls/ActionFeedback.d.ts +5 -0
- package/dist/controls/ActionFeedback.js +43 -0
- package/dist/controls/actionDispatch.d.ts +51 -0
- package/dist/controls/actionDispatch.js +211 -0
- package/dist/controls/actionOutcome.generated.d.ts +64 -0
- package/dist/controls/actionOutcome.generated.js +64 -0
- package/dist/controls/calculationPublisher.d.ts +14 -0
- package/dist/controls/calculationPublisher.js +6 -0
- package/dist/controls/calculations.d.ts +20 -0
- package/dist/controls/calculations.generated.d.ts +73 -0
- package/dist/controls/calculations.generated.js +85 -0
- package/dist/controls/calculations.js +208 -0
- package/dist/controls/controlState.d.ts +84 -0
- package/dist/controls/controlState.js +256 -0
- package/dist/controls/fieldMessages.d.ts +41 -0
- package/dist/controls/fieldMessages.js +81 -0
- package/dist/controls/fieldValidation.d.ts +19 -0
- package/dist/controls/fieldValidation.js +98 -0
- package/dist/controls/formComponents.d.ts +23 -0
- package/dist/controls/formComponents.js +738 -0
- package/dist/controls/formProgress.d.ts +63 -0
- package/dist/controls/formProgress.js +122 -0
- package/dist/controls/inputDrafts.d.ts +55 -0
- package/dist/controls/inputDrafts.js +183 -0
- package/dist/controls/inputValidation.d.ts +33 -0
- package/dist/controls/inputValidation.js +119 -0
- package/dist/controls/localWrites.d.ts +9 -0
- package/dist/controls/localWrites.js +29 -0
- package/dist/core/A2uiSurface.d.ts +13 -0
- package/dist/core/A2uiSurface.js +15 -0
- package/dist/core/AtlasIcon.d.ts +18 -0
- package/dist/core/AtlasIcon.js +22 -0
- package/dist/core/AtlasMedia.d.ts +22 -0
- package/dist/core/AtlasMedia.js +45 -0
- package/dist/core/Carousel.d.ts +61 -0
- package/dist/core/Carousel.js +183 -0
- package/dist/core/CoreMedia.d.ts +19 -0
- package/dist/core/CoreMedia.js +25 -0
- package/dist/core/FoundationA2uiSurface.d.ts +86 -0
- package/dist/core/FoundationA2uiSurface.js +440 -0
- package/dist/core/ImagePreview.d.ts +42 -0
- package/dist/core/ImagePreview.js +73 -0
- package/dist/core/LucideIcon.d.ts +19 -0
- package/dist/core/LucideIcon.js +42 -0
- package/dist/core/SurfaceLink.d.ts +35 -0
- package/dist/core/SurfaceLink.js +60 -0
- package/dist/core/appearance/aegis.d.ts +49 -0
- package/dist/core/appearance/aegis.js +34 -0
- package/dist/core/appearance/colour.d.ts +24 -0
- package/dist/core/appearance/colour.js +103 -0
- package/dist/core/appearance/css.d.ts +17 -0
- package/dist/core/appearance/css.js +153 -0
- package/dist/core/appearance/presets.generated.d.ts +4 -0
- package/dist/core/appearance/presets.generated.js +1184 -0
- package/dist/core/appearance/react.d.ts +29 -0
- package/dist/core/appearance/react.js +110 -0
- package/dist/core/appearance/resolve.d.ts +76 -0
- package/dist/core/appearance/resolve.js +127 -0
- package/dist/core/appearance/textScale.d.ts +11 -0
- package/dist/core/appearance/textScale.js +51 -0
- package/dist/core/appearance/theme.d.ts +138 -0
- package/dist/core/appearance/theme.js +274 -0
- package/dist/core/baseComponents.d.ts +53 -0
- package/dist/core/baseComponents.js +480 -0
- package/dist/core/binding.d.ts +46 -0
- package/dist/core/binding.js +118 -0
- package/dist/core/bundle.d.ts +23 -0
- package/dist/core/bundle.js +75 -0
- package/dist/core/catalog/catalog-index.generated.d.ts +44 -0
- package/dist/core/catalog/catalog-index.generated.js +79 -0
- package/dist/core/catalog/icons.generated.d.ts +6 -0
- package/dist/core/catalog/icons.generated.js +1788 -0
- package/dist/core/catalog.d.ts +6 -0
- package/dist/core/catalog.generated.d.ts +50 -0
- package/dist/core/catalog.generated.js +2174 -0
- package/dist/core/catalog.js +8 -0
- package/dist/core/chartRows.d.ts +7 -0
- package/dist/core/chartRows.js +38 -0
- package/dist/core/component-support.d.ts +39 -0
- package/dist/core/component-support.js +127 -0
- package/dist/core/components/actions.d.ts +4 -0
- package/dist/core/components/actions.js +21 -0
- package/dist/core/components/cards.d.ts +9 -0
- package/dist/core/components/cards.js +227 -0
- package/dist/core/components/charts.d.ts +18 -0
- package/dist/core/components/charts.js +412 -0
- package/dist/core/components/comparisonTable.d.ts +50 -0
- package/dist/core/components/comparisonTable.js +89 -0
- package/dist/core/components/content.d.ts +13 -0
- package/dist/core/components/content.js +108 -0
- package/dist/core/components/seriesCharts.d.ts +531 -0
- package/dist/core/components/seriesCharts.js +1053 -0
- package/dist/core/components/stepFlow.d.ts +7 -0
- package/dist/core/components/stepFlow.js +13 -0
- package/dist/core/components.full.d.ts +10 -0
- package/dist/core/components.full.js +41 -0
- package/dist/core/context.d.ts +207 -0
- package/dist/core/context.js +172 -0
- package/dist/core/coverage.d.ts +30 -0
- package/dist/core/coverage.js +93 -0
- package/dist/core/foundation.d.ts +21 -0
- package/dist/core/foundation.js +22 -0
- package/dist/core/fullTheme.d.ts +5 -0
- package/dist/core/fullTheme.js +9 -0
- package/dist/core/iconNodes.generated.d.ts +7 -0
- package/dist/core/iconNodes.generated.js +5 -0
- package/dist/core/lucideIcons.d.ts +5 -0
- package/dist/core/lucideIcons.js +7 -0
- package/dist/core/messages.d.ts +111 -0
- package/dist/core/messages.js +134 -0
- package/dist/core/pointer.d.ts +17 -0
- package/dist/core/pointer.js +104 -0
- package/dist/core/registry.d.ts +12 -0
- package/dist/core/registry.js +114 -0
- package/dist/core/runtime.d.ts +8 -0
- package/dist/core/runtime.js +6 -0
- package/dist/core/state.d.ts +73 -0
- package/dist/core/state.js +274 -0
- package/dist/core/surfaceMotion.d.ts +5 -0
- package/dist/core/surfaceMotion.js +46 -0
- package/dist/core/theme.d.ts +5 -0
- package/dist/core/theme.js +7 -0
- package/dist/core/useSurfaceImage.d.ts +20 -0
- package/dist/core/useSurfaceImage.js +65 -0
- package/dist/graph/RelationshipGraph.d.ts +14 -0
- package/dist/graph/RelationshipGraph.js +206 -0
- package/dist/graph/model.d.ts +20 -0
- package/dist/graph/model.js +36 -0
- package/dist/graph/program/assets.d.ts +3 -0
- package/dist/graph/program/assets.js +3 -0
- package/dist/graph/program/bridge.d.ts +6 -0
- package/dist/graph/program/bridge.generated.d.ts +136 -0
- package/dist/graph/program/bridge.generated.js +1 -0
- package/dist/graph/program/bridge.js +24 -0
- package/dist/graph/program/bridge.schema.json +717 -0
- package/dist/graph/program/bridgeValidator.cjs +2 -0
- package/dist/graph/program/bridgeValidator.d.cts +4 -0
- package/dist/graph/program/runner.d.ts +1 -0
- package/dist/graph/program/runner.html +2193 -0
- package/dist/graph/program/runner.js +157 -0
- package/dist/graph/program/runtime-manifest.json +1 -0
- package/dist/graph/program/view.d.ts +11 -0
- package/dist/graph/program/view.js +210 -0
- package/dist/graph/program/worker.d.ts +1 -0
- package/dist/graph/program/worker.js +2186 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +45 -0
- package/dist/internal/dsh.d.ts +4 -0
- package/dist/internal/dsh.js +3 -0
- package/dist/internal/relationship-graph.d.ts +4 -0
- package/dist/internal/relationship-graph.js +7202 -0
- package/dist/page/layoutComponents.d.ts +6 -0
- package/dist/page/layoutComponents.js +123 -0
- package/dist/page/layoutGeometry.d.ts +68 -0
- package/dist/page/layoutGeometry.js +174 -0
- package/dist/page/pageFormat.d.ts +34 -0
- package/dist/page/pageFormat.js +119 -0
- package/dist/page/printFit.d.ts +81 -0
- package/dist/page/printFit.js +338 -0
- package/dist/react/index.d.ts +5 -0
- package/dist/react/index.js +2 -0
- package/dist/report/locate.d.ts +42 -0
- package/dist/report/locate.js +34 -0
- package/dist/styles/renderer.css +4580 -0
- package/licenses/LUCIDE-LICENSE.txt +43 -0
- package/licenses/QUICKJS-EMSCRIPTEN-LICENSE.txt +21 -0
- package/licenses/QUICKJS-VARIANT-LICENSE.txt +47 -0
- package/package.json +68 -3
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
3
|
+
import { rendererStylePacks } from "./theme.js";
|
|
4
|
+
import { appearanceCssVariables, appearanceDataAttributes } from "./appearance/css.js";
|
|
5
|
+
import { themePresets } from "./appearance/presets.generated.js";
|
|
6
|
+
import { useAppearanceResult } from "./appearance/react.js";
|
|
7
|
+
import { createCalculationSession } from "../controls/calculations.js";
|
|
8
|
+
import { calculationSnapshotFor } from "../controls/calculationPublisher.js";
|
|
9
|
+
import { rendererCapabilities } from "./foundation.js";
|
|
10
|
+
import { readBindingPointer, resolveBoolean, resolvePointerIn, resolveRecordList, resolveValue } from "./binding.js";
|
|
11
|
+
import { isChildTemplate } from "./messages.js";
|
|
12
|
+
import { parsePointer, readPointer } from "./pointer.js";
|
|
13
|
+
import { aegisInstanceKey, MAX_ANSWER_AEGIS_BLOCKS } from "../answer/answerComponents.js";
|
|
14
|
+
import { calculationInputErrors, createInputDraft, discardStaleDrafts, reconcileInputDrafts } from "../controls/inputDrafts.js";
|
|
15
|
+
import { applyLocalOverrides, draftsAfterLocalWrite, overridesAfterEdit } from "../controls/localWrites.js";
|
|
16
|
+
import { isChineseLanguage, surfaceLanguage } from "../controls/fieldMessages.js";
|
|
17
|
+
import { formatAspectRatio } from "../page/pageFormat.js";
|
|
18
|
+
import { foundationRendererRegistry, RenderComponent } from "./registry.js";
|
|
19
|
+
import { locateComponentIn, surfaceAnchorPrefix } from "../report/locate.js";
|
|
20
|
+
import { createSurfaceMotion } from "./surfaceMotion.js";
|
|
21
|
+
import { actionRevisionOf, createActionSession, surfaceIsStreaming } from "../controls/actionDispatch.js";
|
|
22
|
+
import { ActionFeedback } from "../controls/ActionFeedback.js";
|
|
23
|
+
const noopAction = () => { };
|
|
24
|
+
export function collectAdmittedAegisBlockIds(state, binding, valueFunctions) {
|
|
25
|
+
const admitted = new Set();
|
|
26
|
+
if (!state?.rootComponentId || state.deleted)
|
|
27
|
+
return admitted;
|
|
28
|
+
const visit = (id, ancestors, currentBinding, renderPath) => {
|
|
29
|
+
if (admitted.size >= MAX_ANSWER_AEGIS_BLOCKS || ancestors.includes(id) || ancestors.length >= 32)
|
|
30
|
+
return;
|
|
31
|
+
const comp = state.components[id];
|
|
32
|
+
if (!comp)
|
|
33
|
+
return;
|
|
34
|
+
if (comp.visible !== undefined && resolveBoolean(comp.visible, currentBinding, valueFunctions) === false)
|
|
35
|
+
return;
|
|
36
|
+
if (comp.component === "lp.aegis-block" || comp.component === "LPAegisBlock_Default") {
|
|
37
|
+
admitted.add(aegisInstanceKey(comp.id, renderPath));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const next = [...ancestors, id];
|
|
41
|
+
if (Array.isArray(comp.children)) {
|
|
42
|
+
const childIds = comp.children.filter((childId) => typeof childId === "string");
|
|
43
|
+
for (let index = 0; index < childIds.length && admitted.size < MAX_ANSWER_AEGIS_BLOCKS; index++) {
|
|
44
|
+
visit(childIds[index], next, currentBinding, `${renderPath}/${index}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
else if (isChildTemplate(comp.children)) {
|
|
48
|
+
const resolved = resolveValue(comp.children, currentBinding, valueFunctions);
|
|
49
|
+
const list = Array.isArray(resolved)
|
|
50
|
+
? resolved
|
|
51
|
+
: resolveRecordList({ path: comp.children.path }, currentBinding, valueFunctions);
|
|
52
|
+
const basePointer = readBindingPointer({ path: comp.children.path }, currentBinding);
|
|
53
|
+
for (let index = 0; index < list.length && admitted.size < MAX_ANSWER_AEGIS_BLOCKS; index++) {
|
|
54
|
+
const itemPointer = basePointer ? `${basePointer}/${index}` : null;
|
|
55
|
+
visit(comp.children.componentId, next, { ...currentBinding, itemPointer }, `${renderPath}/${index}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (typeof comp.child === "string") {
|
|
59
|
+
visit(comp.child, next, currentBinding, `${renderPath}/child`);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
visit(state.rootComponentId, [], binding, "root");
|
|
63
|
+
return admitted;
|
|
64
|
+
}
|
|
65
|
+
const noSubscription = () => () => { };
|
|
66
|
+
const noopInputChange = () => { };
|
|
67
|
+
// The same status region reports the pause and then, hidden, the discard, so the change is announced.
|
|
68
|
+
function StaleDraftStatus({ chinese, paused, onDiscard }) {
|
|
69
|
+
const discarded = chinese ? "已放弃你的修改。" : "Your changes were discarded.";
|
|
70
|
+
return (_jsxs("div", { className: paused ? "lp-draft-status" : undefined, children: [_jsx("p", { className: paused ? "lp-field-error" : "lp-visually-hidden", role: "status", children: !paused ? discarded : chinese
|
|
71
|
+
? "你的修改已保留。字段或选项暂时不可用,相关提交已暂停。请选择可用的选项或数值、清除非必填项的选择、放弃修改,或等待字段恢复。"
|
|
72
|
+
: "Your edits are kept. Related submissions are paused while fields or options are unavailable. Choose an available option or value, clear an optional selection, discard your changes, or wait for the field to return." }), paused ? _jsx("button", { type: "button", className: "lp-btn ghost", onClick: onDiscard, children: chinese ? "放弃我的修改" : "Discard my changes" }) : null] }));
|
|
73
|
+
}
|
|
74
|
+
const marked = (root, attribute, value) => [...root.querySelectorAll(`[${attribute}]`)].find(node => node.getAttribute(attribute) === value);
|
|
75
|
+
/**
|
|
76
|
+
* Where focus may go after a discard removes the button that had it, in order: each restored
|
|
77
|
+
* field that can take it, then the submit button of that field's form, which the discard
|
|
78
|
+
* released. Fields and forms are found by draft identity; a `fieldId` is unique only within
|
|
79
|
+
* its form.
|
|
80
|
+
*/
|
|
81
|
+
function discardFocusCandidates(root, conflicts) {
|
|
82
|
+
return conflicts.flatMap(conflict => [
|
|
83
|
+
marked(root, "data-a2ui-field", conflict.key)?.querySelector(":is(input, select, textarea):not(:disabled)"),
|
|
84
|
+
marked(root, "data-a2ui-form", conflict.formKey)?.closest("form")?.querySelector('button[type="submit"]:not(:disabled)'),
|
|
85
|
+
]).filter((node) => node != null);
|
|
86
|
+
}
|
|
87
|
+
function SurfaceNotice({ title, detail }) {
|
|
88
|
+
return (_jsxs("section", { className: "a2ui-surface-notice", children: [_jsx("p", { className: "lp-kicker default", children: title }), _jsx("p", { className: "lp-body", children: detail })] }));
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The A2UI v1.0 surface renderer.
|
|
92
|
+
*
|
|
93
|
+
* Takes the folded state (not raw messages) so the caller owns the message
|
|
94
|
+
* history and partial updates re-render exactly the branch that changed.
|
|
95
|
+
* A `ref` receives an `A2uiSurfaceHandle` for moving the reader to a heading.
|
|
96
|
+
*/
|
|
97
|
+
export const A2uiSurface = forwardRef(function A2uiSurface({ state: givenState = null, stream, pack, stylePacks, mode, layout, frame, sectionDividers, itemDividers, actionHandler, onInputChange, valueFunctions, registry, renderAegisBlock, saveFile, images, imageLoader, renderMap, componentMetadata, className, }, ref) {
|
|
98
|
+
const readStream = () => stream?.getState() ?? null;
|
|
99
|
+
const streamed = useSyncExternalStore(stream?.subscribe ?? noSubscription, readStream, readStream);
|
|
100
|
+
const state = stream ? streamed : givenState;
|
|
101
|
+
const surfaceId = state?.surfaceId ?? null;
|
|
102
|
+
const requestHandler = useRef(actionHandler);
|
|
103
|
+
requestHandler.current = actionHandler;
|
|
104
|
+
const [, refreshActions] = useState(0);
|
|
105
|
+
// While a whole answer streams, each bundle replaces blocks in place: the same answer keeps
|
|
106
|
+
// its action session, so a link's pending or failed state survives the next replacement.
|
|
107
|
+
// Once the answer says it is done, a new bundle is a new revision as before.
|
|
108
|
+
const streamingRevision = useRef(null);
|
|
109
|
+
const actionRevision = useMemo(() => {
|
|
110
|
+
const previous = streamingRevision.current;
|
|
111
|
+
const revision = previous && previous.streaming && previous.surfaceId === surfaceId && state
|
|
112
|
+
? previous.revision
|
|
113
|
+
: actionRevisionOf(state);
|
|
114
|
+
streamingRevision.current = { surfaceId, revision, streaming: surfaceIsStreaming(state) };
|
|
115
|
+
return revision;
|
|
116
|
+
}, [state, surfaceId]);
|
|
117
|
+
const actionSession = useMemo(() => createActionSession(() => requestHandler.current, () => refreshActions(value => value + 1)), [actionRevision]);
|
|
118
|
+
useLayoutEffect(() => {
|
|
119
|
+
actionSession.activate();
|
|
120
|
+
return () => actionSession.dispose();
|
|
121
|
+
}, [actionSession]);
|
|
122
|
+
const anchorPrefix = surfaceAnchorPrefix(useId());
|
|
123
|
+
const rootRef = useRef(null);
|
|
124
|
+
useImperativeHandle(ref, () => ({
|
|
125
|
+
locateComponent: (componentId, options) => locateComponentIn(rootRef.current, anchorPrefix, componentId, options),
|
|
126
|
+
}), [anchorPrefix]);
|
|
127
|
+
const [inputDrafts, setInputDrafts] = useState({ surfaceId, values: {} });
|
|
128
|
+
const activeInputDrafts = inputDrafts.surfaceId === surfaceId ? inputDrafts.values : {};
|
|
129
|
+
const [localOverrides, setLocalOverrides] = useState({ surfaceId, values: {} });
|
|
130
|
+
const activeLocalOverrides = localOverrides.surfaceId === surfaceId ? localOverrides.values : {};
|
|
131
|
+
const reconciled = useMemo(() => reconcileInputDrafts(state, activeInputDrafts, valueFunctions), [activeInputDrafts, state, valueFunctions]);
|
|
132
|
+
// Drafts and overrides never overlap (each write clears the other, see localWrites.ts), so the
|
|
133
|
+
// order they are applied in does not decide what wins: the last write does.
|
|
134
|
+
const effectiveDataModel = useMemo(() => applyLocalOverrides(reconciled.dataModel, activeLocalOverrides), [reconciled.dataModel, activeLocalOverrides]);
|
|
135
|
+
const clearDraftsAt = useCallback((path) => {
|
|
136
|
+
setInputDrafts((current) => {
|
|
137
|
+
if (current.surfaceId !== surfaceId)
|
|
138
|
+
return current;
|
|
139
|
+
const values = draftsAfterLocalWrite(current.values, path);
|
|
140
|
+
return values === current.values ? current : { surfaceId, values };
|
|
141
|
+
});
|
|
142
|
+
}, [surfaceId]);
|
|
143
|
+
const handleLocalAction = useCallback((action) => {
|
|
144
|
+
if (surfaceIsStreaming(state))
|
|
145
|
+
return true;
|
|
146
|
+
if (action.name === "toggleLocalFlag") {
|
|
147
|
+
const path = typeof action.payload.path === "string" ? action.payload.path : null;
|
|
148
|
+
if (!path || !path.startsWith("/data/") || parsePointer(path) === null)
|
|
149
|
+
return true;
|
|
150
|
+
setLocalOverrides((current) => {
|
|
151
|
+
const values = current.surfaceId === surfaceId ? current.values : {};
|
|
152
|
+
const currentValue = Object.hasOwn(values, path)
|
|
153
|
+
? values[path]
|
|
154
|
+
: readPointer(reconciled.dataModel, path);
|
|
155
|
+
return { surfaceId, values: { ...values, [path]: !(currentValue === true) } };
|
|
156
|
+
});
|
|
157
|
+
clearDraftsAt(path);
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
160
|
+
if (action.name === "setValue") {
|
|
161
|
+
const path = typeof action.payload.path === "string" ? action.payload.path : null;
|
|
162
|
+
const value = action.payload.value;
|
|
163
|
+
const isScalar = value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
164
|
+
if (!path || !path.startsWith("/data/") || parsePointer(path) === null || !isScalar)
|
|
165
|
+
return true;
|
|
166
|
+
setLocalOverrides((current) => {
|
|
167
|
+
const values = current.surfaceId === surfaceId ? current.values : {};
|
|
168
|
+
return { surfaceId, values: { ...values, [path]: value } };
|
|
169
|
+
});
|
|
170
|
+
clearDraftsAt(path);
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
if (action.name === "copyText") {
|
|
174
|
+
const copy = typeof action.payload.text === "string" ? action.payload.text : null;
|
|
175
|
+
if (copy !== null && copy.length > 0) {
|
|
176
|
+
void globalThis.navigator?.clipboard?.writeText(copy).catch(() => { });
|
|
177
|
+
}
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
return false;
|
|
181
|
+
}, [clearDraftsAt, reconciled.dataModel, state, surfaceId]);
|
|
182
|
+
const binding = useMemo(() => {
|
|
183
|
+
const base = { dataModel: effectiveDataModel, itemPointer: null };
|
|
184
|
+
const errors = state ? calculationInputErrors(state, effectiveDataModel, reconciled.blockedInputPaths, valueFunctions) : new Map();
|
|
185
|
+
return { ...base, calculations: createCalculationSession((path, itemPointer) => {
|
|
186
|
+
const current = { ...base, itemPointer };
|
|
187
|
+
const absolute = readBindingPointer({ path }, current);
|
|
188
|
+
if (!absolute || (absolute !== "/data" && !absolute.startsWith("/data/")))
|
|
189
|
+
return { error: { kind: "calculation-error", code: "invalid_calculation" } };
|
|
190
|
+
const error = errors.get(absolute);
|
|
191
|
+
return error ? { error } : { value: resolvePointerIn(current, path) };
|
|
192
|
+
}) };
|
|
193
|
+
}, [state, effectiveDataModel, reconciled.blockedInputPaths, valueFunctions]);
|
|
194
|
+
const admittedAegisBlockIds = useMemo(() => collectAdmittedAegisBlockIds(state, binding, valueFunctions), [state, binding, valueFunctions]);
|
|
195
|
+
const [renderedCalculations, setRenderedCalculations] = useState({ surfaceId, snapshot: "[]" });
|
|
196
|
+
const calculationSnapshot = renderedCalculations.surfaceId === surfaceId ? renderedCalculations.snapshot : "[]";
|
|
197
|
+
// Compare *before* calling the setter. Doing the equality check inside the updater is not
|
|
198
|
+
// the same thing: React 18 keeps an equal updater queued and can replay it against an older
|
|
199
|
+
// base state, which then schedules another commit - the loop that made typing in a surface
|
|
200
|
+
// with calculations take the page down.
|
|
201
|
+
const publishedCalculation = useRef({ surfaceId, snapshot: "[]" });
|
|
202
|
+
publishedCalculation.current = renderedCalculations;
|
|
203
|
+
const publishCalculations = useCallback((snapshot) => {
|
|
204
|
+
const previous = publishedCalculation.current;
|
|
205
|
+
const next = calculationSnapshotFor(previous, surfaceId, snapshot);
|
|
206
|
+
if (next === previous)
|
|
207
|
+
return;
|
|
208
|
+
publishedCalculation.current = next;
|
|
209
|
+
setRenderedCalculations(next);
|
|
210
|
+
}, [surfaceId]);
|
|
211
|
+
// Read the committed view so orphan components, inactive tabs and repeated rows follow
|
|
212
|
+
// the same visibility and binding context as the content being announced.
|
|
213
|
+
const captureCalculations = useCallback(() => {
|
|
214
|
+
const root = rootRef.current;
|
|
215
|
+
if (!root) {
|
|
216
|
+
publishCalculations("[]");
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const values = [...root.querySelectorAll("[data-calculation-announcement]")]
|
|
220
|
+
.filter(element => !element.closest('[hidden], [inert], [aria-hidden="true"]')
|
|
221
|
+
&& element.getClientRects().length > 0 && getComputedStyle(element).visibility !== "hidden")
|
|
222
|
+
.map(element => [element.dataset.calculationIdentity, element.dataset.calculationAnnouncement, element.dataset.calculationFailure ?? null]);
|
|
223
|
+
publishCalculations(JSON.stringify(values));
|
|
224
|
+
}, [publishCalculations]);
|
|
225
|
+
// After every commit, so the announcement revision moves synchronously: a Host that
|
|
226
|
+
// pauses timers must still get the paused-editing behaviour the tests describe.
|
|
227
|
+
useLayoutEffect(() => { captureCalculations(); });
|
|
228
|
+
// Once per surface, for DOM changes React did not commit such as a `hidden` attribute
|
|
229
|
+
// the Host toggles. The callback already receives one batch per task.
|
|
230
|
+
useEffect(() => {
|
|
231
|
+
const root = rootRef.current;
|
|
232
|
+
if (!root)
|
|
233
|
+
return;
|
|
234
|
+
const observer = new MutationObserver(captureCalculations);
|
|
235
|
+
observer.observe(root, { subtree: true, childList: true, attributes: true });
|
|
236
|
+
return () => observer.disconnect();
|
|
237
|
+
}, [captureCalculations, surfaceId]);
|
|
238
|
+
const calculationErrors = [...new Set(JSON.parse(calculationSnapshot)
|
|
239
|
+
.map(([, , error]) => error).filter((error) => Boolean(error)))];
|
|
240
|
+
const calculationRevision = useMemo(() => ({ surfaceId, snapshot: calculationSnapshot }), [surfaceId, calculationSnapshot]);
|
|
241
|
+
const announcedCalculations = useRef(null);
|
|
242
|
+
const [calculationAnnouncement, setCalculationAnnouncement] = useState({ revision: calculationRevision, text: "" });
|
|
243
|
+
useEffect(() => {
|
|
244
|
+
const values = new Map(JSON.parse(calculationRevision.snapshot));
|
|
245
|
+
const previous = announcedCalculations.current;
|
|
246
|
+
if (!previous || previous.surfaceId !== calculationRevision.surfaceId) {
|
|
247
|
+
announcedCalculations.current = { surfaceId: calculationRevision.surfaceId, values };
|
|
248
|
+
setCalculationAnnouncement({ revision: calculationRevision, text: "" });
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
// The first committed view is the baseline, not an unsolicited announcement.
|
|
252
|
+
if (previous.values.size === 0) {
|
|
253
|
+
announcedCalculations.current = { surfaceId: calculationRevision.surfaceId, values };
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const changed = [...values].filter(([id, value]) => previous.values.get(id) !== value).map(([, value]) => value);
|
|
257
|
+
if (changed.length === 0) {
|
|
258
|
+
announcedCalculations.current = { surfaceId: calculationRevision.surfaceId, values };
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const timer = setTimeout(() => {
|
|
262
|
+
announcedCalculations.current = { surfaceId: calculationRevision.surfaceId, values };
|
|
263
|
+
setCalculationAnnouncement({ revision: calculationRevision, text: [...new Set(changed)].join(". ") });
|
|
264
|
+
}, 400);
|
|
265
|
+
return () => clearTimeout(timer);
|
|
266
|
+
}, [calculationRevision]);
|
|
267
|
+
const notifiedConflicts = useRef(new Set());
|
|
268
|
+
useEffect(() => {
|
|
269
|
+
const active = new Set(reconciled.conflicts.map(conflict => conflict.key));
|
|
270
|
+
for (const conflict of reconciled.conflicts) {
|
|
271
|
+
const notification = JSON.stringify([surfaceId, conflict.key]);
|
|
272
|
+
if (notifiedConflicts.current.has(notification))
|
|
273
|
+
continue;
|
|
274
|
+
notifiedConflicts.current.add(notification);
|
|
275
|
+
(onInputChange ?? noopInputChange)({ ...conflict.change, valid: false, errorCode: "draft_unavailable" });
|
|
276
|
+
}
|
|
277
|
+
for (const notification of notifiedConflicts.current) {
|
|
278
|
+
const [previousSurface, key] = JSON.parse(notification);
|
|
279
|
+
if (previousSurface !== surfaceId || !active.has(key))
|
|
280
|
+
notifiedConflicts.current.delete(notification);
|
|
281
|
+
}
|
|
282
|
+
}, [reconciled.conflicts, onInputChange, surfaceId]);
|
|
283
|
+
// The surface whose stale edits the user discarded, until their next edit.
|
|
284
|
+
const [discardedSurface, setDiscardedSurface] = useState(undefined);
|
|
285
|
+
const handleInputChange = useCallback((change) => {
|
|
286
|
+
const draft = state ? createInputDraft(state, change, valueFunctions) : null;
|
|
287
|
+
if (!draft)
|
|
288
|
+
return;
|
|
289
|
+
setDiscardedSurface(undefined);
|
|
290
|
+
// The user's edit replaces whatever a local action wrote at this field's path.
|
|
291
|
+
setLocalOverrides((current) => {
|
|
292
|
+
if (current.surfaceId !== change.surfaceId)
|
|
293
|
+
return current;
|
|
294
|
+
const values = overridesAfterEdit(current.values, draft.change.path);
|
|
295
|
+
return values === current.values ? current : { surfaceId: current.surfaceId, values };
|
|
296
|
+
});
|
|
297
|
+
const key = draft.key;
|
|
298
|
+
setInputDrafts((current) => {
|
|
299
|
+
const values = current.surfaceId === change.surfaceId ? current.values : {};
|
|
300
|
+
const currentValue = values[key]?.change.value;
|
|
301
|
+
const nextValue = change.value;
|
|
302
|
+
const unchanged = Array.isArray(currentValue) && Array.isArray(nextValue)
|
|
303
|
+
? currentValue.length === nextValue.length && currentValue.every((entry, index) => entry === nextValue[index])
|
|
304
|
+
: currentValue === nextValue;
|
|
305
|
+
return unchanged ? current : { surfaceId: change.surfaceId, values: { ...values, [key]: draft } };
|
|
306
|
+
});
|
|
307
|
+
(onInputChange ?? noopInputChange)(change);
|
|
308
|
+
}, [onInputChange, state, valueFunctions]);
|
|
309
|
+
const submissionBlocked = reconciled.conflicts.length > 0;
|
|
310
|
+
const discarded = !submissionBlocked && discardedSurface === surfaceId;
|
|
311
|
+
const discardStale = useCallback(() => {
|
|
312
|
+
const conflicts = reconciled.conflicts;
|
|
313
|
+
setInputDrafts((current) => ({ surfaceId: current.surfaceId, values: discardStaleDrafts(current.values, conflicts) }));
|
|
314
|
+
setDiscardedSurface(surfaceId);
|
|
315
|
+
const root = rootRef.current;
|
|
316
|
+
requestAnimationFrame(() => {
|
|
317
|
+
if (!root)
|
|
318
|
+
return;
|
|
319
|
+
// focus() silently does nothing on an element that is hidden or inert, so check it took.
|
|
320
|
+
const focused = () => root.getRootNode().activeElement;
|
|
321
|
+
for (const candidate of discardFocusCandidates(root, conflicts)) {
|
|
322
|
+
candidate.focus();
|
|
323
|
+
if (focused() === candidate)
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
// Nothing restored can take focus: keep it in the surface rather than on the page body.
|
|
327
|
+
root.tabIndex = -1;
|
|
328
|
+
root.addEventListener("blur", () => root.removeAttribute("tabindex"), { once: true });
|
|
329
|
+
root.focus();
|
|
330
|
+
});
|
|
331
|
+
}, [reconciled.conflicts, surfaceId]);
|
|
332
|
+
// Appearance comes from the Host (LittlePressAppearance and these props), never from the message.
|
|
333
|
+
const activeStylePacks = stylePacks ?? rendererStylePacks;
|
|
334
|
+
const presetTheme = pack !== undefined && activeStylePacks.includes(pack) && Object.hasOwn(themePresets, pack)
|
|
335
|
+
? themePresets[pack]
|
|
336
|
+
: undefined;
|
|
337
|
+
const { resolved: appearance } = useAppearanceResult({ theme: presetTheme, colorMode: mode });
|
|
338
|
+
const appearanceStyle = useMemo(() => appearanceCssVariables(appearance), [appearance]);
|
|
339
|
+
const shellAppearance = { ...appearanceDataAttributes(appearance), "data-pack": appearance.themeId, style: appearanceStyle };
|
|
340
|
+
const hintedFrame = state?.rendererHints.frame;
|
|
341
|
+
const hintedSectionDividers = state?.rendererHints.sectionDividers;
|
|
342
|
+
const hintedItemDividers = state?.rendererHints.itemDividers;
|
|
343
|
+
const resolvedFrame = frame ?? (hintedFrame === "card" || hintedFrame === "none" ? hintedFrame : "none");
|
|
344
|
+
const resolvedSectionDividers = sectionDividers ?? (hintedSectionDividers === "none" || hintedSectionDividers === "strong" ? hintedSectionDividers : "subtle");
|
|
345
|
+
const resolvedItemDividers = itemDividers ?? (hintedItemDividers === "none" || hintedItemDividers === "full" ? hintedItemDividers : "inset");
|
|
346
|
+
// Print rendering only engages when the surface actually IS a compiled page.
|
|
347
|
+
const rootComponent = state?.rootComponentId ? state.components[state.rootComponentId] : undefined;
|
|
348
|
+
const isLayoutPageRoot = rootComponent?.component === "LayoutPage_Default";
|
|
349
|
+
const resolvedLayout = layout ?? (isLayoutPageRoot && rootComponent?.pageScrollable === false ? "print" : "flow");
|
|
350
|
+
const printActive = resolvedLayout === "print" && isLayoutPageRoot;
|
|
351
|
+
const motion = useRef(null);
|
|
352
|
+
useLayoutEffect(() => {
|
|
353
|
+
const root = rootRef.current;
|
|
354
|
+
if (!root)
|
|
355
|
+
return;
|
|
356
|
+
const controller = createSurfaceMotion(root);
|
|
357
|
+
motion.current = controller;
|
|
358
|
+
return () => { controller.dispose(); motion.current = null; };
|
|
359
|
+
}, [surfaceId, Boolean(state?.rootComponentId), state?.deleted]);
|
|
360
|
+
useLayoutEffect(() => {
|
|
361
|
+
motion.current?.update(!printActive);
|
|
362
|
+
}, [state, surfaceId, printActive]);
|
|
363
|
+
const shellClassName = `a2ui-surface pv ${printActive ? "a2ui-surface-print " : ""}${className ?? ""}`.trim();
|
|
364
|
+
if (!state || !state.surfaceId) {
|
|
365
|
+
if (stream)
|
|
366
|
+
return null;
|
|
367
|
+
return (_jsx("div", { className: shellClassName, ...shellAppearance, children: _jsx(SurfaceNotice, { title: "No surface", detail: "This bundle carries no A2UI createSurface message. Generate once to render a surface." }) }));
|
|
368
|
+
}
|
|
369
|
+
if (state.deleted) {
|
|
370
|
+
return (_jsx("div", { className: shellClassName, ...shellAppearance, "data-surface-id": state.surfaceId, children: _jsx(SurfaceNotice, { title: "Surface deleted", detail: `deleteSurface removed "${state.surfaceId}" from the runtime.` }) }));
|
|
371
|
+
}
|
|
372
|
+
if (!state.rootComponentId) {
|
|
373
|
+
return (_jsx("div", { className: shellClassName, ...shellAppearance, "data-surface-id": state.surfaceId, children: _jsx(SurfaceNotice, { title: "Empty surface", detail: "createSurface arrived without any components." }) }));
|
|
374
|
+
}
|
|
375
|
+
const requiredCapabilities = state.rendererHints.requiredCapabilities;
|
|
376
|
+
if (requiredCapabilities !== undefined && (!Array.isArray(requiredCapabilities)
|
|
377
|
+
|| requiredCapabilities.some(capability => !rendererCapabilities.includes(capability)))) {
|
|
378
|
+
return _jsx("div", { className: shellClassName, ...shellAppearance, children: _jsx(SurfaceNotice, { title: "Client update required", detail: "This content requires an interaction capability that this renderer does not support. Open it in an updated client." }) });
|
|
379
|
+
}
|
|
380
|
+
const context = {
|
|
381
|
+
state,
|
|
382
|
+
registry: registry ?? foundationRendererRegistry,
|
|
383
|
+
componentMetadata,
|
|
384
|
+
binding,
|
|
385
|
+
valueFunctions,
|
|
386
|
+
onAction: noopAction,
|
|
387
|
+
onLocalAction: handleLocalAction,
|
|
388
|
+
renderAegisBlock,
|
|
389
|
+
saveFile,
|
|
390
|
+
images,
|
|
391
|
+
imageLoader,
|
|
392
|
+
renderMap,
|
|
393
|
+
admittedAegisBlockIds,
|
|
394
|
+
actionSession,
|
|
395
|
+
blockedInputPaths: reconciled.blockedInputPaths,
|
|
396
|
+
blockedFormKeys: reconciled.blockedFormKeys,
|
|
397
|
+
onInputChange: handleInputChange,
|
|
398
|
+
layout: printActive ? "print" : "flow",
|
|
399
|
+
depth: 0,
|
|
400
|
+
ancestors: [],
|
|
401
|
+
renderPath: "root",
|
|
402
|
+
anchorPrefix,
|
|
403
|
+
};
|
|
404
|
+
return (_jsxs("div", { ref: rootRef, className: shellClassName, ...shellAppearance, "data-surface-id": state.surfaceId, "data-surface-type": typeof state.rendererHints.surfaceType === "string" ? state.rendererHints.surfaceType : undefined, "data-footprint": typeof state.rendererHints.footprint === "string" ? state.rendererHints.footprint : undefined, "data-widget-state": typeof state.rendererHints.widgetState === "string" ? state.rendererHints.widgetState : undefined, "data-recipe": typeof state.rendererHints.recipe === "string" ? state.rendererHints.recipe : undefined, "data-frame": resolvedFrame, "data-section-dividers": resolvedSectionDividers, "data-item-dividers": resolvedItemDividers, children: [submissionBlocked || discarded ? _jsx(StaleDraftStatus, { chinese: isChineseLanguage(surfaceLanguage(state.rendererHints)), paused: submissionBlocked, onDiscard: discardStale }) : null, calculationSnapshot !== "[]" ? _jsx("p", { className: "lp-visually-hidden", role: "status", "aria-atomic": "true", children: calculationAnnouncement.revision === calculationRevision ? calculationAnnouncement.text : "" }) : null, _jsx(RenderComponent, { componentId: state.rootComponentId, context: context }, state.surfaceId), _jsx(ActionFeedback, { context: context, scope: "surface" }), calculationErrors.map(error => _jsx("p", { className: "lp-field-error", "data-calculation-summary": "true", children: error }, error))] }));
|
|
405
|
+
});
|
|
406
|
+
/**
|
|
407
|
+
* Fixed-ratio page frame. A scrollable format keeps one scrolling surface at
|
|
408
|
+
* the trim aspect ratio; a non-scrollable format (every print trim) clips at
|
|
409
|
+
* the page edge and shows an overflow badge instead — a fixed page that
|
|
410
|
+
* pretends to scroll is lying about what fits.
|
|
411
|
+
*/
|
|
412
|
+
export function A2uiPageFrame({ pageFormat, children, isUncompiledTrim = false }) {
|
|
413
|
+
const contentRef = useRef(null);
|
|
414
|
+
const [overflows, setOverflows] = useState(false);
|
|
415
|
+
const clips = pageFormat ? !pageFormat.pageScrollable : false;
|
|
416
|
+
useEffect(() => {
|
|
417
|
+
const node = contentRef.current;
|
|
418
|
+
if (!node || !clips) {
|
|
419
|
+
setOverflows(false);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
const measure = () => {
|
|
423
|
+
// A print-true page manages its own fit: slots clip and report overset
|
|
424
|
+
// individually, and the zoomed page always matches the frame height bar
|
|
425
|
+
// sub-pixel rounding — a page-level badge here would only ever be noise.
|
|
426
|
+
if (node.querySelector(".a2ui-print-page")) {
|
|
427
|
+
setOverflows(false);
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
setOverflows(node.scrollHeight > node.clientHeight + 1);
|
|
431
|
+
};
|
|
432
|
+
measure();
|
|
433
|
+
const observer = new ResizeObserver(measure);
|
|
434
|
+
observer.observe(node);
|
|
435
|
+
return () => observer.disconnect();
|
|
436
|
+
}, [clips, children]);
|
|
437
|
+
if (!pageFormat)
|
|
438
|
+
return _jsx(_Fragment, { children: children });
|
|
439
|
+
return (_jsxs("div", { className: "a2ui-page-frame", children: [_jsxs("div", { className: `a2ui-page a2ui-page-${pageFormat.orientation}`, style: { aspectRatio: `${pageFormat.aspectWidth} / ${pageFormat.aspectHeight}` }, "data-page-scrollable": pageFormat.pageScrollable ? "true" : "false", children: [_jsx("div", { ref: contentRef, className: clips ? "a2ui-page-clip" : "a2ui-page-scroll", children: children }), clips && overflows ? (_jsx("p", { className: "a2ui-page-overflow-badge", role: "status", children: "Overflows the fixed page \u2014 content below the trim edge is cut" })) : null] }), _jsxs("p", { className: "a2ui-page-caption", children: [pageFormat.preset, " \u00B7 ", pageFormat.orientation, " \u00B7 ", formatAspectRatio(pageFormat), " \u00B7 ", pageFormat.spreadPolicy, clips ? " · fixed page" : "", isUncompiledTrim ? " · trim preview, not compiled yet" : ""] })] }));
|
|
440
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tappable `lp.image`: with `preview` it opens the renderer's own viewer, with `tapAction` it
|
|
3
|
+
* runs that action (a Host event from an answer). The viewer is a native modal `<dialog>`: the
|
|
4
|
+
* page behind it is inert, Tab stays inside, Esc closes it, and focus returns to the image.
|
|
5
|
+
* Compose and SwiftUI draw the same viewer (`ui-foundation/surface/contracts/fixtures/renderer/carousel.json`).
|
|
6
|
+
*/
|
|
7
|
+
import { type ReactNode } from "react";
|
|
8
|
+
import type { ActionClickHandler, RenderContext } from "./context.ts";
|
|
9
|
+
import { type CoreMediaProps, type CoreMediaValue } from "./CoreMedia.tsx";
|
|
10
|
+
export declare const imagePreviewCopy: {
|
|
11
|
+
readonly open: "Open preview";
|
|
12
|
+
readonly close: "Close preview";
|
|
13
|
+
/** The name of a tappable image with neither alt text nor a caption. */
|
|
14
|
+
readonly action: "Open image";
|
|
15
|
+
};
|
|
16
|
+
/** What a tappable image is called: its alt text, else its caption, else `imagePreviewCopy.action`. */
|
|
17
|
+
export declare function tappableImageName(alt: string, caption?: string | null): string;
|
|
18
|
+
export type ImagePreviewProps = {
|
|
19
|
+
/** The image as drawn in the answer. */
|
|
20
|
+
children: ReactNode;
|
|
21
|
+
url?: string;
|
|
22
|
+
alt: string;
|
|
23
|
+
caption?: string | null;
|
|
24
|
+
/** While the answer streams, the image cannot be tapped. */
|
|
25
|
+
locked: boolean;
|
|
26
|
+
/** Render context so preview and thumbnail share the same Host `images` / `imageLoader` decision. */
|
|
27
|
+
context?: RenderContext;
|
|
28
|
+
/** Optional media descriptor rendered with the same resolved `src` as the preview dialog. */
|
|
29
|
+
media?: CoreMediaValue;
|
|
30
|
+
ratio?: CoreMediaProps["ratio"];
|
|
31
|
+
};
|
|
32
|
+
/** The words under the image in the viewer: its caption, or else its alt text. */
|
|
33
|
+
export declare function imagePreviewText(alt: string, caption?: string | null): string;
|
|
34
|
+
export declare function ImagePreview({ children, url, alt, caption, locked, context, media, ratio }: ImagePreviewProps): import("react/jsx-runtime").JSX.Element;
|
|
35
|
+
/** An image whose tap runs its `tapAction`, such as a Host event, as a button would. */
|
|
36
|
+
export declare function ImageAction({ children, alt, caption, activate, locked }: {
|
|
37
|
+
children: ReactNode;
|
|
38
|
+
alt: string;
|
|
39
|
+
caption?: string | null;
|
|
40
|
+
activate: ActionClickHandler | undefined;
|
|
41
|
+
locked: boolean;
|
|
42
|
+
}): import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* A tappable `lp.image`: with `preview` it opens the renderer's own viewer, with `tapAction` it
|
|
4
|
+
* runs that action (a Host event from an answer). The viewer is a native modal `<dialog>`: the
|
|
5
|
+
* page behind it is inert, Tab stays inside, Esc closes it, and focus returns to the image.
|
|
6
|
+
* Compose and SwiftUI draw the same viewer (`ui-foundation/surface/contracts/fixtures/renderer/carousel.json`).
|
|
7
|
+
*/
|
|
8
|
+
import { useEffect, useRef, useState } from "react";
|
|
9
|
+
import { LucideIcon } from "./LucideIcon.js";
|
|
10
|
+
import { CoreMedia } from "./CoreMedia.js";
|
|
11
|
+
import { useSurfaceImage } from "./useSurfaceImage.js";
|
|
12
|
+
export const imagePreviewCopy = {
|
|
13
|
+
open: "Open preview",
|
|
14
|
+
close: "Close preview",
|
|
15
|
+
/** The name of a tappable image with neither alt text nor a caption. */
|
|
16
|
+
action: "Open image",
|
|
17
|
+
};
|
|
18
|
+
/** What a tappable image is called: its alt text, else its caption, else `imagePreviewCopy.action`. */
|
|
19
|
+
export function tappableImageName(alt, caption) {
|
|
20
|
+
return alt.trim() || caption?.trim() || imagePreviewCopy.action;
|
|
21
|
+
}
|
|
22
|
+
/** The words under the image in the viewer: its caption, or else its alt text. */
|
|
23
|
+
export function imagePreviewText(alt, caption) {
|
|
24
|
+
return caption?.trim() || alt.trim();
|
|
25
|
+
}
|
|
26
|
+
export function ImagePreview({ children, url, alt, caption, locked, context, media, ratio }) {
|
|
27
|
+
const [open, setOpen] = useState(false);
|
|
28
|
+
const trigger = useRef(null);
|
|
29
|
+
const dialog = useRef(null);
|
|
30
|
+
const text = imagePreviewText(alt, caption);
|
|
31
|
+
const { src: resolvedUrl, onError } = useSurfaceImage(url, context, { streaming: locked });
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
if (!resolvedUrl && open)
|
|
34
|
+
setOpen(false);
|
|
35
|
+
}, [resolvedUrl, open]);
|
|
36
|
+
useEffect(() => {
|
|
37
|
+
const element = dialog.current;
|
|
38
|
+
if (!open || !element)
|
|
39
|
+
return;
|
|
40
|
+
if (typeof element.showModal === "function" && !element.open)
|
|
41
|
+
element.showModal();
|
|
42
|
+
return () => {
|
|
43
|
+
if (element.open)
|
|
44
|
+
element.close();
|
|
45
|
+
};
|
|
46
|
+
}, [open]);
|
|
47
|
+
const close = () => {
|
|
48
|
+
setOpen(false);
|
|
49
|
+
// The dialog unmounts; the reader goes back to the image they opened.
|
|
50
|
+
queueMicrotask(() => trigger.current?.focus());
|
|
51
|
+
};
|
|
52
|
+
const renderedThumbnail = media
|
|
53
|
+
? _jsx(CoreMedia, { media: media, ratio: ratio, context: context, streaming: locked, resolvedSrc: resolvedUrl, onImageError: onError })
|
|
54
|
+
: children;
|
|
55
|
+
return (_jsxs(_Fragment, { children: [_jsx("button", { ref: trigger, type: "button", className: "lp-image-button", "data-preview": "true", "aria-haspopup": "dialog", "aria-label": alt.trim() || caption?.trim()
|
|
56
|
+
? `${tappableImageName(alt, caption)}, ${imagePreviewCopy.open.toLowerCase()}`
|
|
57
|
+
: imagePreviewCopy.open, disabled: locked || !resolvedUrl, onClick: () => { if (!locked && resolvedUrl)
|
|
58
|
+
setOpen(true); }, children: renderedThumbnail }), open && resolvedUrl ? (_jsxs("dialog", { ref: dialog, className: "lp-image-preview", "aria-label": text || imagePreviewCopy.open,
|
|
59
|
+
// Esc fires `cancel`; the dialog then closes, and so does this state.
|
|
60
|
+
onClose: close, onCancel: (event) => {
|
|
61
|
+
event.preventDefault();
|
|
62
|
+
close();
|
|
63
|
+
}, onClick: (event) => {
|
|
64
|
+
// A click on the backdrop lands on the dialog itself, outside its content.
|
|
65
|
+
if (event.target === event.currentTarget)
|
|
66
|
+
close();
|
|
67
|
+
}, children: [_jsxs("figure", { className: "lp-image-preview-body", children: [_jsx("img", { src: resolvedUrl, alt: alt, referrerPolicy: "no-referrer", onError: onError }), text ? _jsx("figcaption", { className: "lp-image-preview-caption", children: text }) : null] }), _jsx("button", { type: "button", className: "lp-image-preview-close", "aria-label": imagePreviewCopy.close, onClick: close, autoFocus: true, children: _jsx(LucideIcon, { name: "x", size: "md" }) })] })) : null] }));
|
|
68
|
+
}
|
|
69
|
+
/** An image whose tap runs its `tapAction`, such as a Host event, as a button would. */
|
|
70
|
+
export function ImageAction({ children, alt, caption, activate, locked }) {
|
|
71
|
+
const disabled = !activate || activate.disabled === true || locked;
|
|
72
|
+
return (_jsx("button", { type: "button", className: "lp-image-button", "data-action": "true", "aria-label": tappableImageName(alt, caption), "aria-disabled": disabled || undefined, "aria-busy": activate?.pending || undefined, disabled: disabled, onClick: disabled ? undefined : activate, children: children }));
|
|
73
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { lucideIconNames, isLucideIconName, type LucideIconName } from "./lucideIcons.ts";
|
|
2
|
+
export type LucideIconSize = "sm" | "md" | "lg";
|
|
3
|
+
export type LucideIconTone = "default" | "muted" | "accent" | "info" | "positive" | "warning" | "danger";
|
|
4
|
+
export type LucideIconProps = {
|
|
5
|
+
name: unknown;
|
|
6
|
+
size?: LucideIconSize;
|
|
7
|
+
tone?: LucideIconTone;
|
|
8
|
+
label?: string;
|
|
9
|
+
decorative?: boolean;
|
|
10
|
+
className?: string;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Geometry comes from the pinned Lucide package at build time and is drawn with
|
|
14
|
+
* `createElement`, never `dangerouslySetInnerHTML`: remote content supplies an
|
|
15
|
+
* icon *name*, never markup. The bundled set is the whole pinned catalog, so a
|
|
16
|
+
* renderer never silently drops an icon the compiler accepted.
|
|
17
|
+
*/
|
|
18
|
+
export declare function LucideIcon({ name, size, tone, label, decorative, className, }: LucideIconProps): import("react/jsx-runtime").JSX.Element | null;
|
|
19
|
+
export { lucideIconNames, isLucideIconName, type LucideIconName };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createElement } from "react";
|
|
3
|
+
import { lucideIconAliases, lucideIconNodes } from "./iconNodes.generated.js";
|
|
4
|
+
import { lucideIconNames, isLucideIconName } from "./lucideIcons.js";
|
|
5
|
+
/**
|
|
6
|
+
* Root attributes, matching the pinned lucide-react `defaultAttributes`, so the
|
|
7
|
+
* data-driven path renders exactly what the upstream component rendered.
|
|
8
|
+
*/
|
|
9
|
+
const SVG_ROOT = {
|
|
10
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
11
|
+
width: 24,
|
|
12
|
+
height: 24,
|
|
13
|
+
viewBox: "0 0 24 24",
|
|
14
|
+
fill: "none",
|
|
15
|
+
stroke: "currentColor",
|
|
16
|
+
strokeWidth: 2,
|
|
17
|
+
strokeLinecap: "round",
|
|
18
|
+
strokeLinejoin: "round",
|
|
19
|
+
};
|
|
20
|
+
/** Resolve a published name, following upstream's re-export aliases. */
|
|
21
|
+
function iconGeometry(name) {
|
|
22
|
+
if (typeof name !== "string")
|
|
23
|
+
return null;
|
|
24
|
+
const canonical = lucideIconAliases[name] ?? name;
|
|
25
|
+
return lucideIconNodes[canonical] ?? null;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Geometry comes from the pinned Lucide package at build time and is drawn with
|
|
29
|
+
* `createElement`, never `dangerouslySetInnerHTML`: remote content supplies an
|
|
30
|
+
* icon *name*, never markup. The bundled set is the whole pinned catalog, so a
|
|
31
|
+
* renderer never silently drops an icon the compiler accepted.
|
|
32
|
+
*/
|
|
33
|
+
export function LucideIcon({ name, size = "md", tone = "default", label, decorative = !label, className, }) {
|
|
34
|
+
const geometry = iconGeometry(name);
|
|
35
|
+
if (!geometry) {
|
|
36
|
+
if (decorative)
|
|
37
|
+
return null;
|
|
38
|
+
return (_jsx("span", { className: `lp-icon-slot lp-icon-fallback ${className ?? ""}`.trim(), role: "img", "aria-label": label ?? "Icon unavailable", "data-icon-fallback": "true", children: label ?? "Icon unavailable" }));
|
|
39
|
+
}
|
|
40
|
+
return (_jsx("span", { className: `lp-icon-slot ${className ?? ""}`.trim(), "data-icon": name, "data-size": size, "data-tone": tone, role: decorative ? undefined : "img", "aria-label": decorative ? undefined : (label ?? name), "aria-hidden": decorative ? true : undefined, children: createElement("svg", { ...SVG_ROOT, "aria-hidden": "true", focusable: "false" }, geometry.map(([tag, attributes], index) => createElement(tag, { ...attributes, key: index }))) }));
|
|
41
|
+
}
|
|
42
|
+
export { lucideIconNames, isLucideIconName };
|