# Samples

Three complete widgets (a task list, a CI dashboard and a weather forecast), with their code and how they render on each platform.

Three widgets that go past the counter: clickable rows, a filter, weighted columns, colored
tiles, app images and a layout that changes with the size. The same Kotlin renders on every
platform; register them as shown in each platform page ([Windows](/docs/os/widgets/windows),
[macOS](/docs/os/widgets/macos), [iOS](/docs/os/widgets/ios), [Android](/docs/os/widgets/android)).

These samples come from `examples/widget-ios-demo` in the Nucleus repository, trimmed for reading.
Imports come from `dev.nucleusframework.widget`, plus `androidx.compose.runtime.Composable`.

## Task list

A list of tasks kept in the widget's state. Clicking a row toggles it through an
`ActionCallback` that receives the row index; the Large size adds a filter and a "Clear
completed" action.

- `actionRunCallback` with `actionParametersOf` passes the index of the clicked row.
- `ChoiceField(defaultValue = "all")` shows "All" as selected before the user picks anything.
- A badge is a `Column` with a semantic background, next to a `Text` with `weight(1)`.
- `LocalSize` decides how many rows fit and whether the filter is shown.

```kotlin
private val Tasks = stringStateKey("tasks") // "1Ship the widgets|0Review the PR", 1 = done
private val Filter = stringStateKey("filter")

private const val DefaultTasks = "1Ship the widgets|1Write the docs|0Review the PR|0Test on a device|0Publish 3.0"

private data class Task(val title: String, val done: Boolean)

private fun parse(raw: String?): List<Task> =
    (raw ?: DefaultTasks).split('|').filter { it.length > 1 }.map { Task(it.substring(1), it[0] == '1') }

private fun List<Task>.encode() = joinToString("|") { (if (it.done) "1" else "0") + it.title }

/** Flips the task at [Index], on the state of the widget that was clicked. */
object ToggleTask : ActionCallback {
    val Index = ActionParameters.Key<Int>("index")

    override suspend fun onAction(id: WidgetId, parameters: ActionParameters) {
        val index = parameters[Index] ?: return
        updateWidgetState(id) { state ->
            val tasks = parse(state[Tasks]).toMutableList()
            if (index in tasks.indices) tasks[index] = tasks[index].copy(done = !tasks[index].done)
            state[Tasks] = tasks.encode()
        }
    }
}

class TasksWidget : NucleusWidget() {
    override suspend fun provideWidget(id: WidgetId) {
        provideContent {
            val state = currentWidgetState()
            val tasks = parse(state[Tasks])
            val large = LocalSize.current == WidgetSize.Large
            // The filter is only shown on Large: a smaller size lists everything.
            val filter = if (large) state[Filter] else null
            val limit = if (large) 8 else 3
            val left = tasks.count { !it.done }
            val shown = tasks.withIndex().filter { (_, task) ->
                when (filter) {
                    "todo" -> !task.done
                    "done" -> task.done
                    else -> true
                }
            }

            Column(modifier = WidgetModifier.fillMaxSize(), spacing = Spacing.Small) {
                Row(
                    modifier = WidgetModifier.fillMaxWidth(),
                    verticalAlignment = Alignment.Vertical.CenterVertically,
                ) {
                    Text(
                        "Tasks",
                        modifier = WidgetModifier.weight(1),
                        style = TextStyle(fontSize = TextSize.Medium, fontWeight = FontWeight.Bold),
                    )
                    val badge = if (left == 0) WidgetBackground.Good else WidgetBackground.Accent
                    Column(modifier = WidgetModifier.background(badge)) {
                        Text(
                            if (left == 0) "All done" else "$left left",
                            style = TextStyle(fontSize = TextSize.Small, fontWeight = FontWeight.Bold),
                        )
                    }
                }
                if (large) {
                    ChoiceField(
                        Filter,
                        listOf(Choice("All", "all"), Choice("To do", "todo"), Choice("Done", "done")),
                        defaultValue = "all",
                    )
                }
                for ((index, task) in shown.take(limit)) {
                    Row(
                        modifier = WidgetModifier
                            .fillMaxWidth()
                            .clickable(actionRunCallback(ToggleTask, actionParametersOf(ToggleTask.Index to index))),
                        spacing = Spacing.Small,
                        verticalAlignment = Alignment.Vertical.CenterVertically,
                    ) {
                        Image(
                            ImageProvider.appResource(if (task.done) "widget/task-done.png" else "widget/task-open.png"),
                            contentDescription = if (task.done) "Done" else "To do",
                            size = ImageSize.Icon,
                        )
                        Text(
                            task.title,
                            modifier = WidgetModifier.weight(1),
                            style = TextStyle(color = if (task.done) WidgetColor.Subtle else WidgetColor.Default),
                            maxLines = 1,
                        )
                    }
                }
                if (shown.size > limit) {
                    Text(
                        "+ ${shown.size - limit} more",
                        style = TextStyle(fontSize = TextSize.Small, color = WidgetColor.Subtle),
                    )
                }
                Spacer(WidgetModifier.fillMaxHeight())
                if (large && tasks.any { it.done }) {
                    // A lambda click runs in place: no ActionCallback needed.
                    Row(modifier = WidgetModifier.clickable { state.update { it[Tasks] = tasks.filterNot(Task::done).encode() } }) {
                        Text("Clear completed", style = TextStyle(fontSize = TextSize.Small, color = WidgetColor.Accent))
                    }
                }
            }
        }
    }
}
```

<div style={{ display: "flex", flexWrap: "wrap", gap: 16, alignItems: "flex-start" }}>
<img src="/assets/docs/os/widgets/tasks-large-ios.png" alt="The task list widget, Large size, on the iOS home screen" width={290} height={295} />
<img src="/assets/docs/os/widgets/tasks-medium-ios.png" alt="The task list widget, Medium size, on the iOS home screen" width={290} height={137} />
</div>

<div style={{ display: "flex", flexWrap: "wrap", gap: 16, alignItems: "flex-start" }}>
<img src="/assets/docs/os/widgets/tasks-large-android.png" alt="The task list widget, Large size, on the Android home screen" width={290} height={363} />
<img src="/assets/docs/os/widgets/tasks-medium-android.png" alt="The task list widget, Medium size, on the Android home screen" width={290} height={181} />
</div>

## CI dashboard

Three tiles that share the width equally, each on a background that follows its value, a
Refresh button and, on the Large size, the latest runs.

- Siblings with `weight(1)` split the row evenly; a `Text` without weight keeps its natural width.
- `WidgetBackground` and `WidgetColor` are semantic: each host maps them to its own palette and
  to dark mode.
- `Button(onClick = { … })` and `actionOpenUrl` cover in-place updates and links.

```kotlin
private val Refreshes = intStateKey("refreshes")

class DashboardWidget : NucleusWidget() {
    override suspend fun provideWidget(id: WidgetId) {
        // Load real data here, before provideContent: the content itself is not suspending.
        provideContent {
            val state = currentWidgetState()
            val refreshes = state[Refreshes] ?: 0
            val builds = 128 + refreshes * 3
            val failing = (refreshes * 7) % 5
            val latency = 42 + (refreshes * 13) % 60

            Column(modifier = WidgetModifier.fillMaxSize(), spacing = Spacing.Small) {
                Row(
                    modifier = WidgetModifier.fillMaxWidth(),
                    verticalAlignment = Alignment.Vertical.CenterVertically,
                ) {
                    Image(ImageProvider.appResource("widget/logo.png"), contentDescription = "Logo", size = ImageSize.Icon)
                    Text("CI dashboard", modifier = WidgetModifier.weight(1), style = TextStyle(fontWeight = FontWeight.Bold))
                    Button("Refresh", onClick = { state.update { it[Refreshes] = refreshes + 1 } })
                }
                Row(modifier = WidgetModifier.fillMaxWidth(), spacing = Spacing.Small) {
                    Tile("Builds", "$builds", WidgetBackground.Good)
                    Tile("Failing", "$failing", if (failing == 0) WidgetBackground.Good else WidgetBackground.Attention)
                    Tile("p95 ms", "$latency", if (latency > 80) WidgetBackground.Warning else WidgetBackground.Emphasis)
                }
                if (LocalSize.current == WidgetSize.Large) {
                    Text("Recent runs", style = TextStyle(fontSize = TextSize.Small, color = WidgetColor.Subtle))
                    for (run in 0 until 4) {
                        val ok = (refreshes + run) % 4 != 0
                        Row(modifier = WidgetModifier.fillMaxWidth(), spacing = Spacing.Small) {
                            Text("●", style = TextStyle(color = if (ok) WidgetColor.Good else WidgetColor.Attention))
                            Text("preMerge #${builds - run}", modifier = WidgetModifier.weight(1), maxLines = 1)
                            Text("${3 + run}m", style = TextStyle(color = WidgetColor.Subtle))
                        }
                    }
                }
                Spacer(WidgetModifier.fillMaxHeight())
                Row(modifier = WidgetModifier.clickable(actionOpenUrl("https://github.com/NucleusFramework/Nucleus/actions"))) {
                    Text(
                        "Refreshed $refreshes times · open in GitHub",
                        style = TextStyle(fontSize = TextSize.Small, color = WidgetColor.Accent),
                    )
                }
            }
        }
    }
}

@Composable
private fun Tile(label: String, value: String, background: WidgetBackground) {
    Column(
        modifier = WidgetModifier.weight(1).background(background),
        spacing = Spacing.None,
        horizontalAlignment = Alignment.Horizontal.CenterHorizontally,
    ) {
        Text(value, style = TextStyle(fontSize = TextSize.Large, fontWeight = FontWeight.Bold))
        Text(label, style = TextStyle(fontSize = TextSize.Small, color = WidgetColor.Subtle), maxLines = 1)
    }
}
```

<div style={{ display: "flex", flexWrap: "wrap", gap: 16, alignItems: "flex-start" }}>
<img src="/assets/docs/os/widgets/dashboard-large-ios.png" alt="The CI dashboard widget, Large size, after one refresh, on the iOS home screen" width={290} height={295} />
<img src="/assets/docs/os/widgets/dashboard-medium-ios.png" alt="The CI dashboard widget, Medium size, on the iOS home screen" width={290} height={137} />
</div>

<div style={{ display: "flex", flexWrap: "wrap", gap: 16, alignItems: "flex-start" }}>
<img src="/assets/docs/os/widgets/dashboard-large-android.png" alt="The CI dashboard widget, Large size, after one refresh, on the Android home screen" width={290} height={363} />
<img src="/assets/docs/os/widgets/dashboard-medium-android.png" alt="The CI dashboard widget, Medium size, after one refresh, on the Android home screen" width={290} height={181} />
</div>

## Weather

One widget, three layouts: centered on Small, a five-day forecast on Medium, and a city choice on
Large.

- The forecast is a `Row` of five `Column`s with `weight(1)`, on an `Emphasis` background.
- The text color of each day follows its temperature (`Warning` when hot, `Accent` when freezing).
- The city is a `ChoiceField`: picking one writes the state key and the widget is drawn again.

```kotlin
private val City = stringStateKey("city")

private class Forecast(val temp: Int, val condition: String, val days: List<Pair<String, Int>>)

private val Cities = mapOf(
    "paris" to Forecast(14, "Cloudy", listOf("Mon" to 15, "Tue" to 12, "Wed" to 17, "Thu" to 18, "Fri" to 13)),
    "jerusalem" to Forecast(22, "Sunny", listOf("Mon" to 24, "Tue" to 25, "Wed" to 23, "Thu" to 21, "Fri" to 22)),
    "oslo" to Forecast(3, "Snow", listOf("Mon" to 1, "Tue" to -2, "Wed" to 0, "Thu" to 4, "Fri" to 2)),
)

class WeatherWidget : NucleusWidget() {
    override suspend fun provideWidget(id: WidgetId) {
        provideContent {
            val state = currentWidgetState()
            val city = state[City] ?: "paris"
            val forecast = Cities.getValue(city)
            val size = LocalSize.current
            val small = size == WidgetSize.Small

            Column(
                modifier = WidgetModifier.fillMaxSize(),
                spacing = Spacing.Small,
                horizontalAlignment = if (small) Alignment.Horizontal.CenterHorizontally else Alignment.Horizontal.Start,
            ) {
                Text(city.replaceFirstChar { it.uppercase() }, style = TextStyle(fontWeight = FontWeight.Bold))
                Row(spacing = Spacing.Medium, verticalAlignment = Alignment.Vertical.CenterVertically) {
                    Text("${forecast.temp}°", style = TextStyle(fontSize = TextSize.ExtraLarge, fontWeight = FontWeight.Light))
                    if (!small) {
                        Column(spacing = Spacing.None) {
                            Text(forecast.condition, style = TextStyle(fontSize = TextSize.Medium))
                            Text(
                                "H ${forecast.days.maxOf { it.second }}°  L ${forecast.days.minOf { it.second }}°",
                                style = TextStyle(fontSize = TextSize.Small, color = WidgetColor.Subtle),
                            )
                        }
                    }
                }
                if (small) {
                    Text(forecast.condition, style = TextStyle(fontSize = TextSize.Small, color = WidgetColor.Subtle))
                } else {
                    Spacer(WidgetModifier.fillMaxHeight())
                    Row(modifier = WidgetModifier.fillMaxWidth().background(WidgetBackground.Emphasis)) {
                        for ((day, temp) in forecast.days) {
                            Column(
                                modifier = WidgetModifier.weight(1),
                                spacing = Spacing.None,
                                horizontalAlignment = Alignment.Horizontal.CenterHorizontally,
                            ) {
                                Text(day, style = TextStyle(fontSize = TextSize.Small, color = WidgetColor.Subtle))
                                val color = when {
                                    temp >= 24 -> WidgetColor.Warning
                                    temp <= 0 -> WidgetColor.Accent
                                    else -> WidgetColor.Default
                                }
                                Text("$temp°", style = TextStyle(fontWeight = FontWeight.Bold, color = color))
                            }
                        }
                    }
                }
                if (size == WidgetSize.Large) {
                    ChoiceField(
                        City,
                        listOf(Choice("Paris", "paris"), Choice("Jerusalem", "jerusalem"), Choice("Oslo", "oslo")),
                        label = "City",
                        defaultValue = "paris",
                    )
                }
            }
        }
    }
}
```

<div style={{ display: "flex", flexWrap: "wrap", gap: 16, alignItems: "flex-start" }}>
<img src="/assets/docs/os/widgets/weather-small-ios.png" alt="The weather widget, Small size, on the iOS home screen" width={145} height={139} />
<img src="/assets/docs/os/widgets/weather-medium-ios.png" alt="The weather widget, Medium size, on the iOS home screen" width={290} height={137} />
<img src="/assets/docs/os/widgets/weather-large-ios.png" alt="The weather widget, Large size, with Jerusalem picked, on the iOS home screen" width={290} height={295} />
</div>

<div style={{ display: "flex", flexWrap: "wrap", gap: 16, alignItems: "flex-start" }}>
<img src="/assets/docs/os/widgets/weather-small-android.png" alt="The weather widget, Small size, on the Android home screen" width={145} height={181} />
<img src="/assets/docs/os/widgets/weather-medium-android.png" alt="The weather widget, Medium size, on the Android home screen" width={290} height={181} />
<img src="/assets/docs/os/widgets/weather-large-android.png" alt="The weather widget, Large size, with Jerusalem picked, on the Android home screen" width={290} height={363} />
</div>
