From 9da96f5b4b87a63ab4eb16fa96dc28b6000cab1b Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 29 Jul 2026 18:15:31 -0700 Subject: [PATCH 01/20] initial wip for tooltip component --- feature/preview/build.gradle.kts | 1 + .../feature/preview/PreviewScreen.kt | 51 ++- gradle/libs.versions.toml | 6 +- ui/components/build.gradle.kts | 2 + .../jetpackcamera/ui/components/Tooltip.kt | 344 ++++++++++++++++++ 5 files changed, 393 insertions(+), 11 deletions(-) create mode 100644 ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt diff --git a/feature/preview/build.gradle.kts b/feature/preview/build.gradle.kts index 54ab1c505d..49e3692bee 100644 --- a/feature/preview/build.gradle.kts +++ b/feature/preview/build.gradle.kts @@ -147,6 +147,7 @@ dependencies { testImplementation(project(":data:media:testing")) testImplementation(project(":core:common:testing")) implementation(project(":ui:components:capture")) + implementation(project(":ui:components")) implementation(project(":ui:controller")) implementation(project(":ui:controller:impl")) implementation(project(":ui:uistate")) 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 eff65479a2..d356beec9f 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 @@ -26,11 +26,14 @@ import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme @@ -71,6 +74,10 @@ import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.ImageCaptureEvent import com.google.jetpackcamera.model.LensToZoom import com.google.jetpackcamera.model.VideoCaptureEvent +import com.google.jetpackcamera.ui.components.BeakAlignment +import com.google.jetpackcamera.ui.components.BeakDirection +import com.google.jetpackcamera.ui.components.BeakStyle +import com.google.jetpackcamera.ui.components.TooltipIconButton import com.google.jetpackcamera.ui.components.capture.AmplitudeToggleButton import com.google.jetpackcamera.ui.components.capture.CAPTURE_MODE_TOGGLE_BUTTON import com.google.jetpackcamera.ui.components.capture.CaptureButton @@ -144,7 +151,7 @@ fun PreviewScreen( val isReady by remember { derivedStateOf { rawUiState.value is CaptureUiState.Ready } } val surfaceRequest: SurfaceRequest? - by viewModel.surfaceRequest.collectAsState() + by viewModel.surfaceRequest.collectAsState() LifecycleStartEffect(Unit) { viewModel.cameraController.startCamera() @@ -190,7 +197,7 @@ fun PreviewScreen( { requireNotNull(rawUiState.value as? CaptureUiState.Ready) { "Deferred read invoked when state was not Ready. " + - "Current state: ${rawUiState.value}" + "Current state: ${rawUiState.value}" } } } @@ -280,7 +287,7 @@ private fun ContentScreen( } ZoomStateManager( initialZoomLevel = - (zoomControlState.value as? ZoomControlUiState.Enabled)?.initialZoomRatio ?: 1f, + (zoomControlState.value as? ZoomControlUiState.Enabled)?.initialZoomRatio ?: 1f, zoomRange = (zoomUiState.value as? ZoomUiState.Enabled) ?.primaryZoomRange ?: Range(1f, 1f), zoomController = safeZoomController @@ -290,7 +297,7 @@ private fun ContentScreen( LaunchedEffect((flipLensState.value as? FlipLensUiState.Available)?.selectedLensFacing) { zoomStateManager.onChangeLens( newInitialZoomLevel = - (zoomControlState.value as? ZoomControlUiState.Enabled)?.initialZoomRatio ?: 1f, + (zoomControlState.value as? ZoomControlUiState.Enabled)?.initialZoomRatio ?: 1f, newZoomRange = (zoomUiState.value as? ZoomUiState.Enabled) ?.primaryZoomRange ?: Range(1f, 1f) ) @@ -303,6 +310,7 @@ private fun ContentScreen( is VideoRecordingState.Starting -> { initialRecordingSettings = this.initialRecordingSettings } + is VideoRecordingState.Inactive -> { initialRecordingSettings?.let { val oldPrimaryLensFacing = it.lensFacing @@ -323,6 +331,7 @@ private fun ContentScreen( } initialRecordingSettings = null } + is VideoRecordingState.Active -> {} } } @@ -787,14 +796,36 @@ private fun LayoutWrapper( indicatorRow = { modifier -> Row( modifier = modifier - .fillMaxWidth(), + .fillMaxWidth() + .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp) ) { - flashModeIndicator(Modifier) - hdrIndicator(Modifier) - videoQualityIndicator(Modifier) - stabilizationIndicator(Modifier) + Row( + modifier = Modifier.weight(1f), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + flashModeIndicator(Modifier) + hdrIndicator(Modifier) + videoQualityIndicator(Modifier) + stabilizationIndicator(Modifier) + } + + TooltipIconButton( + icon = { + Box( + modifier = Modifier + .size(24.dp) + .background(Color.White, shape = CircleShape) + ) + }, + tooltipText = "This is a placeholder tooltip message. It demonstrates how text " + + "wraps and aligns with the beak pointing to the anchor.", + beakStyle = BeakStyle( + alignment = BeakAlignment.End, + direction = BeakDirection.Up + ) + ) } }, debugOverlay = { modifier -> diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 69f1d6c6d1..2cc2246f56 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -3,7 +3,7 @@ compileSdk = "36" desugar_jdk_libs = "2.1.5" orchestrator = "1.6.1" -minSdk = "23" +minSdk = "24" targetSdk = "35" # Used below in dependency definitions @@ -55,6 +55,8 @@ playServicesTasks = "18.4.0" cameraLowLightBoost = "16.0.1-beta06" material = "1.12.0" material3WindowSizeClass = "1.3.2" +uiToolingPreview = "1.11.4" +uiTooling = "1.11.4" [libraries] accompanist-permissions = { module = "com.google.accompanist:accompanist-permissions", version.ref = "accompanist" } @@ -114,6 +116,8 @@ robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectr truth = { module = "com.google.truth:truth", version.ref = "truth" } material = { group = "com.google.android.material", name = "material", version.ref = "material" } androidx-material3-window-size-klass = { group = "androidx.compose.material3", name = "material3-window-size-class", version.ref = "material3WindowSizeClass" } +androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview", version.ref = "uiToolingPreview" } +androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "uiTooling" } [plugins] android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" } diff --git a/ui/components/build.gradle.kts b/ui/components/build.gradle.kts index 02d3b2dca4..423069b94f 100644 --- a/ui/components/build.gradle.kts +++ b/ui/components/build.gradle.kts @@ -60,12 +60,14 @@ android { } dependencies { + implementation(libs.androidx.ui.tooling.preview) // Compose val composeBom = platform(libs.compose.bom) implementation(composeBom) // Compose - Material Design 3 implementation(libs.compose.material3) + debugImplementation(libs.androidx.ui.tooling) } // Allow references to generated code diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt new file mode 100644 index 0000000000..b03e76cea5 --- /dev/null +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -0,0 +1,344 @@ +/* + * 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 + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Alignment +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.RoundRect +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathOperation +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.foundation.layout.widthIn +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties + +/** + * A custom tooltip component that overlays the screen using a [Popup]. + * It should be placed inside a [Box] along with its anchor component. + * + * @param expanded Whether the tooltip is currently visible. + * @param onDismissRequest Called when the user taps outside the tooltip. + * @param modifier Modifier for the tooltip content. + * @param beakStyle Configuration for the beak's size, alignment, and direction. + * @param colors Colors for the tooltip container and content. + * @param content The content to display inside the tooltip (usually a Text composable). + */ +@Composable +fun Tooltip( + expanded: Boolean, + onDismissRequest: () -> Unit, + modifier: Modifier = Modifier, + beakStyle: BeakStyle = BeakStyle(), + colors: TooltipColors = TooltipDefaults.tooltipColors(), + maxWidth: Dp = TooltipDefaults.MaxWidth, + content: @Composable () -> Unit +) { + if (expanded) { + val density = LocalDensity.current + Popup( + popupPositionProvider = TooltipPositionProvider(beakStyle, density), + onDismissRequest = onDismissRequest, + properties = PopupProperties(focusable = true) + ) { + TooltipContent( + beakStyle = beakStyle, + colors = colors, + modifier = modifier.widthIn(max = maxWidth), + content = content + ) + } + } +} + +/** + * An icon button that shows a tooltip when clicked. + * + * @param icon The icon to display inside the button. + * @param tooltipText The text to display inside the tooltip. + * @param modifier Modifier for the button container. + * @param beakStyle Configuration for the tooltip's beak. + * @param colors Colors for the tooltip. + * @param onClick Optional callback when the button is clicked. + */ +@Composable +fun TooltipIconButton( + icon: @Composable () -> Unit, + tooltipText: String, + modifier: Modifier = Modifier, + beakStyle: BeakStyle = BeakStyle(), + colors: TooltipColors = TooltipDefaults.tooltipColors(), + maxWidth: Dp = TooltipDefaults.MaxWidth, + onClick: () -> Unit = {} +) { + var showTooltip by remember { mutableStateOf(false) } + Box(modifier = modifier) { + IconButton(onClick = { + showTooltip = true + onClick() + }) { + icon() + } + Tooltip( + expanded = showTooltip, + onDismissRequest = { showTooltip = false }, + beakStyle = beakStyle, + colors = colors, + maxWidth = maxWidth + ) { + Text( + text = tooltipText, + textAlign = TextAlign.Center, + style = MaterialTheme.typography.labelLarge + ) + } + } +} + +/** + * The visual content of the tooltip, including the custom shape. + */ +@Composable +private fun TooltipContent( + beakStyle: BeakStyle, + colors: TooltipColors, + modifier: Modifier = Modifier, + content: @Composable () -> Unit +) { + val shape = TooltipShape(beakStyle) + val containerColor = colors.containerColor.takeOrElse { + MaterialTheme.colorScheme.secondaryFixed + } + val contentColor = colors.contentColor.takeOrElse { + MaterialTheme.colorScheme.onSecondaryFixed + } + + val topPadding = if (beakStyle.direction == BeakDirection.Up) { + 16.dp + beakStyle.height + } else { + 16.dp + } + val bottomPadding = if (beakStyle.direction == BeakDirection.Down) { + 16.dp + beakStyle.height + } else { + 16.dp + } + + CompositionLocalProvider(LocalContentColor provides contentColor) { + Box( + modifier = modifier + .background(color = containerColor, shape = shape) + .padding( + start = 16.dp, + top = topPadding, + end = 16.dp, + bottom = bottomPadding + ), + contentAlignment = Alignment.Center + ) { + // We might need to adjust content color here if it's text + content() + } + } +} + +/** + * Configuration for the tooltip's beak (arrow). + * + * @param width The width of the beak base. + * @param height The height of the beak. + * @param alignment Horizontal alignment of the beak relative to the tooltip body. + * @param direction Direction the beak points (Up or Down). + * @param offset Optional horizontal offset from the alignment position. + */ +data class BeakStyle( + val width: Dp = 24.dp, + val height: Dp = 8.dp, + val alignment: BeakAlignment = BeakAlignment.End, + val direction: BeakDirection = BeakDirection.Up, + val offset: Dp = 0.dp +) + +enum class BeakAlignment { + Start, Center, End +} + +enum class BeakDirection { + Up, Down +} + +data class TooltipColors( + val containerColor: Color = Color.Unspecified,// + val contentColor: Color = Color.Unspecified +) + +object TooltipDefaults { + val MaxWidth: Dp = 296.dp + + @Composable + fun tooltipColors( + containerColor: Color = Color.Unspecified, + contentColor: Color = Color.Unspecified + ): TooltipColors = TooltipColors(containerColor, contentColor) +} + +/** + * A custom [Shape] that draws a rounded rectangle with a beak. + */ +private class TooltipShape( + private val beakStyle: BeakStyle +) : Shape { + override fun createOutline( + size: Size, + layoutDirection: LayoutDirection, + density: Density + ): Outline { + val beakWidthPx = with(density) { beakStyle.width.toPx() } + val beakHeightPx = with(density) { beakStyle.height.toPx() } + val cornerRadiusPx = with(density) { 28.dp.toPx() } // Default 28dp matching Figma + + val bodyPath = Path().apply { + val rect = if (beakStyle.direction == BeakDirection.Up) { + Rect(0f, beakHeightPx, size.width, size.height) + } else { + Rect(0f, 0f, size.width, size.height - beakHeightPx) + } + addRoundRect( + RoundRect(rect = rect, cornerRadius = CornerRadius(cornerRadiusPx)) + ) + } + + val beakPath = Path().apply { + val yBase = if (beakStyle.direction == BeakDirection.Up) beakHeightPx else size.height - beakHeightPx + val yTip = if (beakStyle.direction == BeakDirection.Up) 0f else size.height + + val xCenter = when (beakStyle.alignment) { + BeakAlignment.Start -> cornerRadiusPx + beakWidthPx / 2 + BeakAlignment.Center -> size.width / 2 + BeakAlignment.End -> size.width - cornerRadiusPx - beakWidthPx / 2 + } + with(density) { beakStyle.offset.toPx() } + + // Clamp beak position to flat edges + val minX = cornerRadiusPx + beakWidthPx / 2 + val maxX = size.width - cornerRadiusPx - beakWidthPx / 2 + val clampedXCenter = xCenter.coerceIn(minX, maxX) + + val x1 = clampedXCenter - beakWidthPx / 2 + val x2 = clampedXCenter + val x3 = clampedXCenter + beakWidthPx / 2 + + moveTo(x1, yBase) + lineTo(x2, yTip) + lineTo(x3, yBase) + close() + } + + val combinedPath = Path.combine( + operation = PathOperation.Union, + path1 = bodyPath, + path2 = beakPath + ) + return Outline.Generic(combinedPath) + } +} + +/** + * Positions the tooltip relative to the anchor. + */ +private class TooltipPositionProvider( + private val beakStyle: BeakStyle, + private val density: Density +) : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize + ): IntOffset { + val beakWidthPx = with(density) { beakStyle.width.toPx() } + val beakHeightPx = with(density) { beakStyle.height.toPx() } + val cornerRadiusPx = with(density) { 28.dp.toPx() } + + val y = if (beakStyle.direction == BeakDirection.Up) { + anchorBounds.bottom + } else { + anchorBounds.top - popupContentSize.height + } + + val beakTipX = when (beakStyle.alignment) { + BeakAlignment.Start -> cornerRadiusPx + beakWidthPx / 2 + BeakAlignment.Center -> popupContentSize.width.toFloat() / 2 + BeakAlignment.End -> popupContentSize.width.toFloat() - cornerRadiusPx - beakWidthPx / 2 + } + with(density) { beakStyle.offset.toPx() } + + val minX = cornerRadiusPx + beakWidthPx / 2 + val maxX = popupContentSize.width.toFloat() - cornerRadiusPx - beakWidthPx / 2 + val clampedBeakTipX = beakTipX.coerceIn(minX, maxX) + + val anchorCenterX = anchorBounds.left + anchorBounds.width / 2 + val x = anchorCenterX - clampedBeakTipX.toInt() + val clampedX = x.coerceIn(0, windowSize.width - popupContentSize.width) + + return IntOffset(clampedX, y) + } +} + +// Extension to helper resolve unspecified colors +@Composable +private fun Color.takeOrElse(block: @Composable () -> Color): Color { + return if (this != Color.Unspecified) this else block() +} + +@Preview(showBackground = true, backgroundColor = 0) +@Composable +private fun TooltipPreview() { + MaterialTheme { + TooltipContent( + beakStyle = BeakStyle(alignment = BeakAlignment.Center), + colors = TooltipDefaults.tooltipColors() + ) { + Text("This is a preview of the tooltip content.") + } + } +} From d293b340e37fee9cb8aba0dca867c21343904703 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 29 Jul 2026 18:38:38 -0700 Subject: [PATCH 02/20] polish component + slight animation --- .../feature/preview/PreviewScreen.kt | 16 +- .../jetpackcamera/ui/components/Tooltip.kt | 145 ++++++++++++++---- 2 files changed, 122 insertions(+), 39 deletions(-) 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 d356beec9f..cc13f2b15c 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 @@ -151,7 +151,7 @@ fun PreviewScreen( val isReady by remember { derivedStateOf { rawUiState.value is CaptureUiState.Ready } } val surfaceRequest: SurfaceRequest? - by viewModel.surfaceRequest.collectAsState() + by viewModel.surfaceRequest.collectAsState() LifecycleStartEffect(Unit) { viewModel.cameraController.startCamera() @@ -197,7 +197,7 @@ fun PreviewScreen( { requireNotNull(rawUiState.value as? CaptureUiState.Ready) { "Deferred read invoked when state was not Ready. " + - "Current state: ${rawUiState.value}" + "Current state: ${rawUiState.value}" } } } @@ -287,7 +287,7 @@ private fun ContentScreen( } ZoomStateManager( initialZoomLevel = - (zoomControlState.value as? ZoomControlUiState.Enabled)?.initialZoomRatio ?: 1f, + (zoomControlState.value as? ZoomControlUiState.Enabled)?.initialZoomRatio ?: 1f, zoomRange = (zoomUiState.value as? ZoomUiState.Enabled) ?.primaryZoomRange ?: Range(1f, 1f), zoomController = safeZoomController @@ -297,7 +297,7 @@ private fun ContentScreen( LaunchedEffect((flipLensState.value as? FlipLensUiState.Available)?.selectedLensFacing) { zoomStateManager.onChangeLens( newInitialZoomLevel = - (zoomControlState.value as? ZoomControlUiState.Enabled)?.initialZoomRatio ?: 1f, + (zoomControlState.value as? ZoomControlUiState.Enabled)?.initialZoomRatio ?: 1f, newZoomRange = (zoomUiState.value as? ZoomUiState.Enabled) ?.primaryZoomRange ?: Range(1f, 1f) ) @@ -798,7 +798,7 @@ private fun LayoutWrapper( modifier = modifier .fillMaxWidth() .padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, + verticalAlignment = Alignment.CenterVertically ) { Row( modifier = Modifier.weight(1f), @@ -811,6 +811,7 @@ private fun LayoutWrapper( stabilizationIndicator(Modifier) } + // TODO: this whole button is currently a PLACEHOLDER TooltipIconButton( icon = { Box( @@ -819,8 +820,9 @@ private fun LayoutWrapper( .background(Color.White, shape = CircleShape) ) }, - tooltipText = "This is a placeholder tooltip message. It demonstrates how text " + - "wraps and aligns with the beak pointing to the anchor.", + tooltipText = "This is a placeholder tooltip message. It demonstrates how" + + " text wraps and aligns with the beak pointing to the anchor.", + isOutlined = true, beakStyle = BeakStyle( alignment = BeakAlignment.End, direction = BeakDirection.Up diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index b03e76cea5..1729eaf388 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -15,33 +15,41 @@ */ package com.google.jetpackcamera.ui.components +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.slideInVertically +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text +import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.IconButton import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedIconButton +import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.ui.Alignment -import androidx.compose.ui.text.style.TextAlign import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue -import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.RoundRect -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.PathOperation -import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathOperation import androidx.compose.ui.graphics.Shape import androidx.compose.ui.platform.LocalDensity +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 @@ -49,7 +57,6 @@ import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp -import androidx.compose.foundation.layout.widthIn import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupPositionProvider import androidx.compose.ui.window.PopupProperties @@ -82,12 +89,24 @@ fun Tooltip( onDismissRequest = onDismissRequest, properties = PopupProperties(focusable = true) ) { - TooltipContent( - beakStyle = beakStyle, - colors = colors, - modifier = modifier.widthIn(max = maxWidth), - content = content - ) + val slideDistance = with(density) { 12.dp.roundToPx() } + val enterTransition = if (beakStyle.direction == BeakDirection.Up) { + slideInVertically(initialOffsetY = { -slideDistance }) + fadeIn() + } else { + slideInVertically(initialOffsetY = { slideDistance }) + fadeIn() + } + + AnimatedVisibility( + visible = true, + enter = enterTransition + ) { + TooltipContent( + beakStyle = beakStyle, + colors = colors, + modifier = modifier.widthIn(max = maxWidth), + content = content + ) + } } } } @@ -110,15 +129,28 @@ fun TooltipIconButton( beakStyle: BeakStyle = BeakStyle(), colors: TooltipColors = TooltipDefaults.tooltipColors(), maxWidth: Dp = TooltipDefaults.MaxWidth, + isOutlined: Boolean = false, onClick: () -> Unit = {} ) { var showTooltip by remember { mutableStateOf(false) } Box(modifier = modifier) { - IconButton(onClick = { - showTooltip = true - onClick() - }) { - icon() + if (isOutlined) { + OutlinedIconButton( + onClick = { + showTooltip = true + onClick() + }, + border = BorderStroke(1.dp, Color.White.copy(alpha = 0.2f)) + ) { + icon() + } + } else { + IconButton(onClick = { + showTooltip = true + onClick() + }) { + icon() + } } Tooltip( expanded = showTooltip, @@ -142,8 +174,8 @@ fun TooltipIconButton( @Composable private fun TooltipContent( beakStyle: BeakStyle, - colors: TooltipColors, modifier: Modifier = Modifier, + colors: TooltipColors = TooltipDefaults.tooltipColors(), content: @Composable () -> Unit ) { val shape = TooltipShape(beakStyle) @@ -193,7 +225,7 @@ private fun TooltipContent( * @param offset Optional horizontal offset from the alignment position. */ data class BeakStyle( - val width: Dp = 24.dp, + val width: Dp = 10.dp, val height: Dp = 8.dp, val alignment: BeakAlignment = BeakAlignment.End, val direction: BeakDirection = BeakDirection.Up, @@ -201,15 +233,18 @@ data class BeakStyle( ) enum class BeakAlignment { - Start, Center, End + Start, + Center, + End } enum class BeakDirection { - Up, Down + Up, + Down } data class TooltipColors( - val containerColor: Color = Color.Unspecified,// + val containerColor: Color = Color.Unspecified, // val contentColor: Color = Color.Unspecified ) @@ -250,8 +285,16 @@ private class TooltipShape( } val beakPath = Path().apply { - val yBase = if (beakStyle.direction == BeakDirection.Up) beakHeightPx else size.height - beakHeightPx - val yTip = if (beakStyle.direction == BeakDirection.Up) 0f else size.height + val yBase = if (beakStyle.direction == BeakDirection.Up) { + beakHeightPx + } else { + size.height - beakHeightPx + } + val yTip = if (beakStyle.direction == BeakDirection.Up) { + 0f + } else { + size.height + } val xCenter = when (beakStyle.alignment) { BeakAlignment.Start -> cornerRadiusPx + beakWidthPx / 2 @@ -332,13 +375,51 @@ private fun Color.takeOrElse(block: @Composable () -> Color): Color { @Preview(showBackground = true, backgroundColor = 0) @Composable -private fun TooltipPreview() { +private fun TooltipVariousStylesPreview() { MaterialTheme { - TooltipContent( - beakStyle = BeakStyle(alignment = BeakAlignment.Center), - colors = TooltipDefaults.tooltipColors() + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(24.dp) ) { - Text("This is a preview of the tooltip content.") + TooltipContent( + beakStyle = BeakStyle(direction = BeakDirection.Up, alignment = BeakAlignment.Start) + ) { + Text("Beak Up - Start Alignment") + } + TooltipContent( + beakStyle = BeakStyle( + direction = BeakDirection.Up, + alignment = BeakAlignment.Center + ) + ) { + Text("Beak Up - Center Alignment") + } + TooltipContent( + beakStyle = BeakStyle(direction = BeakDirection.Up, alignment = BeakAlignment.End) + ) { + Text("Beak Up - End Alignment") + } + TooltipContent( + beakStyle = BeakStyle( + direction = BeakDirection.Down, + alignment = BeakAlignment.Start + ) + ) { + Text("Beak Down - Start Alignment") + } + TooltipContent( + beakStyle = BeakStyle( + direction = BeakDirection.Down, + alignment = BeakAlignment.Center + ) + ) { + Text("Beak Down - Center Alignment") + } + TooltipContent( + beakStyle = BeakStyle(direction = BeakDirection.Down, alignment = BeakAlignment.End) + ) { + Text("Beak Down - End Alignment") + } } } } From 05ba546ab29009ac1e3a052ac20c2cd7fb154986 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 29 Jul 2026 18:43:22 -0700 Subject: [PATCH 03/20] add optional auto dismiss timer param --- .../feature/preview/PreviewScreen.kt | 1 + .../jetpackcamera/ui/components/Tooltip.kt | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) 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 cc13f2b15c..0538fc798b 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 @@ -823,6 +823,7 @@ private fun LayoutWrapper( tooltipText = "This is a placeholder tooltip message. It demonstrates how" + " text wraps and aligns with the beak pointing to the anchor.", isOutlined = true, + autoDismissDelayMillis = 3000L, beakStyle = BeakStyle( alignment = BeakAlignment.End, direction = BeakDirection.Up diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 1729eaf388..f8b2bde03b 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -31,11 +31,13 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedIconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius @@ -60,6 +62,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupPositionProvider import androidx.compose.ui.window.PopupProperties +import kotlinx.coroutines.delay /** * A custom tooltip component that overlays the screen using a [Popup]. @@ -80,9 +83,17 @@ fun Tooltip( beakStyle: BeakStyle = BeakStyle(), colors: TooltipColors = TooltipDefaults.tooltipColors(), maxWidth: Dp = TooltipDefaults.MaxWidth, + autoDismissDelayMillis: Long = TooltipDefaults.NoAutoDismiss, content: @Composable () -> Unit ) { if (expanded) { + if (autoDismissDelayMillis > 0) { + val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) + LaunchedEffect(autoDismissDelayMillis) { + delay(autoDismissDelayMillis) + currentOnDismissRequest() + } + } val density = LocalDensity.current Popup( popupPositionProvider = TooltipPositionProvider(beakStyle, density), @@ -130,6 +141,7 @@ fun TooltipIconButton( colors: TooltipColors = TooltipDefaults.tooltipColors(), maxWidth: Dp = TooltipDefaults.MaxWidth, isOutlined: Boolean = false, + autoDismissDelayMillis: Long = TooltipDefaults.NoAutoDismiss, onClick: () -> Unit = {} ) { var showTooltip by remember { mutableStateOf(false) } @@ -157,7 +169,8 @@ fun TooltipIconButton( onDismissRequest = { showTooltip = false }, beakStyle = beakStyle, colors = colors, - maxWidth = maxWidth + maxWidth = maxWidth, + autoDismissDelayMillis = autoDismissDelayMillis ) { Text( text = tooltipText, @@ -249,6 +262,7 @@ data class TooltipColors( ) object TooltipDefaults { + const val NoAutoDismiss = 0L val MaxWidth: Dp = 296.dp @Composable From 3c272dccd128648dcda3658964e417962b041bc0 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 29 Jul 2026 19:04:48 -0700 Subject: [PATCH 04/20] polish tooltip and clean up dependencies --- README.md | 2 +- gradle/libs.versions.toml | 4 ---- ui/components/build.gradle.kts | 4 ++-- .../jetpackcamera/ui/components/Tooltip.kt | 20 +++++++++++-------- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index a733c15c34..65febf87cb 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ OEMs looking to validate their camera feature implementations. This project uses the gradle build system, and can be imported directly into Android Studio. -Currently, Jetpack Camera App is built using the Android Gradle Plugin 8.10.0, which is only +Currently, Jetpack Camera App is built using the Android Gradle Plugin 8.10.1, which is only compatible with Android Studio Meerkat or newer. ## Pre-push Hook (Recommended) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 2cc2246f56..a2317d598e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -55,8 +55,6 @@ playServicesTasks = "18.4.0" cameraLowLightBoost = "16.0.1-beta06" material = "1.12.0" material3WindowSizeClass = "1.3.2" -uiToolingPreview = "1.11.4" -uiTooling = "1.11.4" [libraries] accompanist-permissions = { module = "com.google.accompanist:accompanist-permissions", version.ref = "accompanist" } @@ -116,8 +114,6 @@ robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectr truth = { module = "com.google.truth:truth", version.ref = "truth" } material = { group = "com.google.android.material", name = "material", version.ref = "material" } androidx-material3-window-size-klass = { group = "androidx.compose.material3", name = "material3-window-size-class", version.ref = "material3WindowSizeClass" } -androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview", version.ref = "uiToolingPreview" } -androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "uiTooling" } [plugins] android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" } diff --git a/ui/components/build.gradle.kts b/ui/components/build.gradle.kts index 423069b94f..ddad87da91 100644 --- a/ui/components/build.gradle.kts +++ b/ui/components/build.gradle.kts @@ -60,14 +60,14 @@ android { } dependencies { - implementation(libs.androidx.ui.tooling.preview) + implementation(libs.compose.ui.tooling.preview) // Compose val composeBom = platform(libs.compose.bom) implementation(composeBom) // Compose - Material Design 3 implementation(libs.compose.material3) - debugImplementation(libs.androidx.ui.tooling) + debugImplementation(libs.compose.ui.tooling) } // Allow references to generated code diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index f8b2bde03b..ee180e8894 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -45,6 +45,7 @@ import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.PathOperation @@ -73,6 +74,8 @@ import kotlinx.coroutines.delay * @param modifier Modifier for the tooltip content. * @param beakStyle Configuration for the beak's size, alignment, and direction. * @param colors Colors for the tooltip container and content. + * @param maxWidth The maximum width of the tooltip. + * @param autoDismissDelayMillis The delay in milliseconds before the tooltip auto-dismisses. Use [TooltipDefaults.NoAutoDismiss] to disable. * @param content The content to display inside the tooltip (usually a Text composable). */ @Composable @@ -96,7 +99,9 @@ fun Tooltip( } val density = LocalDensity.current Popup( - popupPositionProvider = TooltipPositionProvider(beakStyle, density), + popupPositionProvider = remember(beakStyle, density) { + TooltipPositionProvider(beakStyle, density) + }, onDismissRequest = onDismissRequest, properties = PopupProperties(focusable = true) ) { @@ -130,6 +135,9 @@ fun Tooltip( * @param modifier Modifier for the button container. * @param beakStyle Configuration for the tooltip's beak. * @param colors Colors for the tooltip. + * @param maxWidth The maximum width of the tooltip. + * @param isOutlined Whether the icon button should be outlined. + * @param autoDismissDelayMillis The delay in milliseconds before the tooltip auto-dismisses. * @param onClick Optional callback when the button is clicked. */ @Composable @@ -191,7 +199,7 @@ private fun TooltipContent( colors: TooltipColors = TooltipDefaults.tooltipColors(), content: @Composable () -> Unit ) { - val shape = TooltipShape(beakStyle) + val shape = remember(beakStyle) { TooltipShape(beakStyle) } val containerColor = colors.containerColor.takeOrElse { MaterialTheme.colorScheme.secondaryFixed } @@ -257,7 +265,7 @@ enum class BeakDirection { } data class TooltipColors( - val containerColor: Color = Color.Unspecified, // + val containerColor: Color = Color.Unspecified, val contentColor: Color = Color.Unspecified ) @@ -381,11 +389,7 @@ private class TooltipPositionProvider( } } -// Extension to helper resolve unspecified colors -@Composable -private fun Color.takeOrElse(block: @Composable () -> Color): Color { - return if (this != Color.Unspecified) this else block() -} + @Preview(showBackground = true, backgroundColor = 0) @Composable From d66f96a2f92df3bf44e7a92075f806467a5534bd Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 29 Jul 2026 19:17:10 -0700 Subject: [PATCH 05/20] migrate to compose native tooltip --- .../feature/preview/PreviewScreen.kt | 12 +- ui/components/build.gradle.kts | 2 - .../jetpackcamera/ui/components/Tooltip.kt | 448 +++--------------- 3 files changed, 63 insertions(+), 399 deletions(-) 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 0538fc798b..8af07babe6 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 @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) package com.google.jetpackcamera.feature.preview import android.Manifest @@ -57,6 +58,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel @@ -74,9 +76,6 @@ import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.ImageCaptureEvent import com.google.jetpackcamera.model.LensToZoom import com.google.jetpackcamera.model.VideoCaptureEvent -import com.google.jetpackcamera.ui.components.BeakAlignment -import com.google.jetpackcamera.ui.components.BeakDirection -import com.google.jetpackcamera.ui.components.BeakStyle import com.google.jetpackcamera.ui.components.TooltipIconButton import com.google.jetpackcamera.ui.components.capture.AmplitudeToggleButton import com.google.jetpackcamera.ui.components.capture.CAPTURE_MODE_TOGGLE_BUTTON @@ -821,13 +820,8 @@ private fun LayoutWrapper( ) }, tooltipText = "This is a placeholder tooltip message. It demonstrates how" + - " text wraps and aligns with the beak pointing to the anchor.", + " text wraps and aligns.", isOutlined = true, - autoDismissDelayMillis = 3000L, - beakStyle = BeakStyle( - alignment = BeakAlignment.End, - direction = BeakDirection.Up - ) ) } }, diff --git a/ui/components/build.gradle.kts b/ui/components/build.gradle.kts index ddad87da91..02d3b2dca4 100644 --- a/ui/components/build.gradle.kts +++ b/ui/components/build.gradle.kts @@ -60,14 +60,12 @@ android { } dependencies { - implementation(libs.compose.ui.tooling.preview) // Compose val composeBom = platform(libs.compose.bom) implementation(composeBom) // Compose - Material Design 3 implementation(libs.compose.material3) - debugImplementation(libs.compose.ui.tooling) } // Allow references to generated code diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index ee180e8894..dd04d095e0 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -15,428 +15,100 @@ */ package com.google.jetpackcamera.ui.components -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.fadeIn -import androidx.compose.animation.slideInVertically import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton -import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedIconButton +import androidx.compose.material3.RichTooltip import androidx.compose.material3.Text +import androidx.compose.material3.TooltipAnchorPosition +import androidx.compose.material3.TooltipBox +import androidx.compose.material3.TooltipDefaults +import androidx.compose.material3.rememberTooltipState import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.ui.Alignment +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.CornerRadius -import androidx.compose.ui.geometry.Rect -import androidx.compose.ui.geometry.RoundRect -import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.takeOrElse -import androidx.compose.ui.graphics.Outline -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.PathOperation -import androidx.compose.ui.graphics.Shape -import androidx.compose.ui.platform.LocalDensity 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.IntRect -import androidx.compose.ui.unit.IntSize -import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.Popup -import androidx.compose.ui.window.PopupPositionProvider -import androidx.compose.ui.window.PopupProperties -import kotlinx.coroutines.delay +import kotlinx.coroutines.launch /** - * A custom tooltip component that overlays the screen using a [Popup]. - * It should be placed inside a [Box] along with its anchor component. - * - * @param expanded Whether the tooltip is currently visible. - * @param onDismissRequest Called when the user taps outside the tooltip. - * @param modifier Modifier for the tooltip content. - * @param beakStyle Configuration for the beak's size, alignment, and direction. - * @param colors Colors for the tooltip container and content. - * @param maxWidth The maximum width of the tooltip. - * @param autoDismissDelayMillis The delay in milliseconds before the tooltip auto-dismisses. Use [TooltipDefaults.NoAutoDismiss] to disable. - * @param content The content to display inside the tooltip (usually a Text composable). - */ -@Composable -fun Tooltip( - expanded: Boolean, - onDismissRequest: () -> Unit, - modifier: Modifier = Modifier, - beakStyle: BeakStyle = BeakStyle(), - colors: TooltipColors = TooltipDefaults.tooltipColors(), - maxWidth: Dp = TooltipDefaults.MaxWidth, - autoDismissDelayMillis: Long = TooltipDefaults.NoAutoDismiss, - content: @Composable () -> Unit -) { - if (expanded) { - if (autoDismissDelayMillis > 0) { - val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) - LaunchedEffect(autoDismissDelayMillis) { - delay(autoDismissDelayMillis) - currentOnDismissRequest() - } - } - val density = LocalDensity.current - Popup( - popupPositionProvider = remember(beakStyle, density) { - TooltipPositionProvider(beakStyle, density) - }, - onDismissRequest = onDismissRequest, - properties = PopupProperties(focusable = true) - ) { - val slideDistance = with(density) { 12.dp.roundToPx() } - val enterTransition = if (beakStyle.direction == BeakDirection.Up) { - slideInVertically(initialOffsetY = { -slideDistance }) + fadeIn() - } else { - slideInVertically(initialOffsetY = { slideDistance }) + fadeIn() - } - - AnimatedVisibility( - visible = true, - enter = enterTransition - ) { - TooltipContent( - beakStyle = beakStyle, - colors = colors, - modifier = modifier.widthIn(max = maxWidth), - content = content - ) - } - } - } -} - -/** - * An icon button that shows a tooltip when clicked. + * An icon button that shows a styled RichTooltip when clicked. + * The tooltip is persistent and stays visible until the user taps outside. * * @param icon The icon to display inside the button. + * @param tooltipTitle The optional title to display inside the tooltip. * @param tooltipText The text to display inside the tooltip. * @param modifier Modifier for the button container. - * @param beakStyle Configuration for the tooltip's beak. - * @param colors Colors for the tooltip. - * @param maxWidth The maximum width of the tooltip. * @param isOutlined Whether the icon button should be outlined. - * @param autoDismissDelayMillis The delay in milliseconds before the tooltip auto-dismisses. * @param onClick Optional callback when the button is clicked. */ +@OptIn(ExperimentalMaterial3Api::class) @Composable fun TooltipIconButton( icon: @Composable () -> Unit, - tooltipText: String, modifier: Modifier = Modifier, - beakStyle: BeakStyle = BeakStyle(), - colors: TooltipColors = TooltipDefaults.tooltipColors(), - maxWidth: Dp = TooltipDefaults.MaxWidth, + tooltipTitle: String? = null, + tooltipText: String, isOutlined: Boolean = false, - autoDismissDelayMillis: Long = TooltipDefaults.NoAutoDismiss, onClick: () -> Unit = {} ) { - var showTooltip by remember { mutableStateOf(false) } - Box(modifier = modifier) { - if (isOutlined) { - OutlinedIconButton( - onClick = { - showTooltip = true - onClick() + val tooltipState = rememberTooltipState(isPersistent = true) + val scope = rememberCoroutineScope() + + TooltipBox( + positionProvider = TooltipDefaults.rememberTooltipPositionProvider( + positioning = TooltipAnchorPosition.Above + ), + tooltip = { + RichTooltip( + title = { + tooltipTitle?.let { + Text( + text = it, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth() + ) + } }, - border = BorderStroke(1.dp, Color.White.copy(alpha = 0.2f)) - ) { - icon() - } - } else { - IconButton(onClick = { - showTooltip = true - onClick() - }) { - icon() - } - } - Tooltip( - expanded = showTooltip, - onDismissRequest = { showTooltip = false }, - beakStyle = beakStyle, - colors = colors, - maxWidth = maxWidth, - autoDismissDelayMillis = autoDismissDelayMillis - ) { - Text( - text = tooltipText, - textAlign = TextAlign.Center, - style = MaterialTheme.typography.labelLarge - ) - } - } -} - -/** - * The visual content of the tooltip, including the custom shape. - */ -@Composable -private fun TooltipContent( - beakStyle: BeakStyle, - modifier: Modifier = Modifier, - colors: TooltipColors = TooltipDefaults.tooltipColors(), - content: @Composable () -> Unit -) { - val shape = remember(beakStyle) { TooltipShape(beakStyle) } - val containerColor = colors.containerColor.takeOrElse { - MaterialTheme.colorScheme.secondaryFixed - } - val contentColor = colors.contentColor.takeOrElse { - MaterialTheme.colorScheme.onSecondaryFixed - } - - val topPadding = if (beakStyle.direction == BeakDirection.Up) { - 16.dp + beakStyle.height - } else { - 16.dp - } - val bottomPadding = if (beakStyle.direction == BeakDirection.Down) { - 16.dp + beakStyle.height - } else { - 16.dp - } - - CompositionLocalProvider(LocalContentColor provides contentColor) { - Box( - modifier = modifier - .background(color = containerColor, shape = shape) - .padding( - start = 16.dp, - top = topPadding, - end = 16.dp, - bottom = bottomPadding + text = { + Text( + text = tooltipText, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth() + ) + }, + colors = TooltipDefaults.richTooltipColors( + containerColor = MaterialTheme.colorScheme.secondaryFixed, + contentColor = MaterialTheme.colorScheme.onSecondaryFixed, + titleContentColor = MaterialTheme.colorScheme.onSecondaryFixed ), - contentAlignment = Alignment.Center - ) { - // We might need to adjust content color here if it's text - content() - } - } -} - -/** - * Configuration for the tooltip's beak (arrow). - * - * @param width The width of the beak base. - * @param height The height of the beak. - * @param alignment Horizontal alignment of the beak relative to the tooltip body. - * @param direction Direction the beak points (Up or Down). - * @param offset Optional horizontal offset from the alignment position. - */ -data class BeakStyle( - val width: Dp = 10.dp, - val height: Dp = 8.dp, - val alignment: BeakAlignment = BeakAlignment.End, - val direction: BeakDirection = BeakDirection.Up, - val offset: Dp = 0.dp -) - -enum class BeakAlignment { - Start, - Center, - End -} - -enum class BeakDirection { - Up, - Down -} - -data class TooltipColors( - val containerColor: Color = Color.Unspecified, - val contentColor: Color = Color.Unspecified -) - -object TooltipDefaults { - const val NoAutoDismiss = 0L - val MaxWidth: Dp = 296.dp - - @Composable - fun tooltipColors( - containerColor: Color = Color.Unspecified, - contentColor: Color = Color.Unspecified - ): TooltipColors = TooltipColors(containerColor, contentColor) -} - -/** - * A custom [Shape] that draws a rounded rectangle with a beak. - */ -private class TooltipShape( - private val beakStyle: BeakStyle -) : Shape { - override fun createOutline( - size: Size, - layoutDirection: LayoutDirection, - density: Density - ): Outline { - val beakWidthPx = with(density) { beakStyle.width.toPx() } - val beakHeightPx = with(density) { beakStyle.height.toPx() } - val cornerRadiusPx = with(density) { 28.dp.toPx() } // Default 28dp matching Figma - - val bodyPath = Path().apply { - val rect = if (beakStyle.direction == BeakDirection.Up) { - Rect(0f, beakHeightPx, size.width, size.height) - } else { - Rect(0f, 0f, size.width, size.height - beakHeightPx) - } - addRoundRect( - RoundRect(rect = rect, cornerRadius = CornerRadius(cornerRadiusPx)) + caretShape = TooltipDefaults.caretShape() ) - } - - val beakPath = Path().apply { - val yBase = if (beakStyle.direction == BeakDirection.Up) { - beakHeightPx - } else { - size.height - beakHeightPx - } - val yTip = if (beakStyle.direction == BeakDirection.Up) { - 0f - } else { - size.height + }, + state = tooltipState, + modifier = modifier + ) { + val showTooltipAction = { + scope.launch { + tooltipState.show() } - - val xCenter = when (beakStyle.alignment) { - BeakAlignment.Start -> cornerRadiusPx + beakWidthPx / 2 - BeakAlignment.Center -> size.width / 2 - BeakAlignment.End -> size.width - cornerRadiusPx - beakWidthPx / 2 - } + with(density) { beakStyle.offset.toPx() } - - // Clamp beak position to flat edges - val minX = cornerRadiusPx + beakWidthPx / 2 - val maxX = size.width - cornerRadiusPx - beakWidthPx / 2 - val clampedXCenter = xCenter.coerceIn(minX, maxX) - - val x1 = clampedXCenter - beakWidthPx / 2 - val x2 = clampedXCenter - val x3 = clampedXCenter + beakWidthPx / 2 - - moveTo(x1, yBase) - lineTo(x2, yTip) - lineTo(x3, yBase) - close() - } - - val combinedPath = Path.combine( - operation = PathOperation.Union, - path1 = bodyPath, - path2 = beakPath - ) - return Outline.Generic(combinedPath) - } -} - -/** - * Positions the tooltip relative to the anchor. - */ -private class TooltipPositionProvider( - private val beakStyle: BeakStyle, - private val density: Density -) : PopupPositionProvider { - override fun calculatePosition( - anchorBounds: IntRect, - windowSize: IntSize, - layoutDirection: LayoutDirection, - popupContentSize: IntSize - ): IntOffset { - val beakWidthPx = with(density) { beakStyle.width.toPx() } - val beakHeightPx = with(density) { beakStyle.height.toPx() } - val cornerRadiusPx = with(density) { 28.dp.toPx() } - - val y = if (beakStyle.direction == BeakDirection.Up) { - anchorBounds.bottom - } else { - anchorBounds.top - popupContentSize.height + onClick() } - val beakTipX = when (beakStyle.alignment) { - BeakAlignment.Start -> cornerRadiusPx + beakWidthPx / 2 - BeakAlignment.Center -> popupContentSize.width.toFloat() / 2 - BeakAlignment.End -> popupContentSize.width.toFloat() - cornerRadiusPx - beakWidthPx / 2 - } + with(density) { beakStyle.offset.toPx() } - - val minX = cornerRadiusPx + beakWidthPx / 2 - val maxX = popupContentSize.width.toFloat() - cornerRadiusPx - beakWidthPx / 2 - val clampedBeakTipX = beakTipX.coerceIn(minX, maxX) - - val anchorCenterX = anchorBounds.left + anchorBounds.width / 2 - val x = anchorCenterX - clampedBeakTipX.toInt() - val clampedX = x.coerceIn(0, windowSize.width - popupContentSize.width) - - return IntOffset(clampedX, y) - } -} - - - -@Preview(showBackground = true, backgroundColor = 0) -@Composable -private fun TooltipVariousStylesPreview() { - MaterialTheme { - Column( - modifier = Modifier.padding(16.dp), - verticalArrangement = Arrangement.spacedBy(24.dp) - ) { - TooltipContent( - beakStyle = BeakStyle(direction = BeakDirection.Up, alignment = BeakAlignment.Start) - ) { - Text("Beak Up - Start Alignment") - } - TooltipContent( - beakStyle = BeakStyle( - direction = BeakDirection.Up, - alignment = BeakAlignment.Center - ) - ) { - Text("Beak Up - Center Alignment") - } - TooltipContent( - beakStyle = BeakStyle(direction = BeakDirection.Up, alignment = BeakAlignment.End) - ) { - Text("Beak Up - End Alignment") - } - TooltipContent( - beakStyle = BeakStyle( - direction = BeakDirection.Down, - alignment = BeakAlignment.Start - ) - ) { - Text("Beak Down - Start Alignment") - } - TooltipContent( - beakStyle = BeakStyle( - direction = BeakDirection.Down, - alignment = BeakAlignment.Center - ) + if (isOutlined) { + OutlinedIconButton( + onClick = showTooltipAction, + border = BorderStroke(1.dp, Color.White.copy(alpha = 0.2f)) ) { - Text("Beak Down - Center Alignment") + icon() } - TooltipContent( - beakStyle = BeakStyle(direction = BeakDirection.Down, alignment = BeakAlignment.End) - ) { - Text("Beak Down - End Alignment") + } else { + IconButton(onClick = showTooltipAction) { + icon() } } } From ae08a58e9c1e1458d0b03c4c8f6baf34e48e11aa Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Thu, 30 Jul 2026 07:22:10 -0700 Subject: [PATCH 06/20] tooltip adjsutments --- .../feature/preview/PreviewScreen.kt | 4 +-- .../jetpackcamera/ui/components/Tooltip.kt | 32 ++++++++++++++----- 2 files changed, 26 insertions(+), 10 deletions(-) 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 8af07babe6..87ccea6728 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 @@ -14,6 +14,7 @@ * limitations under the License. */ @file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) + package com.google.jetpackcamera.feature.preview import android.Manifest @@ -58,7 +59,6 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel @@ -821,7 +821,7 @@ private fun LayoutWrapper( }, tooltipText = "This is a placeholder tooltip message. It demonstrates how" + " text wraps and aligns.", - isOutlined = true, + isOutlined = true ) } }, diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index dd04d095e0..13eb52a871 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -17,6 +17,8 @@ package com.google.jetpackcamera.ui.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme @@ -28,6 +30,7 @@ import androidx.compose.material3.TooltipBox import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.rememberTooltipState import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @@ -65,12 +68,16 @@ fun TooltipIconButton( ), tooltip = { RichTooltip( - title = { - tooltipTitle?.let { + modifier = Modifier + .widthIn(min = 140.dp, max = 296.dp), + title = tooltipTitle?.let { + { Text( text = it, textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth() + modifier = Modifier + .fillMaxWidth() + .padding(top = 10.dp) ) } }, @@ -78,7 +85,14 @@ fun TooltipIconButton( Text( text = tooltipText, textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth() + modifier = Modifier + .fillMaxWidth() + .padding( + top = if (tooltipTitle != null) 0.dp else 10.dp, + start = 10.dp, + end = 10.dp, + bottom = 10.dp + ) ) }, colors = TooltipDefaults.richTooltipColors( @@ -92,11 +106,13 @@ fun TooltipIconButton( state = tooltipState, modifier = modifier ) { - val showTooltipAction = { - scope.launch { - tooltipState.show() + val showTooltipAction = remember(tooltipState, scope, onClick) { + { + scope.launch { + tooltipState.show() + } + onClick() } - onClick() } if (isOutlined) { From 4d385a4e659b3eb03ed0c1679dc79849ebbcd1c4 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 20 Oct 2026 10:47:14 -0700 Subject: [PATCH 07/20] Refactor tooltip into JcaTooltipBox and TooltipIconButton with tests - Decouple container into JcaTooltipBox and anchor into TooltipIconButton - Add TooltipTriggerEvent and triggerFlow for programmatic control - Add autoDismissDuration with triggerRevision reset support - Expose positioning parameter (TooltipAnchorPosition) - Add comprehensive Robolectric Compose unit tests in TooltipTest --- ui/components/build.gradle.kts | 20 ++ .../jetpackcamera/ui/components/Tooltip.kt | 172 +++++++++++--- .../ui/components/TooltipTest.kt | 212 ++++++++++++++++++ 3 files changed, 379 insertions(+), 25 deletions(-) create mode 100644 ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt diff --git a/ui/components/build.gradle.kts b/ui/components/build.gradle.kts index 37a192fea1..fbabc87753 100644 --- a/ui/components/build.gradle.kts +++ b/ui/components/build.gradle.kts @@ -58,6 +58,13 @@ android { buildConfig = true compose = true } + + testOptions { + unitTests { + isReturnDefaultValues = true + isIncludeAndroidResources = true + } + } } dependencies { @@ -67,6 +74,19 @@ dependencies { // Compose - Material Design 3 implementation(libs.compose.material3) + + // Compose - Testing + debugImplementation(libs.compose.test.manifest) + // noinspection TestManifestGradleConfiguration: required for release build unit tests + testImplementation(libs.compose.test.manifest) + testImplementation(libs.compose.junit) + + // Testing + testImplementation(libs.junit) + testImplementation(libs.truth) + testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.robolectric) + testImplementation(libs.androidx.junit) } // Allow references to generated code diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 13eb52a871..e76292b2e3 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -28,48 +28,110 @@ import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.material3.TooltipBox import androidx.compose.material3.TooltipDefaults +import androidx.compose.material3.TooltipState import androidx.compose.material3.rememberTooltipState import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.paneTitle +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import kotlin.time.Duration +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch +const val TOOLTIP_ANCHOR_BUTTON_TAG = "tooltip_anchor_button" +const val TOOLTIP_CONTENT_TAG = "tooltip_content" + /** - * An icon button that shows a styled RichTooltip when clicked. - * The tooltip is persistent and stays visible until the user taps outside. + * Events used to trigger programmatic display or dismissal of tooltips. + */ +sealed interface TooltipTriggerEvent { + data object Show : TooltipTriggerEvent + data object Dismiss : TooltipTriggerEvent +} + +/** + * A generic container that wraps content with a styled [RichTooltip]. * - * @param icon The icon to display inside the button. - * @param tooltipTitle The optional title to display inside the tooltip. * @param tooltipText The text to display inside the tooltip. - * @param modifier Modifier for the button container. - * @param isOutlined Whether the icon button should be outlined. - * @param onClick Optional callback when the button is clicked. + * @param modifier Modifier for the container. + * @param tooltipTitle Optional title displayed above the tooltip text. + * @param state State controlling tooltip visibility. + * @param positioning Anchor position for the tooltip (e.g. Above, Below). + * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. + * @param triggerFlow Optional flow of [TooltipTriggerEvent] to trigger showing or dismissing. + * @param enableUserInput Whether long-press and hover gestures on the anchor trigger the tooltip. + * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. + * @param content The anchor composable wrapped by the tooltip. */ @OptIn(ExperimentalMaterial3Api::class) @Composable -fun TooltipIconButton( - icon: @Composable () -> Unit, +fun JcaTooltipBox( + tooltipText: String, modifier: Modifier = Modifier, tooltipTitle: String? = null, - tooltipText: String, - isOutlined: Boolean = false, - onClick: () -> Unit = {} + state: TooltipState = rememberTooltipState(isPersistent = true), + positioning: TooltipAnchorPosition = TooltipAnchorPosition.Above, + autoDismissDuration: Duration? = null, + triggerFlow: Flow? = null, + enableUserInput: Boolean = true, + onDismissRequest: (() -> Unit)? = null, + content: @Composable () -> Unit ) { - val tooltipState = rememberTooltipState(isPersistent = true) - val scope = rememberCoroutineScope() + var triggerRevision by remember { mutableIntStateOf(0) } + + // External flow triggers using collectLatest to prevent deadlock from show() suspension + if (triggerFlow != null) { + LaunchedEffect(triggerFlow, state) { + triggerFlow.collectLatest { event -> + when (event) { + TooltipTriggerEvent.Show -> { + triggerRevision++ + state.show() + } + TooltipTriggerEvent.Dismiss -> state.dismiss() + } + } + } + } + + // Auto-dismiss timer keyed on targetState and triggerRevision + if (autoDismissDuration != null) { + LaunchedEffect(state.transition.targetState, triggerRevision, autoDismissDuration) { + if (state.transition.targetState) { + delay(autoDismissDuration) + state.dismiss() + onDismissRequest?.invoke() + } + } + } TooltipBox( positionProvider = TooltipDefaults.rememberTooltipPositionProvider( - positioning = TooltipAnchorPosition.Above + positioning = positioning ), tooltip = { RichTooltip( modifier = Modifier - .widthIn(min = 140.dp, max = 296.dp), + .widthIn(min = 140.dp, max = 296.dp) + .testTag(TOOLTIP_CONTENT_TAG) + .semantics { + liveRegion = LiveRegionMode.Assertive + paneTitle = tooltipTitle ?: tooltipText + }, title = tooltipTitle?.let { { Text( @@ -103,27 +165,87 @@ fun TooltipIconButton( caretShape = TooltipDefaults.caretShape() ) }, - state = tooltipState, - modifier = modifier + state = state, + modifier = modifier, + enableUserInput = enableUserInput, + onDismissRequest = onDismissRequest ) { - val showTooltipAction = remember(tooltipState, scope, onClick) { - { - scope.launch { - tooltipState.show() + content() + } +} + +/** + * An icon button that shows a styled [RichTooltip] when clicked. + * + * @param icon The icon to display inside the button. + * @param tooltipText The text to display inside the tooltip. + * @param modifier Modifier for the button container. + * @param tooltipTitle The optional title to display inside the tooltip. + * @param state State controlling tooltip visibility. + * @param positioning Anchor position for the tooltip (e.g. Above, Below). + * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. + * @param triggerFlow Optional flow of [TooltipTriggerEvent] to trigger showing or dismissing. + * @param isOutlined Whether the icon button should be outlined. + * @param onClick Optional callback when the button is clicked. + * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun TooltipIconButton( + icon: @Composable () -> Unit, + tooltipText: String, + modifier: Modifier = Modifier, + tooltipTitle: String? = null, + state: TooltipState = rememberTooltipState(isPersistent = true), + positioning: TooltipAnchorPosition = TooltipAnchorPosition.Above, + autoDismissDuration: Duration? = null, + triggerFlow: Flow? = null, + isOutlined: Boolean = false, + onClick: () -> Unit = {}, + onDismissRequest: (() -> Unit)? = null +) { + val scope = rememberCoroutineScope() + val toggleTooltip = remember(state, scope, onClick, onDismissRequest) { + { + scope.launch { + if (state.transition.targetState) { + state.dismiss() + onDismissRequest?.invoke() + } else { + state.show() } - onClick() } + onClick() } + } + + JcaTooltipBox( + tooltipText = tooltipText, + modifier = modifier, + tooltipTitle = tooltipTitle, + state = state, + positioning = positioning, + autoDismissDuration = autoDismissDuration, + triggerFlow = triggerFlow, + enableUserInput = false, + onDismissRequest = onDismissRequest + ) { + val buttonModifier = Modifier + .testTag(TOOLTIP_ANCHOR_BUTTON_TAG) if (isOutlined) { OutlinedIconButton( - onClick = showTooltipAction, + onClick = toggleTooltip, + modifier = buttonModifier, border = BorderStroke(1.dp, Color.White.copy(alpha = 0.2f)) ) { icon() } } else { - IconButton(onClick = showTooltipAction) { + IconButton( + onClick = toggleTooltip, + modifier = buttonModifier + ) { icon() } } diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt new file mode 100644 index 0000000000..e37b2bbf9a --- /dev/null +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -0,0 +1,212 @@ +/* + * 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 + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TooltipAnchorPosition +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isPopup +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.flow.MutableSharedFlow +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@OptIn(ExperimentalMaterial3Api::class) +@RunWith(RobolectricTestRunner::class) +class TooltipTest { + + @get:Rule + val composeTestRule = createComposeRule() + + @Test + fun tooltip_initialState_isNotDisplayed() { + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "Help information" + ) + } + } + + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + + @Test + fun tooltip_clickAnchor_togglesVisibility() { + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipTitle = "Info Title", + tooltipText = "Help information" + ) + } + } + + // Show on first tap + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + composeTestRule.waitForIdle() + + composeTestRule.onNode(isPopup()).assertExists() + composeTestRule.onNode(hasText("Help information") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + composeTestRule.onNode(hasText("Info Title") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + + // Dismiss on second tap + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + composeTestRule.waitForIdle() + + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + + @Test + fun tooltip_externalFlowTrigger_showsAndDismisses() { + val triggerFlow = MutableSharedFlow(extraBufferCapacity = 1) + + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "External trigger text", + triggerFlow = triggerFlow + ) + } + } + + composeTestRule.onNode(isPopup()).assertDoesNotExist() + + // Emit Show + triggerFlow.tryEmit(TooltipTriggerEvent.Show) + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertExists() + composeTestRule.onNode(hasText("External trigger text") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + + // Emit Dismiss + triggerFlow.tryEmit(TooltipTriggerEvent.Dismiss) + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + + @Test + fun tooltip_autoDismiss_dismissesAfterSpecifiedDuration() { + composeTestRule.mainClock.autoAdvance = false + + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "Auto dismissing text", + autoDismissDuration = 3000.milliseconds + ) + } + } + + // Trigger show + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + composeTestRule.mainClock.advanceTimeByFrame() + composeTestRule.waitForIdle() + + composeTestRule.onNode(isPopup()).assertExists() + + // Advance part-way (1500ms) -> Still displayed + composeTestRule.mainClock.advanceTimeBy(1500) + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertExists() + + // Advance remaining time past 3000ms -> Trigger dismiss and allow exit transition + composeTestRule.mainClock.advanceTimeBy(1501) + composeTestRule.mainClock.autoAdvance = true + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + + @Test + fun tooltip_autoDismiss_reTriggerResetsTimer() { + composeTestRule.mainClock.autoAdvance = false + val triggerFlow = MutableSharedFlow(extraBufferCapacity = 1) + + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "Resetting timer text", + autoDismissDuration = 3000.milliseconds, + triggerFlow = triggerFlow + ) + } + } + + // Trigger show via flow + triggerFlow.tryEmit(TooltipTriggerEvent.Show) + composeTestRule.mainClock.advanceTimeByFrame() + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertExists() + + // Advance 2000ms of 3000ms + composeTestRule.mainClock.advanceTimeBy(2000) + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertExists() + + // Re-trigger Show -> Timer resets + triggerFlow.tryEmit(TooltipTriggerEvent.Show) + composeTestRule.mainClock.advanceTimeByFrame() + composeTestRule.waitForIdle() + + // Advance another 2000ms (total 4000ms from start, but only 2000ms since reset) + composeTestRule.mainClock.advanceTimeBy(2000) + composeTestRule.waitForIdle() + // Must still exist because timer was reset + composeTestRule.onNode(isPopup()).assertExists() + + // Advance past reset expiration (remaining 1001ms) -> Trigger dismiss and allow exit transition + composeTestRule.mainClock.advanceTimeBy(1001) + composeTestRule.mainClock.autoAdvance = true + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + + @Test + fun tooltip_positioning_supportsAboveAndBelow() { + composeTestRule.setContent { + MaterialTheme { + JcaTooltipBox( + tooltipText = "Position Below Text", + positioning = TooltipAnchorPosition.Below + ) { + Box(modifier = Modifier.size(48.dp)) + } + } + } + + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } +} From 228de283e161b277021188bfe882c9bce65c5fae Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 21 Oct 2026 09:48:04 -0700 Subject: [PATCH 08/20] Position tooltip in status bar topEndContent with overlap-aware styling and tests - Add containerColor and contentColor parameters to TooltipIconButton and pass to IconButtonDefaults colors. - Add initialStyle to OverlapAwareStyleProvider to prevent initial frame visual flicker before bounds measurement. - Add topEndContent slot in PreviewLayout aligned to CenterEnd of the top status bar row with OverlapAwareStyleProvider and animated container color. - Wire topEndContent in PreviewScreen with TooltipIconButton positioned below the status bar. - Add unit tests for TooltipIconButton custom container colors and OverlapAwareStyleProvider initialStyle behavior. --- .../feature/preview/PreviewScreen.kt | 43 ++++++++++----- .../ui/components/capture/CaptureLayout.kt | 32 +++++++++++ .../capture/OverlapAwareStyleProvider.kt | 22 +++++--- .../capture/OverlapAwareStyleProviderTest.kt | 54 ++++++++++++++++++- .../jetpackcamera/ui/components/Tooltip.kt | 15 +++++- .../ui/components/TooltipTest.kt | 19 ++++++- 6 files changed, 160 insertions(+), 25 deletions(-) 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 f41d760027..ef7a547560 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 @@ -43,6 +43,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SheetValue import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text +import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.material3.darkColorScheme import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState @@ -805,6 +806,29 @@ private fun ContentScreen( } } + val topEndContentLambda = remember(isErrorDialogShowing) { + @Composable { modifier: Modifier, containerColor: Color -> + if (!isErrorDialogShowing) { + // TODO: Finalize UX design and positioning with design team. + TooltipIconButton( + modifier = modifier, + icon = { + Box( + modifier = Modifier + .size(24.dp) + .background(Color.White, shape = CircleShape) + ) + }, + tooltipText = "This is a placeholder tooltip message. It demonstrates how" + + " text wraps and aligns.", + positioning = TooltipAnchorPosition.Below, + isOutlined = true, + containerColor = containerColor + ) + } + } + } + LayoutWrapper( modifier = modifier, scaffoldState = scaffoldState, @@ -830,6 +854,7 @@ private fun ContentScreen( snackBar = snackBarLambda, pauseToggleButton = pauseToggleButtonLambda, imageWell = imageWellLambda, + topEndContent = topEndContentLambda, errorDialog = errorDialogLambda ) } @@ -927,6 +952,8 @@ private fun LayoutWrapper( debugVisibilityWrapper: (@Composable (@Composable () -> Unit) -> Unit), screenFlashOverlay: @Composable (modifier: Modifier) -> Unit, snackBar: @Composable (modifier: Modifier, snackbarHostState: SnackbarHostState) -> Unit, + topStartContent: @Composable (modifier: Modifier) -> Unit = {}, + topEndContent: @Composable (modifier: Modifier, containerColor: Color) -> Unit = { _, _ -> }, errorDialog: @Composable (modifier: Modifier) -> Unit = {} ) { PreviewLayout( @@ -955,22 +982,10 @@ private fun LayoutWrapper( videoQualityIndicator(Modifier) stabilizationIndicator(Modifier) } - - // TODO: this whole button is currently a PLACEHOLDER - TooltipIconButton( - icon = { - Box( - modifier = Modifier - .size(24.dp) - .background(Color.White, shape = CircleShape) - ) - }, - tooltipText = "This is a placeholder tooltip message. It demonstrates how" + - " text wraps and aligns.", - isOutlined = true - ) } }, + topStartContent = topStartContent, + topEndContent = topEndContent, debugOverlay = { modifier -> debugOverlay( modifier, 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 57b3318322..362e249044 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 @@ -15,6 +15,8 @@ */ package com.google.jetpackcamera.ui.components.capture +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.snap import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource @@ -52,6 +54,7 @@ import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment @@ -87,6 +90,7 @@ import androidx.compose.ui.unit.takeOrElse * @param screenFlashOverlay the screen flash overlay composable * @param snackBar the snack bar composable for showing messages * @param topStartContent optional composable content aligned to the top-start of the viewfinder + * @param topEndContent optional composable content aligned to the end of the top bar / status bar, receiving layout modifier and overlap-aware containerColor * @param errorDialog the camera error alert dialog composable */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @@ -116,6 +120,7 @@ fun PreviewLayout( screenFlashOverlay: @Composable (Modifier) -> Unit, snackBar: @Composable (Modifier, snackbarHostState: SnackbarHostState) -> Unit, topStartContent: @Composable (Modifier) -> Unit = {}, + topEndContent: @Composable (Modifier, containerColor: Color) -> Unit = { _, _ -> }, errorDialog: @Composable (Modifier) -> Unit = {} ) { val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } @@ -167,6 +172,33 @@ fun PreviewLayout( contentAlignment = Alignment.CenterStart ) { indicatorRow(Modifier) + OverlapAwareStyleProvider( + modifier = Modifier.align(Alignment.CenterEnd), + initialStyle = CameraControlBackgroundStyle.WHITE_20 + ) { + val backgroundStyle = LocalCameraControlBackgroundStyle.current + val isOverlapping = + backgroundStyle == CameraControlBackgroundStyle.BLACK_60 + val targetContainerColor = if (isOverlapping) { + Color.Black.copy(alpha = 0.6f) + } else { + Color.Transparent + } + val disableAnimations = LocalDisableAnimations.current + val containerColor by animateColorAsState( + targetValue = targetContainerColor, + animationSpec = if (disableAnimations) { + snap() + } else { + CaptureTokens.FastEffectsSpec + }, + label = "topEndButtonContainerColor" + ) + topEndContent( + Modifier, + containerColor + ) + } } Box { viewfinder(Modifier) diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProvider.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProvider.kt index e3459021fe..848542ad4a 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProvider.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProvider.kt @@ -33,26 +33,32 @@ import androidx.compose.ui.layout.onGloballyPositioned * * @param modifier The [Modifier] to be applied to the outer layout. * @param overlapThreshold The ratio of overlap (between 0.0 and 1.0) required to switch the style. + * @param initialStyle The initial style to provide before spatial bounds are measured, preventing visual flicker on launch. * @param content The composable content that will receive the computed [LocalCameraControlBackgroundStyle]. */ @Composable internal fun OverlapAwareStyleProvider( modifier: Modifier = Modifier, overlapThreshold: Float = 0.5f, + initialStyle: CameraControlBackgroundStyle = CameraControlBackgroundStyle.WHITE_20, content: @Composable () -> Unit ) { val targetBounds = LocalOverlapTargetBounds.current.value var myBounds by remember { mutableStateOf(Rect.Zero) } - val intersect = targetBounds.intersect(myBounds) - val intersectArea = if (intersect.isEmpty) 0f else intersect.width * intersect.height - val myArea = myBounds.width * myBounds.height - val isOverlapping = myArea > 0f && (intersectArea / myArea) >= overlapThreshold - - val style = if (isOverlapping) { - CameraControlBackgroundStyle.BLACK_60 + val hasMeasured = myBounds != Rect.Zero && targetBounds != Rect.Zero + val style = if (hasMeasured) { + val intersect = targetBounds.intersect(myBounds) + val intersectArea = if (intersect.isEmpty) 0f else intersect.width * intersect.height + val myArea = myBounds.width * myBounds.height + val isOverlapping = myArea > 0f && (intersectArea / myArea) >= overlapThreshold + if (isOverlapping) { + CameraControlBackgroundStyle.BLACK_60 + } else { + CameraControlBackgroundStyle.WHITE_20 + } } else { - CameraControlBackgroundStyle.WHITE_20 + initialStyle } Box( diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProviderTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProviderTest.kt index 23bd6f19b0..cd614abb33 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProviderTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProviderTest.kt @@ -23,7 +23,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect -import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.unit.dp import com.google.common.truth.Truth.assertThat import org.junit.Rule @@ -153,4 +153,56 @@ class OverlapAwareStyleProviderTest { // the 0f intersection correctly results in WHITE_20. assertThat(detectedStyle).isEqualTo(CameraControlBackgroundStyle.WHITE_20) } + + @Test + fun overlapAware_initialStyleBlack60_providesBlack60BeforeMeasurement() { + var detectedStyle: CameraControlBackgroundStyle? = null + + composeTestRule.setContent { + // Target bounds are Rect.Zero (unmeasured preview) + Box(Modifier.size(500.dp)) { + OverlapAwareStyleProvider( + modifier = Modifier.size(100.dp), + initialStyle = CameraControlBackgroundStyle.BLACK_60 + ) { + detectedStyle = LocalCameraControlBackgroundStyle.current + } + } + } + // Before bounds are available, it provides initialStyle + assertThat(detectedStyle).isEqualTo(CameraControlBackgroundStyle.BLACK_60) + } + + @Test + fun overlapAware_initialStyleBlack60_transitionsToWhite20WhenNoOverlapMeasured() { + var detectedStyle: CameraControlBackgroundStyle? = null + + composeTestRule.setContent { + val density = androidx.compose.ui.platform.LocalDensity.current + val targetBoundsPx = remember(density) { + with(density) { + Rect(0f, 0f, 100.dp.toPx(), 100.dp.toPx()) + } + } + Box(Modifier.size(500.dp)) { + CompositionLocalProvider( + LocalOverlapTargetBounds provides remember( + targetBoundsPx + ) { mutableStateOf(targetBoundsPx) } + ) { + OverlapAwareStyleProvider( + modifier = Modifier + .offset(x = 0.dp, y = 110.dp) + .size(100.dp), + initialStyle = CameraControlBackgroundStyle.BLACK_60 + ) { + detectedStyle = LocalCameraControlBackgroundStyle.current + } + } + } + } + composeTestRule.waitForIdle() + // Once measured with no overlap, it transitions to WHITE_20 + assertThat(detectedStyle).isEqualTo(CameraControlBackgroundStyle.WHITE_20) + } } diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index e76292b2e3..9b322081b0 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -21,6 +21,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedIconButton import androidx.compose.material3.RichTooltip @@ -186,6 +187,8 @@ fun JcaTooltipBox( * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. * @param triggerFlow Optional flow of [TooltipTriggerEvent] to trigger showing or dismissing. * @param isOutlined Whether the icon button should be outlined. + * @param containerColor The background container color for the button. + * @param contentColor The content/tint color for the icon. * @param onClick Optional callback when the button is clicked. * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. */ @@ -201,6 +204,8 @@ fun TooltipIconButton( autoDismissDuration: Duration? = null, triggerFlow: Flow? = null, isOutlined: Boolean = false, + containerColor: Color = Color.Transparent, + contentColor: Color = Color.White, onClick: () -> Unit = {}, onDismissRequest: (() -> Unit)? = null ) { @@ -237,6 +242,10 @@ fun TooltipIconButton( OutlinedIconButton( onClick = toggleTooltip, modifier = buttonModifier, + colors = IconButtonDefaults.outlinedIconButtonColors( + containerColor = containerColor, + contentColor = contentColor + ), border = BorderStroke(1.dp, Color.White.copy(alpha = 0.2f)) ) { icon() @@ -244,7 +253,11 @@ fun TooltipIconButton( } else { IconButton( onClick = toggleTooltip, - modifier = buttonModifier + modifier = buttonModifier, + colors = IconButtonDefaults.iconButtonColors( + containerColor = containerColor, + contentColor = contentColor + ) ) { icon() } diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index e37b2bbf9a..d210b57b5d 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -19,9 +19,9 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasText @@ -209,4 +209,21 @@ class TooltipTest { composeTestRule.onNode(isPopup()).assertDoesNotExist() } + + @Test + fun tooltip_customContainerColor_appliesCorrectly() { + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "Custom colors", + isOutlined = true, + containerColor = Color.Black.copy(alpha = 0.6f), + contentColor = Color.White + ) + } + } + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).assertExists() + } } From 3c047c3748b8c930c617deb8aee2abc9e2c4965c Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 21 Oct 2026 14:39:45 -0700 Subject: [PATCH 09/20] Align tooltip button dimensions, padding, and size tokens with Figma specs - Use IconButtonDefaults.extraSmallContainerSize() for default TooltipIconButton container size (32.dp). - Use IconButtonDefaults.extraSmallIconSize for placeholder icon size (20.dp). - Add 24.dp end padding to status bar button placement in CaptureLayout to achieve 40.dp total clearance from screen edge. - Add unit test in TooltipTest verifying custom size application. --- .../feature/preview/PreviewScreen.kt | 3 ++- .../ui/components/capture/CaptureLayout.kt | 4 +++- .../google/jetpackcamera/ui/components/Tooltip.kt | 5 +++++ .../jetpackcamera/ui/components/TooltipTest.kt | 15 +++++++++++++++ 4 files changed, 25 insertions(+), 2 deletions(-) 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 ef7a547560..9c22ac6810 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 @@ -39,6 +39,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.BottomSheetScaffoldState import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SheetValue import androidx.compose.material3.SnackbarHostState @@ -815,7 +816,7 @@ private fun ContentScreen( icon = { Box( modifier = Modifier - .size(24.dp) + .size(IconButtonDefaults.extraSmallIconSize) .background(Color.White, shape = CircleShape) ) }, 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 362e249044..98c8db4414 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 @@ -173,7 +173,9 @@ fun PreviewLayout( ) { indicatorRow(Modifier) OverlapAwareStyleProvider( - modifier = Modifier.align(Alignment.CenterEnd), + modifier = Modifier + .align(Alignment.CenterEnd) + .padding(end = 24.dp), initialStyle = CameraControlBackgroundStyle.WHITE_20 ) { val backgroundStyle = LocalCameraControlBackgroundStyle.current diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 9b322081b0..d33d008926 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -18,6 +18,7 @@ package com.google.jetpackcamera.ui.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton @@ -46,6 +47,7 @@ import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.paneTitle import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlin.time.Duration import kotlinx.coroutines.delay @@ -189,6 +191,7 @@ fun JcaTooltipBox( * @param isOutlined Whether the icon button should be outlined. * @param containerColor The background container color for the button. * @param contentColor The content/tint color for the icon. + * @param size The size of the button container, defaulting to [IconButtonDefaults.extraSmallContainerSize] (32.dp). * @param onClick Optional callback when the button is clicked. * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. */ @@ -206,6 +209,7 @@ fun TooltipIconButton( isOutlined: Boolean = false, containerColor: Color = Color.Transparent, contentColor: Color = Color.White, + size: Dp = IconButtonDefaults.extraSmallContainerSize().width, onClick: () -> Unit = {}, onDismissRequest: (() -> Unit)? = null ) { @@ -236,6 +240,7 @@ fun TooltipIconButton( onDismissRequest = onDismissRequest ) { val buttonModifier = Modifier + .size(size) .testTag(TOOLTIP_ANCHOR_BUTTON_TAG) if (isOutlined) { diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index d210b57b5d..768badfe1f 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -226,4 +226,19 @@ class TooltipTest { composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).assertExists() } + + @Test + fun tooltip_customSize_appliesCorrectly() { + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(20.dp)) }, + tooltipText = "Custom size", + size = 32.dp + ) + } + } + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).assertExists() + } } From 284217687995475f810c148c2e3b8b35e79c2094 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 27 Oct 2026 13:26:19 -0700 Subject: [PATCH 10/20] Implement bespoke Compose Popup tooltip with dynamic caret tracking - Replace upstream RichTooltip with Compose Popup, JcaTooltipPositionProvider, and JcaTooltipBubbleShape for synchronous Frame 0 caret calculation. - Add continuous vector path uniting rounded bubble and triangular caret with corner-radius boundary clamping. - Support CaretAlignment options: AnchorCenter, BubbleCenter, Start, End, and Custom offset. - Move TooltipIconButton into top bar indicatorRow preceding flash mode indicator and remove topEndContent from CaptureLayout. - Add KDoc explaining upstream Material 3 RichTooltip limitations. - Add unit tests for position provider clamping, vertical flipping, caret alignment modes, and shape outline bounds. --- .../feature/preview/PreviewScreen.kt | 40 +- .../ui/components/capture/CaptureLayout.kt | 33 - .../jetpackcamera/ui/components/Tooltip.kt | 592 ++++++++++++++++-- .../ui/components/TooltipTest.kt | 158 +++++ 4 files changed, 702 insertions(+), 121 deletions(-) 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 9c22ac6810..ba7a8d9405 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 @@ -807,29 +807,6 @@ private fun ContentScreen( } } - val topEndContentLambda = remember(isErrorDialogShowing) { - @Composable { modifier: Modifier, containerColor: Color -> - if (!isErrorDialogShowing) { - // TODO: Finalize UX design and positioning with design team. - TooltipIconButton( - modifier = modifier, - icon = { - Box( - modifier = Modifier - .size(IconButtonDefaults.extraSmallIconSize) - .background(Color.White, shape = CircleShape) - ) - }, - tooltipText = "This is a placeholder tooltip message. It demonstrates how" + - " text wraps and aligns.", - positioning = TooltipAnchorPosition.Below, - isOutlined = true, - containerColor = containerColor - ) - } - } - } - LayoutWrapper( modifier = modifier, scaffoldState = scaffoldState, @@ -855,7 +832,6 @@ private fun ContentScreen( snackBar = snackBarLambda, pauseToggleButton = pauseToggleButtonLambda, imageWell = imageWellLambda, - topEndContent = topEndContentLambda, errorDialog = errorDialogLambda ) } @@ -954,7 +930,6 @@ private fun LayoutWrapper( screenFlashOverlay: @Composable (modifier: Modifier) -> Unit, snackBar: @Composable (modifier: Modifier, snackbarHostState: SnackbarHostState) -> Unit, topStartContent: @Composable (modifier: Modifier) -> Unit = {}, - topEndContent: @Composable (modifier: Modifier, containerColor: Color) -> Unit = { _, _ -> }, errorDialog: @Composable (modifier: Modifier) -> Unit = {} ) { PreviewLayout( @@ -978,6 +953,20 @@ private fun LayoutWrapper( verticalAlignment = Alignment.CenterVertically, horizontalSpacing = 8.dp ) { + TooltipIconButton( + modifier = Modifier, + icon = { + Box( + modifier = Modifier + .size(IconButtonDefaults.extraSmallIconSize) + .background(Color.White, shape = CircleShape) + ) + }, + tooltipText = "This is a placeholder tooltip message. It demonstrates how" + + " text wraps and aligns.", + positioning = TooltipAnchorPosition.Below, + isOutlined = true + ) flashModeIndicator(Modifier) hdrIndicator(Modifier) videoQualityIndicator(Modifier) @@ -986,7 +975,6 @@ private fun LayoutWrapper( } }, topStartContent = topStartContent, - topEndContent = topEndContent, debugOverlay = { modifier -> debugOverlay( modifier, 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 98c8db4414..c21d54fad0 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 @@ -15,8 +15,6 @@ */ package com.google.jetpackcamera.ui.components.capture -import androidx.compose.animation.animateColorAsState -import androidx.compose.animation.core.snap import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource @@ -90,7 +88,6 @@ import androidx.compose.ui.unit.takeOrElse * @param screenFlashOverlay the screen flash overlay composable * @param snackBar the snack bar composable for showing messages * @param topStartContent optional composable content aligned to the top-start of the viewfinder - * @param topEndContent optional composable content aligned to the end of the top bar / status bar, receiving layout modifier and overlap-aware containerColor * @param errorDialog the camera error alert dialog composable */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @@ -120,7 +117,6 @@ fun PreviewLayout( screenFlashOverlay: @Composable (Modifier) -> Unit, snackBar: @Composable (Modifier, snackbarHostState: SnackbarHostState) -> Unit, topStartContent: @Composable (Modifier) -> Unit = {}, - topEndContent: @Composable (Modifier, containerColor: Color) -> Unit = { _, _ -> }, errorDialog: @Composable (Modifier) -> Unit = {} ) { val overlapTargetBounds = remember { mutableStateOf(Rect.Zero) } @@ -172,35 +168,6 @@ fun PreviewLayout( contentAlignment = Alignment.CenterStart ) { indicatorRow(Modifier) - OverlapAwareStyleProvider( - modifier = Modifier - .align(Alignment.CenterEnd) - .padding(end = 24.dp), - initialStyle = CameraControlBackgroundStyle.WHITE_20 - ) { - val backgroundStyle = LocalCameraControlBackgroundStyle.current - val isOverlapping = - backgroundStyle == CameraControlBackgroundStyle.BLACK_60 - val targetContainerColor = if (isOverlapping) { - Color.Black.copy(alpha = 0.6f) - } else { - Color.Transparent - } - val disableAnimations = LocalDisableAnimations.current - val containerColor by animateColorAsState( - targetValue = targetContainerColor, - animationSpec = if (disableAnimations) { - snap() - } else { - CaptureTokens.FastEffectsSpec - }, - label = "topEndButtonContainerColor" - ) - topEndContent( - Modifier, - containerColor - ) - } } Box { viewfinder(Modifier) diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index d33d008926..b3b08360bb 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -16,6 +16,11 @@ package com.google.jetpackcamera.ui.components import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.waitForUpOrCancellation +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -25,39 +30,389 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedIconButton -import androidx.compose.material3.RichTooltip +import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition -import androidx.compose.material3.TooltipBox -import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.TooltipState import androidx.compose.material3.rememberTooltipState import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.PointerEventTimeoutCancellationException +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.paneTitle import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties +import kotlin.math.roundToInt import kotlin.time.Duration +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeout const val TOOLTIP_ANCHOR_BUTTON_TAG = "tooltip_anchor_button" const val TOOLTIP_CONTENT_TAG = "tooltip_content" +/** + * Custom Tooltip Implementation Workaround Rationale: + * + * Upstream Material 3's [androidx.compose.material3.RichTooltip] and [androidx.compose.material3.TooltipBox] + * suffer from three primary limitations that prevent accurate placement in custom camera layouts: + * + * 1. Misaligned Caret Coordinates: Material 3 computes caret offsets using an internal `Modifier.layoutCaret` + * and private `caretX(...)` function. When clamping the popup against window margins, M3's formula incorrectly + * assumes the tooltip popup is flush with the anchor edge or hardcoded margins. When the calling button is small + * or positioned near the screen edge (such as in an indicator or status bar), this causes the caret to drift + * tens of pixels away from the anchor center. + * 2. Visual Hitch / Asynchronous Delay: M3 calculates caret transformations inside an asynchronous + * `onLayoutRectChanged` / `onGloballyPositioned` callback. This causes an unavoidable 1-frame visual jump where + * the tooltip first renders with default/stale caret coordinates before snapping to the recalculated position, + * triggering a full subtree recreation keyed on `tooltipSide`. + * 3. Caret Shape Continuity: M3 draws the caret as a detached child rotated via a transformation matrix, + * preventing unified background fills, continuous corner-radius clipping, and single-pass elevation shadows. + * + * To resolve this, [JcaTooltipBox] uses standard Compose [androidx.compose.ui.window.Popup] paired with + * [JcaTooltipPositionProvider] and [JcaTooltipBubbleShape]. This synchronously computes both popup window placement + * and the exact pixel-level local caret coordinates on Frame 0 before draw, guarantees safe screen margins (16dp), + * protects against corner-radius bleed, and supports flexible [CaretAlignment] configurations. + */ + +/** + * Alignment options for the tooltip caret along the horizontal edge of the tooltip bubble. + */ +sealed interface CaretAlignment { + /** Positions the caret to point directly to the horizontal center of the anchor component. */ + data object AnchorCenter : CaretAlignment + + /** Positions the caret at the horizontal center of the tooltip bubble. */ + data object BubbleCenter : CaretAlignment + + /** Positions the caret near the start edge (respecting layout direction). */ + data object Start : CaretAlignment + + /** Positions the caret near the end edge (respecting layout direction). */ + data object End : CaretAlignment + + /** Positions the caret at a custom horizontal offset from the start edge. */ + data class Custom(val offset: Dp) : CaretAlignment +} + +/** + * Color configuration for the tooltip bubble. + */ +@Immutable +data class JcaTooltipColors( + val containerColor: Color, + val contentColor: Color, + val titleContentColor: Color +) + +/** + * Default dimensions, styling tokens, and color values for JCA tooltips. + */ +object JcaTooltipDefaults { + val MinWidth: Dp = 140.dp + val MaxWidth: Dp = 296.dp + val CornerRadius: Dp = 12.dp + val CaretWidth: Dp = 16.dp + val CaretHeight: Dp = 8.dp + val ScreenMargin: Dp = 16.dp + val SpacingBetweenTooltipAndAnchor: Dp = 4.dp + val DefaultElevation: Dp = 4.dp + + @Composable + fun tooltipColors( + containerColor: Color = MaterialTheme.colorScheme.secondaryFixed, + contentColor: Color = MaterialTheme.colorScheme.onSecondaryFixed, + titleContentColor: Color = MaterialTheme.colorScheme.onSecondaryFixed + ): JcaTooltipColors = JcaTooltipColors( + containerColor = containerColor, + contentColor = contentColor, + titleContentColor = titleContentColor + ) +} + +/** + * State holder for dynamic caret positioning. + */ +@Stable +class CaretPositionState( + initialCaretX: Float = 0f, + initialIsCaretOnTop: Boolean = true +) { + var localCaretX: Float by mutableFloatStateOf(initialCaretX) + var isCaretOnTop: Boolean by mutableStateOf(initialIsCaretOnTop) +} + +/** + * Vector shape that draws a continuous outline combining a rounded rectangle bubble + * and a triangular caret pointing toward the anchor. + */ +class JcaTooltipBubbleShape( + val localCaretX: Float, + val isCaretOnTop: Boolean, + val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, + val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, + val caretHeight: Dp = JcaTooltipDefaults.CaretHeight +) : Shape { + override fun createOutline( + size: Size, + layoutDirection: LayoutDirection, + density: Density + ): Outline { + val w = size.width + val h = size.height + if (w <= 0f || h <= 0f) { + return Outline.Rectangle(Rect.Zero) + } + + val r = with(density) { cornerRadius.toPx() } + val cw = with(density) { caretWidth.toPx() } + val ch = with(density) { caretHeight.toPx() } + + val bodyHeight = (h - ch).coerceAtLeast(0f) + val actualRadius = minOf(r, bodyHeight / 2f, w / 2f).coerceAtLeast(0f) + + // Clamp caret base to ensure the triangle never bleeds into the corner radius arcs + val minCaretX = actualRadius + cw / 2f + val maxCaretX = (w - actualRadius - cw / 2f).coerceAtLeast(minCaretX) + val clampedCaretX = localCaretX.coerceIn(minCaretX, maxCaretX) + + val path = Path() + if (isCaretOnTop) { + val bodyTop = ch + val bodyBottom = h + + path.moveTo(actualRadius, bodyTop) + path.lineTo(clampedCaretX - cw / 2f, bodyTop) + path.lineTo(clampedCaretX, 0f) + path.lineTo(clampedCaretX + cw / 2f, bodyTop) + path.lineTo(w - actualRadius, bodyTop) + path.arcTo( + rect = Rect(w - 2f * actualRadius, bodyTop, w, bodyTop + 2f * actualRadius), + startAngleDegrees = 270f, + sweepAngleDegrees = 90f, + forceMoveTo = false + ) + path.lineTo(w, bodyBottom - actualRadius) + path.arcTo( + rect = Rect(w - 2f * actualRadius, bodyBottom - 2f * actualRadius, w, bodyBottom), + startAngleDegrees = 0f, + sweepAngleDegrees = 90f, + forceMoveTo = false + ) + path.lineTo(actualRadius, bodyBottom) + path.arcTo( + rect = Rect(0f, bodyBottom - 2f * actualRadius, 2f * actualRadius, bodyBottom), + startAngleDegrees = 90f, + sweepAngleDegrees = 90f, + forceMoveTo = false + ) + path.lineTo(0f, bodyTop + actualRadius) + path.arcTo( + rect = Rect(0f, bodyTop, 2f * actualRadius, bodyTop + 2f * actualRadius), + startAngleDegrees = 180f, + sweepAngleDegrees = 90f, + forceMoveTo = false + ) + path.close() + } else { + val bodyTop = 0f + val bodyBottom = h - ch + + path.moveTo(actualRadius, bodyTop) + path.lineTo(w - actualRadius, bodyTop) + path.arcTo( + rect = Rect(w - 2f * actualRadius, bodyTop, w, bodyTop + 2f * actualRadius), + startAngleDegrees = 270f, + sweepAngleDegrees = 90f, + forceMoveTo = false + ) + path.lineTo(w, bodyBottom - actualRadius) + path.arcTo( + rect = Rect(w - 2f * actualRadius, bodyBottom - 2f * actualRadius, w, bodyBottom), + startAngleDegrees = 0f, + sweepAngleDegrees = 90f, + forceMoveTo = false + ) + path.lineTo(clampedCaretX + cw / 2f, bodyBottom) + path.lineTo(clampedCaretX, h) + path.lineTo(clampedCaretX - cw / 2f, bodyBottom) + path.lineTo(actualRadius, bodyBottom) + path.arcTo( + rect = Rect(0f, bodyBottom - 2f * actualRadius, 2f * actualRadius, bodyBottom), + startAngleDegrees = 90f, + sweepAngleDegrees = 90f, + forceMoveTo = false + ) + path.lineTo(0f, bodyTop + actualRadius) + path.arcTo( + rect = Rect(0f, bodyTop, 2f * actualRadius, bodyTop + 2f * actualRadius), + startAngleDegrees = 180f, + sweepAngleDegrees = 90f, + forceMoveTo = false + ) + path.close() + } + + return Outline.Generic(path) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is JcaTooltipBubbleShape) return false + return localCaretX == other.localCaretX && + isCaretOnTop == other.isCaretOnTop && + cornerRadius == other.cornerRadius && + caretWidth == other.caretWidth && + caretHeight == other.caretHeight + } + + override fun hashCode(): Int { + var result = localCaretX.hashCode() + result = 31 * result + isCaretOnTop.hashCode() + result = 31 * result + cornerRadius.hashCode() + result = 31 * result + caretWidth.hashCode() + result = 31 * result + caretHeight.hashCode() + return result + } +} + +/** + * Position provider for the tooltip popup that calculates screen-clamped coordinates and + * derives the local caret offset relative to the popup's top-left corner on Frame 0 before draw. + */ +@OptIn(ExperimentalMaterial3Api::class) +class JcaTooltipPositionProvider( + val positioning: TooltipAnchorPosition, + val caretAlignment: CaretAlignment = CaretAlignment.AnchorCenter, + val spacing: Dp = JcaTooltipDefaults.SpacingBetweenTooltipAndAnchor, + val screenMargin: Dp = JcaTooltipDefaults.ScreenMargin, + val density: Density, + val onCaretCalculated: (localCaretX: Float, isCaretOnTop: Boolean) -> Unit = { _, _ -> } +) : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize + ): IntOffset { + val spacingPx = with(density) { spacing.roundToPx() } + val marginPx = with(density) { screenMargin.roundToPx() } + + // Vertical placement: Above vs Below with automatic flipping when constrained + val spaceAbove = anchorBounds.top - spacingPx + val spaceBelow = windowSize.height - anchorBounds.bottom - spacingPx + + val placeBelow = when (positioning) { + TooltipAnchorPosition.Below -> { + if (spaceBelow >= popupContentSize.height || spaceBelow >= spaceAbove) { + true + } else { + false + } + } + TooltipAnchorPosition.Above -> { + if (spaceAbove >= popupContentSize.height || spaceAbove >= spaceBelow) { + false + } else { + true + } + } + else -> spaceBelow >= popupContentSize.height + } + + val popupY = if (placeBelow) { + anchorBounds.bottom + spacingPx + } else { + anchorBounds.top - spacingPx - popupContentSize.height + } + + // Horizontal placement: Center over anchor by default, clamped to safe screen margins + val anchorCenterX = (anchorBounds.left + anchorBounds.right) / 2f + val idealPopupX = (anchorCenterX - popupContentSize.width / 2f).roundToInt() + + val minX = marginPx + val maxX = (windowSize.width - marginPx - popupContentSize.width).coerceAtLeast(minX) + val popupX = idealPopupX.coerceIn(minX, maxX) + + // Local caret X coordinate relative to the popup's top-left corner + val localCaretX = when (caretAlignment) { + is CaretAlignment.AnchorCenter -> { + anchorCenterX - popupX + } + is CaretAlignment.BubbleCenter -> { + popupContentSize.width / 2f + } + is CaretAlignment.Start -> { + val cornerRadiusPx = with(density) { JcaTooltipDefaults.CornerRadius.toPx() } + val caretWidthPx = with(density) { JcaTooltipDefaults.CaretWidth.toPx() } + if (layoutDirection == LayoutDirection.Rtl) { + popupContentSize.width - cornerRadiusPx - caretWidthPx / 2f + } else { + cornerRadiusPx + caretWidthPx / 2f + } + } + is CaretAlignment.End -> { + val cornerRadiusPx = with(density) { JcaTooltipDefaults.CornerRadius.toPx() } + val caretWidthPx = with(density) { JcaTooltipDefaults.CaretWidth.toPx() } + if (layoutDirection == LayoutDirection.Rtl) { + cornerRadiusPx + caretWidthPx / 2f + } else { + popupContentSize.width - cornerRadiusPx - caretWidthPx / 2f + } + } + is CaretAlignment.Custom -> { + val offsetPx = with(density) { caretAlignment.offset.toPx() } + if (layoutDirection == LayoutDirection.Rtl) { + popupContentSize.width - offsetPx + } else { + offsetPx + } + } + } + + onCaretCalculated(localCaretX, placeBelow) + + return IntOffset(popupX, popupY) + } +} + /** * Events used to trigger programmatic display or dismissal of tooltips. */ @@ -67,16 +422,95 @@ sealed interface TooltipTriggerEvent { } /** - * A generic container that wraps content with a styled [RichTooltip]. + * Custom tooltip bubble composable rendering styled text and an optional title within + * a unified [JcaTooltipBubbleShape]. + */ +@Composable +fun JcaTooltipBubble( + tooltipText: String, + modifier: Modifier = Modifier, + tooltipTitle: String? = null, + caretPositionState: CaretPositionState = remember { CaretPositionState() }, + colors: JcaTooltipColors = JcaTooltipDefaults.tooltipColors(), + elevation: Dp = JcaTooltipDefaults.DefaultElevation +) { + val isCaretOnTop = caretPositionState.isCaretOnTop + val localCaretX = caretPositionState.localCaretX + + val bubbleShape = remember(localCaretX, isCaretOnTop) { + JcaTooltipBubbleShape( + localCaretX = localCaretX, + isCaretOnTop = isCaretOnTop + ) + } + + val topPadding = if (isCaretOnTop) { + JcaTooltipDefaults.CaretHeight + 10.dp + } else { + 10.dp + } + val bottomPadding = if (!isCaretOnTop) { + JcaTooltipDefaults.CaretHeight + 10.dp + } else { + 10.dp + } + + Surface( + shape = bubbleShape, + color = colors.containerColor, + shadowElevation = elevation, + modifier = modifier + .widthIn(min = JcaTooltipDefaults.MinWidth, max = JcaTooltipDefaults.MaxWidth) + .testTag(TOOLTIP_CONTENT_TAG) + .semantics { + liveRegion = LiveRegionMode.Assertive + paneTitle = tooltipTitle ?: tooltipText + } + ) { + Column( + modifier = Modifier.padding( + top = topPadding, + bottom = bottomPadding, + start = 12.dp, + end = 12.dp + ), + horizontalAlignment = Alignment.CenterHorizontally + ) { + if (tooltipTitle != null) { + Text( + text = tooltipTitle, + style = MaterialTheme.typography.titleSmall, + color = colors.titleContentColor, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 4.dp) + ) + } + Text( + text = tooltipText, + style = MaterialTheme.typography.bodySmall, + color = colors.contentColor, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth() + ) + } + } +} + +/** + * A generic container that wraps content with a styled tooltip using a bespoke Compose [Popup]. * * @param tooltipText The text to display inside the tooltip. * @param modifier Modifier for the container. * @param tooltipTitle Optional title displayed above the tooltip text. * @param state State controlling tooltip visibility. * @param positioning Anchor position for the tooltip (e.g. Above, Below). + * @param caretAlignment Alignment configuration for the caret. * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. * @param triggerFlow Optional flow of [TooltipTriggerEvent] to trigger showing or dismissing. - * @param enableUserInput Whether long-press and hover gestures on the anchor trigger the tooltip. + * @param enableUserInput Whether long-press gestures on the anchor trigger the tooltip. + * @param colors Colors applied to the tooltip bubble and text. * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. * @param content The anchor composable wrapped by the tooltip. */ @@ -88,12 +522,16 @@ fun JcaTooltipBox( tooltipTitle: String? = null, state: TooltipState = rememberTooltipState(isPersistent = true), positioning: TooltipAnchorPosition = TooltipAnchorPosition.Above, + caretAlignment: CaretAlignment = CaretAlignment.AnchorCenter, autoDismissDuration: Duration? = null, triggerFlow: Flow? = null, enableUserInput: Boolean = true, + colors: JcaTooltipColors = JcaTooltipDefaults.tooltipColors(), onDismissRequest: (() -> Unit)? = null, content: @Composable () -> Unit ) { + val scope = rememberCoroutineScope() + val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) var triggerRevision by remember { mutableIntStateOf(0) } // External flow triggers using collectLatest to prevent deadlock from show() suspension @@ -117,75 +555,100 @@ fun JcaTooltipBox( if (state.transition.targetState) { delay(autoDismissDuration) state.dismiss() - onDismissRequest?.invoke() + currentOnDismissRequest?.invoke() } } } - TooltipBox( - positionProvider = TooltipDefaults.rememberTooltipPositionProvider( - positioning = positioning - ), - tooltip = { - RichTooltip( - modifier = Modifier - .widthIn(min = 140.dp, max = 296.dp) - .testTag(TOOLTIP_CONTENT_TAG) - .semantics { - liveRegion = LiveRegionMode.Assertive - paneTitle = tooltipTitle ?: tooltipText - }, - title = tooltipTitle?.let { - { - Text( - text = it, - textAlign = TextAlign.Center, - modifier = Modifier - .fillMaxWidth() - .padding(top = 10.dp) - ) - } - }, - text = { - Text( - text = tooltipText, - textAlign = TextAlign.Center, - modifier = Modifier - .fillMaxWidth() - .padding( - top = if (tooltipTitle != null) 0.dp else 10.dp, - start = 10.dp, - end = 10.dp, - bottom = 10.dp - ) - ) - }, - colors = TooltipDefaults.richTooltipColors( - containerColor = MaterialTheme.colorScheme.secondaryFixed, - contentColor = MaterialTheme.colorScheme.onSecondaryFixed, - titleContentColor = MaterialTheme.colorScheme.onSecondaryFixed - ), - caretShape = TooltipDefaults.caretShape() - ) - }, - state = state, - modifier = modifier, - enableUserInput = enableUserInput, - onDismissRequest = onDismissRequest + val density = LocalDensity.current + val caretPositionState = remember { + CaretPositionState( + initialIsCaretOnTop = positioning == TooltipAnchorPosition.Below + ) + } + + val positionProvider = remember(positioning, caretAlignment, density) { + JcaTooltipPositionProvider( + positioning = positioning, + caretAlignment = caretAlignment, + density = density, + onCaretCalculated = { localCaretX, isCaretOnTop -> + caretPositionState.localCaretX = localCaretX + caretPositionState.isCaretOnTop = isCaretOnTop + } + ) + } + + Box( + modifier = modifier.tooltipGestures( + enabled = enableUserInput, + state = state, + scope = scope + ) ) { content() + + if (state.isVisible) { + Popup( + popupPositionProvider = positionProvider, + onDismissRequest = { + scope.launch { state.dismiss() } + currentOnDismissRequest?.invoke() + }, + properties = PopupProperties( + focusable = false, + clippingEnabled = false + ) + ) { + JcaTooltipBubble( + tooltipText = tooltipText, + tooltipTitle = tooltipTitle, + caretPositionState = caretPositionState, + colors = colors + ) + } + } + } + + DisposableEffect(state) { + onDispose { + state.onDispose() + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +private fun Modifier.tooltipGestures( + enabled: Boolean, + state: TooltipState, + scope: CoroutineScope +): Modifier = if (enabled) { + this.pointerInput(state) { + awaitEachGesture { + awaitFirstDown(pass = PointerEventPass.Initial) + try { + withTimeout(viewConfiguration.longPressTimeoutMillis) { + waitForUpOrCancellation(pass = PointerEventPass.Initial) + } + } catch (e: PointerEventTimeoutCancellationException) { + scope.launch { state.show() } + } + } } +} else { + this } /** - * An icon button that shows a styled [RichTooltip] when clicked. + * An icon button that shows a styled tooltip when clicked. * * @param icon The icon to display inside the button. * @param tooltipText The text to display inside the tooltip. * @param modifier Modifier for the button container. * @param tooltipTitle The optional title to display inside the tooltip. * @param state State controlling tooltip visibility. - * @param positioning Anchor position for the tooltip (e.g. Above, Below). + * @param positioning Anchor position for the tooltip (e.g. Above, Below). Defaults to Below. + * @param caretAlignment Alignment configuration for the caret. Defaults to AnchorCenter. * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. * @param triggerFlow Optional flow of [TooltipTriggerEvent] to trigger showing or dismissing. * @param isOutlined Whether the icon button should be outlined. @@ -203,7 +666,8 @@ fun TooltipIconButton( modifier: Modifier = Modifier, tooltipTitle: String? = null, state: TooltipState = rememberTooltipState(isPersistent = true), - positioning: TooltipAnchorPosition = TooltipAnchorPosition.Above, + positioning: TooltipAnchorPosition = TooltipAnchorPosition.Below, + caretAlignment: CaretAlignment = CaretAlignment.AnchorCenter, autoDismissDuration: Duration? = null, triggerFlow: Flow? = null, isOutlined: Boolean = false, @@ -214,17 +678,20 @@ fun TooltipIconButton( onDismissRequest: (() -> Unit)? = null ) { val scope = rememberCoroutineScope() - val toggleTooltip = remember(state, scope, onClick, onDismissRequest) { + val currentOnClick by rememberUpdatedState(onClick) + val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) + + val toggleTooltip = remember(state, scope) { { scope.launch { if (state.transition.targetState) { state.dismiss() - onDismissRequest?.invoke() + currentOnDismissRequest?.invoke() } else { state.show() } } - onClick() + currentOnClick() } } @@ -234,6 +701,7 @@ fun TooltipIconButton( tooltipTitle = tooltipTitle, state = state, positioning = positioning, + caretAlignment = caretAlignment, autoDismissDuration = autoDismissDuration, triggerFlow = triggerFlow, enableUserInput = false, diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index 768badfe1f..da919479ec 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -21,7 +21,9 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Outline import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasText @@ -29,7 +31,13 @@ import androidx.compose.ui.test.isPopup import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp +import com.google.common.truth.Truth.assertThat import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.flow.MutableSharedFlow import org.junit.Rule @@ -241,4 +249,154 @@ class TooltipTest { composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).assertExists() } + + @Test + fun positionProvider_anchoredToFarLeft_clampsToScreenMarginAndCalculatesCaret() { + var calculatedLocalCaretX = 0f + var calculatedIsCaretOnTop = false + + val provider = JcaTooltipPositionProvider( + positioning = TooltipAnchorPosition.Below, + caretAlignment = CaretAlignment.AnchorCenter, + spacing = 4.dp, + screenMargin = 16.dp, + density = Density(1f), + onCaretCalculated = { localCaretX, isCaretOnTop -> + calculatedLocalCaretX = localCaretX + calculatedIsCaretOnTop = isCaretOnTop + } + ) + + // Anchor placed near the left edge of the screen (e.g. status bar button) + val anchorBounds = IntRect(left = 16, top = 20, right = 48, bottom = 52) + val windowSize = IntSize(width = 1080, height = 2400) + val popupContentSize = IntSize(width = 400, height = 150) + + val position = provider.calculatePosition( + anchorBounds = anchorBounds, + windowSize = windowSize, + layoutDirection = LayoutDirection.Ltr, + popupContentSize = popupContentSize + ) + + // The popup is clamped to screen margin (16px) because ideal X (32 - 200 = -168) is offscreen + assertThat(position.x).isEqualTo(16) + // Positioned below anchor: bottom (52) + spacing (4) = 56 + assertThat(position.y).isEqualTo(56) + + // Local caret X is anchor center X (32) - popup X (16) = 16 + assertThat(calculatedLocalCaretX).isEqualTo(16f) + assertThat(calculatedIsCaretOnTop).isTrue() + + // Global caret X points exactly to anchor center X + assertThat(position.x + calculatedLocalCaretX.toInt()).isEqualTo((anchorBounds.left + anchorBounds.right) / 2) + } + + @Test + fun positionProvider_spaceConstrainedBelow_flipsAbove() { + var calculatedIsCaretOnTop = true + + val provider = JcaTooltipPositionProvider( + positioning = TooltipAnchorPosition.Below, + spacing = 4.dp, + screenMargin = 16.dp, + density = Density(1f), + onCaretCalculated = { _, isCaretOnTop -> + calculatedIsCaretOnTop = isCaretOnTop + } + ) + + // Anchor near bottom of window: spaceBelow is 48px, but tooltip height is 150px + val anchorBounds = IntRect(left = 200, top = 2300, right = 248, bottom = 2348) + val windowSize = IntSize(width = 1080, height = 2400) + val popupContentSize = IntSize(width = 400, height = 150) + + val position = provider.calculatePosition( + anchorBounds = anchorBounds, + windowSize = windowSize, + layoutDirection = LayoutDirection.Ltr, + popupContentSize = popupContentSize + ) + + // Flips above anchor: top (2300) - spacing (4) - popupHeight (150) = 2146 + assertThat(position.y).isEqualTo(2146) + // isCaretOnTop is false, meaning caret is drawn on bottom edge pointing DOWN to anchor + assertThat(calculatedIsCaretOnTop).isFalse() + } + + @Test + fun positionProvider_supportsCaretAlignmentOptions() { + val anchorBounds = IntRect(left = 200, top = 100, right = 300, bottom = 200) + val windowSize = IntSize(width = 1080, height = 2400) + val popupContentSize = IntSize(width = 400, height = 150) + + // BubbleCenter + var caretX = 0f + val bubbleCenterProvider = JcaTooltipPositionProvider( + positioning = TooltipAnchorPosition.Below, + caretAlignment = CaretAlignment.BubbleCenter, + density = Density(1f), + onCaretCalculated = { x, _ -> caretX = x } + ) + bubbleCenterProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) + assertThat(caretX).isEqualTo(200f) + + // Start (LTR) + val startProvider = JcaTooltipPositionProvider( + positioning = TooltipAnchorPosition.Below, + caretAlignment = CaretAlignment.Start, + density = Density(1f), + onCaretCalculated = { x, _ -> caretX = x } + ) + startProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) + // cornerRadius (12) + caretWidth / 2 (8) = 20 + assertThat(caretX).isEqualTo(20f) + + // End (LTR) + val endProvider = JcaTooltipPositionProvider( + positioning = TooltipAnchorPosition.Below, + caretAlignment = CaretAlignment.End, + density = Density(1f), + onCaretCalculated = { x, _ -> caretX = x } + ) + endProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) + // popupWidth (400) - cornerRadius (12) - caretWidth / 2 (8) = 380 + assertThat(caretX).isEqualTo(380f) + + // Custom offset + val customProvider = JcaTooltipPositionProvider( + positioning = TooltipAnchorPosition.Below, + caretAlignment = CaretAlignment.Custom(75.dp), + density = Density(1f), + onCaretCalculated = { x, _ -> caretX = x } + ) + customProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) + assertThat(caretX).isEqualTo(75f) + } + + @Test + fun bubbleShape_caretXClamped_doesNotBleedIntoCornerRadius() { + val density = Density(1f) + val size = Size(400f, 150f) + + // Shape with extreme negative caret X + val shapeNegative = JcaTooltipBubbleShape( + localCaretX = -100f, + isCaretOnTop = true + ) + val outlineNegative = shapeNegative.createOutline(size, LayoutDirection.Ltr, density) + assertThat(outlineNegative).isInstanceOf(Outline.Generic::class.java) + assertThat(outlineNegative.bounds.width).isEqualTo(400f) + assertThat(outlineNegative.bounds.height).isEqualTo(150f) + + // Shape with extreme positive caret X + val shapeOverflow = JcaTooltipBubbleShape( + localCaretX = 1000f, + isCaretOnTop = false + ) + val outlineOverflow = shapeOverflow.createOutline(size, LayoutDirection.Ltr, density) + assertThat(outlineOverflow).isInstanceOf(Outline.Generic::class.java) + assertThat(outlineOverflow.bounds.width).isEqualTo(400f) + assertThat(outlineOverflow.bounds.height).isEqualTo(150f) + } } From 844d7e5eefef6223d1bb9cdb8185cc317937dd4f Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 27 Oct 2026 13:30:26 -0700 Subject: [PATCH 11/20] Align tooltip button, dimensions, and typography with Figma and accessibility standards - Enforce 48.dp minimum interactive touch target on TooltipIconButton while maintaining 32.dp visual container and 24.dp icon dimensions. - Center 32.dp visual circular container inside 48.dp touch target, moving the anchor center from 32.dp to 40.dp and eliminating caret clamping offset. - Add TalkBack accessibility support to TooltipIconButton: Role.Button, contentDescription, onClickLabel, and ripple indication. - Update JcaTooltipBubble text typography to labelLarge (14.sp, weight 500, proportional line height) and content padding to 16.dp. - Add vertical scrolling to JcaTooltipBubble content column and screen margin clamping to popupY to prevent overflow under large font scaling. - Update JcaTooltipDefaults: CornerRadius to 16.dp and DefaultElevation to 2.dp. - Add unit tests verifying 48.dp touch target size and TalkBack semantics. --- .../feature/preview/PreviewScreen.kt | 3 +- .../jetpackcamera/ui/components/Tooltip.kt | 120 ++++++++++++------ .../ui/components/TooltipTest.kt | 47 ++++++- 3 files changed, 124 insertions(+), 46 deletions(-) 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 ba7a8d9405..719f41d353 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 @@ -958,10 +958,11 @@ private fun LayoutWrapper( icon = { Box( modifier = Modifier - .size(IconButtonDefaults.extraSmallIconSize) + .size(24.dp) .background(Color.White, shape = CircleShape) ) }, + contentDescription = "Show camera information", tooltipText = "This is a placeholder tooltip message. It demonstrates how" + " text wraps and aligns.", positioning = TooltipAnchorPosition.Below, diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index b3b08360bb..7c5a5a362d 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -16,26 +16,35 @@ package com.google.jetpackcamera.ui.components import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.waitForUpOrCancellation +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedIconButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.material3.TooltipState import androidx.compose.material3.rememberTooltipState +import androidx.compose.material3.ripple import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect @@ -62,9 +71,13 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.paneTitle +import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp @@ -148,12 +161,12 @@ data class JcaTooltipColors( object JcaTooltipDefaults { val MinWidth: Dp = 140.dp val MaxWidth: Dp = 296.dp - val CornerRadius: Dp = 12.dp + val CornerRadius: Dp = 16.dp val CaretWidth: Dp = 16.dp val CaretHeight: Dp = 8.dp val ScreenMargin: Dp = 16.dp val SpacingBetweenTooltipAndAnchor: Dp = 4.dp - val DefaultElevation: Dp = 4.dp + val DefaultElevation: Dp = 2.dp @Composable fun tooltipColors( @@ -357,11 +370,14 @@ class JcaTooltipPositionProvider( else -> spaceBelow >= popupContentSize.height } - val popupY = if (placeBelow) { + val idealPopupY = if (placeBelow) { anchorBounds.bottom + spacingPx } else { anchorBounds.top - spacingPx - popupContentSize.height } + val minY = marginPx + val maxY = (windowSize.height - marginPx - popupContentSize.height).coerceAtLeast(minY) + val popupY = idealPopupY.coerceIn(minY, maxY) // Horizontal placement: Center over anchor by default, clamped to safe screen margins val anchorCenterX = (anchorBounds.left + anchorBounds.right) / 2f @@ -445,14 +461,14 @@ fun JcaTooltipBubble( } val topPadding = if (isCaretOnTop) { - JcaTooltipDefaults.CaretHeight + 10.dp + JcaTooltipDefaults.CaretHeight + 16.dp } else { - 10.dp + 16.dp } val bottomPadding = if (!isCaretOnTop) { - JcaTooltipDefaults.CaretHeight + 10.dp + JcaTooltipDefaults.CaretHeight + 16.dp } else { - 10.dp + 16.dp } Surface( @@ -468,12 +484,14 @@ fun JcaTooltipBubble( } ) { Column( - modifier = Modifier.padding( - top = topPadding, - bottom = bottomPadding, - start = 12.dp, - end = 12.dp - ), + modifier = Modifier + .padding( + top = topPadding, + bottom = bottomPadding, + start = 16.dp, + end = 16.dp + ) + .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { if (tooltipTitle != null) { @@ -489,7 +507,9 @@ fun JcaTooltipBubble( } Text( text = tooltipText, - style = MaterialTheme.typography.bodySmall, + style = MaterialTheme.typography.labelLarge.copy( + fontWeight = FontWeight.Medium + ), color = colors.contentColor, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth() @@ -645,6 +665,7 @@ private fun Modifier.tooltipGestures( * @param icon The icon to display inside the button. * @param tooltipText The text to display inside the tooltip. * @param modifier Modifier for the button container. + * @param contentDescription Optional accessibility content description for TalkBack. * @param tooltipTitle The optional title to display inside the tooltip. * @param state State controlling tooltip visibility. * @param positioning Anchor position for the tooltip (e.g. Above, Below). Defaults to Below. @@ -654,7 +675,8 @@ private fun Modifier.tooltipGestures( * @param isOutlined Whether the icon button should be outlined. * @param containerColor The background container color for the button. * @param contentColor The content/tint color for the icon. - * @param size The size of the button container, defaulting to [IconButtonDefaults.extraSmallContainerSize] (32.dp). + * @param size The size of the inner visual container, defaulting to [IconButtonDefaults.extraSmallContainerSize] (32.dp). + * @param minTouchTargetSize The minimum interactive touch target size for accessibility, defaulting to 48.dp. * @param onClick Optional callback when the button is clicked. * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. */ @@ -664,6 +686,7 @@ fun TooltipIconButton( icon: @Composable () -> Unit, tooltipText: String, modifier: Modifier = Modifier, + contentDescription: String? = null, tooltipTitle: String? = null, state: TooltipState = rememberTooltipState(isPersistent = true), positioning: TooltipAnchorPosition = TooltipAnchorPosition.Below, @@ -674,6 +697,7 @@ fun TooltipIconButton( containerColor: Color = Color.Transparent, contentColor: Color = Color.White, size: Dp = IconButtonDefaults.extraSmallContainerSize().width, + minTouchTargetSize: Dp = 48.dp, onClick: () -> Unit = {}, onDismissRequest: (() -> Unit)? = null ) { @@ -707,32 +731,46 @@ fun TooltipIconButton( enableUserInput = false, onDismissRequest = onDismissRequest ) { - val buttonModifier = Modifier - .size(size) - .testTag(TOOLTIP_ANCHOR_BUTTON_TAG) - - if (isOutlined) { - OutlinedIconButton( - onClick = toggleTooltip, - modifier = buttonModifier, - colors = IconButtonDefaults.outlinedIconButtonColors( - containerColor = containerColor, - contentColor = contentColor - ), - border = BorderStroke(1.dp, Color.White.copy(alpha = 0.2f)) - ) { - icon() - } - } else { - IconButton( - onClick = toggleTooltip, - modifier = buttonModifier, - colors = IconButtonDefaults.iconButtonColors( - containerColor = containerColor, - contentColor = contentColor + val defaultContentDescription = tooltipTitle ?: tooltipText + val effectiveContentDescription = contentDescription ?: defaultContentDescription + + Box( + modifier = Modifier + .sizeIn(minWidth = minTouchTargetSize, minHeight = minTouchTargetSize) + .testTag(TOOLTIP_ANCHOR_BUTTON_TAG) + .clickable( + onClick = toggleTooltip, + role = Role.Button, + onClickLabel = effectiveContentDescription, + interactionSource = remember { MutableInteractionSource() }, + indication = ripple(bounded = false, radius = minTouchTargetSize / 2) ) + .semantics { + this.contentDescription = effectiveContentDescription + }, + contentAlignment = Alignment.Center + ) { + val containerModifier = Modifier + .size(size) + .then( + if (isOutlined) { + Modifier.border( + border = BorderStroke(1.dp, Color.White.copy(alpha = 0.2f)), + shape = CircleShape + ) + } else { + Modifier + } + ) + .background(color = containerColor, shape = CircleShape) + + Box( + modifier = containerModifier, + contentAlignment = Alignment.Center ) { - icon() + CompositionLocalProvider(LocalContentColor provides contentColor) { + icon() + } } } } diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index da919479ec..ea5745fc18 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -24,7 +24,13 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertHeightIsAtLeast import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertWidthIsAtLeast import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasText import androidx.compose.ui.test.isPopup @@ -349,8 +355,8 @@ class TooltipTest { onCaretCalculated = { x, _ -> caretX = x } ) startProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) - // cornerRadius (12) + caretWidth / 2 (8) = 20 - assertThat(caretX).isEqualTo(20f) + // cornerRadius (16) + caretWidth / 2 (8) = 24 + assertThat(caretX).isEqualTo(24f) // End (LTR) val endProvider = JcaTooltipPositionProvider( @@ -360,8 +366,8 @@ class TooltipTest { onCaretCalculated = { x, _ -> caretX = x } ) endProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) - // popupWidth (400) - cornerRadius (12) - caretWidth / 2 (8) = 380 - assertThat(caretX).isEqualTo(380f) + // popupWidth (400) - cornerRadius (16) - caretWidth / 2 (8) = 376 + assertThat(caretX).isEqualTo(376f) // Custom offset val customProvider = JcaTooltipPositionProvider( @@ -374,6 +380,39 @@ class TooltipTest { assertThat(caretX).isEqualTo(75f) } + @Test + fun tooltip_touchTarget_meetsMinimumAccessibilitySize() { + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "Touch target test" + ) + } + } + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG) + .assertWidthIsAtLeast(48.dp) + .assertHeightIsAtLeast(48.dp) + } + + @Test + fun tooltip_accessibility_hasButtonRoleAndContentDescription() { + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + contentDescription = "Custom info action", + tooltipText = "Accessibility description test" + ) + } + } + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG) + .assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Button)) + .assert(SemanticsMatcher.expectValue(SemanticsProperties.ContentDescription, listOf("Custom info action"))) + } + @Test fun bubbleShape_caretXClamped_doesNotBleedIntoCornerRadius() { val density = Density(1f) From 10304441c28be631d5dd2d9cecb66855870b21cd Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 27 Oct 2026 13:56:32 -0700 Subject: [PATCH 12/20] Map tooltip dimensions, shapes, and colors to Material 3 tokens - Map CaretSize to TooltipDefaults.caretSize (16.dp x 8.dp) with convenience CaretWidth and CaretHeight delegates. - Map ContainerSize to IconButtonDefaults.extraSmallContainerSize().width (32.dp). - Map IconSize to IconButtonDefaults.mediumIconSize (24.dp). - Map TouchTargetSize to standard Material 3 48.dp minimum interactive size. - Add standardM3Colors() to JcaTooltipDefaults based on TooltipDefaults.richTooltipColors(). - Reference JcaTooltipDefaults.IconSize in PreviewScreen instead of hardcoded dp. - Reformat all long lines to adhere to the spotless 100-character line-length policy. - Add unit test verifying token mappings and ensure all suite tests pass. --- .../feature/preview/PreviewScreen.kt | 4 +- .../jetpackcamera/ui/components/Tooltip.kt | 108 +++++++++++++----- .../ui/components/TooltipTest.kt | 61 ++++++++-- 3 files changed, 131 insertions(+), 42 deletions(-) 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 719f41d353..6e9a94a7a1 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 @@ -39,7 +39,6 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.BottomSheetScaffoldState import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SheetValue import androidx.compose.material3.SnackbarHostState @@ -80,6 +79,7 @@ import com.google.jetpackcamera.model.ExternalCaptureMode import com.google.jetpackcamera.model.ImageCaptureEvent import com.google.jetpackcamera.model.LensToZoom import com.google.jetpackcamera.model.VideoCaptureEvent +import com.google.jetpackcamera.ui.components.JcaTooltipDefaults import com.google.jetpackcamera.ui.components.TooltipIconButton import com.google.jetpackcamera.ui.components.capture.AmplitudeToggleButton import com.google.jetpackcamera.ui.components.capture.CAPTURE_MODE_TOGGLE_BUTTON @@ -958,7 +958,7 @@ private fun LayoutWrapper( icon = { Box( modifier = Modifier - .size(24.dp) + .size(JcaTooltipDefaults.IconSize) .background(Color.White, shape = CircleShape) ) }, diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 7c5a5a362d..da5440bfa0 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -40,6 +40,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition +import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.TooltipState import androidx.compose.material3.rememberTooltipState import androidx.compose.material3.ripple @@ -81,6 +82,7 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize @@ -102,27 +104,31 @@ const val TOOLTIP_ANCHOR_BUTTON_TAG = "tooltip_anchor_button" const val TOOLTIP_CONTENT_TAG = "tooltip_content" /** - * Custom Tooltip Implementation Workaround Rationale: + * Rationale and benefits of the custom [JcaTooltipBox] implementation: * - * Upstream Material 3's [androidx.compose.material3.RichTooltip] and [androidx.compose.material3.TooltipBox] - * suffer from three primary limitations that prevent accurate placement in custom camera layouts: + * Upstream Material 3's [androidx.compose.material3.RichTooltip] and + * [androidx.compose.material3.TooltipBox] present limitations in camera overlay layouts: * - * 1. Misaligned Caret Coordinates: Material 3 computes caret offsets using an internal `Modifier.layoutCaret` - * and private `caretX(...)` function. When clamping the popup against window margins, M3's formula incorrectly - * assumes the tooltip popup is flush with the anchor edge or hardcoded margins. When the calling button is small - * or positioned near the screen edge (such as in an indicator or status bar), this causes the caret to drift - * tens of pixels away from the anchor center. - * 2. Visual Hitch / Asynchronous Delay: M3 calculates caret transformations inside an asynchronous - * `onLayoutRectChanged` / `onGloballyPositioned` callback. This causes an unavoidable 1-frame visual jump where - * the tooltip first renders with default/stale caret coordinates before snapping to the recalculated position, - * triggering a full subtree recreation keyed on `tooltipSide`. - * 3. Caret Shape Continuity: M3 draws the caret as a detached child rotated via a transformation matrix, - * preventing unified background fills, continuous corner-radius clipping, and single-pass elevation shadows. + * 1. Caret Misalignment: M3's caret positioning does not adjust when the popup window clamps + * against screen boundaries, causing the caret to drift away from edge-positioned anchors. + * 2. Visual Hitch: M3 calculates caret offsets asynchronously across layout passes, causing + * a 1-frame visual jump when the tooltip first appears. + * 3. Disjoint Geometry: M3 renders the caret as a separate rotated element, preventing seamless + * backgrounds, smooth corner clipping, and unified elevation shadows. * - * To resolve this, [JcaTooltipBox] uses standard Compose [androidx.compose.ui.window.Popup] paired with - * [JcaTooltipPositionProvider] and [JcaTooltipBubbleShape]. This synchronously computes both popup window placement - * and the exact pixel-level local caret coordinates on Frame 0 before draw, guarantees safe screen margins (16dp), - * protects against corner-radius bleed, and supports flexible [CaretAlignment] configurations. + * Key advantages and customizations in [JcaTooltipBox]: + * + * - Flexible Caret Alignment: Supports [CaretAlignment.AnchorCenter], + * [CaretAlignment.BubbleCenter], start/end, and custom offsets, dynamically tracking anchors + * without corner bleed. + * - Reactive & Timed Triggers: Built-in support for [autoDismissDuration] and external + * [TooltipTriggerEvent] flows to drive onboarding or guidance tooltips from ViewModels. + * - Frame-0 Synchronous Layout: Derives popup position and caret coordinates simultaneously + * before drawing, eliminating multi-frame visual hops. + * - Continuous Vector Shape: [JcaTooltipBubbleShape] unifies the bubble and caret into a single + * path for seamless fills, borders, and shadows. + * - Viewfinder-Aware & Accessible: High-contrast camera theming, responsive vertical scrolling + * under large font scaling, and TalkBack live region announcements. */ /** @@ -156,18 +162,49 @@ data class JcaTooltipColors( ) /** - * Default dimensions, styling tokens, and color values for JCA tooltips. + * Default dimensions, styling tokens, and color values for JCA tooltips, + * referencing standard Material 3 design tokens and component defaults. */ +@OptIn(ExperimentalMaterial3Api::class) object JcaTooltipDefaults { + /** Default caret dimensions matching Material 3 [TooltipDefaults.caretSize] (16dp x 8dp). */ + val CaretSize: DpSize = TooltipDefaults.caretSize + val CaretWidth: Dp get() = CaretSize.width + val CaretHeight: Dp get() = CaretSize.height + + /** Default spacing between the tooltip bubble and calling anchor. */ + val SpacingBetweenTooltipAndAnchor: Dp = 4.dp + + /** Safe screen edge margins for clamping popup placement against window boundaries. */ + val ScreenMargin: Dp = 16.dp + + /** Large corner radius token (16dp) based on Material 3 ShapeDefaults.Large. */ + val CornerRadius: Dp = 16.dp + + /** Standard Material minimum interactive touch target size (48dp). */ + val TouchTargetSize: Dp = 48.dp + + /** Visual container size (32dp) matching [IconButtonDefaults.extraSmallContainerSize]. */ + val ContainerSize: Dp = IconButtonDefaults.extraSmallContainerSize().width // 32.dp + + /** Medium icon size (24dp) matching [IconButtonDefaults.mediumIconSize]. */ + val IconSize: Dp = IconButtonDefaults.mediumIconSize // 24.dp + + /** Width constraints for the tooltip bubble. */ val MinWidth: Dp = 140.dp + + /** + * Maximum width aligned with design mock (296dp), + * capped within [TooltipDefaults.richTooltipMaxWidth] (320dp). + */ val MaxWidth: Dp = 296.dp - val CornerRadius: Dp = 16.dp - val CaretWidth: Dp = 16.dp - val CaretHeight: Dp = 8.dp - val ScreenMargin: Dp = 16.dp - val SpacingBetweenTooltipAndAnchor: Dp = 4.dp + + /** Container elevation Level 2 (2dp) matching Material 3 RichTooltipTokens. */ val DefaultElevation: Dp = 2.dp + /** + * Default high-contrast colors suited for camera viewfinder overlays. + */ @Composable fun tooltipColors( containerColor: Color = MaterialTheme.colorScheme.secondaryFixed, @@ -178,6 +215,19 @@ object JcaTooltipDefaults { contentColor = contentColor, titleContentColor = titleContentColor ) + + /** + * Standard Material 3 rich tooltip colors based on [TooltipDefaults.richTooltipColors]. + */ + @Composable + fun standardM3Colors(): JcaTooltipColors { + val m3Defaults = TooltipDefaults.richTooltipColors() + return JcaTooltipColors( + containerColor = m3Defaults.containerColor, + contentColor = m3Defaults.contentColor, + titleContentColor = m3Defaults.titleContentColor + ) + } } /** @@ -675,8 +725,10 @@ private fun Modifier.tooltipGestures( * @param isOutlined Whether the icon button should be outlined. * @param containerColor The background container color for the button. * @param contentColor The content/tint color for the icon. - * @param size The size of the inner visual container, defaulting to [IconButtonDefaults.extraSmallContainerSize] (32.dp). - * @param minTouchTargetSize The minimum interactive touch target size for accessibility, defaulting to 48.dp. + * @param size The size of the inner visual container, defaulting to + * [IconButtonDefaults.extraSmallContainerSize] (32.dp). + * @param minTouchTargetSize The minimum interactive touch target size for accessibility, + * defaulting to 48.dp. * @param onClick Optional callback when the button is clicked. * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. */ @@ -696,8 +748,8 @@ fun TooltipIconButton( isOutlined: Boolean = false, containerColor: Color = Color.Transparent, contentColor: Color = Color.White, - size: Dp = IconButtonDefaults.extraSmallContainerSize().width, - minTouchTargetSize: Dp = 48.dp, + size: Dp = JcaTooltipDefaults.ContainerSize, + minTouchTargetSize: Dp = JcaTooltipDefaults.TouchTargetSize, onClick: () -> Unit = {}, onDismissRequest: (() -> Unit)? = null ) { diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index ea5745fc18..4f75d8937c 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -38,7 +38,6 @@ import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick import androidx.compose.ui.unit.Density -import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection @@ -201,7 +200,8 @@ class TooltipTest { // Must still exist because timer was reset composeTestRule.onNode(isPopup()).assertExists() - // Advance past reset expiration (remaining 1001ms) -> Trigger dismiss and allow exit transition + // Advance past reset expiration (remaining 1001ms) -> + // Trigger dismiss and allow exit transition composeTestRule.mainClock.advanceTimeBy(1001) composeTestRule.mainClock.autoAdvance = true composeTestRule.waitForIdle() @@ -285,7 +285,7 @@ class TooltipTest { popupContentSize = popupContentSize ) - // The popup is clamped to screen margin (16px) because ideal X (32 - 200 = -168) is offscreen + // The popup is clamped to screen margin (16px) because ideal X is offscreen assertThat(position.x).isEqualTo(16) // Positioned below anchor: bottom (52) + spacing (4) = 56 assertThat(position.y).isEqualTo(56) @@ -295,7 +295,8 @@ class TooltipTest { assertThat(calculatedIsCaretOnTop).isTrue() // Global caret X points exactly to anchor center X - assertThat(position.x + calculatedLocalCaretX.toInt()).isEqualTo((anchorBounds.left + anchorBounds.right) / 2) + val expectedAnchorCenter = (anchorBounds.left + anchorBounds.right) / 2 + assertThat(position.x + calculatedLocalCaretX.toInt()).isEqualTo(expectedAnchorCenter) } @Test @@ -344,7 +345,12 @@ class TooltipTest { density = Density(1f), onCaretCalculated = { x, _ -> caretX = x } ) - bubbleCenterProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) + bubbleCenterProvider.calculatePosition( + anchorBounds, + windowSize, + LayoutDirection.Ltr, + popupContentSize + ) assertThat(caretX).isEqualTo(200f) // Start (LTR) @@ -354,7 +360,12 @@ class TooltipTest { density = Density(1f), onCaretCalculated = { x, _ -> caretX = x } ) - startProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) + startProvider.calculatePosition( + anchorBounds, + windowSize, + LayoutDirection.Ltr, + popupContentSize + ) // cornerRadius (16) + caretWidth / 2 (8) = 24 assertThat(caretX).isEqualTo(24f) @@ -365,7 +376,12 @@ class TooltipTest { density = Density(1f), onCaretCalculated = { x, _ -> caretX = x } ) - endProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) + endProvider.calculatePosition( + anchorBounds, + windowSize, + LayoutDirection.Ltr, + popupContentSize + ) // popupWidth (400) - cornerRadius (16) - caretWidth / 2 (8) = 376 assertThat(caretX).isEqualTo(376f) @@ -376,7 +392,12 @@ class TooltipTest { density = Density(1f), onCaretCalculated = { x, _ -> caretX = x } ) - customProvider.calculatePosition(anchorBounds, windowSize, LayoutDirection.Ltr, popupContentSize) + customProvider.calculatePosition( + anchorBounds, + windowSize, + LayoutDirection.Ltr, + popupContentSize + ) assertThat(caretX).isEqualTo(75f) } @@ -385,15 +406,26 @@ class TooltipTest { composeTestRule.setContent { MaterialTheme { TooltipIconButton( - icon = { Box(modifier = Modifier.size(24.dp)) }, + icon = { Box(modifier = Modifier.size(JcaTooltipDefaults.IconSize)) }, tooltipText = "Touch target test" ) } } composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG) - .assertWidthIsAtLeast(48.dp) - .assertHeightIsAtLeast(48.dp) + .assertWidthIsAtLeast(JcaTooltipDefaults.TouchTargetSize) + .assertHeightIsAtLeast(JcaTooltipDefaults.TouchTargetSize) + } + + @Test + fun tooltipDefaults_mapsToMaterial3Tokens() { + assertThat(JcaTooltipDefaults.CaretSize.width).isEqualTo(16.dp) + assertThat(JcaTooltipDefaults.CaretSize.height).isEqualTo(8.dp) + assertThat(JcaTooltipDefaults.TouchTargetSize).isEqualTo(48.dp) + assertThat(JcaTooltipDefaults.ContainerSize).isEqualTo(32.dp) + assertThat(JcaTooltipDefaults.IconSize).isEqualTo(24.dp) + assertThat(JcaTooltipDefaults.CornerRadius).isEqualTo(16.dp) + assertThat(JcaTooltipDefaults.DefaultElevation).isEqualTo(2.dp) } @Test @@ -410,7 +442,12 @@ class TooltipTest { composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG) .assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Button)) - .assert(SemanticsMatcher.expectValue(SemanticsProperties.ContentDescription, listOf("Custom info action"))) + .assert( + SemanticsMatcher.expectValue( + SemanticsProperties.ContentDescription, + listOf("Custom info action") + ) + ) } @Test From 3303a7c1b1e138f8ea1b9af9fbb5229dd941c150 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 28 Oct 2026 09:38:46 -0700 Subject: [PATCH 13/20] Wrap top bar indicator items in Row container with IndicatorPill - Encapsulate TooltipIconButton and IndicatorPill inside a centered Row in PreviewScreen's indicatorRow with 8dp horizontal spacing. - Pass incoming indicatorRow modifier to the outer Row container. - Guard the entire indicatorRow layout with isErrorDialogShowing. - Remove redundant Text import and add missing Compose UI imports. --- .../feature/preview/PreviewScreen.kt | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) 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 db17f2ef02..58d4bcf4de 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 @@ -34,7 +34,6 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.BottomSheetScaffoldState @@ -42,7 +41,6 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SheetValue import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.material3.darkColorScheme import androidx.compose.material3.rememberBottomSheetScaffoldState @@ -60,10 +58,12 @@ import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.LifecycleStartEffect import androidx.tracing.Trace @@ -925,35 +925,35 @@ private fun LayoutWrapper( captureModeToggle = captureModeToggle, quickSettingsOverlay = quickSettingsOverlay, indicatorRow = { modifier -> - Row { - TooltipIconButton( - modifier = Modifier, - icon = { - Box( - modifier = Modifier - .size(JcaTooltipDefaults.IconSize) - .background(Color.White, shape = CircleShape) - ) - }, - contentDescription = "Show camera information", - tooltipText = "This is a placeholder tooltip message. It demonstrates how" + - " text wraps and aligns.", - positioning = TooltipAnchorPosition.Below, - isOutlined = true - ) if (!isErrorDialogShowing) { - - IndicatorPill( - modifier = modifier - .fillMaxWidth() + Row( + modifier = modifier, + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) ) { - flashModeIndicator(Modifier) - hdrIndicator(Modifier) - videoQualityIndicator(Modifier) - stabilizationIndicator(Modifier) + TooltipIconButton( + modifier = Modifier, + icon = { + Box( + modifier = Modifier + .size(JcaTooltipDefaults.IconSize) + .background(Color.White, shape = CircleShape) + ) + }, + contentDescription = "Show camera information", + tooltipText = "This is a placeholder tooltip message. It demonstrates how" + + " text wraps and aligns.", + positioning = TooltipAnchorPosition.Below, + isOutlined = true + ) + IndicatorPill { + flashModeIndicator(Modifier) + hdrIndicator(Modifier) + videoQualityIndicator(Modifier) + stabilizationIndicator(Modifier) + } } } - } }, topStartContent = topStartContent, debugOverlay = { modifier -> From de0b7a799b7e65c5c381f04926ae785b9ce3de5f Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 28 Oct 2026 10:09:24 -0700 Subject: [PATCH 14/20] Decouple tooltip triggers and auto-dismissal into JcaTooltipState Decouple triggers and auto-dismissal timers from the UI composable components (`JcaTooltipBox` and `TooltipIconButton`) into a dedicated `JcaTooltipState` extending Compose Material 3's `TooltipState`. Key changes: - Introduce `JcaTooltipState` interface extending `TooltipState` with `toggle()` and `autoDismissDuration` support. - Implement `JcaTooltipStateImpl` utilizing `MutatorMutex` and `withTimeoutOrNull` to coordinate auto-dismissal and naturally reset timers upon subsequent `show()` triggers without custom revision counters. - Provide `rememberJcaTooltipState()` factory function with configurable `autoDismissDuration`, `initialIsVisible`, `isPersistent`, and optional shared `MutatorMutex`. - Remove `triggerFlow`, `autoDismissDuration`, `triggerRevision`, and `sealed interface TooltipTriggerEvent` from `Tooltip.kt`. - Update `TooltipTest.kt` to cover `JcaTooltipState` methods (`toggle()`, programmatic `show()` and `dismiss()`, auto-dismiss timing, and timer reset on re-trigger). --- .../jetpackcamera/ui/components/Tooltip.kt | 190 ++++++++++++------ .../ui/components/TooltipTest.kt | 74 +++++-- 2 files changed, 190 insertions(+), 74 deletions(-) diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index da5440bfa0..3847cde076 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -15,7 +15,10 @@ */ package com.google.jetpackcamera.ui.components +import androidx.compose.animation.core.MutableTransitionState import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.MutatePriority +import androidx.compose.foundation.MutatorMutex import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -42,17 +45,14 @@ import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.TooltipState -import androidx.compose.material3.rememberTooltipState import androidx.compose.material3.ripple import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.Immutable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -93,12 +93,12 @@ import androidx.compose.ui.window.PopupPositionProvider import androidx.compose.ui.window.PopupProperties import kotlin.math.roundToInt import kotlin.time.Duration +import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch +import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull const val TOOLTIP_ANCHOR_BUTTON_TAG = "tooltip_anchor_button" const val TOOLTIP_CONTENT_TAG = "tooltip_content" @@ -121,8 +121,8 @@ const val TOOLTIP_CONTENT_TAG = "tooltip_content" * - Flexible Caret Alignment: Supports [CaretAlignment.AnchorCenter], * [CaretAlignment.BubbleCenter], start/end, and custom offsets, dynamically tracking anchors * without corner bleed. - * - Reactive & Timed Triggers: Built-in support for [autoDismissDuration] and external - * [TooltipTriggerEvent] flows to drive onboarding or guidance tooltips from ViewModels. + * - Reactive & Timed State: Decoupled [JcaTooltipState] managing visibility, [autoDismissDuration], + * and coroutine-driven mutual exclusion via [MutatorMutex]. * - Frame-0 Synchronous Layout: Derives popup position and caret coordinates simultaneously * before drawing, eliminating multi-frame visual hops. * - Continuous Vector Shape: [JcaTooltipBubbleShape] unifies the bubble and caret into a single @@ -479,12 +479,126 @@ class JcaTooltipPositionProvider( } } +private const val DEFAULT_TOOLTIP_DURATION_MILLIS = 1500L + +/** + * An extended [TooltipState] for JCA tooltips that supports auto-dismiss durations, + * coroutine-driven mutual exclusion via [MutatorMutex], and programmatic toggling. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Stable +interface JcaTooltipState : TooltipState { + /** + * Optional duration after which the tooltip automatically dismisses. + */ + val autoDismissDuration: Duration? + + /** + * Toggles the visibility of the tooltip. + * + * If the tooltip is currently visible or transitioning to visible, it will be dismissed. + * Otherwise, it will be shown. + */ + suspend fun toggle(mutatePriority: MutatePriority = MutatePriority.Default) +} + /** - * Events used to trigger programmatic display or dismissal of tooltips. + * Creates and remembers an instance of [JcaTooltipState]. + * + * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. + * When non-null, every call to [TooltipState.show] will keep the tooltip displayed for this + * duration before dismissing, resetting the timer if re-triggered while already visible. + * @param initialIsVisible Whether the tooltip should be initially visible. + * @param isPersistent Whether the tooltip should remain visible until explicitly dismissed + * when [autoDismissDuration] is null. If false and [autoDismissDuration] is null, defaults + * to standard transient duration (1500ms). + * @param mutatorMutex Mutex coordinating tooltip display. Defaults to a fresh [MutatorMutex] + * instance per tooltip state. */ -sealed interface TooltipTriggerEvent { - data object Show : TooltipTriggerEvent - data object Dismiss : TooltipTriggerEvent +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun rememberJcaTooltipState( + autoDismissDuration: Duration? = null, + initialIsVisible: Boolean = false, + isPersistent: Boolean = true, + mutatorMutex: MutatorMutex = remember { MutatorMutex() } +): JcaTooltipState = remember(autoDismissDuration, initialIsVisible, isPersistent, mutatorMutex) { + JcaTooltipStateImpl( + autoDismissDuration = autoDismissDuration, + initialIsVisible = initialIsVisible, + isPersistent = isPersistent, + mutatorMutex = mutatorMutex + ) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Stable +private class JcaTooltipStateImpl( + override val autoDismissDuration: Duration?, + initialIsVisible: Boolean = false, + override val isPersistent: Boolean = true, + private val mutatorMutex: MutatorMutex = MutatorMutex() +) : JcaTooltipState { + + override val transition: MutableTransitionState = + MutableTransitionState(initialIsVisible) + + override val isVisible: Boolean + get() = transition.currentState || transition.targetState + + private var job: CancellableContinuation? = null + + override suspend fun show(mutatePriority: MutatePriority) { + val cancellableShow: suspend () -> Unit = { + try { + suspendCancellableCoroutine { continuation -> + transition.targetState = true + job = continuation + } + } finally { + job = null + transition.targetState = false + } + } + + mutatorMutex.mutate(mutatePriority) { + try { + if (autoDismissDuration != null) { + withTimeoutOrNull(autoDismissDuration.inWholeMilliseconds) { + cancellableShow() + } + } else if (isPersistent) { + cancellableShow() + } else { + withTimeoutOrNull(DEFAULT_TOOLTIP_DURATION_MILLIS) { + cancellableShow() + } + } + } finally { + job = null + transition.targetState = false + } + } + } + + override fun dismiss() { + transition.targetState = false + if (job?.isActive == true) { + job?.cancel() + } + } + + override suspend fun toggle(mutatePriority: MutatePriority) { + if (transition.targetState) { + dismiss() + } else { + show(mutatePriority) + } + } + + override fun onDispose() { + dismiss() + } } /** @@ -574,11 +688,9 @@ fun JcaTooltipBubble( * @param tooltipText The text to display inside the tooltip. * @param modifier Modifier for the container. * @param tooltipTitle Optional title displayed above the tooltip text. - * @param state State controlling tooltip visibility. + * @param state State controlling tooltip visibility. Defaults to [rememberJcaTooltipState]. * @param positioning Anchor position for the tooltip (e.g. Above, Below). * @param caretAlignment Alignment configuration for the caret. - * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. - * @param triggerFlow Optional flow of [TooltipTriggerEvent] to trigger showing or dismissing. * @param enableUserInput Whether long-press gestures on the anchor trigger the tooltip. * @param colors Colors applied to the tooltip bubble and text. * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. @@ -590,11 +702,9 @@ fun JcaTooltipBox( tooltipText: String, modifier: Modifier = Modifier, tooltipTitle: String? = null, - state: TooltipState = rememberTooltipState(isPersistent = true), + state: TooltipState = rememberJcaTooltipState(), positioning: TooltipAnchorPosition = TooltipAnchorPosition.Above, caretAlignment: CaretAlignment = CaretAlignment.AnchorCenter, - autoDismissDuration: Duration? = null, - triggerFlow: Flow? = null, enableUserInput: Boolean = true, colors: JcaTooltipColors = JcaTooltipDefaults.tooltipColors(), onDismissRequest: (() -> Unit)? = null, @@ -602,33 +712,6 @@ fun JcaTooltipBox( ) { val scope = rememberCoroutineScope() val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) - var triggerRevision by remember { mutableIntStateOf(0) } - - // External flow triggers using collectLatest to prevent deadlock from show() suspension - if (triggerFlow != null) { - LaunchedEffect(triggerFlow, state) { - triggerFlow.collectLatest { event -> - when (event) { - TooltipTriggerEvent.Show -> { - triggerRevision++ - state.show() - } - TooltipTriggerEvent.Dismiss -> state.dismiss() - } - } - } - } - - // Auto-dismiss timer keyed on targetState and triggerRevision - if (autoDismissDuration != null) { - LaunchedEffect(state.transition.targetState, triggerRevision, autoDismissDuration) { - if (state.transition.targetState) { - delay(autoDismissDuration) - state.dismiss() - currentOnDismissRequest?.invoke() - } - } - } val density = LocalDensity.current val caretPositionState = remember { @@ -717,11 +800,9 @@ private fun Modifier.tooltipGestures( * @param modifier Modifier for the button container. * @param contentDescription Optional accessibility content description for TalkBack. * @param tooltipTitle The optional title to display inside the tooltip. - * @param state State controlling tooltip visibility. + * @param state State controlling tooltip visibility. Defaults to [rememberJcaTooltipState]. * @param positioning Anchor position for the tooltip (e.g. Above, Below). Defaults to Below. * @param caretAlignment Alignment configuration for the caret. Defaults to AnchorCenter. - * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. - * @param triggerFlow Optional flow of [TooltipTriggerEvent] to trigger showing or dismissing. * @param isOutlined Whether the icon button should be outlined. * @param containerColor The background container color for the button. * @param contentColor The content/tint color for the icon. @@ -740,11 +821,9 @@ fun TooltipIconButton( modifier: Modifier = Modifier, contentDescription: String? = null, tooltipTitle: String? = null, - state: TooltipState = rememberTooltipState(isPersistent = true), + state: JcaTooltipState = rememberJcaTooltipState(), positioning: TooltipAnchorPosition = TooltipAnchorPosition.Below, caretAlignment: CaretAlignment = CaretAlignment.AnchorCenter, - autoDismissDuration: Duration? = null, - triggerFlow: Flow? = null, isOutlined: Boolean = false, containerColor: Color = Color.Transparent, contentColor: Color = Color.White, @@ -760,11 +839,10 @@ fun TooltipIconButton( val toggleTooltip = remember(state, scope) { { scope.launch { - if (state.transition.targetState) { - state.dismiss() + val wasVisible = state.transition.targetState + state.toggle() + if (wasVisible) { currentOnDismissRequest?.invoke() - } else { - state.show() } } currentOnClick() @@ -778,8 +856,6 @@ fun TooltipIconButton( state = state, positioning = positioning, caretAlignment = caretAlignment, - autoDismissDuration = autoDismissDuration, - triggerFlow = triggerFlow, enableUserInput = false, onDismissRequest = onDismissRequest ) { diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index 4f75d8937c..53c5443c57 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -20,6 +20,7 @@ import androidx.compose.foundation.layout.size import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.TooltipAnchorPosition +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color @@ -44,7 +45,8 @@ import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.google.common.truth.Truth.assertThat import kotlin.time.Duration.Companion.milliseconds -import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -101,30 +103,65 @@ class TooltipTest { } @Test - fun tooltip_externalFlowTrigger_showsAndDismisses() { - val triggerFlow = MutableSharedFlow(extraBufferCapacity = 1) + fun tooltip_programmaticTrigger_showsAndDismisses() { + lateinit var tooltipState: JcaTooltipState + lateinit var coroutineScope: CoroutineScope composeTestRule.setContent { + val state = rememberJcaTooltipState() + tooltipState = state + coroutineScope = rememberCoroutineScope() MaterialTheme { TooltipIconButton( icon = { Box(modifier = Modifier.size(24.dp)) }, - tooltipText = "External trigger text", - triggerFlow = triggerFlow + tooltipText = "Programmatic trigger text", + state = state ) } } composeTestRule.onNode(isPopup()).assertDoesNotExist() - // Emit Show - triggerFlow.tryEmit(TooltipTriggerEvent.Show) + // Programmatically show + coroutineScope.launch { tooltipState.show() } composeTestRule.waitForIdle() composeTestRule.onNode(isPopup()).assertExists() - composeTestRule.onNode(hasText("External trigger text") and hasAnyAncestor(isPopup())) + composeTestRule.onNode(hasText("Programmatic trigger text") and hasAnyAncestor(isPopup())) .assertIsDisplayed() - // Emit Dismiss - triggerFlow.tryEmit(TooltipTriggerEvent.Dismiss) + // Programmatically dismiss + tooltipState.dismiss() + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + + @Test + fun tooltipState_toggle_switchesVisibility() { + lateinit var tooltipState: JcaTooltipState + lateinit var coroutineScope: CoroutineScope + + composeTestRule.setContent { + val state = rememberJcaTooltipState() + tooltipState = state + coroutineScope = rememberCoroutineScope() + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "Toggle text", + state = state + ) + } + } + + composeTestRule.onNode(isPopup()).assertDoesNotExist() + + // Toggle on + coroutineScope.launch { tooltipState.toggle() } + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertExists() + + // Toggle off + coroutineScope.launch { tooltipState.toggle() } composeTestRule.waitForIdle() composeTestRule.onNode(isPopup()).assertDoesNotExist() } @@ -138,7 +175,7 @@ class TooltipTest { TooltipIconButton( icon = { Box(modifier = Modifier.size(24.dp)) }, tooltipText = "Auto dismissing text", - autoDismissDuration = 3000.milliseconds + state = rememberJcaTooltipState(autoDismissDuration = 3000.milliseconds) ) } } @@ -165,21 +202,24 @@ class TooltipTest { @Test fun tooltip_autoDismiss_reTriggerResetsTimer() { composeTestRule.mainClock.autoAdvance = false - val triggerFlow = MutableSharedFlow(extraBufferCapacity = 1) + lateinit var tooltipState: JcaTooltipState + lateinit var coroutineScope: CoroutineScope composeTestRule.setContent { + val state = rememberJcaTooltipState(autoDismissDuration = 3000.milliseconds) + tooltipState = state + coroutineScope = rememberCoroutineScope() MaterialTheme { TooltipIconButton( icon = { Box(modifier = Modifier.size(24.dp)) }, tooltipText = "Resetting timer text", - autoDismissDuration = 3000.milliseconds, - triggerFlow = triggerFlow + state = state ) } } - // Trigger show via flow - triggerFlow.tryEmit(TooltipTriggerEvent.Show) + // Trigger show via state + coroutineScope.launch { tooltipState.show() } composeTestRule.mainClock.advanceTimeByFrame() composeTestRule.waitForIdle() composeTestRule.onNode(isPopup()).assertExists() @@ -190,7 +230,7 @@ class TooltipTest { composeTestRule.onNode(isPopup()).assertExists() // Re-trigger Show -> Timer resets - triggerFlow.tryEmit(TooltipTriggerEvent.Show) + coroutineScope.launch { tooltipState.show() } composeTestRule.mainClock.advanceTimeByFrame() composeTestRule.waitForIdle() From 67db7f89ea9e1cfc93aef5aba1832844a028ebda Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 28 Oct 2026 10:34:40 -0700 Subject: [PATCH 15/20] Set tooltip accessibility live region mode to Polite Update the tooltip bubble semantics liveRegion mode from Assertive to Polite so screen readers do not abruptly cut off ongoing speech when the tooltip is displayed, and add corresponding test coverage. --- .../google/jetpackcamera/ui/components/Tooltip.kt | 2 +- .../jetpackcamera/ui/components/TooltipTest.kt | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 3847cde076..1436d0d616 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -643,7 +643,7 @@ fun JcaTooltipBubble( .widthIn(min = JcaTooltipDefaults.MinWidth, max = JcaTooltipDefaults.MaxWidth) .testTag(TOOLTIP_CONTENT_TAG) .semantics { - liveRegion = LiveRegionMode.Assertive + liveRegion = LiveRegionMode.Polite paneTitle = tooltipTitle ?: tooltipText } ) { diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index 53c5443c57..e1ffcc4743 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -25,6 +25,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher @@ -488,6 +489,18 @@ class TooltipTest { listOf("Custom info action") ) ) + + // Show tooltip and verify LiveRegionMode.Polite semantics on bubble content + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(TOOLTIP_CONTENT_TAG) + .assert( + SemanticsMatcher.expectValue( + SemanticsProperties.LiveRegion, + LiveRegionMode.Polite + ) + ) } @Test From 527d64f38b215988f73dde8304b43fc43c814d6c Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Fri, 6 Nov 2026 11:31:06 -0800 Subject: [PATCH 16/20] Refactor TooltipIconButton onto M3 TooltipBox and add PreviewLayout topBarLeadingContent slot - Replace custom JcaTooltipBox, JcaTooltipState, JcaTooltipBubble, and gesture wrappers with Material 3 TooltipBox, RichTooltip, and rememberTooltipState, retaining only JcaTooltipPositionProvider and JcaTooltipBubbleShape for edge-aware synchronous caret placement. - Clamp localCaretX in JcaTooltipPositionProvider and simplify JcaTooltipBubbleShape using RoundedCornerShape + PathOperation.Union. - Add TooltipScope.() -> Unit overload to TooltipIconButton alongside the String convenience overload, track pointer-down visibility to fix anchor tap-to-close on device, and clear duplicate TalkBack onClickLabel speech. - Move top-bar leading button support into an optional cutout-aware topBarLeadingContent slot on PreviewLayout with a Compose preview, reverting placeholder PreviewScreen and OverlapAwareStyleProvider changes. - Streamline TooltipTest, add TooltipInstrumentedTest for real window-level tap toggling, and add CaptureLayoutInsetsTest coverage for topBarLeadingContent. --- feature/preview/build.gradle.kts | 1 - .../feature/preview/PreviewScreen.kt | 47 +- ui/components/build.gradle.kts | 5 + ui/components/capture/build.gradle.kts | 1 + .../ui/components/capture/CaptureLayout.kt | 149 +++- .../capture/OverlapAwareStyleProvider.kt | 22 +- .../capture/CaptureLayoutInsetsTest.kt | 55 ++ .../capture/OverlapAwareStyleProviderTest.kt | 54 +- .../ui/components/TooltipInstrumentedTest.kt | 118 +++ .../jetpackcamera/ui/components/Tooltip.kt | 787 +++++------------- .../ui/components/TooltipTest.kt | 399 ++------- 11 files changed, 645 insertions(+), 993 deletions(-) create mode 100644 ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt diff --git a/feature/preview/build.gradle.kts b/feature/preview/build.gradle.kts index 5a0acde245..b9833eadd9 100644 --- a/feature/preview/build.gradle.kts +++ b/feature/preview/build.gradle.kts @@ -154,7 +154,6 @@ dependencies { testImplementation(project(":core:common:testing")) testImplementation(project(":ui:controller:testing")) implementation(project(":ui:components:capture")) - implementation(project(":ui:components")) implementation(project(":ui:controller")) implementation(project(":ui:controller:impl")) implementation(project(":ui:uistate")) 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 58d4bcf4de..9fc7aebd88 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 @@ -13,8 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) - package com.google.jetpackcamera.feature.preview import android.util.Log @@ -29,19 +27,14 @@ import androidx.compose.animation.ExitTransition import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.BottomSheetScaffoldState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SheetValue import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.TooltipAnchorPosition import androidx.compose.material3.darkColorScheme import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState @@ -58,12 +51,10 @@ import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.LifecycleStartEffect import androidx.tracing.Trace @@ -78,8 +69,6 @@ import com.google.jetpackcamera.model.ImageCaptureEvent import com.google.jetpackcamera.model.LensFacing import com.google.jetpackcamera.model.LensToZoom import com.google.jetpackcamera.model.VideoCaptureEvent -import com.google.jetpackcamera.ui.components.JcaTooltipDefaults -import com.google.jetpackcamera.ui.components.TooltipIconButton import com.google.jetpackcamera.ui.components.capture.AmplitudeToggleButton import com.google.jetpackcamera.ui.components.capture.CAPTURE_MODE_TOGGLE_BUTTON import com.google.jetpackcamera.ui.components.capture.CameraErrorDialog @@ -908,7 +897,6 @@ private fun LayoutWrapper( debugVisibilityWrapper: (@Composable (@Composable () -> Unit) -> Unit), screenFlashOverlay: @Composable (modifier: Modifier) -> Unit, snackBar: @Composable (modifier: Modifier, snackbarHostState: SnackbarHostState) -> Unit, - topStartContent: @Composable (modifier: Modifier) -> Unit = {}, errorDialog: @Composable (modifier: Modifier) -> Unit = {} ) { PreviewLayout( @@ -926,36 +914,17 @@ private fun LayoutWrapper( quickSettingsOverlay = quickSettingsOverlay, indicatorRow = { modifier -> if (!isErrorDialogShowing) { - Row( - modifier = modifier, - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp) + IndicatorPill( + modifier = modifier + .fillMaxWidth() ) { - TooltipIconButton( - modifier = Modifier, - icon = { - Box( - modifier = Modifier - .size(JcaTooltipDefaults.IconSize) - .background(Color.White, shape = CircleShape) - ) - }, - contentDescription = "Show camera information", - tooltipText = "This is a placeholder tooltip message. It demonstrates how" + - " text wraps and aligns.", - positioning = TooltipAnchorPosition.Below, - isOutlined = true - ) - IndicatorPill { - flashModeIndicator(Modifier) - hdrIndicator(Modifier) - videoQualityIndicator(Modifier) - stabilizationIndicator(Modifier) - } + flashModeIndicator(Modifier) + hdrIndicator(Modifier) + videoQualityIndicator(Modifier) + stabilizationIndicator(Modifier) } } }, - topStartContent = topStartContent, debugOverlay = { modifier -> debugOverlay( modifier, diff --git a/ui/components/build.gradle.kts b/ui/components/build.gradle.kts index fbabc87753..7c609d5ed7 100644 --- a/ui/components/build.gradle.kts +++ b/ui/components/build.gradle.kts @@ -76,6 +76,8 @@ dependencies { implementation(libs.compose.material3) // Compose - Testing + androidTestImplementation(composeBom) + androidTestImplementation(libs.compose.junit) debugImplementation(libs.compose.test.manifest) // noinspection TestManifestGradleConfiguration: required for release build unit tests testImplementation(libs.compose.test.manifest) @@ -84,9 +86,12 @@ dependencies { // Testing testImplementation(libs.junit) testImplementation(libs.truth) + androidTestImplementation(libs.truth) testImplementation(libs.kotlinx.coroutines.test) testImplementation(libs.robolectric) testImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) } // Allow references to generated code diff --git a/ui/components/capture/build.gradle.kts b/ui/components/capture/build.gradle.kts index b7876c1837..b64e1bb0d8 100644 --- a/ui/components/capture/build.gradle.kts +++ b/ui/components/capture/build.gradle.kts @@ -120,6 +120,7 @@ dependencies { implementation(project(":ui:uistate")) implementation(project(":ui:uistate:capture")) + implementation(project(":ui:components")) implementation(project(":ui:controller")) implementation(project(":core:camera")) implementation(project(":core:common")) 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 8fb7cd137c..7452d02c1f 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 @@ -15,6 +15,7 @@ */ package com.google.jetpackcamera.ui.components.capture +import android.annotation.SuppressLint import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource @@ -39,11 +40,13 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBarsIgnoringVisibility import androidx.compose.foundation.layout.union import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.BottomSheetDefaults import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.BottomSheetScaffoldState import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon import androidx.compose.material3.LocalMinimumInteractiveComponentSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SheetValue @@ -52,7 +55,6 @@ import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment @@ -60,12 +62,15 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.max import androidx.compose.ui.unit.takeOrElse +import com.google.jetpackcamera.ui.components.TooltipIconButton /** * The base layout for the camera capture screen. @@ -90,6 +95,9 @@ import androidx.compose.ui.unit.takeOrElse * and display cutout areas * @param snackBar the snack bar composable for showing messages * @param topStartContent optional composable content aligned to the top-start of the viewfinder + * @param topBarLeadingContent optional composable content placed at the start of the top bar + * directly adjacent to [indicatorRow] + * @param topBarTrailingContent optional composable content aligned to the end of the top bar * @param errorDialog the camera error alert dialog composable */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @@ -119,6 +127,7 @@ fun PreviewLayout( screenFlashOverlay: @Composable (Modifier) -> Unit, snackBar: @Composable (Modifier, snackbarHostState: SnackbarHostState) -> Unit, topStartContent: @Composable (Modifier) -> Unit = {}, + topBarLeadingContent: (@Composable (Modifier) -> Unit)? = null, topBarTrailingContent: @Composable (Modifier) -> Unit = {}, errorDialog: @Composable (Modifier) -> Unit = {} ) { @@ -172,7 +181,10 @@ fun PreviewLayout( .padding(horizontal = 16.dp), contentAlignment = Alignment.CenterStart ) { - indicatorRow(Modifier) + TopBarLeadingAndIndicatorsRow( + topBarLeadingContent = topBarLeadingContent, + indicatorRow = indicatorRow + ) topBarTrailingContent(Modifier.align(Alignment.CenterEnd)) } Box { @@ -238,6 +250,34 @@ fun PreviewLayout( } } +@SuppressLint("AvoidNullableCollections", "NullableCollection") +@Composable +internal fun TopBarLeadingAndIndicatorsRow( + topBarLeadingContent: (@Composable (Modifier) -> Unit)?, + indicatorRow: @Composable (Modifier) -> Unit, + modifier: Modifier = Modifier, + cutoutRectsOverride: List? = null +) { + Row( + modifier = modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + if (topBarLeadingContent != null) { + CutoutAwareRow( + modifier = Modifier.wrapContentWidth( + align = Alignment.Start, + unbounded = true + ), + horizontalSpacing = 0.dp, + cutoutRectsOverride = cutoutRectsOverride + ) { + topBarLeadingContent(Modifier) + } + } + indicatorRow(Modifier) + } +} + @Composable private fun VerticalMaterialControls( modifier: Modifier = Modifier, @@ -437,3 +477,108 @@ private fun CaptureLayoutPreview() { debugVisibilityWrapper = { content -> content() } ) } + +@OptIn(ExperimentalMaterial3Api::class) +@Preview +@Composable +private fun CaptureLayoutWithTooltipPreview() { + PreviewLayout( + modifier = Modifier.background(Color.Black), + viewfinder = { modifier -> + Box( + modifier = modifier + .fillMaxWidth() + .height(600.dp) + .background(Color.DarkGray) + ) + }, + captureButton = { modifier -> + Box( + modifier = modifier + .size(80.dp) + .background(Color.White) + ) + }, + flipCameraButton = { modifier -> + Box( + modifier = modifier + .size(48.dp) + .background(Color.Cyan) + ) + }, + imageWell = { modifier -> + Box( + modifier = modifier + .size(48.dp) + .background(Color.Cyan) + ) + }, + zoomLevelDisplay = { modifier -> + Box( + modifier = modifier + .height(48.dp) + .fillMaxWidth() + .background(Color.Magenta) + ) + }, + elapsedTimeDisplay = { modifier -> + Box( + modifier = modifier + .height(24.dp) + .fillMaxWidth(0.5f) + .background(Color.Red) + ) + }, + quickSettingsButton = { modifier -> + Box( + modifier = modifier + .size(48.dp) + .background(Color.Yellow) + ) + }, + topBarLeadingContent = { modifier -> + TooltipIconButton( + modifier = modifier, + icon = { + Icon( + painter = painterResource(R.drawable.ic_info_filled), + contentDescription = null + ) + }, + tooltipText = "Camera information", + isOutlined = true + ) + }, + indicatorRow = { modifier -> + IndicatorPill(modifier = modifier.fillMaxWidth()) { + IndicatorPillIcon(visible = true) { + Icon( + painter = painterResource(R.drawable.ic_flash_on_filled), + contentDescription = null + ) + } + } + }, + captureModeToggle = { modifier -> + Box( + modifier = modifier + .height(48.dp) + .fillMaxWidth(0.5f) + .background(Color.Blue) + ) + }, + quickSettingsOverlay = { + // No-op for preview + }, + debugOverlay = { + // No-op for preview + }, + screenFlashOverlay = { + // No-op for preview + }, + snackBar = { _, _ -> + // No-op for preview + }, + debugVisibilityWrapper = { content -> content() } + ) +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProvider.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProvider.kt index 848542ad4a..e3459021fe 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProvider.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProvider.kt @@ -33,32 +33,26 @@ import androidx.compose.ui.layout.onGloballyPositioned * * @param modifier The [Modifier] to be applied to the outer layout. * @param overlapThreshold The ratio of overlap (between 0.0 and 1.0) required to switch the style. - * @param initialStyle The initial style to provide before spatial bounds are measured, preventing visual flicker on launch. * @param content The composable content that will receive the computed [LocalCameraControlBackgroundStyle]. */ @Composable internal fun OverlapAwareStyleProvider( modifier: Modifier = Modifier, overlapThreshold: Float = 0.5f, - initialStyle: CameraControlBackgroundStyle = CameraControlBackgroundStyle.WHITE_20, content: @Composable () -> Unit ) { val targetBounds = LocalOverlapTargetBounds.current.value var myBounds by remember { mutableStateOf(Rect.Zero) } - val hasMeasured = myBounds != Rect.Zero && targetBounds != Rect.Zero - val style = if (hasMeasured) { - val intersect = targetBounds.intersect(myBounds) - val intersectArea = if (intersect.isEmpty) 0f else intersect.width * intersect.height - val myArea = myBounds.width * myBounds.height - val isOverlapping = myArea > 0f && (intersectArea / myArea) >= overlapThreshold - if (isOverlapping) { - CameraControlBackgroundStyle.BLACK_60 - } else { - CameraControlBackgroundStyle.WHITE_20 - } + val intersect = targetBounds.intersect(myBounds) + val intersectArea = if (intersect.isEmpty) 0f else intersect.width * intersect.height + val myArea = myBounds.width * myBounds.height + val isOverlapping = myArea > 0f && (intersectArea / myArea) >= overlapThreshold + + val style = if (isOverlapping) { + CameraControlBackgroundStyle.BLACK_60 } else { - initialStyle + CameraControlBackgroundStyle.WHITE_20 } Box( diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureLayoutInsetsTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureLayoutInsetsTest.kt index daf5612cf9..b4cd32fa8b 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureLayoutInsetsTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureLayoutInsetsTest.kt @@ -18,6 +18,8 @@ package com.google.jetpackcamera.ui.components.capture import android.view.View import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.ui.Modifier @@ -28,6 +30,7 @@ import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onRoot import androidx.compose.ui.unit.DpRect +import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.dp import androidx.core.graphics.Insets import androidx.core.view.ViewCompat @@ -161,6 +164,55 @@ class CaptureLayoutInsetsTest { assertThat(overlayBounds).isEqualTo(rootBounds) } + @Test + fun topBarLeadingContent_touchesIndicatorRowWithZeroGap() { + lateinit var view: View + composeTestRule.setContent { + view = LocalView.current + TestPreviewLayout( + topBarLeadingContent = { + Box(it.size(48.dp).testTag(LEADING_BUTTON_TAG)) + } + ) + } + + val leadingBounds = boundsOf(LEADING_BUTTON_TAG, view, statusBarVisible = false) + val indicatorBounds = boundsOf(INDICATOR_ROW_TAG, view, statusBarVisible = false) + + assertThat(leadingBounds.left).isEqualTo(16.dp) + assertThat(leadingBounds.right).isEqualTo(64.dp) + assertThat(indicatorBounds.left).isEqualTo(leadingBounds.right) + } + + @Test + fun topBarLeadingContent_shiftsPastLeftCornerCutoutAlongsideIndicatorRow() { + // Left-corner cutout occupying local [0, 40] with 8dp clearance -> keep-out [0, 48]. + composeTestRule.setContent { + TopBarLeadingAndIndicatorsRow( + modifier = Modifier + .fillMaxWidth() + .height(48.dp), + topBarLeadingContent = { + Box(it.size(48.dp).testTag(LEADING_BUTTON_TAG)) + }, + indicatorRow = { + Box(it.size(40.dp).testTag(INDICATOR_ROW_TAG)) + }, + cutoutRectsOverride = listOf(IntRect(0, 0, 40, 48)) + ) + } + composeTestRule.waitForIdle() + + val leadingBounds = composeTestRule.onNodeWithTag(LEADING_BUTTON_TAG) + .getUnclippedBoundsInRoot() + val indicatorBounds = composeTestRule.onNodeWithTag(INDICATOR_ROW_TAG) + .getUnclippedBoundsInRoot() + + assertThat(leadingBounds.left).isEqualTo(48.dp) + assertThat(leadingBounds.right).isEqualTo(96.dp) + assertThat(indicatorBounds.left).isEqualTo(leadingBounds.right) + } + private fun boundsOf( tag: String, view: View, @@ -208,11 +260,13 @@ class CaptureLayoutInsetsTest { } private const val INDICATOR_ROW_TAG = "TestIndicatorRow" +private const val LEADING_BUTTON_TAG = "TestTopBarLeadingButton" private const val SCREEN_FLASH_OVERLAY_TAG = "TestScreenFlashOverlay" @OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) @androidx.compose.runtime.Composable private fun TestPreviewLayout( + topBarLeadingContent: (@androidx.compose.runtime.Composable (Modifier) -> Unit)? = null, screenFlashOverlay: @androidx.compose.runtime.Composable (Modifier) -> Unit = { Box(it.size(0.dp)) } @@ -226,6 +280,7 @@ private fun TestPreviewLayout( elapsedTimeDisplay = { Box(it.size(40.dp)) }, quickSettingsButton = { Box(it.size(40.dp)) }, indicatorRow = { Box(it.size(40.dp).testTag(INDICATOR_ROW_TAG)) }, + topBarLeadingContent = topBarLeadingContent, captureModeToggle = { Box(it.size(40.dp)) }, quickSettingsOverlay = { Box(it.size(40.dp)) }, debugOverlay = { Box(it.size(0.dp)) }, diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProviderTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProviderTest.kt index cd614abb33..23bd6f19b0 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProviderTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/OverlapAwareStyleProviderTest.kt @@ -23,7 +23,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect -import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.unit.dp import com.google.common.truth.Truth.assertThat import org.junit.Rule @@ -153,56 +153,4 @@ class OverlapAwareStyleProviderTest { // the 0f intersection correctly results in WHITE_20. assertThat(detectedStyle).isEqualTo(CameraControlBackgroundStyle.WHITE_20) } - - @Test - fun overlapAware_initialStyleBlack60_providesBlack60BeforeMeasurement() { - var detectedStyle: CameraControlBackgroundStyle? = null - - composeTestRule.setContent { - // Target bounds are Rect.Zero (unmeasured preview) - Box(Modifier.size(500.dp)) { - OverlapAwareStyleProvider( - modifier = Modifier.size(100.dp), - initialStyle = CameraControlBackgroundStyle.BLACK_60 - ) { - detectedStyle = LocalCameraControlBackgroundStyle.current - } - } - } - // Before bounds are available, it provides initialStyle - assertThat(detectedStyle).isEqualTo(CameraControlBackgroundStyle.BLACK_60) - } - - @Test - fun overlapAware_initialStyleBlack60_transitionsToWhite20WhenNoOverlapMeasured() { - var detectedStyle: CameraControlBackgroundStyle? = null - - composeTestRule.setContent { - val density = androidx.compose.ui.platform.LocalDensity.current - val targetBoundsPx = remember(density) { - with(density) { - Rect(0f, 0f, 100.dp.toPx(), 100.dp.toPx()) - } - } - Box(Modifier.size(500.dp)) { - CompositionLocalProvider( - LocalOverlapTargetBounds provides remember( - targetBoundsPx - ) { mutableStateOf(targetBoundsPx) } - ) { - OverlapAwareStyleProvider( - modifier = Modifier - .offset(x = 0.dp, y = 110.dp) - .size(100.dp), - initialStyle = CameraControlBackgroundStyle.BLACK_60 - ) { - detectedStyle = LocalCameraControlBackgroundStyle.current - } - } - } - } - composeTestRule.waitForIdle() - // Once measured with no overlap, it transitions to WHITE_20 - assertThat(detectedStyle).isEqualTo(CameraControlBackgroundStyle.WHITE_20) - } } diff --git a/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt new file mode 100644 index 0000000000..0dbdd157dd --- /dev/null +++ b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt @@ -0,0 +1,118 @@ +/* + * 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 + +import android.os.SystemClock +import android.view.InputDevice +import android.view.MotionEvent +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionOnScreen +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasAnyAncestor +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isPopup +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@OptIn(ExperimentalMaterial3Api::class) +@RunWith(AndroidJUnit4::class) +class TooltipInstrumentedTest { + + @get:Rule + val composeTestRule = createComposeRule() + + @Test + fun tooltipIconButton_realWindowTapOnAnchor_opensAndClosesTooltip() { + var anchorCenterOnScreen = Offset.Zero + + composeTestRule.setContent { + MaterialTheme { + Box(modifier = Modifier.fillMaxSize().padding(32.dp)) { + TooltipIconButton( + modifier = Modifier.onGloballyPositioned { coords -> + val pos = coords.positionOnScreen() + anchorCenterOnScreen = Offset( + x = pos.x + coords.size.width / 2f, + y = pos.y + coords.size.height / 2f + ) + }, + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "Real tap toggle message" + ) + } + } + } + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertDoesNotExist() + + // First real window-level tap opens the tooltip + sendRealScreenTap(anchorCenterOnScreen) + composeTestRule.waitForIdle() + composeTestRule.onNode(hasText("Real tap toggle message") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + + // Second real window-level tap on the anchor triggers Popup outside-touch dismissal on + // pointer-down and must leave the tooltip closed rather than reopening it on pointer-up + sendRealScreenTap(anchorCenterOnScreen) + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + + private fun sendRealScreenTap(screenPoint: Offset) { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val downTime = SystemClock.uptimeMillis() + val downEvent = MotionEvent.obtain( + downTime, + downTime, + MotionEvent.ACTION_DOWN, + screenPoint.x, + screenPoint.y, + 0 + ).apply { + source = InputDevice.SOURCE_TOUCHSCREEN + } + val upEvent = MotionEvent.obtain( + downTime, + downTime + 50L, + MotionEvent.ACTION_UP, + screenPoint.x, + screenPoint.y, + 0 + ).apply { + source = InputDevice.SOURCE_TOUCHSCREEN + } + try { + instrumentation.sendPointerSync(downEvent) + instrumentation.sendPointerSync(upEvent) + } finally { + downEvent.recycle() + upEvent.recycle() + } + } +} diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 1436d0d616..0075d763d3 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -15,10 +15,7 @@ */ package com.google.jetpackcamera.ui.components -import androidx.compose.animation.core.MutableTransitionState import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.MutatePriority -import androidx.compose.foundation.MutatorMutex import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -27,29 +24,27 @@ import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.waitForUpOrCancellation import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface +import androidx.compose.material3.RichTooltip import androidx.compose.material3.Text import androidx.compose.material3.TooltipAnchorPosition +import androidx.compose.material3.TooltipBox import androidx.compose.material3.TooltipDefaults +import androidx.compose.material3.TooltipScope import androidx.compose.material3.TooltipState +import androidx.compose.material3.rememberTooltipState import androidx.compose.material3.ripple import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf @@ -60,14 +55,15 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathOperation import androidx.compose.ui.graphics.Shape import androidx.compose.ui.input.pointer.PointerEventPass -import androidx.compose.ui.input.pointer.PointerEventTimeoutCancellationException import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag @@ -76,7 +72,6 @@ import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.paneTitle -import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign @@ -88,82 +83,37 @@ import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupPositionProvider -import androidx.compose.ui.window.PopupProperties import kotlin.math.roundToInt -import kotlin.time.Duration -import kotlinx.coroutines.CancellableContinuation -import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch -import kotlinx.coroutines.suspendCancellableCoroutine -import kotlinx.coroutines.withTimeout -import kotlinx.coroutines.withTimeoutOrNull const val TOOLTIP_ANCHOR_BUTTON_TAG = "tooltip_anchor_button" const val TOOLTIP_CONTENT_TAG = "tooltip_content" -/** - * Rationale and benefits of the custom [JcaTooltipBox] implementation: - * - * Upstream Material 3's [androidx.compose.material3.RichTooltip] and - * [androidx.compose.material3.TooltipBox] present limitations in camera overlay layouts: - * - * 1. Caret Misalignment: M3's caret positioning does not adjust when the popup window clamps - * against screen boundaries, causing the caret to drift away from edge-positioned anchors. - * 2. Visual Hitch: M3 calculates caret offsets asynchronously across layout passes, causing - * a 1-frame visual jump when the tooltip first appears. - * 3. Disjoint Geometry: M3 renders the caret as a separate rotated element, preventing seamless - * backgrounds, smooth corner clipping, and unified elevation shadows. - * - * Key advantages and customizations in [JcaTooltipBox]: +/* + * [JcaTooltipPositionProvider] and [JcaTooltipBubbleShape] plug into Material 3's [TooltipBox] and + * [RichTooltip] (currently androidx.compose.material3:material3:1.5.0-alpha27) to work around two + * upstream caret issues: + * 1. Near screen edges, M3 clamps the popup window without shifting the caret cleanly to track + * edge-aligned anchors within safe screen margins. + * 2. M3 computes caret coordinates in `onLayoutRectChanged` after placement, causing the caret to + * appear a few frames late. * - * - Flexible Caret Alignment: Supports [CaretAlignment.AnchorCenter], - * [CaretAlignment.BubbleCenter], start/end, and custom offsets, dynamically tracking anchors - * without corner bleed. - * - Reactive & Timed State: Decoupled [JcaTooltipState] managing visibility, [autoDismissDuration], - * and coroutine-driven mutual exclusion via [MutatorMutex]. - * - Frame-0 Synchronous Layout: Derives popup position and caret coordinates simultaneously - * before drawing, eliminating multi-frame visual hops. - * - Continuous Vector Shape: [JcaTooltipBubbleShape] unifies the bubble and caret into a single - * path for seamless fills, borders, and shadows. - * - Viewfinder-Aware & Accessible: High-contrast camera theming, responsive vertical scrolling - * under large font scaling, and TalkBack live region announcements. - */ - -/** - * Alignment options for the tooltip caret along the horizontal edge of the tooltip bubble. + * TODO: Remove JcaTooltipPositionProvider and JcaTooltipBubbleShape once upstream Material 3 + * resolves edge-clamped caret placement and initial-frame caret lag. */ -sealed interface CaretAlignment { - /** Positions the caret to point directly to the horizontal center of the anchor component. */ - data object AnchorCenter : CaretAlignment - - /** Positions the caret at the horizontal center of the tooltip bubble. */ - data object BubbleCenter : CaretAlignment - /** Positions the caret near the start edge (respecting layout direction). */ - data object Start : CaretAlignment +private object TooltipTokens { + val BorderWidth = 1.dp + const val BORDER_ALPHA = 0.2f - /** Positions the caret near the end edge (respecting layout direction). */ - data object End : CaretAlignment - - /** Positions the caret at a custom horizontal offset from the start edge. */ - data class Custom(val offset: Dp) : CaretAlignment + // Added to M3 RichTooltip's 4.dp plain vertical padding when no title/action is present + // to achieve 16.dp vertical body padding. + val TextExtraVerticalPadding = 12.dp } /** - * Color configuration for the tooltip bubble. - */ -@Immutable -data class JcaTooltipColors( - val containerColor: Color, - val contentColor: Color, - val titleContentColor: Color -) - -/** - * Default dimensions, styling tokens, and color values for JCA tooltips, - * referencing standard Material 3 design tokens and component defaults. + * Default dimensions for JCA tooltips, referencing Material 3 component defaults where available. */ @OptIn(ExperimentalMaterial3Api::class) object JcaTooltipDefaults { @@ -178,60 +128,27 @@ object JcaTooltipDefaults { /** Safe screen edge margins for clamping popup placement against window boundaries. */ val ScreenMargin: Dp = 16.dp - /** Large corner radius token (16dp) based on Material 3 ShapeDefaults.Large. */ + /** Large corner radius token (16dp) matching Material 3 ShapeDefaults.Large. */ val CornerRadius: Dp = 16.dp /** Standard Material minimum interactive touch target size (48dp). */ val TouchTargetSize: Dp = 48.dp /** Visual container size (32dp) matching [IconButtonDefaults.extraSmallContainerSize]. */ - val ContainerSize: Dp = IconButtonDefaults.extraSmallContainerSize().width // 32.dp + val ContainerSize: Dp = IconButtonDefaults.extraSmallContainerSize().width /** Medium icon size (24dp) matching [IconButtonDefaults.mediumIconSize]. */ - val IconSize: Dp = IconButtonDefaults.mediumIconSize // 24.dp - - /** Width constraints for the tooltip bubble. */ - val MinWidth: Dp = 140.dp + val IconSize: Dp = IconButtonDefaults.mediumIconSize /** * Maximum width aligned with design mock (296dp), * capped within [TooltipDefaults.richTooltipMaxWidth] (320dp). */ val MaxWidth: Dp = 296.dp - - /** Container elevation Level 2 (2dp) matching Material 3 RichTooltipTokens. */ - val DefaultElevation: Dp = 2.dp - - /** - * Default high-contrast colors suited for camera viewfinder overlays. - */ - @Composable - fun tooltipColors( - containerColor: Color = MaterialTheme.colorScheme.secondaryFixed, - contentColor: Color = MaterialTheme.colorScheme.onSecondaryFixed, - titleContentColor: Color = MaterialTheme.colorScheme.onSecondaryFixed - ): JcaTooltipColors = JcaTooltipColors( - containerColor = containerColor, - contentColor = contentColor, - titleContentColor = titleContentColor - ) - - /** - * Standard Material 3 rich tooltip colors based on [TooltipDefaults.richTooltipColors]. - */ - @Composable - fun standardM3Colors(): JcaTooltipColors { - val m3Defaults = TooltipDefaults.richTooltipColors() - return JcaTooltipColors( - containerColor = m3Defaults.containerColor, - contentColor = m3Defaults.contentColor, - titleContentColor = m3Defaults.titleContentColor - ) - } } /** - * State holder for dynamic caret positioning. + * State holder for dynamic caret coordinates computed synchronously during popup placement. */ @Stable class CaretPositionState( @@ -243,8 +160,8 @@ class CaretPositionState( } /** - * Vector shape that draws a continuous outline combining a rounded rectangle bubble - * and a triangular caret pointing toward the anchor. + * Shape that unions a rounded rectangle bubble body with a triangular caret pointing toward the + * anchor. */ class JcaTooltipBubbleShape( val localCaretX: Float, @@ -269,91 +186,41 @@ class JcaTooltipBubbleShape( val ch = with(density) { caretHeight.toPx() } val bodyHeight = (h - ch).coerceAtLeast(0f) + val bodyTop = if (isCaretOnTop) ch else 0f val actualRadius = minOf(r, bodyHeight / 2f, w / 2f).coerceAtLeast(0f) - // Clamp caret base to ensure the triangle never bleeds into the corner radius arcs + // Clamp caret base so the triangle never bleeds into the corner radius arcs val minCaretX = actualRadius + cw / 2f val maxCaretX = (w - actualRadius - cw / 2f).coerceAtLeast(minCaretX) val clampedCaretX = localCaretX.coerceIn(minCaretX, maxCaretX) - val path = Path() - if (isCaretOnTop) { - val bodyTop = ch - val bodyBottom = h - - path.moveTo(actualRadius, bodyTop) - path.lineTo(clampedCaretX - cw / 2f, bodyTop) - path.lineTo(clampedCaretX, 0f) - path.lineTo(clampedCaretX + cw / 2f, bodyTop) - path.lineTo(w - actualRadius, bodyTop) - path.arcTo( - rect = Rect(w - 2f * actualRadius, bodyTop, w, bodyTop + 2f * actualRadius), - startAngleDegrees = 270f, - sweepAngleDegrees = 90f, - forceMoveTo = false - ) - path.lineTo(w, bodyBottom - actualRadius) - path.arcTo( - rect = Rect(w - 2f * actualRadius, bodyBottom - 2f * actualRadius, w, bodyBottom), - startAngleDegrees = 0f, - sweepAngleDegrees = 90f, - forceMoveTo = false - ) - path.lineTo(actualRadius, bodyBottom) - path.arcTo( - rect = Rect(0f, bodyBottom - 2f * actualRadius, 2f * actualRadius, bodyBottom), - startAngleDegrees = 90f, - sweepAngleDegrees = 90f, - forceMoveTo = false - ) - path.lineTo(0f, bodyTop + actualRadius) - path.arcTo( - rect = Rect(0f, bodyTop, 2f * actualRadius, bodyTop + 2f * actualRadius), - startAngleDegrees = 180f, - sweepAngleDegrees = 90f, - forceMoveTo = false - ) - path.close() - } else { - val bodyTop = 0f - val bodyBottom = h - ch - - path.moveTo(actualRadius, bodyTop) - path.lineTo(w - actualRadius, bodyTop) - path.arcTo( - rect = Rect(w - 2f * actualRadius, bodyTop, w, bodyTop + 2f * actualRadius), - startAngleDegrees = 270f, - sweepAngleDegrees = 90f, - forceMoveTo = false - ) - path.lineTo(w, bodyBottom - actualRadius) - path.arcTo( - rect = Rect(w - 2f * actualRadius, bodyBottom - 2f * actualRadius, w, bodyBottom), - startAngleDegrees = 0f, - sweepAngleDegrees = 90f, - forceMoveTo = false - ) - path.lineTo(clampedCaretX + cw / 2f, bodyBottom) - path.lineTo(clampedCaretX, h) - path.lineTo(clampedCaretX - cw / 2f, bodyBottom) - path.lineTo(actualRadius, bodyBottom) - path.arcTo( - rect = Rect(0f, bodyBottom - 2f * actualRadius, 2f * actualRadius, bodyBottom), - startAngleDegrees = 90f, - sweepAngleDegrees = 90f, - forceMoveTo = false - ) - path.lineTo(0f, bodyTop + actualRadius) - path.arcTo( - rect = Rect(0f, bodyTop, 2f * actualRadius, bodyTop + 2f * actualRadius), - startAngleDegrees = 180f, - sweepAngleDegrees = 90f, - forceMoveTo = false - ) - path.close() + val bodyOutline = RoundedCornerShape(cornerRadius).createOutline( + size = Size(w, bodyHeight), + layoutDirection = layoutDirection, + density = density + ) + val bodyPath = Path().apply { + when (bodyOutline) { + is Outline.Generic -> addPath(bodyOutline.path) + is Outline.Rounded -> addRoundRect(bodyOutline.roundRect) + is Outline.Rectangle -> addRect(bodyOutline.rect) + } + translate(Offset(0f, bodyTop)) } - return Outline.Generic(path) + val baseY = if (isCaretOnTop) bodyTop else bodyHeight + val tipY = if (isCaretOnTop) 0f else h + val caretPath = Path().apply { + moveTo(clampedCaretX - cw / 2f, baseY) + lineTo(clampedCaretX, tipY) + lineTo(clampedCaretX + cw / 2f, baseY) + close() + } + + val combinedPath = Path().apply { + op(bodyPath, caretPath, PathOperation.Union) + } + return Outline.Generic(combinedPath) } override fun equals(other: Any?): Boolean { @@ -377,15 +244,16 @@ class JcaTooltipBubbleShape( } /** - * Position provider for the tooltip popup that calculates screen-clamped coordinates and - * derives the local caret offset relative to the popup's top-left corner on Frame 0 before draw. + * Position provider for the tooltip popup that clamps popup coordinates to safe screen margins and + * derives the corner-clamped local caret offset relative to the popup's top-left corner before draw. */ @OptIn(ExperimentalMaterial3Api::class) class JcaTooltipPositionProvider( val positioning: TooltipAnchorPosition, - val caretAlignment: CaretAlignment = CaretAlignment.AnchorCenter, val spacing: Dp = JcaTooltipDefaults.SpacingBetweenTooltipAndAnchor, val screenMargin: Dp = JcaTooltipDefaults.ScreenMargin, + val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, + val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, val density: Density, val onCaretCalculated: (localCaretX: Float, isCaretOnTop: Boolean) -> Unit = { _, _ -> } ) : PopupPositionProvider { @@ -404,18 +272,10 @@ class JcaTooltipPositionProvider( val placeBelow = when (positioning) { TooltipAnchorPosition.Below -> { - if (spaceBelow >= popupContentSize.height || spaceBelow >= spaceAbove) { - true - } else { - false - } + spaceBelow >= popupContentSize.height || spaceBelow >= spaceAbove } TooltipAnchorPosition.Above -> { - if (spaceAbove >= popupContentSize.height || spaceAbove >= spaceBelow) { - false - } else { - true - } + !(spaceAbove >= popupContentSize.height || spaceAbove >= spaceBelow) } else -> spaceBelow >= popupContentSize.height } @@ -437,41 +297,15 @@ class JcaTooltipPositionProvider( val maxX = (windowSize.width - marginPx - popupContentSize.width).coerceAtLeast(minX) val popupX = idealPopupX.coerceIn(minX, maxX) - // Local caret X coordinate relative to the popup's top-left corner - val localCaretX = when (caretAlignment) { - is CaretAlignment.AnchorCenter -> { - anchorCenterX - popupX - } - is CaretAlignment.BubbleCenter -> { - popupContentSize.width / 2f - } - is CaretAlignment.Start -> { - val cornerRadiusPx = with(density) { JcaTooltipDefaults.CornerRadius.toPx() } - val caretWidthPx = with(density) { JcaTooltipDefaults.CaretWidth.toPx() } - if (layoutDirection == LayoutDirection.Rtl) { - popupContentSize.width - cornerRadiusPx - caretWidthPx / 2f - } else { - cornerRadiusPx + caretWidthPx / 2f - } - } - is CaretAlignment.End -> { - val cornerRadiusPx = with(density) { JcaTooltipDefaults.CornerRadius.toPx() } - val caretWidthPx = with(density) { JcaTooltipDefaults.CaretWidth.toPx() } - if (layoutDirection == LayoutDirection.Rtl) { - cornerRadiusPx + caretWidthPx / 2f - } else { - popupContentSize.width - cornerRadiusPx - caretWidthPx / 2f - } - } - is CaretAlignment.Custom -> { - val offsetPx = with(density) { caretAlignment.offset.toPx() } - if (layoutDirection == LayoutDirection.Rtl) { - popupContentSize.width - offsetPx - } else { - offsetPx - } - } - } + // Clamp local caret X so the caret base stays outside the rounded corners and matches + // what JcaTooltipBubbleShape draws + val cornerRadiusPx = with(density) { cornerRadius.toPx() } + val caretWidthPx = with(density) { caretWidth.toPx() } + val actualRadius = minOf(cornerRadiusPx, popupContentSize.width / 2f).coerceAtLeast(0f) + val minCaretX = actualRadius + caretWidthPx / 2f + val maxCaretX = + (popupContentSize.width - actualRadius - caretWidthPx / 2f).coerceAtLeast(minCaretX) + val localCaretX = (anchorCenterX - popupX).coerceIn(minCaretX, maxCaretX) onCaretCalculated(localCaretX, placeBelow) @@ -479,251 +313,40 @@ class JcaTooltipPositionProvider( } } -private const val DEFAULT_TOOLTIP_DURATION_MILLIS = 1500L - -/** - * An extended [TooltipState] for JCA tooltips that supports auto-dismiss durations, - * coroutine-driven mutual exclusion via [MutatorMutex], and programmatic toggling. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Stable -interface JcaTooltipState : TooltipState { - /** - * Optional duration after which the tooltip automatically dismisses. - */ - val autoDismissDuration: Duration? - - /** - * Toggles the visibility of the tooltip. - * - * If the tooltip is currently visible or transitioning to visible, it will be dismissed. - * Otherwise, it will be shown. - */ - suspend fun toggle(mutatePriority: MutatePriority = MutatePriority.Default) -} - -/** - * Creates and remembers an instance of [JcaTooltipState]. - * - * @param autoDismissDuration Optional duration after which the tooltip automatically dismisses. - * When non-null, every call to [TooltipState.show] will keep the tooltip displayed for this - * duration before dismissing, resetting the timer if re-triggered while already visible. - * @param initialIsVisible Whether the tooltip should be initially visible. - * @param isPersistent Whether the tooltip should remain visible until explicitly dismissed - * when [autoDismissDuration] is null. If false and [autoDismissDuration] is null, defaults - * to standard transient duration (1500ms). - * @param mutatorMutex Mutex coordinating tooltip display. Defaults to a fresh [MutatorMutex] - * instance per tooltip state. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun rememberJcaTooltipState( - autoDismissDuration: Duration? = null, - initialIsVisible: Boolean = false, - isPersistent: Boolean = true, - mutatorMutex: MutatorMutex = remember { MutatorMutex() } -): JcaTooltipState = remember(autoDismissDuration, initialIsVisible, isPersistent, mutatorMutex) { - JcaTooltipStateImpl( - autoDismissDuration = autoDismissDuration, - initialIsVisible = initialIsVisible, - isPersistent = isPersistent, - mutatorMutex = mutatorMutex - ) -} - -@OptIn(ExperimentalMaterial3Api::class) -@Stable -private class JcaTooltipStateImpl( - override val autoDismissDuration: Duration?, - initialIsVisible: Boolean = false, - override val isPersistent: Boolean = true, - private val mutatorMutex: MutatorMutex = MutatorMutex() -) : JcaTooltipState { - - override val transition: MutableTransitionState = - MutableTransitionState(initialIsVisible) - - override val isVisible: Boolean - get() = transition.currentState || transition.targetState - - private var job: CancellableContinuation? = null - - override suspend fun show(mutatePriority: MutatePriority) { - val cancellableShow: suspend () -> Unit = { - try { - suspendCancellableCoroutine { continuation -> - transition.targetState = true - job = continuation - } - } finally { - job = null - transition.targetState = false - } - } - - mutatorMutex.mutate(mutatePriority) { - try { - if (autoDismissDuration != null) { - withTimeoutOrNull(autoDismissDuration.inWholeMilliseconds) { - cancellableShow() - } - } else if (isPersistent) { - cancellableShow() - } else { - withTimeoutOrNull(DEFAULT_TOOLTIP_DURATION_MILLIS) { - cancellableShow() - } - } - } finally { - job = null - transition.targetState = false - } - } - } - - override fun dismiss() { - transition.targetState = false - if (job?.isActive == true) { - job?.cancel() - } - } - - override suspend fun toggle(mutatePriority: MutatePriority) { - if (transition.targetState) { - dismiss() - } else { - show(mutatePriority) - } - } - - override fun onDispose() { - dismiss() - } -} - -/** - * Custom tooltip bubble composable rendering styled text and an optional title within - * a unified [JcaTooltipBubbleShape]. - */ -@Composable -fun JcaTooltipBubble( - tooltipText: String, - modifier: Modifier = Modifier, - tooltipTitle: String? = null, - caretPositionState: CaretPositionState = remember { CaretPositionState() }, - colors: JcaTooltipColors = JcaTooltipDefaults.tooltipColors(), - elevation: Dp = JcaTooltipDefaults.DefaultElevation -) { - val isCaretOnTop = caretPositionState.isCaretOnTop - val localCaretX = caretPositionState.localCaretX - - val bubbleShape = remember(localCaretX, isCaretOnTop) { - JcaTooltipBubbleShape( - localCaretX = localCaretX, - isCaretOnTop = isCaretOnTop - ) - } - - val topPadding = if (isCaretOnTop) { - JcaTooltipDefaults.CaretHeight + 16.dp - } else { - 16.dp - } - val bottomPadding = if (!isCaretOnTop) { - JcaTooltipDefaults.CaretHeight + 16.dp - } else { - 16.dp - } - - Surface( - shape = bubbleShape, - color = colors.containerColor, - shadowElevation = elevation, - modifier = modifier - .widthIn(min = JcaTooltipDefaults.MinWidth, max = JcaTooltipDefaults.MaxWidth) - .testTag(TOOLTIP_CONTENT_TAG) - .semantics { - liveRegion = LiveRegionMode.Polite - paneTitle = tooltipTitle ?: tooltipText - } - ) { - Column( - modifier = Modifier - .padding( - top = topPadding, - bottom = bottomPadding, - start = 16.dp, - end = 16.dp - ) - .verticalScroll(rememberScrollState()), - horizontalAlignment = Alignment.CenterHorizontally - ) { - if (tooltipTitle != null) { - Text( - text = tooltipTitle, - style = MaterialTheme.typography.titleSmall, - color = colors.titleContentColor, - textAlign = TextAlign.Center, - modifier = Modifier - .fillMaxWidth() - .padding(bottom = 4.dp) - ) - } - Text( - text = tooltipText, - style = MaterialTheme.typography.labelLarge.copy( - fontWeight = FontWeight.Medium - ), - color = colors.contentColor, - textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth() - ) - } - } -} - /** - * A generic container that wraps content with a styled tooltip using a bespoke Compose [Popup]. + * An icon button that toggles a styled [RichTooltip] when tapped. * - * @param tooltipText The text to display inside the tooltip. - * @param modifier Modifier for the container. - * @param tooltipTitle Optional title displayed above the tooltip text. - * @param state State controlling tooltip visibility. Defaults to [rememberJcaTooltipState]. - * @param positioning Anchor position for the tooltip (e.g. Above, Below). - * @param caretAlignment Alignment configuration for the caret. - * @param enableUserInput Whether long-press gestures on the anchor trigger the tooltip. - * @param colors Colors applied to the tooltip bubble and text. - * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. - * @param content The anchor composable wrapped by the tooltip. + * Uses Material 3's [TooltipBox] and [RichTooltip] for animations, focus, shadow, and state + * management, paired with [JcaTooltipPositionProvider] and [JcaTooltipBubbleShape] for edge-aware + * caret placement. */ @OptIn(ExperimentalMaterial3Api::class) @Composable -fun JcaTooltipBox( +fun TooltipIconButton( + icon: @Composable () -> Unit, tooltipText: String, modifier: Modifier = Modifier, + contentDescription: String? = null, tooltipTitle: String? = null, - state: TooltipState = rememberJcaTooltipState(), - positioning: TooltipAnchorPosition = TooltipAnchorPosition.Above, - caretAlignment: CaretAlignment = CaretAlignment.AnchorCenter, - enableUserInput: Boolean = true, - colors: JcaTooltipColors = JcaTooltipDefaults.tooltipColors(), - onDismissRequest: (() -> Unit)? = null, - content: @Composable () -> Unit + state: TooltipState = rememberTooltipState(isPersistent = true), + positioning: TooltipAnchorPosition = TooltipAnchorPosition.Below, + isOutlined: Boolean = false, + containerColor: Color = Color.Transparent, + contentColor: Color = Color.White, + size: Dp = JcaTooltipDefaults.ContainerSize, + minTouchTargetSize: Dp = JcaTooltipDefaults.TouchTargetSize, + onClick: () -> Unit = {}, + onDismissRequest: (() -> Unit)? = null ) { - val scope = rememberCoroutineScope() - val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) - val density = LocalDensity.current val caretPositionState = remember { CaretPositionState( initialIsCaretOnTop = positioning == TooltipAnchorPosition.Below ) } - - val positionProvider = remember(positioning, caretAlignment, density) { + val positionProvider = remember(positioning, density) { JcaTooltipPositionProvider( positioning = positioning, - caretAlignment = caretAlignment, density = density, onCaretCalculated = { localCaretX, isCaretOnTop -> caretPositionState.localCaretX = localCaretX @@ -732,98 +355,100 @@ fun JcaTooltipBox( ) } - Box( - modifier = modifier.tooltipGestures( - enabled = enableUserInput, - state = state, - scope = scope - ) - ) { - content() - - if (state.isVisible) { - Popup( - popupPositionProvider = positionProvider, - onDismissRequest = { - scope.launch { state.dismiss() } - currentOnDismissRequest?.invoke() + TooltipIconButton( + icon = icon, + modifier = modifier, + contentDescription = contentDescription ?: tooltipTitle ?: tooltipText, + state = state, + positionProvider = positionProvider, + isOutlined = isOutlined, + containerColor = containerColor, + contentColor = contentColor, + size = size, + minTouchTargetSize = minTouchTargetSize, + onClick = onClick, + onDismissRequest = onDismissRequest, + tooltip = { + val isCaretOnTop = caretPositionState.isCaretOnTop + val bubbleShape = remember(caretPositionState.localCaretX, isCaretOnTop) { + JcaTooltipBubbleShape( + localCaretX = caretPositionState.localCaretX, + isCaretOnTop = isCaretOnTop + ) + } + val caretTopPadding = if (isCaretOnTop) JcaTooltipDefaults.CaretHeight else 0.dp + val caretBottomPadding = if (!isCaretOnTop) JcaTooltipDefaults.CaretHeight else 0.dp + + RichTooltip( + modifier = Modifier + .testTag(TOOLTIP_CONTENT_TAG) + .semantics { + liveRegion = LiveRegionMode.Polite + paneTitle = tooltipTitle ?: tooltipText + }, + title = tooltipTitle?.let { titleText -> + { + Text( + text = titleText, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(top = caretTopPadding) + ) + } }, - properties = PopupProperties( - focusable = false, - clippingEnabled = false + caretShape = null, + maxWidth = JcaTooltipDefaults.MaxWidth, + shape = bubbleShape, + colors = TooltipDefaults.richTooltipColors( + containerColor = MaterialTheme.colorScheme.secondaryFixed, + contentColor = MaterialTheme.colorScheme.onSecondaryFixed, + titleContentColor = MaterialTheme.colorScheme.onSecondaryFixed ) ) { - JcaTooltipBubble( - tooltipText = tooltipText, - tooltipTitle = tooltipTitle, - caretPositionState = caretPositionState, - colors = colors + Text( + text = tooltipText, + style = MaterialTheme.typography.labelLarge.copy( + fontWeight = FontWeight.Medium + ), + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding( + top = if (tooltipTitle == null) { + caretTopPadding + TooltipTokens.TextExtraVerticalPadding + } else { + 0.dp + }, + bottom = if (tooltipTitle == null) { + caretBottomPadding + TooltipTokens.TextExtraVerticalPadding + } else { + caretBottomPadding + } + ) ) } } - } - - DisposableEffect(state) { - onDispose { - state.onDispose() - } - } -} - -@OptIn(ExperimentalMaterial3Api::class) -private fun Modifier.tooltipGestures( - enabled: Boolean, - state: TooltipState, - scope: CoroutineScope -): Modifier = if (enabled) { - this.pointerInput(state) { - awaitEachGesture { - awaitFirstDown(pass = PointerEventPass.Initial) - try { - withTimeout(viewConfiguration.longPressTimeoutMillis) { - waitForUpOrCancellation(pass = PointerEventPass.Initial) - } - } catch (e: PointerEventTimeoutCancellationException) { - scope.launch { state.show() } - } - } - } -} else { - this + ) } /** - * An icon button that shows a styled tooltip when clicked. + * An icon button that toggles custom tooltip content scoped to [TooltipScope] when tapped. * - * @param icon The icon to display inside the button. - * @param tooltipText The text to display inside the tooltip. - * @param modifier Modifier for the button container. - * @param contentDescription Optional accessibility content description for TalkBack. - * @param tooltipTitle The optional title to display inside the tooltip. - * @param state State controlling tooltip visibility. Defaults to [rememberJcaTooltipState]. - * @param positioning Anchor position for the tooltip (e.g. Above, Below). Defaults to Below. - * @param caretAlignment Alignment configuration for the caret. Defaults to AnchorCenter. - * @param isOutlined Whether the icon button should be outlined. - * @param containerColor The background container color for the button. - * @param contentColor The content/tint color for the icon. - * @param size The size of the inner visual container, defaulting to - * [IconButtonDefaults.extraSmallContainerSize] (32.dp). - * @param minTouchTargetSize The minimum interactive touch target size for accessibility, - * defaulting to 48.dp. - * @param onClick Optional callback when the button is clicked. - * @param onDismissRequest Optional callback invoked when the tooltip is dismissed. + * Allows callers to supply custom [RichTooltip] content (such as actions or styled text) while + * sharing the camera overlay button styling and pointer-down toggle handling. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun TooltipIconButton( icon: @Composable () -> Unit, - tooltipText: String, + tooltip: @Composable TooltipScope.() -> Unit, modifier: Modifier = Modifier, contentDescription: String? = null, - tooltipTitle: String? = null, - state: JcaTooltipState = rememberJcaTooltipState(), - positioning: TooltipAnchorPosition = TooltipAnchorPosition.Below, - caretAlignment: CaretAlignment = CaretAlignment.AnchorCenter, + state: TooltipState = rememberTooltipState(isPersistent = true), + positionProvider: PopupPositionProvider = + TooltipDefaults.rememberTooltipPositionProvider(TooltipAnchorPosition.Below), + hasAction: Boolean = false, isOutlined: Boolean = false, containerColor: Color = Color.Transparent, contentColor: Color = Color.White, @@ -835,47 +460,64 @@ fun TooltipIconButton( val scope = rememberCoroutineScope() val currentOnClick by rememberUpdatedState(onClick) val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) + var wasVisibleAtDown by remember { mutableStateOf(false) } - val toggleTooltip = remember(state, scope) { - { - scope.launch { - val wasVisible = state.transition.targetState - state.toggle() - if (wasVisible) { - currentOnDismissRequest?.invoke() - } - } - currentOnClick() - } - } - - JcaTooltipBox( - tooltipText = tooltipText, - modifier = modifier, - tooltipTitle = tooltipTitle, + TooltipBox( + positionProvider = positionProvider, + tooltip = tooltip, state = state, - positioning = positioning, - caretAlignment = caretAlignment, + modifier = modifier, + onDismissRequest = onDismissRequest?.let { + { + state.dismiss() + currentOnDismissRequest?.invoke() + } + }, enableUserInput = false, - onDismissRequest = onDismissRequest + hasAction = hasAction ) { - val defaultContentDescription = tooltipTitle ?: tooltipText - val effectiveContentDescription = contentDescription ?: defaultContentDescription - Box( modifier = Modifier .sizeIn(minWidth = minTouchTargetSize, minHeight = minTouchTargetSize) .testTag(TOOLTIP_ANCHOR_BUTTON_TAG) + .pointerInput(state) { + awaitEachGesture { + awaitFirstDown(pass = PointerEventPass.Initial) + wasVisibleAtDown = state.isVisible + val up = waitForUpOrCancellation(pass = PointerEventPass.Initial) + val releasedInBounds = up != null && + up.position.x in 0f..this.size.width.toFloat() && + up.position.y in 0f..this.size.height.toFloat() + if (!releasedInBounds) { + wasVisibleAtDown = false + } + } + } .clickable( - onClick = toggleTooltip, role = Role.Button, - onClickLabel = effectiveContentDescription, + onClickLabel = null, interactionSource = remember { MutableInteractionSource() }, indication = ripple(bounded = false, radius = minTouchTargetSize / 2) - ) - .semantics { - this.contentDescription = effectiveContentDescription - }, + ) { + val wasVisible = wasVisibleAtDown || state.isVisible + wasVisibleAtDown = false + if (wasVisible) { + state.dismiss() + currentOnDismissRequest?.invoke() + } else { + scope.launch { state.show() } + } + currentOnClick() + } + .then( + if (contentDescription != null) { + Modifier.semantics { + this.contentDescription = contentDescription + } + } else { + Modifier + } + ), contentAlignment = Alignment.Center ) { val containerModifier = Modifier @@ -883,7 +525,10 @@ fun TooltipIconButton( .then( if (isOutlined) { Modifier.border( - border = BorderStroke(1.dp, Color.White.copy(alpha = 0.2f)), + border = BorderStroke( + TooltipTokens.BorderWidth, + Color.White.copy(alpha = TooltipTokens.BORDER_ALPHA) + ), shape = CircleShape ) } else { diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index e1ffcc4743..0e9f45ef71 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -19,35 +19,36 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RichTooltip +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TooltipAnchorPosition -import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.semantics.getOrNull import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertHeightIsAtLeast import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertWidthIsAtLeast +import androidx.compose.ui.test.click import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasText import androidx.compose.ui.test.isPopup import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.google.common.truth.Truth.assertThat -import kotlin.time.Duration.Companion.milliseconds -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.launch import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -61,33 +62,21 @@ class TooltipTest { val composeTestRule = createComposeRule() @Test - fun tooltip_initialState_isNotDisplayed() { + fun tooltip_touchTap_togglesVisibility() { composeTestRule.setContent { MaterialTheme { TooltipIconButton( icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipTitle = "Info Title", tooltipText = "Help information" ) } } composeTestRule.onNode(isPopup()).assertDoesNotExist() - } - - @Test - fun tooltip_clickAnchor_togglesVisibility() { - composeTestRule.setContent { - MaterialTheme { - TooltipIconButton( - icon = { Box(modifier = Modifier.size(24.dp)) }, - tooltipTitle = "Info Title", - tooltipText = "Help information" - ) - } - } - // Show on first tap - composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + // Show on first touch tap + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } composeTestRule.waitForIdle() composeTestRule.onNode(isPopup()).assertExists() @@ -96,215 +85,57 @@ class TooltipTest { composeTestRule.onNode(hasText("Info Title") and hasAnyAncestor(isPopup())) .assertIsDisplayed() - // Dismiss on second tap - composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + // Dismiss on second touch tap + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } composeTestRule.waitForIdle() composeTestRule.onNode(isPopup()).assertDoesNotExist() } @Test - fun tooltip_programmaticTrigger_showsAndDismisses() { - lateinit var tooltipState: JcaTooltipState - lateinit var coroutineScope: CoroutineScope - + fun tooltip_composableSlotOverload_rendersCustomRichTooltipAndAction() { + var actionClicked = false composeTestRule.setContent { - val state = rememberJcaTooltipState() - tooltipState = state - coroutineScope = rememberCoroutineScope() MaterialTheme { TooltipIconButton( icon = { Box(modifier = Modifier.size(24.dp)) }, - tooltipText = "Programmatic trigger text", - state = state + contentDescription = "Info button", + hasAction = true, + tooltip = { + RichTooltip( + action = { + TextButton(onClick = { actionClicked = true }) { + Text("Learn more") + } + } + ) { + Text("Styled tooltip body") + } + } ) } } - composeTestRule.onNode(isPopup()).assertDoesNotExist() - - // Programmatically show - coroutineScope.launch { tooltipState.show() } - composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertExists() - composeTestRule.onNode(hasText("Programmatic trigger text") and hasAnyAncestor(isPopup())) - .assertIsDisplayed() - - // Programmatically dismiss - tooltipState.dismiss() + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertDoesNotExist() - } - - @Test - fun tooltipState_toggle_switchesVisibility() { - lateinit var tooltipState: JcaTooltipState - lateinit var coroutineScope: CoroutineScope - composeTestRule.setContent { - val state = rememberJcaTooltipState() - tooltipState = state - coroutineScope = rememberCoroutineScope() - MaterialTheme { - TooltipIconButton( - icon = { Box(modifier = Modifier.size(24.dp)) }, - tooltipText = "Toggle text", - state = state - ) - } - } - - composeTestRule.onNode(isPopup()).assertDoesNotExist() - - // Toggle on - coroutineScope.launch { tooltipState.toggle() } - composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertExists() - - // Toggle off - coroutineScope.launch { tooltipState.toggle() } - composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertDoesNotExist() - } - - @Test - fun tooltip_autoDismiss_dismissesAfterSpecifiedDuration() { - composeTestRule.mainClock.autoAdvance = false - - composeTestRule.setContent { - MaterialTheme { - TooltipIconButton( - icon = { Box(modifier = Modifier.size(24.dp)) }, - tooltipText = "Auto dismissing text", - state = rememberJcaTooltipState(autoDismissDuration = 3000.milliseconds) - ) - } - } - - // Trigger show - composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() - composeTestRule.mainClock.advanceTimeByFrame() - composeTestRule.waitForIdle() - - composeTestRule.onNode(isPopup()).assertExists() - - // Advance part-way (1500ms) -> Still displayed - composeTestRule.mainClock.advanceTimeBy(1500) - composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertExists() - - // Advance remaining time past 3000ms -> Trigger dismiss and allow exit transition - composeTestRule.mainClock.advanceTimeBy(1501) - composeTestRule.mainClock.autoAdvance = true - composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertDoesNotExist() - } - - @Test - fun tooltip_autoDismiss_reTriggerResetsTimer() { - composeTestRule.mainClock.autoAdvance = false - lateinit var tooltipState: JcaTooltipState - lateinit var coroutineScope: CoroutineScope - - composeTestRule.setContent { - val state = rememberJcaTooltipState(autoDismissDuration = 3000.milliseconds) - tooltipState = state - coroutineScope = rememberCoroutineScope() - MaterialTheme { - TooltipIconButton( - icon = { Box(modifier = Modifier.size(24.dp)) }, - tooltipText = "Resetting timer text", - state = state - ) - } - } - - // Trigger show via state - coroutineScope.launch { tooltipState.show() } - composeTestRule.mainClock.advanceTimeByFrame() - composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertExists() - - // Advance 2000ms of 3000ms - composeTestRule.mainClock.advanceTimeBy(2000) - composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertExists() - - // Re-trigger Show -> Timer resets - coroutineScope.launch { tooltipState.show() } - composeTestRule.mainClock.advanceTimeByFrame() - composeTestRule.waitForIdle() - - // Advance another 2000ms (total 4000ms from start, but only 2000ms since reset) - composeTestRule.mainClock.advanceTimeBy(2000) - composeTestRule.waitForIdle() - // Must still exist because timer was reset - composeTestRule.onNode(isPopup()).assertExists() - - // Advance past reset expiration (remaining 1001ms) -> - // Trigger dismiss and allow exit transition - composeTestRule.mainClock.advanceTimeBy(1001) - composeTestRule.mainClock.autoAdvance = true + composeTestRule.onNode(hasText("Styled tooltip body") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + composeTestRule.onNode(hasText("Learn more") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + .performTouchInput { click() } composeTestRule.waitForIdle() - composeTestRule.onNode(isPopup()).assertDoesNotExist() - } - - @Test - fun tooltip_positioning_supportsAboveAndBelow() { - composeTestRule.setContent { - MaterialTheme { - JcaTooltipBox( - tooltipText = "Position Below Text", - positioning = TooltipAnchorPosition.Below - ) { - Box(modifier = Modifier.size(48.dp)) - } - } - } - - composeTestRule.onNode(isPopup()).assertDoesNotExist() - } - - @Test - fun tooltip_customContainerColor_appliesCorrectly() { - composeTestRule.setContent { - MaterialTheme { - TooltipIconButton( - icon = { Box(modifier = Modifier.size(24.dp)) }, - tooltipText = "Custom colors", - isOutlined = true, - containerColor = Color.Black.copy(alpha = 0.6f), - contentColor = Color.White - ) - } - } - - composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).assertExists() - } - - @Test - fun tooltip_customSize_appliesCorrectly() { - composeTestRule.setContent { - MaterialTheme { - TooltipIconButton( - icon = { Box(modifier = Modifier.size(20.dp)) }, - tooltipText = "Custom size", - size = 32.dp - ) - } - } - composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).assertExists() + assertThat(actionClicked).isTrue() } @Test - fun positionProvider_anchoredToFarLeft_clampsToScreenMarginAndCalculatesCaret() { + fun positionProvider_anchoredToFarLeft_clampsToScreenMarginAndPointsCaretAt48dpAnchor() { var calculatedLocalCaretX = 0f var calculatedIsCaretOnTop = false val provider = JcaTooltipPositionProvider( positioning = TooltipAnchorPosition.Below, - caretAlignment = CaretAlignment.AnchorCenter, spacing = 4.dp, screenMargin = 16.dp, density = Density(1f), @@ -314,8 +145,8 @@ class TooltipTest { } ) - // Anchor placed near the left edge of the screen (e.g. status bar button) - val anchorBounds = IntRect(left = 16, top = 20, right = 48, bottom = 52) + // 48px touch-target anchor placed at the 16px left screen margin -> center X = 40 + val anchorBounds = IntRect(left = 16, top = 20, right = 64, bottom = 68) val windowSize = IntSize(width = 1080, height = 2400) val popupContentSize = IntSize(width = 400, height = 150) @@ -326,155 +157,90 @@ class TooltipTest { popupContentSize = popupContentSize ) - // The popup is clamped to screen margin (16px) because ideal X is offscreen + // Popup clamps to screen margin (16px) assertThat(position.x).isEqualTo(16) - // Positioned below anchor: bottom (52) + spacing (4) = 56 - assertThat(position.y).isEqualTo(56) + // Positioned below anchor: bottom (68) + spacing (4) = 72 + assertThat(position.y).isEqualTo(72) - // Local caret X is anchor center X (32) - popup X (16) = 16 - assertThat(calculatedLocalCaretX).isEqualTo(16f) + // Local caret X is anchor center X (40) - popup X (16) = 24 + assertThat(calculatedLocalCaretX).isEqualTo(24f) assertThat(calculatedIsCaretOnTop).isTrue() - // Global caret X points exactly to anchor center X + // Global caret X points directly at anchor center X (40) val expectedAnchorCenter = (anchorBounds.left + anchorBounds.right) / 2 assertThat(position.x + calculatedLocalCaretX.toInt()).isEqualTo(expectedAnchorCenter) } @Test - fun positionProvider_spaceConstrainedBelow_flipsAbove() { - var calculatedIsCaretOnTop = true + fun positionProvider_anchorInsideCornerArc_clampsCaretToMinCornerClearance() { + var calculatedLocalCaretX = 0f val provider = JcaTooltipPositionProvider( positioning = TooltipAnchorPosition.Below, spacing = 4.dp, screenMargin = 16.dp, + cornerRadius = 16.dp, + caretWidth = 16.dp, density = Density(1f), - onCaretCalculated = { _, isCaretOnTop -> - calculatedIsCaretOnTop = isCaretOnTop + onCaretCalculated = { localCaretX, _ -> + calculatedLocalCaretX = localCaretX } ) - // Anchor near bottom of window: spaceBelow is 48px, but tooltip height is 150px - val anchorBounds = IntRect(left = 200, top = 2300, right = 248, bottom = 2348) + // Narrow anchor near left edge: center X (32) - popup X (16) = 16, which is inside + // minCaretX = cornerRadius (16) + caretWidth / 2 (8) = 24 + val anchorBounds = IntRect(left = 16, top = 20, right = 48, bottom = 52) val windowSize = IntSize(width = 1080, height = 2400) val popupContentSize = IntSize(width = 400, height = 150) - val position = provider.calculatePosition( + provider.calculatePosition( anchorBounds = anchorBounds, windowSize = windowSize, layoutDirection = LayoutDirection.Ltr, popupContentSize = popupContentSize ) - // Flips above anchor: top (2300) - spacing (4) - popupHeight (150) = 2146 - assertThat(position.y).isEqualTo(2146) - // isCaretOnTop is false, meaning caret is drawn on bottom edge pointing DOWN to anchor - assertThat(calculatedIsCaretOnTop).isFalse() + assertThat(calculatedLocalCaretX).isEqualTo(24f) } @Test - fun positionProvider_supportsCaretAlignmentOptions() { - val anchorBounds = IntRect(left = 200, top = 100, right = 300, bottom = 200) - val windowSize = IntSize(width = 1080, height = 2400) - val popupContentSize = IntSize(width = 400, height = 150) + fun positionProvider_spaceConstrainedBelow_flipsAbove() { + var calculatedIsCaretOnTop = true - // BubbleCenter - var caretX = 0f - val bubbleCenterProvider = JcaTooltipPositionProvider( + val provider = JcaTooltipPositionProvider( positioning = TooltipAnchorPosition.Below, - caretAlignment = CaretAlignment.BubbleCenter, + spacing = 4.dp, + screenMargin = 16.dp, density = Density(1f), - onCaretCalculated = { x, _ -> caretX = x } - ) - bubbleCenterProvider.calculatePosition( - anchorBounds, - windowSize, - LayoutDirection.Ltr, - popupContentSize + onCaretCalculated = { _, isCaretOnTop -> + calculatedIsCaretOnTop = isCaretOnTop + } ) - assertThat(caretX).isEqualTo(200f) - // Start (LTR) - val startProvider = JcaTooltipPositionProvider( - positioning = TooltipAnchorPosition.Below, - caretAlignment = CaretAlignment.Start, - density = Density(1f), - onCaretCalculated = { x, _ -> caretX = x } - ) - startProvider.calculatePosition( - anchorBounds, - windowSize, - LayoutDirection.Ltr, - popupContentSize - ) - // cornerRadius (16) + caretWidth / 2 (8) = 24 - assertThat(caretX).isEqualTo(24f) + // Anchor near bottom of window: spaceBelow is 48px, but tooltip height is 150px + val anchorBounds = IntRect(left = 200, top = 2300, right = 248, bottom = 2348) + val windowSize = IntSize(width = 1080, height = 2400) + val popupContentSize = IntSize(width = 400, height = 150) - // End (LTR) - val endProvider = JcaTooltipPositionProvider( - positioning = TooltipAnchorPosition.Below, - caretAlignment = CaretAlignment.End, - density = Density(1f), - onCaretCalculated = { x, _ -> caretX = x } - ) - endProvider.calculatePosition( - anchorBounds, - windowSize, - LayoutDirection.Ltr, - popupContentSize + val position = provider.calculatePosition( + anchorBounds = anchorBounds, + windowSize = windowSize, + layoutDirection = LayoutDirection.Ltr, + popupContentSize = popupContentSize ) - // popupWidth (400) - cornerRadius (16) - caretWidth / 2 (8) = 376 - assertThat(caretX).isEqualTo(376f) - // Custom offset - val customProvider = JcaTooltipPositionProvider( - positioning = TooltipAnchorPosition.Below, - caretAlignment = CaretAlignment.Custom(75.dp), - density = Density(1f), - onCaretCalculated = { x, _ -> caretX = x } - ) - customProvider.calculatePosition( - anchorBounds, - windowSize, - LayoutDirection.Ltr, - popupContentSize - ) - assertThat(caretX).isEqualTo(75f) + // Flips above anchor: top (2300) - spacing (4) - popupHeight (150) = 2146 + assertThat(position.y).isEqualTo(2146) + // isCaretOnTop is false, meaning caret is drawn on bottom edge pointing down to anchor + assertThat(calculatedIsCaretOnTop).isFalse() } @Test - fun tooltip_touchTarget_meetsMinimumAccessibilitySize() { + fun tooltip_accessibility_hasTouchTargetButtonRoleSingleLabelAndPoliteLiveRegion() { composeTestRule.setContent { MaterialTheme { TooltipIconButton( icon = { Box(modifier = Modifier.size(JcaTooltipDefaults.IconSize)) }, - tooltipText = "Touch target test" - ) - } - } - - composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG) - .assertWidthIsAtLeast(JcaTooltipDefaults.TouchTargetSize) - .assertHeightIsAtLeast(JcaTooltipDefaults.TouchTargetSize) - } - - @Test - fun tooltipDefaults_mapsToMaterial3Tokens() { - assertThat(JcaTooltipDefaults.CaretSize.width).isEqualTo(16.dp) - assertThat(JcaTooltipDefaults.CaretSize.height).isEqualTo(8.dp) - assertThat(JcaTooltipDefaults.TouchTargetSize).isEqualTo(48.dp) - assertThat(JcaTooltipDefaults.ContainerSize).isEqualTo(32.dp) - assertThat(JcaTooltipDefaults.IconSize).isEqualTo(24.dp) - assertThat(JcaTooltipDefaults.CornerRadius).isEqualTo(16.dp) - assertThat(JcaTooltipDefaults.DefaultElevation).isEqualTo(2.dp) - } - - @Test - fun tooltip_accessibility_hasButtonRoleAndContentDescription() { - composeTestRule.setContent { - MaterialTheme { - TooltipIconButton( - icon = { Box(modifier = Modifier.size(24.dp)) }, contentDescription = "Custom info action", tooltipText = "Accessibility description test" ) @@ -482,6 +248,8 @@ class TooltipTest { } composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG) + .assertWidthIsAtLeast(JcaTooltipDefaults.TouchTargetSize) + .assertHeightIsAtLeast(JcaTooltipDefaults.TouchTargetSize) .assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Button)) .assert( SemanticsMatcher.expectValue( @@ -489,9 +257,14 @@ class TooltipTest { listOf("Custom info action") ) ) + .assert( + SemanticsMatcher("onClickLabel is null to prevent duplicate TalkBack speech") { + it.config.getOrNull(SemanticsActions.OnClick)?.label == null + } + ) - // Show tooltip and verify LiveRegionMode.Polite semantics on bubble content - composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + // Show tooltip and verify LiveRegionMode.Polite semantics on RichTooltip + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } composeTestRule.waitForIdle() composeTestRule.onNodeWithTag(TOOLTIP_CONTENT_TAG) From d966cc29427178695857d0b131afbdcc20affc20 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 10 Nov 2026 07:45:52 -0800 Subject: [PATCH 17/20] Address PR review feedback for TooltipIconButton and JcaTooltipCaret - Add @Stable JcaTooltipCaret and rememberJcaTooltipCaret(positioning) encapsulating CaretPositionState privately and keying state on positioning. - Defer horizontal caret X evaluation via localCaretXProvider in JcaTooltipBubbleShape.createOutline so Frame 0 renders at the exact anchor offset without an extra recomposition. - Require explicit contentDescription on the TooltipScope.() -> Unit TooltipIconButton overload and use contentColor for the outlined button border. - Guard onDismissRequest invocations with !state.transition.targetState so tapping the anchor while open fires onDismissRequest exactly once. - Remove unused unit test dependencies from :ui:components and expand unit/instrumented test coverage. --- ui/components/build.gradle.kts | 2 - .../ui/components/TooltipInstrumentedTest.kt | 12 +- .../jetpackcamera/ui/components/Tooltip.kt | 183 +++++++++++++----- .../ui/components/TooltipTest.kt | 169 +++++++++++++++- 4 files changed, 307 insertions(+), 59 deletions(-) diff --git a/ui/components/build.gradle.kts b/ui/components/build.gradle.kts index 7c609d5ed7..0af42121df 100644 --- a/ui/components/build.gradle.kts +++ b/ui/components/build.gradle.kts @@ -87,9 +87,7 @@ dependencies { testImplementation(libs.junit) testImplementation(libs.truth) androidTestImplementation(libs.truth) - testImplementation(libs.kotlinx.coroutines.test) testImplementation(libs.robolectric) - testImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) } diff --git a/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt index 0dbdd157dd..99d6112f2a 100644 --- a/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt +++ b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt @@ -32,10 +32,11 @@ import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasText import androidx.compose.ui.test.isPopup -import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry +import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -50,6 +51,7 @@ class TooltipInstrumentedTest { @Test fun tooltipIconButton_realWindowTapOnAnchor_opensAndClosesTooltip() { var anchorCenterOnScreen = Offset.Zero + var dismissCount = 0 composeTestRule.setContent { MaterialTheme { @@ -63,7 +65,8 @@ class TooltipInstrumentedTest { ) }, icon = { Box(modifier = Modifier.size(24.dp)) }, - tooltipText = "Real tap toggle message" + tooltipText = "Real tap toggle message", + onDismissRequest = { dismissCount++ } ) } } @@ -76,12 +79,15 @@ class TooltipInstrumentedTest { composeTestRule.waitForIdle() composeTestRule.onNode(hasText("Real tap toggle message") and hasAnyAncestor(isPopup())) .assertIsDisplayed() + assertThat(dismissCount).isEqualTo(0) // Second real window-level tap on the anchor triggers Popup outside-touch dismissal on - // pointer-down and must leave the tooltip closed rather than reopening it on pointer-up + // pointer-down and must leave the tooltip closed rather than reopening it on pointer-up, + // while invoking onDismissRequest exactly once. sendRealScreenTap(anchorCenterOnScreen) composeTestRule.waitForIdle() composeTestRule.onNode(isPopup()).assertDoesNotExist() + assertThat(dismissCount).isEqualTo(1) } private fun sendRealScreenTap(screenPoint: Offset) { diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 0075d763d3..8aeade771a 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -24,6 +24,7 @@ import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.waitForUpOrCancellation import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -87,7 +88,10 @@ import androidx.compose.ui.window.PopupPositionProvider import kotlin.math.roundToInt import kotlinx.coroutines.launch +/** Test tag applied to the interactive anchor button inside [TooltipIconButton]. */ const val TOOLTIP_ANCHOR_BUTTON_TAG = "tooltip_anchor_button" + +/** Test tag applied to the default [RichTooltip] surface rendered by [TooltipIconButton]. */ const val TOOLTIP_CONTENT_TAG = "tooltip_content" /* @@ -119,7 +123,11 @@ private object TooltipTokens { object JcaTooltipDefaults { /** Default caret dimensions matching Material 3 [TooltipDefaults.caretSize] (16dp x 8dp). */ val CaretSize: DpSize = TooltipDefaults.caretSize + + /** Default base width of the tooltip caret (16dp). */ val CaretWidth: Dp get() = CaretSize.width + + /** Default height of the tooltip caret extending from the bubble body (8dp). */ val CaretHeight: Dp get() = CaretSize.height /** Default spacing between the tooltip bubble and calling anchor. */ @@ -147,11 +155,8 @@ object JcaTooltipDefaults { val MaxWidth: Dp = 296.dp } -/** - * State holder for dynamic caret coordinates computed synchronously during popup placement. - */ @Stable -class CaretPositionState( +private class CaretPositionState( initialCaretX: Float = 0f, initialIsCaretOnTop: Boolean = true ) { @@ -159,12 +164,100 @@ class CaretPositionState( var isCaretOnTop: Boolean by mutableStateOf(initialIsCaretOnTop) } +/** + * Coordinates edge-aware tooltip placement, caret padding, and bubble shape rendering for a + * [TooltipIconButton] or [TooltipBox]. + * + * Create an instance via [rememberJcaTooltipCaret], pass [positionProvider] to [TooltipIconButton] + * (or [TooltipBox]), apply [caretPadding] to the tooltip content so it clears the caret triangle, + * and pass [bubbleShape] to [RichTooltip]'s `shape` parameter with `caretShape = null`. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Stable +class JcaTooltipCaret internal constructor( + positioning: TooltipAnchorPosition, + density: Density, + private val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, + private val caretHeight: Dp = JcaTooltipDefaults.CaretHeight +) { + private val caretPositionState = CaretPositionState( + initialIsCaretOnTop = positioning == TooltipAnchorPosition.Below + ) + private val localCaretXProvider: () -> Float = { caretPositionState.localCaretX } + private val topCaretPadding = PaddingValues(top = caretHeight) + private val bottomCaretPadding = PaddingValues(bottom = caretHeight) + + /** + * [PopupPositionProvider] that clamps popup placement within safe screen margins and updates + * the caret coordinates during layout before the first draw frame. + */ + val positionProvider: PopupPositionProvider = JcaTooltipPositionProvider( + positioning = positioning, + caretWidth = caretWidth, + density = density, + onCaretCalculated = { localCaretX, isCaretOnTop -> + caretPositionState.localCaretX = localCaretX + caretPositionState.isCaretOnTop = isCaretOnTop + } + ) + + /** + * Padding that reserves [caretHeight] on the edge of the bubble where the caret is drawn + * (top when positioned below the anchor, bottom when positioned above). + */ + val caretPadding: PaddingValues + get() = if (caretPositionState.isCaretOnTop) topCaretPadding else bottomCaretPadding + + /** + * Returns a [Shape] combining a rounded rectangle of [cornerRadius] with a caret pointing + * toward the anchor. The horizontal caret offset is read during [Shape.createOutline] in the + * draw phase so Frame 0 renders at the exact anchor X without an extra recomposition. + */ + fun bubbleShape(cornerRadius: Dp = JcaTooltipDefaults.CornerRadius): Shape = + JcaTooltipBubbleShape( + localCaretXProvider = localCaretXProvider, + isCaretOnTop = caretPositionState.isCaretOnTop, + cornerRadius = cornerRadius, + caretWidth = caretWidth, + caretHeight = caretHeight + ) +} + +/** + * Remembers a [JcaTooltipCaret] keyed on [positioning] for pairing edge-clamped popup placement + * with [JcaTooltipCaret.bubbleShape] and [JcaTooltipCaret.caretPadding]. + * + * @param positioning preferred anchor placement ([TooltipAnchorPosition.Below] or + * [TooltipAnchorPosition.Above]); flips automatically when vertical window space is constrained. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun rememberJcaTooltipCaret( + positioning: TooltipAnchorPosition = TooltipAnchorPosition.Below +): JcaTooltipCaret { + val density = LocalDensity.current + return remember(positioning, density) { + JcaTooltipCaret( + positioning = positioning, + density = density + ) + } +} + /** * Shape that unions a rounded rectangle bubble body with a triangular caret pointing toward the * anchor. + * + * @param localCaretXProvider deferred provider for the caret center X in local popup coordinates, + * evaluated inside [createOutline] during the draw phase after popup placement has run. + * @param isCaretOnTop `true` when the caret is along the top edge pointing up at the anchor, or + * `false` when along the bottom edge pointing down. + * @param cornerRadius corner radius of the rounded rectangle bubble body. + * @param caretWidth base width of the triangular caret. + * @param caretHeight height of the triangular caret extending from the bubble body. */ class JcaTooltipBubbleShape( - val localCaretX: Float, + val localCaretXProvider: () -> Float, val isCaretOnTop: Boolean, val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, @@ -192,7 +285,7 @@ class JcaTooltipBubbleShape( // Clamp caret base so the triangle never bleeds into the corner radius arcs val minCaretX = actualRadius + cw / 2f val maxCaretX = (w - actualRadius - cw / 2f).coerceAtLeast(minCaretX) - val clampedCaretX = localCaretX.coerceIn(minCaretX, maxCaretX) + val clampedCaretX = localCaretXProvider().coerceIn(minCaretX, maxCaretX) val bodyOutline = RoundedCornerShape(cornerRadius).createOutline( size = Size(w, bodyHeight), @@ -226,7 +319,7 @@ class JcaTooltipBubbleShape( override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is JcaTooltipBubbleShape) return false - return localCaretX == other.localCaretX && + return localCaretXProvider == other.localCaretXProvider && isCaretOnTop == other.isCaretOnTop && cornerRadius == other.cornerRadius && caretWidth == other.caretWidth && @@ -234,7 +327,7 @@ class JcaTooltipBubbleShape( } override fun hashCode(): Int { - var result = localCaretX.hashCode() + var result = localCaretXProvider.hashCode() result = 31 * result + isCaretOnTop.hashCode() result = 31 * result + cornerRadius.hashCode() result = 31 * result + caretWidth.hashCode() @@ -245,7 +338,8 @@ class JcaTooltipBubbleShape( /** * Position provider for the tooltip popup that clamps popup coordinates to safe screen margins and - * derives the corner-clamped local caret offset relative to the popup's top-left corner before draw. + * derives the corner-clamped local caret offset relative to the popup's top-left corner before + * draw. */ @OptIn(ExperimentalMaterial3Api::class) class JcaTooltipPositionProvider( @@ -317,8 +411,7 @@ class JcaTooltipPositionProvider( * An icon button that toggles a styled [RichTooltip] when tapped. * * Uses Material 3's [TooltipBox] and [RichTooltip] for animations, focus, shadow, and state - * management, paired with [JcaTooltipPositionProvider] and [JcaTooltipBubbleShape] for edge-aware - * caret placement. + * management, paired with [rememberJcaTooltipCaret] for edge-aware caret placement. */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -338,29 +431,14 @@ fun TooltipIconButton( onClick: () -> Unit = {}, onDismissRequest: (() -> Unit)? = null ) { - val density = LocalDensity.current - val caretPositionState = remember { - CaretPositionState( - initialIsCaretOnTop = positioning == TooltipAnchorPosition.Below - ) - } - val positionProvider = remember(positioning, density) { - JcaTooltipPositionProvider( - positioning = positioning, - density = density, - onCaretCalculated = { localCaretX, isCaretOnTop -> - caretPositionState.localCaretX = localCaretX - caretPositionState.isCaretOnTop = isCaretOnTop - } - ) - } + val caret = rememberJcaTooltipCaret(positioning) TooltipIconButton( icon = icon, - modifier = modifier, contentDescription = contentDescription ?: tooltipTitle ?: tooltipText, + modifier = modifier, state = state, - positionProvider = positionProvider, + positionProvider = caret.positionProvider, isOutlined = isOutlined, containerColor = containerColor, contentColor = contentColor, @@ -369,15 +447,9 @@ fun TooltipIconButton( onClick = onClick, onDismissRequest = onDismissRequest, tooltip = { - val isCaretOnTop = caretPositionState.isCaretOnTop - val bubbleShape = remember(caretPositionState.localCaretX, isCaretOnTop) { - JcaTooltipBubbleShape( - localCaretX = caretPositionState.localCaretX, - isCaretOnTop = isCaretOnTop - ) - } - val caretTopPadding = if (isCaretOnTop) JcaTooltipDefaults.CaretHeight else 0.dp - val caretBottomPadding = if (!isCaretOnTop) JcaTooltipDefaults.CaretHeight else 0.dp + val caretPadding = caret.caretPadding + val caretTopPadding = caretPadding.calculateTopPadding() + val caretBottomPadding = caretPadding.calculateBottomPadding() RichTooltip( modifier = Modifier @@ -399,7 +471,7 @@ fun TooltipIconButton( }, caretShape = null, maxWidth = JcaTooltipDefaults.MaxWidth, - shape = bubbleShape, + shape = caret.bubbleShape(), colors = TooltipDefaults.richTooltipColors( containerColor = MaterialTheme.colorScheme.secondaryFixed, contentColor = MaterialTheme.colorScheme.onSecondaryFixed, @@ -436,18 +508,23 @@ fun TooltipIconButton( * An icon button that toggles custom tooltip content scoped to [TooltipScope] when tapped. * * Allows callers to supply custom [RichTooltip] content (such as actions or styled text) while - * sharing the camera overlay button styling and pointer-down toggle handling. + * sharing camera overlay button styling and pointer-down toggle handling. + * + * Callers must explicitly pass an accessible [contentDescription] for the anchor button (or `null` + * only if the button's description is supplied elsewhere). To render an edge-clamped bubble with a + * caret pointing at the anchor, hoist `val caret = rememberJcaTooltipCaret(positioning)`, pass + * `positionProvider = caret.positionProvider`, configure `RichTooltip(shape = caret.bubbleShape(), + * caretShape = null)`, and apply `Modifier.padding(caret.caretPadding)` to the inner content. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun TooltipIconButton( icon: @Composable () -> Unit, tooltip: @Composable TooltipScope.() -> Unit, + contentDescription: String?, modifier: Modifier = Modifier, - contentDescription: String? = null, state: TooltipState = rememberTooltipState(isPersistent = true), - positionProvider: PopupPositionProvider = - TooltipDefaults.rememberTooltipPositionProvider(TooltipAnchorPosition.Below), + positionProvider: PopupPositionProvider = rememberJcaTooltipCaret().positionProvider, hasAction: Boolean = false, isOutlined: Boolean = false, containerColor: Color = Color.Transparent, @@ -462,17 +539,20 @@ fun TooltipIconButton( val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) var wasVisibleAtDown by remember { mutableStateOf(false) } + val dismissTooltip = { + val wasAlreadyDismissing = !state.transition.targetState + state.dismiss() + if (!wasAlreadyDismissing) { + currentOnDismissRequest?.invoke() + } + } + TooltipBox( positionProvider = positionProvider, tooltip = tooltip, state = state, modifier = modifier, - onDismissRequest = onDismissRequest?.let { - { - state.dismiss() - currentOnDismissRequest?.invoke() - } - }, + onDismissRequest = onDismissRequest?.let { dismissTooltip }, enableUserInput = false, hasAction = hasAction ) { @@ -502,8 +582,7 @@ fun TooltipIconButton( val wasVisible = wasVisibleAtDown || state.isVisible wasVisibleAtDown = false if (wasVisible) { - state.dismiss() - currentOnDismissRequest?.invoke() + dismissTooltip() } else { scope.launch { state.show() } } @@ -527,7 +606,7 @@ fun TooltipIconButton( Modifier.border( border = BorderStroke( TooltipTokens.BorderWidth, - Color.White.copy(alpha = TooltipTokens.BORDER_ALPHA) + contentColor.copy(alpha = TooltipTokens.BORDER_ALPHA) ), shape = CircleShape ) diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index 0e9f45ef71..7e4293bb73 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -16,6 +16,8 @@ package com.google.jetpackcamera.ui.components import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme @@ -23,9 +25,17 @@ import androidx.compose.material3.RichTooltip import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TooltipAnchorPosition +import androidx.compose.material3.TooltipState +import androidx.compose.material3.rememberTooltipState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathOperation import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.SemanticsActions @@ -42,6 +52,7 @@ import androidx.compose.ui.test.hasText import androidx.compose.ui.test.isPopup import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntRect @@ -129,6 +140,117 @@ class TooltipTest { assertThat(actionClicked).isTrue() } + @Test + fun rememberJcaTooltipCaret_providesCaretPaddingAndBubbleShape_andKeysOnPositioning() { + var positioning by mutableStateOf(TooltipAnchorPosition.Below) + var observedPadding: PaddingValues? = null + + composeTestRule.setContent { + MaterialTheme { + val caret = rememberJcaTooltipCaret(positioning) + observedPadding = caret.caretPadding + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + contentDescription = "Caret slot button", + positionProvider = caret.positionProvider, + tooltip = { + RichTooltip( + caretShape = null, + shape = caret.bubbleShape() + ) { + Text( + text = "Custom caret body", + modifier = Modifier.padding(caret.caretPadding) + ) + } + } + ) + } + } + composeTestRule.waitForIdle() + + assertThat(observedPadding?.calculateTopPadding()).isEqualTo(JcaTooltipDefaults.CaretHeight) + assertThat(observedPadding?.calculateBottomPadding()).isEqualTo(0.dp) + + // Changing positioning re-keys rememberJcaTooltipCaret and flips initial caret padding edge + composeTestRule.runOnIdle { + positioning = TooltipAnchorPosition.Above + } + composeTestRule.waitForIdle() + + assertThat(observedPadding?.calculateTopPadding()).isEqualTo(0.dp) + assertThat(observedPadding?.calculateBottomPadding()) + .isEqualTo(JcaTooltipDefaults.CaretHeight) + + // Opening the custom slot tooltip renders the bubble shape and body cleanly + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } + composeTestRule.waitForIdle() + + composeTestRule.onNode(hasText("Custom caret body") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + } + + @Test + fun tooltip_onDismissRequest_invokedExactlyOnceWhenClosingAnchor() { + var dismissCount = 0 + lateinit var tooltipState: TooltipState + + composeTestRule.setContent { + MaterialTheme { + tooltipState = rememberTooltipState(isPersistent = true) + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + tooltipText = "Dismiss count test", + state = tooltipState, + onDismissRequest = { dismissCount++ } + ) + } + } + + // 1. Open and close via touch tap on anchor + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } + composeTestRule.waitForIdle() + assertThat(dismissCount).isEqualTo(0) + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } + composeTestRule.waitForIdle() + assertThat(dismissCount).isEqualTo(1) + composeTestRule.onNode(isPopup()).assertDoesNotExist() + + // 2. Open and close via semantics performClick() + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + composeTestRule.waitForIdle() + assertThat(dismissCount).isEqualTo(1) + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performClick() + composeTestRule.waitForIdle() + assertThat(dismissCount).isEqualTo(2) + composeTestRule.onNode(isPopup()).assertDoesNotExist() + + // 3. Simulate real-window touch sequence where Popup outside-touch dismisses on ACTION_DOWN + // (setting transition.targetState = false) before clickable runs on ACTION_UP: + // clickable must NOT invoke onDismissRequest a second time. + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } + composeTestRule.waitForIdle() + assertThat(dismissCount).isEqualTo(2) + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { + down(center) + } + composeTestRule.runOnIdle { + // Simulate TooltipBox.onDismissRequest having already fired on ACTION_DOWN + tooltipState.dismiss() + dismissCount++ + } + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { + up() + } + composeTestRule.waitForIdle() + + assertThat(dismissCount).isEqualTo(3) + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + @Test fun positionProvider_anchoredToFarLeft_clampsToScreenMarginAndPointsCaretAt48dpAnchor() { var calculatedLocalCaretX = 0f @@ -283,7 +405,7 @@ class TooltipTest { // Shape with extreme negative caret X val shapeNegative = JcaTooltipBubbleShape( - localCaretX = -100f, + localCaretXProvider = { -100f }, isCaretOnTop = true ) val outlineNegative = shapeNegative.createOutline(size, LayoutDirection.Ltr, density) @@ -293,7 +415,7 @@ class TooltipTest { // Shape with extreme positive caret X val shapeOverflow = JcaTooltipBubbleShape( - localCaretX = 1000f, + localCaretXProvider = { 1000f }, isCaretOnTop = false ) val outlineOverflow = shapeOverflow.createOutline(size, LayoutDirection.Ltr, density) @@ -301,4 +423,47 @@ class TooltipTest { assertThat(outlineOverflow.bounds.width).isEqualTo(400f) assertThat(outlineOverflow.bounds.height).isEqualTo(150f) } + + @Test + fun bubbleShape_defersCaretXProviderReadUntilCreateOutline() { + var providerReads = 0 + var dynamicCaretX = 60f + val shape = JcaTooltipBubbleShape( + localCaretXProvider = { + providerReads++ + dynamicCaretX + }, + isCaretOnTop = true + ) + + // Constructing the shape during composition must not evaluate localCaretXProvider + assertThat(providerReads).isEqualTo(0) + + val density = Density(1f) + val size = Size(200f, 100f) + val outlineAt60 = + shape.createOutline(size, LayoutDirection.Ltr, density) as Outline.Generic + assertThat(providerReads).isEqualTo(1) + + // Updating dynamicCaretX during layout before draw produces a shifted caret outline + // from the same JcaTooltipBubbleShape instance without recomposing + dynamicCaretX = 140f + val outlineAt140 = + shape.createOutline(size, LayoutDirection.Ltr, density) as Outline.Generic + assertThat(providerReads).isEqualTo(2) + + val xorDiff = Path().apply { + op(outlineAt60.path, outlineAt140.path, PathOperation.Xor) + } + assertThat(xorDiff.isEmpty).isFalse() + + // Verify the tip at y = 0 moved from x = 60 to x = 140 + val probeAt140Tip = Path().apply { + addRect(androidx.compose.ui.geometry.Rect(Offset(139f, 1f), Size(2f, 2f))) + } + val intersectAt140 = Path().apply { + op(outlineAt140.path, probeAt140Tip, PathOperation.Intersect) + } + assertThat(intersectAt140.isEmpty).isFalse() + } } From 4559d9aa677fc4e58fb9de4c3a8e6b2edad76ecf Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Tue, 10 Nov 2026 08:38:07 -0800 Subject: [PATCH 18/20] Apply styleguide polish to Tooltip components and tests - Restrict JcaTooltipBubbleShape and JcaTooltipPositionProvider to internal classes with private constructor properties. - Add behavioral descriptions and @param KDocs to both TooltipIconButton overloads and JcaTooltipPositionProvider. - Update TOOLTIP_ANCHOR_BUTTON_TAG string value to btn_tooltip_anchor per the element_purpose_value test tag schema. - Extract shared clampCaretX helper accounting for bodyHeight / 2f consistently and simplify TooltipBox onDismissRequest wiring. - Import Rect directly in TooltipTest and add class-level KDocs to TooltipTest and TooltipInstrumentedTest. --- .../ui/components/TooltipInstrumentedTest.kt | 4 + .../jetpackcamera/ui/components/Tooltip.kt | 164 +++++++++++++----- .../ui/components/TooltipTest.kt | 18 +- 3 files changed, 146 insertions(+), 40 deletions(-) diff --git a/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt index 99d6112f2a..beb62923eb 100644 --- a/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt +++ b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt @@ -41,6 +41,10 @@ import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith +/** + * Instrumented window-input tests verifying that real screen-level taps on [TooltipIconButton] + * cleanly toggle and dismiss the popup without outside-touch reopen races. + */ @OptIn(ExperimentalMaterial3Api::class) @RunWith(AndroidJUnit4::class) class TooltipInstrumentedTest { diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 8aeade771a..9c55779b4b 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -89,7 +89,7 @@ import kotlin.math.roundToInt import kotlinx.coroutines.launch /** Test tag applied to the interactive anchor button inside [TooltipIconButton]. */ -const val TOOLTIP_ANCHOR_BUTTON_TAG = "tooltip_anchor_button" +const val TOOLTIP_ANCHOR_BUTTON_TAG = "btn_tooltip_anchor" /** Test tag applied to the default [RichTooltip] surface rendered by [TooltipIconButton]. */ const val TOOLTIP_CONTENT_TAG = "tooltip_content" @@ -194,6 +194,7 @@ class JcaTooltipCaret internal constructor( val positionProvider: PopupPositionProvider = JcaTooltipPositionProvider( positioning = positioning, caretWidth = caretWidth, + caretHeight = caretHeight, density = density, onCaretCalculated = { localCaretX, isCaretOnTop -> caretPositionState.localCaretX = localCaretX @@ -244,6 +245,19 @@ fun rememberJcaTooltipCaret( } } +private fun clampCaretX( + caretX: Float, + width: Float, + bodyHeight: Float, + cornerRadiusPx: Float, + caretWidthPx: Float +): Float { + val actualRadius = minOf(cornerRadiusPx, bodyHeight / 2f, width / 2f).coerceAtLeast(0f) + val minCaretX = actualRadius + caretWidthPx / 2f + val maxCaretX = (width - actualRadius - caretWidthPx / 2f).coerceAtLeast(minCaretX) + return caretX.coerceIn(minCaretX, maxCaretX) +} + /** * Shape that unions a rounded rectangle bubble body with a triangular caret pointing toward the * anchor. @@ -256,12 +270,12 @@ fun rememberJcaTooltipCaret( * @param caretWidth base width of the triangular caret. * @param caretHeight height of the triangular caret extending from the bubble body. */ -class JcaTooltipBubbleShape( - val localCaretXProvider: () -> Float, - val isCaretOnTop: Boolean, - val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, - val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, - val caretHeight: Dp = JcaTooltipDefaults.CaretHeight +internal class JcaTooltipBubbleShape( + private val localCaretXProvider: () -> Float, + private val isCaretOnTop: Boolean, + private val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, + private val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, + private val caretHeight: Dp = JcaTooltipDefaults.CaretHeight ) : Shape { override fun createOutline( size: Size, @@ -280,12 +294,14 @@ class JcaTooltipBubbleShape( val bodyHeight = (h - ch).coerceAtLeast(0f) val bodyTop = if (isCaretOnTop) ch else 0f - val actualRadius = minOf(r, bodyHeight / 2f, w / 2f).coerceAtLeast(0f) - // Clamp caret base so the triangle never bleeds into the corner radius arcs - val minCaretX = actualRadius + cw / 2f - val maxCaretX = (w - actualRadius - cw / 2f).coerceAtLeast(minCaretX) - val clampedCaretX = localCaretXProvider().coerceIn(minCaretX, maxCaretX) + val clampedCaretX = clampCaretX( + caretX = localCaretXProvider(), + width = w, + bodyHeight = bodyHeight, + cornerRadiusPx = r, + caretWidthPx = cw + ) val bodyOutline = RoundedCornerShape(cornerRadius).createOutline( size = Size(w, bodyHeight), @@ -340,16 +356,28 @@ class JcaTooltipBubbleShape( * Position provider for the tooltip popup that clamps popup coordinates to safe screen margins and * derives the corner-clamped local caret offset relative to the popup's top-left corner before * draw. + * + * @param positioning preferred placement relative to the anchor ([TooltipAnchorPosition.Below] or + * [TooltipAnchorPosition.Above]), flipping automatically when window space is constrained. + * @param spacing vertical gap between the anchor bounds and the tooltip popup. + * @param screenMargin minimum horizontal and vertical distance from window edges. + * @param cornerRadius bubble corner radius used to keep the caret base clear of corner arcs. + * @param caretWidth base width of the caret triangle. + * @param caretHeight height of the caret triangle subtracted from popup height for corner clamping. + * @param density screen density used to convert Dp dimensions to pixels. + * @param onCaretCalculated callback invoked during layout with the clamped local caret center X and + * whether the caret sits on the top edge (`true` when placed below the anchor). */ @OptIn(ExperimentalMaterial3Api::class) -class JcaTooltipPositionProvider( - val positioning: TooltipAnchorPosition, - val spacing: Dp = JcaTooltipDefaults.SpacingBetweenTooltipAndAnchor, - val screenMargin: Dp = JcaTooltipDefaults.ScreenMargin, - val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, - val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, - val density: Density, - val onCaretCalculated: (localCaretX: Float, isCaretOnTop: Boolean) -> Unit = { _, _ -> } +internal class JcaTooltipPositionProvider( + private val positioning: TooltipAnchorPosition, + private val spacing: Dp = JcaTooltipDefaults.SpacingBetweenTooltipAndAnchor, + private val screenMargin: Dp = JcaTooltipDefaults.ScreenMargin, + private val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, + private val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, + private val caretHeight: Dp = JcaTooltipDefaults.CaretHeight, + private val density: Density, + private val onCaretCalculated: (localCaretX: Float, isCaretOnTop: Boolean) -> Unit = { _, _ -> } ) : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, @@ -393,13 +421,15 @@ class JcaTooltipPositionProvider( // Clamp local caret X so the caret base stays outside the rounded corners and matches // what JcaTooltipBubbleShape draws - val cornerRadiusPx = with(density) { cornerRadius.toPx() } - val caretWidthPx = with(density) { caretWidth.toPx() } - val actualRadius = minOf(cornerRadiusPx, popupContentSize.width / 2f).coerceAtLeast(0f) - val minCaretX = actualRadius + caretWidthPx / 2f - val maxCaretX = - (popupContentSize.width - actualRadius - caretWidthPx / 2f).coerceAtLeast(minCaretX) - val localCaretX = (anchorCenterX - popupX).coerceIn(minCaretX, maxCaretX) + val bodyHeight = + (popupContentSize.height - with(density) { caretHeight.toPx() }).coerceAtLeast(0f) + val localCaretX = clampCaretX( + caretX = anchorCenterX - popupX, + width = popupContentSize.width.toFloat(), + bodyHeight = bodyHeight, + cornerRadiusPx = with(density) { cornerRadius.toPx() }, + caretWidthPx = with(density) { caretWidth.toPx() } + ) onCaretCalculated(localCaretX, placeBelow) @@ -408,10 +438,38 @@ class JcaTooltipPositionProvider( } /** - * An icon button that toggles a styled [RichTooltip] when tapped. + * Circular camera-overlay icon button that toggles a styled [RichTooltip] when tapped. * - * Uses Material 3's [TooltipBox] and [RichTooltip] for animations, focus, shadow, and state - * management, paired with [rememberJcaTooltipCaret] for edge-aware caret placement. + * Uses Material 3's [TooltipBox] and [RichTooltip] with `secondaryFixed` / `onSecondaryFixed` theme + * colors, polite live-region announcements, and edge-clamped caret placement via + * [rememberJcaTooltipCaret]. Renders a circular [size] container centered inside a + * [minTouchTargetSize] touch target; when [isOutlined] is `true`, draws a `1.dp` circular border at + * 20% [contentColor] alpha. [onClick] fires on every tap, whereas [onDismissRequest] fires once + * each time an open tooltip is dismissed. + * + * @param icon icon composable centered inside the button container with [LocalContentColor] set to + * [contentColor]. + * @param tooltipText body copy displayed inside the tooltip; receives extra vertical padding when + * [tooltipTitle] is `null`. + * @param modifier [Modifier] applied to the outer [TooltipBox] wrapper. + * @param contentDescription accessibility label for the anchor button; falls back to + * `tooltipTitle ?: tooltipText` when `null`. + * @param tooltipTitle optional centered header displayed above [tooltipText] and preferred for the + * popup's accessibility `paneTitle`. + * @param state controls tooltip visibility; defaults to a persistent [TooltipState] so the bubble + * remains open until tapped again or dismissed externally. + * @param positioning preferred placement relative to the anchor ([TooltipAnchorPosition.Below] or + * [TooltipAnchorPosition.Above]), flipping automatically when vertical window space is tight. + * @param isOutlined when `true`, draws a `1.dp` circular border around the [size] container using + * [contentColor] at 20% alpha. + * @param containerColor background fill of the circular [size] button container. + * @param contentColor tint provided via [LocalContentColor] to [icon] and used at 20% alpha for the + * [isOutlined] border. + * @param size diameter of the visible circular button container inside the touch target. + * @param minTouchTargetSize minimum interactive bounds and unbounded ripple diameter of the anchor. + * @param onClick callback invoked on every anchor tap after toggling tooltip visibility. + * @param onDismissRequest optional callback invoked once when an open tooltip is dismissed (via + * anchor re-tap or outside touch). */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -505,16 +563,44 @@ fun TooltipIconButton( } /** - * An icon button that toggles custom tooltip content scoped to [TooltipScope] when tapped. + * Circular camera-overlay icon button that toggles custom tooltip content scoped to [TooltipScope] + * when tapped. + * + * Shares the circular [size] container, [minTouchTargetSize] touch target, `1.dp` border at 20% + * [contentColor] alpha when [isOutlined] is `true`, and pointer-down toggle tracking that prevents + * an outside-touch dismissal from immediately reopening the popup on pointer-up. [onClick] fires on + * every tap, whereas [onDismissRequest] fires once each time an open tooltip is dismissed. * - * Allows callers to supply custom [RichTooltip] content (such as actions or styled text) while - * sharing camera overlay button styling and pointer-down toggle handling. + * To render an edge-clamped bubble with a caret pointing at the anchor, hoist + * `val caret = rememberJcaTooltipCaret(positioning)`, pass + * `positionProvider = caret.positionProvider`, configure + * `RichTooltip(shape = caret.bubbleShape(), caretShape = null)`, and apply + * `Modifier.padding(caret.caretPadding)` to the inner content. * - * Callers must explicitly pass an accessible [contentDescription] for the anchor button (or `null` - * only if the button's description is supplied elsewhere). To render an edge-clamped bubble with a - * caret pointing at the anchor, hoist `val caret = rememberJcaTooltipCaret(positioning)`, pass - * `positionProvider = caret.positionProvider`, configure `RichTooltip(shape = caret.bubbleShape(), - * caretShape = null)`, and apply `Modifier.padding(caret.caretPadding)` to the inner content. + * @param icon icon composable centered inside the button container with [LocalContentColor] set to + * [contentColor]. + * @param tooltip custom popup content scoped to [TooltipScope] (such as a [RichTooltip] with action + * buttons or styled text). + * @param contentDescription explicit accessibility label for the anchor button; unlike the `String` + * overload, no automatic fallback is available, so pass `null` only when semantics are supplied + * externally. + * @param modifier [Modifier] applied to the outer [TooltipBox] wrapper. + * @param state controls tooltip visibility; defaults to a persistent [TooltipState] so the popup + * remains open until tapped again or dismissed externally. + * @param positionProvider computes popup coordinates relative to the anchor; defaults to + * `rememberJcaTooltipCaret().positionProvider`. + * @param hasAction pass `true` when [tooltip] contains interactive controls so [TooltipBox] adjusts + * accessibility focus and dismissal handling accordingly. + * @param isOutlined when `true`, draws a `1.dp` circular border around the [size] container using + * [contentColor] at 20% alpha. + * @param containerColor background fill of the circular [size] button container. + * @param contentColor tint provided via [LocalContentColor] to [icon] and used at 20% alpha for the + * [isOutlined] border. + * @param size diameter of the visible circular button container inside the touch target. + * @param minTouchTargetSize minimum interactive bounds and unbounded ripple diameter of the anchor. + * @param onClick callback invoked on every anchor tap after toggling tooltip visibility. + * @param onDismissRequest optional callback invoked once when an open tooltip is dismissed (via + * anchor re-tap or outside touch). */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -552,7 +638,7 @@ fun TooltipIconButton( tooltip = tooltip, state = state, modifier = modifier, - onDismissRequest = onDismissRequest?.let { dismissTooltip }, + onDismissRequest = dismissTooltip, enableUserInput = false, hasAction = hasAction ) { diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index 7e4293bb73..0b6ba4db88 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -32,6 +32,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path @@ -65,6 +66,10 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner +/** + * Robolectric unit tests for [TooltipIconButton], [rememberJcaTooltipCaret], + * [JcaTooltipPositionProvider], and [JcaTooltipBubbleShape]. + */ @OptIn(ExperimentalMaterial3Api::class) @RunWith(RobolectricTestRunner::class) class TooltipTest { @@ -323,6 +328,17 @@ class TooltipTest { ) assertThat(calculatedLocalCaretX).isEqualTo(24f) + + // When bodyHeight (28 - 8 = 20) shrinks actualRadius to bodyHeight / 2 = 10, + // minCaretX tightens to 10 + 8 = 18 consistently with JcaTooltipBubbleShape. + provider.calculatePosition( + anchorBounds = IntRect(left = 16, top = 20, right = 40, bottom = 44), + windowSize = windowSize, + layoutDirection = LayoutDirection.Ltr, + popupContentSize = IntSize(width = 400, height = 28) + ) + + assertThat(calculatedLocalCaretX).isEqualTo(18f) } @Test @@ -459,7 +475,7 @@ class TooltipTest { // Verify the tip at y = 0 moved from x = 60 to x = 140 val probeAt140Tip = Path().apply { - addRect(androidx.compose.ui.geometry.Rect(Offset(139f, 1f), Size(2f, 2f))) + addRect(Rect(Offset(139f, 1f), Size(2f, 2f))) } val intersectAt140 = Path().apply { op(outlineAt140.path, probeAt140Tip, PathOperation.Intersect) From 81930a5219cf40d762df8455b112ff7550782778 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Wed, 11 Nov 2026 07:31:03 -0800 Subject: [PATCH 19/20] Assert returned popup position in TooltipTest corner clearance test --- .../com/google/jetpackcamera/ui/components/TooltipTest.kt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index 0b6ba4db88..fa0c81e78d 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -320,24 +320,26 @@ class TooltipTest { val windowSize = IntSize(width = 1080, height = 2400) val popupContentSize = IntSize(width = 400, height = 150) - provider.calculatePosition( + val firstPosition = provider.calculatePosition( anchorBounds = anchorBounds, windowSize = windowSize, layoutDirection = LayoutDirection.Ltr, popupContentSize = popupContentSize ) + assertThat(firstPosition.x).isEqualTo(16) assertThat(calculatedLocalCaretX).isEqualTo(24f) // When bodyHeight (28 - 8 = 20) shrinks actualRadius to bodyHeight / 2 = 10, // minCaretX tightens to 10 + 8 = 18 consistently with JcaTooltipBubbleShape. - provider.calculatePosition( + val compactPosition = provider.calculatePosition( anchorBounds = IntRect(left = 16, top = 20, right = 40, bottom = 44), windowSize = windowSize, layoutDirection = LayoutDirection.Ltr, popupContentSize = IntSize(width = 400, height = 28) ) + assertThat(compactPosition.x).isEqualTo(16) assertThat(calculatedLocalCaretX).isEqualTo(18f) } From b4dcbd31394537a2a58eadaaac07f212ef881a04 Mon Sep 17 00:00:00 2001 From: Kimberly Crevecoeur Date: Fri, 13 Nov 2026 11:31:56 -0800 Subject: [PATCH 20/20] Address tooltip review: take TooltipCaret in slot overload, drop Jca prefix - Slot TooltipIconButton overload now takes caret: TooltipCaret instead of a PopupPositionProvider, so the bubble shape, caret padding, and popup placement always come from the same instance. - Rename JcaTooltipCaret/rememberJcaTooltipCaret to TooltipCaret/ rememberTooltipCaret, JcaTooltipDefaults to TooltipIconButtonDefaults, and internal JcaTooltipBubbleShape/JcaTooltipPositionProvider to TooltipBubbleShape/TooltipPositionProvider. - Align tooltip test tag values to PascalCase (TooltipAnchorButton, TooltipContent) to match the capture module. - Center the instrumented test anchor within safeDrawingPadding so injected taps never land on System UI bars. --- .../ui/components/TooltipInstrumentedTest.kt | 12 ++- .../jetpackcamera/ui/components/Tooltip.kt | 97 ++++++++++--------- .../ui/components/TooltipTest.kt | 39 ++++---- 3 files changed, 79 insertions(+), 69 deletions(-) diff --git a/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt index beb62923eb..31b10b5ee6 100644 --- a/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt +++ b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt @@ -20,10 +20,11 @@ import android.view.InputDevice import android.view.MotionEvent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.size import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.layout.onGloballyPositioned @@ -59,7 +60,14 @@ class TooltipInstrumentedTest { composeTestRule.setContent { MaterialTheme { - Box(modifier = Modifier.fillMaxSize().padding(32.dp)) { + // Center the anchor inside the safe drawing area so injected taps never land on an + // edge-to-edge system bar or cutout owned by System UI. + Box( + modifier = Modifier + .fillMaxSize() + .safeDrawingPadding(), + contentAlignment = Alignment.Center + ) { TooltipIconButton( modifier = Modifier.onGloballyPositioned { coords -> val pos = coords.positionOnScreen() diff --git a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt index 9c55779b4b..501de186f2 100644 --- a/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -89,13 +89,13 @@ import kotlin.math.roundToInt import kotlinx.coroutines.launch /** Test tag applied to the interactive anchor button inside [TooltipIconButton]. */ -const val TOOLTIP_ANCHOR_BUTTON_TAG = "btn_tooltip_anchor" +const val TOOLTIP_ANCHOR_BUTTON_TAG = "TooltipAnchorButton" /** Test tag applied to the default [RichTooltip] surface rendered by [TooltipIconButton]. */ -const val TOOLTIP_CONTENT_TAG = "tooltip_content" +const val TOOLTIP_CONTENT_TAG = "TooltipContent" /* - * [JcaTooltipPositionProvider] and [JcaTooltipBubbleShape] plug into Material 3's [TooltipBox] and + * [TooltipPositionProvider] and [TooltipBubbleShape] plug into Material 3's [TooltipBox] and * [RichTooltip] (currently androidx.compose.material3:material3:1.5.0-alpha27) to work around two * upstream caret issues: * 1. Near screen edges, M3 clamps the popup window without shifting the caret cleanly to track @@ -103,7 +103,7 @@ const val TOOLTIP_CONTENT_TAG = "tooltip_content" * 2. M3 computes caret coordinates in `onLayoutRectChanged` after placement, causing the caret to * appear a few frames late. * - * TODO: Remove JcaTooltipPositionProvider and JcaTooltipBubbleShape once upstream Material 3 + * TODO: Remove TooltipPositionProvider and TooltipBubbleShape once upstream Material 3 * resolves edge-clamped caret placement and initial-frame caret lag. */ @@ -120,7 +120,7 @@ private object TooltipTokens { * Default dimensions for JCA tooltips, referencing Material 3 component defaults where available. */ @OptIn(ExperimentalMaterial3Api::class) -object JcaTooltipDefaults { +object TooltipIconButtonDefaults { /** Default caret dimensions matching Material 3 [TooltipDefaults.caretSize] (16dp x 8dp). */ val CaretSize: DpSize = TooltipDefaults.caretSize @@ -168,17 +168,18 @@ private class CaretPositionState( * Coordinates edge-aware tooltip placement, caret padding, and bubble shape rendering for a * [TooltipIconButton] or [TooltipBox]. * - * Create an instance via [rememberJcaTooltipCaret], pass [positionProvider] to [TooltipIconButton] - * (or [TooltipBox]), apply [caretPadding] to the tooltip content so it clears the caret triangle, - * and pass [bubbleShape] to [RichTooltip]'s `shape` parameter with `caretShape = null`. + * Create an instance via [rememberTooltipCaret] and pass it to [TooltipIconButton]'s `caret` + * parameter (or pass [positionProvider] to a plain [TooltipBox]), apply [caretPadding] to the + * tooltip content so it clears the caret triangle, and pass [bubbleShape] to [RichTooltip]'s `shape` + * parameter with `caretShape = null`. */ @OptIn(ExperimentalMaterial3Api::class) @Stable -class JcaTooltipCaret internal constructor( +class TooltipCaret internal constructor( positioning: TooltipAnchorPosition, density: Density, - private val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, - private val caretHeight: Dp = JcaTooltipDefaults.CaretHeight + private val caretWidth: Dp = TooltipIconButtonDefaults.CaretWidth, + private val caretHeight: Dp = TooltipIconButtonDefaults.CaretHeight ) { private val caretPositionState = CaretPositionState( initialIsCaretOnTop = positioning == TooltipAnchorPosition.Below @@ -191,7 +192,7 @@ class JcaTooltipCaret internal constructor( * [PopupPositionProvider] that clamps popup placement within safe screen margins and updates * the caret coordinates during layout before the first draw frame. */ - val positionProvider: PopupPositionProvider = JcaTooltipPositionProvider( + val positionProvider: PopupPositionProvider = TooltipPositionProvider( positioning = positioning, caretWidth = caretWidth, caretHeight = caretHeight, @@ -214,8 +215,8 @@ class JcaTooltipCaret internal constructor( * toward the anchor. The horizontal caret offset is read during [Shape.createOutline] in the * draw phase so Frame 0 renders at the exact anchor X without an extra recomposition. */ - fun bubbleShape(cornerRadius: Dp = JcaTooltipDefaults.CornerRadius): Shape = - JcaTooltipBubbleShape( + fun bubbleShape(cornerRadius: Dp = TooltipIconButtonDefaults.CornerRadius): Shape = + TooltipBubbleShape( localCaretXProvider = localCaretXProvider, isCaretOnTop = caretPositionState.isCaretOnTop, cornerRadius = cornerRadius, @@ -225,20 +226,20 @@ class JcaTooltipCaret internal constructor( } /** - * Remembers a [JcaTooltipCaret] keyed on [positioning] for pairing edge-clamped popup placement - * with [JcaTooltipCaret.bubbleShape] and [JcaTooltipCaret.caretPadding]. + * Remembers a [TooltipCaret] keyed on [positioning] for pairing edge-clamped popup placement + * with [TooltipCaret.bubbleShape] and [TooltipCaret.caretPadding]. * * @param positioning preferred anchor placement ([TooltipAnchorPosition.Below] or * [TooltipAnchorPosition.Above]); flips automatically when vertical window space is constrained. */ @OptIn(ExperimentalMaterial3Api::class) @Composable -fun rememberJcaTooltipCaret( +fun rememberTooltipCaret( positioning: TooltipAnchorPosition = TooltipAnchorPosition.Below -): JcaTooltipCaret { +): TooltipCaret { val density = LocalDensity.current return remember(positioning, density) { - JcaTooltipCaret( + TooltipCaret( positioning = positioning, density = density ) @@ -270,12 +271,12 @@ private fun clampCaretX( * @param caretWidth base width of the triangular caret. * @param caretHeight height of the triangular caret extending from the bubble body. */ -internal class JcaTooltipBubbleShape( +internal class TooltipBubbleShape( private val localCaretXProvider: () -> Float, private val isCaretOnTop: Boolean, - private val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, - private val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, - private val caretHeight: Dp = JcaTooltipDefaults.CaretHeight + private val cornerRadius: Dp = TooltipIconButtonDefaults.CornerRadius, + private val caretWidth: Dp = TooltipIconButtonDefaults.CaretWidth, + private val caretHeight: Dp = TooltipIconButtonDefaults.CaretHeight ) : Shape { override fun createOutline( size: Size, @@ -334,7 +335,7 @@ internal class JcaTooltipBubbleShape( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other !is JcaTooltipBubbleShape) return false + if (other !is TooltipBubbleShape) return false return localCaretXProvider == other.localCaretXProvider && isCaretOnTop == other.isCaretOnTop && cornerRadius == other.cornerRadius && @@ -369,13 +370,13 @@ internal class JcaTooltipBubbleShape( * whether the caret sits on the top edge (`true` when placed below the anchor). */ @OptIn(ExperimentalMaterial3Api::class) -internal class JcaTooltipPositionProvider( +internal class TooltipPositionProvider( private val positioning: TooltipAnchorPosition, - private val spacing: Dp = JcaTooltipDefaults.SpacingBetweenTooltipAndAnchor, - private val screenMargin: Dp = JcaTooltipDefaults.ScreenMargin, - private val cornerRadius: Dp = JcaTooltipDefaults.CornerRadius, - private val caretWidth: Dp = JcaTooltipDefaults.CaretWidth, - private val caretHeight: Dp = JcaTooltipDefaults.CaretHeight, + private val spacing: Dp = TooltipIconButtonDefaults.SpacingBetweenTooltipAndAnchor, + private val screenMargin: Dp = TooltipIconButtonDefaults.ScreenMargin, + private val cornerRadius: Dp = TooltipIconButtonDefaults.CornerRadius, + private val caretWidth: Dp = TooltipIconButtonDefaults.CaretWidth, + private val caretHeight: Dp = TooltipIconButtonDefaults.CaretHeight, private val density: Density, private val onCaretCalculated: (localCaretX: Float, isCaretOnTop: Boolean) -> Unit = { _, _ -> } ) : PopupPositionProvider { @@ -420,7 +421,7 @@ internal class JcaTooltipPositionProvider( val popupX = idealPopupX.coerceIn(minX, maxX) // Clamp local caret X so the caret base stays outside the rounded corners and matches - // what JcaTooltipBubbleShape draws + // what TooltipBubbleShape draws val bodyHeight = (popupContentSize.height - with(density) { caretHeight.toPx() }).coerceAtLeast(0f) val localCaretX = clampCaretX( @@ -442,7 +443,7 @@ internal class JcaTooltipPositionProvider( * * Uses Material 3's [TooltipBox] and [RichTooltip] with `secondaryFixed` / `onSecondaryFixed` theme * colors, polite live-region announcements, and edge-clamped caret placement via - * [rememberJcaTooltipCaret]. Renders a circular [size] container centered inside a + * [rememberTooltipCaret]. Renders a circular [size] container centered inside a * [minTouchTargetSize] touch target; when [isOutlined] is `true`, draws a `1.dp` circular border at * 20% [contentColor] alpha. [onClick] fires on every tap, whereas [onDismissRequest] fires once * each time an open tooltip is dismissed. @@ -484,19 +485,19 @@ fun TooltipIconButton( isOutlined: Boolean = false, containerColor: Color = Color.Transparent, contentColor: Color = Color.White, - size: Dp = JcaTooltipDefaults.ContainerSize, - minTouchTargetSize: Dp = JcaTooltipDefaults.TouchTargetSize, + size: Dp = TooltipIconButtonDefaults.ContainerSize, + minTouchTargetSize: Dp = TooltipIconButtonDefaults.TouchTargetSize, onClick: () -> Unit = {}, onDismissRequest: (() -> Unit)? = null ) { - val caret = rememberJcaTooltipCaret(positioning) + val caret = rememberTooltipCaret(positioning) TooltipIconButton( icon = icon, contentDescription = contentDescription ?: tooltipTitle ?: tooltipText, modifier = modifier, state = state, - positionProvider = caret.positionProvider, + caret = caret, isOutlined = isOutlined, containerColor = containerColor, contentColor = contentColor, @@ -528,7 +529,7 @@ fun TooltipIconButton( } }, caretShape = null, - maxWidth = JcaTooltipDefaults.MaxWidth, + maxWidth = TooltipIconButtonDefaults.MaxWidth, shape = caret.bubbleShape(), colors = TooltipDefaults.richTooltipColors( containerColor = MaterialTheme.colorScheme.secondaryFixed, @@ -571,11 +572,11 @@ fun TooltipIconButton( * an outside-touch dismissal from immediately reopening the popup on pointer-up. [onClick] fires on * every tap, whereas [onDismissRequest] fires once each time an open tooltip is dismissed. * - * To render an edge-clamped bubble with a caret pointing at the anchor, hoist - * `val caret = rememberJcaTooltipCaret(positioning)`, pass - * `positionProvider = caret.positionProvider`, configure - * `RichTooltip(shape = caret.bubbleShape(), caretShape = null)`, and apply - * `Modifier.padding(caret.caretPadding)` to the inner content. + * The popup is always placed by [caret]'s edge-clamped position provider. To render a bubble with + * a caret pointing at the anchor, hoist `val caret = rememberTooltipCaret(positioning)`, pass + * `caret = caret`, configure `RichTooltip(shape = caret.bubbleShape(), caretShape = null)`, and + * apply `Modifier.padding(caret.caretPadding)` to the inner content. Because the same [caret] + * drives both placement and shape, they cannot fall out of sync. * * @param icon icon composable centered inside the button container with [LocalContentColor] set to * [contentColor]. @@ -587,8 +588,8 @@ fun TooltipIconButton( * @param modifier [Modifier] applied to the outer [TooltipBox] wrapper. * @param state controls tooltip visibility; defaults to a persistent [TooltipState] so the popup * remains open until tapped again or dismissed externally. - * @param positionProvider computes popup coordinates relative to the anchor; defaults to - * `rememberJcaTooltipCaret().positionProvider`. + * @param caret [TooltipCaret] whose position provider places the popup; reuse the same instance + * for [TooltipCaret.bubbleShape] and [TooltipCaret.caretPadding] inside [tooltip]. * @param hasAction pass `true` when [tooltip] contains interactive controls so [TooltipBox] adjusts * accessibility focus and dismissal handling accordingly. * @param isOutlined when `true`, draws a `1.dp` circular border around the [size] container using @@ -610,13 +611,13 @@ fun TooltipIconButton( contentDescription: String?, modifier: Modifier = Modifier, state: TooltipState = rememberTooltipState(isPersistent = true), - positionProvider: PopupPositionProvider = rememberJcaTooltipCaret().positionProvider, + caret: TooltipCaret = rememberTooltipCaret(), hasAction: Boolean = false, isOutlined: Boolean = false, containerColor: Color = Color.Transparent, contentColor: Color = Color.White, - size: Dp = JcaTooltipDefaults.ContainerSize, - minTouchTargetSize: Dp = JcaTooltipDefaults.TouchTargetSize, + size: Dp = TooltipIconButtonDefaults.ContainerSize, + minTouchTargetSize: Dp = TooltipIconButtonDefaults.TouchTargetSize, onClick: () -> Unit = {}, onDismissRequest: (() -> Unit)? = null ) { @@ -634,7 +635,7 @@ fun TooltipIconButton( } TooltipBox( - positionProvider = positionProvider, + positionProvider = caret.positionProvider, tooltip = tooltip, state = state, modifier = modifier, diff --git a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt index fa0c81e78d..b01964a555 100644 --- a/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -67,8 +67,8 @@ import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner /** - * Robolectric unit tests for [TooltipIconButton], [rememberJcaTooltipCaret], - * [JcaTooltipPositionProvider], and [JcaTooltipBubbleShape]. + * Robolectric unit tests for [TooltipIconButton], [rememberTooltipCaret], + * [TooltipPositionProvider], and [TooltipBubbleShape]. */ @OptIn(ExperimentalMaterial3Api::class) @RunWith(RobolectricTestRunner::class) @@ -146,18 +146,18 @@ class TooltipTest { } @Test - fun rememberJcaTooltipCaret_providesCaretPaddingAndBubbleShape_andKeysOnPositioning() { + fun rememberTooltipCaret_providesCaretPaddingAndBubbleShape_andKeysOnPositioning() { var positioning by mutableStateOf(TooltipAnchorPosition.Below) var observedPadding: PaddingValues? = null composeTestRule.setContent { MaterialTheme { - val caret = rememberJcaTooltipCaret(positioning) + val caret = rememberTooltipCaret(positioning) observedPadding = caret.caretPadding TooltipIconButton( icon = { Box(modifier = Modifier.size(24.dp)) }, contentDescription = "Caret slot button", - positionProvider = caret.positionProvider, + caret = caret, tooltip = { RichTooltip( caretShape = null, @@ -174,10 +174,11 @@ class TooltipTest { } composeTestRule.waitForIdle() - assertThat(observedPadding?.calculateTopPadding()).isEqualTo(JcaTooltipDefaults.CaretHeight) + assertThat(observedPadding?.calculateTopPadding()) + .isEqualTo(TooltipIconButtonDefaults.CaretHeight) assertThat(observedPadding?.calculateBottomPadding()).isEqualTo(0.dp) - // Changing positioning re-keys rememberJcaTooltipCaret and flips initial caret padding edge + // Changing positioning re-keys rememberTooltipCaret and flips initial caret padding edge composeTestRule.runOnIdle { positioning = TooltipAnchorPosition.Above } @@ -185,7 +186,7 @@ class TooltipTest { assertThat(observedPadding?.calculateTopPadding()).isEqualTo(0.dp) assertThat(observedPadding?.calculateBottomPadding()) - .isEqualTo(JcaTooltipDefaults.CaretHeight) + .isEqualTo(TooltipIconButtonDefaults.CaretHeight) // Opening the custom slot tooltip renders the bubble shape and body cleanly composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } @@ -261,7 +262,7 @@ class TooltipTest { var calculatedLocalCaretX = 0f var calculatedIsCaretOnTop = false - val provider = JcaTooltipPositionProvider( + val provider = TooltipPositionProvider( positioning = TooltipAnchorPosition.Below, spacing = 4.dp, screenMargin = 16.dp, @@ -302,7 +303,7 @@ class TooltipTest { fun positionProvider_anchorInsideCornerArc_clampsCaretToMinCornerClearance() { var calculatedLocalCaretX = 0f - val provider = JcaTooltipPositionProvider( + val provider = TooltipPositionProvider( positioning = TooltipAnchorPosition.Below, spacing = 4.dp, screenMargin = 16.dp, @@ -331,7 +332,7 @@ class TooltipTest { assertThat(calculatedLocalCaretX).isEqualTo(24f) // When bodyHeight (28 - 8 = 20) shrinks actualRadius to bodyHeight / 2 = 10, - // minCaretX tightens to 10 + 8 = 18 consistently with JcaTooltipBubbleShape. + // minCaretX tightens to 10 + 8 = 18 consistently with TooltipBubbleShape. val compactPosition = provider.calculatePosition( anchorBounds = IntRect(left = 16, top = 20, right = 40, bottom = 44), windowSize = windowSize, @@ -347,7 +348,7 @@ class TooltipTest { fun positionProvider_spaceConstrainedBelow_flipsAbove() { var calculatedIsCaretOnTop = true - val provider = JcaTooltipPositionProvider( + val provider = TooltipPositionProvider( positioning = TooltipAnchorPosition.Below, spacing = 4.dp, screenMargin = 16.dp, @@ -380,7 +381,7 @@ class TooltipTest { composeTestRule.setContent { MaterialTheme { TooltipIconButton( - icon = { Box(modifier = Modifier.size(JcaTooltipDefaults.IconSize)) }, + icon = { Box(modifier = Modifier.size(TooltipIconButtonDefaults.IconSize)) }, contentDescription = "Custom info action", tooltipText = "Accessibility description test" ) @@ -388,8 +389,8 @@ class TooltipTest { } composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG) - .assertWidthIsAtLeast(JcaTooltipDefaults.TouchTargetSize) - .assertHeightIsAtLeast(JcaTooltipDefaults.TouchTargetSize) + .assertWidthIsAtLeast(TooltipIconButtonDefaults.TouchTargetSize) + .assertHeightIsAtLeast(TooltipIconButtonDefaults.TouchTargetSize) .assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Button)) .assert( SemanticsMatcher.expectValue( @@ -422,7 +423,7 @@ class TooltipTest { val size = Size(400f, 150f) // Shape with extreme negative caret X - val shapeNegative = JcaTooltipBubbleShape( + val shapeNegative = TooltipBubbleShape( localCaretXProvider = { -100f }, isCaretOnTop = true ) @@ -432,7 +433,7 @@ class TooltipTest { assertThat(outlineNegative.bounds.height).isEqualTo(150f) // Shape with extreme positive caret X - val shapeOverflow = JcaTooltipBubbleShape( + val shapeOverflow = TooltipBubbleShape( localCaretXProvider = { 1000f }, isCaretOnTop = false ) @@ -446,7 +447,7 @@ class TooltipTest { fun bubbleShape_defersCaretXProviderReadUntilCreateOutline() { var providerReads = 0 var dynamicCaretX = 60f - val shape = JcaTooltipBubbleShape( + val shape = TooltipBubbleShape( localCaretXProvider = { providerReads++ dynamicCaretX @@ -464,7 +465,7 @@ class TooltipTest { assertThat(providerReads).isEqualTo(1) // Updating dynamicCaretX during layout before draw produces a shifted caret outline - // from the same JcaTooltipBubbleShape instance without recomposing + // from the same TooltipBubbleShape instance without recomposing dynamicCaretX = 140f val outlineAt140 = shape.createOutline(size, LayoutDirection.Ltr, density) as Outline.Generic