This is the full developer documentation for Voltra
# Plugin Configuration (Android)
> Reference for the Android Voltra Expo plugin options, including enableNotifications and widgets, plus widget pre-rendering.
The Voltra Expo config plugin accepts Android-specific configuration options in your `app.json` or `app.config.js`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"enableNotifications": true,
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"description": "Shows current weather conditions",
"targetCellWidth": 2,
"targetCellHeight": 2,
"initialStatePath": "./widgets/weather-initial.tsx",
"previewImage": "./assets/widgets/weather-preview.png"
}
]
}
]
]
}
}
```
## Android-Specific Configuration
[Section titled “Android-Specific Configuration”](#android-specific-configuration)
### `enableNotifications` (optional)
[Section titled “enableNotifications (optional)”](#enablenotifications-optional)
Enables Android notification-related manifest plumbing used by Voltra features such as ongoing notifications.
When enabled, the config plugin adds:
* `android.permission.POST_NOTIFICATIONS`
* `android.permission.POST_PROMOTED_NOTIFICATIONS`
* `voltra.VoltraOngoingNotificationDismissedReceiver`
This does not grant runtime notification permission automatically. Your app still needs to request notification permission on Android 13 and above.
For setup and usage examples, see [Managing Android Ongoing Notifications](/android/development/managing-ongoing-notifications).
### `widgets` (optional)
[Section titled “widgets (optional)”](#widgets-optional)
Array of widget configurations for Home Screen widgets. Each widget will be available in the Android widget picker.
**Widget Configuration Properties:**
* `id`: Unique identifier for the widget (alphanumeric with underscores only)
* `displayName`: Name shown in the widget picker (plain string, or per-locale map; same rules as iOS `widgets[].displayName`)
* `description`: Description shown in the widget picker (same rules as `displayName`)
* `targetCellWidth`: Target widget width in grid cells (1-5, required)
* `targetCellHeight`: Target widget height in grid cells (1-5, required)
* `minWidth`: (optional) Minimum width in dp, used on Android 11 and older (defaults to a value derived from `minCellWidth` or `targetCellWidth`)
* `minHeight`: (optional) Minimum height in dp, used on Android 11 and older (defaults to a value derived from `minCellHeight` or `targetCellHeight`)
* `minCellWidth`: **Deprecated.** (optional) Minimum width in grid cells, converted to dp; prefer `minWidth`
* `minCellHeight`: **Deprecated.** (optional) Minimum height in grid cells, converted to dp; prefer `minHeight`
* `minResizeWidth`: (optional) Smallest width the user can resize the widget to, in dp (supported on all Android versions)
* `minResizeHeight`: (optional) Smallest height the user can resize the widget to, in dp (supported on all Android versions)
* `maxResizeWidth`: (optional) Largest width the user can resize the widget to, in dp (Android 12+; ignored on older versions)
* `maxResizeHeight`: (optional) Largest height the user can resize the widget to, in dp (Android 12+; ignored on older versions)
* `resizeMode`: (optional) Widget resize behavior (`"none"` | `"horizontal"` | `"vertical"` | `"horizontal|vertical"`, default: `"horizontal|vertical"`)
* `widgetCategory`: (optional) Widget category (`"home_screen"` | `"keyguard"` | `"home_screen|keyguard"`, default: `"home_screen"`)
* `initialStatePath`: (optional) Path to a file that exports initial widget state, or a locale map of paths for localized build-time pre-rendering (see [Widget Pre-rendering](/android/development/widget-pre-rendering))
* `previewImage`: (optional) Path to preview image for widget picker (PNG/JPG/WebP)
* `previewLayout`: (optional) Path to custom XML layout for widget picker preview (Android 12+)
* `serverUpdate`: (optional) Fetch the widget’s content on a schedule. Without `entry` the server returns a rendered payload; with `entry` it returns plain JSON that the widget renders on the device. `url` is optional — leave it out to supply one at runtime. See [Server-driven widgets](/android/development/server-driven-widgets) for full details.
* `url`: The Voltra SSR endpoint URL
* `intervalMinutes`: Update interval in minutes (default: `60`, or `15` for a widget with `entry`; minimum 15)
* `refresh`: Show a native refresh button (default: `false`)
* `appIntent`: (optional, Dynamic Widgets) Configuration parameters the widget reads from `env.configuration`. Each has a `name`, an optional `default` used until `setWidgetConfiguration` changes it, an optional `title` and optional `options` (`[{ "value": "metric", "title": "Metric" }]`), each with a required `title`. Titles accept plain strings or locale maps. See [Localization](/android/development/localization#translate-the-picker-and-configuration-copy)
### Localizing `displayName` and `description`
[Section titled “Localizing displayName and description”](#localizing-displayname-and-description)
Use a locale map when the widget picker label should be translated:
```json
{
"widgets": [
{
"id": "weather",
"displayName": {
"en": "Weather",
"pl": "Pogoda",
"zh-Hans": "天气"
},
"description": {
"en": "Current weather conditions",
"pl": "Aktualne warunki pogodowe",
"zh-Hans": "当前天气状况"
},
"targetCellWidth": 2,
"targetCellHeight": 2
}
]
}
```
Use BCP-47-style locale tags such as `en`, `en-US`, `pt-BR`, or `zh-Hans`.
Fallback behavior:
* Voltra first tries the device locale.
* If there is no exact match, it falls back to the language-only match.
* If there is still no match, it prefers an English locale such as `en` or `en-US`.
* If no English entry exists, it uses the first configured locale.
For widget sizing math and widget-picker preview setup (`previewImage`, `previewLayout`), see [Widget Sizing & Previews](/android/api/widget-sizing-and-previews).
## Widget Pre-rendering
[Section titled “Widget Pre-rendering”](#widget-pre-rendering)
Use `initialStatePath` to bundle pre-rendered widget state for the first time a widget is added to the home screen. See [Widget Pre-rendering](/android/development/widget-pre-rendering) for details.
## Example Configuration
[Section titled “Example Configuration”](#example-configuration)
```json
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"enableNotifications": true,
"widgets": [
{
"id": "voltra",
"displayName": "Voltra Widget",
"description": "Voltra logo widget",
"minCellWidth": 2,
"minCellHeight": 2,
"targetCellWidth": 2,
"targetCellHeight": 2,
"resizeMode": "horizontal|vertical",
"widgetCategory": "home_screen",
"initialStatePath": "./widgets/android-voltra-widget-initial.tsx",
"previewImage": "./assets/voltra-icon.jpg"
},
{
"id": "interactive_todos",
"displayName": "Interactive Todos",
"description": "Quick todo list widget",
"targetCellWidth": 2,
"targetCellHeight": 2,
"previewLayout": "./assets/widgets/todos-preview.xml"
}
]
}
]
]
}
}
```
# Widget Sizing & Previews (Android)
> How Android sizes widgets in grid cells and dp, and how to set the previews shown in the widget picker.
## Widget Sizing
[Section titled “Widget Sizing”](#widget-sizing)
### Grid Cells vs Density-Independent Pixels (dp)
[Section titled “Grid Cells vs Density-Independent Pixels (dp)”](#grid-cells-vs-density-independent-pixels-dp)
Android widgets are sized two different ways depending on the OS version. Android 12+ places widgets using `targetCellWidth`/`targetCellHeight`, in grid cells. Android 11 and older don’t understand those attributes at all and place widgets using `minWidth`/`minHeight`, in dp, so Voltra always emits both.
When `minWidth`/`minHeight` aren’t set explicitly, they’re derived from the widget’s cell size using Google’s published figures for a 5x4 handset grid:
* **minWidth (dp) = (cellCount × 73) - 16**
* **minHeight (dp) = (cellCount × 66) - 15**
For example, 2 cells comes out to 130 dp wide and 117 dp tall, and 4 cells to 276 dp wide and 249 dp tall.
Cell size varies by device, launcher and orientation, so this conversion is only an approximation, and it only matters on Android 11 and older — Android 12+ sizes the widget from `targetCellWidth`/ `targetCellHeight` directly. If you need precise placement on Android 11 and older, set `minWidth` and `minHeight` explicitly in dp instead of relying on the conversion.
### Standard Dimensions
[Section titled “Standard Dimensions”](#standard-dimensions)
| Family | Cells | Default DP | Typical Use |
| ----------- | ----- | ---------- | ----------------- |
| Small | 2×1 | 130 × 51 | Quick glance info |
| Medium | 2×2 | 130 × 117 | Main widget size |
| Large | 4×2 | 276 × 117 | Rich content |
| Extra Large | 4×4 | 276 × 249 | Complex layouts |
### Resize Bounds
[Section titled “Resize Bounds”](#resize-bounds)
Voltra can also emit `minResizeWidth`, `minResizeHeight`, `maxResizeWidth`, and `maxResizeHeight` in the generated `appwidget-provider` XML, all optional and all in dp:
* `minResizeWidth`/`minResizeHeight` set the smallest size the user can resize the widget to, and are supported on all Android versions.
* `maxResizeWidth`/`maxResizeHeight` set the largest size the user can resize the widget to. They were introduced in Android 12 and are ignored on older versions.
These bounds only take effect on axes the widget can resize along, per `resizeMode` — a `maxResizeHeight` on a widget with `resizeMode: "horizontal"` has no effect, for instance. Set only the ones you need; Voltra emits exactly what you provide and nothing otherwise, so existing widgets are unaffected.
Android also ignores a bound that contradicts the widget’s minimum size: `minResizeWidth` has no effect if it’s greater than `minWidth`, and `maxResizeWidth` has no effect if it’s smaller than `minWidth` — likewise for the height pair against `minHeight`. Since `minWidth`/`minHeight` are often derived from `targetCellWidth`/`targetCellHeight` rather than written explicitly (see above), Voltra warns at build time when it detects one of these contradictions, naming the attribute, rather than failing the build.
For example:
```json
{
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"targetCellWidth": 2,
"targetCellHeight": 2,
"resizeMode": "horizontal|vertical",
"minResizeWidth": 110,
"minResizeHeight": 100,
"maxResizeWidth": 276,
"maxResizeHeight": 249
}
]
}
```
This lets the widget resize down to 110×100 dp, and up to 276×249 dp on Android 12+.
## Widget Picker Previews
[Section titled “Widget Picker Previews”](#widget-picker-previews)
When users add a widget to their home screen, Android displays a preview in the widget picker. Voltra supports three preview methods, with automatic fallback:
1. **`previewLayout`** (Android 12+) - Custom XML layout for scalable preview
2. **`previewImage`** (All versions) - Static image or auto-generated layout
3. **Default** - System placeholder layout
### Using `previewImage`
[Section titled “Using previewImage”](#using-previewimage)
Static preview image for all Android versions:
```json
{
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"targetCellWidth": 2,
"targetCellHeight": 2,
"previewImage": "./assets/widgets/weather-preview.png"
}
]
}
```
When only `previewImage` is specified, Voltra automatically generates a layout that displays the image with proper scaling.
### Using `previewLayout`
[Section titled “Using previewLayout”](#using-previewlayout)
Custom XML layout for scalable previews (Android 12+):
```json
{
"widgets": [
{
"id": "todos",
"displayName": "Todo Widget",
"targetCellWidth": 2,
"targetCellHeight": 2,
"previewLayout": "./assets/widgets/todos-preview.xml"
}
]
}
```
**Example `todos-preview.xml`:**
```xml
```
The preview layout is rendered at the widget’s target size and displayed in the widget picker.
### Combined Preview Setup
[Section titled “Combined Preview Setup”](#combined-preview-setup)
For best results across Android versions, provide both:
```json
{
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"targetCellWidth": 2,
"targetCellHeight": 2,
"previewImage": "./assets/widgets/weather-preview.png",
"previewLayout": "./assets/widgets/weather-preview.xml",
"initialStatePath": "./widgets/weather-initial.tsx"
}
]
}
```
This uses `previewLayout` on Android 12+, falls back to `previewImage` on Android 11 and earlier, and shows actual widget content on the home screen via `initialStatePath` once available.
# Charts (Android)
> Build bar, line, area, point, rule, and sector charts in Android widgets with VoltraAndroid.Chart and its mark components.
Use charts in Android widgets to show trends, comparisons, progress, or composition at a glance. You can mix bars, lines, areas, points, rules, and sectors in a single chart.
Caution
Mark components (`BarMark`, `LineMark`, and the other mark types) must be direct children of ``. Do not wrap them in a custom component.
## Basic Usage
[Section titled “Basic Usage”](#basic-usage)
Wrap one or more mark components inside ``:
```tsx
```
## Data Types
[Section titled “Data Types”](#data-types)
All marks except `RuleMark` take a `data` prop. There are two data shapes depending on the mark type:
```typescript
// BarMark, LineMark, AreaMark, PointMark
type ChartDataPoint = {
x: string | number // Categorical ("Jan") or numeric (42)
y: number
series?: string // Optional — groups data for multi-series charts
}
// SectorMark
type SectorDataPoint = {
value: number // Proportional angular value
category: string // Sector label
}
```
## Marks
[Section titled “Marks”](#marks)
Pick the mark that fits your data: bars for comparing values across categories, lines for trends over time, areas for volume, points for sparse or scattered measurements, rules for reference lines, and sectors for pie/donut breakdowns.
### BarMark
[Section titled “BarMark”](#barmark)
**Parameters:**
* `data` (ChartDataPoint\[], required): The data points.
* `color` (string, optional): Fill color.
* `cornerRadius` (number, optional): Rounded bar corners.
* `width` (number, optional): Fixed bar width.
* `stacking` (string, optional): `"grouped"` for side-by-side bars in a multi-series chart.
```tsx
```
***
### LineMark
[Section titled “LineMark”](#linemark)
**Parameters:**
* `data` (ChartDataPoint\[], required): The data points.
* `color` (string, optional): Line color.
* `lineWidth` (number, optional): Stroke width.
* `interpolation` (string, optional): `"linear"`, `"monotone"`, `"catmullRom"`, `"cardinal"`, `"stepStart"`, `"stepCenter"`, or `"stepEnd"`.
```tsx
```
***
### AreaMark
[Section titled “AreaMark”](#areamark)
**Parameters:**
* `data` (ChartDataPoint\[], required): The data points.
* `color` (string, optional): Fill color.
* `interpolation` (string, optional): Same options as `LineMark`.
```tsx
```
***
### PointMark
[Section titled “PointMark”](#pointmark)
**Parameters:**
* `data` (ChartDataPoint\[], required): The data points.
* `color` (string, optional): Point color.
* `symbolSize` (number, optional): Point size.
```tsx
```
***
### RuleMark
[Section titled “RuleMark”](#rulemark)
A horizontal or vertical reference line. Unlike other marks, RuleMark has no `data` array.
**Parameters:**
* `yValue` (number, optional): Draw a horizontal line at this y value.
* `xValue` (string | number, optional): Draw a vertical line at this x value.
* `color` (string, optional): Line color.
* `lineWidth` (number, optional): Stroke width.
```tsx
```
***
### SectorMark
[Section titled “SectorMark”](#sectormark)
Pie and donut charts.
**Parameters:**
* `data` (SectorDataPoint\[], required): Sector data with `value` and `category`.
* `color` (string, optional): Fill color (overrides automatic coloring).
* `innerRadius` (number, optional): `0` = pie chart, any value above `0` = donut chart. Values ≤ 1 are treated as a ratio of the max radius; values > 1 are treated as absolute dp.
* `outerRadius` (number, optional): Same behavior as `innerRadius`.
* `angularInset` (number, optional): Gap between sectors in degrees.
```tsx
// Pie chart
// Donut chart
```
## Chart Props
[Section titled “Chart Props”](#chart-props)
The `` container accepts these props in addition to the standard `style` prop:
| Prop | Type | Description |
| ---------------------- | -------------------------------------- | --------------------------------------- |
| `xAxisVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the x-axis |
| `xAxisGridStyle` | `{ visible?: boolean }` | Show or hide x-axis grid lines |
| `yAxisVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the y-axis |
| `yAxisGridStyle` | `{ visible?: boolean }` | Show or hide y-axis grid lines |
| `foregroundStyleScale` | `Record` | Map series names to colors |
| `yScale` | `{ min?: number; max?: number }` | Pin the y-axis lower and/or upper bound |
## Multi-Series Charts
[Section titled “Multi-Series Charts”](#multi-series-charts)
Add a `series` field to your data points when you want multiple datasets in the same chart. Use `foregroundStyleScale` to keep those series colors consistent:
```tsx
```
Without `foregroundStyleScale`, colors are chosen automatically.
For side-by-side bars, set `stacking="grouped"`:
```tsx
```
## Combining Marks
[Section titled “Combining Marks”](#combining-marks)
Mix mark types when one chart needs both context and emphasis, such as bars for totals plus a rule for a target:
```tsx
```
## Value Range
[Section titled “Value Range”](#value-range)
The y-axis frames the values a chart is given:
* `LineMark` and `PointMark` scale to the data range, so a series that varies within a narrow band — exchange rates, ratios, temperatures — fills the plot instead of flattening against the top edge. Axis labels carry as many decimals as the distance between ticks needs.
* `BarMark` and `AreaMark` keep zero on the axis, because their height is read against the baseline.
* `RuleMark` values count as part of the range, so a reference line always stays in view.
Data that nearly reaches zero keeps zero on the axis either way, so a series sitting just above the baseline is not exaggerated.
Use `yScale` when a chart needs a fixed window rather than one that follows the data:
```tsx
```
Either bound can stand alone: `yScale={{ min: 0 }}` keeps the baseline at zero and lets the top follow the data. A pinned bound wins over the rules above, including the zero baseline bars and areas otherwise keep, and values outside the pinned range are clipped to the plot.
## Sizing
[Section titled “Sizing”](#sizing)
Chart dimensions are read from the `style` prop:
* **Fixed size**: `style={{ width: 300, height: 200 }}`
* **Fill parent**: `style={{ width: '100%', height: '100%' }}`
If no width or height is specified, the chart defaults to 300×200 dp.
## Platform Notes
[Section titled “Platform Notes”](#platform-notes)
* `legendVisibility` is not currently available on Android charts.
* Point markers are circular on Android.
* `innerRadius` and `outerRadius` on `SectorMark` accept either a ratio (`0` to `1`) or a larger fixed value.
# Interactive Controls (Android)
> Reference for Voltra Android interactive components such as Button, Switch, and CheckBox, and how clicks open the app.
User interface controls that respond to user interaction on Android widgets.
Note
On Android, buttons, toggles, checkboxes, and radio buttons always open the application when clicked. You can provide a `deepLinkUrl` to open a specific screen instead of the main activity.
### Button
[Section titled “Button”](#button)
Standard button component.
**Parameters:**
* `enabled` (boolean, optional): Whether the button is enabled.
* `deepLinkUrl` (string, optional): URL to open when the button is clicked. If not provided, the app will open to its main activity.
Voltra also provides specialized button variants:
#### FilledButton
[Section titled “FilledButton”](#filledbutton)
* `text` (string): Button label.
* `enabled` (boolean, optional).
* `deepLinkUrl` (string, optional).
* `icon` (object, optional): `{ assetName: string }`.
* `backgroundColor` (string, optional).
* `contentColor` (string, optional).
* `maxLines` (number, optional).
#### OutlineButton
[Section titled “OutlineButton”](#outlinebutton)
* `text` (string): Button label.
* `enabled` (boolean, optional).
* `deepLinkUrl` (string, optional).
* `icon` (object, optional): `{ assetName: string }`.
* `contentColor` (string, optional).
* `maxLines` (number, optional).
#### CircleIconButton & SquareIconButton
[Section titled “CircleIconButton & SquareIconButton”](#circleiconbutton--squareiconbutton)
* `enabled` (boolean, optional).
* `deepLinkUrl` (string, optional).
* `icon` (object, optional): `{ assetName: string, base64: string }`.
* `contentDescription` (string, optional).
* `backgroundColor` (string, optional).
* `contentColor` (string, optional).
***
### Clickable Components
[Section titled “Clickable Components”](#clickable-components)
Most components support being clickable by setting the `pressable` prop (short name `prs` in raw elements) in their props.
**Parameters:**
* `pressable` (boolean): Set to `true` to make the component respond to clicks.
* `deepLinkUrl` (string, optional): URL to open when clicked.
***
### Switch
[Section titled “Switch”](#switch)
A toggle switch component.
**Parameters:**
* `id` (string): Unique identifier for interaction events.
* `checked` (boolean, optional): Current state of the switch.
* `deepLinkUrl` (string, optional): URL to open when clicked.
* `text` (string, optional): Label displayed next to the switch.
* `thumbCheckedColor` (string, optional).
* `thumbUncheckedColor` (string, optional).
* `trackCheckedColor` (string, optional).
* `trackUncheckedColor` (string, optional).
* `maxLines` (number, optional): Maximum lines for the label.
***
### CheckBox
[Section titled “CheckBox”](#checkbox)
Standard checkbox component.
**Parameters:**
* `id` (string): Unique identifier for interaction events.
* `checked` (boolean, optional).
* `deepLinkUrl` (string, optional).
* `text` (string, optional).
* `checkedColor` (string, optional).
* `uncheckedColor` (string, optional).
* `maxLines` (number, optional).
***
### RadioButton
[Section titled “RadioButton”](#radiobutton)
Standard radio button component.
**Parameters:**
* `id` (string): Unique identifier for interaction events.
* `checked` (boolean, optional).
* `enabled` (boolean, optional).
* `deepLinkUrl` (string, optional).
* `text` (string, optional).
* `checkedColor` (string, optional).
* `uncheckedColor` (string, optional).
* `maxLines` (number, optional).
# Layout & Containers (Android)
> Reference for Voltra Android layout components built on Jetpack Compose Glance, such as Column, Row, and Box, and their Glance limits.
Components that arrange other elements or provide structural grouping using Jetpack Compose Glance primitives. See [Styling](/android/development/styling) for details on layout and spacing properties.
### Column
[Section titled “Column”](#column)
A vertical container that arranges its children in a column.
Glance limit
`Column` supports at most 10 direct rendered children. Jetpack Glance truncates extra children. Use `LazyColumn` for dynamic or scrollable collections.
**Parameters:**
* `horizontalAlignment` (string, optional): `"start"`, `"center-horizontally"`, `"end"`.
* `verticalAlignment` (string, optional): `"top"`, `"center-vertically"`, `"bottom"`.
***
### Row
[Section titled “Row”](#row)
A horizontal container that arranges its children in a row.
Glance limit
`Row` supports at most 10 direct rendered children. Jetpack Glance truncates extra children. Use `LazyColumn` for dynamic or scrollable collections.
**Parameters:**
* `horizontalAlignment` (string, optional): `"start"`, `"center-horizontally"`, `"end"`.
* `verticalAlignment` (string, optional): `"top"`, `"center-vertically"`, `"bottom"`.
***
### Box
[Section titled “Box”](#box)
A container that stacks its children on top of each other.
**Parameters:**
* `contentAlignment` (string, optional): Combined alignment. Supports `"top-start"`, `"top-center"`, `"top-end"`, `"center-start"`, `"center"`, `"center-end"`, `"bottom-start"`, `"bottom-center"`, `"bottom-end"`.
***
### Scaffold
[Section titled “Scaffold”](#scaffold)
A top-level container that provides a standard layout structure for widgets.
**Parameters:**
* `backgroundColor` (string, optional): Background color for the scaffold.
* `horizontalPadding` (number, optional): Horizontal padding in dp.
***
### TitleBar
[Section titled “TitleBar”](#titlebar)
A component that displays a title bar with a required leading icon.
**Parameters:**
* `title` (string): Title text to display.
* `startIcon` (object, required): `{ assetName: string }` or `{ base64: string }`.
* `textColor` (string, optional).
* `iconColor` (string, optional).
* `fontFamily` (string, optional): `"monospace"`, `"serif"`, `"sans-serif"`, or `"cursive"`.
***
### Spacer
[Section titled “Spacer”](#spacer)
A component that provides fixed spacing between elements.
**Parameters:**
* `size` (number): Size of the spacer in dp.
***
### LazyColumn
[Section titled “LazyColumn”](#lazycolumn)
A scrollable vertical list that only renders visible items.
**Parameters:**
* `horizontalAlignment` (string, optional): `"start"`, `"center-horizontally"`, `"end"`.
***
### LazyVerticalGrid
[Section titled “LazyVerticalGrid”](#lazyverticalgrid)
A scrollable grid of items.
**Parameters:**
* `columns` (number | `"adaptive"`): Number of columns or `"adaptive"` for an adaptive grid.
* `minSize` (number, optional): Minimum size (in dp) for items in adaptive grid mode.
* `horizontalAlignment` (string, optional): `"start"`, `"center-horizontally"`, `"end"`.
* `verticalAlignment` (string, optional): `"top"`, `"center"`, `"bottom"`.
# Data Visualization & Status (Android)
> Reference for Voltra Android components that show data and progress, including LinearProgressIndicator and its limits.
Components for displaying data and status information on Android widgets.
### LinearProgressIndicator
[Section titled “LinearProgressIndicator”](#linearprogressindicator)
A horizontal progress bar.
**Parameters:**
* `progress` (number, optional): Current progress value (0.0 to 1.0). If omitted, the indicator will be indeterminate.
* `color` (string, optional): Color for the progress indicator.
* `backgroundColor` (string, optional): Color for the background track.
***
### CircularProgressIndicator
[Section titled “CircularProgressIndicator”](#circularprogressindicator)
A circular progress indicator.
**Parameters:**
* `color` (string, optional): Color for the progress indicator.
Indeterminate Only
Due to Jetpack Compose Glance limitations, the `CircularProgressIndicator` on Android renders in **indeterminate** mode.
***
### ArcProgressIndicator
[Section titled “ArcProgressIndicator”](#arcprogressindicator)
A determinate arc gauge: a partial ring whose stroke fills clockwise, with rounded ends and a gap at the bottom by default. Children are centered on top of the arc, so a label, an icon, or nothing goes in the middle.
**Parameters:**
* `progress` (number, optional): Fill fraction, clamped to 0.0–1.0. Defaults to `0`.
* `color` (string, optional): Stroke color of the filled arc. Defaults to the widget theme’s progress color.
* `trackColor` (string, optional): Stroke color of the unfilled arc. Defaults to the widget theme’s track color; use `transparent` to hide the track.
* `strokeWidth` (number, optional): Stroke width in dp of both arcs. Defaults to `8`.
* `startAngle` (number, optional): Angle in degrees where the arc begins. `0` is 3 o’clock and positive is clockwise. Defaults to `135`.
* `sweepAngle` (number, optional): Total angular length of the track in degrees. `360` makes a closed ring. Defaults to `270`.
* `lineCap` (`'round' | 'butt'`, optional): End shape of both arcs. Defaults to `'round'`.
* `gradientColors` (string\[], optional): Sweep gradient spread across the track, starting at `startAngle`. Overrides `color`. Needs at least two colors; a single color is drawn as a solid stroke, and the gradient is ignored if any color fails to parse.
```tsx
75%
```
Unlike the other two indicators, this one works on every supported Android version, because it is drawn as a bitmap rather than composed from a Glance progress primitive.
Give the component a width and a height. When you leave an axis unsized it falls back to 64 dp, which is rarely what you want, and when you give it a `flex` weight the parent controls both axes, so size the arc through the parent instead. Because the arc occupies one of the ten child slots a Glance `Box` allows, you can nest at most nine elements inside it.
Bitmap Memory
The arc is a bitmap, so it costs memory that grows with the square of its pixel size. Voltra sizes it from the smaller of the component’s width and height, multiplies by the display density clamped to 1–3.5, and caps each edge at 512 px, so one gauge costs at most 1 MiB and a typical one around a quarter of that. Identical gauges share a single bitmap, so a fixed-size gauge costs its bytes once per widget no matter how many responsive size variants it appears in; a gauge sized with `'100%'` resolves to a different bitmap per variant. The system caps the bitmaps of one widget instance at roughly 1.5 screens’ worth of pixels, so very large or very many arcs in a single widget remain your responsibility.
The indicator does not animate. Changing `progress` redraws it.
# Visual Elements & Typography (Android)
> Reference for Voltra Android visual components such as Text and Image that display static content in widgets.
Static or decorative elements used to display content on Android widgets. See [Styling](/android/development/styling) for details on supported style properties.
### Text
[Section titled “Text”](#text)
Displays text content.
**Parameters:**
* `maxLines` (number, optional): Maximum number of lines to display.
* `renderAsBitmap` (boolean, optional): Renders text as a bitmap image to enable [custom fonts](/android/development/custom-fonts). Requires `fontFamily` in the style prop.
***
### Image
[Section titled “Image”](#image)
Displays bitmap images from the asset catalog, preloaded runtime cache, or base64 encoded data. SVGs should be rasterized through the image preloading API and referenced by `assetName`.
**Parameters:**
* `source` (object, optional): Image source object.
* `assetName` (string): Reference to a pre-bundled image (drawable resource) or a [preloaded image](/android/development/image-preloading).
* `base64` (string): Base64 encoded image data.
* `resizeMode` (string, optional): `"cover"`, `"contain"`, `"stretch"`, `"repeat"`, or `"center"`.
* `contentDescription` (string, optional): Accessibility description for the image.
* `contentScale` (string, optional): Glance-specific scaling mode: `"crop"`, `"cover"`, `"fit"`, `"contain"`, `"fill-bounds"`, or `"stretch"`.
* `alpha` (number, optional): Opacity value from 0.0 to 1.0.
* `colorFilter` (string, optional): Color tint filter for the image.
* `tintColor` (string, optional): Legacy alias for `colorFilter`.
* `fallback` (ReactNode, optional): Custom content rendered when the image is missing.
**Styling the fallback:**
To add a background color when an image is missing, use `backgroundColor` in the `style` prop:
```jsx
```
Image Preloading
For dynamic images from remote URLs, use the [Image Preloading](/android/development/image-preloading) API to cache them locally for use in widgets.
# Custom Fonts
> Use custom fonts in Android widgets by rendering text as a bitmap with a Typeface loaded from the fonts you list in the plugin config.
Android Glance only supports a handful of built-in font families (`monospace`, `serif`, `sans-serif`, `cursive`). Voltra works around this by rendering text as a bitmap with a custom `Typeface` loaded from `assets/fonts/`.
## Setup
[Section titled “Setup”](#setup)
### 1. Add font files to the plugin config
[Section titled “1. Add font files to the plugin config”](#1-add-font-files-to-the-plugin-config)
List your font paths in the top-level `fonts` array. These can be local files or packages from `@expo-google-fonts`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"fonts": [
"node_modules/@expo-google-fonts/pacifico/400Regular/Pacifico_400Regular.ttf",
"./assets/fonts/MyCustomFont.ttf"
],
"widgets": []
}
]
]
}
}
```
### 2. Run prebuild
[Section titled “2. Run prebuild”](#2-run-prebuild)
```bash
npx expo prebuild
```
The plugin copies each font file to `android/app/src/main/assets/fonts/` automatically.
### 3. Use `renderAsBitmap` on Text
[Section titled “3. Use renderAsBitmap on Text”](#3-use-renderasbitmap-on-text)
```tsx
import { VoltraAndroid } from '@use-voltra/android'
Hello Voltra!
```
The `fontFamily` value should match the font filename **without the extension**.
Note that `renderAsBitmap` text is rasterized — it won’t respond to system font size or accessibility settings. Use it only when a custom typeface is needed.
## Supported style properties
[Section titled “Supported style properties”](#supported-style-properties)
When rendering as bitmap, the following text style properties are supported:
| Property | Description |
| -------------------- | ------------------------------------------ |
| `fontSize` | Font size in sp (scaled to device density) |
| `fontFamily` | Font filename without extension |
| `fontWeight` | `"normal"` or `"bold"` |
| `color` | Text color |
| `textAlign` | `"left"`, `"center"`, `"right"` |
| `textDecorationLine` | `"underline"`, `"line-through"` |
| `letterSpacing` | Letter spacing value |
| `lineHeight` | Line spacing |
## Built-in font families
[Section titled “Built-in font families”](#built-in-font-families)
For built-in families you don’t need `renderAsBitmap` — use `fontFamily` in style directly:
* `monospace`
* `serif`
* `sans-serif`
* `cursive`
These are passed through to Glance’s native `FontFamily` API.
# Developing Android Widgets
> Build Android Home Screen widgets from JSX with the Glance primitives Voltra maps to, plus links to the related development guides.
Voltra allows you to build Android Home Screen widgets using JSX and Jetpack Compose Glance primitives.
## Glance Primitives
[Section titled “Glance Primitives”](#glance-primitives)
On Android, you use `VoltraAndroid` components which map to Glance primitives:
* **Column:** Vertical layout
* **Row:** Horizontal layout
* **Box:** Stacked layout
* **Spacer:** Flexible spacing
* **Text:** Displaying text
* **Image:** Displaying images
* **Scaffold:** Top-level container
### Example Widget
[Section titled “Example Widget”](#example-widget)
```tsx
import { VoltraAndroid } from '@use-voltra/android'
const WeatherWidget = ({ temperature, condition }) => (
{temperature}°C
{condition}
)
```
## Update API
[Section titled “Update API”](#update-api)
To update a widget’s content, use the `updateAndroidWidget` function from `@use-voltra/android-client`:
```typescript
import { updateAndroidWidget } from '@use-voltra/android-client'
await updateAndroidWidget('weather_widget', )
```
`updateAndroidWidget` only updates payload-driven widgets like this one. Calling it on a Dynamic Widget (see [Dynamic Widgets](/android/development/dynamic-widgets)) rejects with `VOLTRA_WIDGET_KIND_MISMATCH`.
## Layout Constraints
[Section titled “Layout Constraints”](#layout-constraints)
Unlike standard React Native or iOS Stacks, Android Glance layouts are more restrictive:
* **Width/Height:** Use fixed numbers (dp), `"100%"` to fill available space, or `"auto"` to wrap content.
* **Modifiers:** Most styling is handled via the `style` prop, which maps to Glance `Modifier`s. See [Styling](/android/development/styling) for full details.
* **Alignment:** Use `verticalAlignment` and `horizontalAlignment` props on `Column` and `Row`.
## Advanced Features
[Section titled “Advanced Features”](#advanced-features)
* **[Querying Active Widgets](/android/development/querying-active-widgets):** Detect active widget instances and their sizes.
* **[Testing and Previews](/android/development/testing-and-previews):** Preview layouts within your app.
* **[Widget Picker Previews](/android/api/widget-sizing-and-previews):** Configure how your widget appears in the Android widget picker.
* **[Image Preloading](/android/development/image-preloading):** Cache remote images for use in widgets.
* **[Widget Pre-rendering](/android/development/widget-pre-rendering):** Provide initial state for widgets before the app first runs.
# Dynamic colors
> Use AndroidDynamicColors semantic tokens so widgets follow the Material palette and wallpaper changes without a JavaScript re-render.
Voltra supports Android dynamic colors through semantic tokens exposed from `@use-voltra/android`.
These colors follow the current Android Material palette, so widgets can pick up wallpaper and theme changes without waiting for JavaScript to run again.
## Importing dynamic colors
[Section titled “Importing dynamic colors”](#importing-dynamic-colors)
```tsx
import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android'
```
`AndroidDynamicColors` includes these roles:
* `primary`
* `onPrimary`
* `primaryContainer`
* `onPrimaryContainer`
* `secondary`
* `onSecondary`
* `secondaryContainer`
* `onSecondaryContainer`
* `tertiary`
* `onTertiary`
* `tertiaryContainer`
* `onTertiaryContainer`
* `error`
* `errorContainer`
* `onError`
* `onErrorContainer`
* `background`
* `onBackground`
* `surface`
* `onSurface`
* `surfaceVariant`
* `onSurfaceVariant`
* `outline`
* `inverseOnSurface`
* `inverseSurface`
* `inversePrimary`
* `widgetBackground`
## Example
[Section titled “Example”](#example)
```tsx
import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android'
export function WeatherWidget() {
return (
21°
)
}
```
## Where you can use them
[Section titled “Where you can use them”](#where-you-can-use-them)
You can use `AndroidDynamicColors.*` anywhere Android accepts a color value, including:
* `style.backgroundColor`
* `style.color`
* `Image.colorFilter`
* button `backgroundColor` and `contentColor`
* `TitleBar.textColor` and `TitleBar.iconColor`
* switch, checkbox, and radio button colors
* progress indicator colors
* chart mark colors
## Server-driven widgets
[Section titled “Server-driven widgets”](#server-driven-widgets)
Dynamic color tokens work in server-rendered Android widgets too.
```tsx
import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android'
const content = (
Server-rendered widget
)
```
The same `AndroidDynamicColors.*` values work whether the widget is rendered in-app or returned from your server.
# Dynamic Widgets
> Write Android widgets whose entry component renders on the device and reacts to app-supplied props and device state such as locale and color scheme.
Dynamic Widgets run their entry component on-device and can react to both app-supplied runtime props and current device state. Declare a Dynamic Widget in `app.json` with a stable `id` and an explicit `entry`, then default-export the Dynamic Widget from that file.
Your Dynamic Widget can react to:
* `env.widgetFamily`
* `env.colorScheme`
* `env.locale`, `env.preferredLanguages`, `env.hourCycle`, `env.timeZone` and the other [locale fields](/android/development/localization)
* `env.configuration`
* `AndroidDynamicColors` tokens, which resolve to the current Material You palette natively
When you change `app.json`, run Expo Prebuild or Voltra Apply so the updated Dynamic Widget configuration is available on device. If you change only the Dynamic Widget JS, reopen the app in development and the Dynamic Widget updates automatically.
## Set up Metro
[Section titled “Set up Metro”](#set-up-metro)
Dynamic Widgets require `@use-voltra/metro` in the app project. Install it alongside the Android packages:
```sh
npm install @use-voltra/metro
```
Wrap the app’s existing Metro config with `withVoltra`:
metro.config.js
```js
const { getDefaultConfig } = require('expo/metro-config')
const { withVoltra } = require('@use-voltra/metro')
const config = getDefaultConfig(__dirname)
module.exports = withVoltra(config)
```
## How to use it
[Section titled “How to use it”](#how-to-use-it)
1. Add an Android Dynamic Widget declaration to `app.json` with an `id`, an `entry`, and any Dynamic Widget metadata you need.
2. Default-export the Dynamic Widget function or component from the module named by `entry`.
3. Use `initialStatePath` if you want a pre-rendered first view.
4. Re-run Expo Prebuild or Voltra Apply after updating `app.json`.
5. Keep Android and iOS Dynamic Widget declarations separate; the same `id` can exist on both platforms because each platform is configured separately.
widgets/android/inbox-widget.tsx
```tsx
import { AndroidDynamicColors, VoltraAndroid, type WidgetEnvironment } from '@use-voltra/android'
type InboxDynamicWidgetProps = {
// Optional because the Dynamic Widget receives {} before its first runtime props update.
unreadCount?: number
}
type InboxDynamicWidgetConfiguration = {
label?: string
}
export default function InboxDynamicWidget(
props: InboxDynamicWidgetProps = {},
env: WidgetEnvironment = {} as WidgetEnvironment
) {
const unreadCount = props.unreadCount ?? 0
const label = env.configuration?.label ?? 'Inbox'
// Format with the user's locale, 12/24-hour setting and time zone.
const renderedAt = (env.date ? new Date(env.date) : new Date()).toLocaleTimeString(env.locale, {
hour: '2-digit',
minute: '2-digit',
hourCycle: env.hourCycle,
timeZone: env.timeZone,
})
return (
{label}
{unreadCount} unread
Size: {env.widgetFamily}
Scheme: {env.colorScheme ?? 'light'}
Rendered: {renderedAt}
)
}
```
Example plugin config:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"widgets": [
{
"id": "inbox_widget",
"entry": "./widgets/android/inbox-widget.tsx",
"displayName": "Inbox Widget",
"description": "A Dynamic Widget with runtime props and live device state",
"targetCellWidth": 2,
"targetCellHeight": 2,
"initialStatePath": "./widgets/android/inbox-widget.tsx",
"appIntent": {
"parameters": [
{
"name": "label",
"title": "Label",
"default": "Inbox"
}
]
}
}
]
}
]
]
}
}
```
After changing the plugin configuration, rebuild the native Android app. You also need a native rebuild after upgrading to a version of `@use-voltra/android-client` that introduces a new native API.
## Update Dynamic Widget props
[Section titled “Update Dynamic Widget props”](#update-dynamic-widget-props)
Call `updateAndroidDynamicWidget` from your app. The object is serialized, persisted, and passed as the first argument to the entry component on each subsequent render. The update re-renders every installed instance with the matching Dynamic Widget id.
```ts
import { updateAndroidDynamicWidget } from '@use-voltra/android-client'
await updateAndroidDynamicWidget('inbox_widget', {
unreadCount: 7,
})
```
Dynamic Widget props must be JSON-serializable. You can use strings, numbers, booleans, `null`, arrays, and nested objects. Functions, `undefined`, `Date`, `BigInt`, and cyclic references are not supported.
Before the first call to `updateAndroidDynamicWidget`, the entry component receives `{}`. The latest props object is persisted by Dynamic Widget id, survives app process restarts, and is reused until a later call replaces it or the app’s data is cleared.
Choose the API by widget type
`updateAndroidDynamicWidget` updates an entry-based Dynamic Widget by passing runtime props to its entry component. The legacy `updateAndroidWidget` API sends pre-rendered variant payloads to a payload-driven widget and cannot update an entry-based Dynamic Widget. Calling it on a Dynamic Widget now rejects with `VOLTRA_WIDGET_KIND_MISMATCH`, and `updateAndroidDynamicWidget` rejects the same way when called on a payload-driven widget.
## Fetching props from a server
[Section titled “Fetching props from a server”](#fetching-props-from-a-server)
Props do not have to come from the app. Add a `serverUpdate` alongside `entry` and the widget fetches a JSON object on a schedule and renders it, without the app running:
```json
{
"id": "portfolio",
"entry": "./widgets/android/portfolio.tsx",
"serverUpdate": {
"url": "https://api.example.com/widgets/portfolio",
"intervalMinutes": 30
}
}
```
The response object becomes the same first argument `updateAndroidDynamicWidget` passes, so the entry component does not change. Because the server returns data rather than a rendered payload, the backend can be written in any language.
`updateAndroidDynamicWidget` keeps working on a server-driven widget — the next fetch simply overwrites what you wrote. See [Server-driven widgets](/android/development/server-driven-widgets) for the response contract, the `env.serverUpdate` fields, and how to take a widget over.
## Configure each placed widget separately
[Section titled “Configure each placed widget separately”](#configure-each-placed-widget-separately)
Every widget placed on the Home Screen has its own `appWidgetId`. Give one placement its own values and it renders them alone — the usual reason to place a widget twice, like one weather widget on London and another on New York. The widget code does not change: it still reads `env.configuration`, and now gets the values of the placement being drawn.
Three layers feed `env.configuration`, each hiding the same key in the one below it:
```plaintext
defaults (app.json) < widget-type values < instance values → env.configuration
```
Read the placements, then write to one of them:
```typescript
import {
getActiveWidgets,
setWidgetInstanceConfiguration,
getWidgetInstanceConfiguration,
clearWidgetInstanceConfiguration,
} from '@use-voltra/android-client'
const placements = await getActiveWidgets()
const weather = placements.filter(widget => widget.widgetType === 'weather')
if (weather.length > 0) {
// One key at a time…
await setWidgetInstanceConfiguration(weather[0].appWidgetId, 'city', 'London')
// What this placement renders with, all three layers merged.
const values = await getWidgetInstanceConfiguration(weather[0].appWidgetId)
// Drop this placement's own values so it follows the widget-type ones again.
await clearWidgetInstanceConfiguration(weather[0].appWidgetId)
}
if (weather.length > 1) {
// Several keys at once, which costs one write and one re-render.
await setWidgetInstanceConfiguration(weather[1].appWidgetId, {
city: 'New York',
units: 'fahrenheit',
})
}
```
Values are strings, and only that placement re-renders.
### How the layers interact
[Section titled “How the layers interact”](#how-the-layers-interact)
`setWidgetConfiguration(widgetId, key, value)` still writes the widget-type value, which is what every placement without its own value for that key renders. A placement that has its own value keeps showing it, so a later type-level write does not visibly change it. `clearWidgetInstanceConfiguration` drops the placement’s values and it follows the type-level ones again. `getWidgetConfiguration(widgetId)` reads the type-level layer — the defaults plus any type-level values — without any placement’s own values.
### What happens to the values
[Section titled “What happens to the values”](#what-happens-to-the-values)
Removing a widget from the Home Screen drops that placement’s values, so adding the widget again starts from the widget-type values rather than inheriting the old placement’s. When the launcher restores its layout from a backup and assigns new ids, each placement’s values move with it, so a configured widget survives a device restore.
These APIs reject when the `appWidgetId` is not a placement of one of your own Dynamic Widgets: `VOLTRA_WIDGET_INSTANCE_NOT_FOUND` when nothing of yours is placed with that id, `VOLTRA_WIDGET_KIND_MISMATCH` when the placement is a payload-driven widget, and `VOLTRA_WIDGET_NOT_FOUND` when the widget id cannot be resolved. Nothing is stored unless the call succeeds.
### Platform differences
[Section titled “Platform differences”](#platform-differences)
The Home Screen’s own edit gesture does not open a Voltra configuration screen yet, so your app is the only place to change a placement’s values on Android. On iOS the system Edit Widget sheet writes them instead, generated from the same `appIntent.parameters`, and the widget reads `env.configuration` exactly as it does here.
## Runtime props and configuration are separate
[Section titled “Runtime props and configuration are separate”](#runtime-props-and-configuration-are-separate)
Dynamic Widget props are app-owned state passed as the entry component’s first argument. Configuration values are declared through `appIntent.parameters`, updated in-app with `setWidgetConfiguration` for every placement or `setWidgetInstanceConfiguration` for one, and read from `env.configuration`. Updating one does not replace the other.
## Localization
[Section titled “Localization”](#localization)
Pass `env.locale` and `env.hourCycle` to every `Intl` and `toLocale*` call, and pick a translation with `resolveLocale(env, messages)`. `Intl.PluralRules`, `Intl.RelativeTimeFormat`, `Intl.ListFormat` and `Intl.DisplayNames` are not available in Android widgets unless you add the polyfills. See [Localization](/android/development/localization) for the polyfills, every locale field, and how to let the app choose the widget language.
## Notes
[Section titled “Notes”](#notes)
* There is no `export` field in app.json for Dynamic Widgets.
* The default-exported Dynamic Widget function or component name does not need to match the widget `id`.
* Use a real device to verify release rendering.
* `initialStatePath` gives the Dynamic Widget a pre-rendered first view.
* To use Glance modifiers that `style` does not cover, such as `semantics` or `appWidgetBackground`, see [Native modifiers](/android/development/native-modifiers).
# Image Preloading (Android)
> API reference for downloading remote images into the app cache so Android widgets can display them through assetName.
Android widgets have limitations when it comes to displaying remote images directly. The image preloading API allows you to download images to the app’s cache directory, making them available to your widgets via a local `FileProvider`.
## Overview
[Section titled “Overview”](#overview)
The image preloading system on Android works by:
1. Downloading images from URLs to the internal app cache.
2. Rasterizing SVG inputs to PNG when needed.
3. Making these images available to Voltra widgets via the `assetName` property.
4. Providing APIs to reload widgets when new images are ready.
## API Reference
[Section titled “API Reference”](#api-reference)
### `preloadImages(images: PreloadImageOptions[]): Promise`
[Section titled “preloadImages(images: PreloadImageOptions\[\]): Promise\”](#preloadimagesimages-preloadimageoptions-promisepreloadimagesresult)
Downloads images to the Android cache for use in Widgets.
Each item must be either a URL preload (`url`) or an SVG preload (`svg`). The TypeScript types express this as a union of two variants:
```typescript
type PreloadImageUrlOptions = {
key: string // The assetName to use when referencing this image
url: string // URL to download the image from
method?: 'GET' | 'POST' | 'PUT' // HTTP method (default: 'GET')
headers?: Record // Optional HTTP headers
width?: number
height?: number
}
type PreloadImageSvgOptions = {
key: string // The assetName to use when referencing this image
svg: string // Inline SVG markup to rasterize and cache as PNG
width?: number // Typically required for SVG rasterization (see native errors if omitted)
height?: number
}
type PreloadImageOptions = PreloadImageUrlOptions | PreloadImageSvgOptions
type PreloadImageFailure = {
key: string
error: string
}
type PreloadImagesResult = {
succeeded: string[] // Keys of successfully downloaded images
failed: PreloadImageFailure[] // Failed downloads with error messages
}
```
**Example:**
```typescript
import { preloadImages } from '@use-voltra/android-client'
const result = await preloadImages([
{
url: 'https://example.com/album-art.jpg',
key: 'current-album',
headers: { Authorization: 'Bearer token' },
},
{
key: 'status-icon-active',
svg: '',
width: 24,
height: 24,
},
])
if (result.succeeded.includes('status-icon-active')) {
// Images are ready to be used in widgets
}
```
### `reloadWidgets(widgetIds?: string[]): Promise`
[Section titled “reloadWidgets(widgetIds?: string\[\]): Promise\”](#reloadwidgetswidgetids-string-promisevoid)
Reloads Android widgets to pick up newly preloaded images. If no `widgetIds` are provided, all active widgets will be reloaded.
```typescript
import { reloadWidgets } from '@use-voltra/android-client'
// Reload all widgets
await reloadWidgets()
// Reload specific widgets
await reloadWidgets(['weather_widget'])
```
### `clearPreloadedImages(keys?: string[]): Promise`
[Section titled “clearPreloadedImages(keys?: string\[\]): Promise\”](#clearpreloadedimageskeys-string-promisevoid)
Removes preloaded images from the Android cache. If no `keys` are provided, all preloaded images will be cleared.
```typescript
import { clearPreloadedImages } from '@use-voltra/android-client'
// Clear specific images
await clearPreloadedImages(['current-album'])
// Clear all preloaded images
await clearPreloadedImages()
```
## Usage in Android Widgets
[Section titled “Usage in Android Widgets”](#usage-in-android-widgets)
Once images are preloaded, reference them using the `assetName` property in the `VoltraAndroid.Image` component:
```tsx
import { VoltraAndroid } from '@use-voltra/android'
function MusicWidget({ albumKey }) {
return (
)
}
```
# Images
> Compare the three ways to include images in Android widgets: build-time asset copying, runtime preloading, and Base64 encoding.
Voltra provides three different approaches for including images in your Android widgets, each with different trade-offs and use cases:
* **Build-time asset copying**: Best for static icons and assets known at build time
* **Runtime preloading**: Best for dynamic images from remote URLs
* **Base64 encoding**: Best for small, generated images
## Build-time asset copying
[Section titled “Build-time asset copying”](#build-time-asset-copying)
Place images in the `/assets/voltra-android/` directory and they’ll be automatically processed and copied to the Android drawable resources during build.
```plaintext
project-root/
├── assets/
│ └── voltra-android/
│ ├── logo.png
│ ├── weather/
│ │ ├── sunny.svg
│ │ └── rainy.xml
│ └── background.webp
```
Run `npx expo prebuild` to apply changes — images are detected during the build, sanitized to fit Android resource naming rules, and copied into the native Android project (SVGs are converted to Vector Drawables along the way).
### Naming & Sanitization
[Section titled “Naming & Sanitization”](#naming--sanitization)
Android drawable resources have strict naming conventions. Voltra automatically handles this for you:
* **Sanitization:** Uppercase letters are converted to lowercase. Hyphens and other special characters are replaced with underscores.
* **Flattening:** Subdirectories are flattened into the resource name to avoid conflicts.
**Examples:**
| Source File | Android Resource Name |
| ----------------------------------------- | --------------------- |
| `assets/voltra-android/Logo.png` | `logo` |
| `assets/voltra-android/icons/My-Icon.png` | `icons_my_icon` |
| `assets/voltra-android/weather/sunny.svg` | `weather_sunny` |
### Supported Formats
[Section titled “Supported Formats”](#supported-formats)
* **Bitmap:** `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`
* **Vector:** `.svg` (converted to Vector Drawable), `.xml` (native Vector Drawable)
### Usage
[Section titled “Usage”](#usage)
Reference these images using their sanitized name in the `assetName` property. You do not need to include the file extension.
```tsx
import { VoltraAndroid } from '@use-voltra/android'
// assets/voltra-android/logo.png -> "logo"
// assets/voltra-android/weather/sunny.svg -> "weather_sunny"
```
## Runtime preloading
[Section titled “Runtime preloading”](#runtime-preloading)
For dynamic images from remote URLs, use Voltra’s image preloading API to cache images locally. See [Image Preloading](/android/development/image-preloading) for how it works.
Once images are preloaded, reference them using the key you provided:
```tsx
import { VoltraAndroid } from '@use-voltra/android'
function ProfileWidget({ user }) {
return (
{user.name}
)
}
```
For detailed API documentation, see [Image Preloading](/android/development/image-preloading).
## Base64 encoding
[Section titled “Base64 encoding”](#base64-encoding)
You can also embed images directly as base64-encoded strings. This is useful for small, generated images or when you want to avoid file management for very simple assets.
```tsx
```
## Comparison table
[Section titled “Comparison table”](#comparison-table)
| Approach | When Known | Dynamic | Setup Required | Performance |
| -------------- | ------------- | ------- | ---------------- | -------------------------------- |
| **Build-time** | Build time | No | File placement | Best (Native Resource) |
| **Preloading** | Runtime | Yes | Preload API call | Good (Cached File) |
| **Base64** | Runtime/Build | No | None | Fair (Memory intensive if large) |
# Localization
> Translate Android Dynamic Widgets, format dates and numbers from env, and localize the widget picker name and description.
A Dynamic Widget renders on the device, so your JavaScript can translate the widget and format dates, numbers and units for the person looking at it. Every render receives the language and regional settings on `env`, and placed widgets render again when those settings change.
## What the widget knows about the user
[Section titled “What the widget knows about the user”](#what-the-widget-knows-about-the-user)
| Field | Example | What it tells you |
| -------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `locale` | `"pl-PL"` | The language and region the widget is drawn in, as a BCP-47 tag. Pass it to every `Intl` and `toLocale*` call. |
| `preferredLanguages` | `["pl-PL", "en-US"]` | The user’s languages in order. A per-app language (Android 13 and newer) comes first, then the system languages. |
| `appLocale` | `"pl"` | The language your app chose with `setDynamicWidgetLocale`. Absent unless you set one. |
| `layoutDirection` | `"ltr"` | `"rtl"` for Arabic, Hebrew and other right-to-left languages. |
| `hourCycle` | `"h23"` | `"h12"` or `"h23"`, matching the user’s 24-hour time setting. |
| `timeZone` | `"Europe/Warsaw"` | The device time zone. |
| `measurementSystem` | `"metric"` | `"metric"`, `"us"` or `"uk"`. Absent on Android 8 and older. |
| `calendar` | `"gregory"` | The user’s calendar, spelled the way `Intl` expects. |
| `firstDayOfWeek` | `2` | `1` is Sunday, `2` is Monday, up to `7` for Saturday. |
Placed widgets render again after the device language, the app’s per-app language or the regional preferences change, even when the app is not running. A language change your app makes while it is running takes effect at once. If the user force-stopped the app in Settings, its widgets keep the old language until the app runs again.
## Translate widget content
[Section titled “Translate widget content”](#translate-widget-content)
Keep one messages object per language and let `resolveLocale` choose. It tries `appLocale`, then each entry of `preferredLanguages` (exact tag, then language only), then `locale`. If none match, it returns `en`, then `__default`, then the alphabetically first key. It returns `undefined` only when the object is empty.
```tsx
import { resolveLocale, VoltraAndroid, type WidgetEnvironment } from '@use-voltra/android'
const messages = {
en: { title: 'Next train' },
pl: { title: 'Następny pociąg' },
}
export default function TrainWidget(props: { departure?: number }, env: WidgetEnvironment) {
const t = messages[resolveLocale(env, messages) ?? 'en']
const time = new Intl.DateTimeFormat(env.locale, {
hour: 'numeric',
minute: '2-digit',
hourCycle: env.hourCycle,
timeZone: env.timeZone,
}).format(new Date(props.departure ?? env.date.valueOf()))
return (
{t.title}{time}
)
}
```
`pickLocalizedValue(map, languages)` applies the same fallback to any locale-keyed map when you want to pass the language list yourself.
## Format dates, numbers and units
[Section titled “Format dates, numbers and units”](#format-dates-numbers-and-units)
Pass `env.locale` to every `Intl` and `toLocale*` call, `env.timeZone` whenever you format a date, and `env.hourCycle` whenever you format a time. The user’s 24-hour setting is separate from the locale on Android, so `Intl` only honors it when you pass `hourCycle`.
Use `env.measurementSystem` to choose between kilometers and miles, or Celsius and Fahrenheit, and `env.firstDayOfWeek` when you draw a week.
### Intl support on Android
[Section titled “Intl support on Android”](#intl-support-on-android)
Android widgets have `Intl.Collator`, `Intl.NumberFormat`, `Intl.DateTimeFormat` and the `toLocale*` methods. They do not have `Intl.PluralRules`, `Intl.RelativeTimeFormat`, `Intl.ListFormat`, `Intl.DisplayNames` or `Intl.Locale`. Calling one of those throws, and i18n libraries that rely on plural rules (i18next 21 and newer, FormatJS) fail without them. `Intl.Segmenter` is missing too, and the polyfills below do not add it.
To use them, add the [FormatJS](https://formatjs.github.io/docs/polyfills) polyfills to Android widget bundles. Install the packages in the app:
```sh
npm install @formatjs/intl-getcanonicallocales @formatjs/intl-locale @formatjs/intl-pluralrules \
@formatjs/intl-listformat @formatjs/intl-displaynames @formatjs/intl-relativetimeformat
```
Then list the languages your widgets render in:
metro.config.js
```js
const { getDefaultConfig } = require('expo/metro-config')
const { withVoltra } = require('@use-voltra/metro')
module.exports = withVoltra(getDefaultConfig(__dirname), {
androidIntlPolyfills: { locales: ['en', 'pl', 'de'] },
})
```
Locale data is loaded per language, so `pt-BR` and `pt-PT` both load `pt`. Each language adds to the Android bundle size, so list only the ones you translate into. iOS bundles are not changed. If a package is missing, Metro fails at startup with a message naming the packages to install.
## Let the app choose the language
[Section titled “Let the app choose the language”](#let-the-app-choose-the-language)
On Android 13 and newer, a per-app language the user picks in Settings already reaches widgets as `env.locale`. On Android 12 and older, a language your app sets with AppCompat does not reach widgets. In that case, or when your app has its own language picker, pass the language to widgets:
```ts
import { setDynamicWidgetLocale } from '@use-voltra/android-client'
await setDynamicWidgetLocale('pl') // every render now sees env.appLocale === 'pl'
await setDynamicWidgetLocale(null) // back to the system languages
```
Every placed Dynamic Widget renders again as soon as the value is stored, and the value survives app restarts. `resolveLocale` prefers `appLocale` over every other field.
The override changes the translation only. `locale`, `layoutDirection`, `hourCycle` and the other formatting fields stay as they were, and Android keeps laying out the widget in the direction of `locale`. If you translate into a right-to-left language while `locale` is left-to-right, position hand-placed content by `env.layoutDirection`, not by the language you chose.
## Translate the picker and configuration copy
[Section titled “Translate the picker and configuration copy”](#translate-the-picker-and-configuration-copy)
The widget picker name and description accept locale maps; see [Localizing `displayName` and `description`](/android/api/plugin-configuration#localizing-displayname-and-description).
`appIntent.parameters[].title` and `options[].title` accept locale maps too. Android has no system screen that shows them, so Voltra stores them as Android string resources for a configuration screen you build in native code, where you read them as `R.string.`:
| Copy | Resource name |
| --------------------- | ------------------------------------------------ |
| a parameter’s `title` | `voltra_widget__param__title` |
| an option’s `title` | `voltra_widget__param__option_` |
``, `` and `` are lower-cased, and anything other than letters, digits and underscores becomes `_`. Rebuild the native app after changing them. Voltra has no JavaScript API that reads them, so a configuration screen written in React Native needs its own copy of these translations.
# Managing Android Ongoing Notifications
> Start, update, and stop Android ongoing notifications from your app, including the channel, permissions, action buttons, and chip.
Voltra supports Android ongoing notifications for local, app-driven status updates such as deliveries, rides, workouts, or timers.
Use this API when you want to:
* start a persistent notification from your app
* update its content over time
* stop it when the task ends
* add action buttons that open deep links in your app
Voltra also supports remote updates if your app receives push notifications in the background and forwards the payload to the ongoing notification APIs. See [Remote Ongoing Notifications](/android/development/remote-ongoing-notifications) for the server-side rendering API and full push integration guide.
## Before you start
[Section titled “Before you start”](#before-you-start)
### 1. Enable notification manifest support
[Section titled “1. Enable notification manifest support”](#1-enable-notification-manifest-support)
Add `android.enableNotifications` to the Voltra Expo plugin config:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"enableNotifications": true
}
]
]
}
}
```
This adds the Android manifest entries required by Voltra’s notification features.
See [Plugin Configuration](/android/api/plugin-configuration#enablenotifications-optional) for details.
### 2. Create a notification channel
[Section titled “2. Create a notification channel”](#2-create-a-notification-channel)
`channelId` is required when starting an ongoing notification, and the channel must already exist.
If you use `expo-notifications`, you can create a channel like this:
```tsx
import * as Notifications from 'expo-notifications'
await Notifications.setNotificationChannelAsync('delivery_updates', {
name: 'Delivery updates',
importance: Notifications.AndroidImportance.DEFAULT,
})
```
### 3. Request notification permission on Android 13+
[Section titled “3. Request notification permission on Android 13+”](#3-request-notification-permission-on-android-13)
On Android 13 and above, posting notifications requires runtime permission.
```tsx
import {
hasAndroidNotificationPermission,
requestAndroidNotificationPermission,
} from '@use-voltra/android-client'
const granted =
(await hasAndroidNotificationPermission()) || (await requestAndroidNotificationPermission())
if (!granted) {
// Show your own UI explaining why notifications are needed.
}
```
### 4. Check the compile SDK
[Section titled “4. Check the compile SDK”](#4-check-the-compile-sdk)
Voltra needs your app to compile against Android 16 (SDK 36) or later. To show [metric notifications](#metric-notification) in the full Android 17 layout, compile against SDK 37 through [expo-build-properties](https://docs.expo.dev/versions/latest/sdk/build-properties/):
```json
{
"expo": {
"plugins": [
[
"expo-build-properties",
{
"android": {
"compileSdkVersion": 37
}
}
]
]
}
}
```
With SDK 36, everything else works the same, and metric notifications use the text-line fallback on every Android version.
## Starting a notification
[Section titled “Starting a notification”](#starting-a-notification)
Voltra provides five built-in layouts:
* `AndroidOngoingNotification.Progress` — a task with a measured amount of progress
* `AndroidOngoingNotification.BigText` — a paragraph of text
* `AndroidOngoingNotification.BigPicture` — one image, such as a delivery photo or a map snapshot
* `AndroidOngoingNotification.Inbox` — up to six short lines
* `AndroidOngoingNotification.Metric` — up to three readings, such as distance, pace, and time remaining
### Progress notification
[Section titled “Progress notification”](#progress-notification)
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
import {
startAndroidOngoingNotification,
} from '@use-voltra/android-client'
const result = await startAndroidOngoingNotification(
,
{
notificationId: 'order-123',
channelId: 'delivery_updates',
deepLinkUrl: 'myapp://orders/123',
}
)
if (result.ok) {
console.log('Started:', result.notificationId)
}
```
### Big text notification
[Section titled “Big text notification”](#big-text-notification)
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
import {
startAndroidOngoingNotification,
} from '@use-voltra/android-client'
await startAndroidOngoingNotification(
,
{
notificationId: 'match-42',
channelId: 'sports_updates',
}
)
```
### Picture notification
[Section titled “Picture notification”](#picture-notification)
Use a picture when the image carries the status: the parcel left at the door, a snapshot of the route, the section of a climb you are on.
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
import {
startAndroidOngoingNotification,
} from '@use-voltra/android-client'
await startAndroidOngoingNotification(
,
{
notificationId: 'order-123',
channelId: 'delivery_updates',
}
)
```
`picture` is required and takes the same sources as every other notification image: an `assetName` you bundled or preloaded, or inline `base64`. `largeIcon` is the thumbnail you see while the notification is collapsed.
The remaining picture props are optional, and the two that need a newer Android version are ignored on older devices rather than failing the update:
| Prop | Effect | Needs |
| --------------------------- | ------------------------------------------------------------------------------------------ | ------------------- |
| `showPictureWhenCollapsed` | Fills the collapsed notification with the picture instead of showing it only when expanded | Android 12 or later |
| `pictureContentDescription` | Screen reader label for the picture | Android 12 or later |
| `bigLargeIcon` | Thumbnail shown while expanded, replacing `largeIcon` | - |
| `hideLargeIconWhenExpanded` | Shows the `largeIcon` thumbnail only while collapsed | - |
| `summaryText` | Short trailing line, such as an order number | - |
**How large should the image be?** Android draws an expanded picture at 416dp by 284dp at most. Voltra hands over at most 1024 px on the long edge for a picture and 256 px for an icon, so a full-resolution camera photo buys you no extra detail and costs your app memory and decode time. A bundled drawable is handed to the system as a resource on Android 12 and later, which resizes it; on Android 11 and older Voltra draws it out to those same limits itself, so a small vector fills the picture slot on every version.
**A picture notification cannot become a Live Update.** Android 16 promotes ongoing notifications with the standard, big text, call, and progress styles; `requestPromotedOngoing` is accepted for this layout and has no effect on it. If you need promotion and artwork, use `largeIcon` on a `Progress` notification.
### Lines notification
[Section titled “Lines notification”](#lines-notification)
Use lines when the status is a short list: the stops left on a route, the files still uploading, the steps of an order.
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
import {
startAndroidOngoingNotification,
} from '@use-voltra/android-client'
await startAndroidOngoingNotification(
,
{
notificationId: 'route-7',
channelId: 'delivery_updates',
}
)
```
`lines` is required and holds one to six non-empty strings. Android shows six lines at most, so the renderer rejects a seventh instead of letting it disappear from the notification.
`text` is the collapsed line. If you leave it out, it takes the value of the first line.
A line holds text only. There is no per-line icon, check mark, or color, so a checklist reads as a list of sentences. If you need the lines to flow as one paragraph instead, use `BigText` with newlines.
### Metric notification
[Section titled “Metric notification”](#metric-notification)
Show up to three readings — distance, pace, time remaining — instead of a progress bar or a text body:
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
import {
startAndroidOngoingNotification,
} from '@use-voltra/android-client'
await startAndroidOngoingNotification(
,
{
notificationId: 'run-7',
channelId: 'activity_updates',
}
)
```
* Pass 1 to 3 metrics, and keep each `label` between 1 and 10 characters.
* A plain number is a reading and a plain string is text. `unit` next to a number is shorthand for the unit of that reading, so `{ label: 'Dist', value: 5.2, unit: 'km' }` is the same as passing the value as `{ type: 'float', value: 5.2, unit: 'km' }`.
* `criticalMetric` is the index of the most important reading. Android doesn’t highlight it in the notification; it can show that reading in the [status bar chip](#showing-a-chip-in-the-status-bar) of a promoted notification. It defaults to the first reading. `semanticStyle` tints every metric: `'info'`, `'safe'`, `'caution'`, `'danger'`, or the default `'unspecified'`.
* Values that change on their own: `{ type: 'timer', endsAt }` counts down to a moment and `{ type: 'stopwatch', startedAt }` counts up from it — each accepts a `Date` or an epoch timestamp, and an optional `format: 'chronometer'`. Frozen durations are `{ type: 'pausedTimer', remainingMillis }` and `{ type: 'pausedStopwatch', elapsedMillis }`. `{ type: 'time', value: '18:40' }` shows a clock time, and `{ type: 'float', value: 5.2, fractionDigits: 1 }` (with optional `min`/`max`) controls how a reading is formatted.
The full metric layout needs Android 17 and later, and an app that [compiles against SDK 37](#4-check-the-compile-sdk). Otherwise the notification posts normally and the readings appear as a text line (`Dist 5.2km, Pace 5:30, ETA 9:52`), and the result carries `styleFallback: 'standard'` so you can tell. Your server can send the same metric payload to every device without knowing their versions. Time-driven values are rendered when the notification is posted, so an `updateAndroidOngoingNotification` call every minute keeps the text line fresh on those devices.
Unlike the other layouts, a metric notification can be promoted to a Live Update without a `title`.
## Presentation options
[Section titled “Presentation options”](#presentation-options)
Everything that says how the system should treat the notification goes in the options, next to `channelId`. Everything that says what the notification means right now goes in the content, as props on the layout component, such as `AndroidOngoingNotification.Progress`.
```tsx
await startAndroidOngoingNotification(
,
{
notificationId: 'ride-44',
channelId: 'ride_updates',
visibility: 'private',
color: '#1E88E5',
category: 'navigation',
timeoutMs: 30 * 60 * 1000,
group: 'rides',
sortKey: '2026-09-22T12:00',
}
)
```
| Option | Values | Default | Applies on | After an update that omits it |
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------ | ----------------------------- |
| `visibility` | `'public'`, `'private'`, `'secret'` | system default, `'private'` | all versions | kept |
| `color` | any static color string: `'#1E88E5'`, `'rgb(30, 136, 229)'`, `'crimson'` | none | all versions | kept |
| `category` | `'progress'`, `'navigation'`, `'transport'`, `'service'`, `'status'`, `'workout'`, `'stopwatch'`, `'location_sharing'` | from the content: a progress notification reports `'progress'`, a big text notification reports none | all versions | kept |
| `timeoutMs` | milliseconds as a whole number | none, the notification stays until you stop it | Android 8.0+ | kept and the timer restarts |
| `localOnly` | `true` to keep it off Wear and Android Auto | `false` | all versions | kept |
| `group`, `sortKey` | group key, and the order inside it | none | all versions | kept |
| `allowSystemGeneratedContextualActions` | `false` to stop the system adding its own actions, such as a directions chip | platform default, `true` | Android 10+ | kept |
Notes on individual options:
* `visibility` decides what the lock screen shows. `'secret'` hides the notification entirely there. Use `'private'` together with `publicVersion` to show a short copy of your own.
* `color` is an accent: the system tints the notification with it, and shows it as background only for styles that support that. A color the device cannot resolve, such as a theme token, rejects the call rather than posting without a color.
* `category` overrides what Voltra derives from your content, and does not change the channel.
* `timeoutMs` is applied on every post, so each update restarts the countdown and a notification that stops being updated eventually disappears on its own. Once the system removes it, `getAndroidOngoingNotificationStatus()` reports it as no longer active, and starting that `notificationId` again needs `stopAndroidOngoingNotification()` first, the same as after a swipe. On Android 7.x and older the value is kept but not applied.
* `group` puts the notification in the bundle the system builds from notifications sharing the key. Voltra does not post a group summary of its own.
### Lock-screen copy
[Section titled “Lock-screen copy”](#lock-screen-copy)
`publicVersion` is a prop on the content, not an option: it is text, so an update replaces it, and an update that leaves it out posts without one.
```tsx
```
The copy is what the lock screen shows when `visibility` hides the real content. It carries the title and text you give it and nothing else: no progress, no action buttons.
### Timestamps
[Section titled “Timestamps”](#timestamps)
`showWhen` (default `true`, and `false` when the payload carries no timestamp) hides the time the notification shows while keeping the timestamp for sorting and timeouts. Set it to `false` for an absolute deadline, so the notification stops claiming it is “5 minutes ago”. To count down to `when` instead, use `chronometer="countDown"` (see [Showing a chip in the status bar](#showing-a-chip-in-the-status-bar)).
```tsx
```
### Changing a presentation option
[Section titled “Changing a presentation option”](#changing-a-presentation-option)
An update keeps every presentation option you do not mention. To change one, send it; to go back to the platform default, send `null`:
```tsx
await updateAndroidOngoingNotification('ride-44', content, {
channelId: 'ride_updates',
color: '#000000', // replace
timeoutMs: null, // stop timing this one out
// group and sortKey left out: they keep their stored values
})
```
The pre-existing options (`smallIcon`, `deepLinkUrl`, `requestPromotedOngoing`, `fallbackBehavior`) behave as before: leaving one out reuses the stored value, and there is no way to clear them.
`upsertAndroidOngoingNotification()` takes the same options, and the `null` clears mean the same thing there when the call ends up updating. When it ends up starting, nothing is stored to clear and the calls behave like a start.
### Letting one update make a sound
[Section titled “Letting one update make a sound”](#letting-one-update-make-a-sound)
An ongoing notification alerts when it is first posted and is silent afterwards. `alert` is an update option that lets one update alert again:
```tsx
await updateAndroidOngoingNotification('ride-44', content, {
channelId: 'ride_updates',
alert: true,
})
```
It applies to that post only and is never stored, so the next update is quiet again. Whether it audibly alerts is still decided by the channel you created: a channel on low importance stays silent however you set `alert`. `upsertAndroidOngoingNotification()` takes it too: it alerts when that call ends up updating, and a first post always alerts anyway.
## Updating a notification
[Section titled “Updating a notification”](#updating-a-notification)
Use the same `notificationId` to update an existing notification.
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
import {
updateAndroidOngoingNotification,
} from '@use-voltra/android-client'
await updateAndroidOngoingNotification(
'order-123',
)
```
`updateAndroidOngoingNotification()` returns a result object. If the notification no longer exists, it returns `reason: 'not_found'` or `reason: 'dismissed'`.
## Starting or updating with one call
[Section titled “Starting or updating with one call”](#starting-or-updating-with-one-call)
If your app may re-enter the same flow multiple times, `upsertAndroidOngoingNotification()` can be easier than separate start/update logic.
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
import {
upsertAndroidOngoingNotification,
} from '@use-voltra/android-client'
const result = await upsertAndroidOngoingNotification(
,
{
notificationId: 'workout-1',
channelId: 'fitness_updates',
}
)
if (result.ok) {
console.log(result.action) // 'started' or 'updated'
}
```
This API is especially useful for remote updates, where the same incoming push may need to create the notification the first time and update it later. It takes the same options as the other two calls: a presentation option sent as `null` clears the stored value and `alert` makes the update branch alert, both only when the call ends up updating.
## Stopping a notification
[Section titled “Stopping a notification”](#stopping-a-notification)
```tsx
import { stopAndroidOngoingNotification } from '@use-voltra/android-client'
await stopAndroidOngoingNotification('order-123')
```
To dismiss every active Voltra ongoing notification at once:
```tsx
import { endAllAndroidOngoingNotifications } from '@use-voltra/android-client'
await endAllAndroidOngoingNotifications()
```
## Hook API
[Section titled “Hook API”](#hook-api)
For React screens and flows, use `useAndroidOngoingNotification()`.
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
import { useAndroidOngoingNotification } from '@use-voltra/android-client'
function DeliveryNotification({ orderId, etaMinutes }) {
const { start, update, end, isActive } = useAndroidOngoingNotification(
,
{
notificationId: `order-${orderId}`,
channelId: 'delivery_updates',
deepLinkUrl: `myapp://orders/${orderId}`,
autoStart: true,
autoUpdate: true,
}
)
return null
}
```
The hook returns:
* `start()`
* `update()`
* `end()`
* `isActive`
Use `autoStart` to create the notification when the component mounts, and `autoUpdate` to refresh it when the JSX content changes.
## Action buttons
[Section titled “Action buttons”](#action-buttons)
You can add action buttons as children of any layout.
```tsx
import { AndroidOngoingNotification } from '@use-voltra/android'
```
Action buttons currently:
* open the provided deep link
* can be used with `Progress`, `BigText`, `BigPicture`, `Inbox`, and `Metric`
* support an optional `icon`
```tsx
```
Android may not show action icons in the standard notification UI, so treat them as optional enhancement rather than a guaranteed visual element.
## Main tap behavior
[Section titled “Main tap behavior”](#main-tap-behavior)
Use `deepLinkUrl` in the start or update options to control what happens when the user taps the main notification body:
```tsx
await startAndroidOngoingNotification(content, {
notificationId: 'order-123',
channelId: 'delivery_updates',
deepLinkUrl: 'myapp://orders/123',
})
```
This is separate from action button deep links.
## Showing a chip in the status bar
[Section titled “Showing a chip in the status bar”](#showing-a-chip-in-the-status-bar)
On Android 16 and above, a promoted ongoing notification shows a chip in the status bar. You fill it with either a short text or a clock:
```tsx
```
* `shortCriticalText` shows a short text in the chip. Keep it to about 7 characters; the chip is at most 96dp wide and longer text is cut.
* `chronometer: true` shows elapsed time since `when`, counting up. `'countUp'` means the same as `true`.
* `chronometer: 'countDown'` shows the time remaining until `when`, counting down — the right choice for an ETA, a timer, or a parking meter. It requires `when`; rendering throws without it.
When you set several of these, the chip picks one in this order:
1. `shortCriticalText` (an empty string means no chip text at all)
2. for a metric notification on Android 17 and later, the value of the `criticalMetric`
3. time derived from `when` — the chronometer when `chronometer` is set, otherwise the remaining time
## Status and capability helpers
[Section titled “Status and capability helpers”](#status-and-capability-helpers)
Use these helpers to adapt your UI to the device state:
```tsx
import {
canPostPromotedAndroidNotifications,
getAndroidOngoingNotificationCapabilities,
getAndroidOngoingNotificationStatus,
openAndroidNotificationSettings,
openAndroidPromotedNotificationSettings,
} from '@use-voltra/android-client'
const status = getAndroidOngoingNotificationStatus('order-123')
const capabilities = getAndroidOngoingNotificationCapabilities()
const canPostPromoted = canPostPromotedAndroidNotifications()
if (!capabilities.notificationsEnabled) {
await openAndroidNotificationSettings()
}
```
Useful values include:
* `status.isActive`
* `status.isDismissed`
* `status.isPromoted` and `status.hasPromotableCharacteristics` — set on Android 16 and above, `undefined` below it
* `capabilities.notificationsEnabled`
* `capabilities.supportsPromotedNotifications`
* `capabilities.canPostPromotedNotifications`
* `capabilities.canRequestPromotedOngoing`
`openAndroidNotificationSettings()` opens your app’s channel list. When the user has turned Live Updates off for your app (`canPostPromotedNotifications === false`), use `openAndroidPromotedNotificationSettings()` to open the page where they turn them back on. It resolves `true` when the Live Updates page opened and `false` when the regular notification settings opened instead, because the device has no such page.
## When posting fails
[Section titled “When posting fails”](#when-posting-fails)
Start, update, and upsert reject with a code instead of posting something broken:
| Code | What happened | What to do |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------- |
| `VOLTRA_NOTIFICATION_CHANNEL_REQUIRED` | No `channelId` was given | Pass `channelId` in the start options |
| `VOLTRA_NOTIFICATION_CHANNEL_NOT_FOUND` | The channel was never created — Android drops such notifications silently | Create the channel before posting |
| `VOLTRA_NOTIFICATION_INVALID_PAYLOAD` | The payload is malformed or breaks a rule (e.g. a remote payload with `chronometerCountDown` but no `when`) | Fix the payload |
| `VOLTRA_NOTIFICATION_INVALID_OPTIONS` | An option cannot be applied on this device (e.g. a `color` that is a theme token rather than a static color) | Pass a static color such as `'#1E88E5'` |
| `VOLTRA_NOTIFICATION_NOT_PROMOTABLE` | Promotion was requested with `fallbackBehavior: 'error'` and the notification is not eligible | Read the reasons in the message (see below) |
| `VOLTRA_NOTIFICATION_INTERNAL_ERROR` | An unexpected device failure | Retry; if it persists, file an issue with the message |
A dismissed notification is different: updates return `ok: false, reason: 'dismissed'` and nothing is re-posted. If your flow legitimately restarts after a dismissal, start a new notification instead of updating.
## Promoted ongoing notifications
[Section titled “Promoted ongoing notifications”](#promoted-ongoing-notifications)
On Android 16 and above, eligible ongoing notifications can be promoted to Live Updates: they expand into the status bar and show up on the lock screen and home screen. Pass `requestPromotedOngoing: true` to ask for it:
```tsx
const result = await startAndroidOngoingNotification(content, {
notificationId: 'ride-44',
channelId: 'ride_updates',
requestPromotedOngoing: true,
})
```
You don’t need the user to have turned Live Updates on first. Voltra records the request on every post, so when the user enables Live Updates in Settings, the next update is promoted without any change in your app.
### Reading why a notification is not promoted
[Section titled “Reading why a notification is not promoted”](#reading-why-a-notification-is-not-promoted)
When you request promotion, a successful result carries a `promotion` object:
```tsx
if (result.ok && result.promotion) {
console.log(result.promotion.eligible, result.promotion.reasons)
}
```
* `promotion.requested` — always `true` when the object is present
* `promotion.eligible` — `true` when the notification can be promoted
* `promotion.reasons` — what stands in the way, as a list
* `promotion.hasPromotableCharacteristics` — the platform’s own verdict on the built notification; only set on Android 16 and above
| Reason | Meaning |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `unsupported_api_level` | The device runs below Android 16 |
| `permission_not_declared` | `enableNotifications` is not on, so `POST_PROMOTED_NOTIFICATIONS` is missing from the manifest. Android 16 QPR2 and later only; Android 16.0 has no such permission |
| `notifications_disabled` | Notifications are turned off for your app |
| `promotion_disabled_by_user` | The user turned Live Updates off for your app |
| `channel_importance_min` | The channel’s importance is `MIN`; use at least `LOW` |
| `missing_title` | The notification has no `title`; promotion requires one |
| `not_promotable` | The platform rejected the built notification for another reason |
With the default `fallbackBehavior: 'standard'`, a notification that cannot be promoted is still posted as a normal ongoing notification and you read the reasons from the result. With `fallbackBehavior: 'error'`, the call rejects with `VOLTRA_NOTIFICATION_NOT_PROMOTABLE`, the message lists the reasons, and nothing is posted.
### Checking before you post
[Section titled “Checking before you post”](#checking-before-you-post)
`checkAndroidOngoingNotificationPromotion()` answers the same questions for a payload without posting it or recording anything:
```tsx
import { checkAndroidOngoingNotificationPromotion } from '@use-voltra/android-client'
const check = await checkAndroidOngoingNotificationPromotion(content, {
channelId: 'ride_updates',
})
if (!check.eligible) {
console.warn('Would not promote:', check.reasons)
}
```
Only `Progress` and `BigText` can be promoted. Android decides which layouts qualify, and a `BigPicture` or `Inbox` notification stays a standard ongoing notification even when you ask for promotion: the call succeeds, `requestPromotedOngoing` is remembered, and nothing is promoted. Check `status.hasPromotableCharacteristics` if you want to show the user why.
## What Voltra does not cover
[Section titled “What Voltra does not cover”](#what-voltra-does-not-cover)
Some Android notification templates look like ongoing status updates and are not one. Voltra does not build them:
* **Conversations (`MessagingStyle`)** — needs `Person` objects, a conversation title, a direct reply field, and a long-lived shortcut on Android 11 and later. Use `expo-notifications` or Notifee.
* **Playback controls (`MediaStyle`)** — needs a `MediaSession` token, which a media library owns and builds the notification from. Use Media3, `expo-notifications`, or Notifee.
* **Bubbles** — need a pushed long-lived shortcut and a conversation, and Voltra does not own your host activity or your shortcuts. Use `expo-notifications` or Notifee.
* **Full-screen intents** — an interruption, not a status. Android 14 grants `USE_FULL_SCREEN_INTENT` by default only to calling and alarm apps, and Google Play revokes it for others. Use `expo-notifications` or Notifee when you genuinely need one.
A common combination is a Voltra ongoing notification for the status plus one of those templates posted through another library.
## Current limitations
[Section titled “Current limitations”](#current-limitations)
* Remote updates require your own push delivery and background task integration. See [Remote Ongoing Notifications](/android/development/remote-ongoing-notifications).
* A push carrying a `bigPicture` or `inbox` payload reaches only app builds that know those payload kinds. See [Compatibility](/android/development/remote-ongoing-notifications#compatibility).
* Your app must create the Android notification channel before starting a notification.
* Notification permission still needs to be requested by your app on Android 13+.
* Action buttons open deep links. They are not a JavaScript event system.
* Some Android notification fields stay out of the API on purpose:
* Badge count and badge icon. The launcher dot belongs to the channel your app creates, and a count makes no sense for a single ongoing item.
* Group summary. Voltra posts no summary, and requesting one disqualifies the notification from promoted presentation.
* A color background on every notification (`colorized`). It does nothing for these styles outside a foreground service, which Voltra does not run, and it also disqualifies promoted presentation.
* Tapping to auto-dismiss. The ongoing lifecycle belongs to `stopAndroidOngoingNotification()`, and a tap-dismiss would leave the notification recorded as active while it is already gone.
* Sound, vibration, lights and their defaults, and importance. All of them are channel settings since Android 8.0.
* Priority below Android 8.0. Deprecated, and a second API level to document for the same result.
* A settings line under the notification, which needs a notification-preferences intent filter in your manifest, and the deprecated extra content-info line.
* A ticker, which older accessibility services read while TalkBack reads the title and text anyway.
* Whether a grouped notification alerts with its group. That only means something together with a summary Voltra does not post.
# Native modifiers
> Apply Jetpack Glance modifiers that style does not cover, such as semantics and appWidgetBackground, with the modifiers prop.
Native modifiers apply Jetpack Glance modifiers that `style` does not cover, such as `semantics`, `appWidgetBackground` and day/night backgrounds, to any Voltra Android component.
Use them in Dynamic Widgets
Native modifiers are meant for [Dynamic Widgets](/android/development/dynamic-widgets). [Payload widgets](/android/development/server-driven-widgets) accept them too, but every modifier is stored and sent with every update, which makes the payload larger.
## Add a modifier
[Section titled “Add a modifier”](#add-a-modifier)
Pass a list of modifiers from `VoltraAndroid.modifiers` to the `modifiers` prop:
```tsx
import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android'
const { appWidgetBackground, background, semantics, visibility } = VoltraAndroid.modifiers
export default function PortfolioWidget({ balance, stale }: { balance: string; stale: boolean }) {
return (
{balance}Updating…
)
}
```
`VoltraAndroid` components only accept modifiers from `VoltraAndroid.modifiers`. Passing a modifier from `Voltra.modifiers`, or a plain object, is a TypeScript error.
## How modifiers combine with `style`
[Section titled “How modifiers combine with style”](#how-modifiers-combine-with-style)
Glance applies modifiers after `style`, and it does not care about their order:
* Where a modifier and a `style` property set the same thing, such as a width or a background, the modifier wins. There are three exceptions:
* `style.flex` on a child of a `Row` or `Column` replaces the child’s `width`, `height`, `size`, `fillMax…` and `wrapContent…` modifiers along the row or column.
* A `Scaffold` always fills the widget and draws its own background and rounded corners, so size modifiers, `background` and `cornerRadius` on the `Scaffold` itself have no effect. Use its `backgroundColor` prop instead.
* `FilledButton`, `OutlineButton`, `CircleIconButton` and `SquareIconButton` draw their own background and rounded corners, so `background` and `cornerRadius` on them have no effect. Use their color props instead.
* `Chart`, `ArcProgressIndicator` and `Text` with `renderAsBitmap` take their size from the size modifiers. `wrapContentWidth`, `wrapContentHeight` and `wrapContentSize` on them keep their default size.
* Padding adds up. `style={{ padding: 8 }}` with `modifiers={[padding(8)]}` gives 16 dp.
* Using the same modifier twice keeps the last one, except for `padding` and `absolutePadding`, which add up.
## Available modifiers
[Section titled “Available modifiers”](#available-modifiers)
| Modifier | What it does |
| --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `padding(dp \| { all?, horizontal?, vertical?, start?, top?, end?, bottom? })` | Adds padding that follows the layout direction. |
| `absolutePadding(dp \| { all?, horizontal?, vertical?, left?, top?, right?, bottom? })` | Adds padding that ignores the layout direction. |
| `width(dp)`, `height(dp)`, `size(dp \| { width, height })` | Sets a fixed size. |
| `fillMaxWidth()`, `fillMaxHeight()`, `fillMaxSize()` | Fills the available space. |
| `wrapContentWidth()`, `wrapContentHeight()`, `wrapContentSize()` | Sizes to the content. |
| `background(color \| { day, night })` | Fills the background with a color, an `AndroidDynamicColors` token, or separate light and dark colors. |
| `cornerRadius(dp)` | Rounds the corners. Android 12+. |
| `visibility('visible' \| 'invisible' \| 'gone')` | Shows the component, hides it but keeps its space, or removes it from layout. |
| `semantics({ contentDescription?, testTag? })` | Sets the text read by accessibility services. `testTag` is only visible to Glance’s own test APIs, not to UI tests of the widget on a device. At least one of the two is required. |
| `appWidgetBackground()` | Marks the widget background so the launcher can animate it when the widget opens your app. Use it once, on the outermost component. If several components set it, only one keeps it. Inside a widget with a `Scaffold`, it is skipped because the `Scaffold` marks its own background. Android 12+. |
For light and dark colors, `background({ day, night })` takes two static color strings; `AndroidDynamicColors` tokens are a type error there. To follow the device’s Material You theme instead, pass an `AndroidDynamicColors` token. See [Dynamic Colors](/android/development/dynamic-colors).
Native modifiers do not handle taps. To open your app from a component, use its `deepLinkUrl` prop.
## Troubleshooting
[Section titled “Troubleshooting”](#troubleshooting)
**Corners are not rounded.** `cornerRadius` only works on Android 12 (API 31) and later. Older versions render square corners.
**A modifier has no effect.** An unknown modifier or an invalid value, such as a color string that does not parse or `day` and `night` given as `AndroidDynamicColors` tokens, is skipped. Run `adb logcat -s VoltraModifiers` to see which one and why.
**The launcher does not animate the widget when it opens the app.** `appWidgetBackground` only works on Android 12 (API 31) and later. Older versions open the app without the animation.
**The padding is larger than expected.** Glance adds `padding` modifiers to `style.padding`. Remove one of them.
# Querying Active Widgets
> Find every Voltra widget instance placed on the Android Home Screen, with its appWidgetId, widget type, and size, using getActiveWidgets.
On Android, you can detect every active instance of your widgets currently placed on the Home Screen. This is particularly useful for Android since each widget instance can have different dimensions and a unique `appWidgetId`.
## getActiveWidgets API
[Section titled “getActiveWidgets API”](#getactivewidgets-api)
The `getActiveWidgets` function returns a promise that resolves to an array of all active widget instances for your app.
```typescript
import { getActiveWidgets } from '@use-voltra/android-client'
async function checkAndroidWidgets() {
const activeWidgets = await getActiveWidgets()
console.log(`Found ${activeWidgets.length} active widget instances`)
activeWidgets.forEach(widget => {
console.log(`- Widget: ${widget.widgetType}`)
console.log(` Placement: ${widget.appWidgetId}`)
console.log(` Size: ${widget.width}x${widget.height}dp`)
})
}
```
### WidgetInfo Object
[Section titled “WidgetInfo Object”](#widgetinfo-object)
Each object in the returned array contains:
| Property | Type | Description |
| ------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `widgetType` | `string` | The Voltra widget ID as defined in your Expo config plugin (e.g., `"weather"`). |
| `appWidgetId` | `number` | The Android identifier of this placement. Pass it to the [per-instance configuration APIs](/android/development/dynamic-widgets#configure-each-placed-widget-separately) to give one placement its own values. |
| `providerClassName` | `string` | The full class name of the widget provider (e.g., `".widget.VoltraWidget_weatherReceiver"`). |
| `label` | `string` | The human-readable label shown in the Android widget picker. |
| `width` | `number` | The current width of the widget instance in dp. |
| `height` | `number` | The current height of the widget instance in dp. |
| `name` | `string` | **Deprecated.** Renamed to `widgetType`, which says what it holds. Same value. |
| `widgetId` | `number` | **Deprecated.** Renamed to `appWidgetId`. It is the Android placement identifier, not the Voltra widget ID that `widgetId` names everywhere else in this package. Same value. |
The same widget placed twice appears twice, with one entry per placement and a different `appWidgetId` on each.
# Remote Ongoing Notifications (Android)
> Update Android ongoing notifications from push messages handled in a background task, with server-side rendering support.
Voltra can apply remote updates to an ongoing notification when your app receives a push notification and handles it in a background task. This builds on the local lifecycle API — see [Managing Ongoing Notifications](/android/development/managing-ongoing-notifications) first for creating the notification channel, requesting permission, and the start/update/stop APIs.
## Server-side rendering support
[Section titled “Server-side rendering support”](#server-side-rendering-support)
Voltra provides a server-side API for converting JSX into the semantic payload used by Android ongoing notifications.
Use these APIs only in server-side or backend code. Do not import them from your React Native app runtime.
Use `@use-voltra/android-server`.
The main renderer APIs are:
* `renderAndroidOngoingNotificationPayloadToJson()` returns an object
* `renderAndroidOngoingNotificationPayload()` returns a JSON string
This API only renders the payload. Your server still needs to send that payload through your push provider, and your app still needs a background task that calls `upsertAndroidOngoingNotification()` or `stopAndroidOngoingNotification()` when the push arrives.
## Register a background notification task
[Section titled “Register a background notification task”](#register-a-background-notification-task)
You should use `expo-notifications` together with `expo-task-manager` to process real push notifications and update ongoing notifications in the background.
Register a background task early in app startup, so incoming pushes can update or stop an ongoing notification even when the app is backgrounded:
```tsx
import * as Notifications from 'expo-notifications'
import * as TaskManager from 'expo-task-manager'
const TASK_NAME = 'voltra-ongoing-notification-task'
TaskManager.defineTask(TASK_NAME, async ({ data, error }) => {
if (error) {
return
}
// Read your push payload and call Voltra APIs here.
})
await Notifications.registerTaskAsync(TASK_NAME)
```
## The remote update flow
[Section titled “The remote update flow”](#the-remote-update-flow)
The end-to-end flow is:
1. Your server renders Voltra JSX into an Android ongoing-notification payload.
2. Your server sends a high-priority push notification.
3. The push `data` contains a `voltraOngoingNotification` object.
4. Your background task parses that object.
5. The task calls `upsertAndroidOngoingNotification()` or `stopAndroidOngoingNotification()`.
### 1. Render the payload on your server
[Section titled “1. Render the payload on your server”](#1-render-the-payload-on-your-server)
Use `renderAndroidOngoingNotificationPayloadToJson()` when preparing a payload on your server or in app tooling:
```tsx
import {
AndroidOngoingNotification,
renderAndroidOngoingNotificationPayloadToJson,
} from '@use-voltra/android-server'
const payload = renderAndroidOngoingNotificationPayloadToJson(
)
```
Then send that payload inside a push message.
A picture works the same way:
```tsx
const payload = renderAndroidOngoingNotificationPayloadToJson(
)
```
```json
{
"v": 1,
"kind": "bigPicture",
"title": "Parcel delivered",
"text": "Left at the front door",
"picture": {
"assetName": "delivery_photo_123"
},
"summaryText": "Order 123"
}
```
An `inbox` payload carries its lines in the same shape:
```tsx
const payload = renderAndroidOngoingNotificationPayloadToJson(
)
```
```json
{
"v": 1,
"kind": "inbox",
"title": "3 stops remaining",
"text": "12 Oak Street",
"lines": ["12 Oak Street", "4 Elm Road", "Depot"],
"summaryText": "Route 7"
}
```
If your push provider expects strings for nested payload data, use `renderAndroidOngoingNotificationPayload()` instead and send the JSON string directly.
### 2. Send the payload through your push provider
[Section titled “2. Send the payload through your push provider”](#2-send-the-payload-through-your-push-provider)
Your payload’s `data.voltraOngoingNotification` should contain:
* `notificationId`: the stable notification identifier
* `operation`: `'upsert'` or `'stop'`
* `options`: start options such as `channelId`, `smallIcon`, `deepLinkUrl`, `requestPromotedOngoing`, or `fallbackBehavior`; the presentation options `visibility`, `color`, `category`, `timeoutMs`, `localOnly`, `group`, `sortKey`, and `allowSystemGeneratedContextualActions`; and `alert`
* `payload`: the Voltra semantic payload for `'upsert'`
Presentation options are the app’s decision, so send them only if your push builder is allowed to make it. An upsert whose `options` leaves them out changes nothing about how the running notification is presented, and a presentation option sent as `null` clears the stored value when the push updates an existing notification. `alert: true` makes an updating push alert the way a first post does; a push that starts a notification always alerts anyway.
The payload itself can carry `publicVersion`, `showWhen`, and `chronometerCountDown`, like any other content field.
Example Expo push request:
```json
{
"to": "ExponentPushToken[project-token]",
"priority": "high",
"data": {
"voltraOngoingNotification": "{\"notificationId\":\"order-123\",\"operation\":\"upsert\",\"options\":{\"channelId\":\"delivery_updates\",\"deepLinkUrl\":\"myapp://orders/123\",\"requestPromotedOngoing\":true,\"visibility\":\"private\",\"color\":\"#1E88E5\",\"category\":\"navigation\",\"timeoutMs\":1800000,\"group\":\"deliveries\"},\"payload\":{\"v\":1,\"kind\":\"progress\",\"title\":\"Driver is approaching\",\"text\":\"2 stops away\",\"value\":80,\"max\":100,\"when\":1758540000000,\"showWhen\":false,\"publicVersion\":{\"title\":\"Delivery in progress\",\"text\":\"Unlock to see the driver\"}}}"
}
}
```
Voltra accepts either an object or a JSON string for `data.voltraOngoingNotification`. Stringifying it is often the safest option when sending through push providers.
To stop the notification remotely, send the same `notificationId` with `operation: "stop"` and omit `payload`.
**Pictures in a remote payload.** A `bigPicture` or `largeIcon` entry in a push payload should reference an image the app can already find, through `assetName` for a bundled or preloaded image. Android push providers cap the data of a message well below the size of a photo — Firebase caps a data message at 4096 bytes — so a `base64` picture does not fit. Download the image on the device with `preloadImages()` from `@use-voltra/android-client`, see [Image Preloading](/android/development/image-preloading), and send its key.
### 3. Apply the payload in your background task
[Section titled “3. Apply the payload in your background task”](#3-apply-the-payload-in-your-background-task)
```tsx
import * as Notifications from 'expo-notifications'
import * as TaskManager from 'expo-task-manager'
import {
stopAndroidOngoingNotification,
upsertAndroidOngoingNotification,
} from '@use-voltra/android-client'
const TASK_NAME = 'voltra-ongoing-notification-task'
const parseMessage = (value: unknown) => {
if (typeof value === 'string') {
try {
return JSON.parse(value)
} catch {
return null
}
}
return value
}
TaskManager.defineTask(TASK_NAME, async ({ data, error }) => {
if (error) {
return
}
const message = parseMessage(data?.voltraOngoingNotification)
if (!message || typeof message !== 'object') {
return
}
const notificationId = typeof message.notificationId === 'string' ? message.notificationId : null
if (!notificationId) {
return
}
if (message.operation === 'stop') {
await stopAndroidOngoingNotification(notificationId)
return
}
if (!message.payload || !message.options?.channelId) {
return
}
await upsertAndroidOngoingNotification(message.payload, {
...message.options,
notificationId,
})
})
await Notifications.registerTaskAsync(TASK_NAME)
```
When the options request promotion, a successful upsert result carries `result.promotion.reasons` — the machine-readable list of what would block promotion on this device — so your handler can log it. A payload that breaks a rule (`kind` unknown, malformed JSON, a countdown without `when`) rejects with a `VOLTRA_NOTIFICATION_...` code instead of posting something broken, and a channel that was never created rejects too. Wrap the call in `try`/`catch` if you want to react to those.
`AndroidOngoingNotification.Metric` renders server-side too, so one metric payload fits every device: below Android 17 it posts as a standard notification whose text line joins the readings, and the upsert result then carries `styleFallback: 'standard'`.
### Channel setup for remote updates
[Section titled “Channel setup for remote updates”](#channel-setup-for-remote-updates)
Your background task should ensure that the target notification channel exists before calling `upsertAndroidOngoingNotification()`. Create the channel on startup, and also ensure it exists again inside the background handler.
## Compatibility
[Section titled “Compatibility”](#compatibility)
The client chooses its parser by the `kind` field, so your server and the installed app have to agree on the available kinds. A build that does not know `bigPicture` or `inbox` fails to parse that payload rather than falling back to a layout it does know, and the update is reported as a failure. Serve `progress` or `bigText` to older installs, which means a server that picks a layout per device needs the app version that device reports.
# Server-driven widgets
> Have Android widgets fetch fresh content from your server with WorkManager on a schedule, without the user opening the app.
Server-driven widgets allow your Android Home Screen widgets to periodically fetch fresh content from a remote server—without the user opening the app. This is powered by WorkManager, which handles scheduling, retries, and network constraints automatically.
Before you start, make sure the widget is registered in the Voltra plugin config and plan to rebuild the native app after adding or changing server-driven widget settings.
Android semantic color tokens from [`AndroidDynamicColors`](/android/development/dynamic-colors) work in server-rendered widgets too, so your backend can return dynamic Material roles instead of fixed hex values.
## How it works
[Section titled “How it works”](#how-it-works)
1. You configure a `serverUpdate` URL in your Android widget’s plugin config
2. WorkManager runs a periodic background task at the configured interval
3. Your server renders Voltra JSX components into a JSON payload
4. The worker parses the payload and pushes a `RemoteViews` update to the widget
Your app doesn’t need to be running. WorkManager handles everything in the background.
A widget that also has an `entry` works the other way round: your server returns plain JSON data and the widget renders it on the device, so the backend can be written in any language. See [Returning data instead of UI](#returning-data-instead-of-ui).
## Plugin configuration
[Section titled “Plugin configuration”](#plugin-configuration)
Add the `serverUpdate` option to your Android widget in `app.json` or `app.config.js`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"widgets": [
{
"id": "dynamic_weather",
"displayName": "Dynamic Weather",
"description": "Weather with live server updates",
"targetCellWidth": 2,
"targetCellHeight": 1,
"serverUpdate": {
"url": "https://api.example.com/widgets/render",
"intervalMinutes": 60
}
}
]
}
]
]
}
}
```
**`serverUpdate` options:**
* `url`: The endpoint the widget fetches from. Voltra appends `widgetId`, `platform`, `theme`, and `locale` query parameters automatically (e.g. `?widgetId=dynamic_weather&platform=android&theme=dark&locale=en-US`). Optional — leave it out to mark the widget server-driven and supply the URL after login with [`setWidgetServerUpdate`](#changing-settings-at-runtime).
* `intervalMinutes`: How often the widget fetches updates. Defaults to `60`, or `15` for a widget that has an `entry`. The minimum is 15 minutes.
* `refresh`: Whether to show a native refresh button in the top-right corner of the widget. When tapped, triggers an immediate server fetch. Defaults to `false`.
After updating plugin configuration, run `npx expo prebuild` if you’re using Continuous Native Generation, then rebuild the app so the generated native widget code picks up the new server update settings.
Note
On the Android emulator, use `10.0.2.2` instead of `localhost` to reach the host machine. Real devices need the host’s LAN IP address.
## Building the server
[Section titled “Building the server”](#building-the-server)
Voltra provides widget server handlers for the common runtime styles. Use `createAndroidWidgetUpdateHandler()` for Fetch-compatible runtimes, `createAndroidWidgetUpdateNodeHandler()` for `node:http`, and `createAndroidWidgetUpdateExpressHandler()` for Express-style handlers. All three share the same request parsing, platform validation, token validation, and response serialization.
```tsx
import { createServer } from 'node:http'
import React from 'react'
import { createAndroidWidgetUpdateNodeHandler } from '@use-voltra/android-server'
import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android'
const handler = createAndroidWidgetUpdateNodeHandler({
render: async (req) => {
// req.widgetId — the widget requesting an update
// req.platform — always "android" for Android widget requests
// req.theme — the system color scheme ("light" or "dark")
// req.token — the auth token (if credentials were set)
const weather = await fetchWeatherData()
const content = (
{weather.temp}°
{weather.condition}
)
// Return size breakpoints for different widget sizes
return [
{ size: { width: 200, height: 100 }, content },
{ size: { width: 200, height: 200 }, content },
{ size: { width: 300, height: 200 }, content },
]
},
validateToken: async (token) => {
return token === 'valid-token'
},
})
createServer(handler).listen(3333)
```
The handler responds to GET requests with these query parameters:
| Parameter | Description |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `widgetId` | The widget identifier (required) |
| `platform` | The requesting platform. Must be `android` (required). |
| `family` | Not used on Android |
| `theme` | The system color scheme (`light` or `dark`) |
| `locale` | The device locale as a BCP-47 tag, e.g. `en-US` |
| `instance` | A stable hash of the placement’s merged configuration. Present only when the widget has configuration parameters (see [Per-instance requests](#per-instance-requests)). |
| `configuration` | The placement’s merged configuration as canonical JSON. Present only when the widget has configuration parameters. |
The `User-Agent` header is set to `VoltraWidget/ (Android/)`.
### Per-instance requests
[Section titled “Per-instance requests”](#per-instance-requests)
Each placed widget can be configured independently (see [Configure each placed widget separately](/android/development/dynamic-widgets#configure-each-placed-widget-separately)). When a widget has configuration parameters, every request carries the placement’s merged configuration — defaults, overlaid with widget-type values, overlaid with the placement’s own values — so a server can answer each placement differently:
```plaintext
GET https://api.example.com/widgets/weather
?widgetId=weather&platform=android&theme=dark&locale=en-US
&instance=3f9a2c1e
&configuration=%7B%22city%22%3A%22London%22%2C%22units%22%3A%22metric%22%7D
```
* `configuration` is the merged configuration map, serialized canonically: keys sorted by code point, no whitespace, values as JSON strings. Decoded, it is exactly what the widget sees as `env.configuration`.
* `instance` is a stable, non-cryptographic hash of that canonical string. Two placements with identical configuration send the same `instance` and share one fetch, one cached response, and one props slot — placing the same widget twice with the same values does not double your request volume.
* Both parameters are absent when the widget has no configuration parameters at all, so an existing server-driven widget’s requests are unchanged by this feature.
* `instance` and `configuration` are reserved query keys: a `query` you pass to `setWidgetServerUpdate` naming either is rejected.
Configurations are meant for identifiers and short choices, not large payloads — percent-encoding roughly triples the size of braces and quotes in the JSON.
**Fetch count.** A server-driven widget fetches once per distinct configuration among its current placements, not once per placement. If ten placements of one widget each use a different value for a free-text parameter, that is ten fetches per interval (each still floored at 15 minutes) rather than one. A server can still stretch the interval per instance with `Cache-Control: max-age`, exactly as it can today.
A widget with no configuration parameters keeps behaving exactly as it did before: one request, one cached response, shared by every placement.
## Returning data instead of UI
[Section titled “Returning data instead of UI”](#returning-data-instead-of-ui)
Everything above assumes your server renders Voltra components and returns a UI payload, which means it has to run Node. If you give the widget an `entry`, it renders on the device instead and your server returns plain JSON — so it can be written in any language.
Add both keys to the same widget:
```json
{
"id": "portfolio",
"displayName": "Portfolio",
"description": "Your holdings",
"targetCellWidth": 2,
"targetCellHeight": 2,
"entry": "./widgets/android/portfolio.tsx",
"initialStatePath": "./widgets/android/portfolio.tsx",
"serverUpdate": {
"url": "https://api.example.com/widgets/portfolio",
"intervalMinutes": 30
}
}
```
The response body becomes the widget’s props, verbatim:
```php
12480.55,
'change' => 1.8,
'holdings' => [
['symbol' => 'AAPL', 'value' => 8200.00],
['symbol' => 'MSFT', 'value' => 4280.55],
],
]);
```
Your widget entry receives that object as its first argument, the same shape you would pass to `updateAndroidDynamicWidget`:
```tsx
export default function PortfolioWidget(props, env) {
return (
${props.total.toFixed(2)}{props.change}% today
)
}
```
Check the endpoint with curl before wiring up the widget:
```bash
curl "https://api.example.com/widgets/portfolio?widgetId=portfolio&platform=android&theme=dark&locale=en-US" \
-H "Accept: application/json"
```
### What the response has to be
[Section titled “What the response has to be”](#what-the-response-has-to-be)
* Status `200` with `Content-Type: application/json` and a JSON **object**. An array, a string, a number or `null` at the top level is rejected.
* At most 256 KB.
* Return `ETag` and Voltra sends it back as `If-None-Match` on the next fetch. A `304` means the widget keeps what it has and counts as fresh. This applies to widgets with an `entry`; a payload widget’s request is unconditional.
* `Cache-Control: max-age=N` moves the next fetch, clamped between 15 minutes and 24 hours. `Retry-After` on a `429` or `503` is honoured the same way.
Returning a rendered Voltra payload from an endpoint whose widget has an `entry` is rejected with a log line naming the mismatch. The widget has an entry, so it wants the data, not the picture.
### Telling fresh data from stale
[Section titled “Telling fresh data from stale”](#telling-fresh-data-from-stale)
The widget is never blanked by a failed fetch: it keeps rendering the last props that arrived, whether from the server or from `updateAndroidDynamicWidget`. `env.serverUpdate` says which:
```tsx
export default function PortfolioWidget(props, env) {
const stale = env.serverUpdate?.status === 'stale'
return (
${props.total?.toFixed(2) ?? '—'}
{env.serverUpdate?.fetchedAt && (
Updated {new Date(env.serverUpdate.fetchedAt).toLocaleTimeString()}
)}
)
}
```
| Field | Meaning |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status` | `fresh` after a `200` or `304`; `stale` when a fetch has succeeded before but the last one failed; `never` before the first success; `disabled` while your app has taken the widget over |
| `fetchedAt` | Epoch milliseconds of the last `200` or `304`. Absent until a fetch succeeds. |
| `error` | `network`, `http`, `unauthorized`, `parse`, or `render`. Absent when `status` is `fresh`. |
| `httpStatus` | Status code of the last response, when there was one |
`env.serverUpdate` is `undefined` on widgets without a `serverUpdate`.
Props that throw during rendering are never committed — Voltra renders them once off screen first, and keeps the previous props when that fails. `env.serverUpdate.error` is `render` while that lasts.
## Authentication
[Section titled “Authentication”](#authentication)
Widgets on Android are part of the main app binary, so the WorkManager background worker can access credential storage directly. Voltra credentials are encrypted at rest on-device.
Note
`setWidgetServerCredentials` is deprecated in favour of [`setWidgetServerUpdate`](#changing-settings-at-runtime) with an `Authorization` header, which can also set the URL, the interval, the method, query parameters and a body. Both write the same encrypted records, so switching is a one-line change and nothing has to be migrated on device.
### Setting credentials
[Section titled “Setting credentials”](#setting-credentials)
Call `setWidgetServerCredentials` after the user logs in:
```typescript
import { setWidgetServerCredentials } from '@use-voltra/android-client'
await setWidgetServerCredentials({
token: userAccessToken,
headers: {
'X-App-Version': '1.0.0',
},
})
```
The `token` is required and is sent as `Authorization: Bearer ` on every server request. Any additional `headers` are also included. If your widget endpoint does not require authentication, skip `setWidgetServerCredentials()` entirely.
### Clearing credentials
[Section titled “Clearing credentials”](#clearing-credentials)
Call `clearWidgetServerCredentials` when the user logs out:
```typescript
import { clearWidgetServerCredentials } from '@use-voltra/android-client'
await clearWidgetServerCredentials()
```
All widgets are automatically reloaded after credentials are cleared, so they revert to their default/unauthenticated state immediately.
## Changing settings at runtime
[Section titled “Changing settings at runtime”](#changing-settings-at-runtime)
`serverUpdate` in `app.json` is the default. Once the app runs it can change any of it, per widget or for all of them, without a rebuild:
```typescript
import { setWidgetServerUpdate } from '@use-voltra/android-client'
await setWidgetServerUpdate(
{
url: `https://${tenant}.example.com/widgets/portfolio`,
intervalMinutes: 30,
headers: { Authorization: `Bearer ${accessToken}` },
},
{ widgetId: 'portfolio' }
)
```
| Setting | |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `url` | Must be `https`, or `http` to a local dev host (`localhost`, `127.0.0.1`, `::1`, `10.0.2.2`, `10.0.3.2`) in a debug build |
| `intervalMinutes` | Clamped between 15 minutes and 24 hours |
| `enabled` | `false` stops fetching until you set it back |
| `method` | `GET` (default), `POST`, `PUT`, `PATCH` or `DELETE` |
| `query` | Extra query parameters |
| `headers` | Extra request headers |
| `body` | Sent as `application/json` |
Leave out `widgetId` to set the same values for every server-driven widget. A widget-scoped call wins over a global one; `headers` and `query` merge per key across the two, everything else takes the more specific value.
Each call replaces everything it set last time, so pass every field you want to keep. Setting anything reschedules the widgets it affects and fetches once straight away.
Use this instead of `setWidgetServerCredentials`, which does the same thing for the `Authorization` header alone:
```typescript
// Before
await setWidgetServerCredentials({ token: accessToken, headers: { 'X-App-Version': '1.0.0' } })
// After
await setWidgetServerUpdate({
headers: { Authorization: `Bearer ${accessToken}`, 'X-App-Version': '1.0.0' },
})
```
To go back to what `app.json` configured, clear the settings:
```typescript
import { clearWidgetServerUpdate } from '@use-voltra/android-client'
await clearWidgetServerUpdate({ widgetId: 'portfolio' })
await clearWidgetServerUpdate()
```
Clearing the global settings is the logout gesture. Along with the settings it drops what the server last sent — the props and the “updated at” of every server-driven widget — so a Dynamic Widget goes back to rendering `{}` with `env.serverUpdate.status` of `never` rather than showing the previous account’s data. A widget-scoped clear only drops that widget’s overrides and leaves its props alone.
Read the settings back with `getWidgetServerUpdate`:
```typescript
import { getWidgetServerUpdate } from '@use-voltra/android-client'
const snapshot = await getWidgetServerUpdate({ widgetId: 'portfolio' })
if (snapshot?.enabled) {
console.log(`portfolio fetches ${snapshot.url} every ${snapshot.intervalMinutes}m`)
}
```
With a `widgetId`, this is the fully resolved settings that widget would fetch with right now — every layer flattened and `app.json`’s defaults applied, or `null` if the widget isn’t server-driven. Without one, it’s the raw global layer only: what the last widget-less `setWidgetServerUpdate` call wrote, with no defaults applied, or `null` if nothing has been set globally.
Credentials set with the deprecated `setWidgetServerCredentials` are stored separately and are not affected; clear those with `clearWidgetServerCredentials`.
Calling either function for a widget that has no `serverUpdate` in `app.json` throws. Whether a widget is server-driven is decided when the native project is generated, so a runtime URL cannot turn a local widget into one — add `serverUpdate` to `app.json` and rebuild.
A `body` set alongside `GET` or `HEAD` is dropped with a warning, because neither platform’s HTTP stack can send one.
### Driving a widget from the app
[Section titled “Driving a widget from the app”](#driving-a-widget-from-the-app)
`updateAndroidWidget` and `updateAndroidDynamicWidget` work on server-driven widgets, but the next scheduled fetch overwrites what you wrote. To keep it, turn fetching off first:
```typescript
await setWidgetServerUpdate({ enabled: false }, { widgetId: 'portfolio' })
await updateAndroidDynamicWidget('portfolio', localProps)
```
While fetching is off, `env.serverUpdate.status` is `disabled`, so the widget can hide its “updated N minutes ago” line. Set `enabled: true`, or clear the settings, to hand it back to the server.
## Refresh button
[Section titled “Refresh button”](#refresh-button)
Server-driven widgets can display a native refresh button that lets users trigger an immediate update on demand. Enable it in your widget config:
```json
{
"serverUpdate": {
"url": "https://api.example.com/widgets/render",
"intervalMinutes": 60,
"refresh": true
}
}
```
When enabled, a small circular button (↻) appears in the top-right corner of the widget.
On a payload widget, tapping it performs an inline HTTP fetch and pushes the update directly—without waiting for the next scheduled fetch. On a widget with an `entry`, a tap with no signal is queued and retries until it succeeds, rather than failing silently.
## Resize handling
[Section titled “Resize handling”](#resize-handling)
Your server should return all size variants in every response. When the user resizes a widget on the home screen, Voltra re-renders from cached data—no network request is made. The `RemoteViews(sizeMapping)` mechanism automatically picks the closest matching variant.
## Triggering manual refreshes
[Section titled “Triggering manual refreshes”](#triggering-manual-refreshes)
You can force-refresh server-driven widgets outside of the regular interval:
```typescript
import { reloadAndroidWidgets } from '@use-voltra/android-client'
// Reload specific widgets (triggers an immediate WorkManager fetch)
await reloadAndroidWidgets(['dynamic_weather'])
// Reload all widgets
await reloadAndroidWidgets()
```
For server-driven widgets, this enqueues an immediate one-time WorkManager request to fetch fresh content. For local-only widgets, it re-renders from cached data.
## Initial state
[Section titled “Initial state”](#initial-state)
Server-driven widgets still need content to display before the first server fetch completes. Use `initialStatePath` to provide a pre-rendered default:
```json
{
"id": "dynamic_weather",
"displayName": "Dynamic Weather",
"description": "Weather with live server updates",
"targetCellWidth": 2,
"targetCellHeight": 1,
"initialStatePath": "./widgets/android/weather-initial.tsx",
"serverUpdate": {
"url": "https://api.example.com/widgets/render",
"intervalMinutes": 60
}
}
```
See [Widget pre-rendering](/android/development/widget-pre-rendering) for details on creating initial state files.
Tip
Provide a meaningful initial state (e.g. “Loading…” or placeholder content) rather than leaving it empty. The user sees this until the first server fetch succeeds.
## Cross-platform server
[Section titled “Cross-platform server”](#cross-platform-server)
A single server can handle both iOS and Android requests using `createWidgetUpdateHandler` from `@use-voltra/server`:
```tsx
import { Voltra } from '@use-voltra/ios'
import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android'
import { createWidgetUpdateHandler } from '@use-voltra/server'
const handler = createWidgetUpdateHandler({
renderIos: async (req) => {
// Return WidgetVariants (systemSmall, systemMedium, etc.)
return { systemSmall: Hello }
},
renderAndroid: async (req) => {
// Return AndroidWidgetVariants (size breakpoints)
return [{ size: { width: 200, height: 100 }, content: Hello }]
},
validateToken: async (token) => {
// Shared token validation for both platforms
return verifyJwt(token)
},
})
```
The handler uses the required `platform` query parameter to route requests to the correct render function.
If you’re serving the cross-platform endpoint from Node or Express, use `createWidgetUpdateNodeHandler()` or `createWidgetUpdateExpressHandler()` from `@use-voltra/server` instead.
## Error handling and retries
[Section titled “Error handling and retries”](#error-handling-and-retries)
WorkManager automatically handles failures with exponential backoff. After 5 consecutive failed attempts, the worker gives up to avoid infinite retry loops. The next periodic run will start fresh.
* **Network unavailable:** The request is deferred until connectivity is restored (via `NetworkType.CONNECTED` constraint).
* **Server errors (non-2xx):** The worker retries with exponential backoff, up to 3 attempts.
* **Empty response:** The worker retries with exponential backoff, up to 3 attempts.
* **Parse errors:** If the JSON is stored but parsing fails, the data is still saved so Glance can attempt to use it later. This counts as a success since the data is persisted.
* **`401` or `403`:** The worker stops rather than backing off — the status will not change until you set a new token, and doing so reloads the widget anyway.
For widgets that return props rather than UI, the widget keeps rendering the last props it has through every one of these, and `env.serverUpdate` says what went wrong.
# Styling
> The React Native style properties Voltra supports on Android and how they map to Jetpack Compose Glance modifiers.
You can style Voltra components on Android using React Native-style `style` props. These properties are automatically converted to Jetpack Compose Glance modifiers.
For Android system-aware colors, use [`AndroidDynamicColors`](/android/development/dynamic-colors) from `@use-voltra/android` instead of snapshotting palette values in JavaScript.
Glance Limitations
Android widgets are built using **Jetpack Compose Glance**, which has a significantly more limited styling API compared to standard Compose or SwiftUI. Many common React Native style properties are either not supported or have limited support.
## Supported Properties
[Section titled “Supported Properties”](#supported-properties)
The following React Native style properties are supported on Android:
### Layout
[Section titled “Layout”](#layout)
* `width`, `height` - Fixed dimensions (number values in dp) or `"100%"` to fill available space.
* `flex`, `flexGrow` - Flex weight. When > 0, the component will take up a proportional amount of space in its parent container (maps to `.defaultWeight()` in Glance).
* `padding` - Uniform padding on all edges.
* `paddingTop`, `paddingBottom`, `paddingLeft`, `paddingRight` - Individual edge padding.
* `paddingHorizontal`, `paddingVertical` - Horizontal and vertical padding.
* `visibility` - Controls component visibility (`"visible"`, `"hidden"`, or `"invisible"`).
### Visual Style
[Section titled “Visual Style”](#visual-style)
* `backgroundColor` - Background color (hex strings, color names, or `AndroidDynamicColors.*` tokens).
* `backgroundImage` - CSS gradient background. Supports `linear-gradient(...)`, `radial-gradient(...)`, and `conic-gradient(...)`.
* `borderRadius` - Corner radius value. **Note:** Requires Android 12+ (API 31). On older versions, this property is ignored.
### Text
[Section titled “Text”](#text)
* `fontSize` - Font size in sp.
* `fontWeight` - Supports `"normal"` and `"bold"`.
* `fontFamily` - Font family name. Built-in values: `"monospace"`, `"serif"`, `"sans-serif"`, `"cursive"`. For custom fonts, see [Custom Fonts](/android/development/custom-fonts).
* `color` - Text color (literal colors or `AndroidDynamicColors.*`).
* `textDecorationLine` - Supports `"underline"` and `"line-through"`.
* `textAlign` - Alignment of text within the component (`"left"`, `"center"`, `"right"`).
* `numberOfLines` - Limits the number of lines displayed.
### Image Specific
[Section titled “Image Specific”](#image-specific)
In addition to general styles, `Image` components support:
* `resizeMode` - `"cover"`, `"contain"`, `"stretch"`, `"repeat"`, or `"center"`.
* `contentScale` - `"crop"`, `"cover"`, `"fit"`, `"contain"`, `"fill-bounds"`, or `"stretch"`.
* `alpha` - Opacity of the image (0.0 to 1.0).
* `colorFilter` - Applies a color filter to the image.
## Dynamic colors
[Section titled “Dynamic colors”](#dynamic-colors)
Android widgets can use semantic Material color roles (`AndroidDynamicColors.*`) so they follow the system palette even when the app isn’t running. See [Dynamic Colors](/android/development/dynamic-colors) for the full role list, examples, and server-rendering behavior.
## Gradient Backgrounds
[Section titled “Gradient Backgrounds”](#gradient-backgrounds)
Android widgets support gradient backgrounds through the camel-case `style.backgroundImage` property.
```tsx
import { VoltraAndroid } from '@use-voltra/android'
const element = (
Gradient Widget
)
```
Supported gradient functions are `linear-gradient(...)`, `radial-gradient(...)`, and `conic-gradient(...)`. Repeating gradients, malformed gradients, unsupported color tokens, and invalid stop positions are ignored. If `backgroundColor` is also provided, Android paints it behind transparent gradient pixels and uses it as a fallback when a gradient cannot be rendered.
Gradient stops can use Android dynamic color tokens from `AndroidDynamicColors`, but those colors are resolved into the generated bitmap when the widget renders or updates. Existing gradient bitmaps do not recolor until the widget is rendered again.
Use `backgroundImage`, not `background-image`. Gradient bitmaps are generated natively during widget rendering and capped before being passed to Glance, so the bitmap does not control layout size.
## Limitations
[Section titled “Limitations”](#limitations)
The following properties are **NOT supported** on Android due to Glance limitations:
* **Margins:** `margin`, `marginTop`, etc. are not part of Android style types. If you need margin-like outside spacing, use `VoltraAndroid.Spacer` between elements.
* **Borders:** `borderWidth` and `borderColor` are not yet implemented.
* **Shadows:** `shadowColor`, `shadowOffset`, `shadowOpacity`, and `shadowRadius` are not supported.
* **Positioning:** Absolute positioning (`top`, `left`, `zIndex`) is not supported. Use stack alignments and spacers.
* **Transforms:** `transform` (rotate, scale, etc.) is not supported.
* **Opacity:** The general `style.opacity` property is not supported (except for the `alpha` prop on `Image`).
* **Dimensions:** `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, and `aspectRatio` are not supported.
* **Text Effects:** `letterSpacing`, `fontVariant`, and custom `lineHeight` are not supported.
## Example
[Section titled “Example”](#example)
```tsx
import { VoltraAndroid } from '@use-voltra/android'
const element = (
Android Widget Text
)
```
## Sharing styles with `StyleSheet`
[Section titled “Sharing styles with StyleSheet”](#sharing-styles-with-stylesheet)
Widget files can import `StyleSheet` and `Platform` from `react-native`, so styles can live outside the element tree exactly as they do in the rest of your app:
```tsx
import { Platform, StyleSheet } from 'react-native'
import { VoltraAndroid } from '@use-voltra/android'
const styles = StyleSheet.create({
container: {
padding: 16,
backgroundColor: '#101828',
},
title: {
color: '#F8FAFC',
fontSize: 18,
fontWeight: 'bold',
},
})
const element = (
{Platform.OS}
)
```
Widget code does not run against the React Native runtime — at build time it is evaluated in a Node sandbox, and Dynamic Widgets run on device in a separate JS engine with no bridge. Only the parts of `react-native` that are pure data manipulation are therefore available:
* `StyleSheet.create`, `StyleSheet.flatten`, `StyleSheet.compose`, `StyleSheet.absoluteFill`, `StyleSheet.absoluteFillObject`, and `StyleSheet.hairlineWidth`.
* `Platform.OS` and `Platform.select`. Inside a widget, `Platform.OS` is the platform the widget is being built for, so `Platform.select` picks the same branch at build time and on device.
Anything else imported from `react-native` — components, `Dimensions`, `Animated`, `PixelRatio` — is rejected with a message naming the symbol. Build steps that evaluate your widget (`voltra apply` and `expo prebuild`) fail outright; a symbol that only appears on a branch those steps never reach throws the same message when the widget renders, rather than reading as `undefined`. Deep imports such as `react-native/Libraries/...` always fail the build. Use the `VoltraAndroid` components for everything visual.
# Testing and Previews (Android)
> Preview Android widgets inside your app with VoltraWidgetPreview and see how widget picker previews relate to it.
Voltra provides multiple ways to preview your Android widgets:
1. **In-App Previews** - Preview layouts within your development app using `VoltraWidgetPreview`
2. **Widget Picker Previews** - Customize what users see in the Android widget picker when adding your widget
This page covers in-app previews for development. For widget picker previews, see [Widget Sizing & Previews](/android/api/widget-sizing-and-previews).
## VoltraWidgetPreview
[Section titled “VoltraWidgetPreview”](#voltrawidgetpreview)
The `VoltraWidgetPreview` component renders Voltra Android JSX content at the exact dimensions of standard Android widget sizes.
### Usage
[Section titled “Usage”](#usage)
```tsx
import { VoltraAndroid } from '@use-voltra/android'
import { VoltraWidgetPreview } from '@use-voltra/android-client'
export function MyWidgetPreview() {
return (
My Awesome Widget
This is how it looks on the home screen!
)
}
```
### Supported Families
[Section titled “Supported Families”](#supported-families)
Android widgets use responsive sizing. Voltra provides several standard families based on typical grid dimensions:
| Family | DP Dimensions | Typical Grid Size |
| -------------- | ------------- | ----------------- |
| `small` | 150 x 100 | 2x1 |
| `mediumSquare` | 200 x 200 | 2x2 |
| `mediumWide` | 250 x 150 | 3x2 |
| `mediumTall` | 150 x 250 | 2x3 |
| `large` | 300 x 200 | 4x2 |
| `extraLarge` | 350 x 300 | 4x4 |
## VoltraView (Android)
[Section titled “VoltraView (Android)”](#voltraview-android)
If you need more control or want to test custom dimensions, you can use the low-level `VoltraView` component.
```tsx
import { VoltraAndroid } from '@use-voltra/android'
import { VoltraView } from '@use-voltra/android-client'
Custom Preview
```
## Accuracy
[Section titled “Accuracy”](#accuracy)
The Android preview components use the **actual native Glance renderers** under the hood, so the preview matches production rendering — layout, styling, and component mapping are all identical to what shows on the home screen.
Note
While layout and styling are accurate, some home-screen specific behaviors (like actual widget resizing by the user) are not simulated by the preview component.
# Widget Pre-rendering (Android)
> Provide initial widget content at build time with initialStatePath so Android widgets show something before the app first updates them.
Widget pre-rendering allows you to provide a meaningful initial state for your Android widgets before they are updated by the app for the first time.
## Configuration
[Section titled “Configuration”](#configuration)
Add `initialStatePath` to your widget configuration in the `@use-voltra/android-client` plugin in `app.json`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"description": "Shows current weather",
"targetCellWidth": 2,
"targetCellHeight": 2,
"initialStatePath": "./widgets/weather-android-initial.tsx"
}
]
}
]
]
}
}
```
For multiple locales, set `initialStatePath` to a map of locale tag → file path (same pattern as iOS); the first-run payload matches the device locale when possible.
## Implementation
[Section titled “Implementation”](#implementation)
Create a file at the specified `initialStatePath` that exports a default Voltra component (or a React element). For Android, this should use `VoltraAndroid` primitives.
```tsx
import { VoltraAndroid } from '@use-voltra/android'
const InitialWeatherWidget = (
Loading weather...
)
export default InitialWeatherWidget
```
Note
`initialStatePath` files are **not** part of your React Native app bundle. They run in Node.js during prebuild. Import `VoltraAndroid` from `@use-voltra/android`, not `@use-voltra/android-client` — the client package pulls in native modules that are unavailable in the prebuild sandbox.
## Limitations
[Section titled “Limitations”](#limitations)
* **Imports**: Use `@use-voltra/android` for JSX and types in `initialStatePath` files. Do not import from `@use-voltra/android-client` or other React Native client APIs.
* **Static Content**: The initial state should represent a “loading” or “offline” state, as it won’t have access to dynamic runtime data until the app runs.
# Android Introduction
> How Voltra builds Android Home Screen widgets and ongoing notifications from JSX using Jetpack Compose Glance primitives.
Voltra lets you build Android Home Screen widgets with JSX. Under the hood it uses Jetpack Compose Glance, and Voltra’s primitives map directly to Glance components.
## Widgets on Android
[Section titled “Widgets on Android”](#widgets-on-android)
Android widgets have different layout and styling rules compared to iOS Live Activities. While iOS uses SwiftUI-based primitives (VStack, HStack, etc.), Android uses Jetpack Compose Glance primitives (Column, Row, Box).
Voltra abstracts these differences where possible, but provides platform-specific namespaces to ensure your UI looks and behaves correctly on each platform.
Voltra also exposes Android-specific semantic dynamic colors through `AndroidDynamicColors`, which lets widgets follow the current Material palette without requiring a JavaScript re-render. See [Dynamic Colors](/android/development/dynamic-colors).
Voltra also supports Android ongoing notifications for app-driven, persistent status updates. See [Managing Android Ongoing Notifications](/android/development/managing-ongoing-notifications).
### Simple Android Widget
[Section titled “Simple Android Widget”](#simple-android-widget)
```tsx
import { VoltraAndroid } from '@use-voltra/android'
const MyWidget = () => (
Android Widget
Powered by Voltra & Glance
)
```
## Testing and Previews
[Section titled “Testing and Previews”](#testing-and-previews)
You can preview your Android widgets directly in your app using the `VoltraWidgetPreview` component. This allows for fast iteration without needing to constantly check the home screen.
Learn more in the [Testing and Previews guide](/android/development/testing-and-previews).
## Next Steps
[Section titled “Next Steps”](#next-steps)
Check out the [Setup guide](/android/setup) to set up Voltra for Android.
For notification-based experiences, see [Managing Android Ongoing Notifications](/android/development/managing-ongoing-notifications).
# Android Setup
> Configure the Voltra Expo plugin for Android, run prebuild, and run the app to see your widget in the Android widget picker.
Once you have [installed Voltra](/getting-started/installation) for Android, configure the Expo plugin and use `@use-voltra/android` for widget JSX.
## 1. Configure the Expo Plugin
[Section titled “1. Configure the Expo Plugin”](#1-configure-the-expo-plugin)
Add `@use-voltra/android-client` to your `app.json` or `app.config.js`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"enableNotifications": true,
"widgets": [
{
"id": "my_widget",
"displayName": "My First Widget",
"description": "A simple Voltra widget",
"targetCellWidth": 2,
"targetCellHeight": 2
}
]
}
]
]
}
}
```
See [Plugin Configuration](/android/api/plugin-configuration) for all options.
## 2. Prebuild for Android
[Section titled “2. Prebuild for Android”](#2-prebuild-for-android)
Update your native Android project:
* npm
```sh
npx expo prebuild --platform android
```
* yarn
```sh
yarn dlx expo prebuild --platform android
```
* pnpm
```sh
pnpm dlx expo prebuild --platform android
```
* bun
```sh
bunx expo prebuild --platform android
```
## 3. Run the app
[Section titled “3. Run the app”](#3-run-the-app)
```bash
npx expo run:android
```
Your widget should now be available in the Android widget picker!
# Installation
> Install the Voltra platform packages for JSX primitives and runtime APIs on iOS and Android, plus the optional server packages.
Voltra v2 ships as platform packages. In most apps, you install one package for JSX primitives and one package for runtime APIs per platform.
## 1. Install packages
[Section titled “1. Install packages”](#1-install-packages)
### iOS (Live Activities and widgets)
[Section titled “iOS (Live Activities and widgets)”](#ios-live-activities-and-widgets)
* npm
```sh
npm install @use-voltra/ios @use-voltra/ios-client
```
* yarn
```sh
yarn add @use-voltra/ios @use-voltra/ios-client
```
* pnpm
```sh
pnpm add @use-voltra/ios @use-voltra/ios-client
```
* bun
```sh
bun add @use-voltra/ios @use-voltra/ios-client
```
### Android (Home Screen widgets and ongoing notifications)
[Section titled “Android (Home Screen widgets and ongoing notifications)”](#android-home-screen-widgets-and-ongoing-notifications)
* npm
```sh
npm install @use-voltra/android @use-voltra/android-client
```
* yarn
```sh
yarn add @use-voltra/android @use-voltra/android-client
```
* pnpm
```sh
pnpm add @use-voltra/android @use-voltra/android-client
```
* bun
```sh
bun add @use-voltra/android @use-voltra/android-client
```
Use the platform package for JSX primitives:
* `@use-voltra/ios` exports `Voltra`
* `@use-voltra/android` exports `VoltraAndroid`, `AndroidDynamicColors`, and `AndroidOngoingNotification`
Use the client package for React Native runtime APIs:
* `@use-voltra/ios-client` exports `startLiveActivity`, `updateWidget`, `VoltraView`, `VoltraWidgetPreview`, and other app-side APIs
* `@use-voltra/android-client` exports `updateAndroidWidget`, `requestPinAndroidWidget`, `reloadAndroidWidgets`, `VoltraView`, `VoltraWidgetPreview`, and other app-side APIs
### Server rendering (optional)
[Section titled “Server rendering (optional)”](#server-rendering-optional)
Use these in your backend or SSR service-not in the React Native app bundle:
* **iOS payloads:** `@use-voltra/ios-server`
* **Android payloads:** `@use-voltra/android-server`
* **Cross-platform widget HTTP handlers:** `@use-voltra/server`
Note that pre-render files such as `initialStatePath` should import JSX from `@use-voltra/ios` or `@use-voltra/android` directly, not from the client packages.
## 2. Next Steps
[Section titled “2. Next Steps”](#2-next-steps)
After installing packages, configure the Voltra Expo plugin for each platform you support:
* [Configure iOS Setup](/ios/setup)
* [Configure Android Setup](/android/setup)
* [Use Voltra in React Native CLI projects](/getting-started/react-native-cli)
* [Migrate from v1 to v2](/getting-started/migration-v2)
# Introduction
> What Voltra is and how it turns JSX into native iOS Live Activities, Dynamic Island layouts, and iOS and Android widgets.
Voltra is a library that brings new “platforms” to React Native. Creating features like iOS Live Activities, Dynamic Island layouts, or Android Home Screen Widgets normally requires writing native code in Swift or Kotlin.
Voltra changes this by providing a JavaScript-based API and JSX components that get automatically converted to native primitives (SwiftUI on iOS, Jetpack Compose Glance on Android).
Here’s how simple it is to create a live activity:
```tsx
import { Voltra } from '@use-voltra/ios'
import { startLiveActivity } from '@use-voltra/ios-client'
const activityUI = (
Driver en routeBuilding A · Lobby pickupContact driver
)
// Start the live activity
await startLiveActivity({
lockScreen: activityUI,
})
```
If you prefer using the hook API, check out [`useLiveActivity`](/ios/development/developing-live-activities#useliveactivity) for integrating live activities with the component lifecycle and automatic updates during development.
## Server-side updates via push notifications
[Section titled “Server-side updates via push notifications”](#server-side-updates-via-push-notifications)
Voltra also supports server-side updates through push notifications. You can use Voltra’s server-side rendering to convert JSX into JSON payloads that you send to devices via Apple’s Push Notification Service (APNS) or Firebase Cloud Messaging (FCM). This enables real-time updates without keeping your app running.
The same components you use in your app work on the server:
```tsx
import { Voltra, renderLiveActivityToString } from '@use-voltra/ios-server'
// Render JSX to JSON payload on your server
const payload = renderLiveActivityToString({
lockScreen: (
Driver arrivedReady for pickup
),
})
```
Ready to get started? Head over to the [Installation](/getting-started/installation) guide, or explore platform-specific guides for [iOS](/ios/introduction) and [Android](/android/introduction).
# Migration to v2
> Migrate from Voltra v1 to v2: new package names, import mapping, Expo plugin changes, API renames, and pre-render file rules.
Voltra v2 introduces two major architectural changes:
* The old Voltra umbrella package is gone. Voltra now ships as separate iOS, Android, and server packages.
* The native layer moved from Expo Modules to Turbo Modules.
Upgrading to v2 requires updating package installs, Expo plugin configuration, and some API usage. This guide walks through those changes.
## Recommended migration order
[Section titled “Recommended migration order”](#recommended-migration-order)
1. Replace package installs.
2. Swap the Expo plugin to the platform-specific package.
3. Move JSX imports to `@use-voltra/ios` or `@use-voltra/android`.
4. Move runtime APIs to the matching `*-client` package.
5. Move server rendering code to `@use-voltra/ios-server` or `@use-voltra/android-server`.
6. Rename Android widget APIs that became platform-specific.
7. Verify `initialStatePath` files only import from platform packages.
## What changed
[Section titled “What changed”](#what-changed)
* **Package split:** old `voltra`, `voltra/client`, `voltra/server`, `voltra/android`, etc. paths are replaced by scoped packages (`@use-voltra/ios`, `@use-voltra/ios-client`, `@use-voltra/ios-server`, `@use-voltra/android`, `@use-voltra/android-client`, `@use-voltra/android-server`, `@use-voltra/server`).
* **Platform-specific JSX namespaces:** iOS primitives come from `@use-voltra/ios` as `Voltra`; Android primitives, color tokens, and ongoing notification JSX come from `@use-voltra/android` as `VoltraAndroid`, `AndroidDynamicColors`, and `AndroidOngoingNotification`.
* **Client APIs stay in `*-client`:** runtime APIs that run inside the React Native app (starting/updating Live Activities, updating or pinning widgets, preview components, event listeners and hooks) come from `@use-voltra/ios-client` and `@use-voltra/android-client`.
* **Server APIs are platform-specific:** use `@use-voltra/ios-server` and `@use-voltra/android-server` for server-side rendering, and `@use-voltra/server` only for cross-platform widget HTTP handlers.
See the sections below for exact import diffs.
## Installation changes
[Section titled “Installation changes”](#installation-changes)
Install the packages that match the layers you use.
### iOS app code
[Section titled “iOS app code”](#ios-app-code)
* npm
```sh
npm install @use-voltra/ios @use-voltra/ios-client
```
* yarn
```sh
yarn add @use-voltra/ios @use-voltra/ios-client
```
* pnpm
```sh
pnpm add @use-voltra/ios @use-voltra/ios-client
```
* bun
```sh
bun add @use-voltra/ios @use-voltra/ios-client
```
### Android app code
[Section titled “Android app code”](#android-app-code)
* npm
```sh
npm install @use-voltra/android @use-voltra/android-client
```
* yarn
```sh
yarn add @use-voltra/android @use-voltra/android-client
```
* pnpm
```sh
pnpm add @use-voltra/android @use-voltra/android-client
```
* bun
```sh
bun add @use-voltra/android @use-voltra/android-client
```
### Optional server packages
[Section titled “Optional server packages”](#optional-server-packages)
* npm
```sh
npm install @use-voltra/ios-server @use-voltra/android-server @use-voltra/server
```
* yarn
```sh
yarn add @use-voltra/ios-server @use-voltra/android-server @use-voltra/server
```
* pnpm
```sh
pnpm add @use-voltra/ios-server @use-voltra/android-server @use-voltra/server
```
* bun
```sh
bun add @use-voltra/ios-server @use-voltra/android-server @use-voltra/server
```
## Import mapping
[Section titled “Import mapping”](#import-mapping)
### iOS app code
[Section titled “iOS app code”](#ios-app-code-1)
```tsx
// v1
import { Voltra } from 'voltra'
import { startLiveActivity } from 'voltra/client'
// v2
import { Voltra } from '@use-voltra/ios'
import { startLiveActivity } from '@use-voltra/ios-client'
```
### iOS server code
[Section titled “iOS server code”](#ios-server-code)
```tsx
// v1
import { renderLiveActivityToString, Voltra } from 'voltra/server'
// v2
import { Voltra, renderLiveActivityToString } from '@use-voltra/ios-server'
```
### Android widget code
[Section titled “Android widget code”](#android-widget-code)
```tsx
// v1
import { VoltraAndroid } from 'voltra/android'
import { updateWidget } from 'voltra/android'
// v2
import { VoltraAndroid } from '@use-voltra/android'
import { updateAndroidWidget } from '@use-voltra/android-client'
```
### Android server widget code
[Section titled “Android server widget code”](#android-server-widget-code)
```tsx
// v1
import { createWidgetUpdateNodeHandler } from 'voltra/server'
import { AndroidDynamicColors, VoltraAndroid } from 'voltra/android'
// v2
import { createAndroidWidgetUpdateNodeHandler } from '@use-voltra/android-server'
import { AndroidDynamicColors, VoltraAndroid } from '@use-voltra/android'
```
## Expo plugin migration
[Section titled “Expo plugin migration”](#expo-plugin-migration)
The old docs used a single `voltra` plugin and nested per-platform config. v2 uses platform-specific plugins.
### iOS
[Section titled “iOS”](#ios)
```json
// v1
{
"expo": {
"plugins": [
[
"voltra",
{
"ios": {
"groupIdentifier": "group.example.app",
"widgets": []
}
}
]
]
}
}
// v2
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"groupIdentifier": "group.example.app",
"widgets": []
}
]
]
}
}
```
### Android
[Section titled “Android”](#android)
```json
// v1
{
"expo": {
"plugins": [
[
"voltra",
{
"android": {
"widgets": []
}
}
]
]
}
}
// v2
{
"expo": {
"plugins": [
[
"@use-voltra/android-client",
{
"widgets": []
}
]
]
}
}
```
## API renames to watch for
[Section titled “API renames to watch for”](#api-renames-to-watch-for)
* Android widget updates: `updateWidget(...)` -> `updateAndroidWidget(...)`
* Android widget reloads: `reloadWidgets(...)` for image-preloading remains, but widget refresh APIs use `reloadAndroidWidgets(...)`
* Android widget server handlers: `createWidgetUpdateHandler(...)` style examples should become `createAndroidWidgetUpdateHandler(...)`, `createAndroidWidgetUpdateNodeHandler(...)`, or `createAndroidWidgetUpdateExpressHandler(...)`
* iOS widget server handlers: use `createIOSWidgetUpdateHandler(...)`, `createIOSWidgetUpdateNodeHandler(...)`, or `createIOSWidgetUpdateExpressHandler(...)`
## Pre-render files
[Section titled “Pre-render files”](#pre-render-files)
`initialStatePath` files run in Node during prebuild, not in the React Native runtime.
Use:
* `@use-voltra/ios` for iOS widget JSX and types
* `@use-voltra/android` for Android widget JSX and types
Do not import `@use-voltra/ios-client` or `@use-voltra/android-client` from pre-render files.
## After migrating
[Section titled “After migrating”](#after-migrating)
Re-run prebuild for any platform whose plugin configuration changed:
```bash
npx expo prebuild --platform ios
npx expo prebuild --platform android
```
# Prior Art
> The open-source libraries and projects that inspired Voltra's approach to bridging JavaScript and native Live Activities.
Voltra wouldn’t be possible without the incredible work of the open-source community. This page acknowledges the libraries and projects that inspired and informed our approach to bridging JavaScript and native iOS Live Activities.
## Inspiration
[Section titled “Inspiration”](#inspiration)
### Dynamic UI
[Section titled “Dynamic UI”](#dynamic-ui)
The core concept of describing SwiftUI layouts through JSON configuration was pioneered by Wesley de Groot’s [Dynamic UI](https://github.com/0xWDG/DynamicUI).
### Expo Live Activity
[Section titled “Expo Live Activity”](#expo-live-activity)
The insight of combining JavaScript-driven development with iOS Live Activities came from Software Mansion’s [Expo Live Activity](https://github.com/software-mansion-labs/expo-live-activity). Referencing their open-source Expo config plugin logic was helpful during early development.
### Expo Widgets
[Section titled “Expo Widgets”](#expo-widgets)
Voltra spawns a secondary JS runtime to drive native widget and Live Activity rendering. That’s not just a theoretical option — Expo’s own [`expo-widgets`](https://docs.expo.dev/versions/latest/sdk/widgets/) module does the same thing in production: when the system asks for a widget timeline or starts a Live Activity, your component runs in a separate JS runtime and produces a native layout tree. Seeing this pattern work at Expo SDK scale, across both iOS and Android, was a strong signal that it’s a practical foundation to build on, not just a corner case.
## Thank You
[Section titled “Thank You”](#thank-you)
We extend our gratitude to the following organizations and individuals:
* **Wesley de Groot** for creating Dynamic UI and demonstrating the power of JSON-driven SwiftUI interfaces.
* **Software Mansion** for open-sourcing their Expo Live Activity library.
* **Expo** for building Expo Modules that power Voltra behind the scenes.
* **The broader open-source community** for all the libraries, tools, and ideas that make innovative projects like Voltra possible in the first place.
Voltra is our contribution back to the broader React Native community. We hope it helps developers create more engaging and interactive Live Activities and Widgets for their iOS applications.
***
*If you’re working on something that builds upon Voltra, we’d love to hear about it! Feel free to reach out and let us know how you’re using it.*
# React Native CLI Projects
> Use Voltra in React Native CLI projects with the voltra CLI and voltra.config.ts instead of Expo config plugins.
Voltra fully supports React Native CLI projects through the `voltra` CLI. Instead of relying on Expo config plugins, `voltra apply` updates the native project for you: it modifies the files Voltra needs, generates new Voltra-owned files, and cleans up outdated generated files from previous runs.
## Installation
[Section titled “Installation”](#installation)
Install the same native Voltra packages you would use in Expo for the platforms you support, then add `voltra` as a dev dependency.
### iOS
[Section titled “iOS”](#ios)
* npm
```sh
npm install @use-voltra/ios @use-voltra/ios-client
```
* yarn
```sh
yarn add @use-voltra/ios @use-voltra/ios-client
```
* pnpm
```sh
pnpm add @use-voltra/ios @use-voltra/ios-client
```
* bun
```sh
bun add @use-voltra/ios @use-voltra/ios-client
```
### Android
[Section titled “Android”](#android)
* npm
```sh
npm install @use-voltra/android @use-voltra/android-client
```
* yarn
```sh
yarn add @use-voltra/android @use-voltra/android-client
```
* pnpm
```sh
pnpm add @use-voltra/android @use-voltra/android-client
```
* bun
```sh
bun add @use-voltra/android @use-voltra/android-client
```
### Voltra CLI
[Section titled “Voltra CLI”](#voltra-cli)
* npm
```sh
npm install -D voltra
```
* yarn
```sh
yarn add -D voltra
```
* pnpm
```sh
pnpm add -D voltra
```
* bun
```sh
bun add -D voltra
```
Then create a `voltra.config.ts` file. Most properties under `ios` and `android` are the same as the Expo config equivalents (see [Configuration](#configuration) below).
Minimal example:
```ts
import type { VoltraConfig } from 'voltra'
const config: VoltraConfig = {
ios: {
// Commonly needed on iOS so the app and extension can share data.
groupIdentifier: 'group.com.example.app',
widgets: [
{
// Basic widget identity fields.
id: 'portfolio',
displayName: 'Portfolio',
description: 'Track holdings',
// Optional, but commonly used for build-time initial widget content.
initialStatePath: './widgets/portfolio.ios.tsx',
},
],
},
android: {
widgets: [
{
id: 'portfolio',
displayName: 'Portfolio',
description: 'Track holdings',
// Required on Android.
targetCellWidth: 2,
targetCellHeight: 2,
initialStatePath: './widgets/portfolio.android.tsx',
},
],
},
}
export default config
```
Once the config is in place, apply the native project changes:
* npm
```sh
npx voltra apply
```
* yarn
```sh
yarn voltra apply
```
* pnpm
```sh
pnpm voltra apply
```
* bun
```sh
bunx voltra apply
```
## Configuration
[Section titled “Configuration”](#configuration)
Most properties under `ios` and `android` use the same names as the Expo config equivalents:
* [iOS Expo config options](/ios/api/plugin-configuration)
* [Android Expo config options](/android/api/plugin-configuration)
The properties below are specific to the Voltra CLI:
| Property | Purpose |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `projectRoot` | Overrides the root directory Voltra should treat as the native project root. Useful when the config file does not live at the app root. |
| `ios.userImagesPath` | Overrides the directory for user-provided iOS widget images. |
| `ios.project` | Lets you override iOS project discovery when the app does not use the standard React Native layout. Supports fields such as `rootDir`, `xcodeprojPath`, `mainTargetName`, `infoPlistPath`, `entitlementsPath`, and `podfilePath`. See [Multiple environments](#multiple-environments) for setting `entitlementsPath` per build configuration. |
| `android.userImagesPath` | Overrides the directory for user-provided Android widget images. |
| `android.project` | Lets you override Android project discovery when the app does not use the standard React Native layout. Supports fields such as `rootDir`, `appModuleName`, `manifestPath`, and `packageName`. |
For the full config shape, see [`VoltraConfig` and related types in source](https://github.com/callstackincubator/voltra/blob/main/packages/cli/src/config/types.ts).
## Multiple environments
[Section titled “Multiple environments”](#multiple-environments)
Apps that ship several environments — dev, test, staging, production — build them from one Xcode project using a build configuration per environment, and each environment usually needs its own App Group so a dev build cannot read the production widget’s data.
`ios.groupIdentifier`, `ios.keychainGroup` and `ios.project.entitlementsPath` accept one value per Xcode build configuration name for that:
```ts
ios: {
groupIdentifier: {
Debug: 'group.com.example.app.dev',
ReleaseStaging: 'group.com.example.app.staging',
Release: 'group.com.example.app',
},
}
```
The keys are Xcode **build configuration** names, not scheme names. A scheme selects a build configuration per action, so a scheme that runs `Debug` and archives `Release` picks up the value for whichever configuration the build uses. Every build configuration of the app target must have a value; `voltra apply` lists the project’s configurations if one is missing or misspelled.
For `groupIdentifier` and `keychainGroup`, `voltra apply` writes the map into your Xcode project as a `VOLTRA_*` user-defined build setting holding one value per configuration, then writes a reference to that setting — not the value itself — into the entitlements and `Info.plist` files. Both the app and the generated widget extension inherit the setting, so each build picks up the value for the configuration it is built with. Voltra adds, updates, and removes these settings as your config changes; do not define your own settings under the `VOLTRA_` prefix.
If you already keep environment values in `.xcconfig` files, pass a plain string referencing your own build setting instead, and Voltra copies it through verbatim:
```ts
ios: {
groupIdentifier: '$(MY_APP_GROUP)',
}
```
`ios.project.entitlementsPath` works differently: it does not create a `VOLTRA_*` setting. Most projects need no config at all — when a build configuration already points at its own `.entitlements` file, `voltra apply` discovers it and writes the App Group in directly. Set `entitlementsPath` per build configuration only when a file cannot be discovered; each path is then written as that configuration’s `CODE_SIGN_ENTITLEMENTS` on the app target.
## Using Voltra CLI
[Section titled “Using Voltra CLI”](#using-voltra-cli)
Every time you change `voltra.config.ts`, reapply the native project changes (see the command above).
The JSX APIs and runtime APIs are the same as in the rest of the Voltra docs. Once `voltra apply` has set up your native project, continue with the platform guides for [iOS](/ios/introduction) and [Android](/android/introduction).
# Configuration
> Reference for the options passed when starting, updating, or ending a Live Activity, including dismissal policy and stale dates.
Voltra provides several configuration options to control Live Activity behavior, lifecycle, and appearance. These options can be used when starting, updating, or stopping Live Activities.
For Expo plugin configuration options (like `groupIdentifier`, `enablePushNotifications`, `deploymentTarget`, and `widgets`), see the [Plugin Configuration](/ios/api/plugin-configuration) documentation.
## Dismissal Policy
[Section titled “Dismissal Policy”](#dismissal-policy)
Voltra supports configuring how Live Activities behave after they end. You can control the dismissal timing using the `dismissalPolicy` option:
### Dismissal Policy Options
[Section titled “Dismissal Policy Options”](#dismissal-policy-options)
* **`'immediate'`** (default): The Live Activity is dismissed immediately when it ends
* **`{ after: number }`**: The Live Activity remains visible for the specified number of seconds after ending, then automatically dismisses
### Usage Examples
[Section titled “Usage Examples”](#usage-examples)
**Immediate dismissal (default behavior):**
```typescript
import { startLiveActivity } from '@use-voltra/ios-client'
await startLiveActivity(variants, {
dismissalPolicy: 'immediate', // or omit for default
})
```
**Delayed dismissal (keep visible for 30 seconds after ending):**
```typescript
await startLiveActivity(variants, {
dismissalPolicy: { after: 30 },
})
```
**Update dismissal policy for active Live Activities:**
```typescript
import { updateLiveActivity } from '@use-voltra/ios-client'
await updateLiveActivity(activityId, variants, {
dismissalPolicy: { after: 60 },
})
```
**Set dismissal policy when ending a Live Activity:**
```typescript
import { stopLiveActivity } from '@use-voltra/ios-client'
await stopLiveActivity(activityId, {
dismissalPolicy: { after: 10 },
})
```
The dismissal policy applies to both programmatic ending (`stopLiveActivity`) and natural ending (when timers reach their end time). This gives you fine-grained control over the user experience when Live Activities conclude.
## Additional Configuration Options
[Section titled “Additional Configuration Options”](#additional-configuration-options)
### Stale Date
[Section titled “Stale Date”](#stale-date)
The `staleDate` option allows you to specify when a Live Activity should be considered stale and automatically dismissed by the system.
```typescript
import { startLiveActivity } from '@use-voltra/ios-client'
// Dismiss the Live Activity after 1 hour
await startLiveActivity(variants, {
staleDate: Date.now() + 60 * 60 * 1000, // 1 hour from now
})
```
**Note:** If you provide a `staleDate` in the past, it will be ignored and the Live Activity will use default behavior.
### Relevance Score
[Section titled “Relevance Score”](#relevance-score)
The `relevanceScore` option helps iOS prioritize which Live Activities to display when space is limited. Higher scores (closer to 1.0) indicate more important activities.
```typescript
import { startLiveActivity } from '@use-voltra/ios-client'
// High priority Live Activity (e.g., active delivery)
await startLiveActivity(variants, {
relevanceScore: 0.8,
})
// Low priority Live Activity (e.g., background task)
await startLiveActivity(variants, {
relevanceScore: 0.2,
})
```
**Valid range:** 0.0 to 1.0 (default: 0.0)
### Channel ID (broadcast push, iOS 18+)
[Section titled “Channel ID (broadcast push, iOS 18+)”](#channel-id-broadcast-push-ios-18)
The `channelId` option subscribes the Live Activity to a broadcast channel for server-side updates. When provided, the activity receives updates via broadcast push notifications instead of individual device tokens—one server notification updates all activities on that channel. Requires `enablePushNotifications: true` and the Broadcast Capability enabled in your Apple Developer account.
```typescript
import { startLiveActivity } from '@use-voltra/ios-client'
await startLiveActivity(variants, {
activityName: 'match-123',
channelId: 'CTrNsYq/Ee8AALLzHQaVlA==', // From APNs channel management
})
```
For full broadcast setup, see [Server-side updates - Broadcast push notifications](/ios/development/server-side-updates#broadcast-push-notifications-ios-18).
These options can be used together with dismissal policy and other configuration options:
```typescript
await startLiveActivity(variants, {
dismissalPolicy: { after: 30 },
staleDate: Date.now() + 2 * 60 * 60 * 1000, // 2 hours
relevanceScore: 0.7,
})
```
# Plugin configuration
> Reference for the iOS Voltra Expo plugin options: groupIdentifier, enablePushNotifications, liveActivities, deploymentTarget, and widgets.
The Voltra Expo config plugin accepts several configuration options in your `app.json` or `app.config.js`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"groupIdentifier": "group.your.bundle.identifier",
"enablePushNotifications": true,
"deploymentTarget": "18.0",
"targetName": "MyAppLiveActivity",
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"description": "Shows current weather conditions",
"supportedFamilies": ["systemSmall", "systemMedium", "systemLarge"],
"initialStatePath": "./widgets/weather-initial.tsx"
}
]
}
]
]
}
}
```
## Configuration options
[Section titled “Configuration options”](#configuration-options)
### `groupIdentifier` (optional)
[Section titled “groupIdentifier (optional)”](#groupidentifier-optional)
App Group identifier for sharing data between your app and the widget extension. Required if you want to:
* Forward component events (like button taps) from Live Activities to your JavaScript code
* Share images between your app and the extension
* Use image preloading features
* Update entry-based Dynamic Widgets with runtime props
* Use Dynamic Live Activities
**Format:** Must start with `group.` (e.g., `group.your.bundle.identifier`)
### `enablePushNotifications` (optional)
[Section titled “enablePushNotifications (optional)”](#enablepushnotifications-optional)
Enable server-side updates for Live Activities via Apple Push Notification Service (APNS). When enabled, you can update Live Activities even when your app is in the background or terminated.
**Type:** `boolean`\
**Default:** `false`
### `liveActivities` (optional)
[Section titled “liveActivities (optional)”](#liveactivities-optional)
Bundled Dynamic Live Activity definitions. Every declaration has a stable `id` and an `entry` module that default-exports the renderer function. IDs use only alphanumeric characters and underscores, and are unique within this collection; they are separate from Dynamic Widget IDs.
When this array is non-empty, `groupIdentifier` is required. See [Dynamic Live Activities](/ios/development/dynamic-live-activities) for the entry signature, lifecycle APIs, and push payload contract.
### `deploymentTarget` (optional)
[Section titled “deploymentTarget (optional)”](#deploymenttarget-optional)
iOS deployment target version for the widget extension. If not provided, defaults to `17.0`. This allows the widget extension to have its own deployment target independent of the main app.
**Type:** `string` **Default:** `"17.0"` **Example:** `"18.0"`
**Note:** Code signing settings (development team, provisioning profiles) are automatically synchronized from the main app target, but the deployment target can be set independently.
### `targetName` (optional)
[Section titled “targetName (optional)”](#targetname-optional)
Custom target name for the widget extension. If not provided, defaults to `{AppName}LiveActivity` where `AppName` is your app’s sanitized name.
Useful for matching existing provisioning profiles, credentials, or naming conventions (e.g., when migrating from `@bacons/apple-targets`).
**Type:** `string` **Default:** `"{AppName}LiveActivity"` **Example:** `"widget"`, `"MyAppLiveActivity"`
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"groupIdentifier": "group.your.bundle.identifier",
"targetName": "widget"
}
]
]
}
}
```
### `widgets` (optional)
[Section titled “widgets (optional)”](#widgets-optional)
Array of widget configurations for Home Screen widgets. Each widget will be available in the iOS widget gallery.
**Widget Configuration Properties:**
* `id`: Unique identifier for the widget (alphanumeric with underscores only)
* `displayName`: Name shown in the widget gallery (plain string, or per-locale map like `{ "en": "Weather", "pl": "Pogoda" }`; locale keys are BCP‑47-style tags)
* `description`: Description shown in the widget gallery (same localization rules as `displayName`)
* `kind` (optional): WidgetKit kind of the widget. Defaults to `Voltra_Widget_`; see [Keeping the kind of an existing widget](#keeping-the-kind-of-an-existing-widget)
* `supportedFamilies`: Array of supported widget sizes (`systemSmall`, `systemMedium`, `systemLarge`)
* `initialStatePath`: (optional) Project-relative path to a file that exports initial widget state, **or** a locale map of paths for localized build-time pre-rendering (see [Widget Pre-rendering](/ios/development/widget-pre-rendering))
* `serverUpdate`: (optional) Fetch the widget’s content on a schedule. Without `entry` the server returns a rendered payload; with `entry` it returns plain JSON that the widget renders on the device. `url` is optional — leave it out to supply one at runtime. See [Server-driven widgets](/ios/development/server-driven-widgets) for full details.
* `url`: The Voltra SSR endpoint URL
* `intervalMinutes`: Update interval in minutes (default: `15`)
* `refresh`: Show a native refresh button (default: `false`, requires iOS 17+)
* `appIntent`: (optional, Dynamic Widgets, iOS 17+) Parameters the user edits in the Edit Widget sheet. Each parameter has a `name`, a `title` (plain string or locale map), an optional `default`, and optional `options` (`[{ "value": "metric", "title": "Metric" }]`) that turn the field into a picker. See [Configurable Widgets](/ios/development/configurable-widgets)
**Example:**
```json
{
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"description": "Current weather conditions",
"supportedFamilies": ["systemSmall", "systemMedium", "systemLarge"],
"initialStatePath": {
"en": "./widgets/weather-initial.tsx",
"pl": "./widgets/weather-initial-pl.tsx"
},
"serverUpdate": {
"url": "https://api.example.com/widgets/render",
"intervalMinutes": 30,
"refresh": true
}
}
]
}
```
### Keeping the kind of an existing widget
[Section titled “Keeping the kind of an existing widget”](#keeping-the-kind-of-an-existing-widget)
WidgetKit identifies a widget placed on the Home Screen by its extension bundle identifier and its `kind`. When you migrate an existing WidgetKit widget to Voltra, keep both so users don’t have to remove and re-add the widget: set `targetName` to the name of your existing extension target and `kind` to the `kind` your `WidgetConfiguration` used.
```json
{
"targetName": "MyWidgets",
"widgets": [
{
"id": "streak",
"kind": "StreakWidget",
"displayName": "Streak",
"description": "Your daily streak"
}
]
}
```
The `id` stays the handle you use from JavaScript (`updateWidget('streak', ...)`), only the WidgetKit kind changes. Kinds must be unique across widgets. This works the same way in `voltra.config.ts` when you use the [React Native CLI setup](/getting-started/react-native-cli).
### Localizing `displayName` and `description`
[Section titled “Localizing displayName and description”](#localizing-displayname-and-description)
Use a locale map when the widget gallery label should be translated:
```json
{
"widgets": [
{
"id": "weather",
"displayName": {
"en": "Weather",
"pl": "Pogoda",
"zh-Hans": "天气"
},
"description": {
"en": "Current weather conditions",
"pl": "Aktualne warunki pogodowe",
"zh-Hans": "当前天气状况"
}
}
]
}
```
Use BCP-47-style locale tags such as `en`, `en-US`, `pt-BR`, or `zh-Hans`.
Fallback behavior:
* Voltra first tries the device locale.
* If there is no exact match, it falls back to the language-only match.
* If there is still no match, it prefers an English locale such as `en` or `en-US`.
* If no English entry exists, it uses the first configured locale.
### Languages widgets can use
[Section titled “Languages widgets can use”](#languages-widgets-can-use)
Widgets declare the same languages as the app, so `env.locale` resolves to the same language the app runs in. The list comes from the Expo `locales` config keys, `ios.infoPlist.CFBundleLocalizations`, every locale used in a widget locale map, and the app’s development language (`ios.infoPlist.CFBundleDevelopmentRegion`, otherwise `en`). A language missing from this list is never used for `env.locale`, even when the user prefers it. See [Localization](/ios/development/localization#declare-the-languages-your-app-supports).
# Charts (iOS)
> Build bar, line, area, point, rule, and sector charts in iOS Live Activities and widgets with Voltra.Chart and its mark components.
Use charts in Live Activities and widgets to show trends, comparisons, progress, or composition at a glance. You can mix bars, lines, areas, points, rules, and sectors in a single chart.
Note
Charts require iOS 16.0+. SectorMark (pie/donut) requires iOS 17.0+.
Caution
Mark components (`BarMark`, `LineMark`, etc.) must be **direct children** of ``. They cannot be wrapped in custom components. For example, this will not work:
```tsx
// This won't work — marks are not direct children
function MyMarks() {
return
}
```
Instead, always place marks directly inside Chart:
```tsx
```
## Basic Usage
[Section titled “Basic Usage”](#basic-usage)
Wrap one or more mark components inside ``:
```tsx
```
## Data Types
[Section titled “Data Types”](#data-types)
All marks except `RuleMark` take a `data` prop. There are two data shapes depending on the mark type:
```typescript
// BarMark, LineMark, AreaMark, PointMark
type ChartDataPoint = {
x: string | number // Categorical ("Jan") or numeric (42)
y: number
series?: string // Optional — groups data for multi-series charts
}
// SectorMark
type SectorDataPoint = {
value: number // Proportional angular value
category: string // Sector label
}
```
## Marks
[Section titled “Marks”](#marks)
### BarMark
[Section titled “BarMark”](#barmark)
Use bars when people need to compare values across categories.
**Parameters:**
* `data` (ChartDataPoint\[], required): The data points.
* `color` (string, optional): Fill color.
* `cornerRadius` (number, optional): Rounded bar corners.
* `width` (number, optional): Fixed bar width.
* `stacking` (string, optional): `"grouped"` (side by side).
```tsx
```
***
### LineMark
[Section titled “LineMark”](#linemark)
Use a line when the shape of change matters more than individual columns.
**Parameters:**
* `data` (ChartDataPoint\[], required): The data points.
* `color` (string, optional): Line color.
* `lineWidth` (number, optional): Stroke width in points.
* `interpolation` (string, optional): Curve type — `"linear"`, `"monotone"`, `"catmullRom"`, `"cardinal"`, `"stepStart"`, `"stepCenter"`, or `"stepEnd"`.
* `symbol` (string, optional): Symbol at each point — `"circle"`, `"square"`, `"triangle"`, `"diamond"`, `"pentagon"`, `"cross"`, `"plus"`, or `"asterisk"`.
```tsx
```
***
### AreaMark
[Section titled “AreaMark”](#areamark)
Use an area chart when you want the overall volume or rise/fall pattern to read quickly.
**Parameters:**
* `data` (ChartDataPoint\[], required): The data points.
* `color` (string, optional): Fill color.
* `interpolation` (string, optional): Same options as LineMark.
```tsx
```
***
### PointMark
[Section titled “PointMark”](#pointmark)
Use points for sparse measurements, scatter plots, or to emphasize exact observations.
**Parameters:**
* `data` (ChartDataPoint\[], required): The data points.
* `color` (string, optional): Point color.
* `symbol` (string, optional): Same options as LineMark.
* `symbolSize` (number, optional): Symbol size in points.
```tsx
```
***
### RuleMark
[Section titled “RuleMark”](#rulemark)
A horizontal or vertical reference line. Unlike other marks, RuleMark has no `data` array.
**Parameters:**
* `yValue` (number, optional): Draw a horizontal line at this y value.
* `xValue` (string | number, optional): Draw a vertical line at this x value.
* `color` (string, optional): Line color.
* `lineWidth` (number, optional): Stroke width in points.
If both `xValue` and `yValue` are provided, Voltra renders both lines.
```tsx
```
***
### SectorMark
[Section titled “SectorMark”](#sectormark)
Pie and donut charts. Requires iOS 17+.
**Parameters:**
* `data` (SectorDataPoint\[], required): Sector data with `value` and `category`.
* `color` (string, optional): Fill color (overrides automatic coloring).
* `innerRadius` (number, optional): Ratio from 0 to 1. `0` = pie chart, any value above `0` = donut chart.
* `outerRadius` (number, optional): Ratio from 0 to 1.
* `angularInset` (number, optional): Gap between sectors in degrees.
```tsx
// Pie chart
// Donut chart
```
## Chart Props
[Section titled “Chart Props”](#chart-props)
The `` container accepts these props in addition to the standard Voltra `style` prop:
| Prop | Type | Description |
| ---------------------- | ---------------------------------------------------------------------------- | --------------------------------------- |
| `xAxisVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the x-axis |
| `xAxisGridStyle` | `{ visible?: boolean; color?: string; lineWidth?: number; dash?: number[] }` | Control x-axis grid lines |
| `yAxisVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the y-axis |
| `yAxisGridStyle` | `{ visible?: boolean; color?: string; lineWidth?: number; dash?: number[] }` | Control y-axis grid lines |
| `legendVisibility` | `"automatic" \| "visible" \| "hidden"` | Show or hide the legend |
| `foregroundStyleScale` | `Record` | Map series names to colors |
| `yScale` | `{ min?: number; max?: number }` | Pin the y-axis lower and/or upper bound |
## Value Range
[Section titled “Value Range”](#value-range)
By default the y-axis follows the data. Use `yScale` when a chart needs a fixed window instead — a percentage that should always read against 100, or a series whose swings you want to keep comparable between updates:
```tsx
```
Either bound can stand alone. `yScale={{ min: 0 }}` keeps the baseline at zero and lets the top follow the data, which is the usual way to stop a line chart from exaggerating small changes. Values outside the pinned range are clipped to the plot.
## Grid Lines
[Section titled “Grid Lines”](#grid-lines)
Use `xAxisGridStyle` and `yAxisGridStyle` when the default grid is too busy or not visible enough for your design:
```tsx
```
## Multi-Series Charts
[Section titled “Multi-Series Charts”](#multi-series-charts)
Add a `series` field to your data points when you want multiple datasets in the same chart. Use `foregroundStyleScale` to keep those series colors consistent:
```tsx
```
Without `foregroundStyleScale`, colors are chosen automatically.
For side-by-side bars, set `stacking="grouped"`:
```tsx
```
## Combining Marks
[Section titled “Combining Marks”](#combining-marks)
Mix mark types when one chart needs both context and emphasis, such as bars for totals plus a rule for a target:
```tsx
```
## Sparkline / Minimal Style
[Section titled “Sparkline / Minimal Style”](#sparkline--minimal-style)
Hide axes and legend for a clean, compact visualization:
```tsx
```
## Widget / Live Activity Notes
[Section titled “Widget / Live Activity Notes”](#widget--live-activity-notes)
Charts in widgets and Live Activities are static. Focus on a clear snapshot of the data rather than interactions like panning or scrolling.
The `` component supports the full Voltra style system on its container — padding, background, borders, corner radius, shadows, and sizing all work:
```tsx
```
# Interactive Controls (iOS)
> Reference for Voltra iOS interactive components: Button, Link, and Toggle, which trigger events or open URLs from Live Activities.
User interface controls that respond to user interaction in Live Activities.
***
## Button
[Section titled “Button”](#button)
An interactive button component that triggers in-app events via interaction intents.
**Parameters:**
* `buttonStyle` (string, optional): Visual style of the button:
* `"automatic"` - System-determined style
* `"bordered"` - Bordered style
* `"borderedProminent"` - Bordered with prominent fill
* `"plain"` - Plain style without border
* `"borderless"` - Borderless style
**Apple Documentation:** [Button](https://developer.apple.com/documentation/swiftui/button)
**Availability:** iOS 17.0+ (interaction intents)
### Usage
[Section titled “Usage”](#usage)
Buttons fire interaction events that you can handle in your app:
```tsx
Play Music
```
Handle the event:
```typescript
import { addVoltraListener } from '@use-voltra/ios-client'
const subscription = addVoltraListener('interaction', (event) => {
if (event.identifier === 'play-button') {
// Handle play action
}
})
```
### Examples
[Section titled “Examples”](#examples)
**Basic button:**
```tsx
Save Changes
```
**Button with icon:**
```tsx
Delete
```
***
## Link
[Section titled “Link”](#link)
A navigable link component that opens a URL when tapped. Uses SwiftUI’s native Link for semantic navigation.
**Parameters:**
* `destination` (string, required): URL to navigate to when tapped. Supports both absolute URLs and relative paths.
**Apple Documentation:** [Link](https://developer.apple.com/documentation/swiftui/link)
**Availability:** iOS 14.0+
### URL Normalization
[Section titled “URL Normalization”](#url-normalization)
Link automatically normalizes URLs using your app’s URL scheme:
* Absolute URLs: Used as-is (`"myapp://orders/123"`, `"https://example.com"`)
* Relative with `/`: `"/settings"` → `"myapp://settings"`
* Relative without `/`: `"help"` → `"myapp://help"`
### Examples
[Section titled “Examples”](#examples-1)
**Link with absolute URL:**
```tsx
Order #123Tap to view details
```
**Link with relative path:**
```tsx
Open Settings
```
### When to use Link vs Button
[Section titled “When to use Link vs Button”](#when-to-use-link-vs-button)
| Feature | Link | Button |
| ---------------- | ------------------------------ | ------------------------------------------ |
| **Use Case** | Navigation to URLs | In-app actions/events |
| **Visual** | Unstyled (custom via children) | Button styling (bordered, prominent, etc.) |
| **iOS Version** | 14.0+ | 17.0+ |
| **Tap Behavior** | Opens URL | Fires interaction event |
| **Mechanism** | SwiftUI Link | AppIntents (VoltraInteractionIntent) |
***
## Toggle
[Section titled “Toggle”](#toggle)
Toggles a boolean state via an intent. Fires an interaction event when changed.
**Parameters:**
* `defaultValue` (boolean, optional): Initial toggle state (default: `false`)
**Apple Documentation:** [Toggle](https://developer.apple.com/documentation/swiftui/toggle)
**Availability:** iOS 17.0+
**Example:**
```tsx
```
Handle toggle events:
```typescript
import { addVoltraListener } from '@use-voltra/ios-client'
const subscription = addVoltraListener('interaction', (event) => {
if (event.identifier === 'notifications-toggle') {
// Handle toggle state change
}
})
```
# Layout & Containers (iOS)
> Reference for Voltra iOS layout components: stacks, alignment and offsets, View, Spacer, and other containers that arrange child elements.
Components that arrange other elements or provide structural grouping.
## Alignment & Positioning
[Section titled “Alignment & Positioning”](#alignment--positioning)
Voltra uses SwiftUI’s native positioning model. Instead of CSS-style `position: absolute` with `top`/`left`/`right`/`bottom`, you use:
1. **Stack `alignment` props** - Position children within their container
2. **`offsetX`/`offsetY` styles** - Fine-tune individual element positions after alignment (positive `offsetX` moves right, positive `offsetY` moves down)
Each stack type has different alignment options based on its layout direction.
***
### VStack
[Section titled “VStack”](#vstack)
A vertical stack container that arranges its children in a column.
**Parameters:**
* `spacing` (number, optional): Spacing between children in points
* `alignment` (string, optional): Horizontal alignment of children:
* `"leading"` - Align to left edge
* `"center"` (default) - Align to center
* `"trailing"` - Align to right edge
**Apple Documentation:** [VStack](https://developer.apple.com/documentation/swiftui/vstack)
***
### HStack
[Section titled “HStack”](#hstack)
A horizontal stack container that arranges its children in a row.
**Parameters:**
* `spacing` (number, optional): Spacing between children in points
* `alignment` (string, optional): Vertical alignment of children:
* `"top"` - Align to top edge
* `"center"` (default) - Align to center
* `"bottom"` - Align to bottom edge
* `"firstTextBaseline"` - Align to first text baseline
* `"lastTextBaseline"` - Align to last text baseline
**Apple Documentation:** [HStack](https://developer.apple.com/documentation/swiftui/hstack)
***
### ZStack
[Section titled “ZStack”](#zstack)
A depth-based stack container that overlays its children on top of each other. Use ZStack when you need to layer elements, such as placing a badge over an image.
**Parameters:**
* `alignment` (string, optional): Positions ALL children at the specified alignment point. Available values:
* `"center"` (default) - Center of the stack
* `"leading"` - Left edge (or right in RTL)
* `"trailing"` - Right edge (or left in RTL)
* `"top"` - Top edge
* `"bottom"` - Bottom edge
* `"topLeading"` - Top-left corner
* `"topTrailing"` - Top-right corner
* `"bottomLeading"` - Bottom-left corner
* `"bottomTrailing"` - Bottom-right corner
**Apple Documentation:** [ZStack](https://developer.apple.com/documentation/swiftui/zstack)
#### Positioning with ZStack
[Section titled “Positioning with ZStack”](#positioning-with-zstack)
**Example: Badge overlay**
```tsx
{/* Image defines the ZStack size */}
{/* Badge is positioned at top-right, then nudged with offset */}
3
```
***
### View
[Section titled “View”](#view)
A flexible container that **always uses flexbox layout**, unlike VStack and HStack which use native SwiftUI stacks. See the [Flexbox Layout](/ios/development/flexbox-layout) guide for details.
**Style Properties:**
View responds to flexbox style properties set via the `style` prop:
* `flexDirection`: `'row'` | `'column'` (default: `'column'`)
* `alignItems`: `'flex-start'` | `'center'` | `'flex-end'` | `'stretch'`
* `justifyContent`: `'flex-start'` | `'center'` | `'flex-end'` | `'space-between'` | `'space-around'` | `'space-evenly'`
* `gap`: Spacing between children in points
**Example:**
```tsx
// Horizontal layout with space between
LeftCenterRight
// Vertical layout with centered items
Success
```
**When to use View:**
* You need React Native-style flexbox behavior
* You want dynamic `flexDirection` (switching between row/column)
* You need `justifyContent` spacing modes
**When to use VStack/HStack:**
* Simple vertical or horizontal layouts
* You want SwiftUI’s native stack performance
* You need SwiftUI-specific alignment (like firstTextBaseline)
**Availability:** iOS 16.0+
**Learn More:** [Flexbox Layout Guide](/ios/development/flexbox-layout)
***
### Spacer
[Section titled “Spacer”](#spacer)
A flexible space component that expands to fill available space in its container.
**Parameters:**
* `minLength` (number, optional): Minimum length
**Apple Documentation:** [Spacer](https://developer.apple.com/documentation/swiftui/spacer)
***
### GroupBox
[Section titled “GroupBox”](#groupbox)
A grouped content container that visually groups related content with a styled background.
**Parameters:** None
**Apple Documentation:** [GroupBox](https://developer.apple.com/documentation/swiftui/groupbox)
***
### GlassContainer
[Section titled “GlassContainer”](#glasscontainer)
A Liquid Glass container that wraps Apple’s [`GlassEffectContainer`](https://developer.apple.com/documentation/swiftui/glasseffectcontainer) to provide a modern glassmorphism effect for grouping content.
iOS 26 SDK Required
This component uses Apple’s `GlassEffectContainer` API which requires **Xcode with iOS 26 SDK** to build. If you’re using an older Xcode version, you’ll encounter build errors:
```plaintext
- value of type 'some View' has no member 'glassEffect'
- cannot find 'GlassEffectContainer' in scope
```
**Workaround:** Avoid using this component until iOS 26 SDK is available in your Xcode version. At runtime, devices with iOS < 26 will gracefully fall back to a regular container without the glass effect.
**Parameters:**
* `spacing` (number, optional): Spacing between glass elements
**Availability:**
* **Build:** Requires Xcode with iOS 26 SDK (uses `GlassEffectContainer` API)
* **Runtime:** iOS 26+ for glass effect, graceful fallback on earlier versions
**Apple Documentation:** [GlassEffectContainer](https://developer.apple.com/documentation/swiftui/glasseffectcontainer)
# Components Overview (iOS)
> Overview of the SwiftUI primitives Voltra exposes for Live Activities and widgets, grouped into layout, visual, status, and interactive components.
Voltra provides SwiftUI primitives with JSX bindings, allowing developers to create rich, interactive Live Activities using React/JSX syntax.
## Getting Started
[Section titled “Getting Started”](#getting-started)
Import iOS primitives from `@use-voltra/ios` and use the `Voltra` namespace:
```tsx
import { Voltra } from '@use-voltra/ios'
const MyComponent = () => {
// Use any component
return (
Hello Live Activity!Tap me
)
}
```
## Component Categories
[Section titled “Component Categories”](#component-categories)
Voltra organizes its components into categories:
### Layout & Containers
[Section titled “Layout & Containers”](#layout--containers)
Components that arrange other elements or provide structural grouping. These include stacks (VStack, HStack, ZStack), spacers, and container components like GroupBox and GlassContainer.
[See all layout & container components →](/ios/components/layout)
### Visual Elements & Typography
[Section titled “Visual Elements & Typography”](#visual-elements--typography)
Static or decorative elements used to display content. This category includes Text, Label, Image, Symbol, and visual effects like LinearGradient, Mask, and Divider.
[See all visual elements & typography components →](/ios/components/visual)
### Data Visualization & Status
[Section titled “Data Visualization & Status”](#data-visualization--status)
Components for displaying data and status information. This includes progress indicators (LinearProgressView, CircularProgressView), gauges, and timers for showing dynamic information in Live Activities.
[See all data visualization & status components →](/ios/components/status)
### Interactive Controls & Navigation
[Section titled “Interactive Controls & Navigation”](#interactive-controls--navigation)
User interface controls that respond to user interaction and navigation. This category includes Button and Toggle components for interactive Live Activities, plus Link for semantic URL navigation.
[See all interactive control & navigation components →](/ios/components/interactive)
# Data Visualization & Status (iOS)
> Reference for Voltra iOS components that show values and progress over time, including LinearProgressView and its timer-based mode.
Components specifically designed to show dynamic values or states over time in Live Activities and Widgets.
### LinearProgressView
[Section titled “LinearProgressView”](#linearprogressview)
A horizontal progress bar that displays determinate progress or timer-based progress.
#### Limitations
[Section titled “Limitations”](#limitations)
* When using `timerInterval` for smooth animations, custom styling properties such as `height`, `trackColor`, `cornerRadius`, and the `thumb` component are ignored. The component will use the default system appearance in this mode.
***
### CircularProgressView
[Section titled “CircularProgressView”](#circularprogressview)
A circular progress indicator that displays determinate progress or timer-based progress.
#### Limitations
[Section titled “Limitations”](#limitations-1)
* While `timerInterval` is supported, the progress ring will not animate continuously. It only updates its visual state when the component state is refreshed. For a smooth, live-animating progress bar, use `LinearProgressView`.
***
### Gauge
[Section titled “Gauge”](#gauge)
A gauge indicator for progress visualization (iOS 16+).
***
### Timer
[Section titled “Timer”](#timer)
A flexible component for displaying live-updating time intervals. Crucial for Live Activities, it uses native SwiftUI text interpolation to ensure the time updates automatically on the lock screen and in the Dynamic Island without requiring background updates from React Native.
**Modes:**
* **Timer Mode:** For fixed intervals (countdowns or counting up to a target). Requires `endAtMs` or `durationMs`.
* **Stopwatch Mode:** For open-ended intervals counting up from a starting point. Requires `startAtMs` and `direction="up"`, but both `endAtMs` and `durationMs` must be omitted.
**Parameters:**
* `startAtMs` (number, optional): Start time in milliseconds since epoch.
* `endAtMs` (number, optional): End time in milliseconds since epoch.
* `durationMs` (number, optional): Duration in milliseconds. Used if `endAtMs` is omitted.
* `direction` (string, optional): Count direction. Can be `'up'` or `'down'`. Defaults to `'down'`.
* `textStyle` (string, optional): Formatting style.
* `'timer'`: Standard clock format (e.g., `05:00`).
* `'relative'`: Relative format (e.g., `5m`).
* `showHours` (boolean, optional): Whether to show hours (e.g., `1:30:00` vs `90:00`). Defaults to `false`.
* `textTemplates` (string, optional): JSON-encoded object with `running` and `completed` templates. Use `{time}` as a placeholder.
**Examples:**
```tsx
// Timer Mode: Countdown 5 minutes
// Stopwatch Mode: Count up indefinitely from now
// Relative Timer with Template
```
# Visual Elements & Typography (iOS)
> Reference for Voltra iOS visual components such as Text, Image, Symbol, and other elements that display static content.
Static or decorative elements used to display content.
### Text
[Section titled “Text”](#text)
Displays text content.
**Parameters:**
* `numberOfLines` (number, optional): Maximum number of lines to display
***
### Label
[Section titled “Label”](#label)
A semantic label that can display both an icon and title text.
**Parameters:**
* `title` (string, optional): Text content for the label
* `systemImage` (string, optional): SF Symbol name for the label icon
***
### Image
[Section titled “Image”](#image)
Displays bitmap images from the asset catalog or base64 encoded data.
**Parameters:**
* `source` (object, optional): Image source object (`assetName` or `base64`)
* `resizeMode` (string, optional): `"cover"`, `"contain"`, `"stretch"`, `"repeat"`, or `"center"`
* `fallback` (ReactNode, optional): Custom content rendered when the image is missing
**Styling the fallback:**
To add a background color when an image is missing, use `backgroundColor` in the `style` prop:
```jsx
```
***
### Symbol
[Section titled “Symbol”](#symbol)
Displays SF Symbols (system icons) with configuration options.
***
### Divider
[Section titled “Divider”](#divider)
A visual divider component.
***
### LinearGradient
[Section titled “LinearGradient”](#lineargradient)
A linear gradient background that can contain children.
***
### Mask
[Section titled “Mask”](#mask)
Masks content using any Voltra element as the mask shape.
# Configurable Widgets
> Let users edit widget parameters in the iOS Edit Widget sheet by adding appIntent parameters to a Dynamic Widget.
Configurable widgets let users edit widget parameters in the native iOS Edit Widget sheet. Use them when a Dynamic Widget needs a few user-editable knobs, such as a label, unit, theme, or source.
It requires iOS 17+, because Voltra wires it through `AppIntentConfiguration`.
## How it works
[Section titled “How it works”](#how-it-works)
1. Define a Dynamic Widget module with a default export.
2. Add `entry` and `appIntent.parameters` to the widget config in `app.json`.
3. Read the selected values from `env.configuration` in your widget’s JSX.
4. Build and install the app on a real iPhone, add the widget to the Home Screen, then long-press it and tap **Edit Widget** to change parameters — your widget re-reads `env.configuration` with the new values.
Each parameter has:
* `name`: key that appears in `env.configuration`
* `title`: label shown in the Edit Widget sheet, as a plain string or a locale map
* `default`: code-defined starting value before the user changes anything
* `options` (optional): fixed values to pick from, each with a `value` and a `title`. The sheet shows a picker with the titles instead of a free-text field, and `env.configuration` receives the `value`. `default` must be one of the values; without a `default`, the first option is used.
## How to use it
[Section titled “How to use it”](#how-to-use-it)
```tsx
import { Voltra, type WidgetEnvironment } from '@use-voltra/ios'
type GreetingConfig = { label?: string }
export default function GreetingWidget(
_props: object,
env: WidgetEnvironment = {} as WidgetEnvironment
) {
const label = env.configuration?.label ?? 'Hello'
return (
{label}
Edit me from the widget sheet.
)
}
```
Plugin config:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"widgets": [
{
"id": "greeting_widget",
"entry": "./widgets/ios/greeting-widget.tsx",
"displayName": "Greeting Widget",
"description": "A Dynamic Widget with user-editable parameters",
"supportedFamilies": ["systemSmall", "systemMedium"],
"initialStatePath": "./widgets/ios/greeting-widget.tsx",
"appIntent": {
"parameters": [
{
"name": "label",
"title": "Label",
"default": "Hello"
}
]
}
}
]
}
]
]
}
}
```
If you need more than one value, add more entries to `appIntent.parameters` and read each key from `env.configuration`.
## Offer fixed choices
[Section titled “Offer fixed choices”](#offer-fixed-choices)
When a parameter has a known set of values, list them as `options`. The sheet then shows a picker:
```json
{
"name": "units",
"title": "Units",
"default": "metric",
"options": [
{ "value": "metric", "title": "Metric" },
{ "value": "imperial", "title": "Imperial" }
]
}
```
`env.configuration.units` is `"metric"` or `"imperial"`, whichever the user picked.
Expo Prebuild and Voltra Apply stop with an error that names the parameter if `default` is not one of the values, a value is empty or listed twice, or an option has no `title`.
## Translate the Edit Widget sheet
[Section titled “Translate the Edit Widget sheet”](#translate-the-edit-widget-sheet)
iOS draws the Edit Widget sheet itself, so its text comes from `app.json` rather than from your widget code. `title` and `options[].title` accept locale maps, the same way `displayName` does. The sheet header shows the widget’s `displayName`, so translate it the same way:
```json
{
"id": "weather_widget",
"entry": "./widgets/ios/weather-widget.tsx",
"displayName": { "en": "Weather", "pl": "Pogoda" },
"description": { "en": "Current conditions", "pl": "Aktualne warunki" },
"appIntent": {
"parameters": [
{
"name": "units",
"title": { "en": "Units", "pl": "Jednostki" },
"default": "metric",
"options": [
{ "value": "metric", "title": { "en": "Metric", "pl": "Metryczne" } },
{ "value": "imperial", "title": { "en": "Imperial", "pl": "Imperialne" } }
]
}
]
}
}
```
iOS shows the sheet in the system language, and `setDynamicWidgetLocale` does not affect it. A language with no translation for a string shows your app’s development language instead. Rebuild the native app after changing these. See [Localization](/ios/development/localization) for how the app’s languages are declared.
## Notes
[Section titled “Notes”](#notes)
* `appIntent` only wires up for Dynamic Widgets.
* Defaults come from code, not from the native sheet.
* There is no `export` field in app.json for Dynamic Widgets.
* Use a real device to verify the Edit Widget flow.
# Custom Fonts
> Add custom fonts to iOS Live Activities and widgets through the plugin configuration or manually in Xcode, and use them with fontFamily.
Voltra supports custom fonts through the `fontFamily` style property.
## Adding Custom Fonts to Your Project
[Section titled “Adding Custom Fonts to Your Project”](#adding-custom-fonts-to-your-project)
Voltra supports custom fonts in your Live Activities and Widgets through two main methods:
### 1. Using Voltra’s Font Configuration (Recommended)
[Section titled “1. Using Voltra’s Font Configuration (Recommended)”](#1-using-voltras-font-configuration-recommended)
The simplest way is to specify fonts directly in the Voltra plugin configuration. This follows the same pattern as `expo-font`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"groupIdentifier": "group.com.example.app",
"fonts": ["./assets/fonts", "./assets/custom-font.ttf"]
}
]
]
}
}
```
The `fonts` array can include:
* Individual font files: `"./assets/fonts/CustomFont.ttf"`
* Entire directories: `"./assets/fonts"` (all fonts in the directory will be included)
* Supported formats: `.ttf`, `.otf`, `.woff`, `.woff2`
### 2. Adding Fonts Manually in Xcode
[Section titled “2. Adding Fonts Manually in Xcode”](#2-adding-fonts-manually-in-xcode)
For non-Expo projects or if you prefer manual configuration, you can add fonts directly to your Xcode project:
1. Add your font files (`.otf` or `.ttf`) to your Xcode project
2. Ensure they’re included in the Live Activity target’s “Copy Bundle Resources” build phase
3. Add the font file names to your `Info.plist` under the `UIAppFonts` key for Live Activity target
For detailed instructions, see Apple’s documentation on [Applying custom fonts to text](https://developer.apple.com/documentation/swiftui/applying-custom-fonts-to-text).
## Using Custom Fonts
[Section titled “Using Custom Fonts”](#using-custom-fonts)
Once your fonts are added to the project, you can use them with the `fontFamily` style property:
```tsx
import { Voltra } from '@use-voltra/ios'
const element = (
Text with Custom Font
)
```
Font Family Names
The font family name you use in `fontFamily` should match the font’s PostScript name, not the file name. You can find the PostScript name:
* In the Font Book app on macOS
* Using online tools like [fontdrop.info](https://fontdrop.info)
* In Xcode’s font picker
For example, the font file `Inter-Bold.ttf` has the PostScript name `Inter-Bold`.
## Font Weight with Custom Fonts
[Section titled “Font Weight with Custom Fonts”](#font-weight-with-custom-fonts)
When using `fontFamily`, the `fontWeight` style property is ignored since you typically specify the exact font variant (e.g., `Inter-Bold`, `Inter-Regular`). If you need different weights, add multiple font files and specify the complete font name:
```tsx
// Regular weight
Regular Text
// Bold weight
Bold Text
```
## Example with Google Fonts
[Section titled “Example with Google Fonts”](#example-with-google-fonts)
If you’re using Google Fonts via `@expo-google-fonts`, they work seamlessly with Voltra:
```json
{
"expo": {
"plugins": [
[
"expo-font",
{
"fonts": ["node_modules/@expo-google-fonts/inter/Inter_400Regular.ttf"]
}
]
]
}
}
```
```tsx
Text using Google Font
```
System Font Fallback
If `fontFamily` is not specified or the font cannot be found, Voltra will fall back to the system font with the specified `fontWeight`.
# Developing Live Activities
> Define Lock Screen and Dynamic Island variants for a Live Activity and use the APIs for building and testing them during development.
Voltra provides APIs that make building and testing Live Activities easier during development.
For bundled, on-device definitions that receive generic props rather than a rendered UI payload, see [Dynamic Live Activities](/ios/development/dynamic-live-activities).
## Supported variants
[Section titled “Supported variants”](#supported-variants)
Live Activities in iOS can appear in different contexts, and Voltra supports defining UI variants for each of these contexts. For detailed information about Live Activity design guidelines, see the [Apple Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/live-activities).
### Lock Screen
[Section titled “Lock Screen”](#lock-screen)
The `lockScreen` variant defines how your Live Activity appears on the lock screen. It can be either a ReactNode directly, or an object with content and optional styling:
```typescript
const variants = {
lockScreen: (
Your content here
),
}
```
To customize the system Lock Screen chrome, pass an object with `content` and `activityBackgroundTint`:
```typescript
const variants = {
lockScreen: {
activityBackgroundTint: '#101828',
content: (
Your content here
),
},
}
```
`activityBackgroundTint` is applied via SwiftUI’s `activityBackgroundTint(...)` modifier on iOS. Voltra currently accepts the same color formats handled by the native iOS parser:
* Hex colors such as `#RGB`, `#RGBA`, `#RRGGBB`, and `#RRGGBBAA`
* `rgb(...)` and `rgba(...)`
* `hsl(...)` and `hsla(...)`
* Named colors: `red`, `orange`, `yellow`, `green`, `mint`, `teal`, `cyan`, `blue`, `indigo`, `purple`, `pink`, `brown`, `white`, `gray`, `black`, `clear`, `transparent`, `primary`, `secondary`
Use `clear` or `transparent` to make the Live Activity background transparent.
If the string cannot be parsed as one of those formats, iOS ignores the tint.
The tint changes the Lock Screen and banner background. It does not change the background of the Live Activity in CarPlay; see [Background color in CarPlay](#background-color-in-carplay).
### Dynamic Island
[Section titled “Dynamic Island”](#dynamic-island)
The `island` variant defines how your Live Activity appears in the Dynamic Island (available on iPhone 14 Pro and later). The Dynamic Island has three display states:
* **Minimal**: A compact pill-shaped view that appears when the activity is in the background
* **Compact**: A slightly larger view with leading and trailing regions
* **Expanded**: A full-width view with center, leading, trailing, and bottom regions
```typescript
const variants = {
island: {
keylineTint: '#10B981', // Optional tint color for the Dynamic Island keyline
minimal: ,
compact: {
leading: Order,
trailing: Confirmed,
},
expanded: {
center: Order Confirmed,
leading: ,
trailing: ETA: 15 min,
bottom: Your order is being prepared,
},
},
}
```
`keylineTint` uses the same iOS color parser and accepted formats as `activityBackgroundTint`.
### Supplemental Activity Families (iOS 18+, watchOS 11+)
[Section titled “Supplemental Activity Families (iOS 18+, watchOS 11+)”](#supplemental-activity-families-ios-18-watchos-11)
The `supplementalActivityFamilies` variant defines how your Live Activity appears on Apple Watch Smart Stack and CarPlay displays. This variant is optional and works seamlessly with your existing lock screen and Dynamic Island variants.
```typescript
const variants = {
lockScreen: (
{/* iPhone lock screen content */}
),
island: {
/* Dynamic Island variants for iPhone */
},
supplementalActivityFamilies: {
small: (
12 minETA
),
},
}
```
If `supplementalActivityFamilies.small` is not provided, Voltra will automatically construct it from your Dynamic Island `compact` variant by combining the leading and trailing content in an HStack.
#### Background color in CarPlay
[Section titled “Background color in CarPlay”](#background-color-in-carplay)
In CarPlay, `activityBackgroundTint` has no effect. iOS draws the `small` layout on its own dark grey tile in both light and dark appearance, and `containerBackground` and `preferredColorScheme` don’t change it either. This is iOS behavior: Apple documents `activityBackgroundTint` as the background color of the Lock Screen presentation only.
To use a different background in CarPlay, give the root of your `small` layout `flex: 1` and a `backgroundColor`. An opaque fill covers the whole tile:
```typescript
supplementalActivityFamilies: {
small: (
12 min
),
},
```
Keep in mind:
* Padding on the root without `flex: 1` leaves the grey tile visible around the content.
* A translucent color blends with the grey tile and doesn’t replace it.
* The same `small` layout is also used on Apple Watch Smart Stack, so check how a filled background looks there.
* This was verified in Xcode 27’s CarPlay Simulator on an iPhone running iOS 27, not on a car head unit.
## Limitations
[Section titled “Limitations”](#limitations)
### Animations and Live Updates
[Section titled “Animations and Live Updates”](#animations-and-live-updates)
There are specific constraints on how content can animate or update:
* **Continuous Animations**: Custom continuous animations, such as rotating icons or elements moving along a path, are not supported.
* **Smooth Updates**: Per-second “live” updates are only supported by specific components designed for this purpose:
* `Timer`: For countdowns and stopwatches.
* `LinearProgressView`: When used with `timerInterval`.
* **Styling Trade-offs**: To enable smooth, system-driven animations (like a progress bar filling up in real-time), certain components may ignore custom styling properties (e.g., custom heights or thumb components) and fallback to standard system appearances.
All other components only update their visual state when a new activity state is pushed from your application.
## useLiveActivity
[Section titled “useLiveActivity”](#useliveactivity)
For React development, Voltra provides the `useLiveActivity` hook for integration with the component lifecycle and automatic updates during development.
Caution
Unfortunately, iOS suspends background apps after approximately 30 seconds. This means that if you navigate away from your app (for example, to check the Dynamic Island or lock screen), live reload and auto-update functionality will be paused.
```typescript
import { Voltra } from '@use-voltra/ios'
import { useLiveActivity } from '@use-voltra/ios-client'
function OrderLiveActivity({ orderId, status }) {
const variants = {
lockScreen: (
{status === 'confirmed' ? 'Order Confirmed' : 'Order Ready'}
{status === 'confirmed' ? 'Your order is being prepared' : 'Your order is ready for pickup'}
{status === 'ready' && (
I'm Here
)}
),
}
const { start, update, end, isActive } = useLiveActivity(variants, {
activityName: `order-${orderId}`,
autoStart: true, // Automatically start when component mounts
autoUpdate: true, // Automatically update when variants change
deepLinkUrl: `myapp://order/${orderId}`,
})
// Manual control if needed
const handleCancelOrder = async () => {
await end()
}
return (
Live Activity: {isActive ? 'Active' : 'Inactive'}
)
}
```
## VoltraView Component
[Section titled “VoltraView Component”](#voltraview-component)
For testing and development, Voltra provides a `VoltraView` component that renders Voltra JSX components directly in your React Native app, so you can test layouts and interactions before deploying to a real Live Activity.
```tsx
import { Voltra } from '@use-voltra/ios'
import { VoltraView } from '@use-voltra/ios-client'
function MyComponent() {
const handleInteraction = (event: VoltraInteractionEvent) => {
console.log('User interacted with:', event.identifier)
console.log('Payload:', event.payload)
}
return (
Test Live ActivityThis is how it will lookTest Button
)
}
```
**Props:**
* `id`: Unique identifier for the view (used for event filtering)
* `children`: Voltra JSX components to render
* `style`: React Native style for the container
* `onInteraction`: Callback for user interactions with buttons/toggles
**Hook Options:**
* `activityName`: Name of the Live Activity
* `autoStart`: Automatically start when component mounts
* `autoUpdate`: Automatically update when variants change
* `deepLinkUrl`: URL to open when Live Activity is tapped
**Hook Returns:**
* `start()`: Start the Live Activity
* `update()`: Update the Live Activity
* `end()`: Stop the Live Activity
* `isActive`: Boolean indicating if the Live Activity is currently active
# Developing Widgets
> Preview Voltra widget content at real iOS widget sizes with VoltraWidgetPreview and use the other APIs for developing Home Screen widgets.
Voltra provides APIs that make building and testing Home Screen widgets easier during development.
## VoltraWidgetPreview component
[Section titled “VoltraWidgetPreview component”](#voltrawidgetpreview-component)
`VoltraWidgetPreview` is a **React Native component** for testing and developing Voltra widget content. It renders Voltra JSX components at the exact dimensions of specific iOS widget families. This is useful for:
* Testing component layouts before deploying to widgets
* Previewing how your widget will look across different sizes
* Developing and iterating on widget content within your React Native app
Note
`VoltraWidgetPreview` is a regular React Native component. Use it in your React Native screens, not inside Voltra components.
```tsx
import { ScrollView, View } from 'react-native'
import { Voltra } from '@use-voltra/ios'
import { VoltraWidgetPreview } from '@use-voltra/ios-client'
function MyWidgetContent() {
return (
Weather WidgetSunny, 72°F
)
}
// Preview different widget sizes in your React Native screen
function WidgetTestingScreen() {
return (
)
}
```
**Props:**
* `family`: Widget family size to preview (systemSmall, systemMedium, systemLarge, etc.)
* `style`: Additional React Native styles to apply
* `id`: Unique identifier for the view (used for event filtering)
* `onInteraction`: Callback for user interactions with buttons/toggles
## updateWidget API
[Section titled “updateWidget API”](#updatewidget-api)
The `updateWidget` function allows you to update home screen widget content with new data.
Caution
Widget updates are throttled to around an update per minute. iOS limits how frequently widgets can be refreshed to preserve battery life and system performance.
```typescript
import { Voltra } from '@use-voltra/ios'
import { updateWidget } from '@use-voltra/ios-client'
await updateWidget('weather', {
systemSmall: 72°F,
systemMedium: (
72°FSunnyHigh: 78° Low: 65°
),
systemLarge: (
Weather72°F - SunnyHigh: 78° Low: 65°
),
}, { deepLinkUrl: 'myapp://weather' })
```
**Parameters:**
* `widgetId`: The widget identifier (as defined in your config plugin)
* `variants`: An object mapping widget families to specific content
* `options.deepLinkUrl`: URL to open when the widget is tapped
## scheduleWidget API
[Section titled “scheduleWidget API”](#schedulewidget-api)
For widgets that need to change throughout the day, `scheduleWidget` lets you batch multiple updates in advance. iOS will automatically display each entry at its scheduled time—even when your app isn’t running.
Tip
This is perfect for weather forecasts, calendar events, news rotation, or any content that changes on a predictable schedule.
```typescript
import { Voltra } from '@use-voltra/ios'
import { scheduleWidget } from '@use-voltra/ios-client'
// Schedule weather updates throughout the day
await scheduleWidget('weather', [
{
date: new Date('2026-01-16T09:00:00'),
variants: {
systemSmall: Morning: 65°F ☀️,
systemMedium: Good morning! 65°F and sunny
}
},
{
date: new Date('2026-01-16T15:00:00'),
variants: {
systemSmall: Afternoon: 72°F ☀️,
systemMedium: Afternoon: 72°F and sunny
}
},
{
date: new Date('2026-01-16T21:00:00'),
variants: {
systemSmall: Evening: 68°F 🌙,
systemMedium: Good evening! 68°F and clear
}
}
])
```
**Parameters:**
* `widgetId`: The widget identifier (as defined in your config plugin)
* `entries`: Array of timeline entries, each containing:
* `date`: When this content should be displayed
* `variants`: Widget content for different size families
* `deepLinkUrl` (optional): URL to open when tapping this specific entry
**With deep links per entry:**
```typescript
await scheduleWidget('news', [
{
date: new Date('2026-01-16T08:00:00'),
variants: {
systemSmall: Morning Headlines
},
deepLinkUrl: '/news/morning'
},
{
date: new Date('2026-01-16T20:00:00'),
variants: {
systemSmall: Evening Edition
},
deepLinkUrl: '/news/evening'
}
])
```
iOS System Constraints
iOS controls when widgets actually update based on battery level, widget visibility, and system load. While you can schedule entries at any interval, iOS typically enforces a minimum of \~15 minutes between updates. Entries scheduled more frequently may be delayed or coalesced.
**Best practices:**
* Schedule entries at realistic intervals (15+ minutes apart)
* Don’t schedule hundreds of entries—iOS has a daily refresh budget
* Use `updateWidget` for immediate one-time updates
* Use `scheduleWidget` for predictable, recurring content changes
## Widget configuration via Expo plugin
[Section titled “Widget configuration via Expo plugin”](#widget-configuration-via-expo-plugin)
Widgets are configured through the Voltra Expo config plugin. Add the widget configuration to your `app.json` or `app.config.js`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"description": "Current weather conditions",
"supportedFamilies": ["systemSmall", "systemMedium", "systemLarge"]
}
]
}
]
]
}
}
```
**Widget Configuration Properties:**
* `id`: Unique identifier for the widget (alphanumeric with underscores only)
* `displayName`: Name shown in the widget gallery
* `description`: Description shown in the widget gallery
* `supportedFamilies`: Array of supported widget sizes (defaults to systemSmall, systemMedium, systemLarge)
## Fallback logic for variants
[Section titled “Fallback logic for variants”](#fallback-logic-for-variants)
When a widget size doesn’t have specific content defined, Voltra automatically falls back to other available variants in this order:
1. `systemMedium` (preferred fallback for home screen widgets)
2. `systemSmall`
3. `systemLarge`
4. `systemExtraLarge`
5. `accessoryRectangular`
6. `accessoryCircular`
7. `accessoryInline`
This ensures your widget always displays content even when a specific size variant isn’t provided. For example, if you only define `systemSmall` and `systemLarge`, a `systemMedium` widget will use the `systemSmall` content.
```typescript
// Only defining systemSmall and systemLarge
await updateWidget('minimal', {
systemSmall: 72°F,
systemLarge: Weather: 72°F - Sunny,
})
// systemMedium will automatically use systemSmall content as fallback
```
## Additional widget APIs
[Section titled “Additional widget APIs”](#additional-widget-apis)
### getActiveWidgets
[Section titled “getActiveWidgets”](#getactivewidgets)
Detect which widgets are currently installed on the user’s home screen:
```typescript
import { getActiveWidgets } from '@use-voltra/ios-client'
const widgets = await getActiveWidgets()
// [{ name: 'weather', family: 'systemSmall', kind: '...' }]
```
See [Querying Active Widgets](/ios/development/querying-active-widgets) for more details.
### reloadWidgets
[Section titled “reloadWidgets”](#reloadwidgets)
Force widget timelines to refresh their content after updating shared resources like preloaded images:
```typescript
import { reloadWidgets } from '@use-voltra/ios-client'
// Reload specific widgets
await reloadWidgets(['weather', 'calendar'])
// Reload all widgets
await reloadWidgets()
```
### clearWidget / clearAllWidgets
[Section titled “clearWidget / clearAllWidgets”](#clearwidget--clearallwidgets)
Remove stored widget data, causing widgets to show their placeholder state:
```typescript
import { clearWidget, clearAllWidgets } from '@use-voltra/ios-client'
// Clear specific widget
await clearWidget('weather')
// Clear all widgets
await clearAllWidgets()
```
# Dynamic Live Activities
> Declare Dynamic Live Activities that bundle their rendering with the app and update from a props record sent by the app or a push.
Dynamic Live Activities are a separate engine from both legacy Live Activities and [Dynamic Widgets](/ios/development/dynamic-widgets).
A legacy Live Activity sends a fully rendered Voltra UI in every update. A Dynamic Live Activity bundles its rendering definition in the app and receives only a complete, JSON-compatible props record. Keep payloads small — but remember the definition ID and its props are basically a contract with whoever sends the push.
## Configure a definition
[Section titled “Configure a definition”](#configure-a-definition)
Install the iOS packages and `@use-voltra/metro`, then wrap the app Metro configuration as shown in [Dynamic Widgets: Set up Metro](/ios/development/dynamic-widgets#set-up-metro). Declare each Dynamic Live Activity in the iOS Voltra plugin. An App Group is mandatory, even if updates arrive only through ActivityKit pushes, because the extension uses it to deliver diagnostic render failures to the app.
app.json
```json
{
"expo": {
"ios": { "bundleIdentifier": "com.example.orders" },
"plugins": [
[
"@use-voltra/ios-client",
{
"groupIdentifier": "group.com.example.orders",
"enablePushNotifications": true,
"liveActivities": [
{
"id": "order_finished",
"entry": "./live-activities/order-finished.tsx"
}
]
}
]
]
}
}
```
IDs contain only letters, numbers, and underscores. They are unique only within `liveActivities`, so a Dynamic Widget may use the same ID. Run Expo Prebuild (or Voltra Apply) and make a new native build after changing this configuration.
The generated ActivityKit attributes type turns underscores into UpperCamelCase. The declaration above produces `VoltraOrderFinishedLiveActivityAttributes`; this exact name is required for a push-to-start payload.
## Write the entry
[Section titled “Write the entry”](#write-the-entry)
The entry must default-export a function with the signature `(props, environment) => LiveActivityVariants`. It returns the same Lock Screen, Dynamic Island, and optional supplemental-family shape as a legacy Live Activity.
live-activities/order-finished.tsx
```tsx
import { Voltra, type LiveActivityEnvironment } from '@use-voltra/ios'
type OrderFinishedProps = {
orderNumber?: string
status?: string
}
export default function OrderFinished(
props: OrderFinishedProps = {},
environment: LiveActivityEnvironment
) {
return {
lockScreen: (
Order #{props.orderNumber ?? '123'}{props.status ?? 'Preparing'}
{environment.isStale ? Status may be outdated : null}
),
island: {
compact: {
leading: Order,
trailing: ,
},
},
}
}
```
`LiveActivityEnvironment` provides `date`, `colorScheme`, `widgetRenderingMode`, `build`, `isStale`, the [locale fields](/ios/development/localization) (`locale`, `preferredLanguages`, `appLocale`, `layoutDirection`, `hourCycle`, `timeZone`, `measurementSystem`, `calendar` and `firstDayOfWeek`), and, for applicable iOS 18+ activity families, `activityFamily`. Pass `locale` to every `Intl` call and pick translations with `resolveLocale(environment, messages)`. It deliberately does not expose Home Screen widget fields such as `widgetFamily`, `showsWidgetContainerBackground`, or `configuration`.
To use SwiftUI modifiers that `style` does not cover, such as `contentTransition` or `privacySensitive`, see [Native modifiers](/ios/development/native-modifiers).
Props are opaque in V1. They must be a complete JSON-compatible object (strings, finite numbers, booleans, `null`, arrays, and plain nested objects). Each update replaces the whole record; it does not merge it. Voltra does not generate definition-specific prop types or validate that the producer supplied the props this entry expects.
## Start and update locally
[Section titled “Start and update locally”](#start-and-update-locally)
Use the explicit Dynamic APIs—do not use `startLiveActivity`, `updateLiveActivity`, or `useLiveActivity` for a bundled definition.
```tsx
import {
getDynamicLiveActivityDefinitionIds,
startDynamicLiveActivity,
updateDynamicLiveActivity,
useDynamicLiveActivity,
} from '@use-voltra/ios-client'
const activityId = await startDynamicLiveActivity(
'order_finished',
{ orderNumber: '123', status: 'Preparing' },
{ activityName: 'order-123', deepLinkUrl: 'myapp://orders/123' }
)
await updateDynamicLiveActivity(activityId, {
orderNumber: '123',
status: 'Ready for pickup',
})
const availableDefinitions = await getDynamicLiveActivityDefinitionIds()
// In a React component:
const activity = useDynamicLiveActivity('order_finished', { orderNumber: '123', status: 'Preparing' }, {
activityName: 'order-123',
autoStart: true,
autoUpdate: true,
})
```
The hook’s auto-update also sends the complete latest props object. `stopLiveActivity`, `endAllLiveActivities`, active-state checks, and shared lifecycle operations work across both engines. Updating through the wrong engine-specific API fails with a renderer-mismatch error. Local starts keep the existing replacement behavior: when replacement is enabled, an existing activity with the same name is ended across both engines.
For Fast Refresh in development, keep the generated host-graph import and enable targeted reload once at app startup:
```ts
import '@use-voltra/live-activity-hot-reload'
import { enableDynamicLiveActivityHotReload } from '@use-voltra/ios-client'
enableDynamicLiveActivityHotReload()
```
When Metro identifies the generated definition entry, only that definition is reloaded. A component-only Fast Refresh boundary does not re-evaluate its importer, so Voltra safely falls back to reloading all Dynamic Live Activity definitions. Legacy Live Activities and Dynamic Widgets are unaffected. A development bundle is served from `/voltra/live-activities/.bundle`; release bundles use the separate `voltra-live-activity-.bundle` asset prefix.
## Remote updates and payloads
[Section titled “Remote updates and payloads”](#remote-updates-and-payloads)
Push-to-start requires the generated type name in `attributes-type`. For `order_finished`, the Voltra-specific ActivityKit fields are exactly:
```json
{
"attributes-type": "VoltraOrderFinishedLiveActivityAttributes",
"attributes": {
"name": "order-123",
"deepLinkUrl": "myapp://orders/123"
},
"content-state": {
"props": {
"orderNumber": "123",
"status": "Preparing"
}
}
}
```
`deepLinkUrl` is optional. Update and end pushes omit static `attributes`; an update replaces the complete `content-state.props` record. Standard ActivityKit/APNs fields—including timestamps, alerts, stale dates, relevance scores, dismissal dates, and channel fields—continue to use their normal semantics.
For server producers, `DynamicLiveActivityProps`, `DynamicLiveActivityContentState`, and `getDynamicLiveActivityAttributesType(definitionId)` are exported from both `@use-voltra/ios` and `@use-voltra/ios-server`. V1 intentionally has no dynamic render or payload-construction helper: props go directly into ActivityKit content state.
Voltra checks the existing 4 KB ActivityKit limit for encoded attributes plus state on a local start, and for encoded content state on a local update. A server producer remains responsible for the size of its complete APNs payload.
Existing `activityPushToStartTokenReceived` and `activityTokenReceived` event contracts do not change. The former remains app-wide; an update token already targets its activity instance and carries its existing activity name. Register `getDynamicLiveActivityDefinitionIds()` alongside the unchanged push-to-start token so your server can route the correct engine and definition.
Rendering failures are diagnostic events, delivered as `dynamicLiveActivityRenderFailed` through `addVoltraListener`. Each event includes the common `type`, `source`, and `timestamp` fields plus `activityName`, `definitionId`, and a sanitized `message`; it never includes props or tokens.
```ts
import { addVoltraListener } from '@use-voltra/ios-client'
const subscription = addVoltraListener('dynamicLiveActivityRenderFailed', (event) => {
console.warn(`Could not render ${event.definitionId} for ${event.activityName}: ${event.message}`)
})
```
## Known limitation: `colorScheme` on iOS 26
[Section titled “Known limitation: colorScheme on iOS 26”](#known-limitation-colorscheme-on-ios-26)
On iOS 26, the `colorScheme` value that reaches a Live Activity is unreliable. In the Dynamic Island it is always `dark`. On the Lock Screen and in banners it can follow the wallpaper or the background behind the activity instead of the system Light or Dark setting. This behavior comes from iOS and ActivityKit, not from Voltra’s renderer. Apple staff have acknowledged it in the [Apple Developer Forums thread](https://developer.apple.com/forums/thread/799684).
As a result, a Dynamic Live Activity, or any Live Activity content that branches on `environment.colorScheme`, may not re-render correctly after the system appearance changes on iOS 26. Voltra does not currently detect this condition or provide a workaround for it.
When you build Live Activity content, avoid relying on `colorScheme` alone to choose colors:
* Use explicit colors that stay readable on both light and dark backgrounds, and check them over the Lock Screen wallpaper and on the Dynamic Island.
* Use the named `primary` and `secondary` colors where you need text or tints that follow the system. Voltra’s iOS color parser maps them to SwiftUI’s semantic colors, so they are not chosen from `colorScheme`.
## Rollout and compatibility
[Section titled “Rollout and compatibility”](#rollout-and-compatibility)
* An older app version can only accept a push-to-start for a definition it actually has bundled. Having some other Dynamic Live Activity isn’t enough — the specific definition ID needs to exist in that build.
* If a definition isn’t declared in the app, both local APIs and remote ActivityKit pushes for it will fail.
* Don’t remove a definition’s declaration while activities using it might still be running — end those first.
* Treat each definition ID as a versioned contract for its rendering and props. If you need to make a breaking change to the props shape, ship it under a new ID (e.g. `order_finished_v2`) instead of changing the old one.
* Broadcast channels send the same payload to every subscriber, so only use Dynamic Live Activities on a channel if every recipient supports that same definition — otherwise stick with the legacy format for that channel.
* If the bundle is missing or corrupt, or the renderer fails, a remotely-started activity can end up active but empty. It’ll recover on the next successful update, but V1 doesn’t cache the last good UI in the meantime.
* ActivityKit can create duplicate remote starts under the same name, and V1 doesn’t dedupe them — unlike local starts, where an existing activity with the same name gets replaced.
# Dynamic Widgets
> Write iOS widgets whose entry component renders on the device and reacts to app-supplied props and device state such as color scheme and locale.
Dynamic Widgets run their entry component on-device and can react to both app-supplied runtime props and current device state on iOS. Declare a Dynamic Widget in `app.json` with a stable `id` and an explicit `entry`, then default-export the Dynamic Widget from that file.
That means your Dynamic Widget can react to:
* `env.widgetFamily`
* `env.colorScheme`
* `env.locale`, `env.preferredLanguages`, `env.hourCycle`, `env.timeZone` and the other [locale fields](/ios/development/localization)
* `env.widgetRenderingMode`
* `env.showsWidgetContainerBackground`
* `env.configuration` when you also add widget parameters
When you change `app.json`, run Expo Prebuild or Voltra Apply so the updated widget configuration is available on device. If you change only the widget JS, reopen the app in development and the widget updates automatically.
## Set up Metro
[Section titled “Set up Metro”](#set-up-metro)
Dynamic Widgets require `@use-voltra/metro` in the app project. Install it alongside the iOS packages:
```sh
npm install @use-voltra/metro
```
Wrap the app’s existing Metro config with `withVoltra`:
metro.config.js
```js
const { getDefaultConfig } = require('expo/metro-config')
const { withVoltra } = require('@use-voltra/metro')
const config = getDefaultConfig(__dirname)
module.exports = withVoltra(config)
```
## How to use it
[Section titled “How to use it”](#how-to-use-it)
1. Add an iOS widget declaration to `app.json` with an `id`, an `entry`, and any widget metadata you need.
2. Default-export the widget function or component from the module named by `entry`.
3. Use `initialStatePath` if you want a pre-rendered first view.
4. Re-run Expo Prebuild or Voltra Apply after updating `app.json`.
5. Keep iOS and Android widget declarations separate; the same `id` can exist on both platforms because each platform is configured separately.
```tsx
import { Voltra, type WidgetEnvironment } from '@use-voltra/ios'
type WeatherDynamicWidgetProps = {
headline?: string
unreadCount?: number
}
export default function WeatherDynamicWidget(
props: WeatherDynamicWidgetProps = {},
env: WidgetEnvironment = {} as WidgetEnvironment
) {
const headline = props.headline ?? 'Weather update'
const unreadCount = props.unreadCount ?? 0
// Format with the user's locale, 12/24-hour setting and time zone.
const renderedAt = (env.date ? new Date(env.date) : new Date()).toLocaleTimeString(env.locale, {
hour: '2-digit',
minute: '2-digit',
hourCycle: env.hourCycle,
timeZone: env.timeZone,
})
return (
{headline}
{unreadCount} unread
Family: {env.widgetFamily}
Scheme: {env.colorScheme ?? 'light'}
Rendered: {renderedAt}
)
}
```
Example plugin config:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"groupIdentifier": "group.com.example.app",
"widgets": [
{
"id": "weather_widget",
"entry": "./widgets/ios/weather-widget.tsx",
"displayName": "Weather Widget",
"description": "A Dynamic Widget that reacts to live device state",
"supportedFamilies": ["systemSmall", "systemMedium", "systemLarge"],
"initialStatePath": "./widgets/ios/weather-widget.tsx"
}
]
}
]
]
}
}
```
`groupIdentifier` is required when using runtime props because the app and WidgetKit extension exchange the latest props through the shared App Group. Environment-only Dynamic Widgets can omit it.
After changing the plugin configuration, rebuild the native iOS app. You also need a native rebuild after upgrading to a version of `@use-voltra/ios-client` that introduces a new native API.
## Update Dynamic Widget props
[Section titled “Update Dynamic Widget props”](#update-dynamic-widget-props)
Call `updateDynamicWidget` from your app. The object is serialized, persisted, and passed as the first argument to the entry component on each subsequent render. The update re-renders every installed instance with the matching Dynamic Widget id.
```ts
import { updateDynamicWidget } from '@use-voltra/ios-client'
await updateDynamicWidget('weather_widget', {
headline: 'Rain arriving soon',
unreadCount: 2,
})
```
Dynamic Widget props must be JSON-serializable. You can use strings, numbers, booleans, `null`, arrays, and nested objects. Functions, `undefined`, `Date`, `BigInt`, and cyclic references are not supported.
Before the first call to `updateDynamicWidget`, the entry component receives `{}`. The latest props object is persisted by Dynamic Widget id, survives app process restarts, and is reused until a later call replaces it or the app’s data is cleared.
Choose the API by widget type
`updateDynamicWidget` updates an entry-based Dynamic Widget by passing runtime props to its entry component. The legacy `updateWidget` API sends pre-rendered variant payloads to a payload-driven widget and cannot update an entry-based Dynamic Widget.
## Fetching props from a server
[Section titled “Fetching props from a server”](#fetching-props-from-a-server)
Props do not have to come from the app. Add a `serverUpdate` alongside `entry` and the widget fetches a JSON object on a schedule and renders it, without the app running:
```json
{
"id": "portfolio",
"entry": "./widgets/ios/portfolio.tsx",
"serverUpdate": {
"url": "https://api.example.com/widgets/portfolio",
"intervalMinutes": 30
}
}
```
The response object becomes the same first argument `updateDynamicWidget` passes, so the entry component does not change. Because the server returns data rather than a rendered payload, the backend can be written in any language.
`updateDynamicWidget` keeps working on a server-driven widget — the next fetch simply overwrites what you wrote. See [Server-driven widgets](/ios/development/server-driven-widgets) for the response contract, the `env.serverUpdate` fields, and how to take a widget over.
## Runtime props and configuration are separate
[Section titled “Runtime props and configuration are separate”](#runtime-props-and-configuration-are-separate)
Dynamic Widget props are app-owned state passed as the entry component’s first argument. Configuration values are declared through `appIntent.parameters`, edited by the user in the native iOS Edit Widget sheet, and read from `env.configuration`. Updating runtime props does not replace configuration.
If you want user-editable values, add `appIntent` too. See [Configurable Widgets](/ios/development/configurable-widgets).
## Localization
[Section titled “Localization”](#localization)
Pass `env.locale` to every `Intl` and `toLocale*` call, and pick a translation with `resolveLocale(env, messages)`. See [Localization](/ios/development/localization) for every locale field, how to declare the languages your app supports, and how to let the app choose the widget language.
## Notes
[Section titled “Notes”](#notes)
* There is no `export` field in app.json for Dynamic Widgets.
* The default-exported function or component name does not need to match the widget `id`.
* Use a real device to verify release rendering.
* `initialStatePath` gives the widget a pre-rendered first view.
* To use SwiftUI modifiers that `style` does not cover, such as `widgetURL` or `containerBackground`, see [Native modifiers](/ios/development/native-modifiers).
# Events
> Listen for Live Activity state changes, push tokens, and user interaction events in your app, with the event types and their payloads.
Voltra emits several types of events that allow your app to respond to changes in Live Activities and user interactions.
## Overview
[Section titled “Overview”](#overview)
Voltra provides four main event types:
* **Activity state changes**: Notifications when a Live Activity’s state changes (e.g., dismissed, ended)
* **Push tokens**: Tokens needed for server-side updates via push notifications
* **Push-to-start tokens**: Tokens for starting Live Activities remotely (iOS 17.2+)
* **User interactions**: Events triggered when users interact with buttons or toggles in your Live Activity
## Activity state changes
[Section titled “Activity state changes”](#activity-state-changes)
Voltra emits events whenever a Live Activity’s state changes. This allows you to track the lifecycle of your Live Activities and respond accordingly.
### Listening for state changes
[Section titled “Listening for state changes”](#listening-for-state-changes)
Use `addVoltraListener` with the `'stateChange'` event type to subscribe to state change events:
```typescript
import { addVoltraListener } from '@use-voltra/ios-client'
const subscription = addVoltraListener('stateChange', (event) => {
console.log('Activity name:', event.activityName)
console.log('New state:', event.activityState)
// Handle different states
if (event.activityState === 'dismissed') {
// User dismissed the Live Activity
} else if (event.activityState === 'ended') {
// Live Activity ended
} else if (event.activityState === 'active') {
// Live Activity is active
}
})
// Don't forget to clean up
subscription.remove()
```
### Activity states
[Section titled “Activity states”](#activity-states)
The `activityState` field can have the following values:
* `'active'`: The Live Activity is currently active and visible
* `'dismissed'`: The user manually dismissed the Live Activity
* `'pending'`: The Live Activity is pending activation
* `'stale'`: The Live Activity has become stale
* `'ended'`: The Live Activity has ended
### Event structure
[Section titled “Event structure”](#event-structure)
Each state change event contains:
* `activityName`: The name of the Live Activity (as specified when starting it)
* `activityState`: The new state of the Live Activity
## Push tokens
[Section titled “Push tokens”](#push-tokens)
To enable server-side updates for your Live Activities, you need to obtain push tokens. Voltra emits events when these tokens become available.
### Activity push tokens
[Section titled “Activity push tokens”](#activity-push-tokens)
Activity push tokens are used to update existing Live Activities via push notifications. Listen for these tokens using `addVoltraListener` with the `'activityTokenReceived'` event type:
```typescript
import { addVoltraListener } from '@use-voltra/ios-client'
const subscription = addVoltraListener('activityTokenReceived', (event) => {
console.log('Activity name:', event.activityName)
console.log('Push token:', event.pushToken)
// Send the token to your server
sendTokenToServer({
activityName: event.activityName,
pushToken: event.pushToken,
})
})
subscription.remove()
```
For more information about using push tokens for server-side updates, see the [server-side updates guide](/ios/development/server-side-updates).
### Push-to-start tokens
[Section titled “Push-to-start tokens”](#push-to-start-tokens)
Push-to-start tokens (available on iOS 17.2+) allow you to start Live Activities remotely via push notifications. Listen for these tokens using `addVoltraListener` with the `'activityPushToStartTokenReceived'` event type:
```typescript
import { addVoltraListener } from '@use-voltra/ios-client'
const subscription = addVoltraListener('activityPushToStartTokenReceived', (event) => {
console.log('Push-to-start token:', event.pushToStartToken)
// Send the token to your server
sendTokenToServer({
pushToStartToken: event.pushToStartToken,
})
})
subscription.remove()
```
For more information about using push tokens for starting Live Activity remotely, see the [server-side updates guide](/ios/development/server-side-updates).
## User interactions
[Section titled “User interactions”](#user-interactions)
When users interact with buttons or toggles in your Live Activity, Voltra emits an `'interaction'` event via `addVoltraListener` — this works even when your app isn’t running. For the full example, component identifiers, deep linking, and app lifecycle considerations, see the [interactions guide](/ios/development/interactions).
## Best practices
[Section titled “Best practices”](#best-practices)
### Set up listeners early
[Section titled “Set up listeners early”](#set-up-listeners-early)
Initialize your event listeners as early as possible in your app lifecycle (e.g., in your root component or app entry point). This ensures they’re ready when events occur, especially when your app is launched from a terminated state due to a Live Activity interaction.
### Clean up subscriptions
[Section titled “Clean up subscriptions”](#clean-up-subscriptions)
Always clean up your event subscriptions to prevent memory leaks. If you’re using React hooks, return a cleanup function from `useEffect`:
```typescript
import { useEffect } from 'react'
import { addVoltraListener } from '@use-voltra/ios-client'
function MyComponent() {
useEffect(() => {
const subscription = addVoltraListener('stateChange', (event) => {
// Handle event
})
return () => {
subscription.remove()
}
}, [])
return null
}
```
### Handle app launch scenarios
[Section titled “Handle app launch scenarios”](#handle-app-launch-scenarios)
When your app is launched from a terminated state (e.g., due to a Live Activity interaction), make sure your event listeners are set up before processing any queued events. Voltra handles event queuing automatically when using App Groups.
# Flexbox Layout
> Lay out Voltra iOS components with React Native-style flexbox by using Voltra.View, with the supported properties and differences from React Native.
Voltra supports React Native-style flexbox layout through the `Voltra.View` component.
## Enabling Flexbox
[Section titled “Enabling Flexbox”](#enabling-flexbox)
Use `Voltra.View` to opt in to flexbox layout:
```tsx
LeftRight
```
## Supported Properties
[Section titled “Supported Properties”](#supported-properties)
Voltra supports the following flexbox style properties. For detailed explanations and examples of each property, see the [React Native Flexbox documentation](https://reactnative.dev/docs/flexbox).
### Container Properties
[Section titled “Container Properties”](#container-properties)
| Property | Supported Values |
| ---------------- | --------------------------------------------------------------------------------------------------------- |
| `flexDirection` | `'column'` (default), `'row'` |
| `justifyContent` | `'flex-start'` (default), `'center'`, `'flex-end'`, `'space-between'`, `'space-around'`, `'space-evenly'` |
| `alignItems` | `'stretch'` (default), `'flex-start'`, `'center'`, `'flex-end'` |
| `gap` | Number (points) — applies along main axis only |
### Child Properties
[Section titled “Child Properties”](#child-properties)
| Property | Description |
| ------------------------ | ---------------------------------------------- |
| `flex` | Shorthand for `flexGrow` and `flexShrink` |
| `flexGrow` | How much the item should grow (default: `0`) |
| `flexShrink` | How much the item should shrink (default: `0`) |
| `flexBasis` | Initial size before flex grow/shrink |
| `alignSelf` | Override parent’s `alignItems` for this child |
| `width`, `height` | Fixed dimensions |
| `minWidth`, `maxWidth` | Width constraints |
| `minHeight`, `maxHeight` | Height constraints |
| `margin` | Outer spacing |
| `padding` | Inner spacing |
### Unsupported Properties
[Section titled “Unsupported Properties”](#unsupported-properties)
The following React Native flexbox properties are **not supported** in Voltra:
* `flexWrap` — items are always laid out in a single line
* `rowGap`, `columnGap` — only the unified `gap` property is supported, applied along the main axis
* Percentage-based `width` or `height` (e.g. `width: '50%'`) — use `flexGrow` instead
## Differences from React Native
[Section titled “Differences from React Native”](#differences-from-react-native)
If you’re coming from React Native, the biggest difference is that flexbox is opt-in: in React Native every `View` uses flexbox by default, but in Voltra only `Voltra.View` does — other containers (`VStack`, `HStack`) use native SwiftUI layout instead. The rest of the differences are the unsupported/limited properties listed in the tables above (single-axis `gap`, no `flexWrap`, no percentage dimensions).
## Next Steps
[Section titled “Next Steps”](#next-steps)
* [React Native Flexbox documentation](https://reactnative.dev/docs/flexbox) — comprehensive guide to flexbox properties and concepts
* [View component documentation](/ios/components/layout#view) — API reference for `Voltra.View`
* [Styling in Voltra](/ios/development/styling) — more about style properties
# Gradients
> Use CSS linear, radial, and conic gradient strings in backgroundColor, rendered natively with SwiftUI and clipped by borderRadius.
The `backgroundColor` style property accepts CSS gradient strings in addition to solid colors. Gradients are rendered natively using SwiftUI gradient modifiers and are automatically clipped by `borderRadius`.
Invalid or unsupported gradient syntax is parsed in **strict mode** and results in **no gradient background** (instead of silent best-effort fallback).
## Linear gradients
[Section titled “Linear gradients”](#linear-gradients)
```tsx
// Named direction
// Diagonal
// Angle in degrees/radians/turns
```
Supported directions: `to right`, `to left`, `to top`, `to bottom`, `to top right`, `to top left`, `to bottom right`, `to bottom left`.
## Color stops
[Section titled “Color stops”](#color-stops)
Explicit percentage positions are supported:
```tsx
```
When positions are omitted, Voltra applies CSS-like stop fix-up:
* First and last unspecified stops default to `0%` and `100%`.
* Unspecified stops between explicit anchors are linearly interpolated.
* Non-monotonic explicit positions are clamped forward.
## RGBA colors inside gradients
[Section titled “RGBA colors inside gradients”](#rgba-colors-inside-gradients)
```tsx
```
## Radial gradients
[Section titled “Radial gradients”](#radial-gradients)
```tsx
```
Note
Radial gradients are rendered with geometry-aware radii computed from the view size (`closest-side`, `farthest-side`, `closest-corner`, `farthest-corner`).
For `ellipse`, SwiftUI does not provide native elliptical radial gradients. Voltra approximates ellipse behavior by scaling a circular radial gradient.
## Conic gradients
[Section titled “Conic gradients”](#conic-gradients)
```tsx
```
## With border radius
[Section titled “With border radius”](#with-border-radius)
Gradients are clipped by `borderRadius` automatically — no extra configuration needed:
```tsx
Rounded gradient card
```
## Solid colors still work unchanged
[Section titled “Solid colors still work unchanged”](#solid-colors-still-work-unchanged)
Passing a plain color string to `backgroundColor` continues to work exactly as before:
```tsx
```
## Comparison with `` component
[Section titled “Comparison with \ component”](#comparison-with-lineargradient-component)
| Feature | `backgroundColor` gradient | `` component |
| ------------------------------------ | ------------------------------------------------ | ---------------------------- |
| CSS string syntax | ✓ | — |
| Named directions (`to right`) | ✓ (physical direction) | ✓ |
| Angle units | `deg`, `rad`, `turn` | ✓ via `{x,y}` |
| `{x, y}` coordinate control | — | ✓ |
| Stop positions | `linear/radial`: `%`, `conic`: `%` + angle units | ✓ via `locations` prop |
| Multi-position stops (`red 20% 40%`) | ✓ | — |
| `radial-gradient` | ✓ (`circle` / approximated `ellipse`) | — |
| `conic-gradient` | ✓ (`from` + `at`) | — |
| Strict invalid syntax handling | ✓ (fails closed) | — |
| Dithering | — | ✓ |
| Children layered on top | ✓ (as background) | ✓ (as container) |
Use `backgroundColor` gradient strings for convenience and web-style syntax. Use `` when you need precise `{x, y}` coordinate control or dithering.
## Scope and exclusions
[Section titled “Scope and exclusions”](#scope-and-exclusions)
* Supported core syntax: `linear-gradient(...)`, `radial-gradient(...)`, `conic-gradient(...)`.
* Not supported in this parser: `repeating-linear-gradient(...)`, `repeating-radial-gradient(...)`, `repeating-conic-gradient(...)`.
# Image Preloading
> API reference for preloading remote images into shared App Group storage so Live Activities and widgets can display them.
This page provides detailed API documentation for Voltra’s image preloading system. For an overview of all image handling approaches in Live Activities, see the [Images](/ios/development/images) documentation.
Live Activities have strict size limits (4KB per update), which makes displaying remote images challenging. The image preloading API downloads images to shared App Group storage, making them available to both your app and Live Activities.
## Overview
[Section titled “Overview”](#overview)
The image preloading system works by:
1. Downloading images from URLs to App Group shared storage
2. Validating that images are under the 4KB ActivityKit limit
3. Making images available to Live Activities via the `assetName` property
4. Providing APIs to reload existing Live Activities when new images are available
## API Reference
[Section titled “API Reference”](#api-reference)
### `preloadImages(images: PreloadImageOptions[]): Promise`
[Section titled “preloadImages(images: PreloadImageOptions\[\]): Promise\”](#preloadimagesimages-preloadimageoptions-promisepreloadimagesresult)
Downloads bitmap images to App Group storage or rasterizes SVGs to PNG before storing them for use in Live Activities.
Each item must be either a URL preload (`url`) or an SVG preload (`svg`). The TypeScript types express this as a union of two variants:
```typescript
type PreloadImageUrlOptions = {
key: string // The assetName to use when referencing this image
url: string // URL to download the image from
method?: 'GET' | 'POST' | 'PUT' // HTTP method (default: 'GET')
headers?: Record // Optional HTTP headers
width?: number
height?: number
}
type PreloadImageSvgOptions = {
key: string // The assetName to use when referencing this image
svg: string // Inline SVG markup to rasterize and cache as PNG
width?: number // Typically required for SVG rasterization (see native errors if omitted)
height?: number
}
type PreloadImageOptions = PreloadImageUrlOptions | PreloadImageSvgOptions
type PreloadImageFailure = {
key: string
error: string
}
type PreloadImagesResult = {
succeeded: string[] // Keys of successfully downloaded images
failed: PreloadImageFailure[] // Failed downloads with error messages
}
```
**Example:**
```typescript
import { preloadImages } from '@use-voltra/ios-client'
const result = await preloadImages([
{
url: 'https://example.com/album-art.jpg',
key: 'current-song-artwork',
headers: { Authorization: 'Bearer token' },
},
{
key: 'status-icon-active',
svg: '',
width: 24,
height: 24,
},
])
console.log('Succeeded:', result.succeeded)
console.log('Failed:', result.failed)
```
### `reloadLiveActivities(activityNames?: string[]): Promise`
[Section titled “reloadLiveActivities(activityNames?: string\[\]): Promise\”](#reloadliveactivitiesactivitynames-string-promisevoid)
Reloads Live Activities to pick up newly preloaded images. If no `activityNames` are provided, all active Live Activities will be reloaded.
```typescript
import { reloadLiveActivities } from '@use-voltra/ios-client'
// Reload all Live Activities
await reloadLiveActivities()
// Reload specific activities
await reloadLiveActivities(['music-player', 'order-tracker'])
```
### `clearPreloadedImages(keys?: string[]): Promise`
[Section titled “clearPreloadedImages(keys?: string\[\]): Promise\”](#clearpreloadedimageskeys-string-promisevoid)
Removes preloaded images from App Group storage. If no `keys` are provided, all preloaded images will be cleared.
```typescript
import { clearPreloadedImages } from '@use-voltra/ios-client'
// Clear specific images
await clearPreloadedImages(['album-art', 'profile-pic'])
// Clear all preloaded images
await clearPreloadedImages()
```
## Usage in Live Activities
[Section titled “Usage in Live Activities”](#usage-in-live-activities)
Once images are preloaded, reference them using the `assetName` property:
```typescript
import { Voltra } from '@use-voltra/ios'
function MusicPlayerLiveActivity({ song }) {
return {
lockScreen: (
{song.title}
{song.artist}
)
}
}
```
## Size Validation
[Section titled “Size Validation”](#size-validation)
ActivityKit enforces a 4KB limit per Live Activity update. Images are validated both before and after download:
* **Content-Length header**: If available, images larger than 4KB are rejected before download
* **Actual size**: After download, the actual data size is validated
* **SVG rasterization**: SVG inputs are converted to PNG before storage and the generated PNG is size-checked
* **Image validation**: Ensures the downloaded data is a valid image format
Images that exceed 4KB will result in a preload failure with a descriptive error message.
## Error Handling
[Section titled “Error Handling”](#error-handling)
The `preloadImages` function provides detailed error information:
```typescript
const result = await preloadImages([
{ url: 'https://example.com/large-image.jpg', key: 'big-image' },
{ url: 'https://invalid-url.com/image.jpg', key: 'broken-url' },
])
// Handle results
if (result.failed.length > 0) {
result.failed.forEach(({ key, error }) => {
console.error(`Failed to preload ${key}: ${error}`)
})
}
// Only proceed if all images succeeded
if (result.succeeded.length === 2) {
await reloadLiveActivities()
}
```
## Common Error Messages
[Section titled “Common Error Messages”](#common-error-messages)
* `"Image 'key-name' is too large: 5120 bytes (max 4096 bytes for Live Activities)"` - Image exceeds 4KB limit
* `"Invalid image data for 'key-name'"` - Downloaded data is not a valid image
* `"Invalid SVG data for 'key-name'"` - SVG markup is malformed or contains unsupported external/script references
* `"SVG 'key-name' requires positive width and height"` - SVG rasterization needs explicit dimensions
* `"HTTP error: 404"` - Server returned an error status code
* `"App Group not configured"` - Missing App Group configuration in the config plugin
## Configuration
[Section titled “Configuration”](#configuration)
Image preloading requires App Group configuration in your Expo config plugin:
```json
{
"plugins": [
[
"@use-voltra/ios-client",
{
"groupIdentifier": "group.your.app"
}
]
]
}
```
# Images
> Compare the three ways to include images in Live Activities: Base64 encoding, build-time asset copying, and runtime preloading.
Live Activities have strict size limits (4KB per update), making image handling a critical optimization area. Voltra provides three different approaches for including images in your Live Activities, each with different trade-offs and use cases:
* **Base64 encoding**: Best for small, static images (< 1KB)
* **Build-time asset copying**: Best for medium-sized images that are known at build time
* **Runtime preloading**: Best for dynamic images from remote URLs or inline SVG data
## Base64 encoding
[Section titled “Base64 encoding”](#base64-encoding)
For extremely small images, you can embed them directly as base64-encoded strings in your JSX.
```tsx
```
## Build-time asset copying
[Section titled “Build-time asset copying”](#build-time-asset-copying)
Place images in the `/assets/voltra/` directory and they’ll be automatically copied to the iOS extension bundle during build.
```plaintext
project-root/
├── assets/
│ └── voltra/
│ ├── logo.png
│ ├── icon-star.png
│ └── background-pattern.png
```
Images must be under 4KB (the ActivityKit limit) — anything larger fails the build. You can then reference these images using their assetName:
```tsx
```
## Runtime preloading
[Section titled “Runtime preloading”](#runtime-preloading)
For dynamic images from remote URLs or inline SVG markup, use Voltra’s image preloading API to cache images (also subject to the 4KB limit) in App Group shared storage, then reference them the same way via `assetName`. See [Image Preloading](/ios/development/image-preloading) for the full API and a usage example.
## Comparison table
[Section titled “Comparison table”](#comparison-table)
| Approach | Image Size | When Known | Dynamic | Setup Required | Payload Impact |
| ---------- | ---------- | ---------- | ------- | ---------------- | ------------------- |
| Base64 | < 1KB | Build time | No | None | High (encoded size) |
| Build-time | 1KB - 4KB | Build time | No | File placement | Low (filename only) |
| Preloading | 1KB - 4KB | Runtime | Yes | App Group config | Low (filename only) |
# Interactions
> The interactions ActivityKit allows in Live Activities (tapping the activity, links, buttons, and toggles) and how to handle them and use deep links.
Voltra components leverage Apple’s ActivityKit to provide interactive Live Activities.
## Interaction capabilities
[Section titled “Interaction capabilities”](#interaction-capabilities)
ActivityKit provides a limited set of interactions with Live Activities. The only interactable elements are:
* **Live Activity view**: Tapping anywhere on the Live Activity itself can launch your app via a deep link, allowing users to access more detailed information or perform specific actions.
* **Links**: Navigation elements that open URLs when tapped. Links use SwiftUI’s native Link component and work across all Live Activity contexts (iOS 14.0+).
* **Buttons**: Interactive buttons that trigger in-app events. Buttons are implemented using AppIntents and work on both the Lock Screen and Dynamic Island (iOS 17.0+).
* **Toggles**: Interactive toggle switches that allow users to change boolean states. Like buttons, toggles use AppIntents and are supported across all Live Activity contexts (iOS 17.0+).
## Handling interactions
[Section titled “Handling interactions”](#handling-interactions)
When a user interacts with a button or toggle in your Live Activity, Voltra automatically emits an event containing the identifier of the component that was interacted with. This allows your app to respond appropriately to specific user actions.
### Listening for events
[Section titled “Listening for events”](#listening-for-events)
To handle interactions, subscribe to Voltra UI events using the `addVoltraListener` function with the `'interaction'` event type:
```typescript
import { addVoltraListener } from '@use-voltra/ios-client'
const subscription = addVoltraListener('interaction', (event) => {
console.log('Component interacted:', event.identifier)
console.log('Component type:', event.componentType)
// Handle the interaction based on the identifier
if (event.identifier === 'contact-driver') {
// Open contact screen
} else if (event.identifier === 'toggle') {
// Handle toggle state change
}
})
// Don't forget to clean up
subscription.remove()
```
### Event structure
[Section titled “Event structure”](#event-structure)
Each interaction event contains:
* `identifier`: The unique identifier of the component that was interacted with (as specified in your JSX via the `id` prop)
* `componentType`: The type of component that triggered the event (e.g., “button”, “toggle”)
### Component identifiers
[Section titled “Component identifiers”](#component-identifiers)
To receive interaction events, make sure your interactive components have unique identifiers:
```typescript
Contact driver
```
If you don’t provide an explicit `id` prop, Voltra will automatically generate a deterministic identifier based on the component’s position in the tree. However, for reliable event handling, it’s recommended to use explicit identifiers.
## Deep linking
[Section titled “Deep linking”](#deep-linking)
### Activity-level deep links
[Section titled “Activity-level deep links”](#activity-level-deep-links)
When users tap on the Live Activity itself (not on a button or link), your app can be launched via a deep link. Configure the deep link URL when starting a Live Activity:
```typescript
import { useLiveActivity } from '@use-voltra/ios-client'
const { start } = useLiveActivity(
{
lockScreen: ,
},
{
activityName: 'activity-detail',
deepLinkUrl: '/voltraui/activity-detail',
}
)
```
The deep link URL can be:
* A full URL with a scheme (e.g., `myapp://activity-detail`)
* A path that will be prefixed with your app’s URL scheme (e.g., `/activity-detail`)
When the Live Activity is tapped, your app will be launched (or brought to the foreground) and the deep link will be handled by your routing system.
### Component-level deep links
[Section titled “Component-level deep links”](#component-level-deep-links)
Individual components can also open URLs when tapped, providing granular navigation within your Live Activity.
#### Link Component
[Section titled “Link Component”](#link-component)
The `Link` component provides semantic navigation to URLs. It uses SwiftUI’s native Link and works on iOS 14.0+:
```tsx
Order #123
```
Links support URL normalization:
* Absolute URLs: `"myapp://path"`, `"https://example.com"`
* Relative paths: `"/settings"` → `"myapp://settings"`
* Simple paths: `"help"` → `"myapp://help"`
For styled navigation buttons, wrap a Link with custom children to achieve button-like appearance while maintaining URL navigation functionality.
## Limitations
[Section titled “Limitations”](#limitations)
* **Limited interactable elements**: Only buttons and toggles are supported as interactive components. Other UI elements like text fields, sliders, or custom controls are not available in Live Activities.
* **iOS version requirements**: Interactive buttons and toggles require iOS 17.0+. On iOS 16.x, these components will render but will not be interactive.
* **No real-time updates from interactions**: When a user interacts with a button or toggle, the Live Activity UI doesn’t update automatically. You’ll need to update the Live Activity content manually using the `update` function if you want to reflect state changes.
* **Event delivery timing**: Events are delivered asynchronously. There may be a slight delay between the user’s interaction and your event handler being called, especially if the app needs to be launched.
## Example
[Section titled “Example”](#example)
Here’s a complete example showing how to handle interactions:
```typescript
import { useEffect } from 'react'
import { Voltra } from '@use-voltra/ios'
import { useLiveActivity } from '@use-voltra/ios-client'
import { addVoltraListener } from '@use-voltra/ios-client'
function MyLiveActivity() {
const { start, update } = useLiveActivity(
{
lockScreen: (
Music PlayerPlayPause
),
},
{
activityName: 'music-player',
deepLinkUrl: '/music-player',
}
)
useEffect(() => {
const subscription = addVoltraListener('interaction', (event) => {
switch (event.identifier) {
case 'play-button':
// Start playback
console.log('Play button tapped')
break
case 'pause-button':
// Pause playback
console.log('Pause button tapped')
break
case 'shuffle-toggle':
// Toggle shuffle mode
console.log('Shuffle toggled')
break
}
})
return () => subscription.remove()
}, [])
return null
}
```
# Localization
> Translate Dynamic Widgets and Dynamic Live Activities, format dates and numbers from env, and localize the widget gallery and Edit Widget sheet.
A Dynamic Widget or Dynamic Live Activity renders on the device, so your JavaScript can translate the widget and format dates, numbers and units for the person looking at it. Every render receives the language and regional settings on `env`, and widgets render again when those settings change.
Two parts of a widget are drawn by iOS, not by your code: the widget gallery and the Edit Widget sheet. You translate those in `app.json`; see [Translate the gallery and the Edit Widget sheet](#translate-the-gallery-and-the-edit-widget-sheet).
## What the widget knows about the user
[Section titled “What the widget knows about the user”](#what-the-widget-knows-about-the-user)
These fields are on `env` in a Dynamic Widget and on `environment` in a Dynamic Live Activity:
| Field | Example | What it tells you |
| -------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `locale` | `"pl-PL"`, `"en-US-u-hc-h23"` | The language and region the widget is drawn in, as a BCP-47 tag. It includes the user’s overrides, such as 24-Hour Time. Pass it to every `Intl` and `toLocale*` call. |
| `preferredLanguages` | `["pl-PL", "en-US"]` | The user’s language list from Settings, in order, whether or not your app supports those languages. |
| `appLocale` | `"pl"` | The language your app chose with `setDynamicWidgetLocale`. Absent unless you set one. |
| `layoutDirection` | `"ltr"` | `"rtl"` for Arabic, Hebrew and other right-to-left languages. |
| `hourCycle` | `"h23"` | `"h12"` or `"h23"`, matching the user’s 24-Hour Time setting. |
| `timeZone` | `"Europe/Warsaw"` | The device time zone. |
| `measurementSystem` | `"metric"` | `"metric"`, `"us"` or `"uk"`. |
| `calendar` | `"gregory"` | The user’s calendar, spelled the way `Intl` expects. |
| `firstDayOfWeek` | `2` | `1` is Sunday, `2` is Monday, up to `7` for Saturday. |
`locale` follows the languages your app declares, not the device language on its own. A Polish user of an app that only declares English gets `"en-PL"`. See [Declare the languages your app supports](#declare-the-languages-your-app-supports).
Versions of `@use-voltra/ios-client` before 2.4.0 passed `locale` as `pl_PL`. If your widget compared it against that form, switch to the hyphenated tag.
## Translate widget content
[Section titled “Translate widget content”](#translate-widget-content)
Keep one messages object per language and let `resolveLocale` choose. It tries `appLocale`, then each entry of `preferredLanguages` (exact tag, then language only), then `locale`. If none match, it returns `en`, then `__default`, then the alphabetically first key. It returns `undefined` only when the object is empty.
```tsx
import { resolveLocale, Voltra, type WidgetEnvironment } from '@use-voltra/ios'
const messages = {
en: { title: 'Next train' },
pl: { title: 'Następny pociąg' },
}
export default function TrainWidget(props: { departure?: number }, env: WidgetEnvironment) {
const t = messages[resolveLocale(env, messages) ?? 'en']
const departure = new Date(props.departure ?? env.date.valueOf())
const time = new Intl.DateTimeFormat(env.locale, {
hour: 'numeric',
minute: '2-digit',
hourCycle: env.hourCycle,
timeZone: env.timeZone,
}).format(departure)
return (
{t.title}{time}
)
}
```
`pickLocalizedValue(map, languages)` applies the same fallback to any locale-keyed map when you want to pass the language list yourself.
## Format dates, numbers and units
[Section titled “Format dates, numbers and units”](#format-dates-numbers-and-units)
Pass `env.locale` to every `Intl` and `toLocale*` call, and `env.timeZone` whenever you format a date. A call without a locale uses the device language list, which can differ from the language the widget is drawn in, so the widget text and its dates would disagree.
The full `Intl` API is available on iOS: `DateTimeFormat` with `dateStyle` and `timeStyle`, `NumberFormat`, `PluralRules`, `RelativeTimeFormat`, `ListFormat` and `DisplayNames`. You do not need polyfills.
Use `env.measurementSystem` to choose between kilometers and miles, or Celsius and Fahrenheit, and `env.firstDayOfWeek` when you draw a week.
## Support right-to-left languages
[Section titled “Support right-to-left languages”](#support-right-to-left-languages)
Stacks mirror on their own in right-to-left languages, so `leading` is the right edge there. Use `env.layoutDirection` for anything you position by hand, such as the direction of an arrow symbol.
## Let the app choose the language
[Section titled “Let the app choose the language”](#let-the-app-choose-the-language)
Use this when your app has its own language picker. It is also how a per-app language chosen in Settings reaches widgets on iOS 17 and 18, which do not pass it to widgets on their own.
It requires `groupIdentifier` in the plugin configuration. Without it, the call rejects with `App Group not configured. Set 'groupIdentifier' in the Voltra config plugin to use widgets.`
```ts
import { setDynamicWidgetLocale } from '@use-voltra/ios-client'
await setDynamicWidgetLocale('pl') // every render now sees env.appLocale === 'pl'
await setDynamicWidgetLocale(null) // back to the system languages
```
Widgets and running Dynamic Live Activities render again as soon as the value is stored, and the value survives app restarts. `resolveLocale` prefers `appLocale` over every other field.
The override changes the translation only. `locale`, `layoutDirection`, `hourCycle` and the other formatting fields stay as they were, and iOS keeps laying out the widget in the direction of `locale`. If you translate into a right-to-left language while `locale` is left-to-right, position hand-placed content by `env.layoutDirection`, not by the language you chose.
Your app’s Language row in Settings appears only when the device lists more than one language in Settings > General > Language & Region. To show it on every device, set `UIPrefersShowingLanguageSettings` to `true` in `ios.infoPlist`.
## Declare the languages your app supports
[Section titled “Declare the languages your app supports”](#declare-the-languages-your-app-supports)
iOS picks the widget’s language from the languages the app declares. Voltra declares the same languages for widgets as for the app, taken from:
* the keys of the Expo [`locales`](https://docs.expo.dev/guides/localization/#translating-app-metadata) config,
* `ios.infoPlist.CFBundleLocalizations`, if you set it,
* every locale used in a widget’s locale maps (gallery labels and Edit Widget sheet copy),
* your app’s development language (`ios.infoPlist.CFBundleDevelopmentRegion`, otherwise `en`).
Declare every language your widgets translate into, for example with `"locales": { "pl": "./locales/pl.json" }`. If Polish is missing, a Polish user gets `env.locale === "en-PL"`, while `env.preferredLanguages` still lists Polish first. Rebuild the native app after changing the list.
## Translate the gallery and the Edit Widget sheet
[Section titled “Translate the gallery and the Edit Widget sheet”](#translate-the-gallery-and-the-edit-widget-sheet)
The widget gallery name and description, and the titles on the Edit Widget sheet, accept locale maps in `app.json`:
```json
{
"id": "weather",
"entry": "./widgets/ios/weather.tsx",
"displayName": { "en": "Weather", "pl": "Pogoda" },
"description": { "en": "Current conditions", "pl": "Aktualne warunki" },
"appIntent": {
"parameters": [
{
"name": "units",
"title": { "en": "Units", "pl": "Jednostki" },
"default": "metric",
"options": [
{ "value": "metric", "title": { "en": "Metric", "pl": "Metryczne" } },
{ "value": "imperial", "title": { "en": "Imperial", "pl": "Imperialne" } }
]
}
]
}
}
```
iOS shows these in the system language, not in your app’s language, and `setDynamicWidgetLocale` does not affect them. A language with no translation for a string shows your development language instead. Rebuild the native app after changing them. The sheet header shows the widget’s `displayName`, so the same locale map translates it. See [Configurable Widgets](/ios/development/configurable-widgets) for `options`.
## Translate Live Activity alerts
[Section titled “Translate Live Activity alerts”](#translate-live-activity-alerts)
The `alert` of an ActivityKit push is shown by iOS and is not rendered by Voltra. Translate it with the APNs `title-loc-key` and `loc-key` fields and strings in the app bundle.
# Managing Live Activities locally
> Start, update, and end Live Activities from your app with the imperative APIs and React hooks.
Live Activities are dynamic interfaces that display real-time information on iOS devices. Voltra provides a comprehensive set of APIs for managing the complete lifecycle of Live Activities directly from your React Native app, without requiring server-side infrastructure.
Voltra offers both imperative APIs for direct control and React hooks for seamless integration with your components.
This page documents the legacy server-rendered engine. For the separate engine that bundles a definition with the app and updates it with props, see [Dynamic Live Activities](/ios/development/dynamic-live-activities).
## Imperative APIs
[Section titled “Imperative APIs”](#imperative-apis)
The imperative APIs provide direct, programmatic control over Live Activities. These are the core functions you’ll use to manage Live Activity lifecycles. For the shape of the `variants` object used below, see [Supported variants](/ios/development/developing-live-activities#supported-variants).
### Starting Live Activities
[Section titled “Starting Live Activities”](#starting-live-activities)
Use `startLiveActivity()` to create and display a new Live Activity.
```typescript
import { Voltra } from '@use-voltra/ios'
import { startLiveActivity } from '@use-voltra/ios-client'
const variants = {
lockScreen: (
Order Confirmed
Your order is being prepared
),
// Define compact, minimal, and expanded variants for Dynamic Island
compact: Order confirmed,
minimal: ,
expanded: (
Order Confirmed
Your order is being prepared
),
}
const activityId = await startLiveActivity(variants, {
activityName: 'order-123', // Optional: for re-binding on app restart
deepLinkUrl: 'myapp://order/123', // Optional: URL to open when tapped
channelId: 'CTrNsYq/Ee8AALLzHQaVlA==', // Optional: broadcast channel (iOS 18+)
dismissalPolicy: { after: 30 },
staleDate: Date.now() + 60 * 60 * 1000, // 1 hour
relevanceScore: 0.8,
})
```
**Parameters:**
* `variants`: A `LiveActivityVariants` object defining the UI for different display contexts
* `options`: Configuration options (see Configuration Options section below)
**Returns:** A promise that resolves to the Live Activity ID (string)
### Updating Live Activities
[Section titled “Updating Live Activities”](#updating-live-activities)
Use `updateLiveActivity()` to modify the content and configuration of an active Live Activity.
```typescript
import { Voltra } from '@use-voltra/ios'
import { updateLiveActivity } from '@use-voltra/ios-client'
const updatedVariants = {
lockScreen: (
Order Ready
Your order is ready for pickup
I'm Here
),
compact: Ready for pickup,
minimal: ,
}
await updateLiveActivity(activityId, updatedVariants, {
dismissalPolicy: { after: 300 }, // 5 minutes
relevanceScore: 1.0, // High priority now
})
```
**Parameters:**
* `activityId`: The ID returned from `startLiveActivity()`
* `variants`: Updated UI variants
* `options`: Updated configuration options
### Stopping Live Activities
[Section titled “Stopping Live Activities”](#stopping-live-activities)
Use `stopLiveActivity()` to end a Live Activity.
```typescript
import { stopLiveActivity } from '@use-voltra/ios-client'
await stopLiveActivity(activityId, {
dismissalPolicy: { after: 10 }, // Keep visible for 10 seconds after ending
})
```
**Parameters:**
* `activityId`: The ID of the Live Activity to stop
* `options`: Final configuration options
### Checking Live Activity status
[Section titled “Checking Live Activity status”](#checking-live-activity-status)
Use `isLiveActivityActive()` to check if a specific Live Activity is currently active.
```typescript
import { isLiveActivityActive } from '@use-voltra/ios-client'
if (isLiveActivityActive('order-123')) {
console.log('Live Activity is active')
} else {
console.log('Live Activity is not active')
}
```
**Parameters:**
* `activityName`: The name of the Live Activity to check (same as `activityName` used when starting the activity)
**Returns:** Boolean indicating whether the Live Activity is currently active
### Utility functions
[Section titled “Utility functions”](#utility-functions)
#### Platform detection
[Section titled “Platform detection”](#platform-detection)
```typescript
import { isGlassSupported } from '@use-voltra/ios-client'
function App() {
// Check if the device supports Liquid Glass (iOS 26+)
if (isGlassSupported()) {
// Use Liquid Glass features
}
}
```
Voltra also exposes `useIsHeadless()` for detecting when your app was launched in the background (e.g. to handle a push token refresh without mounting your UI). See [Handling background execution](/ios/development/server-side-updates#handling-background-execution) for the full explanation and example.
#### Ending all Live Activities
[Section titled “Ending all Live Activities”](#ending-all-live-activities)
Use `endAllLiveActivities()` to immediately end all active Live Activities in your app.
```typescript
import { endAllLiveActivities } from '@use-voltra/ios-client'
// End all Live Activities (useful for cleanup or logout scenarios)
await endAllLiveActivities()
```
**Note:** This function ends all Live Activities immediately without applying any dismissal policies. Use this for bulk cleanup scenarios rather than individual activity management.
## Development tools
[Section titled “Development tools”](#development-tools)
For development-friendly APIs that provide automatic updates and easier testing, see the [Development documentation](/ios/development/developing-live-activities).
## Event handling
[Section titled “Event handling”](#event-handling)
Live Activities emit events that you can listen to for state changes and user interactions. See the [Events API documentation](/ios/development/events) for detailed information on subscribing to and handling Live Activity events.
## Configuration options
[Section titled “Configuration options”](#configuration-options)
Voltra provides several configuration options to control Live Activity behavior, lifecycle, and appearance. These options can be used with `startLiveActivity()`, `updateLiveActivity()`, and `stopLiveActivity()`.
### Dismissal policy
[Section titled “Dismissal policy”](#dismissal-policy)
Controls how Live Activities behave after they end.
**Options:**
* **`'immediate'`** (default): Live Activity is dismissed immediately when it ends
* **`{ after: number }`**: Live Activity remains visible for the specified number of seconds after ending, then automatically dismisses
**Examples:**
```typescript
// Immediate dismissal (default)
await startLiveActivity(variants, {
dismissalPolicy: 'immediate',
})
// Keep visible for 30 seconds after ending
await startLiveActivity(variants, {
dismissalPolicy: { after: 30 },
})
// Update dismissal timing for active Live Activities
await updateLiveActivity(activityId, variants, {
dismissalPolicy: { after: 300 }, // 5 minutes
})
// Set dismissal timing when stopping
await stopLiveActivity(activityId, {
dismissalPolicy: { after: 10 },
})
```
The dismissal policy applies to both programmatic ending and natural ending (when timers expire).
### Stale date
[Section titled “Stale date”](#stale-date)
Specifies when a Live Activity should be considered stale and automatically dismissed by iOS.
```typescript
// Dismiss after 1 hour
await startLiveActivity(variants, {
staleDate: Date.now() + 60 * 60 * 1000,
})
// Dismiss after 2 hours
await startLiveActivity(variants, {
staleDate: Date.now() + 2 * 60 * 60 * 1000,
})
```
**Note:** If you provide a `staleDate` in the past, it will be ignored.
### Relevance score
[Section titled “Relevance score”](#relevance-score)
Helps iOS prioritize which Live Activities to display when space is limited.
**Range:** 0.0 to 1.0 (default: 0.0)
```typescript
// High priority (e.g., active delivery)
await startLiveActivity(variants, {
relevanceScore: 0.8,
})
// Low priority (e.g., background task)
await startLiveActivity(variants, {
relevanceScore: 0.2,
})
```
Live Activities can receive updates even when your app is in the background or terminated, but they cannot execute JavaScript code. For real-time updates from backgrounded apps, use server-side push notifications.
### Channel ID (broadcast push, iOS 18+)
[Section titled “Channel ID (broadcast push, iOS 18+)”](#channel-id-broadcast-push-ios-18)
Subscribes the Live Activity to a broadcast channel for server-side updates. When provided, the activity receives updates via broadcast push notifications instead of individual device tokens—one server notification updates all activities on that channel.
```typescript
// For shared content (e.g., live sports, flight status)
await startLiveActivity(variants, {
activityName: 'match-123',
channelId: 'CTrNsYq/Ee8AALLzHQaVlA==', // From APNs channel management
})
```
Requires `enablePushNotifications: true` in the Voltra plugin and the Broadcast Capability enabled in your Apple Developer account. See [Server-side updates](/ios/development/server-side-updates#broadcast-push-notifications-ios-18) for details.
## Best practices
[Section titled “Best practices”](#best-practices)
* Provide an `activityName` when starting a Live Activity, so you can re-bind to it (e.g. via `isLiveActivityActive`) after an app restart.
* Set a `staleDate` so iOS can automatically dismiss activities you forget to end (e.g. after a delivery is likely already complete).
* Provide a `deepLinkUrl` so tapping the Live Activity takes users somewhere useful in your app.
* Pick a `dismissalPolicy` deliberately — `{ after: N }` is useful when you want users to see a final state (like “Delivered”) before it disappears.
# Native modifiers
> Apply SwiftUI modifiers that style does not cover, such as widgetURL and containerBackground, with the modifiers prop.
Native modifiers apply SwiftUI modifiers that `style` does not cover, such as `widgetURL`, `containerBackground`, `privacySensitive` and `contentTransition`, to any Voltra component.
Use them in Dynamic Widgets and Dynamic Live Activities
Native modifiers are meant for [Dynamic Widgets](/ios/development/dynamic-widgets) and [Dynamic Live Activities](/ios/development/dynamic-live-activities). [Payload widgets](/ios/development/server-driven-widgets) and [pushed Live Activities](/ios/development/server-side-updates) accept them too, but every modifier is sent with every update and counts against the payload size limit. Voltra keeps Live Activity payloads under about 3.3 KB so they fit ActivityKit’s 4 KB limit, and throws a payload size error when you render an update that is larger.
## Add a modifier
[Section titled “Add a modifier”](#add-a-modifier)
Pass a list of modifiers from `Voltra.modifiers` to the `modifiers` prop:
```tsx
import { Voltra } from '@use-voltra/ios'
const { containerBackground, widgetURL, privacySensitive, contentTransition } = Voltra.modifiers
export default function PortfolioWidget({ balance }: { balance: string }) {
return (
{balance}
)
}
```
`Voltra` components only accept modifiers from `Voltra.modifiers`. Passing a modifier from `VoltraAndroid.modifiers`, or a plain object, is a TypeScript error.
## Order and style
[Section titled “Order and style”](#order-and-style)
Modifiers wrap the finished component, including everything `style` does, in list order. The first modifier is innermost:
* `clipShape`, `blur` and the color adjustments apply to the whole component, background included.
* Geometry modifiers such as `rotationEffect`, `scaleEffect` and `offset` add to a `style.transform`, they do not replace it.
* Text modifiers set a value for the text inside, and SwiftUI uses the setting closest to the text. A value the component sets itself wins over the modifier, such as `style.textAlign` or the `multilineTextAlignment` prop over a `multilineTextAlignment` modifier.
* To apply a modifier before part of the style, such as clipping before a shadow is drawn, nest a `Voltra.View`: put the modifier on the inner one and the shadow on the outer one.
Text modifiers such as `minimumScaleFactor`, `truncationMode` and `monospacedDigit` work on any component. On a container they apply to every `Text` inside it that does not set the same thing itself.
## Available modifiers
[Section titled “Available modifiers”](#available-modifiers)
Modifiers marked iOS 17+ leave the component unchanged on older systems. The same applies to options marked iOS 17 or iOS 18.
### Widgets and Live Activities
[Section titled “Widgets and Live Activities”](#widgets-and-live-activities)
| Modifier | What it does |
| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `widgetURL(url)` | Opens the URL in your app when the widget or Live Activity is tapped. Takes an absolute URL or a path, like `deepLinkUrl`. The compact and minimal Dynamic Island ignore it. |
| `containerBackground(color)` | Sets the widget’s removable container background. Use it on the outermost component. iOS 17+. |
| `widgetAccentable(accentable?)` | Adds the component to the accent group in accented rendering mode. |
| `privacySensitive(sensitive?)` | Redacts the component while the device is locked. |
| `redacted(reason)` | Renders the component redacted: `placeholder`, `privacy`, or `invalidated` (iOS 17). |
| `unredacted()` | Keeps the component visible inside a redacted container. |
| `invalidatableContent(invalidatable?)` | Marks content that goes stale while an interactive widget updates. iOS 17+. |
| `activityBackgroundTint(color \| null)` | Tints the Live Activity’s Lock Screen background. A tint passed when starting or updating the Live Activity takes precedence. |
| `activitySystemActionForegroundColor(color \| null)` | Colors the system action button next to the Live Activity. |
### Transitions and animation
[Section titled “Transitions and animation”](#transitions-and-animation)
| Modifier | What it does |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `contentTransition(kind, { countsDown? })` | Animates content changes: `identity`, `opacity`, `interpolate`, `numericText`, or `symbolEffect` (iOS 17). |
| `transition(kind, { edge? })` | Animates a component that appears or disappears between two updates: `identity`, `opacity`, `scale`, `slide`, `push`, `move`. Put `animation` on a parent that stays, and give the siblings an `id`. |
| `animation(curve, { value, duration? })` | Animates the component when `value` changes. `duration` does not apply to `default` and `spring`. `bouncy`, `smooth` and `snappy` need iOS 17. |
| `symbolEffect(effect)` | Applies an indefinite effect to `Symbol` components: `pulse`, `variableColor`, or `breathe`, `rotate`, `wiggle` (iOS 18). Widgets and Live Activities may show it as a still frame. iOS 17+. |
### Visual effects
[Section titled “Visual effects”](#visual-effects)
| Modifier | What it does |
| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `clipShape(shape, { cornerRadius?, cornerStyle? })` | Clips to `rectangle`, `roundedRectangle`, `circle`, `capsule`, or `ellipse`. `cornerRadius` only applies to `roundedRectangle`. |
| `blur(radius, { opaque? })` | Applies a Gaussian blur. |
| `grayscale(amount)`, `saturation(amount)`, `brightness(amount)`, `contrast(amount)` | Adjusts colors. |
| `blendMode(mode)` | Sets how the component blends with what is behind it. |
### Geometry and layout
[Section titled “Geometry and layout”](#geometry-and-layout)
| Modifier | What it does |
| --------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `rotationEffect(degrees)` | Rotates the rendered component without changing layout. |
| `scaleEffect(scale \| { x?, y? })` | Scales the rendered component without changing layout. |
| `offset({ x?, y? })` | Moves the rendered component without changing layout. |
| `fixedSize({ horizontal?, vertical? })` | Keeps the ideal size instead of shrinking to fit. |
| `layoutPriority(priority)` | Gives the component a larger share of space in its stack. |
| `containerRelativeFrame(axes)` | Sizes the component relative to its container: `horizontal`, `vertical`, or `both`. iOS 17+. |
| `dynamicTypeSize(size)` | Uses a fixed Dynamic Type size for content inside. Voltra `Text` uses fixed font sizes, so it does not change. |
### Text
[Section titled “Text”](#text)
| Modifier | What it does |
| ----------------------------------- | ----------------------------------------------------------------- |
| `minimumScaleFactor(factor)` | Lets text shrink to this fraction of its size to fit. |
| `truncationMode(mode)` | Truncates at the `head`, `middle`, or `tail`. |
| `multilineTextAlignment(alignment)` | Aligns lines of multi-line text: `leading`, `center`, `trailing`. |
| `monospacedDigit()` | Uses fixed-width digits so changing numbers do not shift. |
## Troubleshooting
[Section titled “Troubleshooting”](#troubleshooting)
**A modifier has no effect.** Check whether the table marks it iOS 17+. On older systems the component renders without the modifier. An invalid value, such as an unknown color string, is also skipped; the widget extension logs `Ignoring modifier ` under the `com.voltra` subsystem in Console.
**Tapping the widget opens the wrong URL.** A `deepLinkUrl` configured for the widget or Live Activity takes precedence over `widgetURL`. Remove one of them, and use `widgetURL` only once per widget. In a Live Activity, use it once per presentation.
**Tapping the Dynamic Island opens the app but not the URL.** A tap on the compact or minimal Dynamic Island opens only the Live Activity’s `deepLinkUrl`. A `widgetURL` inside those regions is not used, and Voltra logs a warning under the `com.voltra` subsystem in Console. Pass `deepLinkUrl` when you start the Live Activity.
**The widget background does not change.** Put `containerBackground` on the widget’s outermost component, and use it only once. It needs iOS 17; on iOS 16 use `style.backgroundColor` instead.
**Values change without animating.** SwiftUI animates between updates only when each position in the list keeps the same modifier. Changing the modifier at a position, or adding and removing the whole list, redraws the component instead.
**A component appears or disappears without animating.** SwiftUI animates an insertion or removal in the parent, so `animation` on the component itself has nothing to animate. Put `animation({ value })` on a parent that is present before and after, keep `transition` on the component, and give the parent’s children an `id`; without one, children are matched by position, and a sibling can take the place of the component that disappeared.
**Rendering a pushed update fails with `Compressed payload size … exceeds safe budget`.** Move the UI that needs modifiers to a Dynamic Live Activity or Dynamic Widget, or remove modifiers from the pushed tree.
# Performance
> Reduce Live Activity payload size with element deduplication and other practices that keep updates within ActivityKit limits.
Voltra provides automatic optimizations to help you create efficient Live Activities, but following these best practices will ensure optimal performance and stay within ActivityKit’s payload size limits.
## Element deduplication
[Section titled “Element deduplication”](#element-deduplication)
Reuse JSX elements by creating them once, storing them in variables, and reusing them across your JSX tree, instead of recreating the same element inline in multiple places. Voltra automatically detects duplicate element references and shrinks the payload size as a result — no extra code required.
```tsx
import { Voltra } from '@use-voltra/ios'
// ✅ Good: Create element once and reuse
const sharedButton = Click me
const sharedIcon =
const variants = {
lockScreen: (
Order Status
{sharedButton}
{sharedIcon}
),
island: {
minimal: (
{sharedIcon}
{sharedButton}
),
},
}
```
```tsx
// ❌ Avoid: Creating separate element instances
const variants = {
lockScreen: (
Order StatusClick me // Duplicate instance
// Duplicate instance
),
island: {
minimal: (
// Another duplicate instance
Click me // Another duplicate instance
),
},
}
```
## Image optimization
[Section titled “Image optimization”](#image-optimization)
Images can significantly impact payload size. For comprehensive guidance on handling images in Live Activities, see the [Images](/ios/development/images) documentation, which covers:
* Base64 encoding for small static images
* Build-time asset copying for medium-sized images
* Runtime preloading for dynamic images
Choose the appropriate approach based on your image size, when it’s known, and whether it changes dynamically.
## Reuse style objects
[Section titled “Reuse style objects”](#reuse-style-objects)
Reuse style objects and avoid inline styles when possible:
```tsx
// ✅ Good: Shared style objects
const buttonStyle = { padding: 8, borderRadius: 6 }
const textStyle = { fontSize: 14, color: '#666' }
TitleAction
// ❌ Avoid: Inline styles everywhere
TitleAction
```
# Querying Active Widgets
> Detect which Voltra widgets the user has placed on the Home Screen with the getActiveWidgets API.
Voltra allows you to detect which widgets the user has currently placed on their Home Screen. This is useful for:
* Determining if you need to update a specific widget
* Showing a list of active widgets in your app settings
* Optimizing background updates by only targeting installed widgets
## getActiveWidgets API
[Section titled “getActiveWidgets API”](#getactivewidgets-api)
The `getActiveWidgets` function returns a promise that resolves to an array of all active widget configurations for your app.
Caution
There may be a slight delay in the data returned by this API. iOS caches widget configurations, and it might take a few moments for the system to reflect recent additions or removals of widgets on the Home Screen.
```typescript
import { getActiveWidgets } from '@use-voltra/ios-client'
async function checkWidgets() {
const activeWidgets = await getActiveWidgets()
console.log(`User has ${activeWidgets.length} widgets installed`)
activeWidgets.forEach(widget => {
console.log(`- Widget Name: ${widget.name}`)
console.log(` Family: ${widget.family}`)
console.log(` Kind: ${widget.kind}`)
})
}
```
### WidgetInfo Object
[Section titled “WidgetInfo Object”](#widgetinfo-object)
Each object in the returned array contains:
| Property | Type | Description |
| -------- | -------------- | -------------------------------------------------------------------------------------- |
| `name` | `string` | The unique ID of the widget as defined in your Expo config plugin (e.g., `"weather"`). |
| `kind` | `string` | The internal identifier string used by iOS (e.g., `"Voltra_Widget_weather"`). |
| `family` | `WidgetFamily` | The size of the widget instance (e.g., `"systemSmall"`, `"systemMedium"`, etc.). |
# Server-driven widgets
> Have Home Screen widgets fetch fresh content from your server on a schedule with serverUpdate, without the user opening the app.
Server-driven widgets allow your Home Screen widgets to periodically fetch fresh content from a remote server—without the user opening the app. This is ideal for widgets that display dynamic data like weather, news, stock prices, or live scores.
Before you start, make sure the widget is registered in the Voltra plugin config and plan to rebuild the native app after adding or changing server-driven widget settings.
## How it works
[Section titled “How it works”](#how-it-works)
1. You configure a `serverUpdate` URL in your widget’s plugin config
2. iOS WidgetKit calls your server at the configured interval
3. Your server renders Voltra JSX components into a JSON payload
4. The widget extension parses the payload and updates the widget
The entire lifecycle is managed by the OS timeline system. Your app doesn’t need to be running.
A widget that also has an `entry` works the other way round: your server returns plain JSON data and the widget renders it on the device, so the backend can be written in any language. See [Returning data instead of UI](#returning-data-instead-of-ui).
## Plugin configuration
[Section titled “Plugin configuration”](#plugin-configuration)
Add the `serverUpdate` option to your widget in `app.json` or `app.config.js`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"widgets": [
{
"id": "dynamic_weather",
"displayName": "Dynamic Weather",
"description": "Weather with live server updates",
"supportedFamilies": ["systemSmall", "systemMedium", "systemLarge"],
"serverUpdate": {
"url": "https://api.example.com/widgets/render",
"intervalMinutes": 30
}
}
]
}
]
]
}
}
```
**`serverUpdate` options:**
* `url`: The endpoint the widget fetches from. Voltra appends `widgetId`, `platform`, `family`, `theme`, and `locale` query parameters automatically (e.g. `?widgetId=dynamic_weather&platform=ios&family=systemSmall&theme=dark&locale=en-US`). Optional — leave it out to mark the widget server-driven and supply the URL after login with [`setWidgetServerUpdate`](#changing-settings-at-runtime).
* `intervalMinutes`: How often the widget fetches updates. Defaults to `15`. WidgetKit may stretch it: the reload budget is shared across every widget in your app, and frequently viewed widgets get roughly 40 to 70 reloads a day between them.
* `refresh`: Whether to show a native refresh button in the top-right corner of the widget. When tapped, triggers an immediate server fetch. Defaults to `false`. Requires iOS 17+.
After updating plugin configuration, run `npx expo prebuild` if you’re using Continuous Native Generation, then rebuild the app so the generated native files and widget extension pick up the new server update settings.
## Building the server
[Section titled “Building the server”](#building-the-server)
Voltra provides widget server handlers for the common runtime styles. Use `createWidgetUpdateHandler()` for Fetch-compatible runtimes, `createWidgetUpdateNodeHandler()` for `node:http`, and `createWidgetUpdateExpressHandler()` for Express-style handlers. All three share the same request parsing, platform validation, token validation, and response serialization.
```tsx
import { createServer } from 'node:http'
import React from 'react'
import { createIOSWidgetUpdateNodeHandler, Voltra } from '@use-voltra/ios-server'
const handler = createIOSWidgetUpdateNodeHandler({
render: async (req) => {
// req.widgetId — the widget requesting an update
// req.platform — always "ios" for iOS widget requests
// req.family — the widget size ("systemSmall", "systemMedium", etc.)
// req.theme — the system color scheme ("light" or "dark")
// req.token — the auth token (if credentials were set)
const weather = await fetchWeatherData()
return {
systemSmall: (
{weather.temp}°{weather.condition}
),
systemMedium: (
{weather.temp}°{weather.condition}
H: {weather.high}° L: {weather.low}°
),
}
},
validateToken: async (token) => {
// Return true if the token is valid, false to reject with 401
return token === 'valid-token'
},
})
createServer(handler).listen(3333, () => {
console.log('Widget server running on http://localhost:3333')
})
```
The handler responds to GET requests with these query parameters:
| Parameter | Description |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `widgetId` | The widget identifier (required) |
| `platform` | The requesting platform. Must be `ios` for iOS widgets (required). |
| `family` | The widget family/size (iOS only) |
| `theme` | The system color scheme (`light` or `dark`) |
| `locale` | The device locale as a BCP-47 tag, e.g. `en-US` |
| `instance` | A stable hash of the placement’s merged configuration. Present only when the widget has configuration parameters (see [Per-instance requests](#per-instance-requests)). |
| `configuration` | The placement’s merged configuration as canonical JSON. Present only when the widget has configuration parameters. |
The `Authorization: Bearer ` header is automatically extracted and passed to `validateToken` and `render`. The `User-Agent` header is set to `VoltraWidget/1.0 (iOS/)`.
### Per-instance requests
[Section titled “Per-instance requests”](#per-instance-requests)
WidgetKit lets people configure each placed widget separately through the system Edit Widget sheet — one placement can be set to London, another to New York. When a widget has configuration parameters, every request carries that placement’s configuration so a server can answer each one differently:
```plaintext
GET https://api.example.com/widgets/weather
?widgetId=weather&platform=ios&family=systemSmall&theme=dark&locale=en-US
&instance=3f9a2c1e
&configuration=%7B%22city%22%3A%22London%22%2C%22units%22%3A%22metric%22%7D
```
* `configuration` is the merged configuration map, serialized canonically: keys sorted by code point, no whitespace, values as JSON strings. Decoded, it is exactly what the widget sees as `env.configuration`.
* `instance` is a stable, non-cryptographic hash of that canonical string. Two placements with identical configuration send the same `instance` and share one fetch, one cached response, and one props slot. WidgetKit has no placement identity of its own, so a placement’s configuration is the only thing that can distinguish it from another.
* Both parameters are absent when the widget has no configuration parameters at all, so an existing server-driven widget’s requests are unchanged by this feature.
* `instance` and `configuration` are reserved query keys: a `query` you pass to `setWidgetServerUpdate` naming either is rejected.
Configurations are meant for identifiers and short choices, not large payloads — percent-encoding roughly triples the size of braces and quotes in the JSON.
**Fetch count.** A server-driven widget fetches once per distinct configuration among its current placements, not once per placement. If ten placements of one widget each use a different value for a free-text parameter, that is ten fetches per interval (each still floored at 15 minutes) rather than one. A server can still stretch the interval per instance with `Cache-Control: max-age`, exactly as it can today.
A widget with no configuration parameters keeps behaving exactly as it did before: one request, one cached response, shared by every placement.
For Fetch-native runtimes, use `createWidgetUpdateHandler()` instead of the Node adapter:
```tsx
import { createIOSWidgetUpdateHandler, Voltra } from '@use-voltra/ios-server'
export const GET = createIOSWidgetUpdateHandler({
render: async (req) => ({
systemSmall: {req.widgetId},
}),
})
```
## Returning data instead of UI
[Section titled “Returning data instead of UI”](#returning-data-instead-of-ui)
Everything above assumes your server renders Voltra components and returns a UI payload, which means it has to run Node. If you give the widget an `entry`, it renders on the device instead and your server returns plain JSON — so it can be written in any language.
Add both keys to the same widget. A widget with an `entry` and a `serverUpdate` also needs a `groupIdentifier`, because the fetched props are shared with the widget extension through the App Group:
```json
{
"id": "portfolio",
"displayName": "Portfolio",
"description": "Your holdings",
"supportedFamilies": ["systemSmall", "systemMedium"],
"entry": "./widgets/ios/portfolio.tsx",
"initialStatePath": "./widgets/ios/portfolio.tsx",
"serverUpdate": {
"url": "https://api.example.com/widgets/portfolio",
"intervalMinutes": 30
}
}
```
The response body becomes the widget’s props, verbatim:
```php
12480.55,
'change' => 1.8,
'holdings' => [
['symbol' => 'AAPL', 'value' => 8200.00],
['symbol' => 'MSFT', 'value' => 4280.55],
],
]);
```
Your widget entry receives that object as its first argument, the same shape you would pass to `updateDynamicWidget`:
```tsx
export default function PortfolioWidget(props, env) {
return (
${props.total.toFixed(2)}{props.change}% today
)
}
```
Check the endpoint with curl before wiring up the widget:
```bash
curl "https://api.example.com/widgets/portfolio?widgetId=portfolio&platform=ios&theme=dark&locale=en-US" \
-H "Accept: application/json"
```
One fetch serves every size and instance of the widget, so the request carries no `family` and your props have to be size-agnostic. The entry picks its layout from `env.widgetFamily`, the way it already does.
### What the response has to be
[Section titled “What the response has to be”](#what-the-response-has-to-be)
* Status `200` with `Content-Type: application/json` and a JSON **object**. An array, a string, a number or `null` at the top level is rejected.
* At most 256 KB. The widget extension has a 30 MB memory ceiling for the whole render.
* Return `ETag` and Voltra sends it back as `If-None-Match` on the next fetch. A `304` means the widget keeps what it has and counts as fresh. This applies to widgets with an `entry`; a payload widget’s request is unconditional.
* `Cache-Control: max-age=N` moves the next fetch, clamped between 15 minutes and 24 hours. `Retry-After` on a `429` or `503` is honoured the same way.
Returning a rendered Voltra payload from an endpoint whose widget has an `entry` is rejected with a log line naming the mismatch. The widget has an entry, so it wants the data, not the picture.
### Telling fresh data from stale
[Section titled “Telling fresh data from stale”](#telling-fresh-data-from-stale)
The widget is never blanked by a failed fetch: it keeps rendering the last props that arrived, whether from the server or from `updateDynamicWidget`. `env.serverUpdate` says which:
```tsx
export default function PortfolioWidget(props, env) {
const stale = env.serverUpdate?.status === 'stale'
return (
${props.total?.toFixed(2) ?? '—'}
{env.serverUpdate?.fetchedAt && (
Updated {new Date(env.serverUpdate.fetchedAt).toLocaleTimeString()}
)}
)
}
```
| Field | Meaning |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status` | `fresh` after a `200` or `304`; `stale` when a fetch has succeeded before but the last one failed; `never` before the first success; `disabled` while your app has taken the widget over |
| `fetchedAt` | Epoch milliseconds of the last `200` or `304`. Absent until a fetch succeeds. |
| `error` | `network`, `http`, `unauthorized`, `parse`, or `render`. Absent when `status` is `fresh`. |
| `httpStatus` | Status code of the last response, when there was one |
`env.serverUpdate` is `undefined` on widgets without a `serverUpdate`.
Props that throw during rendering are never committed — Voltra renders them once off screen first, and keeps the previous props when that fails. `env.serverUpdate.error` is `render` while that lasts.
## Authentication
[Section titled “Authentication”](#authentication)
Widgets run in a separate extension process and can’t access your app’s network layer or auth state. Voltra solves this by storing credentials in the **Shared Keychain**, which is accessible by both the main app and the widget extension.
Note
`setWidgetServerCredentials` is deprecated in favour of [`setWidgetServerUpdate`](#changing-settings-at-runtime) with an `Authorization` header, which can also set the URL, the interval, the method, query parameters and a body. Both write the same Keychain records, so switching is a one-line change and nothing has to be migrated on device.
### Setting credentials
[Section titled “Setting credentials”](#setting-credentials)
Call `setWidgetServerCredentials` after the user logs in:
```typescript
import { setWidgetServerCredentials } from '@use-voltra/ios-client'
await setWidgetServerCredentials({
token: userAccessToken,
headers: {
'X-App-Version': '1.0.0',
},
})
```
The `token` is required and is sent as `Authorization: Bearer ` on every server request. Any additional `headers` are also included. If your widget endpoint does not require authentication, skip `setWidgetServerCredentials()` entirely.
### Clearing credentials
[Section titled “Clearing credentials”](#clearing-credentials)
Call `clearWidgetServerCredentials` when the user logs out:
```typescript
import { clearWidgetServerCredentials } from '@use-voltra/ios-client'
await clearWidgetServerCredentials()
```
All widget timelines are automatically reloaded after credentials are cleared, so widgets revert to their default/unauthenticated state immediately.
### Keychain group
[Section titled “Keychain group”](#keychain-group)
For credentials to be shared between the main app and the widget extension, both must belong to the same Keychain Access Group. This is configured via the `keychainGroup` plugin option:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"keychainGroup": "$(AppIdentifierPrefix)com.example.shared",
"widgets": [...]
}
]
]
}
}
```
If you don’t specify `keychainGroup` but any widget has `serverUpdate` configured, Voltra automatically derives a default: `$(AppIdentifierPrefix)`.
## Changing settings at runtime
[Section titled “Changing settings at runtime”](#changing-settings-at-runtime)
`serverUpdate` in `app.json` is the default. Once the app runs it can change any of it, per widget or for all of them, without a rebuild:
```typescript
import { setWidgetServerUpdate } from '@use-voltra/ios-client'
await setWidgetServerUpdate(
{
url: `https://${tenant}.example.com/widgets/portfolio`,
intervalMinutes: 30,
headers: { Authorization: `Bearer ${accessToken}` },
},
{ widgetId: 'portfolio' }
)
```
| Setting | |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `url` | Must be `https`, or `http` to a local dev host (`localhost`, `127.0.0.1`, `::1`, `10.0.2.2`, `10.0.3.2`) in a debug build |
| `intervalMinutes` | Clamped between 15 minutes and 24 hours |
| `enabled` | `false` stops fetching until you set it back |
| `method` | `GET` (default), `POST`, `PUT`, `PATCH` or `DELETE` |
| `query` | Extra query parameters |
| `headers` | Extra request headers |
| `body` | Sent as `application/json` |
Leave out `widgetId` to set the same values for every server-driven widget. A widget-scoped call wins over a global one; `headers` and `query` merge per key across the two, everything else takes the more specific value.
Each call replaces everything it set last time, so pass every field you want to keep. Setting anything reloads the widgets it affects, so the change takes effect without waiting out the current interval.
Use this instead of `setWidgetServerCredentials`, which does the same thing for the `Authorization` header alone:
```typescript
// Before
await setWidgetServerCredentials({ token: accessToken, headers: { 'X-App-Version': '1.0.0' } })
// After
await setWidgetServerUpdate({
headers: { Authorization: `Bearer ${accessToken}`, 'X-App-Version': '1.0.0' },
})
```
To go back to what `app.json` configured, clear the settings:
```typescript
import { clearWidgetServerUpdate } from '@use-voltra/ios-client'
await clearWidgetServerUpdate({ widgetId: 'portfolio' })
await clearWidgetServerUpdate()
```
Clearing the global settings is the logout gesture. Along with the settings it drops what the server last sent — the props and the “updated at” of every server-driven widget — so a Dynamic Widget goes back to rendering `{}` with `env.serverUpdate.status` of `never` rather than showing the previous account’s data. A widget-scoped clear only drops that widget’s overrides and leaves its props alone.
Read the settings back with `getWidgetServerUpdate`:
```typescript
import { getWidgetServerUpdate } from '@use-voltra/ios-client'
const snapshot = await getWidgetServerUpdate({ widgetId: 'portfolio' })
if (snapshot?.enabled) {
console.log(`portfolio fetches ${snapshot.url} every ${snapshot.intervalMinutes}m`)
}
```
With a `widgetId`, this is the fully resolved settings that widget would fetch with right now — every layer flattened and `app.json`’s defaults applied, or `null` if the widget isn’t server-driven. Without one, it’s the raw global layer only: what the last widget-less `setWidgetServerUpdate` call wrote, with no defaults applied, or `null` if nothing has been set globally.
Credentials set with the deprecated `setWidgetServerCredentials` are stored separately and are not affected; clear those with `clearWidgetServerCredentials`.
Calling either function for a widget that has no `serverUpdate` in `app.json` throws. Whether a widget is server-driven is decided when the native project is generated, so a runtime URL cannot turn a local widget into one — add `serverUpdate` to `app.json` and rebuild.
A `body` set alongside `GET` or `HEAD` is dropped with a warning, because `URLSession` cannot send one.
### Driving a widget from the app
[Section titled “Driving a widget from the app”](#driving-a-widget-from-the-app)
`updateWidget` and `updateDynamicWidget` work on server-driven widgets, but the next scheduled fetch overwrites what you wrote. To keep it, turn fetching off first:
```typescript
await setWidgetServerUpdate({ enabled: false }, { widgetId: 'portfolio' })
await updateDynamicWidget('portfolio', localProps)
```
While fetching is off, `env.serverUpdate.status` is `disabled`, so the widget can hide its “updated N minutes ago” line. Set `enabled: true`, or clear the settings, to hand it back to the server.
## Refresh button
[Section titled “Refresh button”](#refresh-button)
Server-driven widgets can display a native refresh button that lets users trigger an immediate update on demand. Enable it in your widget config:
```json
{
"serverUpdate": {
"url": "https://api.example.com/widgets/render",
"intervalMinutes": 30,
"refresh": true
}
}
```
When enabled, a small circular button (↻) appears in the top-right corner of the widget. Tapping it triggers `reloadTimelines(ofKind:)` via an `AppIntent`, which causes WidgetKit to immediately fetch fresh content from your server.
Note
The refresh button requires iOS 17+ (`AppIntent` API). On older iOS versions, the button is not shown.
### Fetch coalescing
[Section titled “Fetch coalescing”](#fetch-coalescing)
When WidgetKit reloads timelines, it may call `getTimeline` multiple times for each supported family (e.g. `systemSmall`, `systemMedium`). To avoid redundant network requests, Voltra coalesces fetches within a 3-second window per widget. Only the first call triggers a server fetch; subsequent calls within the window use cached data and `selectContentForFamily` picks the correct family-specific content.
## Triggering manual refreshes
[Section titled “Triggering manual refreshes”](#triggering-manual-refreshes)
You can force-refresh server-driven widgets outside of the regular interval:
```typescript
import { reloadWidgets } from '@use-voltra/ios-client'
// Reload specific widgets
await reloadWidgets(['dynamic_weather'])
// Reload all widgets
await reloadWidgets()
```
This triggers an immediate timeline refresh, which causes WidgetKit to call your server for new content.
## Initial state
[Section titled “Initial state”](#initial-state)
Server-driven widgets still need content to display before the first server fetch completes (e.g. when the widget is first added to the Home Screen). Use `initialStatePath` to provide a pre-rendered default:
```json
{
"id": "dynamic_weather",
"displayName": "Dynamic Weather",
"description": "Weather with live server updates",
"supportedFamilies": ["systemSmall", "systemMedium"],
"initialStatePath": "./widgets/ios/weather-initial.tsx",
"serverUpdate": {
"url": "https://api.example.com/widgets/render",
"intervalMinutes": 30
}
}
```
See [Widget pre-rendering](/ios/development/widget-pre-rendering) for details on creating initial state files.
Tip
Provide a meaningful initial state (e.g. “Loading…” or placeholder content) rather than leaving it empty. The user sees this until the first server fetch succeeds.
## Error handling and retries
[Section titled “Error handling and retries”](#error-handling-and-retries)
When a server fetch fails, the widget extension falls back to the last successfully fetched data (or the initial state if no data has been fetched yet), and WidgetKit schedules a retry after 15 minutes. The last successful response is kept in memory for the lifetime of the widget extension process; when an App Group is configured it is also persisted so a freshly started process can fall back to it. This applies to network errors/timeouts, non-2xx server errors, and empty responses.
Parse errors are handled slightly differently: if the server returns a 2xx response but the JSON can’t be parsed into a valid widget tree, the cached data from the previous successful fetch is preserved (not overwritten), so the widget keeps showing the last known good content.
A `401` or `403` does not shorten the retry: the status will not change until you set a new token, and doing so reloads the widget anyway.
For widgets that return props rather than UI, the widget keeps rendering the last props it has through every one of these, and `env.serverUpdate` says what went wrong.
Note
WidgetKit may also throttle updates based on battery level and widget visibility.
# Server-side updates
> Start, update, and end Live Activities from your server through APNS push notifications, including plugin setup and push tokens.
Voltra supports server-side updates for Live Activities through Apple Push Notification Service (APNS). This allows you to update Live Activities even when your app is in the background or terminated.
## Configuration
[Section titled “Configuration”](#configuration)
### Expo Config plugin setup
[Section titled “Expo Config plugin setup”](#expo-config-plugin-setup)
To enable server-side updates via push notifications, you need to configure the Voltra plugin in your `app.json` or `app.config.js`:
**Minimal configuration (push notifications only):**
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"enablePushNotifications": true
}
]
]
}
}
```
**Full configuration (with App Groups for event forwarding and shared images):**
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"enablePushNotifications": true,
"groupIdentifier": "group.your.app.voltraui",
"deploymentTarget": "18.0"
}
]
]
}
}
```
**Note:** The `groupIdentifier` is optional. It’s only needed if you want to forward component events (like button taps) from the Live Activity extension to your JavaScript code, or if you need to share images between your app and the extension. Push notifications work perfectly fine without it.
### Xcode configuration
[Section titled “Xcode configuration”](#xcode-configuration)
The Voltra config plugin automatically handles most of the Xcode configuration for you:
* Adds the `aps-environment` entitlement (set to `development` for debug builds)
* Configures Info.plist flags to enable push notification integration
* Sets up App Group entitlements (if `groupIdentifier` is provided)
However, you’ll still need to complete a few manual steps:
1. **Provisioning Profiles:** Ensure your app has proper provisioning profiles configured in Xcode with push notification capabilities enabled.
2. **APNs Certificates:** Set up APNs authentication certificates or keys in your Apple Developer account. You’ll need these to send push notifications from your server.
3. **Capabilities:** Verify that Push Notifications capability is enabled in your app’s target settings in Xcode.
For detailed information about setting up push notifications in iOS, refer to [Apple’s official push notification documentation](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server).
## Server-side rendering
[Section titled “Server-side rendering”](#server-side-rendering)
Voltra provides a server-side API that allows you to render React components into JSON payloads that can be sent via APNS. The same Voltra components you use in your app work on the server.
### Using the server-side API
[Section titled “Using the server-side API”](#using-the-server-side-api)
Import the server-side rendering functions from `@use-voltra/ios-server`:
```tsx
import { Voltra, renderLiveActivityToString } from '@use-voltra/ios-server'
// Render your UI components to a JSON string
const jsonPayload = renderLiveActivityToString({
lockScreen: (
Driver arrivedReady for pickup
),
})
```
The `renderLiveActivityToString` function accepts a `LiveActivityVariants` object and returns a compressed, base64-encoded JSON string for your APNS payload.
## APNS payload format
[Section titled “APNS payload format”](#apns-payload-format)
When sending push notifications to update Live Activities, you need to structure your APNS payload correctly. For detailed information about APNS payload structure, see Apple’s [official ActivityKit push notification documentation](https://developer.apple.com/documentation/activitykit/starting-and-updating-live-activities-with-activitykit-push-notifications).
You can also use Apple’s [CloudKit - Push Notifications tool](https://icloud.developer.apple.com/dashboard/notifications/) to send test push notifications during development.
### Required APNS headers
[Section titled “Required APNS headers”](#required-apns-headers)
```plaintext
apns-push-type: liveactivity
apns-topic: .push-type.liveactivity
```
Replace `` with your app’s bundle identifier (e.g., `com.example.myapp`).
### Payload structure
[Section titled “Payload structure”](#payload-structure)
**For updating an existing Live Activity:**
```json
{
"aps": {
"event": "update",
"content-state": {
"uiJsonData": "{\"lockScreen\":{\"type\":\"VStack\",\"children\":{\"type\":\"Text\",\"children\":\"Hello\",\"props\":{}},\"props\":{}}}"
},
"timestamp": 1764145755
}
}
```
**For starting a Live Activity remotely (iOS 17.2+):**
```json
{
"aps": {
"event": "start",
"content-state": {
"uiJsonData": "{\"lockScreen\":{\"type\":\"VStack\",\"children\":{\"type\":\"Text\",\"children\":\"Hello\",\"props\":{}},\"props\":{}}}"
},
"attributes-type": "VoltraAttributes",
"attributes": {
"name": "some-name",
"deepLinkUrl": "app://some-deep-link-url"
},
"timestamp": 1764145755,
"alert": {
"title": "Driver arrived",
"body": "Ready for pickup"
}
}
}
```
**For ending an existing Live Activity:**
```json
{
"aps": {
"timestamp": 1683012400,
"event": "end",
"content-state": {
"uiJsonData": "{\"lockScreen\":{\"type\":\"VStack\",\"children\":{\"type\":\"Text\",\"children\":\"Hello\",\"props\":{}},\"props\":{}}}"
},
"dismissal-date": 1683016000
}
}
```
**Key fields:**
* `aps.event`: Set to `"update"` to update, `"end"` to end, or `"start"` for push-to-start (iOS 17.2+)
* `aps.content-state.uiJsonData`: The JSON string returned by `renderLiveActivityToString`, embedded as a string value eg. `ixOAeyJ2IjoxLCJscyI6eyJ0IjowLCJjIjoiSGVsbG8sIHdvcmxkISJ9fQM=`. This must be sent for `update` and `end` events.
* `aps.timestamp`: Unix timestamp in seconds (required for Live Activities)
* `aps.attributes-type`: For push-to-start, must be `"VoltraAttributes"`
* `aps.attributes.name`: For push-to-start, a user-defined name for the activity (can be any string you choose)
* `aps.alert`: Required field for push-to-start
For `event: "end"`, include `aps.dismissal-date`. To remove the Live Activity from the Lock Screen right after it ends, set `dismissal-date` to a timestamp in the past (for example, 1663177260). You can also set a timestamp up to four hours in the future to control when it’s dismissed.
Danger
ActivityKit enforces a strict payload size limit of approximately 4 KB. Keep your UI JSON minimal to stay within this limit. Avoid deeply nested component trees, excessive styling and [native modifiers](/ios/development/native-modifiers) to ensure your payloads fit within the constraint.
## Getting push tokens
[Section titled “Getting push tokens”](#getting-push-tokens)
Voltra provides specialized push tokens that are different from regular device tokens. These tokens are specifically designed for Live Activity push notifications and should be used instead of standard device tokens.
### Tokens for updating Live Activities
[Section titled “Tokens for updating Live Activities”](#tokens-for-updating-live-activities)
To update existing Live Activities, use activity push tokens:
```tsx
import { addVoltraListener } from '@use-voltra/ios-client'
useEffect(() => {
const subscription = addVoltraListener('activityTokenReceived', ({
activityName,
pushToken,
timestamp,
type
}) => {
// Send the token to your server for updating this specific Live Activity
sendTokenToServer({
activityID,
token: pushToken,
type: 'update',
})
})
return () => {
subscription.remove()
}
}, [])
```
### Tokens for starting Live Activities remotely
[Section titled “Tokens for starting Live Activities remotely”](#tokens-for-starting-live-activities-remotely)
To start Live Activities remotely (push-to-start), use push-to-start tokens:
```tsx
useEffect(() => {
const subscription = addVoltraListener('activityPushToStartTokenReceived', ({ pushToStartToken, type }) => {
// Send the token to your server for starting new Live Activities
sendTokenToServer({
token: pushToStartToken,
type: 'start',
})
})
return () => {
subscription.remove()
}
}, [])
```
Use only Voltra-provided tokens, which are specialized for Live Activity push notifications and different from regular device tokens. Update tokens are tied to specific Live Activities, while push-to-start tokens are for starting new activities. Update tokens are provided when Live Activities are started and may change during the activity’s lifecycle. When sending notifications via APNS, use these push tokens as the target device token to route notifications to the correct Live Activity or device.
## Broadcast push notifications (iOS 18+)
[Section titled “Broadcast push notifications (iOS 18+)”](#broadcast-push-notifications-ios-18)
Starting with iOS 18 and iPadOS 18, you can use **broadcast push notifications** to update many Live Activities with a single push notification. Instead of sending individual notifications to each device token, you send one broadcast to a shared channel—all Live Activities subscribed to that channel receive the update. This is ideal for scenarios like live sports scores or flight status where many users follow the same event.
### Prerequisites
[Section titled “Prerequisites”](#prerequisites)
1. **Enable Broadcast Capability:** In your [Apple Developer account](https://developer.apple.com/account), go to Certificates, Identifiers & Profiles > Identifiers, select your App ID, and enable **Broadcast Capability** under Push Notifications.
2. **Create a channel:** Your server creates a channel via APNs and receives a channel ID. You can maintain up to 10,000 channels per app. Use [Apple Push Notification Console](https://icloud.developer.apple.com/dashboard/notifications/) or the [channel management API](https://developer.apple.com/documentation/usernotifications/sending-channel-management-requests-to-apns) to create channels.
3. **Plugin configuration:** Keep `enablePushNotifications: true` in your Voltra plugin config—the `aps-environment` entitlement is still required for broadcast push.
### Starting a Live Activity with a channel
[Section titled “Starting a Live Activity with a channel”](#starting-a-live-activity-with-a-channel)
Pass the `channelId` option when starting a Live Activity to subscribe it to a broadcast channel:
```typescript
import { Voltra } from '@use-voltra/ios'
import { startLiveActivity } from '@use-voltra/ios-client'
const activityId = await startLiveActivity(variants, {
activityName: 'match-123',
channelId: 'CTrNsYq/Ee8AALLzHQaVlA==', // Channel ID from your server
})
```
When `channelId` is provided, the Live Activity subscribes to broadcast updates on iOS 18+. On iOS versions before 18, broadcast is unavailable and Voltra falls back to token-based Live Activity push updates.
### Sending broadcast updates
[Section titled “Sending broadcast updates”](#sending-broadcast-updates)
To update all Live Activities on a channel, send a POST request to APNs with:
* **Path:** `/4/broadcasts/apps/` (bundle ID without the `.push-type.liveactivity` suffix)
* **Header:** `apns-channel-id: `
* **Payload:** Same structure as individual updates—`event: "update"`, `content-state`, `timestamp`, etc.
For the full broadcast payload format and headers, see [Apple’s broadcast push documentation](https://developer.apple.com/documentation/usernotifications/sending-broadcast-push-notification-requests-to-apns).
### Broadcast vs. individual tokens
[Section titled “Broadcast vs. individual tokens”](#broadcast-vs-individual-tokens)
| Aspect | Individual tokens | Broadcast |
| ----------------------------- | -------------------------------- | -------------------------------- |
| Server sends | One notification per device | One notification per channel |
| `activityTokenReceived` event | Fires for each activity | Does not fire |
| Best for | Per-user content (orders, rides) | Shared content (scores, flights) |
| iOS version | 16.4+ | 18+ |
## Handling background execution
[Section titled “Handling background execution”](#handling-background-execution)
When Live Activity tokens change or need to be refreshed, iOS may wake your app in the background to deliver new tokens. The app has a limited window of time (typically around 30 seconds) to handle the event and communicate with your server before iOS may suspend or terminate the background process.
### Detecting background execution
[Section titled “Detecting background execution”](#detecting-background-execution)
Use the `useIsHeadless()` hook in React components to determine if your app is running in the background. The hook re-checks the native headless state when the app becomes active, which prevents the UI from staying hidden if the user opens the app after it was initially launched in the background.
```tsx
import { useIsHeadless } from '@use-voltra/ios-client'
function App() {
const isHeadless = useIsHeadless()
if (isHeadless) {
// App is running in background/headless mode
console.log('App launched in headless mode for token refresh')
} else {
// App is running in foreground
console.log('App launched in foreground')
}
}
```
The `isHeadless()` function is also available for synchronous checks outside React components, but prefer `useIsHeadless()` when deciding whether to render UI.
### Optimizing for background execution
[Section titled “Optimizing for background execution”](#optimizing-for-background-execution)
When the app is launched in headless mode for token handling, **do not mount your main app component** to avoid excessive resource usage that could cause iOS to terminate the app before token updates are processed.
```typescript
// In your app's entry point (e.g., App.tsx, index.js)
import { useEffect } from 'react'
import { addVoltraListener, useIsHeadless } from '@use-voltra/ios-client'
function App() {
const isHeadless = useIsHeadless()
// Handle token events even in headless mode
useEffect(() => {
const subscription = addVoltraListener('activityTokenReceived', (event) => {
// Process token updates and send to server
sendTokenToServer(event)
})
return () => subscription.remove()
}, [])
// Only render the UI if not in headless mode
if (isHeadless) {
return null // Don't mount the app component tree
}
// Render your normal app UI
return
}
```
# Styling
> The React Native style properties Voltra supports on iOS, with notes on positioning, flexbox, gradients, and fonts.
You can style Voltra components using React Native-style `style` props. Voltra supports a limited subset of React Native style properties — enough to get you productive quickly if you already know RN styling.
## React Native style prop
[Section titled “React Native style prop”](#react-native-style-prop)
### Supported properties
[Section titled “Supported properties”](#supported-properties)
The following React Native style properties are supported:
**Layout:**
* `width` - Fixed width (number values only, percentages are ignored)
* `height` - Fixed height (number values only, percentages are ignored)
* `flex` - Flex shorthand (follows Yoga’s behavior). Positive values act as `flexGrow`, negative values act as `flexShrink`. Explicit `flexGrow`/`flexShrink` take precedence if both are specified.
* `flexGrow` - Flex grow factor. When > 0, allows the view to grow to fill available space (converts to flexible frame with `maxWidth`/`maxHeight` set to infinity)
* `flexShrink` - Flex shrink factor. When > 0, allows the view to shrink below its ideal size (sets `minWidth`/`minHeight` to 0)
* `padding` - Uniform padding on all edges
* `paddingTop`, `paddingBottom`, `paddingLeft`, `paddingRight` - Individual edge padding
* `paddingHorizontal`, `paddingVertical` - Horizontal and vertical padding
* `margin`, `marginTop`, `marginBottom`, `marginLeft`, `marginRight`, `marginHorizontal`, `marginVertical` - All margin properties are mapped to padding in SwiftUI
**Positioning:**
* `position` - Positioning mode: `'static'` (default), `'relative'`, or `'absolute'`
* `left` - Horizontal position coordinate (used with `position`)
* `top` - Vertical position coordinate (used with `position`)
* `zIndex` - Z-order of the element
**Style:**
* `backgroundColor` - Background color (hex strings, color names, or CSS gradient strings — see [Gradients](/ios/development/gradients))
* `opacity` - Opacity value between 0 and 1
* `borderRadius` - Corner radius value
* `borderWidth` - Border width
* `borderColor` - Border color
**Shadow:**
* `shadowColor` - Shadow color
* `shadowOffset` - Shadow offset (`{ width: number, height: number }`)
* `shadowOpacity` - Shadow opacity
* `shadowRadius` - Shadow blur radius
**Text:**
* `fontSize` - Font size (maps to `font` modifier)
* `fontWeight` - Font weight (e.g., `'600'`, `'bold'`, `'regular'`)
* `fontFamily` - Custom font family name (see [Custom Fonts](/ios/development/custom-fonts))
* `color` - Text color (maps to `foregroundStyle` modifier)
* `letterSpacing` - Spacing between characters (maps to `kerning` modifier)
* `fontVariant` - Font variant array (e.g., `['small-caps', 'tabular-nums']`). Supported values:
* `'small-caps'` - Applies small caps styling (iOS 14+)
* `'tabular-nums'` - Applies monospaced digits (iOS 15+)
**Effects:**
* `overflow: 'hidden'` - Clips content to bounds (maps to `clipped` modifier)
### Flexbox Properties (Opt-in)
[Section titled “Flexbox Properties (Opt-in)”](#flexbox-properties-opt-in)
When using the `View` component or enabling flexbox mode on `VStack`/`HStack` with `layout="flex"`, additional flexbox properties become available via the `style` prop:
**Container Properties:**
* `flexDirection`: `'row'` | `'column'` - Main axis direction
* `alignItems`: `'flex-start'` | `'center'` | `'flex-end'` | `'stretch'` - Cross-axis alignment
* `justifyContent`: `'flex-start'` | `'center'` | `'flex-end'` | `'space-between'` | `'space-around'` | `'space-evenly'` - Main-axis distribution
* `gap`: number - Spacing between children along the main axis (one-axis only, no columnGap/rowGap)
**Child Properties:**
* `flex`: number - Shorthand for flexGrow/flexShrink
* `flexGrow`: number - Growth factor
* `flexShrink`: number - Shrink factor
* `flexBasis`: number | ‘auto’ - Base size
* `alignSelf`: Override parent’s alignItems
Note
Flexbox properties only work when flexbox layout is enabled. See [Flexbox Layout](/ios/development/flexbox-layout) for comprehensive documentation.
### Limitations
[Section titled “Limitations”](#limitations)
Properties not listed above are ignored during rendering. This includes common React Native properties like:
* Flexbox layout properties (`flexDirection`, `justifyContent`, `alignItems`, `gap`, etc.) are only available when using flexbox layout. Use the `View` component or set `layout="flex"` on VStack/HStack to enable these properties. See [Flexbox Layout](/ios/development/flexbox-layout) for details. Properties `flex`, `flexGrow`, `flexShrink`, `flexBasis`, and `alignSelf` work on children inside flexbox containers.
* `columnGap`, `rowGap`, and `flexWrap` properties - Voltra only supports a single `gap` value along the main axis, and does not support wrapping
* Percentage-based widths and heights
* `right` and `bottom` positioning properties - Only `left` and `top` are supported
* Most text styling properties beyond `fontSize`, `fontWeight`, `fontFamily`, `color`, `letterSpacing`, and `fontVariant`
* **Live Update Overrides**: Certain styling properties (like `height` or `borderRadius` on progress bars) may be ignored when using live-updating features like `timerInterval` to ensure compatibility with smooth system animations.
Positioning in Voltra
Voltra supports CSS-style positioning with three modes:
* **`position: 'static'`** - Normal layout flow. `left` and `top` are ignored.
* **`position: 'relative'`** - Offsets the element from its natural position using `left` and `top`. The offset moves the element right (positive `left`) and down (positive `top`).
* **`position: 'absolute'`** (default when `left`/`top` provided) - Positions the element’s **center** at the coordinates specified by `left` and `top`. This differs from CSS which positions from the top-left corner, but matches SwiftUI’s native behavior.
**Note**: If you provide `left` or `top` without specifying `position`, it defaults to `'absolute'` for backward compatibility. To ignore `left`/`top`, explicitly set `position: 'static'`.
For most layouts, prefer using stack `alignment` props (`ZStack`, `VStack`, `HStack`) which provide better layout control. Use positioning for fine-tuning or overlays.
See the [Layout & Containers](/ios/components/layout) documentation for details on alignment.
### Example
[Section titled “Example”](#example)
```tsx
import { Voltra } from '@use-voltra/ios'
const element = (
Styled Text
)
```
For gradients and custom fonts, see the dedicated [Gradients](/ios/development/gradients) and [Custom Fonts](/ios/development/custom-fonts) pages.
## Sharing styles with `StyleSheet`
[Section titled “Sharing styles with StyleSheet”](#sharing-styles-with-stylesheet)
Widget files can import `StyleSheet` and `Platform` from `react-native`, so styles can live outside the element tree exactly as they do in the rest of your app:
```tsx
import { Platform, StyleSheet } from 'react-native'
import { Voltra } from '@use-voltra/ios'
const styles = StyleSheet.create({
container: {
padding: 16,
borderRadius: 18,
backgroundColor: '#101828',
},
title: {
color: '#F8FAFC',
fontSize: 18,
fontWeight: '600',
},
})
const element = (
{Platform.OS}
)
```
Widget code does not run against the React Native runtime — at build time it is evaluated in a Node sandbox, and Dynamic Widgets run on device in a separate JS engine with no bridge. Only the parts of `react-native` that are pure data manipulation are therefore available:
* `StyleSheet.create`, `StyleSheet.flatten`, `StyleSheet.compose`, `StyleSheet.absoluteFill`, `StyleSheet.absoluteFillObject`, and `StyleSheet.hairlineWidth`.
* `Platform.OS` and `Platform.select`. Inside a widget, `Platform.OS` is the platform the widget is being built for, so `Platform.select` picks the same branch at build time and on device.
Anything else imported from `react-native` — components, `Dimensions`, `Animated`, `PixelRatio` — is rejected with a message naming the symbol. Build steps that evaluate your widget (`voltra apply` and `expo prebuild`) fail outright; a symbol that only appears on a branch those steps never reach throws the same message when the widget renders, rather than reading as `undefined`. Deep imports such as `react-native/Libraries/...` always fail the build. Use the `Voltra` components for everything visual.
# Widget Pre-rendering
> Provide initial widget content at build time with initialStatePath so widgets show something before the app first syncs.
Widget pre-rendering allows you to provide meaningful initial state for widgets before they are synced when the app runs for the first time.
## Configuration
[Section titled “Configuration”](#configuration)
Add `initialStatePath` to your widget configuration in `app.json`:
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"widgets": [
{
"id": "weather",
"displayName": "Weather Widget",
"description": "Shows current weather conditions",
"supportedFamilies": ["systemSmall", "systemMedium", "systemLarge"],
"initialStatePath": "./widgets/weather-initial.tsx"
}
]
}
]
]
}
}
```
### Localized initial states
[Section titled “Localized initial states”](#localized-initial-states)
Use a locale map so the config plugin pre-renders one bundle per language; iOS and Android pick the best match at runtime from the device locale (fallback order: preferred languages → language-only → `en` → first locale):
```json
"initialStatePath": {
"en": "./widgets/weather-initial.tsx",
"pl": "./widgets/weather-initial-pl.tsx"
}
```
## Implementation
[Section titled “Implementation”](#implementation)
Create a file at each configured path that exports a `WidgetVariants` object (or use the same file path for multiple locales if copy is identical):
```tsx
import { Voltra, type WidgetVariants } from '@use-voltra/ios'
const initialState: WidgetVariants = {
systemSmall: Content,
systemMedium: Content,
systemLarge: Content,
}
export default initialState
```
Note
`initialStatePath` files are **not** part of your React Native app bundle. Voltra transpiles them with Babel and runs them in Node.js during prebuild to generate the initial states bundled into the iOS app. Import `Voltra` and types from `@use-voltra/ios`, not `@use-voltra/ios-client` — the client package pulls in native modules that are unavailable in the prebuild sandbox.
## Limitations
[Section titled “Limitations”](#limitations)
* **Node.js Environment**: Code runs in Node.js, not in React Native or iOS
* **Babel Support**: TypeScript is supported via Babel transpilation
* **No Bundling**: Import resolution works for local files but there is no bundler involved
* **Voltra Imports**: Use `@use-voltra/ios` for JSX and types in `initialStatePath` files. Do not import from `@use-voltra/ios-client` or other React Native client APIs.
# Introduction
> An example of building an iOS Live Activity with Voltra JSX components, which are converted to SwiftUI, and where to go next.
This page shows what building a Live Activity with Voltra looks like: you write JSX using Voltra components, and it gets converted to SwiftUI automatically.
```tsx
import { Voltra } from '@use-voltra/ios'
import { startLiveActivity } from '@use-voltra/ios-client'
const activityUI = (
Driver en routeBuilding A · Lobby pickupContact driver
)
// Start the live activity
await startLiveActivity({
lockScreen: activityUI,
})
```
If you prefer using the hook API (`useLiveActivity`), you’ll get live reloads for live activities, with changes appearing in milliseconds without manual restarts.
Voltra also supports updating Live Activities from your server via push notifications — see [Server-side updates](/ios/development/server-side-updates).
You’re ready to dive into the [setup guide](/ios/setup) and get started with live activities in your app.
# iOS Setup
> Configure the Voltra Expo plugin for iOS, regenerate the native project with prebuild, and create your first Live Activity.
Once you have [installed Voltra](/getting-started/installation), configure the iOS Expo plugin and use `@use-voltra/ios` for JSX.
Minimum iOS Version
Voltra requires **iOS 16.4 or later**. Make sure your app’s deployment target is set to iOS 16.4 or higher. See the [expo-build-properties](https://docs.expo.dev/build-reference/variables/) documentation for details on configuring your iOS deployment target.
## 1. Configure the Expo Plugin
[Section titled “1. Configure the Expo Plugin”](#1-configure-the-expo-plugin)
Add the iOS client plugin to your `app.json` or `app.config.js`. For iOS, you typically need to specify a `groupIdentifier` to enable data sharing between your main app and the Live Activity extension.
```json
{
"expo": {
"plugins": [
[
"@use-voltra/ios-client",
{
"groupIdentifier": "group.your.bundle.identifier",
"enablePushNotifications": true
}
]
]
}
}
```
For a complete list of plugin configuration options, see the [Plugin Configuration](/ios/api/plugin-configuration) documentation.
## 2. Regenerate your native project with Expo Prebuild
[Section titled “2. Regenerate your native project with Expo Prebuild”](#2-regenerate-your-native-project-with-expo-prebuild)
It’s time to update your native project. Run the following command to regenerate it and install native dependencies for Voltra.
* npm
```sh
npx expo prebuild --platform ios
```
* yarn
```sh
yarn dlx expo prebuild --platform ios
```
* pnpm
```sh
pnpm dlx expo prebuild --platform ios
```
* bun
```sh
bunx expo prebuild --platform ios
```
## 3. Create your first Live Activity
[Section titled “3. Create your first Live Activity”](#3-create-your-first-live-activity)
Now let’s create a simple “Hello World” live activity. Create a new component:
```tsx
import React from 'react'
import { View, TouchableOpacity, Text } from 'react-native'
import { Voltra } from '@use-voltra/ios'
import { startLiveActivity } from '@use-voltra/ios-client'
function HelloWorldActivity() {
const activityUI = (
Hello World from Voltra!Your first live activity
)
const startActivity = async () => {
await startLiveActivity({
lockScreen: activityUI,
})
}
return (
Start Live Activity
)
}
```