@azx-pbc/axiom-native 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +95 -2
  3. package/dist/configurator.d.ts +39 -0
  4. package/dist/configurator.d.ts.map +1 -0
  5. package/dist/configurator.js +420 -0
  6. package/dist/configurator.js.map +1 -0
  7. package/dist/controls.d.ts +64 -0
  8. package/dist/controls.d.ts.map +1 -0
  9. package/dist/controls.js +8 -0
  10. package/dist/controls.js.map +1 -0
  11. package/dist/copy.d.ts +216 -0
  12. package/dist/copy.d.ts.map +1 -0
  13. package/dist/copy.js +2574 -0
  14. package/dist/copy.js.map +1 -0
  15. package/dist/fields.d.ts +9 -0
  16. package/dist/fields.d.ts.map +1 -0
  17. package/dist/fields.js +1365 -0
  18. package/dist/fields.js.map +1 -0
  19. package/dist/host.d.ts +90 -0
  20. package/dist/host.d.ts.map +1 -0
  21. package/dist/host.js +8 -0
  22. package/dist/host.js.map +1 -0
  23. package/dist/index.d.ts +18 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +10 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/input-chain.d.ts +28 -0
  28. package/dist/input-chain.d.ts.map +1 -0
  29. package/dist/input-chain.js +64 -0
  30. package/dist/input-chain.js.map +1 -0
  31. package/dist/render/layout.d.ts +47 -0
  32. package/dist/render/layout.d.ts.map +1 -0
  33. package/dist/render/layout.js +8 -0
  34. package/dist/render/layout.js.map +1 -0
  35. package/dist/render/native.d.ts +85 -0
  36. package/dist/render/native.d.ts.map +1 -0
  37. package/dist/render/native.js +124 -0
  38. package/dist/render/native.js.map +1 -0
  39. package/dist/render/tree.d.ts +50 -0
  40. package/dist/render/tree.d.ts.map +1 -0
  41. package/dist/render/tree.js +636 -0
  42. package/dist/render/tree.js.map +1 -0
  43. package/dist/theme.d.ts +113 -0
  44. package/dist/theme.d.ts.map +1 -0
  45. package/dist/theme.js +211 -0
  46. package/dist/theme.js.map +1 -0
  47. package/package.json +78 -3
package/dist/fields.js ADDED
@@ -0,0 +1,1365 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { renderDisplayText, renderValueText, useAsyncOptions, useBufferedInput, useField, useFields, useForm, } from '@azx-pbc/axiom-react';
3
+ import { AxiomDecimal, AxiomError, COUNTRY_CODE_PATTERN, WriteRefusedError, assertNever, canonicalDecimal, canonicalizeRestricted, isRecord, mediaAcceptMatches, optionCodeValue, sameWireValue, } from '@azx-pbc/axiom-runtime';
4
+ import { useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react';
5
+ import { Pressable, StyleSheet, Switch, Text, TextInput, View } from 'react-native';
6
+ import { useControlComponents } from './controls.js';
7
+ import { InputChainContext, InputOrderContext } from './input-chain.js';
8
+ import { controlA11yProps, toNativeProps } from './render/native.js';
9
+ import { useNativeTheme } from './theme.js';
10
+ import { useHostCopy } from './copy.js';
11
+ import { useHostActions } from './host.js';
12
+ /**
13
+ * The control-to-affordance table, keyed by the hint and the primitive together.
14
+ *
15
+ * The hint alone is not enough: the wire refuses a value of another shape, and the harness has
16
+ * no way to turn that refusal into a stored value. A hint the compiler admits on a primitive it
17
+ * cannot write — a `checkbox` on a string, a `select` on a boolean — therefore falls back to the
18
+ * primitive's own entry, exactly as the Web adapter does.
19
+ */
20
+ function planOf(node) {
21
+ const { primitive } = node.declaration;
22
+ switch (node.control) {
23
+ case 'percentage':
24
+ return primitive === 'integer'
25
+ ? { family: 'buffered', format: { kind: 'integer' } }
26
+ : { family: 'buffered', format: { kind: 'decimal' } };
27
+ case 'checkbox':
28
+ case 'switch':
29
+ // A checkbox writes a JSON boolean. A string field carrying the hint keeps a text entry.
30
+ return primitive === 'boolean' ? { family: 'boolean' } : { family: 'text' };
31
+ case 'select':
32
+ case 'radio':
33
+ case 'combobox':
34
+ // The compiler states a boolean's two codes as `"true"` and `"false"`; the entry converts
35
+ // the chosen code back to the JSON boolean the wire holds.
36
+ return primitive === 'boolean' ? { family: 'boolean-choice' } : { family: 'choice' };
37
+ case 'rating':
38
+ case 'likert':
39
+ case 'timeslot':
40
+ return { family: 'choice' };
41
+ case 'text':
42
+ case 'textarea':
43
+ case 'email':
44
+ case 'url':
45
+ case 'datetime':
46
+ return { family: 'text' };
47
+ case 'password':
48
+ return { family: 'secure' };
49
+ case 'phone':
50
+ // A control hint implies no validation (`MODEL-3.1.3`). A national spelling such as
51
+ // `(415) 555-0123` writes the raw string; `is_phone` is the optional canonical check.
52
+ return { family: 'text' };
53
+ case 'integer':
54
+ return { family: 'buffered', format: { kind: 'integer' } };
55
+ case 'decimal':
56
+ return { family: 'buffered', format: { kind: 'decimal' } };
57
+ case 'money':
58
+ return { family: 'buffered', format: { kind: 'money' } };
59
+ case 'quantity':
60
+ return { family: 'quantity' };
61
+ case 'slider':
62
+ return { family: 'buffered', format: { kind: 'integer' } };
63
+ case 'date':
64
+ return { family: 'buffered', format: { kind: 'date' } };
65
+ case 'time':
66
+ return { family: 'text' };
67
+ case 'duration':
68
+ return { family: 'duration' };
69
+ case 'address':
70
+ return { family: 'address' };
71
+ case 'media_capture':
72
+ return { family: 'media' };
73
+ case 'map':
74
+ return { family: 'position' };
75
+ case 'signature_capture':
76
+ return { family: 'signature' };
77
+ case 'multiselect':
78
+ case 'tags':
79
+ return primitive === 'array' && node.declaration.items?.primitive === 'media_ref'
80
+ ? { family: 'media' }
81
+ : { family: 'list' };
82
+ case 'rank':
83
+ return { family: 'rank' };
84
+ default:
85
+ return assertNeverControl(node.control);
86
+ }
87
+ }
88
+ /** A union arm the compiler proves unreachable. */
89
+ function assertNeverControl(value) {
90
+ throw new Error(`unreachable control: ${JSON.stringify(value)}`);
91
+ }
92
+ function inputKeyOf(fieldId, rowKey) {
93
+ return `${fieldId}\u0000${String(rowKey ?? '')}`;
94
+ }
95
+ /** One control's link in its enclosing form's return-key chain. */
96
+ function useInputChain(fieldId, rowKey, subOrder) {
97
+ const chain = useContext(InputChainContext);
98
+ const baseOrder = useContext(InputOrderContext);
99
+ const order = baseOrder === undefined
100
+ ? undefined
101
+ : subOrder === undefined
102
+ ? baseOrder
103
+ : `${baseOrder}.${String(subOrder)}`;
104
+ const key = inputKeyOf(fieldId, rowKey);
105
+ // A callback ref registers at commit time, never during render: React calls it with the
106
+ // mounted input and with null on unmount, and the stable identity below keeps a re-render
107
+ // from unregistering and re-registering the same link unless its structural order moved.
108
+ const setInputRef = useCallback((target) => {
109
+ if (chain === undefined)
110
+ return;
111
+ if (target === null)
112
+ chain.unregister(key);
113
+ else
114
+ chain.register(key, target, order);
115
+ }, [chain, key, order]);
116
+ const focusNext = () => {
117
+ chain?.focusAfter(key);
118
+ };
119
+ return { setInputRef, focusNext };
120
+ }
121
+ /** Joins non-empty hint or id-list fragments with a single space, or returns `undefined`. */
122
+ function joinTokens(...parts) {
123
+ const present = parts.filter((part) => part !== undefined && part !== '');
124
+ return present.length === 0 ? undefined : present.join(' ');
125
+ }
126
+ /** One control, bound to its session binding. */
127
+ export function Control({ node, rowKey, translate, }) {
128
+ const field = useField(node.fieldId, rowKey);
129
+ const activeTheme = useNativeTheme();
130
+ const styles = fieldStylesFor(activeTheme);
131
+ const components = useControlComponents();
132
+ const plan = planOf(node);
133
+ const copy = useHostCopy();
134
+ const label = translate(field.descriptor.labelKey ?? field.fieldId);
135
+ const visibleErrors = visibleErrorsOf(field);
136
+ const errorItems = visibleErrors.flatMap((error) => {
137
+ const text = errorTextOf(error, label, translate, copy);
138
+ return text === undefined ? [] : [{ key: errorKeyOf(error), text }];
139
+ });
140
+ const errorHint = errorItems.length === 0 ? undefined : errorItems.map((item) => item.text).join(' ');
141
+ const describedBy = joinTokens(node.description === undefined ? undefined : field.a11y.descriptionId, errorItems.length === 0 ? undefined : field.a11y.errorId);
142
+ // `media_ref` and `media_ref[]` fields route to `components.media` (or `media_capture`) before
143
+ // generic `tags`/`multiselect`, and `signature_ref` routes to `components.signature` (or
144
+ // `signature_capture`) before a generic control fallback.
145
+ const isMedia = node.declaration.primitive === 'media_ref' ||
146
+ (node.declaration.primitive === 'array' && node.declaration.items?.primitive === 'media_ref');
147
+ const Custom = node.declaration.primitive === 'signature_ref'
148
+ ? (components?.signature_capture ?? components?.signature ?? components?.[node.control])
149
+ : isMedia
150
+ ? (components?.media_capture ?? components?.media ?? components?.[node.control])
151
+ : components?.[node.control];
152
+ const canCustom = Custom !== undefined &&
153
+ field.computation.kind === 'none' &&
154
+ field.withheldReason !== 'masked' &&
155
+ field.withheldReason !== 'write_only' &&
156
+ field.access !== 'masked';
157
+ const customA11y = canCustom
158
+ ? controlA11yProps(toNativeProps(node, field, copy.requiredMarker()), {
159
+ ...(errorHint === undefined ? {} : { errorHint }),
160
+ ...(describedBy === undefined ? {} : { describedBy }),
161
+ })
162
+ : undefined;
163
+ return (_jsxs(View, { style: styles.control, testID: `control:${node.fieldId}:${String(rowKey ?? '')}`, children: [_jsxs(Text, { style: styles.label, children: [node.label, field.a11y.required ? ' *' : ''] }), canCustom && Custom !== undefined && customA11y !== undefined ? (_jsx(Custom, { node: node, field: field, translate: translate, a11y: customA11y, theme: activeTheme, value: field.value, setValue: field.setValue, trySetValue: field.trySetValue, error: visibleErrors[0], required: field.a11y.required, disabled: field.disabled, readOnly: field.readOnly, mayWrite: field.mayWrite, options: node.declaration.options, constraints: {
164
+ minimum: node.declaration.minimum,
165
+ maximum: node.declaration.maximum,
166
+ step: node.declaration.step,
167
+ units: node.declaration.units,
168
+ accept: node.declaration.accept,
169
+ minBytes: node.declaration.minBytes,
170
+ maxBytes: node.declaration.maxBytes,
171
+ scale: node.declaration.scale,
172
+ currency: node.declaration.currency,
173
+ } })) : (_jsx(Entry, { node: node, field: field, plan: plan, styles: styles, activeTheme: activeTheme, ...(rowKey === undefined ? {} : { rowKey }), ...(errorHint === undefined ? {} : { errorHint }), ...(describedBy === undefined ? {} : { describedBy }), translate: translate })), node.description === undefined ? null : (_jsx(Text, { style: styles.description, ...(field.a11y.descriptionId === undefined
174
+ ? {}
175
+ : { nativeID: field.a11y.descriptionId }), children: node.description })), field.withheld ? _jsx(Text, { style: styles.description, children: copy.deferredValue() }) : null, errorItems.length > 0 ? (_jsx(Errors, { errorId: field.a11y.errorId, items: errorItems, styles: styles })) : null] }));
176
+ }
177
+ function useWriteGuard(field, label) {
178
+ const copy = useHostCopy();
179
+ const [refusal, setRefusal] = useState(undefined);
180
+ const report = (error) => {
181
+ if (error instanceof WriteRefusedError) {
182
+ setRefusal(error.code === 'INVALID_VALUE'
183
+ ? copy.invalidValue(label)
184
+ : copy.notEditable(label, field.access));
185
+ return;
186
+ }
187
+ if (error instanceof AxiomError) {
188
+ setRefusal(error.message);
189
+ return;
190
+ }
191
+ throw error;
192
+ };
193
+ const guard = (action) => {
194
+ try {
195
+ action();
196
+ setRefusal(undefined);
197
+ }
198
+ catch (error) {
199
+ report(error);
200
+ }
201
+ };
202
+ const write = (value) => {
203
+ if (!field.enabled)
204
+ return;
205
+ guard(() => field.setValue(value));
206
+ };
207
+ return { write, guard, refusal };
208
+ }
209
+ /** A wire value read as text, for a control the device does not write from its own domain. */
210
+ function ReadOnlyValue({ field, styles, }) {
211
+ // `field.text` is the provider's display answer, so a boolean or a list reads as the host
212
+ // states it; an undecided non-withheld value uses the shared dash projection.
213
+ const text = renderDisplayText(field.text, field.withheld);
214
+ return (_jsx(Text, { style: styles.body, accessibilityLabel: text, children: text }));
215
+ }
216
+ function Entry({ node, field, plan, styles, activeTheme, rowKey, errorHint, describedBy, translate, }) {
217
+ const copy = useHostCopy();
218
+ const props = toNativeProps(node, field, copy.requiredMarker());
219
+ const label = translate(field.descriptor.labelKey ?? field.fieldId);
220
+ const { write, guard, refusal } = useWriteGuard(field, label);
221
+ const { setInputRef, focusNext } = useInputChain(node.fieldId, rowKey);
222
+ // A writer owns this value. Painting its control would offer a write the session must refuse.
223
+ if (field.computation.kind !== 'none')
224
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
225
+ // A masked or stored write-only value has no editable control: the mask's host stand-in is the
226
+ // only text the first may show, and the second has no readable text at all. The control's visible
227
+ // deferral sentence states the handoff. A redacted value keeps the control its access permits.
228
+ if (field.withheldReason === 'masked' || field.withheldReason === 'write_only')
229
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
230
+ const refusalId = refusal === undefined ? undefined : `${field.a11y.errorId}-refusal`;
231
+ const combinedHint = joinTokens(errorHint, refusal);
232
+ const combinedDescribedBy = joinTokens(describedBy, refusalId);
233
+ const a11y = {
234
+ props,
235
+ ...(combinedHint === undefined ? {} : { errorHint: combinedHint }),
236
+ ...(combinedDescribedBy === undefined ? {} : { describedBy: combinedDescribedBy }),
237
+ ...(refusal === undefined ? {} : { invalid: true }),
238
+ };
239
+ const controlA11y = controlA11yProps(props, a11y);
240
+ const body = (() => {
241
+ switch (plan.family) {
242
+ case 'buffered':
243
+ if (field.readOnly && node.control === 'slider')
244
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
245
+ return (_jsx(BufferedEntry, { node: node, field: field, a11y: a11y, guard: guard, styles: styles, activeTheme: activeTheme, ...(rowKey === undefined ? {} : { rowKey }), format: plan.format }));
246
+ case 'text':
247
+ return (_jsx(TextInput, { ...controlA11y, style: styles.input, placeholderTextColor: activeTheme.color.muted,
248
+ // A read-only binding stays focusable and copyable, but accepts no text. `mayWrite`
249
+ // includes access, visibility and every enabled rule; rule-enabled alone would leave
250
+ // a redacted read-only input editable.
251
+ editable: field.mayWrite, keyboardType: node.hints.native.keyboardType, textContentType: node.hints.native.textContentType, autoCapitalize: node.hints.native.autoCapitalize, ...(node.placeholder === undefined ? {} : { placeholder: node.placeholder }), value: typeof field.value === 'string' ? field.value : field.text, onChangeText: (text) => write(text === '' ? null : text), onBlur: field.onBlur, multiline: node.control === 'textarea', returnKeyType: node.control === 'textarea' ? 'default' : 'next', ...(node.control === 'textarea'
252
+ ? {}
253
+ : { blurOnSubmit: false, onSubmitEditing: () => focusNext() }), ref: setInputRef }));
254
+ case 'secure':
255
+ return (_jsx(TextInput, { ...controlA11y, style: styles.input, placeholderTextColor: activeTheme.color.muted, editable: field.mayWrite, secureTextEntry: true, textContentType: "password", autoCapitalize: "none", autoCorrect: false, ...(node.placeholder === undefined ? {} : { placeholder: node.placeholder }), value: typeof field.value === 'string' ? field.value : '', onChangeText: (text) => write(text === '' ? null : text), onBlur: field.onBlur, returnKeyType: "next", blurOnSubmit: false, onSubmitEditing: () => focusNext(), ref: setInputRef }));
256
+ case 'quantity':
257
+ return (_jsx(QuantityEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, activeTheme: activeTheme, ...(rowKey === undefined ? {} : { rowKey }) }));
258
+ case 'boolean':
259
+ if (field.readOnly)
260
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
261
+ return (_jsx(Switch, { ...controlA11y, accessibilityRole: "switch", accessibilityState: { disabled: !field.enabled, checked: field.value === true }, "aria-checked": field.value === true, "aria-disabled": !field.enabled, disabled: !field.enabled, trackColor: { false: activeTheme.color.border, true: activeTheme.color.accent }, thumbColor: activeTheme.color.onAccent, value: field.value === true, onValueChange: write }));
262
+ case 'boolean-choice':
263
+ if (field.readOnly)
264
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
265
+ return (_jsx(BooleanChoiceEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, translate: translate }));
266
+ case 'choice':
267
+ if (field.readOnly)
268
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
269
+ return (_jsx(ChoiceEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, ...(rowKey === undefined ? {} : { rowKey }), translate: translate }));
270
+ case 'list':
271
+ if (field.readOnly)
272
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
273
+ return (_jsx(ListEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, activeTheme: activeTheme, ...(rowKey === undefined ? {} : { rowKey }), translate: translate }));
274
+ case 'rank':
275
+ if (field.readOnly)
276
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
277
+ return (_jsx(RankEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, ...(rowKey === undefined ? {} : { rowKey }), translate: translate }));
278
+ case 'signature':
279
+ return _jsx(SignatureEntry, { field: field, styles: styles, translate: translate });
280
+ case 'media':
281
+ return (_jsx(MediaEntry, { node: node, field: field, write: write, styles: styles, translate: translate }));
282
+ case 'position':
283
+ return _jsx(PositionEntry, { field: field, write: write, styles: styles, translate: translate });
284
+ case 'duration':
285
+ if (field.readOnly)
286
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
287
+ return (_jsx(DurationEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, activeTheme: activeTheme, ...(rowKey === undefined ? {} : { rowKey }) }));
288
+ case 'address':
289
+ if (field.readOnly)
290
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
291
+ return (_jsx(AddressEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, activeTheme: activeTheme, ...(rowKey === undefined ? {} : { rowKey }) }));
292
+ default:
293
+ return assertNeverPlan(plan);
294
+ }
295
+ })();
296
+ return (_jsxs(_Fragment, { children: [body, refusal === undefined ? null : (_jsx(Text, { style: styles.danger, ...(refusalId === undefined ? {} : { nativeID: refusalId }), accessibilityRole: "alert", accessibilityLiveRegion: "polite", children: refusal }))] }));
297
+ }
298
+ function assertNeverPlan(value) {
299
+ throw new Error(`unreachable control plan: ${JSON.stringify(value)}`);
300
+ }
301
+ /**
302
+ * A declared option domain: one pressable per option.
303
+ *
304
+ * A `timeslot` states a host source instead of a fixed list, and its items arrive from
305
+ * `useAsyncOptions` keyed by the declared dependencies; a source the host does not answer paints
306
+ * the load failure rather than a box that could only write a value the contract refuses.
307
+ */
308
+ function ChoiceEntry({ node, field, a11y, write, styles, rowKey, translate, }) {
309
+ const copy = useHostCopy();
310
+ const options = node.declaration.options;
311
+ if (options === undefined && node.declaration.optionSource !== undefined) {
312
+ return (_jsx(AsyncChoice, { node: node, field: field, a11y: a11y, write: write, styles: styles, ...(rowKey === undefined ? {} : { rowKey }), translate: translate }));
313
+ }
314
+ if (options === undefined)
315
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
316
+ return (_jsx(View, { style: styles.row, accessibilityRole: "radiogroup", ...controlA11yProps(a11y.props, a11y), accessibilityState: { disabled: !field.enabled }, "aria-disabled": !field.enabled, children: options.map((option) => {
317
+ const value = optionCodeValue(node.declaration, option.code);
318
+ const selected = sameWireValue(field.value, value);
319
+ const answer = availabilityOf(field, value, node.label, translate(option.labelKey), translate, copy, node.declaration);
320
+ return (_jsxs(Pressable, { accessibilityRole: "radio", accessibilityState: { checked: selected, disabled: !field.enabled }, "aria-checked": selected, "aria-disabled": !field.enabled, ...(answer === undefined ? {} : { accessibilityHint: answer }), disabled: !field.enabled, onPress: () => write(value), style: selected ? styles.selected : styles.option, children: [_jsx(Text, { style: styles.body, children: translate(option.labelKey) }), answer === undefined ? null : _jsx(Text, { style: styles.description, children: answer })] }, String(option.code)));
321
+ }) }));
322
+ }
323
+ /**
324
+ * The record's answer for one offered code, in the host's words, or `undefined` when available.
325
+ *
326
+ * An unavailable code states the sentence its declaration carries; a code the record cannot
327
+ * decide states the open question with its cause. This is the one place the device reads the
328
+ * answer, so the hint, the painted reason and the control's pressability cannot disagree.
329
+ */
330
+ function availabilityOf(field, code, fieldLabel, label, translate, copy, declaration) {
331
+ const answer = (field.unavailableOptions ?? []).find((entry) => sameWireValue(declaration === undefined ? entry.code : optionCodeValue(declaration, entry.code), code));
332
+ if (answer === undefined)
333
+ return undefined;
334
+ if (answer.messageKey !== undefined)
335
+ return translate(answer.messageKey, answer.params);
336
+ return answer.state === 'unavailable'
337
+ ? copy.unavailableOption(label)
338
+ : copy.undeterminedOption(fieldLabel, label, answer.cause ?? 'unknown');
339
+ }
340
+ /**
341
+ * A boolean painted as its two codes.
342
+ *
343
+ * The compiler admits `select`/`radio`/`combobox` on a boolean and states the two codes as the
344
+ * strings `"true"` and `"false"`; the field's wire value is a JSON boolean. Choosing a code
345
+ * therefore writes the boolean it names, never the code itself, which the wire would refuse.
346
+ */
347
+ function BooleanChoiceEntry({ node, field, a11y, write, styles, translate, }) {
348
+ const copy = useHostCopy();
349
+ const declared = node.declaration.options;
350
+ const options = declared === undefined
351
+ ? [
352
+ { code: 'true', labelKey: '' },
353
+ { code: 'false', labelKey: '' },
354
+ ]
355
+ : declared;
356
+ return (_jsx(View, { style: styles.row, accessibilityRole: "radiogroup", ...controlA11yProps(a11y.props, a11y), accessibilityState: { disabled: !field.enabled }, "aria-disabled": !field.enabled, children: options.map((option) => {
357
+ const value = optionCodeValue(node.declaration, option.code);
358
+ const selected = sameWireValue(field.value, value);
359
+ const label = option.labelKey === '' ? String(option.code) : translate(option.labelKey);
360
+ const answer = availabilityOf(field, value, node.label, label, translate, copy, node.declaration);
361
+ return (_jsxs(Pressable, { accessibilityRole: "radio", accessibilityState: { checked: selected, disabled: !field.enabled }, "aria-checked": selected, "aria-disabled": !field.enabled, ...(answer === undefined ? {} : { accessibilityHint: answer }), disabled: !field.enabled, onPress: () => write(value), style: selected ? styles.selected : styles.option, children: [_jsx(Text, { style: styles.body, children: label }), answer === undefined ? null : _jsx(Text, { style: styles.description, children: answer })] }, String(option.code)));
362
+ }) }));
363
+ }
364
+ /**
365
+ * A choice whose domain the host loads on demand, whether a timeslot or a generic host domain.
366
+ *
367
+ * The items come from `useAsyncOptions`, keyed by the declared dependencies, so the host offers
368
+ * the slots for the window the form holds and one change loads one source. The selected item is
369
+ * matched by the wire contract's own equality, because a timeslot is an object rather than a
370
+ * code.
371
+ */
372
+ function AsyncChoice({ node, field, a11y, write, styles, rowKey, translate, }) {
373
+ const pages = useAsyncOptions(node.fieldId, rowKey);
374
+ const copy = useHostCopy();
375
+ const selected = pages.items.findIndex((item) => sameWireValue(item.value, field.value));
376
+ return (_jsxs(View, { style: styles.row, accessibilityRole: "radiogroup", ...controlA11yProps(a11y.props, a11y), accessibilityState: { disabled: !field.enabled }, "aria-disabled": !field.enabled, children: [pages.items.map((item, index) => {
377
+ const chosen = index === selected;
378
+ const label = item.labelKey === ''
379
+ ? renderValueText(item.value, copy.display, node.declaration.primitive)
380
+ : translate(item.labelKey);
381
+ const answer = availabilityOf(field, item.value, node.label, label, translate, copy, node.declaration);
382
+ return (_jsxs(Pressable, { accessibilityRole: "radio", accessibilityState: { checked: chosen, disabled: !field.enabled }, "aria-checked": chosen, "aria-disabled": !field.enabled, ...(answer === undefined ? {} : { accessibilityHint: answer }), disabled: !field.enabled, onPress: () => write(item.value), style: chosen ? styles.selected : styles.option, children: [_jsx(Text, { style: styles.body, children: label }), answer === undefined ? null : _jsx(Text, { style: styles.description, children: answer })] }, canonicalizeRestricted(item.value)));
383
+ }), _jsx(OptionPagesStatus, { node: node, pages: pages, styles: styles, translate: translate })] }));
384
+ }
385
+ /** Translated labels of declared top-level host-source dependencies that currently hold no value. */
386
+ function missingDependencyLabels(node, fields, values, translate) {
387
+ const source = node.declaration.optionSource;
388
+ if (source?.kind !== 'host' || source.dependsOn === undefined || source.dependsOn.length === 0) {
389
+ return [];
390
+ }
391
+ const topLevel = new Map(fields.map((entry) => [entry.fieldId, entry]));
392
+ const missing = [];
393
+ for (const depId of source.dependsOn) {
394
+ const declaration = topLevel.get(depId);
395
+ if (declaration === undefined)
396
+ continue;
397
+ const value = values[depId];
398
+ if (value === undefined || value === null || value === '') {
399
+ missing.push(declaration.labelKey === undefined ? depId : translate(declaration.labelKey));
400
+ }
401
+ }
402
+ return missing;
403
+ }
404
+ /** The loading, failure and reader-controlled next-page state every host domain shares. */
405
+ function OptionPagesStatus({ node, pages, styles, translate, }) {
406
+ const copy = useHostCopy();
407
+ const fields = useFields();
408
+ const form = useForm();
409
+ const empty = pages.readable &&
410
+ pages.resolved &&
411
+ pages.error === undefined &&
412
+ pages.items.length === 0 &&
413
+ !pages.hasMore;
414
+ const missing = empty ? missingDependencyLabels(node, fields, form.getValues(), translate) : [];
415
+ return (_jsxs(_Fragment, { children: [pages.hasMore ? (_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.loadMoreOptions(), accessibilityState: { disabled: pages.loading }, "aria-disabled": pages.loading, disabled: pages.loading, onPress: pages.loadMore, style: styles.option, children: _jsx(Text, { style: styles.body, children: copy.loadMoreOptions() }) })) : null, pages.loading ? _jsx(Text, { style: styles.description, children: "Loading options\u2026" }) : null, empty ? (_jsx(Text, { style: styles.description, accessibilityLiveRegion: "polite", children: missing.length > 0 ? copy.optionsNeedDependencies(missing) : copy.emptyOptions() })) : null, pages.error === undefined ? null : (_jsxs(Text, { style: styles.danger, accessibilityRole: "alert", children: ["The options could not be loaded: ", pages.error.message] }))] }));
416
+ }
417
+ /**
418
+ * A captured signature: its value, and the host's sign action when this device has a signer.
419
+ *
420
+ * The binding is read like every other host-domain control: nothing here writes a signature the
421
+ * wire contract did not produce, and the action asks the host to sign the record as it stands.
422
+ * A device with no signer paints the value and the localized unavailability explanation rather
423
+ * than a button that could only fail.
424
+ */
425
+ function SignatureEntry({ field, styles, translate, }) {
426
+ const { captureSignature } = useHostActions();
427
+ const copy = useHostCopy();
428
+ const [failure, setFailure] = useState(undefined);
429
+ // A read-only or disabled viewer must not be offered the signer, matching the Web adapter.
430
+ if (!field.enabled || field.access !== 'read_write')
431
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
432
+ const label = translate(field.descriptor.labelKey ?? field.fieldId);
433
+ if (captureSignature === undefined) {
434
+ return (_jsxs(_Fragment, { children: [_jsx(ReadOnlyValue, { field: field, styles: styles }), _jsx(Text, { style: styles.description, children: copy.signatureUnavailable(label) })] }));
435
+ }
436
+ const paintFailure = (detail) => setFailure(detail);
437
+ const capture = () => {
438
+ setFailure(undefined);
439
+ try {
440
+ void captureSignature(field.fieldId).then(paintFailure, (error) => {
441
+ paintFailure(error instanceof Error ? error.message : copy.signerFailed());
442
+ });
443
+ }
444
+ catch (error) {
445
+ paintFailure(error instanceof Error ? error.message : copy.signerFailed());
446
+ }
447
+ };
448
+ return (_jsxs(_Fragment, { children: [_jsx(ReadOnlyValue, { field: field, styles: styles }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.captureSignature(label), onPress: capture, style: styles.option, children: _jsx(Text, { style: styles.body, children: copy.captureSignature(label) }) }), failure === undefined ? null : (_jsxs(View, { accessibilityRole: "alert", children: [_jsx(Text, { style: styles.danger, children: copy.captureFailed() }), _jsx(Text, { style: styles.danger, children: failure })] }))] }));
449
+ }
450
+ /** Validates a host-returned `media_ref` against declared `accept`/`minBytes`/`maxBytes`. */
451
+ function mediaConstraintRefusal(reference, label, declaration, copy) {
452
+ const rawBytes = reference['byteSize'];
453
+ const bytes = typeof rawBytes === 'number' && Number.isFinite(rawBytes) ? rawBytes : undefined;
454
+ if (bytes !== undefined && declaration.maxBytes !== undefined && bytes > declaration.maxBytes) {
455
+ return copy.mediaConstraint(label, 'maxBytes', declaration.maxBytes, bytes);
456
+ }
457
+ if (bytes !== undefined && declaration.minBytes !== undefined && bytes < declaration.minBytes) {
458
+ return copy.mediaConstraint(label, 'minBytes', declaration.minBytes, bytes);
459
+ }
460
+ const rawMime = reference['mime'];
461
+ const mime = typeof rawMime === 'string' ? rawMime : '';
462
+ if (mime !== '' &&
463
+ declaration.accept !== undefined &&
464
+ declaration.accept.length > 0 &&
465
+ !mediaAcceptMatches(declaration.accept, mime)) {
466
+ return copy.mediaConstraint(label, 'accept', declaration.accept, mime);
467
+ }
468
+ return undefined;
469
+ }
470
+ /** Human-readable name for one attached `media_ref` item in a list. */
471
+ function mediaItemLabel(item, index) {
472
+ if (isRecord(item)) {
473
+ const name = item['name'];
474
+ if (typeof name === 'string' && name !== '')
475
+ return name;
476
+ const filename = item['filename'];
477
+ if (typeof filename === 'string' && filename !== '')
478
+ return filename;
479
+ const id = item['id'];
480
+ if (typeof id === 'string' && id !== '')
481
+ return id;
482
+ }
483
+ return `#${String(index + 1)}`;
484
+ }
485
+ /** Projects a host capture error into a `MediaFailure` without repeating the generic headline. */
486
+ function mediaFailureOf(error, copy) {
487
+ const detail = error instanceof Error && error.message !== '' && error.message !== copy.mediaFailed()
488
+ ? error.message
489
+ : undefined;
490
+ return { kind: 'failed', ...(detail === undefined ? {} : { detail }) };
491
+ }
492
+ /**
493
+ * Reads the latest committed media array from the session store to avoid stale closure overwrites.
494
+ *
495
+ * Reading through `form.getField(field.fieldId, field.rowKey)` resolves top-level arrays, members
496
+ * nested inside a `record` container, and repeating-row arrays uniformly against committed state.
497
+ */
498
+ function latestMediaItems(form, field) {
499
+ try {
500
+ const state = form.getField(field.fieldId, field.rowKey);
501
+ if (state.value.kind === 'value' && Array.isArray(state.value.value)) {
502
+ return state.value.value;
503
+ }
504
+ return [];
505
+ }
506
+ catch {
507
+ return Array.isArray(field.value) ? field.value : [];
508
+ }
509
+ }
510
+ /**
511
+ * Invokes the host's `captureMedia` port outside the component body so both synchronous throws
512
+ * and asynchronous rejections settle through one error callback while keeping `MediaEntry`
513
+ * React Compiler eligible with zero bailouts.
514
+ */
515
+ function invokeMediaCapture(captureMedia, fieldId, request, onSuccess, onError) {
516
+ try {
517
+ void captureMedia(fieldId, request).then(onSuccess, onError);
518
+ }
519
+ catch (error) {
520
+ onError(error);
521
+ }
522
+ }
523
+ /**
524
+ * A captured media reference (or list of references), driven by the host's `captureMedia` port.
525
+ *
526
+ * Without a host capture action, the control paints the stored value read-only rather than
527
+ * offering a button that could only fail. With one, pressing attach passes the field's declared
528
+ * bounds to the host, validates the returned `media_ref` against `accept`/`minBytes`/`maxBytes`,
529
+ * and commits it (or appends it to the latest committed `media_ref[]` array).
530
+ */
531
+ function MediaEntry({ node, field, write, styles, translate, }) {
532
+ const form = useForm();
533
+ const { captureMedia } = useHostActions();
534
+ const copy = useHostCopy();
535
+ const [pending, setPending] = useState(false);
536
+ const [failure, setFailure] = useState(undefined);
537
+ const inFlightRef = useRef(false);
538
+ const mounted = useRef(true);
539
+ useEffect(() => {
540
+ mounted.current = true;
541
+ return () => {
542
+ mounted.current = false;
543
+ inFlightRef.current = false;
544
+ };
545
+ }, []);
546
+ const label = translate(field.descriptor.labelKey ?? field.fieldId);
547
+ const canCapture = captureMedia !== undefined && field.enabled && field.access === 'read_write';
548
+ const isArray = node.declaration.primitive === 'array';
549
+ const items = isArray && Array.isArray(field.value) ? field.value : [];
550
+ const hasValue = isArray ? items.length > 0 : field.value !== undefined && field.value !== null;
551
+ if (!canCapture)
552
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
553
+ const capture = () => {
554
+ if (inFlightRef.current || pending)
555
+ return;
556
+ inFlightRef.current = true;
557
+ setPending(true);
558
+ setFailure(undefined);
559
+ const { accept, minBytes, maxBytes } = node.declaration;
560
+ const request = {
561
+ label,
562
+ ...(accept === undefined ? {} : { accept }),
563
+ ...(minBytes === undefined ? {} : { minBytes }),
564
+ ...(maxBytes === undefined ? {} : { maxBytes }),
565
+ };
566
+ invokeMediaCapture(captureMedia, field.fieldId, request, (reference) => {
567
+ inFlightRef.current = false;
568
+ if (!mounted.current)
569
+ return;
570
+ setPending(false);
571
+ if (reference === undefined)
572
+ return;
573
+ const constraint = mediaConstraintRefusal(reference, label, node.declaration, copy);
574
+ if (constraint !== undefined) {
575
+ setFailure({ kind: 'constraint', sentence: constraint });
576
+ return;
577
+ }
578
+ if (isArray) {
579
+ write([...latestMediaItems(form, field), reference]);
580
+ }
581
+ else {
582
+ write(reference);
583
+ }
584
+ }, (error) => {
585
+ inFlightRef.current = false;
586
+ if (!mounted.current)
587
+ return;
588
+ setPending(false);
589
+ setFailure(mediaFailureOf(error, copy));
590
+ });
591
+ };
592
+ return (_jsxs(_Fragment, { children: [isArray ? (items.length === 0 ? (_jsx(ReadOnlyValue, { field: field, styles: styles })) : (_jsx(View, { style: styles.stack, children: items.map((item, index) => {
593
+ const itemName = mediaItemLabel(item, index);
594
+ const itemKey = canonicalizeRestricted(item);
595
+ let removed = false;
596
+ return (_jsxs(View, { style: styles.row, children: [_jsx(Text, { style: styles.body, children: itemName }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.removeMedia(itemName), onPress: () => {
597
+ if (removed)
598
+ return;
599
+ removed = true;
600
+ const current = latestMediaItems(form, field);
601
+ const atExactIndex = current[index];
602
+ const removeAt = atExactIndex !== undefined &&
603
+ canonicalizeRestricted(atExactIndex) === itemKey
604
+ ? index
605
+ : current.findIndex((entry) => canonicalizeRestricted(entry) === itemKey);
606
+ if (removeAt === -1)
607
+ return;
608
+ write(current.filter((_, at) => at !== removeAt));
609
+ }, style: styles.option, children: _jsx(Text, { style: styles.body, children: copy.removeMedia(itemName) }) })] }, `${String(index)}:${itemKey}`));
610
+ }) }))) : (_jsx(ReadOnlyValue, { field: field, styles: styles })), _jsxs(View, { style: styles.row, children: [_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.attachMedia(), accessibilityState: { disabled: pending }, "aria-disabled": pending, disabled: pending, onPress: capture, style: styles.option, children: _jsx(Text, { style: styles.body, children: copy.attachMedia() }) }), !isArray && hasValue ? (_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.removeMedia(label), onPress: () => write(null), style: styles.option, children: _jsx(Text, { style: styles.body, children: copy.removeMedia(label) }) })) : null] }), failure === undefined ? null : failure.kind === 'constraint' ? (_jsx(Text, { style: styles.danger, accessibilityRole: "alert", children: failure.sentence })) : (_jsxs(View, { children: [_jsx(Text, { style: styles.danger, accessibilityRole: "alert", children: copy.mediaFailed() }), failure.detail === undefined ? null : (_jsx(Text, { style: styles.danger, children: failure.detail }))] }))] }));
611
+ }
612
+ /** Converts a granted host position into the canonical closed coordinate record, or `undefined`. */
613
+ function canonicalPositionOf(reading) {
614
+ if (!Number.isFinite(reading.latitude) || !Number.isFinite(reading.longitude))
615
+ return undefined;
616
+ if (reading.latitude < -90 || reading.latitude > 90)
617
+ return undefined;
618
+ if (reading.longitude < -180 || reading.longitude > 180)
619
+ return undefined;
620
+ if (reading.accuracy !== undefined &&
621
+ (!Number.isFinite(reading.accuracy) || reading.accuracy < 0)) {
622
+ return undefined;
623
+ }
624
+ try {
625
+ const latitude = canonicalDecimal(new AxiomDecimal(reading.latitude));
626
+ const longitude = canonicalDecimal(new AxiomDecimal(reading.longitude));
627
+ const accuracy = reading.accuracy === undefined
628
+ ? undefined
629
+ : canonicalDecimal(new AxiomDecimal(reading.accuracy));
630
+ return {
631
+ latitude,
632
+ longitude,
633
+ ...(accuracy === undefined ? {} : { accuracy }),
634
+ };
635
+ }
636
+ catch {
637
+ return undefined;
638
+ }
639
+ }
640
+ /**
641
+ * A geographic coordinate control, driven by the host's `capturePosition` port.
642
+ *
643
+ * Without a host position reader, the control paints the recorded value read-only. With one,
644
+ * pressing the button requests a reading and commits the canonicalized coordinate record or
645
+ * states the refusal outcome in the active locale.
646
+ */
647
+ function PositionEntry({ field, write, styles, translate, }) {
648
+ const { capturePosition } = useHostActions();
649
+ const copy = useHostCopy();
650
+ const [pending, setPending] = useState(false);
651
+ const [failure, setFailure] = useState(undefined);
652
+ const label = translate(field.descriptor.labelKey ?? field.fieldId);
653
+ if (capturePosition === undefined || !field.enabled)
654
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
655
+ const settle = (result) => {
656
+ setPending(false);
657
+ switch (result.outcome) {
658
+ case 'granted': {
659
+ const record = canonicalPositionOf(result);
660
+ if (record === undefined) {
661
+ setFailure(copy.positionInvalidReading());
662
+ return;
663
+ }
664
+ setFailure(undefined);
665
+ write(record);
666
+ return;
667
+ }
668
+ case 'denied':
669
+ setFailure(copy.positionDenied());
670
+ return;
671
+ case 'unavailable':
672
+ setFailure(copy.positionUnavailable());
673
+ return;
674
+ case 'timed-out':
675
+ setFailure(copy.positionTimedOut());
676
+ return;
677
+ default:
678
+ return assertNever(result);
679
+ }
680
+ };
681
+ const capture = () => {
682
+ setPending(true);
683
+ setFailure(undefined);
684
+ try {
685
+ void capturePosition(field.fieldId).then(settle, () => {
686
+ setPending(false);
687
+ setFailure(copy.positionFailed());
688
+ });
689
+ }
690
+ catch {
691
+ setPending(false);
692
+ setFailure(copy.positionFailed());
693
+ }
694
+ };
695
+ return (_jsxs(_Fragment, { children: [_jsx(ReadOnlyValue, { field: field, styles: styles }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.positionCapture(label), accessibilityState: { disabled: pending }, "aria-disabled": pending, disabled: pending, onPress: capture, style: styles.option, children: _jsx(Text, { style: styles.body, children: pending ? copy.positionRequesting() : copy.positionCapture(label) }) }), failure === undefined ? null : (_jsx(Text, { style: styles.danger, accessibilityRole: "alert", children: failure }))] }));
696
+ }
697
+ /** A list control: option toggles, a field's own domain, or comma-separated text. */
698
+ function ListEntry({ node, field, a11y, write, styles, activeTheme, rowKey, translate, }) {
699
+ const copy = useHostCopy();
700
+ const { setInputRef, focusNext } = useInputChain(node.fieldId, rowKey);
701
+ // The freeform entry is a draft until it is committed: a controlled value derived from the
702
+ // record erases the separator on the keystroke that types it, so a second entry could never
703
+ // be typed. Keeping the line until blur is what lets the split see both entries.
704
+ const [draft, setDraft] = useState(undefined);
705
+ const options = node.declaration.options;
706
+ const source = node.declaration.optionSource;
707
+ if (options === undefined && source?.kind === 'host') {
708
+ return (_jsx(AsyncListEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, ...(rowKey === undefined ? {} : { rowKey }), translate: translate }));
709
+ }
710
+ if (options === undefined && source?.kind === 'field') {
711
+ return (_jsx(SourceListEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, sourceFieldId: source.fieldId }));
712
+ }
713
+ if (options === undefined) {
714
+ if (node.declaration.items?.primitive !== 'string')
715
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
716
+ const committed = Array.isArray(field.value)
717
+ ? field.value
718
+ .map((entry) => renderValueText(entry, copy.display, node.declaration.items?.primitive))
719
+ .join(', ')
720
+ : '';
721
+ const text = draft ?? committed;
722
+ const commit = () => {
723
+ const entries = text
724
+ .split(',')
725
+ .map((entry) => entry.trim())
726
+ .filter((entry) => entry !== '');
727
+ write(entries.length === 0 ? null : entries);
728
+ setDraft(undefined);
729
+ };
730
+ return (_jsx(TextInput, { ...controlA11yProps(a11y.props, a11y), style: styles.input, placeholderTextColor: activeTheme.color.muted, editable: field.enabled, ...(node.placeholder === undefined ? {} : { placeholder: node.placeholder }), value: text, onChangeText: setDraft, onBlur: () => {
731
+ commit();
732
+ field.onBlur();
733
+ }, returnKeyType: "next", blurOnSubmit: false, onSubmitEditing: () => {
734
+ commit();
735
+ focusNext();
736
+ }, ref: setInputRef }));
737
+ }
738
+ const held = Array.isArray(field.value) ? field.value : [];
739
+ const heldKeys = new Set(held.map((entry) => canonicalizeRestricted(entry)));
740
+ const declaredValues = options.map((candidate) => optionCodeValue(node.declaration, candidate.code));
741
+ const declaredKeys = new Set(declaredValues.map((value) => canonicalizeRestricted(value)));
742
+ return (_jsx(View, { style: styles.row, accessibilityRole: "group", ...controlA11yProps(a11y.props, a11y), children: options.map((option, index) => {
743
+ const value = declaredValues[index] ?? optionCodeValue(node.declaration, option.code);
744
+ const selected = heldKeys.has(canonicalizeRestricted(value));
745
+ const label = translate(option.labelKey);
746
+ const answer = availabilityOf(field, value, node.label, label, translate, copy, node.declaration);
747
+ return (_jsxs(Pressable, { accessibilityRole: "checkbox", accessibilityState: { checked: selected, disabled: !field.enabled }, "aria-checked": selected, "aria-disabled": !field.enabled, ...(answer === undefined ? {} : { accessibilityHint: answer }), disabled: !field.enabled, onPress: () => {
748
+ const next = [
749
+ ...held.filter((entry) => !declaredKeys.has(canonicalizeRestricted(entry))),
750
+ ...declaredValues.filter((candidate) => sameWireValue(candidate, value)
751
+ ? !selected
752
+ : heldKeys.has(canonicalizeRestricted(candidate))),
753
+ ];
754
+ write(next);
755
+ }, style: selected ? styles.selected : styles.option, children: [_jsx(Text, { style: styles.body, children: label }), answer === undefined ? null : _jsx(Text, { style: styles.description, children: answer })] }, String(option.code)));
756
+ }) }));
757
+ }
758
+ /**
759
+ * An ordered ranking control (`MODEL-3.1.6`), separate from unordered `multiselect`/`tags`.
760
+ *
761
+ * Pressing an option appends it in the respondent's chosen order (rather than rewriting to
762
+ * declaration or source order), pressing it again removes it, and the ranked list provides move
763
+ * up, move down, and remove controls for reordering.
764
+ */
765
+ function RankEntry({ node, field, a11y, write, styles, rowKey, translate, }) {
766
+ const copy = useHostCopy();
767
+ const options = node.declaration.options;
768
+ const source = node.declaration.optionSource;
769
+ if (options === undefined && source?.kind === 'field') {
770
+ return (_jsx(SourceRankEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, sourceFieldId: source.fieldId }));
771
+ }
772
+ if (options === undefined && source?.kind === 'host') {
773
+ return (_jsx(AsyncRankEntry, { node: node, field: field, a11y: a11y, write: write, styles: styles, ...(rowKey === undefined ? {} : { rowKey }), translate: translate }));
774
+ }
775
+ if (options === undefined)
776
+ return _jsx(ReadOnlyValue, { field: field, styles: styles });
777
+ const domain = options.map((option) => {
778
+ const value = optionCodeValue(node.declaration, option.code);
779
+ const label = translate(option.labelKey);
780
+ const availability = availabilityOf(field, value, node.label, label, translate, copy, node.declaration);
781
+ return {
782
+ key: String(option.code),
783
+ value,
784
+ label,
785
+ ...(availability === undefined ? {} : { availability }),
786
+ };
787
+ });
788
+ return (_jsx(RankEditor, { node: node, field: field, a11y: a11y, domain: domain, write: write, styles: styles }));
789
+ }
790
+ function SourceRankEntry({ node, field, a11y, write, styles, sourceFieldId, }) {
791
+ const source = useField(sourceFieldId);
792
+ const copy = useHostCopy();
793
+ const items = Array.isArray(source.value) ? source.value : [];
794
+ const domain = items.map((value, index) => ({
795
+ key: `${String(index)}:${canonicalizeRestricted(value)}`,
796
+ value,
797
+ label: renderValueText(value, copy.display, node.declaration.items?.primitive),
798
+ }));
799
+ return (_jsx(RankEditor, { node: node, field: field, a11y: a11y, domain: domain, write: write, styles: styles }));
800
+ }
801
+ function AsyncRankEntry({ node, field, a11y, write, styles, rowKey, translate, }) {
802
+ const pages = useAsyncOptions(node.fieldId, rowKey);
803
+ const copy = useHostCopy();
804
+ const domain = pages.items.map((item) => {
805
+ const label = item.labelKey === ''
806
+ ? renderValueText(item.value, copy.display, node.declaration.items?.primitive)
807
+ : translate(item.labelKey);
808
+ const availability = availabilityOf(field, item.value, node.label, label, translate, copy, node.declaration);
809
+ return {
810
+ key: canonicalizeRestricted(item.value),
811
+ value: item.value,
812
+ label,
813
+ ...(availability === undefined ? {} : { availability }),
814
+ };
815
+ });
816
+ return (_jsxs(_Fragment, { children: [_jsx(RankEditor, { node: node, field: field, a11y: a11y, domain: domain, write: write, styles: styles }), _jsx(OptionPagesStatus, { node: node, pages: pages, styles: styles, translate: translate })] }));
817
+ }
818
+ /** Presentational editor for an ordered ranking: option toggles plus move up/down/remove. */
819
+ function RankEditor({ node, field, a11y, domain, write, styles, }) {
820
+ const copy = useHostCopy();
821
+ const chosen = Array.isArray(field.value) ? field.value : [];
822
+ const isChosen = (value) => chosen.some((entry) => sameWireValue(entry, value));
823
+ const toggle = (value) => {
824
+ if (isChosen(value)) {
825
+ write(chosen.filter((entry) => !sameWireValue(entry, value)));
826
+ return;
827
+ }
828
+ // Append in respondent press order rather than sorting by declaration/source order.
829
+ write([...chosen, value]);
830
+ };
831
+ const move = (index, delta) => {
832
+ const target = index + delta;
833
+ if (target < 0 || target >= chosen.length)
834
+ return;
835
+ const next = [...chosen];
836
+ const moved = next.splice(index, 1)[0];
837
+ if (moved === undefined)
838
+ return;
839
+ next.splice(target, 0, moved);
840
+ write(next);
841
+ };
842
+ const labelFor = (value) => domain.find((item) => sameWireValue(item.value, value))?.label ??
843
+ renderValueText(value, copy.display, node.declaration.items?.primitive);
844
+ return (_jsxs(View, { style: styles.stack, accessibilityRole: "group", ...controlA11yProps(a11y.props, a11y), children: [_jsx(View, { style: styles.row, children: domain.map((item) => {
845
+ const selected = isChosen(item.value);
846
+ return (_jsxs(Pressable, { accessibilityRole: "checkbox", accessibilityState: { checked: selected, disabled: !field.enabled }, "aria-checked": selected, "aria-disabled": !field.enabled, ...(item.availability === undefined ? {} : { accessibilityHint: item.availability }), disabled: !field.enabled, onPress: () => toggle(item.value), style: selected ? styles.selected : styles.option, children: [_jsx(Text, { style: styles.body, children: item.label }), item.availability === undefined ? null : (_jsx(Text, { style: styles.description, children: item.availability }))] }, item.key));
847
+ }) }), chosen.length === 0 ? null : (_jsx(View, { style: styles.stack, children: chosen.map((value, index) => {
848
+ const itemLabel = labelFor(value);
849
+ const canMoveUp = field.enabled && index > 0;
850
+ const canMoveDown = field.enabled && index < chosen.length - 1;
851
+ return (_jsxs(View, { style: styles.row, children: [_jsx(Text, { style: styles.body, children: `${String(index + 1)}. ${itemLabel}` }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.rankMoveUp(itemLabel), accessibilityState: { disabled: !canMoveUp }, "aria-disabled": !canMoveUp, disabled: !canMoveUp, onPress: () => move(index, -1), style: styles.option, children: _jsx(Text, { style: styles.body, children: copy.rankMoveUp(itemLabel) }) }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.rankMoveDown(itemLabel), accessibilityState: { disabled: !canMoveDown }, "aria-disabled": !canMoveDown, disabled: !canMoveDown, onPress: () => move(index, 1), style: styles.option, children: _jsx(Text, { style: styles.body, children: copy.rankMoveDown(itemLabel) }) }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: copy.rankRemove(itemLabel), accessibilityState: { disabled: !field.enabled }, "aria-disabled": !field.enabled, disabled: !field.enabled, onPress: () => write(chosen.filter((_, at) => at !== index)), style: styles.option, children: _jsx(Text, { style: styles.body, children: copy.rankRemove(itemLabel) }) })] }, canonicalizeRestricted(value)));
852
+ }) }))] }));
853
+ }
854
+ /** A multiple selection whose domain arrives through the shared paged option machine. */
855
+ function AsyncListEntry({ node, field, a11y, write, styles, rowKey, translate, }) {
856
+ const pages = useAsyncOptions(node.fieldId, rowKey);
857
+ const copy = useHostCopy();
858
+ const held = Array.isArray(field.value) ? field.value : [];
859
+ const toggle = (value) => {
860
+ const selected = held.some((entry) => sameWireValue(entry, value));
861
+ const painted = new Set(pages.items.map((item) => canonicalizeRestricted(item.value)));
862
+ const next = [
863
+ // A page is a window onto the domain, not the whole record: values outside it were not
864
+ // toggled and keep their existing order ahead of the painted entries' declaration order.
865
+ ...held.filter((entry) => !painted.has(canonicalizeRestricted(entry))),
866
+ ...pages.items
867
+ .filter((item) => sameWireValue(item.value, value)
868
+ ? !selected
869
+ : held.some((entry) => sameWireValue(entry, item.value)))
870
+ .map((item) => item.value),
871
+ ];
872
+ write(next);
873
+ };
874
+ return (_jsxs(View, { style: styles.row, accessibilityRole: "group", ...controlA11yProps(a11y.props, a11y), children: [pages.items.map((item) => {
875
+ const selected = held.some((entry) => sameWireValue(entry, item.value));
876
+ const label = item.labelKey === ''
877
+ ? renderValueText(item.value, copy.display, node.declaration.items?.primitive)
878
+ : translate(item.labelKey);
879
+ const answer = availabilityOf(field, item.value, node.label, label, translate, copy, node.declaration);
880
+ return (_jsxs(Pressable, { accessibilityRole: "checkbox", accessibilityState: { checked: selected, disabled: !field.enabled }, "aria-checked": selected, "aria-disabled": !field.enabled, ...(answer === undefined ? {} : { accessibilityHint: answer }), disabled: !field.enabled, onPress: () => toggle(item.value), style: selected ? styles.selected : styles.option, children: [_jsx(Text, { style: styles.body, children: label }), answer === undefined ? null : _jsx(Text, { style: styles.description, children: answer })] }, canonicalizeRestricted(item.value)));
881
+ }), _jsx(OptionPagesStatus, { node: node, pages: pages, styles: styles, translate: translate })] }));
882
+ }
883
+ /**
884
+ * A list whose domain is another field's recorded array.
885
+ *
886
+ * The values are read through the same binding the source control writes, so a value the person
887
+ * typed in the source field is an option here immediately. The result is built in the source's
888
+ * order, which is what makes a `rank` an order the person can express without a separate
889
+ * reordering gesture: the domain is the ranking.
890
+ */
891
+ function SourceListEntry({ node, field, a11y, write, styles, sourceFieldId, }) {
892
+ const source = useField(sourceFieldId);
893
+ const copy = useHostCopy();
894
+ const items = Array.isArray(source.value) ? source.value : [];
895
+ const chosen = Array.isArray(field.value) ? field.value : [];
896
+ const isChosen = (value) => chosen.some((entry) => sameWireValue(entry, value));
897
+ const toggle = (value) => {
898
+ const selected = isChosen(value);
899
+ const next = items.filter((item) => (sameWireValue(item, value) ? !selected : isChosen(item)));
900
+ write(next);
901
+ };
902
+ return (_jsx(View, { style: styles.row, accessibilityRole: "group", ...controlA11yProps(a11y.props, a11y), children: items.map((value, index) => {
903
+ const selected = isChosen(value);
904
+ return (_jsx(Pressable, { accessibilityRole: "checkbox", accessibilityState: { checked: selected, disabled: !field.enabled }, "aria-checked": selected, "aria-disabled": !field.enabled, disabled: !field.enabled, onPress: () => toggle(value), style: selected ? styles.selected : styles.option, children: _jsx(Text, { style: styles.body, children: renderValueText(value, copy.display, node.declaration.items?.primitive) }) }, `${String(index)}:${canonicalizeRestricted(value)}`));
905
+ }) }));
906
+ }
907
+ /** One quantity's committed wire value, or `undefined` when the binding holds none. */
908
+ function quantityOf(value) {
909
+ if (!isRecord(value))
910
+ return undefined;
911
+ const text = value['value'];
912
+ const unit = value['unit'];
913
+ return typeof text === 'string' && typeof unit === 'string' ? { value: text, unit } : undefined;
914
+ }
915
+ /**
916
+ * A quantity's numeric entry, parsed and canonicalised before it reaches the session.
917
+ *
918
+ * A quantity is one value with two members, so the buffer owns the number and the field owns the
919
+ * unit. `AxiomDecimal` is the same constructor the evaluator uses; canonicalising through it
920
+ * means `01.50` and `1.5` are one stored value rather than two, and a magnitude beyond the
921
+ * declared scale is refused instead of rounded (`MODEL-2.1.21`).
922
+ */
923
+ function parseQuantityDraft(text, scale) {
924
+ const trimmed = text.trim();
925
+ // A sign, a point or nothing is the prefix of a number, not a refusal: a buffer that
926
+ // announced an error for the first keystroke of `-12` would be hostile.
927
+ if (trimmed === '' || trimmed === '-' || trimmed === '.' || trimmed === '-.') {
928
+ return { kind: 'partial' };
929
+ }
930
+ if (!/^-?\d+(?:\.\d+)?$/.test(trimmed)) {
931
+ return { kind: 'invalid', reason: 'buffer.decimal.digits' };
932
+ }
933
+ let canonical;
934
+ try {
935
+ canonical = canonicalDecimal(new AxiomDecimal(trimmed));
936
+ }
937
+ catch {
938
+ return { kind: 'invalid', reason: 'buffer.decimal.not_canonical' };
939
+ }
940
+ const dot = canonical.indexOf('.');
941
+ const fraction = dot < 0 ? 0 : canonical.length - dot - 1;
942
+ if (fraction > scale) {
943
+ return { kind: 'invalid', reason: 'buffer.money.scale_exceeded', params: { scale } };
944
+ }
945
+ return { kind: 'value', text: canonical };
946
+ }
947
+ /**
948
+ * A quantity: a numeric buffer and the declared unit selector beside it.
949
+ *
950
+ * The buffer keeps the keystrokes the field cannot store yet, so a partial entry such as `-` is
951
+ * visible without being written. A valid entry writes the quantity on the spot; the unit selector
952
+ * writes the same amount under the chosen unit, because v1 defines no conversion and the two
953
+ * members are one value.
954
+ */
955
+ function QuantityEntry({ node, field, a11y, write, styles, activeTheme, rowKey, }) {
956
+ const copy = useHostCopy();
957
+ const { setInputRef, focusNext } = useInputChain(node.fieldId, rowKey);
958
+ const scale = node.declaration.scale ?? 0;
959
+ const units = node.declaration.units ?? [];
960
+ const committed = quantityOf(field.value);
961
+ const [entry, setEntry] = useState(undefined);
962
+ const [chosenUnit, setChosenUnit] = useState(undefined);
963
+ const [failure, setFailure] = useState(undefined);
964
+ const text = entry ?? committed?.value ?? '';
965
+ const unit = chosenUnit ?? committed?.unit ?? units[0] ?? '';
966
+ const failureText = failure === undefined ? undefined : copy.buffer(failure.reason, failure.params);
967
+ const failureId = failure === undefined ? undefined : `${field.a11y.errorId}-quantity`;
968
+ const mergedHint = joinTokens(a11y.errorHint, failureText);
969
+ const mergedDescribedBy = joinTokens(a11y.describedBy, failureId);
970
+ const inputA11y = controlA11yProps(a11y.props, {
971
+ ...(mergedHint === undefined ? {} : { errorHint: mergedHint }),
972
+ ...(mergedDescribedBy === undefined ? {} : { describedBy: mergedDescribedBy }),
973
+ ...(a11y.invalid === true || failure !== undefined ? { invalid: true } : {}),
974
+ });
975
+ const apply = (nextText, nextUnit) => {
976
+ const parsed = parseQuantityDraft(nextText, scale);
977
+ if (parsed.kind === 'partial') {
978
+ setFailure(undefined);
979
+ return;
980
+ }
981
+ if (parsed.kind === 'invalid') {
982
+ setFailure(parsed);
983
+ return;
984
+ }
985
+ setFailure(undefined);
986
+ const value = { value: parsed.text, unit: nextUnit };
987
+ write(value);
988
+ };
989
+ const commitDraft = () => {
990
+ if (entry === undefined)
991
+ return;
992
+ const parsed = parseQuantityDraft(entry, scale);
993
+ if (parsed.kind === 'invalid') {
994
+ setFailure(parsed);
995
+ return;
996
+ }
997
+ setEntry(undefined);
998
+ setFailure(undefined);
999
+ };
1000
+ return (_jsxs(_Fragment, { children: [_jsxs(View, { style: styles.row, children: [_jsx(TextInput, { ...inputA11y, style: styles.input, placeholderTextColor: activeTheme.color.muted, editable: field.enabled, keyboardType: node.hints.native.keyboardType, ...(node.placeholder === undefined ? {} : { placeholder: node.placeholder }), value: text, onChangeText: (next) => {
1001
+ setEntry(next);
1002
+ apply(next, unit);
1003
+ }, onBlur: () => {
1004
+ commitDraft();
1005
+ field.onBlur();
1006
+ }, returnKeyType: "next", blurOnSubmit: false, onSubmitEditing: () => {
1007
+ commitDraft();
1008
+ focusNext();
1009
+ }, ref: setInputRef }), _jsx(View, { style: styles.row, accessibilityRole: "radiogroup", accessibilityLabel: a11y.props.accessibilityLabel, accessibilityState: { disabled: !field.enabled }, "aria-disabled": !field.enabled, children: units.map((candidate) => {
1010
+ const selected = candidate === unit;
1011
+ return (_jsx(Pressable, { accessibilityRole: "radio", accessibilityState: { checked: selected, disabled: !field.enabled }, "aria-checked": selected, "aria-disabled": !field.enabled, disabled: !field.enabled, onPress: () => {
1012
+ const parsed = entry === undefined ? undefined : parseQuantityDraft(entry, scale);
1013
+ const amount = parsed?.kind === 'value' ? parsed.text : committed?.value;
1014
+ setChosenUnit(candidate);
1015
+ if (amount !== undefined) {
1016
+ const value = { value: amount, unit: candidate };
1017
+ write(value);
1018
+ }
1019
+ }, style: selected ? styles.selected : styles.option, children: _jsx(Text, { style: styles.body, children: candidate }) }, candidate));
1020
+ }) })] }), failureText === undefined ? null : (_jsx(Text, { style: styles.danger, ...(failureId === undefined ? {} : { nativeID: failureId }), accessibilityRole: "alert", accessibilityLiveRegion: "polite", children: failureText }))] }));
1021
+ }
1022
+ /**
1023
+ * A duration: one whole amount in the unit the declaration names.
1024
+ *
1025
+ * The wire value is `{ amount, unit }` and the unit is the field's, so the entry writes both
1026
+ * members and never a bare number. A partial or unsafe entry writes nothing, which leaves the
1027
+ * committed value in place rather than storing an amount the declaration cannot hold.
1028
+ */
1029
+ function DurationEntry({ node, field, a11y, write, styles, activeTheme, rowKey, }) {
1030
+ const record = isRecord(field.value) ? field.value : undefined;
1031
+ const amount = record !== undefined && typeof record['amount'] === 'number' ? record['amount'] : undefined;
1032
+ const unit = node.declaration.unit ?? 'minutes';
1033
+ const { setInputRef, focusNext } = useInputChain(node.fieldId, rowKey);
1034
+ return (_jsxs(View, { style: styles.row, children: [_jsx(TextInput, { ...controlA11yProps(a11y.props, a11y), style: styles.input, placeholderTextColor: activeTheme.color.muted, editable: field.enabled, keyboardType: "number-pad", value: amount === undefined ? '' : String(amount), onChangeText: (text) => {
1035
+ const trimmed = text.trim();
1036
+ if (trimmed === '') {
1037
+ write(null);
1038
+ return;
1039
+ }
1040
+ const parsed = Number(trimmed);
1041
+ if (Number.isSafeInteger(parsed) && parsed >= 0)
1042
+ write({ amount: parsed, unit });
1043
+ }, onBlur: field.onBlur, returnKeyType: "next", blurOnSubmit: false, onSubmitEditing: () => focusNext(), ref: setInputRef }), _jsx(Text, { style: styles.currency, children: unit })] }));
1044
+ }
1045
+ const BLANK_ADDRESS = Object.freeze({
1046
+ line1: '',
1047
+ line2: '',
1048
+ city: '',
1049
+ region: '',
1050
+ postalCode: '',
1051
+ country: '',
1052
+ });
1053
+ /** Extracts all six declared address members from a wire record, reading non-strings as empty. */
1054
+ function addressDraftOf(value) {
1055
+ if (!isRecord(value))
1056
+ return BLANK_ADDRESS;
1057
+ const member = (key) => {
1058
+ const held = value[key];
1059
+ return typeof held === 'string' ? held : '';
1060
+ };
1061
+ return {
1062
+ line1: member('line1'),
1063
+ line2: member('line2'),
1064
+ city: member('city'),
1065
+ region: member('region'),
1066
+ postalCode: member('postalCode'),
1067
+ country: member('country'),
1068
+ };
1069
+ }
1070
+ /**
1071
+ * Builds the closed six-member `address` wire record, or `undefined` while incomplete.
1072
+ *
1073
+ * Empty optional members (`line2`, `region`) are omitted rather than written as empty strings,
1074
+ * matching `packages/web/src/address.tsx` and `MODEL-2.1.25`.
1075
+ */
1076
+ function addressRecordOf(draft) {
1077
+ const line1 = draft.line1.trim();
1078
+ const line2 = draft.line2.trim();
1079
+ const city = draft.city.trim();
1080
+ const region = draft.region.trim();
1081
+ const postalCode = draft.postalCode.trim();
1082
+ const country = draft.country.trim().toUpperCase();
1083
+ if (line1 === '' || city === '' || postalCode === '' || !COUNTRY_CODE_PATTERN.test(country)) {
1084
+ return undefined;
1085
+ }
1086
+ return {
1087
+ line1,
1088
+ city,
1089
+ postalCode,
1090
+ country,
1091
+ ...(line2 === '' ? {} : { line2 }),
1092
+ ...(region === '' ? {} : { region }),
1093
+ };
1094
+ }
1095
+ function createAddressDraftStore() {
1096
+ let held = undefined;
1097
+ const listeners = new Set();
1098
+ return {
1099
+ subscribe: (listener) => {
1100
+ listeners.add(listener);
1101
+ return () => {
1102
+ listeners.delete(listener);
1103
+ };
1104
+ },
1105
+ snapshot: () => held,
1106
+ set: (next) => {
1107
+ if (held === next)
1108
+ return;
1109
+ held = next;
1110
+ for (const listener of listeners)
1111
+ listener();
1112
+ },
1113
+ retireIfStale: (sessionWriter, value) => {
1114
+ if (held !== undefined &&
1115
+ (held.sessionWriter !== sessionWriter || !sameWireValue(held.baseValue, value))) {
1116
+ // The committed render already derived `draft = undefined` from the mismatch, so clearing
1117
+ // without notifying listeners retires the stale draft with zero extra render.
1118
+ held = undefined;
1119
+ }
1120
+ },
1121
+ };
1122
+ }
1123
+ const ADDRESS_MEMBER_SPECS = Object.freeze([
1124
+ { member: 'line1', labelKey: 'addressLine1', required: true, autoCapitalize: 'words' },
1125
+ { member: 'line2', labelKey: 'addressLine2', required: false, autoCapitalize: 'words' },
1126
+ { member: 'city', labelKey: 'addressCity', required: true, autoCapitalize: 'words' },
1127
+ { member: 'region', labelKey: 'addressRegion', required: false, autoCapitalize: 'words' },
1128
+ {
1129
+ member: 'postalCode',
1130
+ labelKey: 'addressPostalCode',
1131
+ required: true,
1132
+ autoCapitalize: 'characters',
1133
+ },
1134
+ {
1135
+ member: 'country',
1136
+ labelKey: 'addressCountry',
1137
+ required: true,
1138
+ autoCapitalize: 'characters',
1139
+ },
1140
+ ]);
1141
+ function AddressMemberInput({ fieldId, rowKey, member, memberIndex, label, accessibleLabel, value, editable, a11y, styles, activeTheme, autoCapitalize, onChange, onBlur, }) {
1142
+ const { setInputRef, focusNext } = useInputChain(`${fieldId}:${member}`, rowKey, memberIndex);
1143
+ return (_jsxs(View, { style: styles.stack, children: [_jsx(Text, { style: styles.label, children: label }), _jsx(TextInput, { ...controlA11yProps(a11y.props, a11y), style: styles.input, placeholderTextColor: activeTheme.color.muted, accessibilityLabel: accessibleLabel, testID: rowKey === undefined
1144
+ ? `address:${fieldId}:${member}`
1145
+ : `address:${fieldId}:${String(rowKey)}:${member}`, editable: editable, autoCapitalize: autoCapitalize, value: value, onChangeText: onChange, onBlur: onBlur, returnKeyType: "next", blurOnSubmit: false, onSubmitEditing: () => focusNext(), ref: setInputRef })] }));
1146
+ }
1147
+ /**
1148
+ * All six declared members of an `address` record (`line1`, `line2`, `city`, `region`,
1149
+ * `postalCode`, `country`), matching `packages/web/src/address.tsx`.
1150
+ *
1151
+ * Focus and blur without edits preserves existing optional members (`line2`, `region`) and
1152
+ * writes nothing; unchanged records are skipped via `sameWireValue`.
1153
+ */
1154
+ function AddressEntry({ node, field, a11y, write, styles, activeTheme, rowKey, }) {
1155
+ const copy = useHostCopy();
1156
+ const published = addressDraftOf(field.value);
1157
+ const [draftStore] = useState(createAddressDraftStore);
1158
+ const scoped = useSyncExternalStore(draftStore.subscribe, draftStore.snapshot, draftStore.snapshot);
1159
+ const draft = scoped !== undefined &&
1160
+ scoped.sessionWriter === field.setValue &&
1161
+ sameWireValue(scoped.baseValue, field.value)
1162
+ ? scoped.draft
1163
+ : undefined;
1164
+ useEffect(() => {
1165
+ draftStore.retireIfStale(field.setValue, field.value);
1166
+ }, [draftStore, field.setValue, field.value]);
1167
+ const shown = draft ?? published;
1168
+ const change = (member, text) => {
1169
+ const next = { ...shown, [member]: text };
1170
+ const record = addressRecordOf(next);
1171
+ if (record !== undefined) {
1172
+ if (!sameWireValue(record, field.value)) {
1173
+ draftStore.set({ baseValue: record, sessionWriter: field.setValue, draft: next });
1174
+ write(record);
1175
+ }
1176
+ else {
1177
+ draftStore.set({ baseValue: field.value, sessionWriter: field.setValue, draft: next });
1178
+ }
1179
+ return;
1180
+ }
1181
+ if (addressRecordOf(published) !== undefined) {
1182
+ draftStore.set({ baseValue: null, sessionWriter: field.setValue, draft: next });
1183
+ write(null);
1184
+ return;
1185
+ }
1186
+ draftStore.set({ baseValue: field.value, sessionWriter: field.setValue, draft: next });
1187
+ };
1188
+ const blur = () => {
1189
+ if (addressRecordOf(shown) !== undefined)
1190
+ draftStore.set(undefined);
1191
+ field.onBlur();
1192
+ };
1193
+ return (_jsx(View, { style: styles.stack, accessibilityRole: "group", accessibilityLabel: a11y.props.accessibilityLabel, children: ADDRESS_MEMBER_SPECS.map((spec, memberIndex) => {
1194
+ const memberLabel = copy[spec.labelKey]();
1195
+ return (_jsx(AddressMemberInput, { fieldId: node.fieldId, ...(rowKey === undefined ? {} : { rowKey }), member: spec.member, memberIndex: memberIndex, label: memberLabel, accessibleLabel: field.a11y.required && spec.required
1196
+ ? `${node.label}: ${memberLabel} (${copy.requiredMarker()})`
1197
+ : `${node.label}: ${memberLabel}`, value: shown[spec.member], editable: field.mayWrite, a11y: a11y, styles: styles, activeTheme: activeTheme, autoCapitalize: spec.autoCapitalize, onChange: (text) => change(spec.member, text), onBlur: blur }, spec.member));
1198
+ }) }));
1199
+ }
1200
+ function BufferedEntry({ node, field, a11y, guard, styles, activeTheme, rowKey, format, }) {
1201
+ const buffer = useBufferedInput(node.fieldId, format, rowKey);
1202
+ const copy = useHostCopy();
1203
+ const { setInputRef, focusNext } = useInputChain(node.fieldId, rowKey);
1204
+ const parseErrorText = buffer.parseError === undefined
1205
+ ? undefined
1206
+ : copy.buffer(buffer.parseError, buffer.parseErrorParams);
1207
+ const parseErrorId = buffer.parseError === undefined ? undefined : `${field.a11y.errorId}-buffer`;
1208
+ const mergedHint = joinTokens(a11y.errorHint, parseErrorText);
1209
+ const mergedDescribedBy = joinTokens(a11y.describedBy, parseErrorId);
1210
+ const inputA11y = controlA11yProps(a11y.props, {
1211
+ ...(mergedHint === undefined ? {} : { errorHint: mergedHint }),
1212
+ ...(mergedDescribedBy === undefined ? {} : { describedBy: mergedDescribedBy }),
1213
+ ...(a11y.invalid === true || buffer.parseError !== undefined ? { invalid: true } : {}),
1214
+ });
1215
+ // The Enter key writes the entry now, so a value cannot sit uncommitted behind a keyboard
1216
+ // with no Done affordance; the chain then moves focus, and the blur that follows records
1217
+ // the visit exactly as a tap-away would.
1218
+ const submit = () => {
1219
+ guard(buffer.commit);
1220
+ focusNext();
1221
+ };
1222
+ // The declaration names the currency, never the host: the adornment below prints that same
1223
+ // string beside the entry, and the wire write stays the buffer's own commit.
1224
+ const currency = format.kind === 'money' ? node.declaration.currency : undefined;
1225
+ const input = (_jsx(TextInput, { ...inputA11y, style: styles.input, placeholderTextColor: activeTheme.color.muted, editable: field.enabled, keyboardType: node.hints.native.keyboardType, ...(node.placeholder === undefined ? {} : { placeholder: node.placeholder }), value: buffer.text, onChangeText: (text) => guard(() => buffer.setText(text)), onBlur: () => {
1226
+ // The visit is recorded whether or not the entry was a value: the buffer owns the
1227
+ // write, and a refusal it reports must not keep the touched state from showing.
1228
+ guard(buffer.commit);
1229
+ field.onBlur();
1230
+ }, returnKeyType: "next", blurOnSubmit: false, onSubmitEditing: submit, ref: setInputRef }));
1231
+ return (_jsxs(_Fragment, { children: [currency === undefined ? (input) : (_jsxs(View, { style: styles.row, children: [input, _jsx(Text, { style: styles.currency, accessibilityElementsHidden: true, importantForAccessibility: "no-hide-descendants", "aria-hidden": true, children: currency })] })), parseErrorText === undefined ? null : (_jsx(Text, { style: styles.danger, ...(parseErrorId === undefined ? {} : { nativeID: parseErrorId }), accessibilityRole: "alert", accessibilityLiveRegion: "polite", children: parseErrorText }))] }));
1232
+ }
1233
+ /** The visible control failures from the session's reveal policy, verbatim. */
1234
+ function visibleErrorsOf(field) {
1235
+ return field.visibleErrors;
1236
+ }
1237
+ /** The failures a binding announced, in the artifact's order and the selected locale. */
1238
+ function Errors({ errorId, items, styles, }) {
1239
+ return (_jsx(View, { nativeID: errorId, accessibilityLiveRegion: "polite", children: items.map((item) => (_jsx(Text, { style: styles.danger, children: item.text }, item.key))) }));
1240
+ }
1241
+ /**
1242
+ * One failure's own identity inside its binding, for a React key.
1243
+ *
1244
+ * Derived per rule, gate item or binding fact, so it never names two different errors; a new
1245
+ * failure above an old one therefore moves the old text's node rather than reusing it, which is
1246
+ * what keeps the announced reason attached to the right control.
1247
+ */
1248
+ function errorKeyOf(error) {
1249
+ switch (error.kind) {
1250
+ case 'validate':
1251
+ case 'deferred':
1252
+ return `${error.kind}:${error.ruleId}:${error.messageKey}`;
1253
+ case 'required':
1254
+ return `required:${error.fieldId}@${String(error.rowKey ?? '')}`;
1255
+ case 'cardinality':
1256
+ return `cardinality:${error.bound}`;
1257
+ case 'invalid-value':
1258
+ return `invalid-value:${error.code}`;
1259
+ case 'access':
1260
+ return `access:${error.access}`;
1261
+ case 'gate':
1262
+ return `gate:${error.gateId}:${error.itemId}:${error.messageKey}`;
1263
+ case 'screen':
1264
+ return `screen:${error.screenId}:${error.outcome}`;
1265
+ case 'row-key':
1266
+ return `row-key:${error.code}:${String(error.rowKey)}`;
1267
+ }
1268
+ }
1269
+ /** The artifact states a message key for a rule or gate and none for the other four kinds. */
1270
+ function errorTextOf(error, label, translate, copy) {
1271
+ switch (error.kind) {
1272
+ case 'validate':
1273
+ case 'deferred':
1274
+ case 'gate':
1275
+ return translate(error.messageKey, error.params);
1276
+ case 'required':
1277
+ return copy.required(label, error.rowName);
1278
+ case 'cardinality':
1279
+ return copy.cardinality(label, error.bound, error.count, error.limit);
1280
+ case 'invalid-value':
1281
+ return copy.invalidValue(label);
1282
+ case 'access':
1283
+ return copy.notEditable(label, error.access);
1284
+ case 'screen':
1285
+ return copy.screenUnavailable(error.screenId);
1286
+ case 'row-key':
1287
+ return copy.rowKey(label, error.rowName);
1288
+ default:
1289
+ return assertNeverError(error);
1290
+ }
1291
+ }
1292
+ /** A union arm the compiler proves unreachable. */
1293
+ function assertNeverError(value) {
1294
+ throw new Error(`unreachable field error: ${JSON.stringify(value)}`);
1295
+ }
1296
+ function createFieldStyles(activeTheme) {
1297
+ return StyleSheet.create({
1298
+ control: { gap: activeTheme.space.tight, marginBottom: activeTheme.space.medium },
1299
+ label: {
1300
+ fontSize: activeTheme.text.label,
1301
+ fontWeight: activeTheme.weight.semibold,
1302
+ color: activeTheme.color.ink,
1303
+ },
1304
+ body: { fontSize: activeTheme.text.body, color: activeTheme.color.ink },
1305
+ description: {
1306
+ fontStyle: 'italic',
1307
+ color: activeTheme.color.muted,
1308
+ fontSize: activeTheme.text.caption,
1309
+ },
1310
+ danger: { color: activeTheme.color.danger, fontSize: activeTheme.text.caption },
1311
+ input: {
1312
+ minHeight: activeTheme.size.target,
1313
+ paddingHorizontal: activeTheme.space.small,
1314
+ paddingVertical: activeTheme.space.tight,
1315
+ borderWidth: 1,
1316
+ borderColor: activeTheme.color.border,
1317
+ borderRadius: activeTheme.radius.chip,
1318
+ backgroundColor: activeTheme.color.surface,
1319
+ color: activeTheme.color.ink,
1320
+ fontSize: activeTheme.text.body,
1321
+ },
1322
+ row: { flexDirection: 'row', flexWrap: 'wrap', gap: activeTheme.space.small },
1323
+ stack: { gap: activeTheme.space.tight },
1324
+ // Every chip shares one floor: a pressable smaller than the target size in both dimensions is
1325
+ // a mis-tap on a phone, and the unit chips below ride the same two styles.
1326
+ option: {
1327
+ paddingHorizontal: activeTheme.space.medium,
1328
+ paddingVertical: activeTheme.space.tight,
1329
+ minHeight: activeTheme.size.target,
1330
+ minWidth: activeTheme.size.target,
1331
+ justifyContent: 'center',
1332
+ borderWidth: 1,
1333
+ borderColor: activeTheme.color.border,
1334
+ borderRadius: activeTheme.radius.chip,
1335
+ backgroundColor: activeTheme.color.surface,
1336
+ },
1337
+ selected: {
1338
+ paddingHorizontal: activeTheme.space.medium,
1339
+ paddingVertical: activeTheme.space.tight,
1340
+ minHeight: activeTheme.size.target,
1341
+ minWidth: activeTheme.size.target,
1342
+ justifyContent: 'center',
1343
+ borderWidth: 2,
1344
+ borderColor: activeTheme.color.accent,
1345
+ borderRadius: activeTheme.radius.chip,
1346
+ backgroundColor: activeTheme.color.surface,
1347
+ },
1348
+ // The currency beside a money entry, aligned with the input it names the unit of.
1349
+ currency: {
1350
+ alignSelf: 'center',
1351
+ color: activeTheme.color.muted,
1352
+ fontSize: activeTheme.text.body,
1353
+ },
1354
+ });
1355
+ }
1356
+ const FIELD_STYLES = new WeakMap();
1357
+ function fieldStylesFor(activeTheme) {
1358
+ const cached = FIELD_STYLES.get(activeTheme);
1359
+ if (cached !== undefined)
1360
+ return cached;
1361
+ const created = createFieldStyles(activeTheme);
1362
+ FIELD_STYLES.set(activeTheme, created);
1363
+ return created;
1364
+ }
1365
+ //# sourceMappingURL=fields.js.map