@colixsystems/widget-sdk 0.210.0 → 0.213.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/README.md CHANGED
@@ -83,8 +83,104 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
83
83
 
84
84
  ## Status
85
85
 
86
- `v0.210.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
86
+ `v0.213.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
87
87
 
88
+ ### What's new in 0.213.0 (contract 1.172.0)
89
+
90
+ **New component `<ConfirmDialog>` — the standard "are you sure?".** Widgets asked for confirmation each in their own way (a button that re-labels itself to be pressed twice, a hand-laid Yes / No row), so a delete looked and behaved differently from one widget to the next. `<ConfirmDialog>` is that prompt, built once as a preset of `<Modal>` and `<Button>`:
91
+
92
+ ```jsx
93
+ import { useState } from "react";
94
+ import { ConfirmDialog, Button, useToast } from "@colixsystems/widget-sdk";
95
+
96
+ function DeleteOrder({ order, onDelete }) {
97
+ const [asking, setAsking] = useState(false);
98
+ const { showToast } = useToast();
99
+ return (
100
+ <>
101
+ <Button variant="danger" title="Delete" onPress={() => setAsking(true)} />
102
+ <ConfirmDialog
103
+ visible={asking}
104
+ tone="destructive"
105
+ title="Delete this order?"
106
+ message="This cannot be undone."
107
+ confirmLabel="Delete"
108
+ onCancel={() => setAsking(false)}
109
+ onConfirm={async () => {
110
+ try {
111
+ await onDelete(order.id);
112
+ } catch (err) {
113
+ showToast({ kind: "error", message: err.message });
114
+ }
115
+ setAsking(false);
116
+ }}
117
+ />
118
+ </>
119
+ );
120
+ }
121
+ ```
122
+
123
+ Props: `visible`, `title` (the question), `message` (what confirming does; text is drawn in the theme's body style, any other node as it is), `confirmLabel` and `cancelLabel`, `tone` (`default` | `destructive`), `busy`, `onConfirm`, `onCancel`, `closeAccessibilityLabel` and `testID` (the parts take `-message`, `-cancel`, `-confirm` and `-busy`, plus the Modal's own).
124
+
125
+ - **Cancelling is the safe default.** The Cancel button, the close button, a backdrop press, Escape on web and the Android back button all fire `onCancel`, never `onConfirm`.
126
+ - **`tone="destructive"`** draws the confirm button as the danger `<Button>`, so it takes its colours from the theme's `destructive` scope (Design > Components > Destructive), and on web opens with focus on Cancel. `default` draws the primary button and opens with focus on Confirm. Focus placement is web only.
127
+ - **Busy.** Return the action's promise from `onConfirm` and the dialog stays busy until it settles: both buttons are disabled, a `<Spinner>` shows, nothing dismisses the dialog, and a second press is ignored. Pass `busy` yourself when the action runs elsewhere; the two combine. A rejected promise is **not** caught: handle the failure inside `onConfirm`, otherwise it is reported as an unhandled rejection. Either way the dialog becomes usable again.
128
+ - **It never closes itself.** Set `visible` to false from `onCancel` and once the action is done.
129
+ - **Labels follow the app's language.** Unset, the buttons read the app's shared `confirm`, `cancel` and `close` translations (the same ones `useI18n().t("cancel")` resolves), falling back to English. Prefer a `confirmLabel` that names the action: "Delete", "Remove", "Send".
130
+
131
+ It adds no theme scope: the panel follows `modal`, the actions `button`, a destructive confirm `destructive`. `<Button>` now forwards a `ref` to its pressable, which is how the dialog places focus. Additive.
132
+
133
+ ### What's new in 0.212.0 (contract 1.171.0)
134
+
135
+ **Standard form controls: `Checkbox`, `Switch`, `Select` and `SearchField`.** Only text entry had a themed component, so every widget drew its own tick boxes, toggles, dropdowns and search boxes. Four controls now sit beside `TextField`, each one view bound to both hosts, and all five share one frame: `label` draws the control's label and names it for a screen reader (pressing a field's label focuses it), `helper` a hint below, `error` a message in the hint's place that also marks the control (`true` marks it without a message), and `disabled` stops input.
136
+
137
+ ```jsx
138
+ <SearchField value={query} onChangeText={setQuery} placeholder="Search orders" />
139
+ <Select
140
+ label="Status"
141
+ value={status}
142
+ onValueChange={setStatus}
143
+ options={[{ value: "open", label: "Open" }, { value: "done", label: "Done" }]}
144
+ />
145
+ <Checkbox label="Urgent only" value={urgent} onValueChange={setUrgent} />
146
+ <Switch label="Notify me" value={notify} onValueChange={setNotify} />
147
+ ```
148
+
149
+ **What existing widgets will look different.** `Switch` was already exported, as React Native's switch with the platform's default colours. It is now themed, so every existing `<Switch>` that passes no colours is repainted when this ships, in published and generated widgets alike:
150
+
151
+ | | Before | Now |
152
+ | --- | --- | --- |
153
+ | Web, off track | `#939393` | the theme's border colour |
154
+ | Web, on track | `#A3D3CF` | the theme's primary colour |
155
+ | Web, on thumb | teal `#009688` | white |
156
+ | Web, off thumb | `#FAFAFA` | unchanged |
157
+ | Web, disabled | the host's grey track and thumb | the themed colours at half opacity |
158
+ | iOS and Android, tracks | the platform's defaults | the theme's border (off) and primary (on) |
159
+ | iOS and Android, thumb | the platform's default | unchanged |
160
+ | iOS and Android, disabled | the platform's greyed switch | unchanged |
161
+
162
+ Three smaller changes reach switches that do pass something:
163
+
164
+ - **Web, `thumbColor` without `activeThumbColor`:** the "on" thumb was the host's teal and is now the `thumbColor` you passed.
165
+ - **Web, a partial `trackColor`** (`{ true: "#0a0" }`, a string, or `activeTrackColor` alone): the state you did not name was the host's default and is now the theme's.
166
+ - **iOS and Android, a truthy non-boolean `value`** (`value={1}`): it was off, because React Native's switch is on only for `true`, and is now on, as it already was on the web.
167
+
168
+ A switch that passes its own colours keeps them, disabled or not: a `trackColor` overrides the theme for the states it names (`{ true: "#0a0" }` still gets the themed off track), the web's `activeTrackColor` and string `trackColor` are still read, and iOS's off colour follows `trackColor.false` unless `ios_backgroundColor` is passed. A disabled switch that brings its own colours is drawn exactly as before on the web, at full strength; only one that left its colours to the theme is dimmed there. Layout does not change: a switch with no `label`, `helper` or `error` renders the bare control. Nothing else that existed before changes appearance; a `TextField` with none of the new props renders exactly what it did.
169
+
170
+ - **`Checkbox`**: `value` / `onValueChange(next)`. One 44px row with the checkbox role and checked state on both hosts; Space toggles it on the web. The box is the input surface and fills with the primary colour when checked. `style` is the row, `containerStyle` the box around a row that shows a helper or error; other props and the ref land on the row.
171
+ - **`Switch`**: the platform's own switch (React Native's `Switch`), so each host keeps its role, state and keys. A device greys a disabled switch itself; on the web a disabled switch is drawn at half strength unless it brings its own colours. With a `label`, `helper` or `error` it draws a row whose label toggles it too.
172
+ - **`Select`**: `options` (`[{ value, label, disabled?, testID? }]`), `value`, `onValueChange(value, option)`, `placeholder`, `title`, `emptyText`. The trigger is the input field, exposed as a button that opens a dialog (`aria-haspopup`, `aria-expanded`). Its options open through `Overlay`, at screen level, each with the option role and a selected state on both hosts (the list around them is a `listbox` on the web only; React Native has no such role), so a card or scroll container cannot clip them, and a long list scrolls inside the sheet. On the web Enter, Space or an arrow key opens it, the arrow keys, Home and End move between options, Enter or Space chooses, Escape closes, and focus returns to the trigger; on Android the back button closes it. Other props and the ref land on the trigger.
173
+ - **`SearchField`**: a `TextField` with a search glyph, the search key on the on-screen keyboard (`enterKeyHint="search"`, overridable) and a clear control that appears once there is text. Clearing calls `onChangeText("")`, then `onClear`, and keeps focus in the field. `style` styles the input and `containerStyle` the box around it.
174
+ - **`TextField`** gains `label`, `helper`, `error`, `disabled` and `containerStyle`. An invalid field keeps its danger border while focused.
175
+ - **`spaceActivates(onPress)`**: the `onKeyDown` handler the controls use to answer Space on the web, for a control you build yourself whose role is not a button. It fires once per key press and is ignored on native.
176
+
177
+ **Theming.** No new scope. All five read **Design > Components > Muted** for the field (background, text colour, border, corner radius, height) and show focus in the primary colour, as `TextField` always has: a field and a Select trigger in their own border, a checkbox and a labelled switch as a 2px ring around the control whose width is always reserved, so focusing moves nothing. A bare switch keeps the host's own focus indication. The Select's option sheet reads **Popover** (background, text colour, border). In the contract, `muted` and `popover` now list these components under `sdkComponents` next to the form widgets they already targeted. The `ring` scope is the Button widget's emphasis border and is not read by these controls.
178
+
179
+ **Known limits.** On a device a long option list does not scroll to the current choice when it opens (the web does, through focus). A helper or error is linked to its control with `aria-describedby` on the web, for all five controls; a device's screen reader reads it in place, and Android announces an error when it appears.
180
+
181
+ The built-in Data List, Files and User Management widgets and the form widgets' user and group pickers now draw their search boxes with `SearchField`.
182
+
183
+ - **`CONTRACT.version` → `1.171.0`** (`Checkbox`, `Select`, `SearchField`, `spaceActivates`; the `TextField` frame props; `sdkComponents` on `muted` and `popover`; and the visible change to `Switch` described above).
88
184
  ### What's new in 0.210.0 (contract 1.169.0)
89
185
 
90
186
  **New component `<Modal>` — the standard dialog.** Widgets that opened a dialog each built their own header, close button and action row inside a bare `<Overlay>`, so no two dialogs in an app matched and none could be restyled from the theme. `<Modal>` is that dialog, built once on `<Overlay>`:
@@ -2499,6 +2595,7 @@ import { defineWidget, validateManifest, useDatastoreQuery, Text, View } from "@
2499
2595
  - `WidgetTree({ node })` — component that renders an author-authored child node through the host's renderer; used by Tabs / Card / custom containers to host arbitrary child widgets.
2500
2596
  - `Text`, `View`, `Pressable`, `Image`, `ScrollView`, `TextInput`, `FlatList`, `SectionList`, `ActivityIndicator`, `Switch`, `StyleSheet`, `Linking`, `Icon`, `DateTimePicker` — re-exported from `react-native` (the RN primitives) or implemented in the SDK (`Icon` wraps `lucide-react-native`; `DateTimePicker` wraps `@react-native-community/datetimepicker` on native and renders `<input type="date|time|datetime-local">` directly on web because the RN library has no react-native-web mapping). The web build aliases `react-native` to `react-native-web` so the RN-re-exported primitives render in the browser without any per-platform code; the exported Expo app's Metro bundler resolves the real `react-native` library. `Linking` is a static API (`Linking.openURL(url)`) — use it for external URLs, and use `useNavigation().goTo(pageId)` for internal page navigation. See https://reactnative.dev/docs/ for per-component props.
2501
2597
  - `Overlay` — the screen-level overlay (sc-6607). `<Overlay visible={!!preview} onRequestClose={() => setPreview(null)} size="full">…</Overlay>` renders its children OUTSIDE the widget's layout box on both hosts (web portals it to the document root, native uses the OS modal), so no clipping card, `ScrollView` or neighbouring widget can cut off a document/media preview, lightbox or confirm dialog — which absolute positioning inside the widget cannot achieve on either platform. Children stay in your own React tree, so state and hooks work normally. `onRequestClose` carries the backdrop press, Escape on web, and the Android back button; `size` is `sm` | `md` (default) | `lg` | `full`; the scrim, surface, radius, padding and elevation come from the workspace theme. An anchored dropdown still belongs inside your own root.
2598
+ - `ConfirmDialog` — the standard confirmation prompt, a preset of `Modal` and `Button`. `<ConfirmDialog visible={asking} tone="destructive" title="Delete this order?" message="This cannot be undone." confirmLabel="Delete" onCancel={() => setAsking(false)} onConfirm={removeOrder} />` asks before a delete or any other action that cannot be undone. Cancel, the close button, the backdrop, Escape and the Android back button fire `onCancel`; a promise returned from `onConfirm` keeps it busy (buttons disabled, a second press ignored) until it settles. Props: `visible`, `title`, `message`, `confirmLabel`, `cancelLabel`, `tone` (`default` | `destructive`), `busy`, `onConfirm`, `onCancel`, `closeAccessibilityLabel`, `testID`. Use it instead of building a confirmation from `Modal` yourself.
2502
2599
  - `Modal` — the standard dialog, built on `Overlay`. `<Modal visible={open} onRequestClose={() => setOpen(false)} title="Edit order" footer={<Button title="Save" onPress={save} />}>…</Modal>` draws a title, a close button, a body that scrolls when it is long and a footer action row laid out below it. Its background, corner radius, padding, scrim, shadow and title colour come from the theme's `modal` scope (Design > Components > Dialogs), so every dialog in an app matches. Props: `visible`, `onRequestClose`, `dismissible`, `title`, `footer`, `presentation` (`dialog` | `sheet`), `size` (`sm` | `md` | `lg` | `full`), `dismissOnBackdropPress`, `role`, `initialFocusRef`, `closeAccessibilityLabel`, `accessibilityLabel`, `testID`. Use it for every dialog instead of hand-building a header and an action row inside `Overlay`.
2503
2600
  - `RichText` — the formatted-content renderer (sc-6970). `<RichText value={post.body} />` parses the markdown subset (`**bold**`, `*italic*` / `_italic_`, `` `code` ``, `#`/`##`/`###` headings, `-`/`*` bullets, `1.` ordered items, one-line `![alt](src "large")` images) and renders it with SDK primitives, so formatted content reads the same in the web Player and the exported Expo app. `value` is markdown, NOT HTML — widgets have no `dangerouslySetInnerHTML` on either host, so tags in a content string render as literal tag soup; stored text that still holds legacy HTML is stripped to plain text rather than shown as markup. Props: `value`, `renderImage` (`({ src, alt, size }) => node` — supply it when images are filestore ids, because resolving one needs the scopes your own widget holds; without it only absolute `http(s)` URLs render), `style`, `testID`. Colour, type scale and leading come from the workspace theme — never re-style them.
2504
2601
  - `MarkdownInput` — the authoring half of `<RichText>` (sc-6970). `<MarkdownInput value={draft} onChange={setDraft} />` is a multi-line field, a toolbar whose buttons wrap the current SELECTION in markdown markers (bold, italic, code, H2, H3, bullets, numbered list, each toggling back off), and a live `<RichText>` preview of the result underneath — the way to let an app USER write formatted text, instead of a bare `TextInput` plus hand-rolled buttons that can only splice literal tags into the value. Props: `value`, `onChange(next)`, `placeholder`, `previewLabel` (default `Preview`), `showPreview` (default true), `renderImage` (passed through to the preview), `minHeight` (150) and `maxHeight` (280) so a long draft scrolls inside its box, `accessibilityLabel`, `style`, `testID`.
@@ -2510,6 +2607,7 @@ import { defineWidget, validateManifest, useDatastoreQuery, Text, View } from "@
2510
2607
  - `Banner` — the themed inline message. `<Banner tone message>` shows an error, warning, success or notice in place, styled by the theme's `alert` scope; `action` adds one button and `onDismiss` a close control. Use `useToast()` for a brief confirmation instead. Never hand-roll a tinted error box.
2511
2608
  - `Accordion`, `AccordionItem` — themed collapsible sections. `<Accordion><AccordionItem title subtitle trailing>…</AccordionItem></Accordion>` draws its surface from the theme's `card` scope and its headers and dividers from the `list` scope; one section open at a time, or `multiple`. Never hand-roll a collapsible from `Pressable` + a chevron.
2512
2609
  - `Spinner`, `Skeleton` — the themed loading states. `<Spinner size label>` for a pending action; `<Skeleton shape="text" | "block" | "circle" | "listRow">` (or a group of bones) for content whose layout you know. The spinner wears `colors.loader`, the skeleton follows the theme's `loading` scope; both stop under reduced motion and mark one busy region. Never use `ActivityIndicator` or hand-build placeholder bars.
2610
+ - `Checkbox`, `Switch`, `Select`, `SearchField` — the themed tick box, on/off toggle, single-choice picker and search box. Like `TextField` they follow the theme's `muted` scope (and `popover` for the Select's option sheet) and take `label`, `helper`, `error` and `disabled`. `Select` opens its options at screen level. Never hand-roll one from `Pressable` and `View`.
2513
2611
  - `Tabs` — the themed tab strip. `<Tabs items value onChange>` draws a segmented control, pills or an underline as the theme's `tabs` scope says; render the selected panel yourself. Never hand-roll tabs from `Pressable` chips.
2514
2612
  - `textRoleStyle(role, typography, colors)`, `TEXT_ROLES` — the style of a semantic text tier, shared with the built-in widgets.
2515
2613
  - `WidgetContextProvider` — React context provider that the host (Studio, Player, exported app) wraps widgets with.
@@ -2541,7 +2639,7 @@ A widget that works but looks unfinished is only half done. `useTheme()` is the
2541
2639
  - **Spend one gradient.** `<Gradient colors={[theme.colors.primary, theme.colors.primaryStrong]} angle={160} style={…}>` is a `View` that paints a gradient behind its children, so it replaces the `View` you'd otherwise give a flat `backgroundColor`. `angle` is CSS degrees (0 = to top, 90 = to right, default 180); text on it uses `colors.onPrimary`. Exactly **one** per widget — on the focal element — and never behind body text. Both hosts render it identically (web paints CSS, native uses `expo-linear-gradient`), so there is no per-platform branching to write; don't import `expo-linear-gradient` yourself and don't write a `backgroundImage` string.
2542
2640
  - **Answer the touch.** Every tappable card, row and list entry lifts while the pointer is over it (web) or it is pressed (touch). One declaration does both: give the Pressable a style FUNCTION and spread `pressableLift` — `<Pressable onPress={open} style={(state) => [styles.card, ...pressableLift(state)]}>`. The lift is a -2px nudge plus one elevation step from `theme.interaction`, with the web transition built in. Never hand-write hover logic or your own pressed shadows, and never fake feedback with `opacity` — a dimmed surface reads as disabling itself.
2543
2641
  - **Size to your container — measure it, don't stretch into it.** The same widget sits in a full-width desktop section (~1400px), a half-width grid cell (~700px) and a phone (~360px), so layout built only from `flex: 1` stretches to fill whatever it is handed — a month calendar ends up with 200px day cells and swallows the page. Measure your own width with `const [width, onLayout] = useContainerWidth();`, spreading `onLayout` on an unpadded root `View` (a React Native callback, so it behaves identically on both hosts). A width of `0` means "not yet measured" and the SDK helpers answer it with the wide form, so do not special-case it — except a count or size computed from the width (a calendar day, a chart, a card grid's cards per line), which renders nothing size-dependent until the width arrives: a widget gets no declared breakpoint prop, but it can always measure. **Every form, list, table and filter bar lays out in three tiers** (sc-8508): `const [width, onLayout] = useContainerWidth();` then branch on `widthTier(width)` — a form is one column narrow, paired short fields at medium, a 2–3 column grid capped near 1000px wide; a list is stacked cards, one-line cards, then real columns under a header; a filter bar is one toolbar row (search, a dropdown per facet, sort) with the active filters as removable chips beneath, and a single "Filters" button opening a panel when narrow. **Cap a repeating cell** rather than giving a grid `flex: 1` — `const cell = Math.max(32, Math.min(Math.floor((usable - gap * (columns - 1)) / columns), 64));`, with a calendar day cell topping out at 56–72px on `aspectRatio: 1`, and the grid given its exact computed width plus `alignSelf: 'center'` when the cap leaves slack. **Split two co-equal surfaces in the wide tier** (`flexDirection: widthTier(width) === 'wide' ? 'row' : 'column'`, each half `{ flex: 1, minWidth: 0 }`) — a picker beside the form it feeds on a wide canvas, stacked in reading order below it. Never hardcode a width, never put `flex: 1` / `height: '100%'` on a content widget's root, and don't read the screen with `Dimensions` — the screen is not the widget. **Whatever you narrow, you centre** — a block that caps its own measure carries all three of `{ width: '100%', maxWidth: FORM_MAX, alignSelf: 'center' }`, because `alignSelf` alone stops the block stretching and sizes it to its content instead, and `maxWidth` alone leaves the widget flush left with dead space beside it; a capped wrap row lays its cells out along the MAIN axis, so it centres with `justifyContent: 'center'` on the row instead — but a card grid or a tile row is never capped. **A card grid fills its lines, it never wraps freely** — a free `flexWrap` strands the remainder (six cards that fit five render 5 + 1). Count the cards that fit the measured width (`const max = Math.max(1, Math.floor((width + gap) / (CARD_MIN + gap)));`), take `const lines = Math.ceil(count / max); const cols = Math.ceil(count / lines);`, and render each slice of `cols` cards as a row of `{ flex: 1, minWidth: 0 }` cells, padding the last line with empty `{ flex: 1 }` spacers so its cards keep the width of the cards above (six that fit five are 3 + 3, ten that fit four are 4 + 4 + 2). **A short value never breaks across lines** — a time, date, price, count, percentage or code takes `numberOfLines={1}` and `flexShrink: 0`, never a fixed width narrower than it, and a narrow slot re-arranges or steps the font down instead. **A metric / stat-tile row FILLS ITS ROW** — when you know the count, balance the lines (`const lines = Math.ceil(count / max); const base = Math.floor(count / lines); const extra = count % lines; const rows = Array.from({ length: lines }, (_, i) => tiles.slice(i * base + Math.min(i, extra), (i + 1) * base + Math.min(i + 1, extra)));`, with `max` 4 / 3 / 2 by tier, each tile `{ flex: 1, minWidth: 0 }`), and when the count comes from data wrap it (`{ flexDirection: 'row', flexWrap: 'wrap', gap: theme.spacing.md }`, each tile `{ flexGrow: 1, flexBasis: TILE_MIN }`, never a `maxWidth` — capped tiles cluster to one side), because a bare `flexDirection: 'row'` has no way to break and a React Native flex child defaults to `flexShrink: 0` (unlike CSS), so the tiles cannot give ground either: the row runs past its container, spilling out of the card natively and cut off by the scrolling page column on web, with nothing thrown and nothing logged, once there are enough of them (four fit where five do not). The basis is also the per-line ceiling — `Math.floor((usable + gap) / (TILE_MIN + gap))` tiles fit a line, so 240 tops out at five across a full-width ~1400px section and 320 at four; past four or five a line the tiles stop reading as cards.
2544
- - **Compose forms — pair fields into rows, don't stack one per row.** Lay the form out in three tiers and cap it near 1000px, centred with the three declarations above — never a 560–720px column alone in a wide box, which leaves a form that IS the page as a narrow strip in empty space. Put short, related fields side by side (first + last name, city + postal code, expiry + CVC): a row of `{ flexDirection: 'row', flexWrap: 'wrap', gap: theme.spacing.md }` with each field cell `{ flexGrow: 1, flexBasis: 160 }` splits the width on a wide card and wraps to stacked on a narrow phone — the right recipe for field pairs because it needs no measurement (a fixed-width column overflows a phone; when a layout needs a real column count instead of wrapping, measure your width as above). Keep wide fields (email, address, notes) full-width with `width: '100%'` — NEVER `flexBasis: '100%'`, which sizes the main axis and therefore claims the parent's whole HEIGHT in a column (sc-7274) — cap it at two–three per row, group a long form into labelled sections, and label every input above it (not placeholder-only). Give a `multiline` field BOTH a floor and a ceiling (`{ minHeight: 150, maxHeight: 260 }`) so a long value scrolls inside the box instead of growing past its card, and keep the Save / Cancel row in normal flow below the fields, never positioned over them. When a field carries an icon beside it (a search glyph, a clear button), the border belongs on the WRAPPER row and the `TextInput` inside it goes borderless and transparent with `flex: 1, minWidth: 0` (the `minWidth: 0` stops a long value pushing the border past its container) — React Native has no `:focus-within`, so drive the wrapper's `borderColor` between `colors.border` and `colors.primary` from the input's own `onFocus` / `onBlur`. A border left on the input rings only its own `<input>` box on web, leaving the icon outside the ring; never absolutely-position the icon over the field to work around it.
2642
+ - **Compose forms — pair fields into rows, don't stack one per row.** Lay the form out in three tiers and cap it near 1000px, centred with the three declarations above — never a 560–720px column alone in a wide box, which leaves a form that IS the page as a narrow strip in empty space. Put short, related fields side by side (first + last name, city + postal code, expiry + CVC): a row of `{ flexDirection: 'row', flexWrap: 'wrap', gap: theme.spacing.md }` with each field cell `{ flexGrow: 1, flexBasis: 160 }` splits the width on a wide card and wraps to stacked on a narrow phone — the right recipe for field pairs because it needs no measurement (a fixed-width column overflows a phone; when a layout needs a real column count instead of wrapping, measure your width as above). Keep wide fields (email, address, notes) full-width with `width: '100%'` — NEVER `flexBasis: '100%'`, which sizes the main axis and therefore claims the parent's whole HEIGHT in a column (sc-7274) — cap it at two–three per row, group a long form into labelled sections, and label every input above it (not placeholder-only). Give a `multiline` field BOTH a floor and a ceiling (`{ minHeight: 150, maxHeight: 260 }`) so a long value scrolls inside the box instead of growing past its card, and keep the Save / Cancel row in normal flow below the fields, never positioned over them. A search box is `<SearchField>`, which already carries its glyph and clear control. Put any other icon or unit beside the field as a sibling in a row (`flex: 1, minWidth: 0` on the field, so a long value shrinks instead of pushing the row past its container) rather than rebuilding the field to hold it: a hand-built bordered wrapper around a bare `TextInput` loses the app's input look and its label, focus and error handling.
2545
2643
  - **Respond to touch.** Give every `Pressable` the lift via the function-style `style={(state) => [base, ...pressableLift(state)]}` — see "Answer the touch" above. Never dim with `opacity`, which reads as the surface disabling itself.
2546
2644
  - **Drag and drop — show what is being dragged.** A drag where the item stays put reads as broken. Three things change the moment a drag starts: the **drag proxy** (the item lifts and follows the finger — `...theme.elevation.lg`, `{ scale: 1.03 }`, `opacity: 0.9`; for a tall or full-width item drag a compact `primarySoft` pill with its icon + one line of label instead), the **source placeholder** (the vacated slot keeps its height as a quiet `colors.surfaceMuted` block so the list doesn't collapse), and the **drop target** (one slot at a time highlighted with `primarySoft` or a 2px `colors.primary` border). Always animate the release — settle into the new slot, or `Animated.spring(pan, { toValue: { x: 0, y: 0 }, useNativeDriver: false })` back to the origin on cancel. Build it with `Animated` + `PanResponder` from `react-native` (the only mechanism that behaves identically on both hosts) — never HTML5 drag events (`draggable` / `onDragStart` / `dataTransfer` are web-only, and `document` / `window` are banned) — and start the drag from a `GripVertical` grip handle whenever the row is also tappable or sits in a `ScrollView`. **A board (kanban, pipeline) drops onto ANOTHER column**, which needs four more things: the board's root renders the one proxy (a column clips whatever leaves it); you hit-test the drop yourself — `measureInWindow` every column and the board when the drag starts and compare the gesture's window `moveX` (never `onLayout` frames, which are relative to a padded or scrolled parent) — highlighting exactly one target; the drop WRITES (`update(id, { [statusField]: value })` through `useDatastoreMutation`, optimistic until `refetch()`, a toast and a spring-back on failure); and three or more columns go in a `horizontal` `ScrollView` when `widthTier(width) === "narrow"`, with the grip claiming the gesture (`onStartShouldSetPanResponder`, `onPanResponderTerminationRequest: () => false`) and carrying `touchAction: 'none'` on web so a finger drag moves the card instead of scrolling the page. And because `useRef(PanResponder.create(...))` runs ONCE, everything its callbacks read — the `useCanWrite` flag included, which starts `false` — goes through a ref refreshed every render (`latest.current.canDrag`); the publish gate `widget.staleResponder` rejects a value read directly.
2547
2645
  - **Use icons for clarity.** Pair a `lucide-react-native` icon with its label at a consistent size, coloured from the theme. The label never repeats the icon as a character — with a `Plus` icon the button says "Add item", never "+ Add item" (that renders a doubled plus).
@@ -100,8 +100,9 @@ export function makeButton(rn) {
100
100
  * @param {boolean} [props.hostThemed] — `fields` already carry the theme
101
101
  * (a built-in the host folded); skip the second fold, which would add the
102
102
  * Button widget's own scopes to a form submit or a Link action.
103
+ * @param {object} ref — forwarded to the pressable, so a caller can focus it.
103
104
  */
104
- function Button({
105
+ const Button = React.forwardRef(function Button({
105
106
  title,
106
107
  variant = "primary",
107
108
  icon,
@@ -114,7 +115,7 @@ export function makeButton(rn) {
114
115
  hostThemed = false,
115
116
  accessibilityLabel,
116
117
  testID,
117
- }) {
118
+ }, ref) {
118
119
  const theme = useHostTheme() || DEFAULT_THEME_TOKENS;
119
120
  const { colors, spacing, radii, typography } = theme;
120
121
  const f = hostThemed
@@ -192,6 +193,7 @@ export function makeButton(rn) {
192
193
  return React.createElement(
193
194
  Pressable,
194
195
  {
196
+ ref,
195
197
  onPress,
196
198
  disabled,
197
199
  accessibilityRole: "button",
@@ -202,7 +204,7 @@ export function makeButton(rn) {
202
204
  },
203
205
  children,
204
206
  );
205
- }
207
+ });
206
208
 
207
209
  Button.displayName = "Button";
208
210
  return Button;
@@ -0,0 +1,150 @@
1
+ // The ONE implementation behind the `<Checkbox>` SDK primitive. The platform
2
+ // bindings (`checkbox.js` / `checkbox.native.js`) differ only in where the
3
+ // primitives come from, so the hosts cannot drift.
4
+ //
5
+ // Widgets each drew their own tick box, so one control looked different per
6
+ // widget. This one follows the theme's `muted` scope.
7
+
8
+ import React from "react";
9
+ import { useHostTheme } from "./hooks.js";
10
+ import { DEFAULT_THEME_TOKENS } from "./_theme-tokens.js";
11
+ import { Icon } from "./icon.js";
12
+ import {
13
+ CHECKBOX_MAX_RADIUS,
14
+ CHECKBOX_SIZE,
15
+ CONTROL_MIN_TARGET,
16
+ focusHaloStyle,
17
+ resolveFormControlTokens,
18
+ } from "./form-control-tokens.js";
19
+ import {
20
+ errorMessage,
21
+ hasNote,
22
+ isShown,
23
+ isText,
24
+ spaceActivates,
25
+ spokenLabel,
26
+ } from "./form-control-logic.js";
27
+ import { makeFieldFrame } from "./form-control-view.js";
28
+
29
+ const h = React.createElement;
30
+
31
+ /**
32
+ * Bind the shared checkbox to one platform's primitives.
33
+ *
34
+ * @param {{View: any, Text: any, Pressable: any}} rn
35
+ */
36
+ export function makeCheckbox(rn) {
37
+ const { View, Text, Pressable } = rn;
38
+ const FieldFrame = makeFieldFrame(rn);
39
+
40
+ const Checkbox = React.forwardRef(function Checkbox(props, ref) {
41
+ const {
42
+ value = false,
43
+ onValueChange,
44
+ label,
45
+ helper,
46
+ error,
47
+ disabled = false,
48
+ accessibilityLabel,
49
+ style,
50
+ containerStyle,
51
+ onFocus,
52
+ onBlur,
53
+ ...rest
54
+ } = props;
55
+ const theme = useHostTheme() || DEFAULT_THEME_TOKENS;
56
+ const t = resolveFormControlTokens(theme);
57
+ const [focused, setFocused] = React.useState(false);
58
+ const noteId = React.useId();
59
+ const checked = Boolean(value);
60
+ const invalid = isShown(error);
61
+ const noted = hasNote({ helper, error });
62
+ const radius = Math.min(t.radius, CHECKBOX_MAX_RADIUS);
63
+ const toggle = () => {
64
+ if (!disabled && typeof onValueChange === "function") onValueChange(!checked);
65
+ };
66
+
67
+ const row = h(
68
+ Pressable,
69
+ {
70
+ ...rest,
71
+ ref,
72
+ onPress: toggle,
73
+ onKeyDown: spaceActivates(toggle),
74
+ onFocus: (event) => {
75
+ setFocused(true);
76
+ if (typeof onFocus === "function") onFocus(event);
77
+ },
78
+ onBlur: (event) => {
79
+ setFocused(false);
80
+ if (typeof onBlur === "function") onBlur(event);
81
+ },
82
+ disabled,
83
+ // accessibilityRole + aria-*: the pair that announces on both hosts.
84
+ accessibilityRole: "checkbox",
85
+ "aria-checked": checked,
86
+ "aria-disabled": disabled,
87
+ ...(invalid ? { "aria-invalid": true } : null),
88
+ ...(noted ? { "aria-describedby": noteId } : null),
89
+ accessibilityLabel: spokenLabel(accessibilityLabel, label),
90
+ style: [
91
+ {
92
+ flexDirection: "row",
93
+ alignItems: "center",
94
+ gap: t.rowGap,
95
+ minHeight: CONTROL_MIN_TARGET,
96
+ minWidth: CONTROL_MIN_TARGET,
97
+ },
98
+ // The frame dims a noted checkbox as a whole.
99
+ disabled && !noted ? { opacity: t.disabledOpacity } : null,
100
+ style,
101
+ ],
102
+ },
103
+ h(
104
+ View,
105
+ { style: focusHaloStyle(t, focused, radius) },
106
+ h(
107
+ View,
108
+ {
109
+ style: {
110
+ width: CHECKBOX_SIZE,
111
+ height: CHECKBOX_SIZE,
112
+ alignItems: "center",
113
+ justifyContent: "center",
114
+ borderWidth: 1,
115
+ borderRadius: radius,
116
+ borderColor: checked ? t.accent : invalid ? t.errorColor : t.borderColor,
117
+ backgroundColor: checked ? t.accent : t.background,
118
+ },
119
+ },
120
+ checked ? h(Icon, { name: "check", size: 16, color: t.onAccent }) : null,
121
+ ),
122
+ ),
123
+ isText(label)
124
+ ? h(
125
+ Text,
126
+ {
127
+ style: {
128
+ flexShrink: 1,
129
+ color: t.labelColor,
130
+ fontFamily: t.fontFamily,
131
+ fontSize: t.fontSize,
132
+ },
133
+ },
134
+ label,
135
+ )
136
+ : isShown(label)
137
+ ? label
138
+ : null,
139
+ );
140
+ if (!noted) return row;
141
+ return h(
142
+ FieldFrame,
143
+ { t, helper, error: errorMessage(error), disabled, noteId, style: containerStyle },
144
+ row,
145
+ );
146
+ });
147
+
148
+ Checkbox.displayName = "Checkbox";
149
+ return Checkbox;
150
+ }
@@ -0,0 +1,11 @@
1
+ // `<Checkbox>` (web). Binds ./checkbox-view.js to react-native-web; see
2
+ // ./primitives.js for why not the bare specifier.
3
+
4
+ import * as ReactNative from "react-native-web";
5
+ import { makeCheckbox } from "./checkbox-view.js";
6
+
7
+ export const Checkbox = makeCheckbox({
8
+ View: ReactNative.View,
9
+ Text: ReactNative.Text,
10
+ Pressable: ReactNative.Pressable,
11
+ });
@@ -0,0 +1,7 @@
1
+ // `<Checkbox>` (native). Binds ./checkbox-view.js to React Native's own
2
+ // primitives; only the import differs from ./checkbox.js.
3
+
4
+ import { View, Text, Pressable } from "react-native";
5
+ import { makeCheckbox } from "./checkbox-view.js";
6
+
7
+ export const Checkbox = makeCheckbox({ View, Text, Pressable });
@@ -0,0 +1,158 @@
1
+ // The ONE implementation behind the `<ConfirmDialog>` SDK component: a preset
2
+ // of `<Modal>` holding a message, a Cancel and a Confirm `<Button>`.
3
+ //
4
+ // Bound per host by confirm-dialog.js / confirm-dialog.native.js, which differ
5
+ // only in where the primitives come from, so the two hosts cannot drift.
6
+
7
+ import React from "react";
8
+ import { useHostSharedText, useHostTheme } from "./hooks.js";
9
+ import { DEFAULT_THEME_TOKENS } from "./_theme-tokens.js";
10
+ import { textRoleStyle } from "./text-roles.js";
11
+
12
+ function isThenable(value) {
13
+ return value != null && typeof value.then === "function";
14
+ }
15
+
16
+ function isText(value) {
17
+ return typeof value === "string" || typeof value === "number";
18
+ }
19
+
20
+ /**
21
+ * Bind the shared confirmation to one platform's primitives and to that
22
+ * host's `<Modal>`, `<Button>` and `<Spinner>`.
23
+ *
24
+ * @param {{Text: any}} rn
25
+ * @param {any} Modal — the host's bound `<Modal>`.
26
+ * @param {any} Button — the host's bound `<Button>`.
27
+ * @param {any} Spinner — the host's bound `<Spinner>`.
28
+ */
29
+ export function makeConfirmDialog(rn, Modal, Button, Spinner) {
30
+ const { Text } = rn;
31
+
32
+ // Rendered inside the Modal, so it reads the theme the Modal re-inks.
33
+ function Message({ testID, children }) {
34
+ const theme = useHostTheme() || DEFAULT_THEME_TOKENS;
35
+ return React.createElement(
36
+ Text,
37
+ { testID, style: textRoleStyle("body", theme.typography, theme.colors) },
38
+ children,
39
+ );
40
+ }
41
+
42
+ /**
43
+ * The standard "are you sure?" prompt. Cancelling is the safe default: the
44
+ * close button, the backdrop, Escape (web) and the Android back button all
45
+ * fire `onCancel`, never `onConfirm`.
46
+ *
47
+ * @param {object} props
48
+ * @param {boolean} [props.visible] — nothing is mounted while false.
49
+ * @param {string} props.title — the question, e.g. "Delete this order?".
50
+ * @param {any} [props.message] — what confirming does; text is drawn in the
51
+ * theme's body style, any other node is rendered as it is.
52
+ * @param {string} [props.confirmLabel] — default the app's "Confirm".
53
+ * @param {string} [props.cancelLabel] — default the app's "Cancel".
54
+ * @param {"default"|"destructive"} [props.tone] — `destructive` draws the
55
+ * confirm button from the theme's Destructive colours and, on web, opens
56
+ * with focus on Cancel; `default` opens with focus on Confirm.
57
+ * @param {boolean} [props.busy] — the confirmed action is running: both
58
+ * buttons are disabled, a loading indicator shows, nothing closes it.
59
+ * @param {() => void|Promise<any>} [props.onConfirm] — a returned promise
60
+ * keeps the dialog busy until it settles. A rejection is not caught.
61
+ * @param {() => void} [props.onCancel]
62
+ * @param {string} [props.closeAccessibilityLabel] — default the app's "Close".
63
+ * @param {string} [props.testID] — on the panel; the parts take `-message`,
64
+ * `-cancel`, `-confirm` and `-busy`, plus the Modal's own.
65
+ */
66
+ function ConfirmDialog({
67
+ visible = false,
68
+ title,
69
+ message,
70
+ confirmLabel,
71
+ cancelLabel,
72
+ tone = "default",
73
+ busy = false,
74
+ onConfirm,
75
+ onCancel,
76
+ closeAccessibilityLabel,
77
+ testID,
78
+ }) {
79
+ const sharedConfirm = useHostSharedText("confirm", "Confirm");
80
+ const sharedCancel = useHostSharedText("cancel", "Cancel");
81
+ const sharedClose = useHostSharedText("close", "Close");
82
+ const [pending, setPending] = React.useState(false);
83
+ // Set before the re-render, so a second press in the same frame is ignored.
84
+ const inFlight = React.useRef(false);
85
+ const cancelRef = React.useRef(null);
86
+ const confirmRef = React.useRef(null);
87
+
88
+ const working = busy || pending;
89
+ const destructive = tone === "destructive";
90
+ const part = (name) => (testID ? `${testID}-${name}` : undefined);
91
+
92
+ const confirm = () => {
93
+ if (working || inFlight.current || typeof onConfirm !== "function") return;
94
+ const result = onConfirm();
95
+ if (!isThenable(result)) return;
96
+ inFlight.current = true;
97
+ setPending(true);
98
+ const settle = () => {
99
+ inFlight.current = false;
100
+ setPending(false);
101
+ };
102
+ result.then(settle, (error) => {
103
+ settle();
104
+ // Rethrown so a failure the caller did not handle is still reported.
105
+ throw error;
106
+ });
107
+ };
108
+
109
+ const cancel = () => {
110
+ if (working || inFlight.current) return;
111
+ if (typeof onCancel === "function") onCancel();
112
+ };
113
+
114
+ const footer = React.createElement(
115
+ React.Fragment,
116
+ null,
117
+ working ? React.createElement(Spinner, { testID: part("busy") }) : null,
118
+ React.createElement(Button, {
119
+ ref: cancelRef,
120
+ variant: "secondary",
121
+ title: cancelLabel ?? sharedCancel,
122
+ onPress: cancel,
123
+ disabled: working,
124
+ testID: part("cancel"),
125
+ }),
126
+ React.createElement(Button, {
127
+ ref: confirmRef,
128
+ variant: destructive ? "danger" : "primary",
129
+ title: confirmLabel ?? sharedConfirm,
130
+ onPress: confirm,
131
+ disabled: working,
132
+ testID: part("confirm"),
133
+ }),
134
+ );
135
+
136
+ return React.createElement(
137
+ Modal,
138
+ {
139
+ visible,
140
+ title,
141
+ footer,
142
+ role: "alertdialog",
143
+ size: "sm",
144
+ dismissible: !working,
145
+ onRequestClose: cancel,
146
+ initialFocusRef: destructive ? cancelRef : confirmRef,
147
+ closeAccessibilityLabel: closeAccessibilityLabel ?? sharedClose,
148
+ testID,
149
+ },
150
+ isText(message)
151
+ ? React.createElement(Message, { testID: part("message") }, message)
152
+ : message,
153
+ );
154
+ }
155
+
156
+ ConfirmDialog.displayName = "ConfirmDialog";
157
+ return ConfirmDialog;
158
+ }
@@ -0,0 +1,11 @@
1
+ // `<ConfirmDialog>` (web). Binds ./confirm-dialog-view.js to react-native-web
2
+ // and the web `<Modal>`, `<Button>` and `<Spinner>`; see ./primitives.js for
3
+ // why not the bare specifier.
4
+
5
+ import { Text } from "react-native-web";
6
+ import { makeConfirmDialog } from "./confirm-dialog-view.js";
7
+ import { Modal } from "./modal.js";
8
+ import { Button } from "./button.js";
9
+ import { Spinner } from "./loading.js";
10
+
11
+ export const ConfirmDialog = makeConfirmDialog({ Text }, Modal, Button, Spinner);
@@ -0,0 +1,11 @@
1
+ // `<ConfirmDialog>` (native). Binds ./confirm-dialog-view.js to React Native's
2
+ // own primitives and the native `<Modal>`, `<Button>` and `<Spinner>`; only the
3
+ // imports differ from ./confirm-dialog.js.
4
+
5
+ import { Text } from "react-native";
6
+ import { makeConfirmDialog } from "./confirm-dialog-view.js";
7
+ import { Modal } from "./modal.native.js";
8
+ import { Button } from "./button.native.js";
9
+ import { Spinner } from "./loading.native.js";
10
+
11
+ export const ConfirmDialog = makeConfirmDialog({ Text }, Modal, Button, Spinner);