From 890565bce22382365809fbade2e08759c190ac6e Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 21 Oct 2026 20:48:05 -0700 Subject: [PATCH 01/14] Refactor ZoomBar component to match updated design specifications MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Redesign zoom controls with a unified stadium capsule track (56dp radius) and an animated sliding indicator pill (12dp radius). - Support both horizontal and vertical orientations via configurable parameter. - Implement label formatting (.5, 1×, 2, 5) with Unicode multiplication symbol on selected ratio. - Ensure buttons are flush with vertical sides in vertical view, with appropriate clearance in horizontal view. - Wrap zoom controls with OverlapAwareStyleProvider to dynamically toggle between 60% black (viewfinder overlap) and 20% white (outside viewfinder). - Preserve ZoomButtonRow as a backward-compatible delegate for external consumers. - Add ZoomBar unit tests and previews for both orientations and color themes. --- .../ui/components/capture/CaptureLayout.kt | 4 +- .../components/capture/ZoomBarComponents.kt | 569 +++++++++++++----- .../capture/ZoomBarComponentsTest.kt | 56 ++ 3 files changed, 493 insertions(+), 136 deletions(-) create mode 100644 ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt index 5b2483a22e..6d888c7689 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureLayout.kt @@ -249,7 +249,9 @@ private fun VerticalMaterialControls( elapsedTimeDisplay(Modifier) // zoom controls row - zoomControls(Modifier) + OverlapAwareStyleProvider { + zoomControls(Modifier) + } // capture button row Column { Row( diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index a04151f010..5f897b2687 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -15,33 +15,41 @@ */ package com.google.jetpackcamera.ui.components.capture -import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.animation.core.spring import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text -import androidx.compose.material3.ToggleButton -import androidx.compose.material3.ToggleButtonDefaults import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.semantics.testTag +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp @@ -50,143 +58,338 @@ import com.google.jetpackcamera.model.LensFacing import com.google.jetpackcamera.ui.uistate.capture.ZoomControlUiState import java.math.RoundingMode import java.text.DecimalFormat +import java.text.DecimalFormatSymbols +import java.util.Locale /** - * A composable that displays a row of zoom buttons. + * Styling configuration for [ZoomBar]. * - * @param onChangeZoom the callback for when the zoom changes - * @param modifier the modifier for this component - * @param zoomControlUiState the [ZoomControlUiState] for this component - * @param buttonSize the size of the buttons - * @param spacing the spacing between the buttons + * @param trackColor Background color of the stadium track capsule (e.g. 60% black over viewfinder, 20% white off viewfinder). + * @param selectedIndicatorColor Background color of the sliding indicator pill behind the active stop (e.g. primaryFixed / #EBE1CF). + * @param selectedContentColor Text color for the currently selected stop (e.g. onPrimaryFixed / #1C1B1F). + * @param unselectedContentColor Text color for unselected stops (e.g. Color.White). + */ +@Immutable +data class ZoomBarColors( + val trackColor: Color, + val selectedIndicatorColor: Color, + val selectedContentColor: Color, + val unselectedContentColor: Color +) + +/** + * Default color palettes and dimensions for [ZoomBar]. + */ +object ZoomBarDefaults { + val HorizontalItemWidth = 44.dp + val HorizontalItemHeight = 36.dp + val VerticalItemWidth = 40.dp + val VerticalItemHeight = 40.dp + val EndPadding = 4.dp + val HorizontalClearance = 4.dp + + val TrackShape = RoundedCornerShape(56.dp) + val IndicatorShape = RoundedCornerShape(12.dp) + + /** + * Default dynamic colors adapting to viewfinder overlap via [LocalCameraControlBackgroundStyle] + * and Material 3 theme color tokens. + */ + @Composable + fun colors( + trackColor: Color = LocalCameraControlBackgroundStyle.current.containerColor, + selectedIndicatorColor: Color = MaterialTheme.colorScheme.primaryFixed, + selectedContentColor: Color = MaterialTheme.colorScheme.onPrimaryFixed, + unselectedContentColor: Color = Color.White + ) = ZoomBarColors( + trackColor = trackColor, + selectedIndicatorColor = selectedIndicatorColor, + selectedContentColor = selectedContentColor, + unselectedContentColor = unselectedContentColor + ) + + /** + * Colors for overlapping the viewfinder (60% black background). + */ + fun black60Colors( + trackColor: Color = Color.Black.copy(alpha = 0.60f), + selectedIndicatorColor: Color = Color(0xFFEBE1CF), + selectedContentColor: Color = Color(0xFF1C1B1F), + unselectedContentColor: Color = Color.White + ) = ZoomBarColors( + trackColor = trackColor, + selectedIndicatorColor = selectedIndicatorColor, + selectedContentColor = selectedContentColor, + unselectedContentColor = unselectedContentColor + ) + + /** + * Colors when not overlapping the viewfinder (lighter translucent background). + */ + fun white20Colors( + trackColor: Color = Color.White.copy(alpha = 0.20f), + selectedIndicatorColor: Color = Color(0xFFEBE1CF), + selectedContentColor: Color = Color(0xFF1C1B1F), + unselectedContentColor: Color = Color.White + ) = ZoomBarColors( + trackColor = trackColor, + selectedIndicatorColor = selectedIndicatorColor, + selectedContentColor = selectedContentColor, + unselectedContentColor = unselectedContentColor + ) +} + +/** + * Formats zoom ratios for camera controls: + * - Unselected stops: ".5", "1", "2", "5" (no leading zero, no multiplication symbol). + * - Selected stop: ".5×", "1×", "2×", "5×" (with Unicode multiplication symbol \u00D7). + * - In-between ratios (e.g. while pinching): "1.4×". + */ +fun formatZoomLabel( + targetZoom: Float, + currentRatio: Float, + isSelected: Boolean +): String { + val valueToFormat = if (isSelected) currentRatio else targetZoom + val symbols = DecimalFormatSymbols(Locale.US) + val formattedNumber = if (valueToFormat < 1f && valueToFormat > 0f) { + val dec = DecimalFormat(".#", symbols).apply { + minimumIntegerDigits = 0 + roundingMode = RoundingMode.HALF_UP + } + dec.format(valueToFormat) + } else if (valueToFormat % 1.0f == 0f) { + valueToFormat.toInt().toString() + } else { + val dec = DecimalFormat("#.#", symbols).apply { + roundingMode = RoundingMode.HALF_UP + } + dec.format(valueToFormat) + } + return if (isSelected) { + "$formattedNumber\u00D7" + } else { + formattedNumber + } +} + +/** + * A composable that displays zoom controls formatted as a unified capsule track + * with a sliding selected indicator pill. + * + * @param zoomControlUiState The [ZoomControlUiState] providing available zoom levels and current ratio. + * @param onChangeZoom Callback when a zoom level is tapped. + * @param modifier Modifier for the component. + * @param orientation Layout orientation ([Orientation.Horizontal] or [Orientation.Vertical]), + * allowing flexible placement across portrait phones, landscape mode, and open foldables/tablets. + * @param colors Styling configuration for track and indicator colors. */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -fun ZoomButtonRow( +fun ZoomBar( + zoomControlUiState: ZoomControlUiState, onChangeZoom: (Float) -> Unit, modifier: Modifier = Modifier, - zoomControlUiState: ZoomControlUiState, - buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, - spacing: Dp = 16.dp + orientation: Orientation = Orientation.Horizontal, + colors: ZoomBarColors = ZoomBarDefaults.colors() ) { if (zoomControlUiState is ZoomControlUiState.Enabled) { val currentZoomState by rememberUpdatedState(zoomControlUiState) val selectedOptionIndex: Int by remember(zoomControlUiState.primaryLensFacing) { - // todo(kc): checkValue will flash to 1.0 when flipping between camera lenses on API 30+. + // checkValue will flash to 1.0 when flipping between camera lenses on API 30+. // cameraState (cameraState's zoom value) should have an intermediate, "unknown", state when // camera flip is in progress. Then we can ensure that the zoom controls don't flash to 1.0 // when cameraState is in this intermediate state. - derivedStateOf { - // if animating towards a value, then that option will be selected - // otherwise, select the closest option that is less than the current zoom ratio - val checkValue = currentZoomState.animatingToValue ?: currentZoomState.primaryZoomRatio ?: 1f if (checkValue >= 1f) { - // -1 if no index is found - currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> + val index = currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> checkValue >= zoomLevelOption } + if (index >= 0) index else 0 } else { 0 } } } - Row( + val zoomLevels = zoomControlUiState.zoomLevels + if (zoomLevels.isEmpty()) return + + val validIndex = selectedOptionIndex.coerceIn(0, zoomLevels.size - 1) + val currentRatio = currentZoomState.primaryZoomRatio ?: 1f + + val itemWidth = if (orientation == Orientation.Horizontal) { + ZoomBarDefaults.HorizontalItemWidth + } else { + ZoomBarDefaults.VerticalItemWidth + } + val itemHeight = if (orientation == Orientation.Horizontal) { + ZoomBarDefaults.HorizontalItemHeight + } else { + ZoomBarDefaults.VerticalItemHeight + } + + val animatedOffset by animateDpAsState( + targetValue = ZoomBarDefaults.EndPadding + (validIndex * if (orientation == Orientation.Horizontal) itemWidth.value else itemHeight.value).dp, + animationSpec = spring(stiffness = Spring.StiffnessMediumLow), + label = "zoomIndicatorOffset" + ) + + // In horizontal, clearance exists on all sides; in vertical, buttons are flush with the vertical sides. + val totalWidth = if (orientation == Orientation.Horizontal) { + itemWidth * zoomLevels.size + ZoomBarDefaults.EndPadding * 2 + } else { + itemWidth + } + val totalHeight = if (orientation == Orientation.Horizontal) { + itemHeight + ZoomBarDefaults.HorizontalClearance * 2 + } else { + itemHeight * zoomLevels.size + ZoomBarDefaults.EndPadding * 2 + } + + Box( modifier = modifier - .background( - color = Color.Black.copy(alpha = 0.32f), - shape = CircleShape - ) - .padding(horizontal = spacing / 2, vertical = spacing / 2) + .size(totalWidth, totalHeight) + .background(color = colors.trackColor, shape = ZoomBarDefaults.TrackShape) .semantics { testTag = ZOOM_BUTTON_ROW_TAG stateDescription = zoomControlUiState.primaryZoomRatio.toString() } - .height(buttonSize), - verticalAlignment = Alignment.CenterVertically ) { - zoomControlUiState.zoomLevels.forEachIndexed { index, value -> - Box( - modifier = Modifier.width(buttonSize + spacing + 8.dp), - contentAlignment = Alignment.Center - ) { - ZoomButton( - targetZoom = value, - zoomRatio = zoomControlUiState.primaryZoomRatio ?: 1f, - isSelected = selectedOptionIndex == index, - onChangeZoom = onChangeZoom + // Animated sliding indicator pill + val indicatorModifier = if (orientation == Orientation.Horizontal) { + Modifier + .offset(x = animatedOffset, y = ZoomBarDefaults.HorizontalClearance) + .size(itemWidth, itemHeight) + } else { + Modifier + .offset(x = 0.dp, y = animatedOffset) + .size(itemWidth, itemHeight) + } + Box( + modifier = indicatorModifier + .background( + color = colors.selectedIndicatorColor, + shape = ZoomBarDefaults.IndicatorShape ) + ) + + // Stops + if (orientation == Orientation.Horizontal) { + Row( + modifier = Modifier + .fillMaxSize() + .padding( + horizontal = ZoomBarDefaults.EndPadding, + vertical = ZoomBarDefaults.HorizontalClearance + ), + verticalAlignment = Alignment.CenterVertically + ) { + zoomLevels.forEachIndexed { index, value -> + ZoomBarItem( + value = value, + currentRatio = currentRatio, + isSelected = index == validIndex, + colors = colors, + modifier = Modifier.size(itemWidth, itemHeight), + onClick = { onChangeZoom(value) } + ) + } + } + } else { + Column( + modifier = Modifier + .fillMaxSize() + .padding(vertical = ZoomBarDefaults.EndPadding), + horizontalAlignment = Alignment.CenterHorizontally + ) { + zoomLevels.forEachIndexed { index, value -> + ZoomBarItem( + value = value, + currentRatio = currentRatio, + isSelected = index == validIndex, + colors = colors, + modifier = Modifier.size(itemWidth, itemHeight), + onClick = { onChangeZoom(value) } + ) + } } } } } } -@OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -private fun ZoomButton( +private fun ZoomBarItem( + value: Float, + currentRatio: Float, + isSelected: Boolean, + colors: ZoomBarColors, modifier: Modifier = Modifier, - buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, - targetZoom: Float, - zoomRatio: Float, - isSelected: Boolean = false, - onChangeZoom: (Float) -> Unit + onClick: () -> Unit ) { - val selectedFormat = remember { DecimalFormat("#.0") } - val formatter = remember(targetZoom) { - DecimalFormat("#.#").apply { - minimumIntegerDigits = 0 - roundingMode = if (targetZoom >= 1) { - RoundingMode.DOWN - } else { - RoundingMode.UP - } - } - } - val displayText by remember(isSelected, zoomRatio) { - derivedStateOf { - if (!isSelected) { - formatter.format(targetZoom) - } else { - "${selectedFormat.format(zoomRatio)}x" - } - } + val displayText = remember(value, currentRatio, isSelected) { + formatZoomLabel(targetZoom = value, currentRatio = currentRatio, isSelected = isSelected) } - ToggleButton( - checked = isSelected, - onCheckedChange = { onChangeZoom(targetZoom) }, - modifier = modifier.heightIn(buttonSize) + + Box( + modifier = modifier + .clip(ZoomBarDefaults.IndicatorShape) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + onClick = onClick + ) .semantics { - testTag = getZoomButtonTestTag(targetZoom) - // todo(kc): move to text resource + testTag = getZoomButtonTestTag(value) contentDescription = if (isSelected) "selected" else "not selected" + selected = isSelected }, - shapes = ToggleButtonDefaults.shapesFor(buttonSize), - contentPadding = ButtonDefaults.contentPaddingFor(buttonSize), - colors = if (isSelected) { - ToggleButtonDefaults.colors( - containerColor = MaterialTheme.colorScheme.primaryFixed, - contentColor = MaterialTheme.colorScheme.onPrimaryFixed - ) - } else { - ToggleButtonDefaults.colors( - containerColor = Color.White.copy(alpha = .16f), - contentColor = Color.White - ) - } + contentAlignment = Alignment.Center ) { Text( - modifier = Modifier.animateContentSize(), text = displayText, - style = MaterialTheme.typography.labelSmall, - textAlign = TextAlign.Center + style = MaterialTheme.typography.labelMedium.copy( + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium + ), + color = if (isSelected) colors.selectedContentColor else colors.unselectedContentColor, + textAlign = TextAlign.Center, + maxLines = 1 ) } } +/** + * A composable that displays a row of zoom buttons. + * + * Maintained as a delegate to [ZoomBar] for backward compatibility with existing callers. + * + * @param onChangeZoom the callback for when the zoom changes + * @param modifier the modifier for this component + * @param zoomControlUiState the [ZoomControlUiState] for this component + * @param buttonSize the size of the buttons (retained for backward compatibility) + * @param spacing the spacing between the buttons (retained for backward compatibility) + * @param orientation the layout orientation ([Orientation.Horizontal] or [Orientation.Vertical]) + */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +fun ZoomButtonRow( + onChangeZoom: (Float) -> Unit, + modifier: Modifier = Modifier, + zoomControlUiState: ZoomControlUiState, + buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, + spacing: Dp = 16.dp, + orientation: Orientation = Orientation.Horizontal +) { + ZoomBar( + zoomControlUiState = zoomControlUiState, + onChangeZoom = onChangeZoom, + modifier = modifier, + orientation = orientation + ) +} + private fun getZoomButtonTestTag(buttonValue: Float): String { return if (buttonValue < 1 && buttonValue > 0) { ZOOM_BUTTON_MIN_TAG @@ -197,78 +400,174 @@ private fun getZoomButtonTestTag(buttonValue: Float): String { } else if (buttonValue == 5f) { ZOOM_BUTTON_5_TAG } else { - TODO("Zoom button with value $buttonValue needs a test tag") + "ZoomButton_${buttonValue}Tag" } } -@Preview(showBackground = true) +// --------------------------------------------------------------------------- +// Previews +// --------------------------------------------------------------------------- + +@Preview(name = "Horizontal 60% Black (Overlapping Viewfinder)", showBackground = true) @Composable -fun ZoomButtonPreview() { +fun ZoomBarHorizontalDarkPreview() { Box( - Modifier - .padding(16.dp) - .background(Color.DarkGray) + modifier = Modifier + .background(Color(0xFF2B2B2B)) .padding(16.dp), contentAlignment = Alignment.Center ) { - Row { - ZoomButton( - targetZoom = 1f, - onChangeZoom = {}, - isSelected = false, - zoomRatio = 2f - ) + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f + ), + onChangeZoom = {}, + orientation = Orientation.Horizontal, + colors = ZoomBarDefaults.black60Colors() + ) + } +} - ZoomButton( - targetZoom = 3f, - onChangeZoom = {}, - zoomRatio = 3.3f, - isSelected = true - ) - } +@Preview(name = "Horizontal 20% White (Not Overlapping Viewfinder)", showBackground = true) +@Composable +fun ZoomBarHorizontalTranslucentPreview() { + Box( + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), + contentAlignment = Alignment.Center + ) { + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f + ), + onChangeZoom = {}, + orientation = Orientation.Horizontal, + colors = ZoomBarDefaults.white20Colors() + ) } } -@Preview(showBackground = true) +@Preview(name = "Horizontal - Fraction (.5x Selected)", showBackground = true) @Composable -fun ZoomBarPreviewOneSelected() { - val sampleValues = listOf(0.5f, 1.0f, 2.0f, 5.0f) +fun ZoomBarHorizontalFractionPreview() { Box( - Modifier - .background(Color.DarkGray), + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), contentAlignment = Alignment.Center ) { - ZoomButtonRow( + ZoomBar( zoomControlUiState = ZoomControlUiState.Enabled( - sampleValues, - primaryLensFacing = LensFacing.FRONT, - primaryZoomRatio = 1f + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 0.5f ), - onChangeZoom = { - println("Clicked value: $it") - } + onChangeZoom = {}, + orientation = Orientation.Horizontal, + colors = ZoomBarDefaults.black60Colors() ) } } -@Preview(showBackground = true) +@Preview(name = "Vertical 60% Black - Flush Sides", showBackground = true) @Composable -fun ZoomBarPreviewFractionSelected() { - val sampleValues = listOf(0.5f, 1.0f, 2.0f, 5.0f, 25.0f) +fun ZoomBarVerticalDarkPreview() { Box( - Modifier - .background(Color.DarkGray), + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), contentAlignment = Alignment.Center ) { - ZoomButtonRow( + ZoomBar( zoomControlUiState = ZoomControlUiState.Enabled( - sampleValues, - primaryLensFacing = LensFacing.FRONT, - primaryZoomRatio = .6f + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f ), - onChangeZoom = { - println("Clicked value: $it") - } + onChangeZoom = {}, + orientation = Orientation.Vertical, + colors = ZoomBarDefaults.black60Colors() ) } } + +@Preview(name = "Vertical 20% White - Flush Sides", showBackground = true) +@Composable +fun ZoomBarVerticalTranslucentPreview() { + Box( + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), + contentAlignment = Alignment.Center + ) { + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f + ), + onChangeZoom = {}, + orientation = Orientation.Vertical, + colors = ZoomBarDefaults.white20Colors() + ) + } +} + +@Preview(name = "Single Value Range (1.0x only)", showBackground = true) +@Composable +fun ZoomBarSingleValuePreview() { + Box( + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), + contentAlignment = Alignment.Center + ) { + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(1.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 1.0f + ), + onChangeZoom = {}, + orientation = Orientation.Horizontal + ) + } +} + +@Preview(name = "Extended Telephoto Range (2x Selected)", showBackground = true) +@Composable +fun ZoomBarExtendedRangePreview() { + Box( + modifier = Modifier + .background(Color(0xFF2B2B2B)) + .padding(16.dp), + contentAlignment = Alignment.Center + ) { + ZoomBar( + zoomControlUiState = ZoomControlUiState.Enabled( + zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f, 10.0f), + primaryLensFacing = LensFacing.BACK, + primaryZoomRatio = 2.0f + ), + onChangeZoom = {}, + orientation = Orientation.Horizontal + ) + } +} + +@Preview(name = "Legacy Delegate - One Selected", showBackground = true) +@Composable +fun ZoomBarPreviewOneSelected() { + ZoomBarHorizontalDarkPreview() +} + +@Preview(name = "Legacy Delegate - Fraction Selected", showBackground = true) +@Composable +fun ZoomBarPreviewFractionSelected() { + ZoomBarHorizontalFractionPreview() +} diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt new file mode 100644 index 0000000000..da3fda4ce2 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt @@ -0,0 +1,56 @@ +/* + * Copyright (C) 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.google.jetpackcamera.ui.components.capture + +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +class ZoomBarComponentsTest { + + @Test + fun formatZoomLabel_unselectedStops_formatsWithoutMultiplierOrLeadingZero() { + assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 1.0f, isSelected = false)) + .isEqualTo(".5") + assertThat(formatZoomLabel(targetZoom = 1.0f, currentRatio = 1.0f, isSelected = false)) + .isEqualTo("1") + assertThat(formatZoomLabel(targetZoom = 2.0f, currentRatio = 1.0f, isSelected = false)) + .isEqualTo("2") + assertThat(formatZoomLabel(targetZoom = 5.0f, currentRatio = 1.0f, isSelected = false)) + .isEqualTo("5") + assertThat(formatZoomLabel(targetZoom = 10.0f, currentRatio = 1.0f, isSelected = false)) + .isEqualTo("10") + } + + @Test + fun formatZoomLabel_selectedStops_formatsWithMultiplier() { + assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 0.5f, isSelected = true)) + .isEqualTo(".5\u00D7") + assertThat(formatZoomLabel(targetZoom = 1.0f, currentRatio = 1.0f, isSelected = true)) + .isEqualTo("1\u00D7") + assertThat(formatZoomLabel(targetZoom = 2.0f, currentRatio = 2.0f, isSelected = true)) + .isEqualTo("2\u00D7") + assertThat(formatZoomLabel(targetZoom = 5.0f, currentRatio = 5.0f, isSelected = true)) + .isEqualTo("5\u00D7") + } + + @Test + fun formatZoomLabel_inBetweenPinchRatio_formatsCurrentRatio() { + assertThat(formatZoomLabel(targetZoom = 1.0f, currentRatio = 1.4f, isSelected = true)) + .isEqualTo("1.4\u00D7") + assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 0.7f, isSelected = true)) + .isEqualTo(".7\u00D7") + } +} From 6acb4bb736a9d59991c677ae3867817a4b8207d1 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 21 Oct 2026 21:08:48 -0700 Subject: [PATCH 02/14] Optimize ZoomBar memory usage and recomposition performance - Reuse ThreadLocal DecimalFormat instances to eliminate object allocation churn during high-frequency pinch gestures. - Migrate animated slider offset to layout-phase IntOffset lambda to prevent full component recompositions during spring animations. - Isolate ZoomBarItem recomposition by passing currentRatio only to the active selection, enabling Compose skipping for unselected stops. - Fix sub-1.0 stop selection logic to support devices with multiple ultra-wide/macro ratios. - Add rounding boundary tests for sub-1.0 to 1.0 transitions. --- .../components/capture/ZoomBarComponents.kt | 81 ++++++++++++------- .../capture/ZoomBarComponentsTest.kt | 2 + 2 files changed, 52 insertions(+), 31 deletions(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index 5f897b2687..c4022bd039 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -53,6 +53,7 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.google.jetpackcamera.model.LensFacing import com.google.jetpackcamera.ui.uistate.capture.ZoomControlUiState @@ -61,6 +62,21 @@ import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.util.Locale +private val US_SYMBOLS = DecimalFormatSymbols(Locale.US) + +private val SUB_ONE_FORMATTER = ThreadLocal.withInitial { + DecimalFormat(".#", US_SYMBOLS).apply { + minimumIntegerDigits = 0 + roundingMode = RoundingMode.HALF_UP + } +} + +private val DECIMAL_FORMATTER = ThreadLocal.withInitial { + DecimalFormat("#.#", US_SYMBOLS).apply { + roundingMode = RoundingMode.HALF_UP + } +} + /** * Styling configuration for [ZoomBar]. * @@ -151,20 +167,13 @@ fun formatZoomLabel( isSelected: Boolean ): String { val valueToFormat = if (isSelected) currentRatio else targetZoom - val symbols = DecimalFormatSymbols(Locale.US) val formattedNumber = if (valueToFormat < 1f && valueToFormat > 0f) { - val dec = DecimalFormat(".#", symbols).apply { - minimumIntegerDigits = 0 - roundingMode = RoundingMode.HALF_UP - } - dec.format(valueToFormat) + val formatted = SUB_ONE_FORMATTER.get()!!.format(valueToFormat) + if (formatted == "1" || formatted == "1.0") "1" else formatted } else if (valueToFormat % 1.0f == 0f) { valueToFormat.toInt().toString() } else { - val dec = DecimalFormat("#.#", symbols).apply { - roundingMode = RoundingMode.HALF_UP - } - dec.format(valueToFormat) + DECIMAL_FORMATTER.get()!!.format(valueToFormat) } return if (isSelected) { "$formattedNumber\u00D7" @@ -195,21 +204,14 @@ fun ZoomBar( if (zoomControlUiState is ZoomControlUiState.Enabled) { val currentZoomState by rememberUpdatedState(zoomControlUiState) val selectedOptionIndex: Int by remember(zoomControlUiState.primaryLensFacing) { - // checkValue will flash to 1.0 when flipping between camera lenses on API 30+. - // cameraState (cameraState's zoom value) should have an intermediate, "unknown", state when - // camera flip is in progress. Then we can ensure that the zoom controls don't flash to 1.0 - // when cameraState is in this intermediate state. derivedStateOf { + // If animating towards a value, select that target; otherwise find closest matching stop val checkValue = currentZoomState.animatingToValue ?: currentZoomState.primaryZoomRatio ?: 1f - if (checkValue >= 1f) { - val index = currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> - checkValue >= zoomLevelOption - } - if (index >= 0) index else 0 - } else { - 0 + val index = currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> + checkValue >= zoomLevelOption } + if (index >= 0) index else 0 } } @@ -230,6 +232,7 @@ fun ZoomBar( ZoomBarDefaults.VerticalItemHeight } + // Layout-phase animated offset prevents recompositions during slider animation val animatedOffset by animateDpAsState( targetValue = ZoomBarDefaults.EndPadding + (validIndex * if (orientation == Orientation.Horizontal) itemWidth.value else itemHeight.value).dp, animationSpec = spring(stiffness = Spring.StiffnessMediumLow), @@ -257,14 +260,24 @@ fun ZoomBar( stateDescription = zoomControlUiState.primaryZoomRatio.toString() } ) { - // Animated sliding indicator pill + // Animated sliding indicator pill rendered with layout-phase offset val indicatorModifier = if (orientation == Orientation.Horizontal) { Modifier - .offset(x = animatedOffset, y = ZoomBarDefaults.HorizontalClearance) + .offset { + IntOffset( + x = animatedOffset.roundToPx(), + y = ZoomBarDefaults.HorizontalClearance.roundToPx() + ) + } .size(itemWidth, itemHeight) } else { Modifier - .offset(x = 0.dp, y = animatedOffset) + .offset { + IntOffset( + x = 0, + y = animatedOffset.roundToPx() + ) + } .size(itemWidth, itemHeight) } Box( @@ -287,10 +300,11 @@ fun ZoomBar( verticalAlignment = Alignment.CenterVertically ) { zoomLevels.forEachIndexed { index, value -> + val isSelected = index == validIndex ZoomBarItem( value = value, - currentRatio = currentRatio, - isSelected = index == validIndex, + currentRatio = if (isSelected) currentRatio else null, + isSelected = isSelected, colors = colors, modifier = Modifier.size(itemWidth, itemHeight), onClick = { onChangeZoom(value) } @@ -305,10 +319,11 @@ fun ZoomBar( horizontalAlignment = Alignment.CenterHorizontally ) { zoomLevels.forEachIndexed { index, value -> + val isSelected = index == validIndex ZoomBarItem( value = value, - currentRatio = currentRatio, - isSelected = index == validIndex, + currentRatio = if (isSelected) currentRatio else null, + isSelected = isSelected, colors = colors, modifier = Modifier.size(itemWidth, itemHeight), onClick = { onChangeZoom(value) } @@ -323,14 +338,18 @@ fun ZoomBar( @Composable private fun ZoomBarItem( value: Float, - currentRatio: Float, + currentRatio: Float?, isSelected: Boolean, colors: ZoomBarColors, modifier: Modifier = Modifier, onClick: () -> Unit ) { - val displayText = remember(value, currentRatio, isSelected) { - formatZoomLabel(targetZoom = value, currentRatio = currentRatio, isSelected = isSelected) + val displayText = remember(value, isSelected, currentRatio) { + formatZoomLabel( + targetZoom = value, + currentRatio = currentRatio ?: value, + isSelected = isSelected + ) } Box( diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt index da3fda4ce2..d369ab41c6 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt @@ -52,5 +52,7 @@ class ZoomBarComponentsTest { .isEqualTo("1.4\u00D7") assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 0.7f, isSelected = true)) .isEqualTo(".7\u00D7") + assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 0.99f, isSelected = true)) + .isEqualTo("1\u00D7") } } From 5311050a81ddc269f76fbd5f8cdb94746f183f65 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 21 Oct 2026 21:50:34 -0700 Subject: [PATCH 03/14] Refactor ZoomBar active indicator to in-place appearing animation and refine end padding - Replace sliding indicator offset animation with in-place container and content color transitions using animateColorAsState on individual zoom items. - Retain Modifier.animateContentSize() on label text for smooth suffix expansion. - Adjust HorizontalItemWidth to 40.dp and HorizontalEndPadding to 6.dp to ensure uniform clearance around stadium capsule end caps. - Preserve vertical orientation dimensions and flush side alignment. --- .../components/capture/ZoomBarComponents.kt | 76 ++++++++----------- 1 file changed, 30 insertions(+), 46 deletions(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index c4022bd039..6616750069 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -15,9 +15,8 @@ */ package com.google.jetpackcamera.ui.components.capture -import androidx.compose.animation.core.Spring -import androidx.compose.animation.core.animateDpAsState -import androidx.compose.animation.core.spring +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.Orientation @@ -26,7 +25,6 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape @@ -53,7 +51,6 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.google.jetpackcamera.model.LensFacing import com.google.jetpackcamera.ui.uistate.capture.ZoomControlUiState @@ -97,10 +94,12 @@ data class ZoomBarColors( * Default color palettes and dimensions for [ZoomBar]. */ object ZoomBarDefaults { - val HorizontalItemWidth = 44.dp + val HorizontalItemWidth = 40.dp val HorizontalItemHeight = 36.dp val VerticalItemWidth = 40.dp val VerticalItemHeight = 40.dp + val HorizontalEndPadding = 6.dp + val VerticalEndPadding = 4.dp val EndPadding = 4.dp val HorizontalClearance = 4.dp @@ -184,7 +183,7 @@ fun formatZoomLabel( /** * A composable that displays zoom controls formatted as a unified capsule track - * with a sliding selected indicator pill. + * with a selected indicator pill appearing on the active stop. * * @param zoomControlUiState The [ZoomControlUiState] providing available zoom levels and current ratio. * @param onChangeZoom Callback when a zoom level is tapped. @@ -232,23 +231,22 @@ fun ZoomBar( ZoomBarDefaults.VerticalItemHeight } - // Layout-phase animated offset prevents recompositions during slider animation - val animatedOffset by animateDpAsState( - targetValue = ZoomBarDefaults.EndPadding + (validIndex * if (orientation == Orientation.Horizontal) itemWidth.value else itemHeight.value).dp, - animationSpec = spring(stiffness = Spring.StiffnessMediumLow), - label = "zoomIndicatorOffset" - ) + val endPadding = if (orientation == Orientation.Horizontal) { + ZoomBarDefaults.HorizontalEndPadding + } else { + ZoomBarDefaults.VerticalEndPadding + } // In horizontal, clearance exists on all sides; in vertical, buttons are flush with the vertical sides. val totalWidth = if (orientation == Orientation.Horizontal) { - itemWidth * zoomLevels.size + ZoomBarDefaults.EndPadding * 2 + itemWidth * zoomLevels.size + endPadding * 2 } else { itemWidth } val totalHeight = if (orientation == Orientation.Horizontal) { itemHeight + ZoomBarDefaults.HorizontalClearance * 2 } else { - itemHeight * zoomLevels.size + ZoomBarDefaults.EndPadding * 2 + itemHeight * zoomLevels.size + endPadding * 2 } Box( @@ -260,41 +258,13 @@ fun ZoomBar( stateDescription = zoomControlUiState.primaryZoomRatio.toString() } ) { - // Animated sliding indicator pill rendered with layout-phase offset - val indicatorModifier = if (orientation == Orientation.Horizontal) { - Modifier - .offset { - IntOffset( - x = animatedOffset.roundToPx(), - y = ZoomBarDefaults.HorizontalClearance.roundToPx() - ) - } - .size(itemWidth, itemHeight) - } else { - Modifier - .offset { - IntOffset( - x = 0, - y = animatedOffset.roundToPx() - ) - } - .size(itemWidth, itemHeight) - } - Box( - modifier = indicatorModifier - .background( - color = colors.selectedIndicatorColor, - shape = ZoomBarDefaults.IndicatorShape - ) - ) - // Stops if (orientation == Orientation.Horizontal) { Row( modifier = Modifier .fillMaxSize() .padding( - horizontal = ZoomBarDefaults.EndPadding, + horizontal = endPadding, vertical = ZoomBarDefaults.HorizontalClearance ), verticalAlignment = Alignment.CenterVertically @@ -315,7 +285,7 @@ fun ZoomBar( Column( modifier = Modifier .fillMaxSize() - .padding(vertical = ZoomBarDefaults.EndPadding), + .padding(vertical = endPadding), horizontalAlignment = Alignment.CenterHorizontally ) { zoomLevels.forEachIndexed { index, value -> @@ -352,8 +322,21 @@ private fun ZoomBarItem( ) } + val containerColor by animateColorAsState( + targetValue = if (isSelected) colors.selectedIndicatorColor else Color.Transparent, + label = "zoomItemContainerColor" + ) + val contentColor by animateColorAsState( + targetValue = if (isSelected) colors.selectedContentColor else colors.unselectedContentColor, + label = "zoomItemContentColor" + ) + Box( modifier = modifier + .background( + color = containerColor, + shape = ZoomBarDefaults.IndicatorShape + ) .clip(ZoomBarDefaults.IndicatorShape) .clickable( interactionSource = remember { MutableInteractionSource() }, @@ -368,11 +351,12 @@ private fun ZoomBarItem( contentAlignment = Alignment.Center ) { Text( + modifier = Modifier.animateContentSize(), text = displayText, style = MaterialTheme.typography.labelMedium.copy( fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium ), - color = if (isSelected) colors.selectedContentColor else colors.unselectedContentColor, + color = contentColor, textAlign = TextAlign.Center, maxLines = 1 ) From a216b2742b53fd8eac605a621f576a75ea6a18c5 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 21 Oct 2026 21:57:26 -0700 Subject: [PATCH 04/14] Apply Spotless formatting to ZoomBarComponents Format lines exceeding max line length and wrap parameters according to ktlint and spotless standards. --- .../components/capture/ZoomBarComponents.kt | 38 ++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index 6616750069..fa7b26097b 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -77,9 +77,12 @@ private val DECIMAL_FORMATTER = ThreadLocal.withInitial { /** * Styling configuration for [ZoomBar]. * - * @param trackColor Background color of the stadium track capsule (e.g. 60% black over viewfinder, 20% white off viewfinder). - * @param selectedIndicatorColor Background color of the sliding indicator pill behind the active stop (e.g. primaryFixed / #EBE1CF). - * @param selectedContentColor Text color for the currently selected stop (e.g. onPrimaryFixed / #1C1B1F). + * @param trackColor Background color of the stadium track capsule (e.g. 60% black over + * viewfinder, 20% white off viewfinder). + * @param selectedIndicatorColor Background color of the indicator pill behind the active stop (e.g. + * primaryFixed / #EBE1CF). + * @param selectedContentColor Text color for the currently selected stop (e.g. onPrimaryFixed / + * #1C1B1F). * @param unselectedContentColor Text color for unselected stops (e.g. Color.White). */ @Immutable @@ -160,11 +163,7 @@ object ZoomBarDefaults { * - Selected stop: ".5×", "1×", "2×", "5×" (with Unicode multiplication symbol \u00D7). * - In-between ratios (e.g. while pinching): "1.4×". */ -fun formatZoomLabel( - targetZoom: Float, - currentRatio: Float, - isSelected: Boolean -): String { +fun formatZoomLabel(targetZoom: Float, currentRatio: Float, isSelected: Boolean): String { val valueToFormat = if (isSelected) currentRatio else targetZoom val formattedNumber = if (valueToFormat < 1f && valueToFormat > 0f) { val formatted = SUB_ONE_FORMATTER.get()!!.format(valueToFormat) @@ -185,7 +184,8 @@ fun formatZoomLabel( * A composable that displays zoom controls formatted as a unified capsule track * with a selected indicator pill appearing on the active stop. * - * @param zoomControlUiState The [ZoomControlUiState] providing available zoom levels and current ratio. + * @param zoomControlUiState The [ZoomControlUiState] providing available zoom levels and + * current ratio. * @param onChangeZoom Callback when a zoom level is tapped. * @param modifier Modifier for the component. * @param orientation Layout orientation ([Orientation.Horizontal] or [Orientation.Vertical]), @@ -204,7 +204,8 @@ fun ZoomBar( val currentZoomState by rememberUpdatedState(zoomControlUiState) val selectedOptionIndex: Int by remember(zoomControlUiState.primaryLensFacing) { derivedStateOf { - // If animating towards a value, select that target; otherwise find closest matching stop + // If animating towards a value, select that target; otherwise find closest + // matching stop val checkValue = currentZoomState.animatingToValue ?: currentZoomState.primaryZoomRatio ?: 1f val index = currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> @@ -237,7 +238,8 @@ fun ZoomBar( ZoomBarDefaults.VerticalEndPadding } - // In horizontal, clearance exists on all sides; in vertical, buttons are flush with the vertical sides. + // In horizontal, clearance exists on all sides; in vertical, buttons are flush with + // the vertical sides. val totalWidth = if (orientation == Orientation.Horizontal) { itemWidth * zoomLevels.size + endPadding * 2 } else { @@ -323,11 +325,21 @@ private fun ZoomBarItem( } val containerColor by animateColorAsState( - targetValue = if (isSelected) colors.selectedIndicatorColor else Color.Transparent, + targetValue = + if (isSelected) { + colors.selectedIndicatorColor + } else { + Color.Transparent + }, label = "zoomItemContainerColor" ) val contentColor by animateColorAsState( - targetValue = if (isSelected) colors.selectedContentColor else colors.unselectedContentColor, + targetValue = + if (isSelected) { + colors.selectedContentColor + } else { + colors.unselectedContentColor + }, label = "zoomItemContentColor" ) From 987038aa6cd5cc24d30704cd5d4a27600a11e9f2 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Thu, 22 Oct 2026 07:27:16 -0700 Subject: [PATCH 05/14] Adopt Material theme default colors for ZoomBar indicator and expose colors in ZoomButtonRow - Replace hardcoded mock colors (tan / #EBE1CF) in black60Colors and white20Colors with MaterialTheme.colorScheme.primaryFixed and onPrimaryFixed. - Expose colors parameter on ZoomButtonRow to allow external callers and implementing apps to customize track and indicator colors. --- .../components/capture/ZoomBarComponents.kt | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index fa7b26097b..b849c3969c 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -80,9 +80,8 @@ private val DECIMAL_FORMATTER = ThreadLocal.withInitial { * @param trackColor Background color of the stadium track capsule (e.g. 60% black over * viewfinder, 20% white off viewfinder). * @param selectedIndicatorColor Background color of the indicator pill behind the active stop (e.g. - * primaryFixed / #EBE1CF). - * @param selectedContentColor Text color for the currently selected stop (e.g. onPrimaryFixed / - * #1C1B1F). + * primaryFixed). + * @param selectedContentColor Text color for the currently selected stop (e.g. onPrimaryFixed). * @param unselectedContentColor Text color for unselected stops (e.g. Color.White). */ @Immutable @@ -129,10 +128,11 @@ object ZoomBarDefaults { /** * Colors for overlapping the viewfinder (60% black background). */ + @Composable fun black60Colors( trackColor: Color = Color.Black.copy(alpha = 0.60f), - selectedIndicatorColor: Color = Color(0xFFEBE1CF), - selectedContentColor: Color = Color(0xFF1C1B1F), + selectedIndicatorColor: Color = MaterialTheme.colorScheme.primaryFixed, + selectedContentColor: Color = MaterialTheme.colorScheme.onPrimaryFixed, unselectedContentColor: Color = Color.White ) = ZoomBarColors( trackColor = trackColor, @@ -144,10 +144,11 @@ object ZoomBarDefaults { /** * Colors when not overlapping the viewfinder (lighter translucent background). */ + @Composable fun white20Colors( trackColor: Color = Color.White.copy(alpha = 0.20f), - selectedIndicatorColor: Color = Color(0xFFEBE1CF), - selectedContentColor: Color = Color(0xFF1C1B1F), + selectedIndicatorColor: Color = MaterialTheme.colorScheme.primaryFixed, + selectedContentColor: Color = MaterialTheme.colorScheme.onPrimaryFixed, unselectedContentColor: Color = Color.White ) = ZoomBarColors( trackColor = trackColor, @@ -386,6 +387,7 @@ private fun ZoomBarItem( * @param buttonSize the size of the buttons (retained for backward compatibility) * @param spacing the spacing between the buttons (retained for backward compatibility) * @param orientation the layout orientation ([Orientation.Horizontal] or [Orientation.Vertical]) + * @param colors the [ZoomBarColors] styling configuration for track and indicator colors */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable @@ -395,13 +397,15 @@ fun ZoomButtonRow( zoomControlUiState: ZoomControlUiState, buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, spacing: Dp = 16.dp, - orientation: Orientation = Orientation.Horizontal + orientation: Orientation = Orientation.Horizontal, + colors: ZoomBarColors = ZoomBarDefaults.colors() ) { ZoomBar( zoomControlUiState = zoomControlUiState, onChangeZoom = onChangeZoom, modifier = modifier, - orientation = orientation + orientation = orientation, + colors = colors ) } From 717df9193bee1c5cfa862f87c2592d7c0481e1ea Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Thu, 22 Oct 2026 08:24:26 -0700 Subject: [PATCH 06/14] Address PR review comments: defer zoom ratio read, restrict visibility, and add test runner - Defer high-frequency primaryZoomRatio read in ZoomBar using a lambda provider and derivedStateOf in ZoomBarItem to prevent top-level recomposition during pinch gestures. - Clean up redundant contentDescription in ZoomBarItem semantics in favor of selected state. - Restrict formatZoomLabel visibility to internal. - Annotate ZoomBarComponentsTest with @RunWith(JUnit4::class). --- .../components/capture/ZoomBarComponents.kt | 26 +++++++++---------- .../capture/ZoomBarComponentsTest.kt | 3 +++ 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index b849c3969c..ce27899fc4 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -42,7 +42,6 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color -import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription @@ -164,7 +163,7 @@ object ZoomBarDefaults { * - Selected stop: ".5×", "1×", "2×", "5×" (with Unicode multiplication symbol \u00D7). * - In-between ratios (e.g. while pinching): "1.4×". */ -fun formatZoomLabel(targetZoom: Float, currentRatio: Float, isSelected: Boolean): String { +internal fun formatZoomLabel(targetZoom: Float, currentRatio: Float, isSelected: Boolean): String { val valueToFormat = if (isSelected) currentRatio else targetZoom val formattedNumber = if (valueToFormat < 1f && valueToFormat > 0f) { val formatted = SUB_ONE_FORMATTER.get()!!.format(valueToFormat) @@ -220,7 +219,7 @@ fun ZoomBar( if (zoomLevels.isEmpty()) return val validIndex = selectedOptionIndex.coerceIn(0, zoomLevels.size - 1) - val currentRatio = currentZoomState.primaryZoomRatio ?: 1f + val currentRatioProvider = remember { { currentZoomState.primaryZoomRatio ?: 1f } } val itemWidth = if (orientation == Orientation.Horizontal) { ZoomBarDefaults.HorizontalItemWidth @@ -276,7 +275,7 @@ fun ZoomBar( val isSelected = index == validIndex ZoomBarItem( value = value, - currentRatio = if (isSelected) currentRatio else null, + currentRatioProvider = currentRatioProvider, isSelected = isSelected, colors = colors, modifier = Modifier.size(itemWidth, itemHeight), @@ -295,7 +294,7 @@ fun ZoomBar( val isSelected = index == validIndex ZoomBarItem( value = value, - currentRatio = if (isSelected) currentRatio else null, + currentRatioProvider = currentRatioProvider, isSelected = isSelected, colors = colors, modifier = Modifier.size(itemWidth, itemHeight), @@ -311,18 +310,20 @@ fun ZoomBar( @Composable private fun ZoomBarItem( value: Float, - currentRatio: Float?, + currentRatioProvider: () -> Float, isSelected: Boolean, colors: ZoomBarColors, modifier: Modifier = Modifier, onClick: () -> Unit ) { - val displayText = remember(value, isSelected, currentRatio) { - formatZoomLabel( - targetZoom = value, - currentRatio = currentRatio ?: value, - isSelected = isSelected - ) + val displayText by remember(value, isSelected) { + derivedStateOf { + formatZoomLabel( + targetZoom = value, + currentRatio = if (isSelected) currentRatioProvider() else value, + isSelected = isSelected + ) + } } val containerColor by animateColorAsState( @@ -358,7 +359,6 @@ private fun ZoomBarItem( ) .semantics { testTag = getZoomButtonTestTag(value) - contentDescription = if (isSelected) "selected" else "not selected" selected = isSelected }, contentAlignment = Alignment.Center diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt index d369ab41c6..5d4a203292 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt @@ -17,7 +17,10 @@ package com.google.jetpackcamera.ui.components.capture import com.google.common.truth.Truth.assertThat import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +@RunWith(JUnit4::class) class ZoomBarComponentsTest { @Test From 244428f6607bac773c1aa06f4d3ec7d568ae06a3 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Thu, 22 Oct 2026 08:37:33 -0700 Subject: [PATCH 07/14] Polish ZoomBar: add semantic radio button role, restrict preview visibility, and remove unused constant - Add Role.RadioButton to ZoomBarItem's clickable modifier to improve screen reader navigation. - Restrict all @Preview composable functions in ZoomBarComponents to private visibility. - Remove unused ZoomBarDefaults.EndPadding constant. --- .../components/capture/ZoomBarComponents.kt | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index ce27899fc4..e64ef4a6f7 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -42,6 +42,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription @@ -101,7 +102,6 @@ object ZoomBarDefaults { val VerticalItemHeight = 40.dp val HorizontalEndPadding = 6.dp val VerticalEndPadding = 4.dp - val EndPadding = 4.dp val HorizontalClearance = 4.dp val TrackShape = RoundedCornerShape(56.dp) @@ -355,6 +355,7 @@ private fun ZoomBarItem( .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, + role = Role.RadioButton, onClick = onClick ) .semantics { @@ -429,7 +430,7 @@ private fun getZoomButtonTestTag(buttonValue: Float): String { @Preview(name = "Horizontal 60% Black (Overlapping Viewfinder)", showBackground = true) @Composable -fun ZoomBarHorizontalDarkPreview() { +private fun ZoomBarHorizontalDarkPreview() { Box( modifier = Modifier .background(Color(0xFF2B2B2B)) @@ -451,7 +452,7 @@ fun ZoomBarHorizontalDarkPreview() { @Preview(name = "Horizontal 20% White (Not Overlapping Viewfinder)", showBackground = true) @Composable -fun ZoomBarHorizontalTranslucentPreview() { +private fun ZoomBarHorizontalTranslucentPreview() { Box( modifier = Modifier .background(Color(0xFF2B2B2B)) @@ -473,7 +474,7 @@ fun ZoomBarHorizontalTranslucentPreview() { @Preview(name = "Horizontal - Fraction (.5x Selected)", showBackground = true) @Composable -fun ZoomBarHorizontalFractionPreview() { +private fun ZoomBarHorizontalFractionPreview() { Box( modifier = Modifier .background(Color(0xFF2B2B2B)) @@ -495,7 +496,7 @@ fun ZoomBarHorizontalFractionPreview() { @Preview(name = "Vertical 60% Black - Flush Sides", showBackground = true) @Composable -fun ZoomBarVerticalDarkPreview() { +private fun ZoomBarVerticalDarkPreview() { Box( modifier = Modifier .background(Color(0xFF2B2B2B)) @@ -517,7 +518,7 @@ fun ZoomBarVerticalDarkPreview() { @Preview(name = "Vertical 20% White - Flush Sides", showBackground = true) @Composable -fun ZoomBarVerticalTranslucentPreview() { +private fun ZoomBarVerticalTranslucentPreview() { Box( modifier = Modifier .background(Color(0xFF2B2B2B)) @@ -539,7 +540,7 @@ fun ZoomBarVerticalTranslucentPreview() { @Preview(name = "Single Value Range (1.0x only)", showBackground = true) @Composable -fun ZoomBarSingleValuePreview() { +private fun ZoomBarSingleValuePreview() { Box( modifier = Modifier .background(Color(0xFF2B2B2B)) @@ -560,7 +561,7 @@ fun ZoomBarSingleValuePreview() { @Preview(name = "Extended Telephoto Range (2x Selected)", showBackground = true) @Composable -fun ZoomBarExtendedRangePreview() { +private fun ZoomBarExtendedRangePreview() { Box( modifier = Modifier .background(Color(0xFF2B2B2B)) @@ -581,12 +582,12 @@ fun ZoomBarExtendedRangePreview() { @Preview(name = "Legacy Delegate - One Selected", showBackground = true) @Composable -fun ZoomBarPreviewOneSelected() { +private fun ZoomBarPreviewOneSelected() { ZoomBarHorizontalDarkPreview() } @Preview(name = "Legacy Delegate - Fraction Selected", showBackground = true) @Composable -fun ZoomBarPreviewFractionSelected() { +private fun ZoomBarPreviewFractionSelected() { ZoomBarHorizontalFractionPreview() } From ba9844d9f22137afeadf2aed6c92d38729aa7b54 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Thu, 22 Oct 2026 10:17:17 -0700 Subject: [PATCH 08/14] Use explicit setter for DecimalFormat rounding mode Invoke setRoundingMode directly on DecimalFormat instances instead of property assignment syntax to ensure compatibility across compiler toolchains and Android SDK stubs. --- .../jetpackcamera/ui/components/capture/ZoomBarComponents.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index e64ef4a6f7..d9563a2da8 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -64,13 +64,13 @@ private val US_SYMBOLS = DecimalFormatSymbols(Locale.US) private val SUB_ONE_FORMATTER = ThreadLocal.withInitial { DecimalFormat(".#", US_SYMBOLS).apply { minimumIntegerDigits = 0 - roundingMode = RoundingMode.HALF_UP + setRoundingMode(RoundingMode.HALF_UP) } } private val DECIMAL_FORMATTER = ThreadLocal.withInitial { DecimalFormat("#.#", US_SYMBOLS).apply { - roundingMode = RoundingMode.HALF_UP + setRoundingMode(RoundingMode.HALF_UP) } } From 3a3b1469beea425e033fc0b0a929bb64bd7931bd Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Fri, 23 Oct 2026 14:22:41 -0700 Subject: [PATCH 09/14] Optimize ZoomBar indicator, harden zoom pipeline, and fix lens-flip 1x flash --- .../core/camera/CameraSession.kt | 26 +++- .../components/capture/ZoomBarComponents.kt | 87 ++++++++++--- .../ui/components/capture/ZoomStateManager.kt | 52 +++++--- .../capture/ZoomStateManagerTest.kt | 115 ++++++++++++++++++ .../ui/controller/impl/ZoomControllerImpl.kt | 29 ++++- .../controller/impl/ZoomControllerImplTest.kt | 115 ++++++++++++++++++ 6 files changed, 381 insertions(+), 43 deletions(-) create mode 100644 ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManagerTest.kt create mode 100644 ui/controller/impl/src/test/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImplTest.kt diff --git a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt index 4b99c794c2..ed7ebab9f8 100644 --- a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt +++ b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt @@ -351,11 +351,14 @@ internal suspend fun runSingleCameraSession( .collectLatest { zoomState -> // TODO(b/405987189): remove checks after buggy zoomState is fixed if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + // Ignore the initial 1.0f zoomState emitted on camera bind + // unless 1.0f is the actual target zoom for this lens. + val targetZoomRatio = + (transientSettings.value ?: currentTransientSettings) + .zoomRatios[camera.cameraInfo.appLensFacing] + ?: 1.0f if (zoomState.zoomRatio != 1.0f || - zoomState.zoomRatio == currentTransientSettings - .zoomRatios[ - currentTransientSettings.primaryLensFacing - ] + zoomState.zoomRatio == targetZoomRatio ) { currentCameraState.update { old -> old.copy( @@ -1371,9 +1374,22 @@ private fun Preview.Builder.updateCameraStateWithCaptureResults( ) { // update camerastate with zoom ratio val newZoomRatio = result.get(CaptureResult.CONTROL_ZOOM_RATIO) + val targetZoomRatio = + transientSettings.value?.zoomRatios?.get(targetCameraInfo.appLensFacing) + ?: 1.0f currentCameraState.update { old -> + val currentZoomRatio = old.zoomRatios[targetCameraInfo.appLensFacing] + // When a lens is newly bound, initial capture results emit the hardware + // default 1.0f before cameraControl.setZoomRatio(initialZoomRatio) takes + // effect in the repeating request. Ignore those initial 1.0f frames if + // the lens is restoring a non-1.0f target zoom so the UI doesn't flash 1x. + val isInitialDefaultEmission = + currentZoomRatio == null && + newZoomRatio == 1.0f && + targetZoomRatio != 1.0f if (newZoomRatio != null && - old.zoomRatios[targetCameraInfo.appLensFacing] != newZoomRatio + !isInitialDefaultEmission && + currentZoomRatio != newZoomRatio ) { old.copy( zoomRatios = old.zoomRatios diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index d9563a2da8..83a3a502de 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -17,6 +17,10 @@ package com.google.jetpackcamera.ui.components.capture import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateContentSize +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.snap +import androidx.compose.animation.core.spring import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.Orientation @@ -40,7 +44,10 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.selected @@ -52,12 +59,14 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.lerp import com.google.jetpackcamera.model.LensFacing import com.google.jetpackcamera.ui.uistate.capture.ZoomControlUiState import java.math.RoundingMode import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.util.Locale +import kotlin.math.round private val US_SYMBOLS = DecimalFormatSymbols(Locale.US) @@ -105,7 +114,9 @@ object ZoomBarDefaults { val HorizontalClearance = 4.dp val TrackShape = RoundedCornerShape(56.dp) - val IndicatorShape = RoundedCornerShape(12.dp) + val IndicatorCornerRadius = 12.dp + val IndicatorShape = RoundedCornerShape(IndicatorCornerRadius) + val UnselectedIndicatorSize = 32.dp /** * Default dynamic colors adapting to viewfinder overlap via [LocalCameraControlBackgroundStyle] @@ -207,9 +218,14 @@ fun ZoomBar( // If animating towards a value, select that target; otherwise find closest // matching stop val checkValue = - currentZoomState.animatingToValue ?: currentZoomState.primaryZoomRatio ?: 1f + currentZoomState.animatingToValue + ?: currentZoomState.primaryZoomRatio + ?: currentZoomState.initialZoomRatio + ?: 1f + val roundedCheckValue = round(checkValue * 10f) / 10f val index = currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> - checkValue >= zoomLevelOption + val roundedOption = round(zoomLevelOption * 10f) / 10f + roundedCheckValue >= roundedOption } if (index >= 0) index else 0 } @@ -219,7 +235,13 @@ fun ZoomBar( if (zoomLevels.isEmpty()) return val validIndex = selectedOptionIndex.coerceIn(0, zoomLevels.size - 1) - val currentRatioProvider = remember { { currentZoomState.primaryZoomRatio ?: 1f } } + val currentRatioProvider = remember { + { + currentZoomState.primaryZoomRatio + ?: currentZoomState.initialZoomRatio + ?: 1f + } + } val itemWidth = if (orientation == Orientation.Horizontal) { ZoomBarDefaults.HorizontalItemWidth @@ -278,6 +300,8 @@ fun ZoomBar( currentRatioProvider = currentRatioProvider, isSelected = isSelected, colors = colors, + itemWidth = itemWidth, + itemHeight = itemHeight, modifier = Modifier.size(itemWidth, itemHeight), onClick = { onChangeZoom(value) } ) @@ -297,6 +321,8 @@ fun ZoomBar( currentRatioProvider = currentRatioProvider, isSelected = isSelected, colors = colors, + itemWidth = itemWidth, + itemHeight = itemHeight, modifier = Modifier.size(itemWidth, itemHeight), onClick = { onChangeZoom(value) } ) @@ -313,6 +339,8 @@ private fun ZoomBarItem( currentRatioProvider: () -> Float, isSelected: Boolean, colors: ZoomBarColors, + itemWidth: Dp, + itemHeight: Dp, modifier: Modifier = Modifier, onClick: () -> Unit ) { @@ -326,18 +354,25 @@ private fun ZoomBarItem( } } - val containerColor by animateColorAsState( - targetValue = - if (isSelected) { - colors.selectedIndicatorColor + val unselectedSize = (if (itemWidth < itemHeight) itemWidth else itemHeight) + .coerceAtMost(ZoomBarDefaults.UnselectedIndicatorSize) + val unselectedCornerRadius = unselectedSize / 2 + + val indicatorProgress by animateFloatAsState( + targetValue = if (isSelected) 1f else 0f, + animationSpec = if (isSelected) { + spring( + dampingRatio = Spring.DampingRatioMediumBouncy, + stiffness = Spring.StiffnessMediumLow + ) } else { - Color.Transparent + snap() }, - label = "zoomItemContainerColor" + label = "zoomIndicatorProgress" ) + val contentColor by animateColorAsState( - targetValue = - if (isSelected) { + targetValue = if (isSelected) { colors.selectedContentColor } else { colors.unselectedContentColor @@ -347,11 +382,27 @@ private fun ZoomBarItem( Box( modifier = modifier - .background( - color = containerColor, - shape = ZoomBarDefaults.IndicatorShape - ) - .clip(ZoomBarDefaults.IndicatorShape) + .drawBehind { + val progress = indicatorProgress + if (isSelected || progress > 0f) { + val width = lerp(unselectedSize, itemWidth, progress).toPx().coerceAtLeast(0f) + val height = lerp(unselectedSize, itemHeight, progress).toPx().coerceAtLeast(0f) + val cornerRadius = lerp( + unselectedCornerRadius, + ZoomBarDefaults.IndicatorCornerRadius, + progress + ).toPx().coerceAtLeast(0f) + drawRoundRect( + color = colors.selectedIndicatorColor, + topLeft = Offset( + x = (size.width - width) / 2f, + y = (size.height - height) / 2f + ), + size = Size(width = width, height = height), + cornerRadius = CornerRadius(cornerRadius, cornerRadius) + ) + } + } .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt index cf85a44c41..128ffef6e9 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt @@ -52,6 +52,9 @@ class ZoomStateManager( // The valid zoom range for the current camera lens. private var functionalZoomRange = zoomRange + // Tracks the active animated zoom target and lens to avoid restarting an identical animation. + private var currentAnimationTarget: Pair? = null + // A mutex to ensure that zoom operations are atomic and thread-safe. This is crucial for // preventing race conditions, as multiple zoom actions (e.g., pinch-to-zoom and button // clicks) can be triggered concurrently. By using a MutatorMutex, we can ensure that @@ -77,13 +80,14 @@ class ZoomStateManager( */ suspend fun absoluteZoom(targetZoomLevel: Float, lensToZoom: LensToZoom) { mutateZoom { + val coercedZoom = targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()) if (lensToZoom == LensToZoom.PRIMARY) { - functionalZoom = targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()) + functionalZoom = coercedZoom } zoomController.setZoomRatio( CameraZoomRatio( ZoomStrategy.Absolute( - targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()), + coercedZoom, lensToZoom = lensToZoom ) ) @@ -131,23 +135,38 @@ class ZoomStateManager( animationSpec: AnimationSpec = tween(durationMillis = 500), lensToZoom: LensToZoom ) { + if (currentAnimationTarget == + lensToZoom to targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()) + ) { + return + } mutatorMutex.mutate { - zoomController.setZoomAnimationState(targetZoomLevel) - - Animatable(initialValue = functionalZoom).animateTo( - targetValue = targetZoomLevel, - animationSpec = animationSpec - ) { - // this is called every animation frame - functionalZoom = value.coerceIn(functionalZoomRange.toClosedRange()) - zoomController.setZoomRatio( - CameraZoomRatio( - ZoomStrategy.Absolute( - functionalZoom, - lensToZoom + val coercedTarget = targetZoomLevel.coerceIn(functionalZoomRange.toClosedRange()) + if (lensToZoom == LensToZoom.PRIMARY && coercedTarget == functionalZoom) { + zoomController.setZoomAnimationState(null) + return@mutate + } + currentAnimationTarget = lensToZoom to coercedTarget + zoomController.setZoomAnimationState(coercedTarget) + try { + Animatable(initialValue = functionalZoom).animateTo( + targetValue = coercedTarget, + animationSpec = animationSpec + ) { + // this is called every animation frame + functionalZoom = value.coerceIn(functionalZoomRange.toClosedRange()) + zoomController.setZoomRatio( + CameraZoomRatio( + ZoomStrategy.Absolute( + functionalZoom, + lensToZoom + ) ) ) - ) + } + } finally { + currentAnimationTarget = null + zoomController.setZoomAnimationState(null) } } } @@ -163,6 +182,7 @@ class ZoomStateManager( */ suspend fun onChangeLens(newInitialZoomLevel: Float, newZoomRange: Range) { mutatorMutex.mutate(MutatePriority.PreventUserInput) { + zoomController.setZoomAnimationState(null) functionalZoom = newInitialZoomLevel functionalZoomRange = newZoomRange } diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManagerTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManagerTest.kt new file mode 100644 index 0000000000..8a749c4bf2 --- /dev/null +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManagerTest.kt @@ -0,0 +1,115 @@ +/* + * Copyright (C) 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.google.jetpackcamera.ui.components.capture + +import android.util.Range +import androidx.compose.animation.core.snap +import androidx.compose.runtime.MonotonicFrameClock +import com.google.common.truth.Truth.assertThat +import com.google.jetpackcamera.model.CameraZoomRatio +import com.google.jetpackcamera.model.LensToZoom +import com.google.jetpackcamera.model.ZoomStrategy +import com.google.jetpackcamera.ui.controller.testing.FakeZoomController +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class ZoomStateManagerTest { + + private val appliedRatios = mutableListOf() + private val animationStates = mutableListOf() + private lateinit var zoomController: FakeZoomController + private lateinit var zoomStateManager: ZoomStateManager + + private val testFrameClock = object : MonotonicFrameClock { + private var frameTimeNanos = 0L + override suspend fun withFrameNanos(onFrame: (frameTimeNanos: Long) -> R): R { + frameTimeNanos += 16_000_000L + return onFrame(frameTimeNanos) + } + } + + @Before + fun setUp() { + appliedRatios.clear() + animationStates.clear() + zoomController = FakeZoomController( + setZoomRatioAction = { appliedRatios.add(it) }, + setZoomAnimationStateAction = { animationStates.add(it) } + ) + zoomStateManager = ZoomStateManager( + initialZoomLevel = 1.0f, + zoomRange = Range(0.5f, 10.0f), + zoomController = zoomController + ) + } + + @Test + fun animatedZoom_setsAndClearsZoomAnimationStateOnCompletion() = runTest { + animationStates.clear() + + withContext(testFrameClock) { + zoomStateManager.animatedZoom( + targetZoomLevel = 5.0f, + animationSpec = snap(), + lensToZoom = LensToZoom.PRIMARY + ) + } + + assertThat(animationStates).containsExactly(5.0f, null).inOrder() + assertThat(appliedRatios.last()).isEqualTo( + CameraZoomRatio(ZoomStrategy.Absolute(5.0f, LensToZoom.PRIMARY)) + ) + } + + @Test + fun animatedZoom_whenAlreadyAtTargetZoom_shortCircuits() = runTest { + animationStates.clear() + + withContext(testFrameClock) { + zoomStateManager.animatedZoom( + targetZoomLevel = 1.0f, + animationSpec = snap(), + lensToZoom = LensToZoom.PRIMARY + ) + } + + assertThat(appliedRatios).isEmpty() + assertThat(animationStates).containsExactly(null) + } + + @Test + fun onChangeLens_resetsZoomAnimationStateAndUpdatesRange() = runTest { + animationStates.clear() + + zoomStateManager.onChangeLens( + newInitialZoomLevel = 2.0f, + newZoomRange = Range(1.0f, 4.0f) + ) + zoomStateManager.scaleZoom(scalingFactor = 3.0f, lensToZoom = LensToZoom.PRIMARY) + + assertThat(animationStates).contains(null) + assertThat(appliedRatios.last()).isEqualTo( + CameraZoomRatio(ZoomStrategy.Absolute(4.0f, LensToZoom.PRIMARY)) + ) + } +} diff --git a/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt b/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt index b54b4f6a1a..77d6fafd8e 100644 --- a/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt +++ b/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt @@ -17,6 +17,8 @@ package com.google.jetpackcamera.ui.controller.impl import com.google.jetpackcamera.core.camera.CameraSystem import com.google.jetpackcamera.model.CameraZoomRatio +import com.google.jetpackcamera.model.LensToZoom +import com.google.jetpackcamera.model.ZoomStrategy import com.google.jetpackcamera.ui.controller.ZoomController import com.google.jetpackcamera.ui.uistate.capture.TrackedCaptureUiState import kotlin.coroutines.CoroutineContext @@ -41,12 +43,31 @@ class ZoomControllerImpl( ) : ZoomController { private val job = Job(parent = coroutineContext[Job]) private val scope = CoroutineScope(coroutineContext + job) + private var primaryZoomJob: Job? = null + private var secondaryZoomJob: Job? = null override fun setZoomRatio(zoomRatio: CameraZoomRatio) { - scope.launch { - cameraSystemProvider().changeZoomRatio( - newZoomState = zoomRatio - ) + if (zoomRatio.changeType is ZoomStrategy.Absolute) { + when (zoomRatio.changeType.lensToZoom) { + LensToZoom.PRIMARY -> { + primaryZoomJob?.cancel() + primaryZoomJob = scope.launch { + cameraSystemProvider().changeZoomRatio(newZoomState = zoomRatio) + } + } + LensToZoom.SECONDARY -> { + secondaryZoomJob?.cancel() + secondaryZoomJob = scope.launch { + cameraSystemProvider().changeZoomRatio(newZoomState = zoomRatio) + } + } + } + } else { + scope.launch { + cameraSystemProvider().changeZoomRatio( + newZoomState = zoomRatio + ) + } } } diff --git a/ui/controller/impl/src/test/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImplTest.kt b/ui/controller/impl/src/test/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImplTest.kt new file mode 100644 index 0000000000..5bd6f56fd5 --- /dev/null +++ b/ui/controller/impl/src/test/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImplTest.kt @@ -0,0 +1,115 @@ +/* + * Copyright (C) 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.google.jetpackcamera.ui.controller.impl + +import com.google.common.truth.Truth.assertThat +import com.google.jetpackcamera.core.camera.CameraSystem +import com.google.jetpackcamera.core.camera.testing.FakeCameraSystem +import com.google.jetpackcamera.model.CameraZoomRatio +import com.google.jetpackcamera.model.LensToZoom +import com.google.jetpackcamera.model.ZoomStrategy +import com.google.jetpackcamera.ui.uistate.capture.TrackedCaptureUiState +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(JUnit4::class) +internal class ZoomControllerImplTest { + private val testScope = TestScope() + private val testDispatcher = StandardTestDispatcher(testScope.testScheduler) + + private class RecordingCameraSystem : CameraSystem by FakeCameraSystem() { + val zoomChanges = mutableListOf() + + override fun changeZoomRatio(newZoomState: CameraZoomRatio) { + zoomChanges.add(newZoomState) + } + } + + private val cameraSystem = RecordingCameraSystem() + private val trackedCaptureUiState = MutableStateFlow(TrackedCaptureUiState()) + private lateinit var controller: ZoomControllerImpl + + @Before + fun setup() { + controller = ZoomControllerImpl( + cameraSystemProvider = { cameraSystem }, + trackedCaptureUiState = trackedCaptureUiState, + coroutineContext = testDispatcher + ) + } + + @Test + fun setZoomRatio_conflatesPendingAbsoluteUpdatesForSameLens() = testScope.runTest { + val deferredCameraSystem = CompletableDeferred() + val delayedController = ZoomControllerImpl( + cameraSystemProvider = { deferredCameraSystem.await() }, + trackedCaptureUiState = trackedCaptureUiState, + coroutineContext = testDispatcher + ) + + delayedController.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(0.5f, LensToZoom.PRIMARY)) + ) + delayedController.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(2.0f, LensToZoom.PRIMARY)) + ) + delayedController.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(5.0f, LensToZoom.PRIMARY)) + ) + + deferredCameraSystem.complete(cameraSystem) + advanceUntilIdle() + + assertThat(cameraSystem.zoomChanges).containsExactly( + CameraZoomRatio(ZoomStrategy.Absolute(5.0f, LensToZoom.PRIMARY)) + ) + } + + @Test + fun setZoomRatio_primaryAndSecondaryDoNotCancelEachOther() = testScope.runTest { + controller.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(2.0f, LensToZoom.PRIMARY)) + ) + controller.setZoomRatio( + CameraZoomRatio(ZoomStrategy.Absolute(1.0f, LensToZoom.SECONDARY)) + ) + advanceUntilIdle() + + assertThat(cameraSystem.zoomChanges).containsExactly( + CameraZoomRatio(ZoomStrategy.Absolute(2.0f, LensToZoom.PRIMARY)), + CameraZoomRatio(ZoomStrategy.Absolute(1.0f, LensToZoom.SECONDARY)) + ).inOrder() + } + + @Test + fun setZoomAnimationState_updatesTrackedCaptureUiState() { + controller.setZoomAnimationState(5.0f) + assertThat(trackedCaptureUiState.value.zoomAnimationTarget).isEqualTo(5.0f) + + controller.setZoomAnimationState(null) + assertThat(trackedCaptureUiState.value.zoomAnimationTarget).isNull() + } +} From b46841a88ef2903f756aa33173a15ad660121019 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Mon, 26 Oct 2026 10:35:38 -0700 Subject: [PATCH 10/14] Address PR review feedback on ZoomBar UX parity - Implement single sliding pill indicator with M3 spatial motion - Update slot and indicator dimensions for spec parity and 48dp touch targets - Decouple layout orientation from device rotation and rotate text in-place - Align vertical layout with 48dp flush-edge mock specification - Interpolate label color via lerp in draw phase based on indicator proximity - Cap system font scale at 1.3f to prevent label clipping/wrapping - Fix tap jump-back glitch by prioritizing primarySettingZoomRatio - Unify half-up decimal rounding and add localized decimal separator support - Add selectableGroup and accessible action semantics for TalkBack - Deprecate ZoomButtonRow and migrate PreviewScreen call site - Allow 1.0f tolerance for HAL quantization in CameraSession - Transfer interrupted zoom animations cleanly in ZoomStateManager --- .../core/camera/CameraSession.kt | 10 +- .../feature/preview/PreviewScreen.kt | 4 +- .../components/capture/ZoomBarComponents.kt | 413 +++++++++--------- .../ui/components/capture/ZoomStateManager.kt | 2 +- .../capture/src/main/res/values/strings.xml | 3 + .../capture/ZoomBarComponentsTest.kt | 169 ++++++- .../ui/controller/impl/ZoomControllerImpl.kt | 4 + 7 files changed, 374 insertions(+), 231 deletions(-) diff --git a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt index ed7ebab9f8..68f0562350 100644 --- a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt +++ b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt @@ -1377,6 +1377,11 @@ private fun Preview.Builder.updateCameraStateWithCaptureResults( val targetZoomRatio = transientSettings.value?.zoomRatios?.get(targetCameraInfo.appLensFacing) ?: 1.0f + val zoomState = targetCameraInfo.zoomState.value + val minZoom = zoomState?.minZoomRatio ?: 1.0f + val maxZoom = zoomState?.maxZoomRatio ?: 1.0f + val clampedTarget = targetZoomRatio.coerceIn(minZoom, maxZoom) + val isTargetEssentiallyOne = kotlin.math.abs(clampedTarget - 1.0f) < 0.01f currentCameraState.update { old -> val currentZoomRatio = old.zoomRatios[targetCameraInfo.appLensFacing] // When a lens is newly bound, initial capture results emit the hardware @@ -1385,8 +1390,9 @@ private fun Preview.Builder.updateCameraStateWithCaptureResults( // the lens is restoring a non-1.0f target zoom so the UI doesn't flash 1x. val isInitialDefaultEmission = currentZoomRatio == null && - newZoomRatio == 1.0f && - targetZoomRatio != 1.0f + newZoomRatio != null && + kotlin.math.abs(newZoomRatio - 1.0f) < 0.001f && + !isTargetEssentiallyOne if (newZoomRatio != null && !isInitialDefaultEmission && currentZoomRatio != newZoomRatio diff --git a/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt b/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt index a398ffca7f..535f4918fa 100644 --- a/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt +++ b/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewScreen.kt @@ -95,7 +95,7 @@ import com.google.jetpackcamera.ui.components.capture.StabilizationIcon import com.google.jetpackcamera.ui.components.capture.TestableSnackbar import com.google.jetpackcamera.ui.components.capture.VIDEO_QUALITY_TAG import com.google.jetpackcamera.ui.components.capture.VideoQualityIcon -import com.google.jetpackcamera.ui.components.capture.ZoomButtonRow +import com.google.jetpackcamera.ui.components.capture.ZoomBar import com.google.jetpackcamera.ui.components.capture.ZoomStateManager import com.google.jetpackcamera.ui.components.capture.debouncedOrientationFlow import com.google.jetpackcamera.ui.components.capture.quicksettings.QuickSettingsScaffoldContent @@ -528,7 +528,7 @@ private fun ContentScreen( val zoomLevelDisplayLambda = remember(zoomControlState) { @Composable { modifier: Modifier -> Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) { - ZoomButtonRow( + ZoomBar( zoomControlUiState = zoomControlState.value, onChangeZoom = { targetZoom -> scope.launch { diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index 83a3a502de..7ca05ba8c2 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -15,28 +15,28 @@ */ package com.google.jetpackcamera.ui.components.capture -import androidx.compose.animation.animateColorAsState -import androidx.compose.animation.animateContentSize -import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState -import androidx.compose.animation.core.snap -import androidx.compose.animation.core.spring import androidx.compose.foundation.background -import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicText import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue @@ -44,44 +44,32 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.geometry.CornerRadius -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size +import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.onClick import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.semantics.testTag +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.lerp +import androidx.compose.ui.unit.times import com.google.jetpackcamera.model.LensFacing import com.google.jetpackcamera.ui.uistate.capture.ZoomControlUiState -import java.math.RoundingMode -import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.util.Locale -import kotlin.math.round - -private val US_SYMBOLS = DecimalFormatSymbols(Locale.US) - -private val SUB_ONE_FORMATTER = ThreadLocal.withInitial { - DecimalFormat(".#", US_SYMBOLS).apply { - minimumIntegerDigits = 0 - setRoundingMode(RoundingMode.HALF_UP) - } -} - -private val DECIMAL_FORMATTER = ThreadLocal.withInitial { - DecimalFormat("#.#", US_SYMBOLS).apply { - setRoundingMode(RoundingMode.HALF_UP) - } -} +import kotlin.math.abs +import kotlin.math.floor /** * Styling configuration for [ZoomBar]. @@ -105,18 +93,13 @@ data class ZoomBarColors( * Default color palettes and dimensions for [ZoomBar]. */ object ZoomBarDefaults { - val HorizontalItemWidth = 40.dp - val HorizontalItemHeight = 36.dp - val VerticalItemWidth = 40.dp - val VerticalItemHeight = 40.dp - val HorizontalEndPadding = 6.dp - val VerticalEndPadding = 4.dp - val HorizontalClearance = 4.dp - - val TrackShape = RoundedCornerShape(56.dp) - val IndicatorCornerRadius = 12.dp - val IndicatorShape = RoundedCornerShape(IndicatorCornerRadius) - val UnselectedIndicatorSize = 32.dp + val SlotSize = 48.dp + val IndicatorHeight = ButtonDefaults.MinHeight // 40.dp + val IndicatorWidth = 48.dp + val Inset = (SlotSize - IndicatorHeight) / 2 // 4.dp + val TrackShape = CircleShape + val IndicatorShape = RoundedCornerShape(12.dp) + const val MAX_LABEL_FONT_SCALE = 1.3f /** * Default dynamic colors adapting to viewfinder overlap via [LocalCameraControlBackgroundStyle] @@ -140,7 +123,7 @@ object ZoomBarDefaults { */ @Composable fun black60Colors( - trackColor: Color = Color.Black.copy(alpha = 0.60f), + trackColor: Color = CameraControlBackgroundStyle.BLACK_60.containerColor, selectedIndicatorColor: Color = MaterialTheme.colorScheme.primaryFixed, selectedContentColor: Color = MaterialTheme.colorScheme.onPrimaryFixed, unselectedContentColor: Color = Color.White @@ -156,7 +139,7 @@ object ZoomBarDefaults { */ @Composable fun white20Colors( - trackColor: Color = Color.White.copy(alpha = 0.20f), + trackColor: Color = CameraControlBackgroundStyle.WHITE_20.containerColor, selectedIndicatorColor: Color = MaterialTheme.colorScheme.primaryFixed, selectedContentColor: Color = MaterialTheme.colorScheme.onPrimaryFixed, unselectedContentColor: Color = Color.White @@ -168,21 +151,35 @@ object ZoomBarDefaults { ) } +/** + * Rounds a zoom ratio half-up to the nearest tenth. + */ +internal fun toTenths(value: Float): Int = floor(value * 10f + 0.5f).toInt() + /** * Formats zoom ratios for camera controls: * - Unselected stops: ".5", "1", "2", "5" (no leading zero, no multiplication symbol). * - Selected stop: ".5×", "1×", "2×", "5×" (with Unicode multiplication symbol \u00D7). * - In-between ratios (e.g. while pinching): "1.4×". + * Respects the given [locale]'s decimal separator. */ -internal fun formatZoomLabel(targetZoom: Float, currentRatio: Float, isSelected: Boolean): String { +internal fun formatZoomLabel( + targetZoom: Float, + currentRatio: Float, + isSelected: Boolean, + locale: Locale = Locale.getDefault() +): String { val valueToFormat = if (isSelected) currentRatio else targetZoom - val formattedNumber = if (valueToFormat < 1f && valueToFormat > 0f) { - val formatted = SUB_ONE_FORMATTER.get()!!.format(valueToFormat) - if (formatted == "1" || formatted == "1.0") "1" else formatted - } else if (valueToFormat % 1.0f == 0f) { - valueToFormat.toInt().toString() + val tenths = toTenths(valueToFormat) + val whole = tenths / 10 + val fraction = tenths % 10 + val decimalSeparator = DecimalFormatSymbols.getInstance(locale).decimalSeparator + val formattedNumber = if (whole == 0) { + "$decimalSeparator$fraction" + } else if (fraction == 0) { + whole.toString() } else { - DECIMAL_FORMATTER.get()!!.format(valueToFormat) + "$whole$decimalSeparator$fraction" } return if (isSelected) { "$formattedNumber\u00D7" @@ -191,9 +188,12 @@ internal fun formatZoomLabel(targetZoom: Float, currentRatio: Float, isSelected: } } +private fun ZoomControlUiState.Enabled.displayZoomRatio(): Float = + primarySettingZoomRatio ?: primaryZoomRatio ?: initialZoomRatio ?: 1f + /** * A composable that displays zoom controls formatted as a unified capsule track - * with a selected indicator pill appearing on the active stop. + * with a sliding indicator pill that smoothly tracks the active zoom stop. * * @param zoomControlUiState The [ZoomControlUiState] providing available zoom levels and * current ratio. @@ -201,33 +201,44 @@ internal fun formatZoomLabel(targetZoom: Float, currentRatio: Float, isSelected: * @param modifier Modifier for the component. * @param orientation Layout orientation ([Orientation.Horizontal] or [Orientation.Vertical]), * allowing flexible placement across portrait phones, landscape mode, and open foldables/tablets. + * @param contentRotation Rotation angle in degrees to accommodate current device orientation + * by rotating the text content in-place without altering track layout geometry. * @param colors Styling configuration for track and indicator colors. */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable fun ZoomBar( zoomControlUiState: ZoomControlUiState, onChangeZoom: (Float) -> Unit, modifier: Modifier = Modifier, orientation: Orientation = Orientation.Horizontal, + contentRotation: Float = 0f, colors: ZoomBarColors = ZoomBarDefaults.colors() ) { if (zoomControlUiState is ZoomControlUiState.Enabled) { val currentZoomState by rememberUpdatedState(zoomControlUiState) val selectedOptionIndex: Int by remember(zoomControlUiState.primaryLensFacing) { derivedStateOf { - // If animating towards a value, select that target; otherwise find closest - // matching stop - val checkValue = - currentZoomState.animatingToValue - ?: currentZoomState.primaryZoomRatio - ?: currentZoomState.initialZoomRatio - ?: 1f - val roundedCheckValue = round(checkValue * 10f) / 10f + val checkValue = currentZoomState.animatingToValue + ?: currentZoomState.displayZoomRatio() + val checkTenths = toTenths(checkValue) val index = currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> - val roundedOption = round(zoomLevelOption * 10f) / 10f - roundedCheckValue >= roundedOption + toTenths(zoomLevelOption) <= checkTenths + } + if (index >= 0) { + if (index > 0 && + toTenths(currentZoomState.zoomLevels[index]) == + toTenths(currentZoomState.zoomLevels[index - 1]) + ) { + val distCurrent = abs(currentZoomState.zoomLevels[index] - checkValue) + val distPrev = abs(currentZoomState.zoomLevels[index - 1] - checkValue) + if (distPrev < distCurrent) index - 1 else index + } else { + index + } + } else { + 0 } - if (index >= 0) index else 0 } } @@ -235,6 +246,12 @@ fun ZoomBar( if (zoomLevels.isEmpty()) return val validIndex = selectedOptionIndex.coerceIn(0, zoomLevels.size - 1) + val indicatorPosition by animateFloatAsState( + targetValue = validIndex.toFloat(), + animationSpec = MaterialTheme.motionScheme.defaultSpatialSpec(), + label = "zoomIndicatorPosition" + ) + val currentRatioProvider = remember { { currentZoomState.primaryZoomRatio @@ -243,35 +260,13 @@ fun ZoomBar( } } - val itemWidth = if (orientation == Orientation.Horizontal) { - ZoomBarDefaults.HorizontalItemWidth - } else { - ZoomBarDefaults.VerticalItemWidth - } - val itemHeight = if (orientation == Orientation.Horizontal) { - ZoomBarDefaults.HorizontalItemHeight - } else { - ZoomBarDefaults.VerticalItemHeight - } + val totalAlongTrack = ZoomBarDefaults.SlotSize * zoomLevels.size + ZoomBarDefaults.Inset * 2 + val totalAcrossTrack = ZoomBarDefaults.SlotSize - val endPadding = if (orientation == Orientation.Horizontal) { - ZoomBarDefaults.HorizontalEndPadding - } else { - ZoomBarDefaults.VerticalEndPadding - } - - // In horizontal, clearance exists on all sides; in vertical, buttons are flush with - // the vertical sides. - val totalWidth = if (orientation == Orientation.Horizontal) { - itemWidth * zoomLevels.size + endPadding * 2 - } else { - itemWidth - } - val totalHeight = if (orientation == Orientation.Horizontal) { - itemHeight + ZoomBarDefaults.HorizontalClearance * 2 - } else { - itemHeight * zoomLevels.size + endPadding * 2 - } + val totalWidth = + if (orientation == Orientation.Horizontal) totalAlongTrack else totalAcrossTrack + val totalHeight = + if (orientation == Orientation.Horizontal) totalAcrossTrack else totalAlongTrack Box( modifier = modifier @@ -279,51 +274,77 @@ fun ZoomBar( .background(color = colors.trackColor, shape = ZoomBarDefaults.TrackShape) .semantics { testTag = ZOOM_BUTTON_ROW_TAG - stateDescription = zoomControlUiState.primaryZoomRatio.toString() } ) { - // Stops if (orientation == Orientation.Horizontal) { + Box( + modifier = Modifier + .offset { + IntOffset( + x = ( + ZoomBarDefaults.Inset + + indicatorPosition * ZoomBarDefaults.SlotSize + ).roundToPx(), + y = ZoomBarDefaults.Inset.roundToPx() + ) + } + .size(ZoomBarDefaults.IndicatorWidth, ZoomBarDefaults.IndicatorHeight) + .background(colors.selectedIndicatorColor, MaterialTheme.shapes.medium) + ) + Row( modifier = Modifier .fillMaxSize() - .padding( - horizontal = endPadding, - vertical = ZoomBarDefaults.HorizontalClearance - ), + .selectableGroup() + .padding(horizontal = ZoomBarDefaults.Inset), verticalAlignment = Alignment.CenterVertically ) { zoomLevels.forEachIndexed { index, value -> - val isSelected = index == validIndex ZoomBarItem( value = value, currentRatioProvider = currentRatioProvider, - isSelected = isSelected, + isSelected = index == validIndex, + indicatorPositionProvider = { indicatorPosition }, + itemIndex = index, colors = colors, - itemWidth = itemWidth, - itemHeight = itemHeight, - modifier = Modifier.size(itemWidth, itemHeight), + contentRotation = contentRotation, onClick = { onChangeZoom(value) } ) } } } else { + Box( + modifier = Modifier + .offset { + IntOffset( + x = 0, + y = ( + ZoomBarDefaults.Inset + + indicatorPosition * ZoomBarDefaults.SlotSize + + ZoomBarDefaults.Inset + ).roundToPx() + ) + } + .size(ZoomBarDefaults.SlotSize, ZoomBarDefaults.IndicatorHeight) + .background(colors.selectedIndicatorColor, MaterialTheme.shapes.medium) + ) + Column( modifier = Modifier .fillMaxSize() - .padding(vertical = endPadding), + .selectableGroup() + .padding(vertical = ZoomBarDefaults.Inset), horizontalAlignment = Alignment.CenterHorizontally ) { zoomLevels.forEachIndexed { index, value -> - val isSelected = index == validIndex ZoomBarItem( value = value, currentRatioProvider = currentRatioProvider, - isSelected = isSelected, + isSelected = index == validIndex, + indicatorPositionProvider = { indicatorPosition }, + itemIndex = index, colors = colors, - itemWidth = itemWidth, - itemHeight = itemHeight, - modifier = Modifier.size(itemWidth, itemHeight), + contentRotation = contentRotation, onClick = { onChangeZoom(value) } ) } @@ -338,9 +359,10 @@ private fun ZoomBarItem( value: Float, currentRatioProvider: () -> Float, isSelected: Boolean, + indicatorPositionProvider: () -> Float, + itemIndex: Int, colors: ZoomBarColors, - itemWidth: Dp, - itemHeight: Dp, + contentRotation: Float = 0f, modifier: Modifier = Modifier, onClick: () -> Unit ) { @@ -354,94 +376,101 @@ private fun ZoomBarItem( } } - val unselectedSize = (if (itemWidth < itemHeight) itemWidth else itemHeight) - .coerceAtMost(ZoomBarDefaults.UnselectedIndicatorSize) - val unselectedCornerRadius = unselectedSize / 2 - - val indicatorProgress by animateFloatAsState( - targetValue = if (isSelected) 1f else 0f, - animationSpec = if (isSelected) { - spring( - dampingRatio = Spring.DampingRatioMediumBouncy, - stiffness = Spring.StiffnessMediumLow - ) + val labelText = remember(displayText) { + if (displayText.endsWith('×')) { + buildAnnotatedString { + append(displayText.dropLast(1)) + pushStyle(SpanStyle(fontWeight = FontWeight.Bold)) + append('×') + pop() + } } else { - snap() - }, - label = "zoomIndicatorProgress" - ) + AnnotatedString(displayText) + } + } - val contentColor by animateColorAsState( - targetValue = if (isSelected) { - colors.selectedContentColor - } else { - colors.unselectedContentColor - }, - label = "zoomItemContentColor" + val accessibleZoomLabel = if (value % 1.0f == 0f) { + "${value.toInt()}x" + } else { + "${value}x" + } + + val density = LocalDensity.current + + val onClickLabel = stringResource(R.string.zoom_stop_click_label, accessibleZoomLabel) + + val animatedRotation by animateFloatAsState( + targetValue = contentRotation, + animationSpec = MaterialTheme.motionScheme.defaultSpatialSpec(), + label = "zoomTextRotation" ) Box( modifier = modifier - .drawBehind { - val progress = indicatorProgress - if (isSelected || progress > 0f) { - val width = lerp(unselectedSize, itemWidth, progress).toPx().coerceAtLeast(0f) - val height = lerp(unselectedSize, itemHeight, progress).toPx().coerceAtLeast(0f) - val cornerRadius = lerp( - unselectedCornerRadius, - ZoomBarDefaults.IndicatorCornerRadius, - progress - ).toPx().coerceAtLeast(0f) - drawRoundRect( - color = colors.selectedIndicatorColor, - topLeft = Offset( - x = (size.width - width) / 2f, - y = (size.height - height) / 2f - ), - size = Size(width = width, height = height), - cornerRadius = CornerRadius(cornerRadius, cornerRadius) - ) - } - } - .clickable( + .size(ZoomBarDefaults.SlotSize) + .selectable( + selected = isSelected, + role = Role.RadioButton, interactionSource = remember { MutableInteractionSource() }, indication = null, - role = Role.RadioButton, onClick = onClick ) .semantics { testTag = getZoomButtonTestTag(value) - selected = isSelected + onClick(label = onClickLabel) { + onClick() + true + } }, contentAlignment = Alignment.Center ) { - Text( - modifier = Modifier.animateContentSize(), - text = displayText, - style = MaterialTheme.typography.labelMedium.copy( - fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium - ), - color = contentColor, - textAlign = TextAlign.Center, - maxLines = 1 - ) + CompositionLocalProvider( + LocalDensity provides Density( + density = density.density, + fontScale = density.fontScale.coerceAtMost(ZoomBarDefaults.MAX_LABEL_FONT_SCALE) + ) + ) { + BasicText( + text = labelText, + style = MaterialTheme.typography.labelLarge.copy( + textAlign = TextAlign.Center + ), + color = { + lerp( + colors.unselectedContentColor, + colors.selectedContentColor, + (1f - abs(indicatorPositionProvider() - itemIndex)).coerceIn(0f, 1f) + ) + }, + modifier = Modifier + .wrapContentSize(unbounded = true) + .rotate(animatedRotation) + .padding(horizontal = 2.dp), + softWrap = false + ) + } } } /** * A composable that displays a row of zoom buttons. * - * Maintained as a delegate to [ZoomBar] for backward compatibility with existing callers. - * - * @param onChangeZoom the callback for when the zoom changes - * @param modifier the modifier for this component - * @param zoomControlUiState the [ZoomControlUiState] for this component - * @param buttonSize the size of the buttons (retained for backward compatibility) - * @param spacing the spacing between the buttons (retained for backward compatibility) - * @param orientation the layout orientation ([Orientation.Horizontal] or [Orientation.Vertical]) - * @param colors the [ZoomBarColors] styling configuration for track and indicator colors + * @deprecated Use [ZoomBar] directly. */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Deprecated( + message = "Use ZoomBar directly.", + replaceWith = ReplaceWith( + "ZoomBar(" + + "zoomControlUiState = zoomControlUiState, " + + "onChangeZoom = onChangeZoom, " + + "modifier = modifier, " + + "orientation = orientation, " + + "contentRotation = contentRotation, " + + "colors = colors" + + ")", + "com.google.jetpackcamera.ui.components.capture.ZoomBar" + ) +) @Composable fun ZoomButtonRow( onChangeZoom: (Float) -> Unit, @@ -450,6 +479,7 @@ fun ZoomButtonRow( buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, spacing: Dp = 16.dp, orientation: Orientation = Orientation.Horizontal, + contentRotation: Float = 0f, colors: ZoomBarColors = ZoomBarDefaults.colors() ) { ZoomBar( @@ -457,6 +487,7 @@ fun ZoomButtonRow( onChangeZoom = onChangeZoom, modifier = modifier, orientation = orientation, + contentRotation = contentRotation, colors = colors ) } @@ -567,31 +598,9 @@ private fun ZoomBarVerticalDarkPreview() { } } -@Preview(name = "Vertical 20% White - Flush Sides", showBackground = true) -@Composable -private fun ZoomBarVerticalTranslucentPreview() { - Box( - modifier = Modifier - .background(Color(0xFF2B2B2B)) - .padding(16.dp), - contentAlignment = Alignment.Center - ) { - ZoomBar( - zoomControlUiState = ZoomControlUiState.Enabled( - zoomLevels = listOf(0.5f, 1.0f, 2.0f, 5.0f), - primaryLensFacing = LensFacing.BACK, - primaryZoomRatio = 1.0f - ), - onChangeZoom = {}, - orientation = Orientation.Vertical, - colors = ZoomBarDefaults.white20Colors() - ) - } -} - -@Preview(name = "Single Value Range (1.0x only)", showBackground = true) +@Preview(name = "Single Stop (1x Only)", showBackground = true) @Composable -private fun ZoomBarSingleValuePreview() { +private fun ZoomBarSingleStopPreview() { Box( modifier = Modifier .background(Color(0xFF2B2B2B)) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt index 128ffef6e9..5d03f3a450 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomStateManager.kt @@ -164,9 +164,9 @@ class ZoomStateManager( ) ) } + zoomController.setZoomAnimationState(null) } finally { currentAnimationTarget = null - zoomController.setZoomAnimationState(null) } } } diff --git a/ui/components/capture/src/main/res/values/strings.xml b/ui/components/capture/src/main/res/values/strings.xml index e7858b6a28..23afd80692 100644 --- a/ui/components/capture/src/main/res/values/strings.xml +++ b/ui/components/capture/src/main/res/values/strings.xml @@ -183,4 +183,7 @@ Dismiss + + + Zoom to %1$s \ No newline at end of file diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt index 5d4a203292..fec03e55f0 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt @@ -16,6 +16,7 @@ package com.google.jetpackcamera.ui.components.capture import com.google.common.truth.Truth.assertThat +import java.util.Locale import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @@ -25,37 +26,157 @@ class ZoomBarComponentsTest { @Test fun formatZoomLabel_unselectedStops_formatsWithoutMultiplierOrLeadingZero() { - assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 1.0f, isSelected = false)) - .isEqualTo(".5") - assertThat(formatZoomLabel(targetZoom = 1.0f, currentRatio = 1.0f, isSelected = false)) - .isEqualTo("1") - assertThat(formatZoomLabel(targetZoom = 2.0f, currentRatio = 1.0f, isSelected = false)) - .isEqualTo("2") - assertThat(formatZoomLabel(targetZoom = 5.0f, currentRatio = 1.0f, isSelected = false)) - .isEqualTo("5") - assertThat(formatZoomLabel(targetZoom = 10.0f, currentRatio = 1.0f, isSelected = false)) - .isEqualTo("10") + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo(".5") + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo("1") + assertThat( + formatZoomLabel( + targetZoom = 2.0f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo("2") + assertThat( + formatZoomLabel( + targetZoom = 5.0f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo("5") + assertThat( + formatZoomLabel( + targetZoom = 10.0f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.US + ) + ).isEqualTo("10") } @Test fun formatZoomLabel_selectedStops_formatsWithMultiplier() { - assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 0.5f, isSelected = true)) - .isEqualTo(".5\u00D7") - assertThat(formatZoomLabel(targetZoom = 1.0f, currentRatio = 1.0f, isSelected = true)) - .isEqualTo("1\u00D7") - assertThat(formatZoomLabel(targetZoom = 2.0f, currentRatio = 2.0f, isSelected = true)) - .isEqualTo("2\u00D7") - assertThat(formatZoomLabel(targetZoom = 5.0f, currentRatio = 5.0f, isSelected = true)) - .isEqualTo("5\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 0.5f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo(".5\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 1.0f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("1\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 2.0f, + currentRatio = 2.0f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("2\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 5.0f, + currentRatio = 5.0f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("5\u00D7") } @Test fun formatZoomLabel_inBetweenPinchRatio_formatsCurrentRatio() { - assertThat(formatZoomLabel(targetZoom = 1.0f, currentRatio = 1.4f, isSelected = true)) - .isEqualTo("1.4\u00D7") - assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 0.7f, isSelected = true)) - .isEqualTo(".7\u00D7") - assertThat(formatZoomLabel(targetZoom = 0.5f, currentRatio = 0.99f, isSelected = true)) - .isEqualTo("1\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 1.4f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("1.4\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 0.7f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo(".7\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 0.99f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("1\u00D7") + } + + @Test + fun formatZoomLabel_halfUpBoundaryCases_roundsCorrectly() { + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 0.95f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("1\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 5.0f, + currentRatio = 4.95f, + isSelected = true, + locale = Locale.US + ) + ).isEqualTo("5\u00D7") + } + + @Test + fun formatZoomLabel_localeWithCommaSeparator_usesLocalizedDecimalSeparator() { + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 0.5f, + isSelected = true, + locale = Locale.GERMANY + ) + ).isEqualTo(",5\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 1.0f, + currentRatio = 1.4f, + isSelected = true, + locale = Locale.GERMANY + ) + ).isEqualTo("1,4\u00D7") + assertThat( + formatZoomLabel( + targetZoom = 0.5f, + currentRatio = 1.0f, + isSelected = false, + locale = Locale.GERMANY + ) + ).isEqualTo(",5") } } diff --git a/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt b/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt index 77d6fafd8e..01124a8b56 100644 --- a/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt +++ b/ui/controller/impl/src/main/java/com/google/jetpackcamera/ui/controller/impl/ZoomControllerImpl.kt @@ -50,12 +50,16 @@ class ZoomControllerImpl( if (zoomRatio.changeType is ZoomStrategy.Absolute) { when (zoomRatio.changeType.lensToZoom) { LensToZoom.PRIMARY -> { + // Drop pending zoom updates while the camera system is still initializing; + // once cameraSystemProvider() resolves, launches on Dispatchers.Main.immediate + // execute synchronously. primaryZoomJob?.cancel() primaryZoomJob = scope.launch { cameraSystemProvider().changeZoomRatio(newZoomState = zoomRatio) } } LensToZoom.SECONDARY -> { + // Drop pending zoom updates while the camera system is still initializing. secondaryZoomJob?.cancel() secondaryZoomJob = scope.launch { cameraSystemProvider().changeZoomRatio(newZoomState = zoomRatio) From d5c3492263fabf84de5360280bf579a985e69e8f Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 27 Oct 2026 08:35:39 -0700 Subject: [PATCH 11/14] Address PR review feedback on ZoomBar label, selection, and accessibility - Drop contentRotation from ZoomBar and ZoomButtonRow in favor of upright modifier - Remove unused IndicatorShape and alias IndicatorWidth to SlotSize - Update currentRatioProvider to prioritize target ratio during tap animation - Extract formatAccessibleZoomLabel with leading zero and localized decimal separator - Move multiplication symbol into zoom_stop_click_label string resource - Extract selectedZoomStopIndex and add unit tests for rounding and tie-breaking - Use imported abs in CameraSession --- .../core/camera/CameraSession.kt | 4 +- .../components/capture/ZoomBarComponents.kt | 98 +++++++++---------- .../capture/src/main/res/values/strings.xml | 4 +- .../capture/ZoomBarComponentsTest.kt | 30 ++++++ 4 files changed, 83 insertions(+), 53 deletions(-) diff --git a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt index e0b9704803..7e7f70c3bc 100644 --- a/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt +++ b/core/camera/src/main/java/com/google/jetpackcamera/core/camera/CameraSession.kt @@ -1501,7 +1501,7 @@ private fun Preview.Builder.updateCameraStateWithCaptureResults( val minZoom = zoomState?.minZoomRatio ?: 1.0f val maxZoom = zoomState?.maxZoomRatio ?: 1.0f val clampedTarget = targetZoomRatio.coerceIn(minZoom, maxZoom) - val isTargetEssentiallyOne = kotlin.math.abs(clampedTarget - 1.0f) < 0.01f + val isTargetEssentiallyOne = abs(clampedTarget - 1.0f) < 0.01f currentCameraState.update { old -> val currentZoomRatio = old.zoomRatios[targetCameraInfo.appLensFacing] // When a lens is newly bound, initial capture results emit the hardware @@ -1511,7 +1511,7 @@ private fun Preview.Builder.updateCameraStateWithCaptureResults( val isInitialDefaultEmission = currentZoomRatio == null && newZoomRatio != null && - kotlin.math.abs(newZoomRatio - 1.0f) < 0.001f && + abs(newZoomRatio - 1.0f) < 0.001f && !isTargetEssentiallyOne if (newZoomRatio != null && !isInitialDefaultEmission && diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index 7ca05ba8c2..5fd03c821d 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -30,7 +30,6 @@ import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicText import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi @@ -44,7 +43,6 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.lerp import androidx.compose.ui.platform.LocalDensity @@ -95,10 +93,8 @@ data class ZoomBarColors( object ZoomBarDefaults { val SlotSize = 48.dp val IndicatorHeight = ButtonDefaults.MinHeight // 40.dp - val IndicatorWidth = 48.dp val Inset = (SlotSize - IndicatorHeight) / 2 // 4.dp val TrackShape = CircleShape - val IndicatorShape = RoundedCornerShape(12.dp) const val MAX_LABEL_FONT_SCALE = 1.3f /** @@ -156,6 +152,51 @@ object ZoomBarDefaults { */ internal fun toTenths(value: Float): Int = floor(value * 10f + 0.5f).toInt() +/** + * Determines the index of the selected zoom stop for a given [zoomRatio]. + * + * Stops are matched against the half-up rounded tenth of [zoomRatio]. If adjacent stops round + * to the same tenth (e.g. 0.96x and 1.0x both round to 1.0x), the stop closest in absolute + * difference to [zoomRatio] is selected. + */ +internal fun selectedZoomStopIndex(zoomLevels: List, zoomRatio: Float): Int { + if (zoomLevels.isEmpty()) return 0 + val checkTenths = toTenths(zoomRatio) + val index = zoomLevels.indexOfLast { zoomLevelOption -> + toTenths(zoomLevelOption) <= checkTenths + } + return if (index >= 0) { + if (index > 0 && + toTenths(zoomLevels[index]) == toTenths(zoomLevels[index - 1]) + ) { + val distCurrent = abs(zoomLevels[index] - zoomRatio) + val distPrev = abs(zoomLevels[index - 1] - zoomRatio) + if (distPrev < distCurrent) index - 1 else index + } else { + index + } + } else { + 0 + } +} + +/** + * Formats a zoom value for speech / accessibility announcements (e.g. "0.5", "1", "2"). + * + * Keeps the leading zero for speech clarity and respects the given [locale]'s decimal separator. + */ +internal fun formatAccessibleZoomLabel(value: Float, locale: Locale = Locale.getDefault()): String { + val tenths = toTenths(value) + val whole = tenths / 10 + val fraction = tenths % 10 + val decimalSeparator = DecimalFormatSymbols.getInstance(locale).decimalSeparator + return if (fraction == 0) { + whole.toString() + } else { + "$whole$decimalSeparator$fraction" + } +} + /** * Formats zoom ratios for camera controls: * - Unselected stops: ".5", "1", "2", "5" (no leading zero, no multiplication symbol). @@ -201,8 +242,6 @@ private fun ZoomControlUiState.Enabled.displayZoomRatio(): Float = * @param modifier Modifier for the component. * @param orientation Layout orientation ([Orientation.Horizontal] or [Orientation.Vertical]), * allowing flexible placement across portrait phones, landscape mode, and open foldables/tablets. - * @param contentRotation Rotation angle in degrees to accommodate current device orientation - * by rotating the text content in-place without altering track layout geometry. * @param colors Styling configuration for track and indicator colors. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @@ -212,7 +251,6 @@ fun ZoomBar( onChangeZoom: (Float) -> Unit, modifier: Modifier = Modifier, orientation: Orientation = Orientation.Horizontal, - contentRotation: Float = 0f, colors: ZoomBarColors = ZoomBarDefaults.colors() ) { if (zoomControlUiState is ZoomControlUiState.Enabled) { @@ -221,24 +259,7 @@ fun ZoomBar( derivedStateOf { val checkValue = currentZoomState.animatingToValue ?: currentZoomState.displayZoomRatio() - val checkTenths = toTenths(checkValue) - val index = currentZoomState.zoomLevels.indexOfLast { zoomLevelOption -> - toTenths(zoomLevelOption) <= checkTenths - } - if (index >= 0) { - if (index > 0 && - toTenths(currentZoomState.zoomLevels[index]) == - toTenths(currentZoomState.zoomLevels[index - 1]) - ) { - val distCurrent = abs(currentZoomState.zoomLevels[index] - checkValue) - val distPrev = abs(currentZoomState.zoomLevels[index - 1] - checkValue) - if (distPrev < distCurrent) index - 1 else index - } else { - index - } - } else { - 0 - } + selectedZoomStopIndex(currentZoomState.zoomLevels, checkValue) } } @@ -253,11 +274,7 @@ fun ZoomBar( ) val currentRatioProvider = remember { - { - currentZoomState.primaryZoomRatio - ?: currentZoomState.initialZoomRatio - ?: 1f - } + { currentZoomState.animatingToValue ?: currentZoomState.displayZoomRatio() } } val totalAlongTrack = ZoomBarDefaults.SlotSize * zoomLevels.size + ZoomBarDefaults.Inset * 2 @@ -288,7 +305,7 @@ fun ZoomBar( y = ZoomBarDefaults.Inset.roundToPx() ) } - .size(ZoomBarDefaults.IndicatorWidth, ZoomBarDefaults.IndicatorHeight) + .size(ZoomBarDefaults.SlotSize, ZoomBarDefaults.IndicatorHeight) .background(colors.selectedIndicatorColor, MaterialTheme.shapes.medium) ) @@ -307,7 +324,6 @@ fun ZoomBar( indicatorPositionProvider = { indicatorPosition }, itemIndex = index, colors = colors, - contentRotation = contentRotation, onClick = { onChangeZoom(value) } ) } @@ -344,7 +360,6 @@ fun ZoomBar( indicatorPositionProvider = { indicatorPosition }, itemIndex = index, colors = colors, - contentRotation = contentRotation, onClick = { onChangeZoom(value) } ) } @@ -362,7 +377,6 @@ private fun ZoomBarItem( indicatorPositionProvider: () -> Float, itemIndex: Int, colors: ZoomBarColors, - contentRotation: Float = 0f, modifier: Modifier = Modifier, onClick: () -> Unit ) { @@ -389,22 +403,12 @@ private fun ZoomBarItem( } } - val accessibleZoomLabel = if (value % 1.0f == 0f) { - "${value.toInt()}x" - } else { - "${value}x" - } + val accessibleZoomLabel = formatAccessibleZoomLabel(value) val density = LocalDensity.current val onClickLabel = stringResource(R.string.zoom_stop_click_label, accessibleZoomLabel) - val animatedRotation by animateFloatAsState( - targetValue = contentRotation, - animationSpec = MaterialTheme.motionScheme.defaultSpatialSpec(), - label = "zoomTextRotation" - ) - Box( modifier = modifier .size(ZoomBarDefaults.SlotSize) @@ -444,7 +448,6 @@ private fun ZoomBarItem( }, modifier = Modifier .wrapContentSize(unbounded = true) - .rotate(animatedRotation) .padding(horizontal = 2.dp), softWrap = false ) @@ -465,7 +468,6 @@ private fun ZoomBarItem( "onChangeZoom = onChangeZoom, " + "modifier = modifier, " + "orientation = orientation, " + - "contentRotation = contentRotation, " + "colors = colors" + ")", "com.google.jetpackcamera.ui.components.capture.ZoomBar" @@ -479,7 +481,6 @@ fun ZoomButtonRow( buttonSize: Dp = ButtonDefaults.ExtraSmallContainerHeight, spacing: Dp = 16.dp, orientation: Orientation = Orientation.Horizontal, - contentRotation: Float = 0f, colors: ZoomBarColors = ZoomBarDefaults.colors() ) { ZoomBar( @@ -487,7 +488,6 @@ fun ZoomButtonRow( onChangeZoom = onChangeZoom, modifier = modifier, orientation = orientation, - contentRotation = contentRotation, colors = colors ) } diff --git a/ui/components/capture/src/main/res/values/strings.xml b/ui/components/capture/src/main/res/values/strings.xml index 23afd80692..4106fac29a 100644 --- a/ui/components/capture/src/main/res/values/strings.xml +++ b/ui/components/capture/src/main/res/values/strings.xml @@ -184,6 +184,6 @@ Dismiss - - Zoom to %1$s + + Zoom to %1$s× \ No newline at end of file diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt index fec03e55f0..2f876d37b1 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponentsTest.kt @@ -179,4 +179,34 @@ class ZoomBarComponentsTest { ) ).isEqualTo(",5") } + + @Test + fun selectedZoomStopIndex_roundsToTenthsAndResolvesTieBreak() { + val stops = listOf(0.5f, 1.0f, 2.0f, 5.0f) + + // 0.95 rounds half-up to 1.0 tenth -> selects index 1 (1.0x stop) + assertThat(selectedZoomStopIndex(stops, 0.95f)).isEqualTo(1) + + // 4.94 rounds to 4.9 tenths -> stays on index 2 (2.0x stop) + assertThat(selectedZoomStopIndex(stops, 4.94f)).isEqualTo(2) + + // 5.0f selects index 3 (5.0x stop) + assertThat(selectedZoomStopIndex(stops, 5.0f)).isEqualTo(3) + + // Adjacent stops rounding to same tenth: picks the closer stop + val adjacentStops = listOf(0.5f, 0.96f, 1.0f, 2.0f) + assertThat(selectedZoomStopIndex(adjacentStops, 0.97f)).isEqualTo(1) + assertThat(selectedZoomStopIndex(adjacentStops, 0.99f)).isEqualTo(2) + } + + @Test + fun formatAccessibleZoomLabel_roundsAndKeepsLeadingZero() { + // Pixel minimum zoom ~0.507 rounds to 0.5 with leading zero for speech + assertThat(formatAccessibleZoomLabel(0.50783783f, Locale.US)).isEqualTo("0.5") + assertThat(formatAccessibleZoomLabel(1.0f, Locale.US)).isEqualTo("1") + assertThat(formatAccessibleZoomLabel(2.0f, Locale.US)).isEqualTo("2") + assertThat(formatAccessibleZoomLabel(5.0f, Locale.US)).isEqualTo("5") + // Respects locale decimal separator + assertThat(formatAccessibleZoomLabel(0.50783783f, Locale.GERMANY)).isEqualTo("0,5") + } } From 50eae959adb016c76f46664546828fd5ffe2e77f Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 27 Oct 2026 08:40:40 -0700 Subject: [PATCH 12/14] Add TODO(#619) for label rotation modifier in ZoomBar --- .../jetpackcamera/ui/components/capture/ZoomBarComponents.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index 5fd03c821d..4939c9adac 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -434,6 +434,7 @@ private fun ZoomBarItem( fontScale = density.fontScale.coerceAtMost(ZoomBarDefaults.MAX_LABEL_FONT_SCALE) ) ) { + // TODO(#619): Apply Modifier.animateToUpright() to keep labels upright on rotation. BasicText( text = labelText, style = MaterialTheme.typography.labelLarge.copy( From 309e5843ceecd5942e12fe53d90e6444de30ad97 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 27 Oct 2026 08:41:43 -0700 Subject: [PATCH 13/14] Include PR link in TODO(#619) comment in ZoomBar --- .../jetpackcamera/ui/components/capture/ZoomBarComponents.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index 4939c9adac..5818c73938 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -434,7 +434,8 @@ private fun ZoomBarItem( fontScale = density.fontScale.coerceAtMost(ZoomBarDefaults.MAX_LABEL_FONT_SCALE) ) ) { - // TODO(#619): Apply Modifier.animateToUpright() to keep labels upright on rotation. + // TODO(#619): Apply Modifier.animateToUpright() to keep labels upright on rotation + // (https://github.com/google/jetpack-camera-app/pull/619). BasicText( text = labelText, style = MaterialTheme.typography.labelLarge.copy( From 2753a8a653a5aa4ff9afb695c278e0934e5f07d2 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 28 Oct 2026 11:56:18 -0700 Subject: [PATCH 14/14] Support LocalDisableAnimations for sliding indicator in ZoomBar --- .../ui/components/capture/ZoomBarComponents.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt index 5818c73938..42590e4793 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/ZoomBarComponents.kt @@ -16,6 +16,7 @@ package com.google.jetpackcamera.ui.components.capture import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.snap import androidx.compose.foundation.background import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.interaction.MutableInteractionSource @@ -267,9 +268,14 @@ fun ZoomBar( if (zoomLevels.isEmpty()) return val validIndex = selectedOptionIndex.coerceIn(0, zoomLevels.size - 1) + val disableAnimations = LocalDisableAnimations.current val indicatorPosition by animateFloatAsState( targetValue = validIndex.toFloat(), - animationSpec = MaterialTheme.motionScheme.defaultSpatialSpec(), + animationSpec = if (disableAnimations) { + snap() + } else { + MaterialTheme.motionScheme.defaultSpatialSpec() + }, label = "zoomIndicatorPosition" )