diff --git a/README.md b/README.md
index 9a369a8..51ad74e 100644
--- a/README.md
+++ b/README.md
@@ -15,6 +15,9 @@ These are the recipes and what they demonstrate.
- **[Debounce](app/src/main/java/com/example/appstaterecipes/debounce)**: Demonstrates how to debounce rapidly changing state (such as search queries) using `DebounceEffect` and `rememberDebounced`.
- **[Sample](app/src/main/java/com/example/appstaterecipes/sample)**: Demonstrates how to periodically sample high-frequency state streams (such as accelerometer sensor data) using `SampleEffect` and `rememberSampled`.
+#### UI surfaces & nested transforms
+- **[Glance Widget](app/src/main/java/com/example/appstaterecipes/glance)**: Demonstrates how to define a `transform` for a Jetpack Glance home-screen widget (`GlanceAppWidget`) and layer nested `transform` blocks across an app screen and widget with dynamic read tracking.
+
### Full-app recipes
Full-app recipes live under `apps/*` (such as `apps/browser/`). Each is an independent Android application module that can be launched directly via its own Android Studio Run Configuration (e.g. `apps.browser`) or deployed to a device and opened from the main Recipe Picker (`:app`). Shared architecture components (like `StateStoreOwner`, `StateStoreViewerActivity`, and common theming) are provided by the shared `:core` library module.
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 235e573..72f2f15 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -65,8 +65,12 @@ dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.appstate.transform)
+ implementation(libs.androidx.glance.appwidget)
+ implementation(libs.androidx.glance.material3)
implementation(libs.androidx.lifecycle.runtime.compose)
+ implementation(libs.androidx.lifecycle.viewmodel.compose)
testImplementation(libs.androidx.appstate.transform.testing)
+ testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.junit)
debugImplementation(libs.androidx.compose.ui.tooling)
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 61b79f9..f1a952f 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -55,6 +55,21 @@
+
+
+
+
+
+
+
+
diff --git a/app/src/main/java/com/example/appstaterecipes/RecipePickerActivity.kt b/app/src/main/java/com/example/appstaterecipes/RecipePickerActivity.kt
index ca7ad39..c9d05e8 100644
--- a/app/src/main/java/com/example/appstaterecipes/RecipePickerActivity.kt
+++ b/app/src/main/java/com/example/appstaterecipes/RecipePickerActivity.kt
@@ -68,6 +68,7 @@ import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
import com.example.appstaterecipes.debounce.DebounceActivity
+import com.example.appstaterecipes.glance.GlanceActivity
import com.example.appstaterecipes.sample.SampleActivity
import com.example.appstaterecipes.ui.excludeBottom
import com.example.appstaterecipes.ui.onlyBottom
@@ -105,6 +106,12 @@ private val recipes = listOf(
description = "Throttles high-frequency streams into a fixed periodic cadence (e.g. sensor readings).",
target = RecipeTarget.InternalActivity(SampleActivity::class.java),
),
+ Heading("Transform — UI Surfaces & Nested Transforms"),
+ Recipe(
+ name = "Glance Widget",
+ description = "Derives state for a Jetpack Glance home-screen widget and layers nested transforms across surfaces.",
+ target = RecipeTarget.InternalActivity(GlanceActivity::class.java),
+ ),
Heading("StateStore — Multi-Window Navigation"),
Recipe(
name = "Browser Multi-Window Navigation",
diff --git a/app/src/main/java/com/example/appstaterecipes/glance/FocusGraph.kt b/app/src/main/java/com/example/appstaterecipes/glance/FocusGraph.kt
new file mode 100644
index 0000000..99122e1
--- /dev/null
+++ b/app/src/main/java/com/example/appstaterecipes/glance/FocusGraph.kt
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2026 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.appstaterecipes.glance
+
+import android.content.Context
+import androidx.appstate.transform.listener
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.glance.appwidget.GlanceAppWidgetManager
+import androidx.glance.appwidget.updateAll
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+internal val sampleFocusTasks = listOf(
+ FocusTask(
+ id = "write-ads-talk",
+ title = "Write the ADS talk",
+ durationMinutes = 25,
+ ),
+ FocusTask(
+ id = "reply-design-doc",
+ title = "Reply to design doc comments",
+ durationMinutes = 15,
+ ),
+ FocusTask(
+ id = "plan-q1-roadmap",
+ title = "Plan Q1 roadmap",
+ durationMinutes = 25,
+ ),
+)
+
+class InMemoryTaskRepository(
+ initialTasks: List = sampleFocusTasks,
+ initialCompletedToday: Int = 0,
+) : TaskRepository {
+ private val _tasksFlow = MutableStateFlow(initialTasks)
+ override val tasksFlow: StateFlow> = _tasksFlow.asStateFlow()
+
+ private val _completedTodayFlow = MutableStateFlow(initialCompletedToday)
+ override val completedTodayFlow: StateFlow = _completedTodayFlow.asStateFlow()
+
+ override fun recordCompletedSession() {
+ _completedTodayFlow.update { it + 1 }
+ }
+}
+
+/**
+ * Process-scoped holder shared between [GlanceActivity] and [FocusWidget].
+ *
+ * Uses [listener] from `androidx.appstate.transform` to wake any placed [FocusWidget] instances
+ * via [FocusWidget.updateAll] when state changes outside an active Glance worker session.
+ * Note that `updateAll` does not restart `provideGlance` if a Glance session is already running.
+ */
+internal class FocusContainer(appContext: Context) {
+ private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ val taskRepository = InMemoryTaskRepository()
+ val focusManager = FocusSessionManager(
+ taskRepository = taskRepository,
+ scope = appScope,
+ )
+
+ val defaultTask: FocusTask
+ get() = taskRepository.tasksFlow.value.first()
+
+ init {
+ appScope.launch {
+ listener {
+ val summary by focusManager.summary
+ val completedToday by taskRepository.completedTodayFlow.collectAsState()
+
+ LaunchedEffect(summary, completedToday) {
+ val glanceIds = GlanceAppWidgetManager(appContext)
+ .getGlanceIds(FocusWidget::class.java)
+ if (glanceIds.isNotEmpty()) {
+ FocusWidget().updateAll(appContext)
+ }
+ }
+ }
+ }
+ }
+
+ companion object {
+ @Volatile
+ private var instance: FocusContainer? = null
+
+ fun get(context: Context): FocusContainer {
+ return instance ?: synchronized(this) {
+ instance ?: FocusContainer(context.applicationContext).also { instance = it }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/example/appstaterecipes/glance/FocusWidget.kt b/app/src/main/java/com/example/appstaterecipes/glance/FocusWidget.kt
new file mode 100644
index 0000000..d46513f
--- /dev/null
+++ b/app/src/main/java/com/example/appstaterecipes/glance/FocusWidget.kt
@@ -0,0 +1,214 @@
+/*
+ * Copyright 2026 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.appstaterecipes.glance
+
+import android.content.Context
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.glance.GlanceId
+import androidx.glance.GlanceModifier
+import androidx.glance.GlanceTheme
+import androidx.glance.action.ActionParameters
+import androidx.glance.action.actionStartActivity
+import androidx.glance.action.clickable
+import androidx.glance.appwidget.GlanceAppWidget
+import androidx.glance.appwidget.GlanceAppWidgetReceiver
+import androidx.glance.appwidget.LinearProgressIndicator
+import androidx.glance.appwidget.action.ActionCallback
+import androidx.glance.appwidget.action.actionRunCallback
+import androidx.glance.appwidget.components.FilledButton
+import androidx.glance.appwidget.components.OutlineButton
+import androidx.glance.appwidget.components.Scaffold
+import androidx.glance.appwidget.provideContent
+import androidx.glance.layout.Alignment
+import androidx.glance.layout.Column
+import androidx.glance.layout.Row
+import androidx.glance.layout.Spacer
+import androidx.glance.layout.fillMaxSize
+import androidx.glance.layout.fillMaxWidth
+import androidx.glance.layout.height
+import androidx.glance.layout.padding
+import androidx.glance.layout.width
+import androidx.glance.text.FontWeight
+import androidx.glance.text.Text
+import androidx.glance.text.TextStyle
+import kotlinx.coroutines.coroutineScope
+
+// [START glance_provide_glance]
+class FocusWidget : GlanceAppWidget() {
+
+ override suspend fun provideGlance(context: Context, id: GlanceId) {
+ val container = FocusContainer.get(context)
+ coroutineScope {
+ val widgetState = focusWidgetTransform(
+ summaryState = container.focusManager.summary,
+ completedTodayFlow = container.taskRepository.completedTodayFlow,
+ scope = this,
+ )
+ provideContent {
+ val uiState by widgetState
+ GlanceTheme {
+ FocusWidgetContent(uiState = uiState)
+ }
+ }
+ }
+ }
+ // [END glance_provide_glance]
+
+ override suspend fun providePreview(context: Context, widgetCategory: Int) {
+ val previewState = FocusWidgetUiState(
+ statusLabel = "Focusing",
+ taskTitle = "Write the ADS talk",
+ formattedTime = "24:55",
+ progress = 0.2f,
+ primaryAction = WidgetPrimaryAction.Pause,
+ isSessionActive = true,
+ completedToday = 1,
+ )
+ provideContent {
+ GlanceTheme {
+ FocusWidgetContent(uiState = previewState)
+ }
+ }
+ }
+}
+
+class FocusWidgetReceiver : GlanceAppWidgetReceiver() {
+ override val glanceAppWidget: GlanceAppWidget = FocusWidget()
+}
+
+class FocusWidgetPrimaryActionCallback : ActionCallback {
+ override suspend fun onAction(
+ context: Context,
+ glanceId: GlanceId,
+ parameters: ActionParameters,
+ ) {
+ val container = FocusContainer.get(context)
+ container.focusManager.togglePrimaryAction(container.defaultTask)
+ }
+}
+
+class FocusWidgetStopActionCallback : ActionCallback {
+ override suspend fun onAction(
+ context: Context,
+ glanceId: GlanceId,
+ parameters: ActionParameters,
+ ) {
+ FocusContainer.get(context).focusManager.stopSession()
+ }
+}
+
+@Composable
+private fun FocusWidgetContent(uiState: FocusWidgetUiState) {
+ Scaffold(
+ backgroundColor = GlanceTheme.colors.widgetBackground,
+ modifier = GlanceModifier
+ .fillMaxSize()
+ .clickable(actionStartActivity()),
+ ) {
+ Column(
+ modifier = GlanceModifier
+ .fillMaxSize()
+ .padding(vertical = 12.dp),
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = GlanceModifier.fillMaxWidth(),
+ ) {
+ Text(
+ text = "FocusFlow",
+ style = TextStyle(
+ color = GlanceTheme.colors.onSurfaceVariant,
+ fontSize = 12.sp,
+ fontWeight = FontWeight.Medium,
+ ),
+ )
+ Spacer(modifier = GlanceModifier.defaultWeight())
+ Text(
+ text = "${uiState.completedToday} done today",
+ style = TextStyle(
+ color = GlanceTheme.colors.onSurfaceVariant,
+ fontSize = 12.sp,
+ ),
+ )
+ }
+
+ Spacer(modifier = GlanceModifier.height(6.dp))
+
+ val subtitle = uiState.taskTitle?.let { "${uiState.statusLabel} • $it" }
+ ?: uiState.statusLabel
+ Text(
+ text = subtitle,
+ maxLines = 1,
+ style = TextStyle(
+ color = GlanceTheme.colors.primary,
+ fontSize = 13.sp,
+ fontWeight = FontWeight.Medium,
+ ),
+ )
+
+ Spacer(modifier = GlanceModifier.defaultWeight())
+
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = GlanceModifier.fillMaxWidth(),
+ ) {
+ Text(
+ text = uiState.formattedTime,
+ style = TextStyle(
+ color = GlanceTheme.colors.onSurface,
+ fontSize = 28.sp,
+ fontWeight = FontWeight.Bold,
+ ),
+ )
+ Spacer(modifier = GlanceModifier.defaultWeight())
+
+ if (uiState.isSessionActive) {
+ OutlineButton(
+ text = "Stop",
+ contentColor = GlanceTheme.colors.onSurfaceVariant,
+ onClick = actionRunCallback(),
+ )
+ Spacer(modifier = GlanceModifier.width(6.dp))
+ }
+
+ val actionLabel = when (uiState.primaryAction) {
+ WidgetPrimaryAction.Start -> "Start"
+ WidgetPrimaryAction.Pause -> "Pause"
+ WidgetPrimaryAction.Resume -> "Resume"
+ }
+ FilledButton(
+ text = actionLabel,
+ onClick = actionRunCallback(),
+ )
+ }
+
+ Spacer(modifier = GlanceModifier.height(8.dp))
+
+ LinearProgressIndicator(
+ progress = uiState.progress,
+ color = GlanceTheme.colors.primary,
+ backgroundColor = GlanceTheme.colors.surfaceVariant,
+ modifier = GlanceModifier
+ .fillMaxWidth()
+ .height(6.dp),
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/com/example/appstaterecipes/glance/GlanceActivity.kt b/app/src/main/java/com/example/appstaterecipes/glance/GlanceActivity.kt
new file mode 100644
index 0000000..5c3f5f1
--- /dev/null
+++ b/app/src/main/java/com/example/appstaterecipes/glance/GlanceActivity.kt
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2026 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.appstaterecipes.glance
+
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.activity.viewModels
+import com.example.appstaterecipes.ui.theme.AppStateRecipesTheme
+
+class GlanceActivity : ComponentActivity() {
+ private val viewModel: GlanceViewModel by viewModels {
+ val container = FocusContainer.get(applicationContext)
+ GlanceViewModel.factory(
+ focusManager = container.focusManager,
+ taskRepository = container.taskRepository,
+ )
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ enableEdgeToEdge()
+ setContent {
+ AppStateRecipesTheme {
+ GlanceScreen(viewModel = viewModel)
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/example/appstaterecipes/glance/GlanceScreen.kt b/app/src/main/java/com/example/appstaterecipes/glance/GlanceScreen.kt
new file mode 100644
index 0000000..f8598f2
--- /dev/null
+++ b/app/src/main/java/com/example/appstaterecipes/glance/GlanceScreen.kt
@@ -0,0 +1,527 @@
+/*
+ * Copyright 2026 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.appstaterecipes.glance
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.FilledTonalButton
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.material3.TopAppBarDefaults
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.tooling.preview.Preview
+import androidx.compose.ui.unit.dp
+import androidx.glance.appwidget.GlanceAppWidgetManager
+import androidx.lifecycle.compose.LifecycleResumeEffect
+import com.example.appstaterecipes.ui.excludeBottom
+import com.example.appstaterecipes.ui.onlyBottom
+import com.example.appstaterecipes.ui.plus
+import com.example.appstaterecipes.ui.theme.AppStateRecipesTheme
+import kotlinx.coroutines.launch
+
+@Composable
+fun GlanceScreen(viewModel: GlanceViewModel) {
+ val context = LocalContext.current
+ val coroutineScope = rememberCoroutineScope()
+ val uiState by viewModel.uiState
+ var placedWidgetCount by remember { mutableIntStateOf(0) }
+
+ LifecycleResumeEffect(Unit) {
+ val job = coroutineScope.launch {
+ placedWidgetCount = GlanceAppWidgetManager(context)
+ .getGlanceIds(FocusWidget::class.java)
+ .size
+ }
+ onPauseOrDispose { job.cancel() }
+ }
+
+ GlanceScreenContent(
+ uiState = uiState,
+ placedWidgetCount = placedWidgetCount,
+ onPinWidgetClick = {
+ coroutineScope.launch {
+ GlanceAppWidgetManager(context).requestPinGlanceAppWidget(
+ receiver = FocusWidgetReceiver::class.java,
+ preview = FocusWidget(),
+ )
+ }
+ },
+ onStartTask = viewModel::startTask,
+ onPrimaryWidgetAction = viewModel::togglePauseOrStart,
+ onPauseSession = viewModel::pauseSession,
+ onResumeSession = viewModel::resumeSession,
+ onCompleteSession = viewModel::completeSession,
+ onStopSession = viewModel::stopSession,
+ onToggleMiniTimerExpanded = viewModel::toggleMiniTimerExpanded,
+ )
+}
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun GlanceScreenContent(
+ uiState: GlanceScreenUiState,
+ placedWidgetCount: Int,
+ onPinWidgetClick: () -> Unit,
+ onStartTask: (FocusTask) -> Unit,
+ onPrimaryWidgetAction: () -> Unit,
+ onPauseSession: () -> Unit,
+ onResumeSession: () -> Unit,
+ onCompleteSession: () -> Unit,
+ onStopSession: () -> Unit,
+ onToggleMiniTimerExpanded: () -> Unit,
+) {
+ val activeTaskId = (uiState.summary as? FocusSummary.Active)?.taskId
+
+ Scaffold(
+ modifier = Modifier.fillMaxSize(),
+ topBar = {
+ TopAppBar(
+ title = { Text("Glance Widget") },
+ colors = TopAppBarDefaults.topAppBarColors(
+ containerColor = MaterialTheme.colorScheme.primaryContainer,
+ titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
+ ),
+ )
+ },
+ bottomBar = {
+ val activeSummary = uiState.summary as? FocusSummary.Active
+ if (activeSummary != null) {
+ MiniTimerBottomBar(
+ summary = activeSummary,
+ isExpanded = uiState.isMiniTimerExpanded,
+ showControls = uiState.showMiniTimerControls,
+ onToggleExpanded = onToggleMiniTimerExpanded,
+ onPause = onPauseSession,
+ onResume = onResumeSession,
+ onComplete = onCompleteSession,
+ onStop = onStopSession,
+ )
+ }
+ },
+ ) { innerPadding ->
+ LazyColumn(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(innerPadding.excludeBottom()),
+ contentPadding = PaddingValues(16.dp) + innerPadding.onlyBottom(),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ item {
+ WidgetLauncherCard(
+ placedWidgetCount = placedWidgetCount,
+ onPinWidgetClick = onPinWidgetClick,
+ )
+ }
+
+ item {
+ Text(
+ text = "Derived FocusWidgetUiState (focusWidgetTransform)",
+ style = MaterialTheme.typography.titleSmall,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(top = 4.dp),
+ )
+ }
+
+ item {
+ WidgetStatePreviewCard(
+ widgetState = uiState.widgetPreviewState,
+ onPrimaryAction = onPrimaryWidgetAction,
+ onStop = onStopSession,
+ )
+ }
+
+ item {
+ Text(
+ text = "Focus Tasks",
+ style = MaterialTheme.typography.titleSmall,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(top = 4.dp),
+ )
+ }
+
+ items(uiState.tasks, key = { it.id }) { task ->
+ val isCurrentTask = activeTaskId == task.id
+ TaskRowCard(
+ task = task,
+ isActive = isCurrentTask,
+ onStartClick = { onStartTask(task) },
+ onCompleteClick = onCompleteSession,
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun WidgetLauncherCard(
+ placedWidgetCount: Int,
+ onPinWidgetClick: () -> Unit,
+) {
+ Card(
+ colors = CardDefaults.cardColors(
+ containerColor = MaterialTheme.colorScheme.surfaceContainerLow,
+ ),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Column(
+ modifier = Modifier.padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ val indicatorColor = if (placedWidgetCount > 0) {
+ MaterialTheme.colorScheme.primary
+ } else {
+ MaterialTheme.colorScheme.outline
+ }
+ Box(
+ modifier = Modifier
+ .size(8.dp)
+ .background(indicatorColor, CircleShape),
+ )
+ Spacer(modifier = Modifier.width(8.dp))
+ Text(
+ text = if (placedWidgetCount > 0) {
+ "Home-screen widget active ($placedWidgetCount placed)"
+ } else {
+ "Home-screen widget not placed yet"
+ },
+ style = MaterialTheme.typography.labelLarge,
+ fontWeight = FontWeight.SemiBold,
+ )
+ }
+ Text(
+ text = "Start, pause, or resume a focus session here or directly on the FocusFlow home-screen widget. Both surfaces observe the same shared FocusSessionManager.summary transform.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ FilledTonalButton(onClick = onPinWidgetClick) {
+ Text("Pin FocusFlow Widget")
+ }
+ }
+ }
+}
+
+@Composable
+private fun WidgetStatePreviewCard(
+ widgetState: FocusWidgetUiState,
+ onPrimaryAction: () -> Unit,
+ onStop: () -> Unit,
+) {
+ Card(
+ shape = RoundedCornerShape(20.dp),
+ colors = CardDefaults.cardColors(
+ containerColor = MaterialTheme.colorScheme.secondaryContainer,
+ ),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Column(
+ modifier = Modifier.padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Text(
+ text = "FocusFlow",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ )
+ Spacer(modifier = Modifier.weight(1f))
+ Text(
+ text = "${widgetState.completedToday} done today",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ )
+ }
+
+ val subtitle = widgetState.taskTitle?.let { "${widgetState.statusLabel} • $it" }
+ ?: widgetState.statusLabel
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodyMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = MaterialTheme.colorScheme.primary,
+ )
+
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Text(
+ text = widgetState.formattedTime,
+ style = MaterialTheme.typography.headlineMedium.copy(
+ fontFamily = FontFamily.Monospace,
+ fontWeight = FontWeight.Bold,
+ ),
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ )
+ Spacer(modifier = Modifier.weight(1f))
+
+ if (widgetState.isSessionActive) {
+ OutlinedButton(onClick = onStop) {
+ Text("Stop")
+ }
+ Spacer(modifier = Modifier.width(8.dp))
+ }
+
+ val actionLabel = when (widgetState.primaryAction) {
+ WidgetPrimaryAction.Start -> "Start"
+ WidgetPrimaryAction.Pause -> "Pause"
+ WidgetPrimaryAction.Resume -> "Resume"
+ }
+ Button(onClick = onPrimaryAction) {
+ Text(actionLabel)
+ }
+ }
+
+ LinearProgressIndicator(
+ progress = { widgetState.progress },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(6.dp),
+ )
+ }
+ }
+}
+
+@Composable
+private fun TaskRowCard(
+ task: FocusTask,
+ isActive: Boolean,
+ onStartClick: () -> Unit,
+ onCompleteClick: () -> Unit,
+) {
+ Card(
+ colors = CardDefaults.cardColors(
+ containerColor = if (isActive) {
+ MaterialTheme.colorScheme.primaryContainer
+ } else {
+ MaterialTheme.colorScheme.surfaceVariant
+ },
+ ),
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 12.dp),
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(
+ text = task.title,
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = FontWeight.Medium,
+ )
+ Text(
+ text = "${task.durationMinutes} min focus block",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ Spacer(modifier = Modifier.width(12.dp))
+ if (isActive) {
+ FilledTonalButton(onClick = onCompleteClick) {
+ Text("Done")
+ }
+ } else {
+ Button(onClick = onStartClick) {
+ Text("Start")
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun MiniTimerBottomBar(
+ summary: FocusSummary.Active,
+ isExpanded: Boolean,
+ showControls: Boolean,
+ onToggleExpanded: () -> Unit,
+ onPause: () -> Unit,
+ onResume: () -> Unit,
+ onComplete: () -> Unit,
+ onStop: () -> Unit,
+) {
+ Surface(
+ tonalElevation = 4.dp,
+ shadowElevation = 4.dp,
+ color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .navigationBarsPadding()
+ .padding(horizontal = 16.dp, vertical = 10.dp),
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(
+ text = if (summary.isPaused) {
+ "Focusing · paused — ${summary.taskTitle}"
+ } else {
+ "Focusing — ${summary.taskTitle}"
+ },
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ Text(
+ text = formatDurationSeconds(summary.remainingSeconds),
+ style = MaterialTheme.typography.titleLarge.copy(
+ fontFamily = FontFamily.Monospace,
+ fontWeight = FontWeight.Bold,
+ ),
+ )
+ }
+ TextButton(onClick = onToggleExpanded) {
+ Text(if (isExpanded) "Less" else "More")
+ }
+ }
+
+ AnimatedVisibility(visible = showControls) {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(top = 8.dp),
+ ) {
+ if (summary.isPaused) {
+ Button(onClick = onResume) {
+ Text("Resume")
+ }
+ } else {
+ Button(onClick = onPause) {
+ Text("Pause")
+ }
+ }
+ FilledTonalButton(onClick = onComplete) {
+ Text("Complete")
+ }
+ OutlinedButton(onClick = onStop) {
+ Text("Stop")
+ }
+ }
+ }
+ }
+ }
+}
+
+@Preview(showBackground = true)
+@Composable
+private fun GlanceScreenActivePreview() {
+ val activeSummary = FocusSummary.Active(
+ taskId = "write-ads-talk",
+ taskTitle = "Write the ADS talk",
+ isPaused = false,
+ remainingSeconds = 24 * 60 + 55,
+ totalSeconds = 25 * 60,
+ )
+ AppStateRecipesTheme {
+ GlanceScreenContent(
+ uiState = GlanceScreenUiState(
+ tasks = sampleFocusTasks,
+ summary = activeSummary,
+ widgetPreviewState = FocusWidgetUiState(
+ statusLabel = "Focusing",
+ taskTitle = "Write the ADS talk",
+ formattedTime = "24:55",
+ progress = 0.01f,
+ primaryAction = WidgetPrimaryAction.Pause,
+ isSessionActive = true,
+ completedToday = 0,
+ ),
+ isMiniTimerExpanded = true,
+ showMiniTimerControls = true,
+ ),
+ placedWidgetCount = 1,
+ onPinWidgetClick = {},
+ onStartTask = {},
+ onPrimaryWidgetAction = {},
+ onPauseSession = {},
+ onResumeSession = {},
+ onCompleteSession = {},
+ onStopSession = {},
+ onToggleMiniTimerExpanded = {},
+ )
+ }
+}
+
+@Preview(showBackground = true)
+@Composable
+private fun GlanceScreenIdlePreview() {
+ AppStateRecipesTheme {
+ GlanceScreenContent(
+ uiState = GlanceScreenUiState(
+ tasks = sampleFocusTasks,
+ summary = FocusSummary.Idle,
+ widgetPreviewState = FocusWidgetUiState(),
+ ),
+ placedWidgetCount = 0,
+ onPinWidgetClick = {},
+ onStartTask = {},
+ onPrimaryWidgetAction = {},
+ onPauseSession = {},
+ onResumeSession = {},
+ onCompleteSession = {},
+ onStopSession = {},
+ onToggleMiniTimerExpanded = {},
+ )
+ }
+}
diff --git a/app/src/main/java/com/example/appstaterecipes/glance/GlanceTransform.kt b/app/src/main/java/com/example/appstaterecipes/glance/GlanceTransform.kt
new file mode 100644
index 0000000..8d9ed71
--- /dev/null
+++ b/app/src/main/java/com/example/appstaterecipes/glance/GlanceTransform.kt
@@ -0,0 +1,275 @@
+/*
+ * Copyright 2026 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.appstaterecipes.glance
+
+import androidx.appstate.transform.transform
+import androidx.compose.runtime.State
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+const val DEFAULT_FOCUS_DURATION_MINUTES = 25
+const val DEFAULT_FOCUS_DURATION_SECONDS = DEFAULT_FOCUS_DURATION_MINUTES * 60
+
+data class FocusTask(
+ val id: String,
+ val title: String,
+ val durationMinutes: Int = DEFAULT_FOCUS_DURATION_MINUTES,
+)
+
+enum class FocusPhase {
+ Idle,
+ Focusing,
+ Paused,
+}
+
+data class FocusSession(
+ val phase: FocusPhase = FocusPhase.Idle,
+ val activeTaskId: String? = null,
+ val remainingSeconds: Int = 0,
+ val totalSeconds: Int = DEFAULT_FOCUS_DURATION_SECONDS,
+)
+
+sealed interface FocusSummary {
+ data object Idle : FocusSummary
+
+ data class Active(
+ val taskId: String,
+ val taskTitle: String,
+ val isPaused: Boolean,
+ val remainingSeconds: Int,
+ val totalSeconds: Int,
+ ) : FocusSummary {
+ val progress: Float
+ get() {
+ val safeTotal = totalSeconds.coerceAtLeast(1)
+ val elapsed = (safeTotal - remainingSeconds).coerceIn(0, safeTotal)
+ return elapsed.toFloat() / safeTotal.toFloat()
+ }
+ }
+}
+
+enum class WidgetPrimaryAction {
+ Start,
+ Pause,
+ Resume,
+}
+
+data class FocusWidgetUiState(
+ val statusLabel: String = "Ready to focus",
+ val taskTitle: String? = null,
+ val formattedTime: String = formatDurationSeconds(DEFAULT_FOCUS_DURATION_SECONDS),
+ val progress: Float = 0f,
+ val primaryAction: WidgetPrimaryAction = WidgetPrimaryAction.Start,
+ val isSessionActive: Boolean = false,
+ val completedToday: Int = 0,
+)
+
+interface TaskRepository {
+ val tasksFlow: Flow>
+ val completedTodayFlow: Flow
+ fun recordCompletedSession()
+}
+
+// [START glance_shared_transform]
+/**
+ * Manages focus timer sessions and exposes a derived [FocusSummary] as Compose [State].
+ *
+ * When [FocusPhase.Idle], [summary] returns early before collecting [TaskRepository.tasksFlow],
+ * so `tasksFlow` is only subscribed while a session is active. ViewModels and Glance widgets can
+ * read [summary] directly or build nested [transform] blocks on top of it.
+ */
+class FocusSessionManager(
+ private val taskRepository: TaskRepository,
+ private val scope: CoroutineScope,
+ private val dispatcher: CoroutineDispatcher = Dispatchers.Default,
+) {
+ private val _sessionFlow = MutableStateFlow(FocusSession())
+ val sessionFlow: StateFlow = _sessionFlow.asStateFlow()
+
+ private var timerJob: Job? = null
+
+ val summary: State = transform(
+ initialValue = FocusSummary.Idle,
+ scope = scope,
+ dispatcher = dispatcher,
+ ) { previous ->
+ val session by sessionFlow.collectAsState()
+ if (session.phase == FocusPhase.Idle) {
+ return@transform FocusSummary.Idle
+ }
+
+ val tasks = taskRepository.tasksFlow.collectAsState(initial = null).value
+ ?: return@transform previous
+ val task = tasks.find { it.id == session.activeTaskId }
+
+ FocusSummary.Active(
+ taskId = session.activeTaskId.orEmpty(),
+ taskTitle = task?.title ?: "Focus session",
+ isPaused = session.phase == FocusPhase.Paused,
+ remainingSeconds = session.remainingSeconds,
+ totalSeconds = session.totalSeconds,
+ )
+ }
+ // [END glance_shared_transform]
+
+ @Synchronized
+ fun startSession(task: FocusTask) {
+ val durationSeconds = (task.durationMinutes * 60).coerceAtLeast(1)
+ _sessionFlow.value = FocusSession(
+ phase = FocusPhase.Focusing,
+ activeTaskId = task.id,
+ remainingSeconds = durationSeconds,
+ totalSeconds = durationSeconds,
+ )
+ startCountdownLoop()
+ }
+
+ @Synchronized
+ fun pauseSession() {
+ val current = _sessionFlow.value
+ if (current.phase != FocusPhase.Focusing) return
+ timerJob?.cancel()
+ timerJob = null
+ _sessionFlow.value = current.copy(phase = FocusPhase.Paused)
+ }
+
+ @Synchronized
+ fun resumeSession() {
+ val current = _sessionFlow.value
+ if (current.phase != FocusPhase.Paused) return
+ _sessionFlow.value = current.copy(phase = FocusPhase.Focusing)
+ startCountdownLoop()
+ }
+
+ @Synchronized
+ fun stopSession() {
+ timerJob?.cancel()
+ timerJob = null
+ _sessionFlow.value = FocusSession()
+ }
+
+ @Synchronized
+ fun completeSession() {
+ val current = _sessionFlow.value
+ if (current.phase == FocusPhase.Idle) return
+ timerJob?.cancel()
+ timerJob = null
+ _sessionFlow.value = FocusSession()
+ taskRepository.recordCompletedSession()
+ }
+
+ @Synchronized
+ fun togglePrimaryAction(defaultTask: FocusTask) {
+ when (_sessionFlow.value.phase) {
+ FocusPhase.Idle -> startSession(defaultTask)
+ FocusPhase.Focusing -> pauseSession()
+ FocusPhase.Paused -> resumeSession()
+ }
+ }
+
+ private fun startCountdownLoop() {
+ timerJob?.cancel()
+ timerJob = scope.launch(dispatcher) {
+ while (true) {
+ delay(1_000L)
+ var finished = false
+ _sessionFlow.update { current ->
+ if (current.phase != FocusPhase.Focusing) {
+ current
+ } else if (current.remainingSeconds <= 1) {
+ finished = true
+ FocusSession()
+ } else {
+ current.copy(remainingSeconds = current.remainingSeconds - 1)
+ }
+ }
+ if (finished) {
+ taskRepository.recordCompletedSession()
+ break
+ }
+ }
+ }
+ }
+}
+
+// [START glance_widget_transform]
+/**
+ * Derives [FocusWidgetUiState] for [FocusWidget] by combining [FocusSessionManager.summary] with
+ * [completedTodayFlow].
+ *
+ * Defining the widget's state in a [transform] runs the derivation on [dispatcher]
+ * (`Dispatchers.Default` by default) for the lifetime of [scope] and makes it unit-testable on the
+ * JVM with `transformTest`.
+ */
+fun focusWidgetTransform(
+ summaryState: State,
+ completedTodayFlow: Flow,
+ scope: CoroutineScope,
+ dispatcher: CoroutineDispatcher = Dispatchers.Default,
+): State = transform(
+ initialValue = FocusWidgetUiState(),
+ scope = scope,
+ dispatcher = dispatcher,
+) {
+ val summary by summaryState
+ val completedToday by completedTodayFlow.collectAsState(initial = 0)
+
+ when (val current = summary) {
+ FocusSummary.Idle -> FocusWidgetUiState(
+ statusLabel = "Ready to focus",
+ taskTitle = null,
+ formattedTime = formatDurationSeconds(DEFAULT_FOCUS_DURATION_SECONDS),
+ progress = 0f,
+ primaryAction = WidgetPrimaryAction.Start,
+ isSessionActive = false,
+ completedToday = completedToday,
+ )
+
+ is FocusSummary.Active -> FocusWidgetUiState(
+ statusLabel = if (current.isPaused) "Focusing · paused" else "Focusing",
+ taskTitle = current.taskTitle,
+ formattedTime = formatDurationSeconds(current.remainingSeconds),
+ progress = current.progress,
+ primaryAction = if (current.isPaused) {
+ WidgetPrimaryAction.Resume
+ } else {
+ WidgetPrimaryAction.Pause
+ },
+ isSessionActive = true,
+ completedToday = completedToday,
+ )
+ }
+}
+// [END glance_widget_transform]
+
+internal fun formatDurationSeconds(totalSeconds: Int): String {
+ val clamped = totalSeconds.coerceAtLeast(0)
+ val minutes = clamped / 60
+ val seconds = clamped % 60
+ return "${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}"
+}
diff --git a/app/src/main/java/com/example/appstaterecipes/glance/GlanceViewModel.kt b/app/src/main/java/com/example/appstaterecipes/glance/GlanceViewModel.kt
new file mode 100644
index 0000000..be9775f
--- /dev/null
+++ b/app/src/main/java/com/example/appstaterecipes/glance/GlanceViewModel.kt
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2026 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.appstaterecipes.glance
+
+import androidx.appstate.transform.transform
+import androidx.compose.runtime.State
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+
+data class GlanceScreenUiState(
+ val tasks: List = emptyList(),
+ val summary: FocusSummary = FocusSummary.Idle,
+ val widgetPreviewState: FocusWidgetUiState = FocusWidgetUiState(),
+ val isMiniTimerExpanded: Boolean = false,
+ val showMiniTimerControls: Boolean = false,
+)
+
+class GlanceViewModel(
+ private val focusManager: FocusSessionManager,
+ private val taskRepository: TaskRepository,
+ coroutineScope: CoroutineScope? = null,
+ dispatcher: CoroutineDispatcher = Dispatchers.Default,
+) : ViewModel() {
+
+ private val effectiveScope: CoroutineScope = coroutineScope ?: viewModelScope
+
+ var isMiniTimerExpanded by mutableStateOf(false)
+ private set
+
+ // [START glance_mini_timer_transform]
+ private val widgetPreviewState: State = focusWidgetTransform(
+ summaryState = focusManager.summary,
+ completedTodayFlow = taskRepository.completedTodayFlow,
+ scope = effectiveScope,
+ dispatcher = dispatcher,
+ )
+
+ val uiState: State = transform(
+ initialValue = GlanceScreenUiState(),
+ scope = effectiveScope,
+ dispatcher = dispatcher,
+ ) {
+ val summary by focusManager.summary
+ val widgetPreview by widgetPreviewState
+ val tasks by taskRepository.tasksFlow.collectAsState(initial = sampleFocusTasks)
+ val expanded = isMiniTimerExpanded
+
+ GlanceScreenUiState(
+ tasks = tasks,
+ summary = summary,
+ widgetPreviewState = widgetPreview,
+ isMiniTimerExpanded = expanded,
+ showMiniTimerControls = expanded && summary is FocusSummary.Active,
+ )
+ }
+ // [END glance_mini_timer_transform]
+
+ fun startTask(task: FocusTask) {
+ focusManager.startSession(task)
+ }
+
+ fun togglePauseOrStart() {
+ val defaultTask = uiState.value.tasks.firstOrNull() ?: sampleFocusTasks.first()
+ focusManager.togglePrimaryAction(defaultTask)
+ }
+
+ fun pauseSession() {
+ focusManager.pauseSession()
+ }
+
+ fun resumeSession() {
+ focusManager.resumeSession()
+ }
+
+ fun completeSession() {
+ focusManager.completeSession()
+ isMiniTimerExpanded = false
+ }
+
+ fun stopSession() {
+ focusManager.stopSession()
+ isMiniTimerExpanded = false
+ }
+
+ fun toggleMiniTimerExpanded() {
+ isMiniTimerExpanded = !isMiniTimerExpanded
+ }
+
+ companion object {
+ fun factory(
+ focusManager: FocusSessionManager,
+ taskRepository: TaskRepository,
+ ): ViewModelProvider.Factory = viewModelFactory {
+ initializer {
+ GlanceViewModel(
+ focusManager = focusManager,
+ taskRepository = taskRepository,
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/example/appstaterecipes/glance/README.md b/app/src/main/java/com/example/appstaterecipes/glance/README.md
new file mode 100644
index 0000000..7d8067c
--- /dev/null
+++ b/app/src/main/java/com/example/appstaterecipes/glance/README.md
@@ -0,0 +1,149 @@
+# Glance Widget Recipe (`transform` with `GlanceAppWidget` and Nested Transforms)
+
+This recipe demonstrates how to define a `transform` for a Jetpack Glance home-screen widget (`GlanceAppWidget`) and compose **nested `transform` blocks** across multiple UI surfaces:
+- **`FocusSessionManager.summary`**: A shared headless `transform` that combines a timer `StateFlow` and `TaskRepository.tasksFlow` into `State` using dynamic read tracking.
+- **`focusWidgetTransform`**: A widget-specific nested `transform` scoped to `FocusWidget.provideGlance` that combines `FocusSessionManager.summary` with `completedTodayFlow` into a UI-ready `State`.
+- **`GlanceViewModel.uiState`**: A companion screen nested `transform` that combines `FocusSessionManager.summary` with local screen state (`isMiniTimerExpanded`).
+
+```mermaid
+flowchart LR
+ Session["sessionFlow
StateFlow<FocusSession>"]
+ Tasks["tasksFlow
Flow<List<FocusTask>>"]
+ Completed["completedTodayFlow
Flow<Int>"]
+
+ Summary["FocusSessionManager.summary
transform → State<FocusSummary>"]
+ WidgetTx["focusWidgetTransform
transform → State<FocusWidgetUiState>"]
+ ScreenTx["GlanceViewModel.uiState
transform → State<GlanceScreenUiState>"]
+
+ Widget["FocusWidget
GlanceAppWidget.provideContent"]
+ Screen["GlanceScreen
Activity + Mini-Timer"]
+
+ Session & Tasks --> Summary
+ Summary & Completed --> WidgetTx --> Widget
+ Summary --> ScreenTx --> Screen
+ Widget -. "Start / Pause / Stop" .-> Session
+```
+
+---
+
+## Comparing `transform` vs. `Flow.combine` + `stateIn` for Glance Widgets
+
+Both approaches derive state for an in-app screen and a home-screen `GlanceAppWidget`, but they differ in subscription behavior, boilerplate, and how Glance observes state.
+
+### Side-by-Side Code
+
+```kotlin
+// Coroutine Flow approach
+class FocusSessionManager(
+ taskRepository: TaskRepository,
+ appScope: CoroutineScope,
+) {
+ val summary: StateFlow = combine(
+ sessionFlow,
+ taskRepository.tasksFlow,
+ ) { session, tasks ->
+ if (session.phase == FocusPhase.Idle) {
+ FocusSummary.Idle
+ } else {
+ val task = tasks.find { it.id == session.activeTaskId }
+ FocusSummary.Active(...)
+ }
+ }.stateIn(
+ scope = appScope,
+ started = SharingStarted.WhileSubscribed(5_000),
+ initialValue = FocusSummary.Idle,
+ )
+}
+
+class FocusWidget : GlanceAppWidget() {
+ override suspend fun provideGlance(context: Context, id: GlanceId) {
+ val container = FocusContainer.get(context)
+ provideContent {
+ val summary by container.focusManager.summary.collectAsState()
+ val completedToday by container.taskRepository.completedTodayFlow.collectAsState(0)
+ GlanceTheme {
+ FocusWidgetContent(summary = summary, completedToday = completedToday)
+ }
+ }
+ }
+}
+```
+
+```kotlin
+// AppState Transform approach
+class FocusSessionManager(
+ private val taskRepository: TaskRepository,
+ scope: CoroutineScope,
+) {
+ val summary: State = transform(
+ initialValue = FocusSummary.Idle,
+ scope = scope,
+ ) { previous ->
+ val session by sessionFlow.collectAsState()
+ if (session.phase == FocusPhase.Idle) {
+ return@transform FocusSummary.Idle
+ }
+ val tasks = taskRepository.tasksFlow.collectAsState(initial = null).value
+ ?: return@transform previous
+ val task = tasks.find { it.id == session.activeTaskId }
+ FocusSummary.Active(...)
+ }
+}
+
+class FocusWidget : GlanceAppWidget() {
+ override suspend fun provideGlance(context: Context, id: GlanceId) {
+ val container = FocusContainer.get(context)
+ coroutineScope {
+ val widgetState = focusWidgetTransform(
+ summaryState = container.focusManager.summary,
+ completedTodayFlow = container.taskRepository.completedTodayFlow,
+ scope = this,
+ )
+ provideContent {
+ val uiState by widgetState
+ GlanceTheme { FocusWidgetContent(uiState = uiState) }
+ }
+ }
+ }
+}
+```
+
+---
+
+### Direct Differences
+
+#### 1. Direct `State` Reads in Glance `provideContent`
+- **`Flow.combine` + `stateIn`**: Exposes a `StateFlow` that each consumer (`FocusWidget.provideContent`, Compose screens, downstream ViewModels) must convert back into Compose state via `collectAsState()` or re-combine with `Flow.combine`.
+- **`transform`**: Produces a Compose `State` directly. Because Jetpack Glance's `provideContent` runs a Compose runtime `Composition` backed by the snapshot system, reading `val uiState by widgetState` registers snapshot tracking automatically and recomposes the widget's `RemoteViews` whenever `uiState` changes.
+
+#### 2. Dynamic Upstream Subscription (`return@transform` While Idle)
+- **`Flow.combine`**: Unconditionally subscribes to *all* upstream flows (`sessionFlow` and `tasksFlow`) as soon as a collector subscribes, even when `session.phase == FocusPhase.Idle` and the task list is unused.
+- **`transform`**: Tracks dependencies dynamically per execution path. Returning early when `session.phase == FocusPhase.Idle` skips `tasksFlow.collectAsState(...)`, so `tasksFlow` has zero active collectors until a focus session starts—and is automatically cancelled when the session returns to `Idle`.
+
+#### 3. Nested Transforms Across Surfaces
+- Instead of duplicating `combine(sessionFlow, tasksFlow)` across the Activity `ViewModel`, mini-timer, and `FocusWidget`, `FocusSessionManager.summary` computes `State` once.
+- Each surface layers a lightweight nested `transform` for its own UI concerns:
+ - **`focusWidgetTransform`**: Combines `summary` with `completedTodayFlow` and formats labels, progress, and button actions into `FocusWidgetUiState` off the main thread (`Dispatchers.Default`).
+ - **`GlanceViewModel.uiState`**: Combines `summary` with `isMiniTimerExpanded` to compute `showMiniTimerControls = expanded && summary is FocusSummary.Active`.
+
+#### 4. Scoping to `provideGlance` and Waking Idle Widget Sessions
+- **`coroutineScope` inside `provideGlance`**: Passing `scope = this` inside `coroutineScope { ... provideContent { ... } }` ties `focusWidgetTransform` to the exact lifetime of the active Glance worker session. When Glance closes the session (~45 seconds after interaction stops), `coroutineScope` cancels and disposes the headless composition cleanly.
+- **Waking idle widgets with `listener` + `updateAll`**: While a Glance session is active, snapshot reads in `provideContent` update the widget automatically. When a state change originates from the app while no Glance worker session is running, `FocusContainer` uses `androidx.appstate.transform.listener` to call `FocusWidget().updateAll(appContext)` if any widget is placed on the home screen. (`updateAll` wakes an idle session without restarting an already-running `provideGlance` session.)
+
+#### 5. Pure JVM Unit Testing with `transformTest`
+- Putting stream collection and state derivation directly inside `GlanceAppWidget.provideContent` couples widget business logic to Glance's `AppWidgetSession` runtime.
+- Defining the widget's state producer as `focusWidgetTransform(...)` allows testing every widget state transition (`Idle`, `Focusing`, `Paused`, countdown ticks, and `completedToday` updates) deterministically on the JVM using `transformTest`, `backgroundScope`, and `testDispatcher`—with no Robolectric or `AppWidgetHost` setup.
+
+---
+
+## How It Works
+
+1. **`FocusSessionManager`** ([`GlanceTransform.kt`](GlanceTransform.kt)):
+ - Runs the countdown loop and exposes `summary: State` via `transform`, dynamically collecting `TaskRepository.tasksFlow` only during active/paused sessions.
+2. **`focusWidgetTransform`** ([`GlanceTransform.kt`](GlanceTransform.kt)):
+ - Reads `summaryState` and collects `completedTodayFlow` inside a nested `transform` to produce `State`.
+3. **`FocusWidget` & `ActionCallback`s** ([`FocusWidget.kt`](FocusWidget.kt)):
+ - `FocusWidget.provideGlance` scopes `focusWidgetTransform` to `coroutineScope` and renders `FocusWidgetUiState` with Glance Material 3 components (`Scaffold`, `FilledButton`, `OutlineButton`, `LinearProgressIndicator`).
+ - Tapping **Start / Pause / Resume** or **Stop** on the home-screen widget runs `FocusWidgetPrimaryActionCallback` / `FocusWidgetStopActionCallback`, mutating `FocusSessionManager` so both the widget and any open Activity screen stay synchronized.
+4. **`FocusContainer`** ([`FocusGraph.kt`](FocusGraph.kt)):
+ - Shares `FocusSessionManager` and `InMemoryTaskRepository` across `GlanceActivity` and `FocusWidget` in-process, and uses `listener` to trigger `FocusWidget().updateAll(appContext)` when state changes while widgets are placed.
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index a54ae46..d651a97 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -17,4 +17,5 @@
AppState Recipes
+ Track and control active focus sessions on your home screen.
\ No newline at end of file
diff --git a/app/src/main/res/xml/focus_widget_info.xml b/app/src/main/res/xml/focus_widget_info.xml
new file mode 100644
index 0000000..df04246
--- /dev/null
+++ b/app/src/main/res/xml/focus_widget_info.xml
@@ -0,0 +1,29 @@
+
+
+
+
diff --git a/app/src/test/java/com/example/appstaterecipes/glance/GlanceTransformTest.kt b/app/src/test/java/com/example/appstaterecipes/glance/GlanceTransformTest.kt
new file mode 100644
index 0000000..ecd62e3
--- /dev/null
+++ b/app/src/test/java/com/example/appstaterecipes/glance/GlanceTransformTest.kt
@@ -0,0 +1,310 @@
+/*
+ * Copyright 2026 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.appstaterecipes.glance
+
+import androidx.appstate.transform.testing.TransformTestScope
+import androidx.appstate.transform.testing.transformTest
+import androidx.appstate.transform.transform
+import java.util.concurrent.atomic.AtomicInteger
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.onCompletion
+import kotlinx.coroutines.flow.onStart
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class GlanceTransformTest {
+
+ @Test
+ fun focusSessionManager_idleDoesNotSubscribeToTasksFlow_dynamicReadTracking() = transformTest {
+ val activeTaskFlowCollectors = AtomicInteger(0)
+ val backingTasks = MutableStateFlow(sampleFocusTasks)
+ val countingTasksRepository = object : TaskRepository {
+ override val tasksFlow: Flow> = backingTasks
+ .onStart { activeTaskFlowCollectors.incrementAndGet() }
+ .onCompletion { activeTaskFlowCollectors.decrementAndGet() }
+ override val completedTodayFlow = MutableStateFlow(0)
+ override fun recordCompletedSession() {}
+ }
+
+ val manager = FocusSessionManager(
+ taskRepository = countingTasksRepository,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ advance()
+
+ // While Idle, early return skips tasksFlow.collectAsState() completely
+ assertEquals(FocusSummary.Idle, manager.summary.value)
+ assertEquals(0, activeTaskFlowCollectors.get())
+
+ // Starting a session enters the active branch and subscribes to tasksFlow
+ manager.startSession(sampleFocusTasks.first())
+ settle()
+
+ assertTrue(manager.summary.value is FocusSummary.Active)
+ assertEquals(1, activeTaskFlowCollectors.get())
+
+ // Stopping returns to Idle, disposing the tasksFlow collector automatically
+ manager.stopSession()
+ settle()
+
+ assertEquals(FocusSummary.Idle, manager.summary.value)
+ assertEquals(0, activeTaskFlowCollectors.get())
+ }
+
+ @Test
+ fun focusSessionManager_combinesSessionAndTaskTitle_andCompletesCountdown() = transformTest {
+ val repository = InMemoryTaskRepository(
+ initialTasks = listOf(
+ FocusTask(id = "task-1", title = "Write the ADS talk", durationMinutes = 1),
+ ),
+ )
+ val manager = FocusSessionManager(
+ taskRepository = repository,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ advance()
+
+ manager.startSession(FocusTask(id = "task-1", title = "Write the ADS talk", durationMinutes = 1))
+ settle()
+
+ val initialSummary = manager.summary.value as FocusSummary.Active
+ assertEquals("Write the ADS talk", initialSummary.taskTitle)
+ assertEquals(60, initialSummary.remainingSeconds)
+ assertFalse(initialSummary.isPaused)
+
+ // Advance 5 seconds: 55 seconds remaining (00:55)
+ advanceTimeBy(5.seconds)
+ settle()
+
+ val afterFiveSeconds = manager.summary.value as FocusSummary.Active
+ assertEquals(55, afterFiveSeconds.remainingSeconds)
+
+ // Advance remaining 55 seconds: session completes and increments completedToday
+ advanceTimeBy(55.seconds)
+ settle()
+
+ assertEquals(FocusSummary.Idle, manager.summary.value)
+ assertEquals(1, repository.completedTodayFlow.value)
+ }
+
+ @Test
+ fun focusSessionManager_pauseAndResumePreservesRemainingTime() = transformTest {
+ val repository = InMemoryTaskRepository()
+ val manager = FocusSessionManager(
+ taskRepository = repository,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ advance()
+
+ manager.startSession(sampleFocusTasks.first())
+ settle()
+
+ advanceTimeBy(5.seconds)
+ settle()
+ assertEquals(24 * 60 + 55, (manager.summary.value as FocusSummary.Active).remainingSeconds)
+
+ manager.pauseSession()
+ settle()
+
+ val paused = manager.summary.value as FocusSummary.Active
+ assertTrue(paused.isPaused)
+ assertEquals(24 * 60 + 55, paused.remainingSeconds)
+
+ // While paused, advancing virtual time does not decrement remainingSeconds
+ advanceTimeBy(30.seconds)
+ settle()
+ assertEquals(24 * 60 + 55, (manager.summary.value as FocusSummary.Active).remainingSeconds)
+
+ // Resuming continues countdown from 24:55
+ manager.resumeSession()
+ settle()
+ advanceTimeBy(5.seconds)
+ settle()
+
+ val resumed = manager.summary.value as FocusSummary.Active
+ assertFalse(resumed.isPaused)
+ assertEquals(24 * 60 + 50, resumed.remainingSeconds)
+ }
+
+ @Test
+ fun focusWidgetTransform_projectsIdleActivePausedAndCompletedWidgetUiState() = transformTest {
+ val repository = InMemoryTaskRepository()
+ val manager = FocusSessionManager(
+ taskRepository = repository,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ val widgetState = focusWidgetTransform(
+ summaryState = manager.summary,
+ completedTodayFlow = repository.completedTodayFlow,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ settle()
+
+ assertEquals(
+ FocusWidgetUiState(
+ statusLabel = "Ready to focus",
+ taskTitle = null,
+ formattedTime = "25:00",
+ progress = 0f,
+ primaryAction = WidgetPrimaryAction.Start,
+ isSessionActive = false,
+ completedToday = 0,
+ ),
+ widgetState.value,
+ )
+
+ manager.startSession(sampleFocusTasks.first())
+ settle()
+ advanceTimeBy(5.seconds)
+ settle()
+
+ assertEquals("Focusing", widgetState.value.statusLabel)
+ assertEquals("Write the ADS talk", widgetState.value.taskTitle)
+ assertEquals("24:55", widgetState.value.formattedTime)
+ assertEquals(WidgetPrimaryAction.Pause, widgetState.value.primaryAction)
+ assertTrue(widgetState.value.isSessionActive)
+
+ manager.togglePrimaryAction(sampleFocusTasks.first())
+ settle()
+
+ assertEquals("Focusing · paused", widgetState.value.statusLabel)
+ assertEquals("24:55", widgetState.value.formattedTime)
+ assertEquals(WidgetPrimaryAction.Resume, widgetState.value.primaryAction)
+
+ manager.completeSession()
+ settle()
+
+ assertEquals("Ready to focus", widgetState.value.statusLabel)
+ assertNull(widgetState.value.taskTitle)
+ assertEquals(WidgetPrimaryAction.Start, widgetState.value.primaryAction)
+ assertFalse(widgetState.value.isSessionActive)
+ assertEquals(1, widgetState.value.completedToday)
+ }
+
+ @Test
+ fun focusWidgetTransform_structuralEqualitySkipsRedundantWidgetRecompositions() = transformTest {
+ val mutableTasks = MutableStateFlow(sampleFocusTasks)
+ val repository = object : TaskRepository {
+ override val tasksFlow = mutableTasks
+ override val completedTodayFlow = MutableStateFlow(0)
+ override fun recordCompletedSession() {}
+ }
+ val manager = FocusSessionManager(
+ taskRepository = repository,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ val widgetState = focusWidgetTransform(
+ summaryState = manager.summary,
+ completedTodayFlow = repository.completedTodayFlow,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ settle()
+
+ manager.startSession(sampleFocusTasks.first())
+ settle()
+
+ var widgetContentRecompositions = 0
+ transform(
+ initialValue = Unit,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ ) {
+ widgetState.value
+ widgetContentRecompositions++
+ }
+ settle()
+ assertEquals(1, widgetContentRecompositions)
+
+ // Modify an unrelated inactive task in tasksFlow:
+ // Active task ("write-ads-talk") title is unchanged, so FocusSummary.Active and
+ // FocusWidgetUiState equal their previous values and Glance UI does not recompose.
+ mutableTasks.value = sampleFocusTasks.map { task ->
+ if (task.id == "plan-q1-roadmap") {
+ task.copy(title = "Plan Q2 roadmap")
+ } else {
+ task
+ }
+ }
+ settle()
+ assertEquals(1, widgetContentRecompositions)
+
+ // Renaming the active task DOES update FocusWidgetUiState and trigger recomposition
+ mutableTasks.value = sampleFocusTasks.map { task ->
+ if (task.id == "write-ads-talk") {
+ task.copy(title = "Rehearse the ADS talk")
+ } else {
+ task
+ }
+ }
+ settle()
+ assertEquals(2, widgetContentRecompositions)
+ assertEquals("Rehearse the ADS talk", widgetState.value.taskTitle)
+ }
+
+ @Test
+ fun glanceViewModel_nestedTransformCombinesSummaryAndMiniTimerExpansion() = transformTest {
+ val repository = InMemoryTaskRepository()
+ val manager = FocusSessionManager(
+ taskRepository = repository,
+ scope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ val viewModel = GlanceViewModel(
+ focusManager = manager,
+ taskRepository = repository,
+ coroutineScope = backgroundScope,
+ dispatcher = testDispatcher,
+ )
+ settle()
+
+ // Expanding while Idle keeps showMiniTimerControls = false
+ viewModel.toggleMiniTimerExpanded()
+ settle()
+ assertTrue(viewModel.uiState.value.isMiniTimerExpanded)
+ assertFalse(viewModel.uiState.value.showMiniTimerControls)
+
+ // Starting a session turns showMiniTimerControls = true
+ viewModel.startTask(sampleFocusTasks.first())
+ settle()
+ assertTrue(viewModel.uiState.value.showMiniTimerControls)
+
+ // Collapsing turns showMiniTimerControls = false while session stays Active
+ viewModel.toggleMiniTimerExpanded()
+ settle()
+ assertFalse(viewModel.uiState.value.showMiniTimerControls)
+ assertTrue(viewModel.uiState.value.summary is FocusSummary.Active)
+ }
+
+ /**
+ * Pumps nested/multi-stage Flow -> Snapshot -> Transform recompositions to quiescence.
+ */
+ private fun TransformTestScope.settle() {
+ repeat(3) { advance() }
+ }
+}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index c06d622..4791ebb 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -9,6 +9,7 @@ composeBom = "2026.09.00"
appstate = "1.0.0-alpha01"
appfunctions = "1.0.0-beta01"
+glance = "1.2.0"
espressoCore = "3.7.0"
wearCompose = "1.6.2"
archCoreTesting = "2.2.0"
@@ -49,6 +50,8 @@ androidx-compose-material-icons-core = { group = "androidx.compose.material", na
androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
androidx-appstate-transform = { module = "androidx.appstate.transform:transform", version.ref = "appstate" }
androidx-appstate-transform-testing = { module = "androidx.appstate.transform:transform-testing", version.ref = "appstate" }
+androidx-glance-appwidget = { module = "androidx.glance:glance-appwidget", version.ref = "glance" }
+androidx-glance-material3 = { module = "androidx.glance:glance-material3", version.ref = "glance" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycleRuntimeKtx" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleRuntimeKtx" }
androidx-lifecycle-viewmodel-navigation3 = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-navigation3", version.ref = "lifecycleRuntimeKtx" }