diff --git a/ui/components/build.gradle.kts b/ui/components/build.gradle.kts index 37a192fea1..0af42121df 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,22 @@ dependencies { // Compose - Material Design 3 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) + testImplementation(libs.compose.junit) + + // Testing + testImplementation(libs.junit) + testImplementation(libs.truth) + androidTestImplementation(libs.truth) + testImplementation(libs.robolectric) + 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 0e58984355..2cc9150d53 100644 --- a/ui/components/capture/build.gradle.kts +++ b/ui/components/capture/build.gradle.kts @@ -124,6 +124,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 787be102e2..5c53e3f8e5 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 @@ -42,10 +42,12 @@ import androidx.compose.foundation.layout.systemBarsIgnoringVisibility import androidx.compose.foundation.layout.systemGestures 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.ExperimentalMaterial3Api +import androidx.compose.material3.Icon import androidx.compose.material3.LocalMinimumInteractiveComponentSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SheetValue @@ -70,14 +72,17 @@ import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.layoutId 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.unit.Constraints import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.max import androidx.compose.ui.unit.min import androidx.compose.ui.unit.takeOrElse +import com.google.jetpackcamera.ui.components.TooltipIconButton import com.google.jetpackcamera.ui.components.capture.layout.CameraLayoutDefaults import com.google.jetpackcamera.ui.components.capture.layout.CameraLayoutSolver import com.google.jetpackcamera.ui.components.capture.layout.CameraRowIds @@ -159,8 +164,9 @@ internal val ViewfinderTopLine = HorizontalAlignmentLine { a, b -> minOf(a, b) } * Positions the [viewfinder], individual control slots ([captureButton], [imageWell], * [flipCameraButton], [zoomLevelDisplay], [elapsedTimeDisplay], [quickSettingsButton], * [indicatorRow], [captureModeToggle], [captureModeCarousel]), [quickSettingsOverlay], - * [topStartContent], [viewfinderTopEndContent], [topBarTrailingContent], [overlay], - * [screenFlashOverlay], [snackBar], and [errorDialog] without depending on [CaptureUiState]. + * [topStartContent], [viewfinderTopEndContent], [topBarLeadingContent], [topBarTrailingContent], + * [overlay], [screenFlashOverlay], [snackBar], and [errorDialog] without depending on + * [CaptureUiState]. * * @param modifier the [Modifier] for this component. * @param state the mode-agnostic [CaptureScaffoldState] controlling Quick Settings visibility and @@ -198,6 +204,8 @@ internal val ViewfinderTopLine = HorizontalAlignmentLine { a, b -> minOf(a, b) } * below [topStartContent], this content moves down with the top edge of the viewfinder while * [topStartContent] stays in place. Like [topStartContent], this content receives a * [PreviewOverlaySlotScope]. + * @param topBarLeadingContent optional composable content placed at the start of the top + * status/indicator bar directly adjacent to [indicatorRow]. * @param topBarTrailingContent optional composable content aligned to the end of the top * status/indicator bar. * @param onRequiresImmersiveChange invoked with `true` when the window is too short for the @@ -229,6 +237,7 @@ fun CaptureScaffoldLayout( snackBar: @Composable (Modifier, snackbarHostState: SnackbarHostState) -> Unit = { _, _ -> }, topStartContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, viewfinderTopEndContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, + topBarLeadingContent: (@Composable PreviewOverlaySlotScope.(Modifier) -> Unit)? = null, topBarTrailingContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit = {}, onRequiresImmersiveChange: (Boolean) -> Unit = {}, errorDialog: @Composable (Modifier) -> Unit = {} @@ -310,6 +319,7 @@ fun CaptureScaffoldLayout( viewfinderTopEndContent = viewfinderTopEndContent, onRequiresImmersiveChange = onRequiresImmersiveChange, indicatorRow = indicatorRow, + topBarLeadingContent = topBarLeadingContent, topBarTrailingContent = topBarTrailingContent, elapsedTimeDisplay = elapsedTimeDisplay, zoomControls = zoomLevelDisplay, @@ -356,9 +366,10 @@ fun CaptureScaffoldLayout( .padding(horizontal = LOWER_SECTION_HORIZONTAL_PADDING), contentAlignment = Alignment.CenterStart ) { - OverlapAwareStyleProvider { - indicatorRow(Modifier) - } + TopBarLeadingAndIndicatorsRow( + topBarLeadingContent = topBarLeadingContent, + indicatorRow = indicatorRow + ) OverlapAwareStyleProvider(Modifier.align(Alignment.CenterEnd)) { topBarTrailingContent(Modifier) } @@ -434,6 +445,45 @@ fun CaptureScaffoldLayout( } } +/** + * Lays out the optional [topBarLeadingContent] directly adjacent to [indicatorRow] inside the top + * status/indicator bar, flowing the leading content past any overlapping corner display cutout. + * + * @param topBarLeadingContent optional leading slot content scoped to [PreviewOverlaySlotScope]. + * @param indicatorRow top status indicator row content scoped to [PreviewOverlaySlotScope]. + * @param modifier [Modifier] applied to the outer row. + * @param cutoutRectsOverride synthetic cutout rectangles in local coordinates for deterministic + * unit testing; when empty, the host window's display cutout is used. + */ +@Composable +internal fun TopBarLeadingAndIndicatorsRow( + topBarLeadingContent: (@Composable PreviewOverlaySlotScope.(Modifier) -> Unit)?, + indicatorRow: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + modifier: Modifier = Modifier, + cutoutRectsOverride: List = emptyList() +) { + Row( + modifier = modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + if (topBarLeadingContent != null) { + OverlapAwareStyleProvider { + val slotScope = this + CutoutAwareRow( + modifier = Modifier.wrapContentWidth(align = Alignment.Start), + horizontalSpacing = 0.dp, + cutoutRectsOverride = cutoutRectsOverride.ifEmpty { null } + ) { + slotScope.topBarLeadingContent(Modifier) + } + } + } + OverlapAwareStyleProvider { + indicatorRow(Modifier) + } + } +} + private enum class CaptureSlotId { Viewfinder, TopStartContent, @@ -456,6 +506,7 @@ private fun AdaptivePortraitCaptureLayout( viewfinderTopEndContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, onRequiresImmersiveChange: (Boolean) -> Unit, indicatorRow: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, + topBarLeadingContent: (@Composable PreviewOverlaySlotScope.(Modifier) -> Unit)?, topBarTrailingContent: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, elapsedTimeDisplay: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, zoomControls: @Composable PreviewOverlaySlotScope.(Modifier) -> Unit, @@ -545,9 +596,10 @@ private fun AdaptivePortraitCaptureLayout( .padding(horizontal = LOWER_SECTION_HORIZONTAL_PADDING), contentAlignment = Alignment.CenterStart ) { - OverlapAwareStyleProvider { - indicatorRow(Modifier) - } + TopBarLeadingAndIndicatorsRow( + topBarLeadingContent = topBarLeadingContent, + indicatorRow = indicatorRow + ) OverlapAwareStyleProvider(Modifier.align(Alignment.CenterEnd)) { topBarTrailingContent(Modifier) } @@ -1019,3 +1071,95 @@ private fun CaptureLayoutPreview() { } ) } + +@OptIn(ExperimentalMaterial3Api::class) +@PreviewPortraitDevices +@Composable +private fun CaptureLayoutWithTooltipPreview() { + CaptureScaffoldLayout( + modifier = Modifier.background(Color.Black), + viewfinder = { modifier -> + Box( + modifier = modifier + .fillMaxWidth() + .aspectRatio(3f / 4f) + .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) + ) + } + ) +} diff --git a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScaffold.kt b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScaffold.kt index 577837dd27..06e176a48a 100644 --- a/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScaffold.kt +++ b/ui/components/capture/src/main/java/com/google/jetpackcamera/ui/components/capture/CaptureScaffold.kt @@ -709,7 +709,8 @@ private fun rememberZoomStateManager( * Opinionated camera capture scaffold exposing individual control and chrome slots ([topBar], * [captureButton], [flipCameraButton], [zoomControls], [captureModeToggle], [captureModeCarousel], * [quickSettingsButton], [elapsedTimeDisplay], opt-in [imageWell], [quickSettings], [errorDialog], - * [topStartContent], [viewfinderTopEndContent], [topBarTrailingContent], and [overlay]). + * [topStartContent], [viewfinderTopEndContent], [topBarLeadingContent], [topBarTrailingContent], + * and [overlay]). * * Host screens remain in control of their own screen policy (permissions, camera session start/stop * via [CameraSessionEffect], capture event navigation, and benchmarking), and pass a deferred @@ -766,6 +767,8 @@ private fun rememberZoomStateManager( * below the top bar. * @param viewfinderTopEndContent optional composable slot anchored to the top-end corner of the * viewfinder. + * @param topBarLeadingContent optional composable slot placed at the start of the top bar directly + * adjacent to [topBar]. * @param topBarTrailingContent optional composable slot aligned to the end of the top bar. * @param overlay optional overlay composable slot drawn above the viewfinder and controls. */ @@ -889,6 +892,7 @@ fun CaptureScaffold( }, topStartContent: (@Composable CaptureSlotScope.(Modifier) -> Unit)? = null, viewfinderTopEndContent: (@Composable CaptureSlotScope.(Modifier) -> Unit)? = null, + topBarLeadingContent: (@Composable CaptureSlotScope.(Modifier) -> Unit)? = null, topBarTrailingContent: (@Composable CaptureSlotScope.(Modifier) -> Unit)? = null, overlay: (@Composable CaptureSlotScope.(Modifier) -> Unit)? = null ) { @@ -1290,6 +1294,21 @@ fun CaptureScaffold( slotScope.viewfinderTopEndContent(slotModifier) } }, + topBarLeadingContent = topBarLeadingContent?.let { leadingContent -> + { slotModifier -> + val slotScope = rememberCaptureSlotScope( + overlayScope = this, + isRecordingState = isVideoRecordingActive, + scaffoldState = state, + onToggleQuickSettings = onToggleQuickSettings, + onDismissQuickSettings = onDismissQuickSettings, + onIncrementZoom = onIncrementZoom, + onAnimateZoomTo = onAnimateZoomTo, + onSetAbsoluteZoom = onSetAbsoluteZoom + ) + slotScope.leadingContent(slotModifier) + } + }, topBarTrailingContent = { slotModifier -> if (topBarTrailingContent != null) { val slotScope = rememberCaptureSlotScope( 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 fea45df63e..d313d9fe1d 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,9 +18,14 @@ 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.runtime.Composable import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.getUnclippedBoundsInRoot @@ -28,6 +33,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 +167,84 @@ 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) + } + + @Test + fun topBarLeadingContent_receivesPreviewOverlaySlotScopeOverlapState() { + var leadingOverViewfinder: Boolean? = null + composeTestRule.setContent { + CaptureScaffoldLayout( + viewfinder = { vfModifier -> + val overlapTargetBounds = LocalOverlapTargetBounds.current + Box( + vfModifier + .fillMaxSize() + .onGloballyPositioned { coordinates -> + overlapTargetBounds.value = coordinates.boundsInWindow() + } + ) + }, + topBarLeadingContent = { leadingModifier -> + leadingOverViewfinder = isOverViewfinder + Box(leadingModifier.size(48.dp).testTag(LEADING_BUTTON_TAG)) + }, + indicatorRow = { + Box(it.size(40.dp).testTag(INDICATOR_ROW_TAG)) + } + ) + } + composeTestRule.waitForIdle() + + assertThat(leadingOverViewfinder).isTrue() + } + private fun boundsOf( tag: String, view: View, @@ -208,11 +292,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" -@androidx.compose.runtime.Composable +@Composable private fun TestPreviewLayout( - screenFlashOverlay: @androidx.compose.runtime.Composable (Modifier) -> Unit = { + topBarLeadingContent: (@Composable PreviewOverlaySlotScope.(Modifier) -> Unit)? = null, + screenFlashOverlay: @Composable (Modifier) -> Unit = { Box(it.size(0.dp)) } ) { @@ -225,6 +311,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)) }, screenFlashOverlay = screenFlashOverlay diff --git a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureScaffoldTest.kt b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureScaffoldTest.kt index 5c36434273..aa444bf1c7 100644 --- a/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureScaffoldTest.kt +++ b/ui/components/capture/src/test/java/com/google/jetpackcamera/ui/components/capture/CaptureScaffoldTest.kt @@ -660,8 +660,38 @@ class CaptureScaffoldTest { assertThat(clicked).isTrue() } + @Test + fun captureScaffold_rendersTopBarLeadingContentWhenProvided() { + var showLeading by mutableStateOf(false) + + composeTestRule.setContent { + CompositionLocalProvider(LocalDisableAnimations provides true) { + CaptureScaffold( + captureUiState = { LOADING_CAPTURE_UI_STATE_SKELETON }, + surfaceRequest = null, + topBarLeadingContent = if (showLeading) { + { slotModifier -> + Box(slotModifier.size(48.dp).testTag(TOP_BAR_LEADING_TAG)) + } + } else { + null + } + ) + } + } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(TOP_BAR_LEADING_TAG).assertDoesNotExist() + + composeTestRule.runOnIdle { showLeading = true } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(TOP_BAR_LEADING_TAG).assertIsDisplayed() + } + private companion object { const val TOP_START_BUTTON_TAG = "test_top_start_button" + const val TOP_BAR_LEADING_TAG = "test_top_bar_leading" const val ICON_BUTTON_TAG = "test_icon_button" } } 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..31b10b5ee6 --- /dev/null +++ b/ui/components/src/androidTest/java/com/google/jetpackcamera/ui/components/TooltipInstrumentedTest.kt @@ -0,0 +1,136 @@ +/* + * 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.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 +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.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 + +/** + * 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 { + + @get:Rule + val composeTestRule = createComposeRule() + + @Test + fun tooltipIconButton_realWindowTapOnAnchor_opensAndClosesTooltip() { + var anchorCenterOnScreen = Offset.Zero + var dismissCount = 0 + + composeTestRule.setContent { + MaterialTheme { + // 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() + 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", + onDismissRequest = { dismissCount++ } + ) + } + } + } + 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() + 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, + // while invoking onDismissRequest exactly once. + sendRealScreenTap(anchorCenterOnScreen) + composeTestRule.waitForIdle() + composeTestRule.onNode(isPopup()).assertDoesNotExist() + assertThat(dismissCount).isEqualTo(1) + } + + 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 new file mode 100644 index 0000000000..501de186f2 --- /dev/null +++ b/ui/components/src/main/java/com/google/jetpackcamera/ui/components/Tooltip.kt @@ -0,0 +1,716 @@ +/* + * 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.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.PaddingValues +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.shape.CircleShape +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.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.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +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.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.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.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 +import androidx.compose.ui.unit.DpSize +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.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 = "TooltipAnchorButton" + +/** Test tag applied to the default [RichTooltip] surface rendered by [TooltipIconButton]. */ +const val TOOLTIP_CONTENT_TAG = "TooltipContent" + +/* + * [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 + * 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. + * + * TODO: Remove TooltipPositionProvider and TooltipBubbleShape once upstream Material 3 + * resolves edge-clamped caret placement and initial-frame caret lag. + */ + +private object TooltipTokens { + val BorderWidth = 1.dp + const val BORDER_ALPHA = 0.2f + + // 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 +} + +/** + * Default dimensions for JCA tooltips, referencing Material 3 component defaults where available. + */ +@OptIn(ExperimentalMaterial3Api::class) +object TooltipIconButtonDefaults { + /** 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. */ + 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) 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 + + /** Medium icon size (24dp) matching [IconButtonDefaults.mediumIconSize]. */ + val IconSize: Dp = IconButtonDefaults.mediumIconSize + + /** + * Maximum width aligned with design mock (296dp), + * capped within [TooltipDefaults.richTooltipMaxWidth] (320dp). + */ + val MaxWidth: Dp = 296.dp +} + +@Stable +private class CaretPositionState( + initialCaretX: Float = 0f, + initialIsCaretOnTop: Boolean = true +) { + var localCaretX: Float by mutableFloatStateOf(initialCaretX) + 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 [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 TooltipCaret internal constructor( + positioning: TooltipAnchorPosition, + density: Density, + private val caretWidth: Dp = TooltipIconButtonDefaults.CaretWidth, + private val caretHeight: Dp = TooltipIconButtonDefaults.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 = TooltipPositionProvider( + positioning = positioning, + caretWidth = caretWidth, + caretHeight = caretHeight, + 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 = TooltipIconButtonDefaults.CornerRadius): Shape = + TooltipBubbleShape( + localCaretXProvider = localCaretXProvider, + isCaretOnTop = caretPositionState.isCaretOnTop, + cornerRadius = cornerRadius, + caretWidth = caretWidth, + caretHeight = caretHeight + ) +} + +/** + * 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 rememberTooltipCaret( + positioning: TooltipAnchorPosition = TooltipAnchorPosition.Below +): TooltipCaret { + val density = LocalDensity.current + return remember(positioning, density) { + TooltipCaret( + positioning = positioning, + density = density + ) + } +} + +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. + * + * @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. + */ +internal class TooltipBubbleShape( + private val localCaretXProvider: () -> Float, + private val isCaretOnTop: Boolean, + private val cornerRadius: Dp = TooltipIconButtonDefaults.CornerRadius, + private val caretWidth: Dp = TooltipIconButtonDefaults.CaretWidth, + private val caretHeight: Dp = TooltipIconButtonDefaults.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 bodyTop = if (isCaretOnTop) ch else 0f + // Clamp caret base so the triangle never bleeds into the corner radius arcs + val clampedCaretX = clampCaretX( + caretX = localCaretXProvider(), + width = w, + bodyHeight = bodyHeight, + cornerRadiusPx = r, + caretWidthPx = cw + ) + + 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)) + } + + 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 { + if (this === other) return true + if (other !is TooltipBubbleShape) return false + return localCaretXProvider == other.localCaretXProvider && + isCaretOnTop == other.isCaretOnTop && + cornerRadius == other.cornerRadius && + caretWidth == other.caretWidth && + caretHeight == other.caretHeight + } + + override fun hashCode(): Int { + var result = localCaretXProvider.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 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) +internal class TooltipPositionProvider( + private val positioning: TooltipAnchorPosition, + 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 { + 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 -> { + spaceBelow >= popupContentSize.height || spaceBelow >= spaceAbove + } + TooltipAnchorPosition.Above -> { + !(spaceAbove >= popupContentSize.height || spaceAbove >= spaceBelow) + } + else -> spaceBelow >= popupContentSize.height + } + + 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 + 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) + + // Clamp local caret X so the caret base stays outside the rounded corners and matches + // what TooltipBubbleShape draws + 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) + + return IntOffset(popupX, popupY) + } +} + +/** + * Circular camera-overlay icon button that toggles a styled [RichTooltip] when tapped. + * + * Uses Material 3's [TooltipBox] and [RichTooltip] with `secondaryFixed` / `onSecondaryFixed` theme + * colors, polite live-region announcements, and edge-clamped caret placement via + * [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. + * + * @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 +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, + isOutlined: Boolean = false, + containerColor: Color = Color.Transparent, + contentColor: Color = Color.White, + size: Dp = TooltipIconButtonDefaults.ContainerSize, + minTouchTargetSize: Dp = TooltipIconButtonDefaults.TouchTargetSize, + onClick: () -> Unit = {}, + onDismissRequest: (() -> Unit)? = null +) { + val caret = rememberTooltipCaret(positioning) + + TooltipIconButton( + icon = icon, + contentDescription = contentDescription ?: tooltipTitle ?: tooltipText, + modifier = modifier, + state = state, + caret = caret, + isOutlined = isOutlined, + containerColor = containerColor, + contentColor = contentColor, + size = size, + minTouchTargetSize = minTouchTargetSize, + onClick = onClick, + onDismissRequest = onDismissRequest, + tooltip = { + val caretPadding = caret.caretPadding + val caretTopPadding = caretPadding.calculateTopPadding() + val caretBottomPadding = caretPadding.calculateBottomPadding() + + 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) + ) + } + }, + caretShape = null, + maxWidth = TooltipIconButtonDefaults.MaxWidth, + shape = caret.bubbleShape(), + colors = TooltipDefaults.richTooltipColors( + containerColor = MaterialTheme.colorScheme.secondaryFixed, + contentColor = MaterialTheme.colorScheme.onSecondaryFixed, + titleContentColor = MaterialTheme.colorScheme.onSecondaryFixed + ) + ) { + 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 + } + ) + ) + } + } + ) +} + +/** + * 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. + * + * 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]. + * @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 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 + * [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 +fun TooltipIconButton( + icon: @Composable () -> Unit, + tooltip: @Composable TooltipScope.() -> Unit, + contentDescription: String?, + modifier: Modifier = Modifier, + state: TooltipState = rememberTooltipState(isPersistent = true), + caret: TooltipCaret = rememberTooltipCaret(), + hasAction: Boolean = false, + isOutlined: Boolean = false, + containerColor: Color = Color.Transparent, + contentColor: Color = Color.White, + size: Dp = TooltipIconButtonDefaults.ContainerSize, + minTouchTargetSize: Dp = TooltipIconButtonDefaults.TouchTargetSize, + onClick: () -> Unit = {}, + onDismissRequest: (() -> Unit)? = null +) { + val scope = rememberCoroutineScope() + val currentOnClick by rememberUpdatedState(onClick) + 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 = caret.positionProvider, + tooltip = tooltip, + state = state, + modifier = modifier, + onDismissRequest = dismissTooltip, + enableUserInput = false, + hasAction = hasAction + ) { + 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( + role = Role.Button, + onClickLabel = null, + interactionSource = remember { MutableInteractionSource() }, + indication = ripple(bounded = false, radius = minTouchTargetSize / 2) + ) { + val wasVisible = wasVisibleAtDown || state.isVisible + wasVisibleAtDown = false + if (wasVisible) { + dismissTooltip() + } else { + scope.launch { state.show() } + } + currentOnClick() + } + .then( + if (contentDescription != null) { + Modifier.semantics { + this.contentDescription = contentDescription + } + } else { + Modifier + } + ), + contentAlignment = Alignment.Center + ) { + val containerModifier = Modifier + .size(size) + .then( + if (isOutlined) { + Modifier.border( + border = BorderStroke( + TooltipTokens.BorderWidth, + contentColor.copy(alpha = TooltipTokens.BORDER_ALPHA) + ), + shape = CircleShape + ) + } else { + Modifier + } + ) + .background(color = containerColor, shape = CircleShape) + + Box( + modifier = containerModifier, + contentAlignment = Alignment.Center + ) { + 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 new file mode 100644 index 0000000000..b01964a555 --- /dev/null +++ b/ui/components/src/test/java/com/google/jetpackcamera/ui/components/TooltipTest.kt @@ -0,0 +1,488 @@ +/* + * 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.PaddingValues +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.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.Rect +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 +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 org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * Robolectric unit tests for [TooltipIconButton], [rememberTooltipCaret], + * [TooltipPositionProvider], and [TooltipBubbleShape]. + */ +@OptIn(ExperimentalMaterial3Api::class) +@RunWith(RobolectricTestRunner::class) +class TooltipTest { + + @get:Rule + val composeTestRule = createComposeRule() + + @Test + 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() + + // Show on first touch tap + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } + 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 touch tap + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } + composeTestRule.waitForIdle() + + composeTestRule.onNode(isPopup()).assertDoesNotExist() + } + + @Test + fun tooltip_composableSlotOverload_rendersCustomRichTooltipAndAction() { + var actionClicked = false + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + contentDescription = "Info button", + hasAction = true, + tooltip = { + RichTooltip( + action = { + TextButton(onClick = { actionClicked = true }) { + Text("Learn more") + } + } + ) { + Text("Styled tooltip body") + } + } + ) + } + } + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } + composeTestRule.waitForIdle() + + composeTestRule.onNode(hasText("Styled tooltip body") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + composeTestRule.onNode(hasText("Learn more") and hasAnyAncestor(isPopup())) + .assertIsDisplayed() + .performTouchInput { click() } + composeTestRule.waitForIdle() + + assertThat(actionClicked).isTrue() + } + + @Test + fun rememberTooltipCaret_providesCaretPaddingAndBubbleShape_andKeysOnPositioning() { + var positioning by mutableStateOf(TooltipAnchorPosition.Below) + var observedPadding: PaddingValues? = null + + composeTestRule.setContent { + MaterialTheme { + val caret = rememberTooltipCaret(positioning) + observedPadding = caret.caretPadding + TooltipIconButton( + icon = { Box(modifier = Modifier.size(24.dp)) }, + contentDescription = "Caret slot button", + caret = caret, + tooltip = { + RichTooltip( + caretShape = null, + shape = caret.bubbleShape() + ) { + Text( + text = "Custom caret body", + modifier = Modifier.padding(caret.caretPadding) + ) + } + } + ) + } + } + composeTestRule.waitForIdle() + + assertThat(observedPadding?.calculateTopPadding()) + .isEqualTo(TooltipIconButtonDefaults.CaretHeight) + assertThat(observedPadding?.calculateBottomPadding()).isEqualTo(0.dp) + + // Changing positioning re-keys rememberTooltipCaret and flips initial caret padding edge + composeTestRule.runOnIdle { + positioning = TooltipAnchorPosition.Above + } + composeTestRule.waitForIdle() + + assertThat(observedPadding?.calculateTopPadding()).isEqualTo(0.dp) + assertThat(observedPadding?.calculateBottomPadding()) + .isEqualTo(TooltipIconButtonDefaults.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 + var calculatedIsCaretOnTop = false + + val provider = TooltipPositionProvider( + positioning = TooltipAnchorPosition.Below, + spacing = 4.dp, + screenMargin = 16.dp, + density = Density(1f), + onCaretCalculated = { localCaretX, isCaretOnTop -> + calculatedLocalCaretX = localCaretX + calculatedIsCaretOnTop = isCaretOnTop + } + ) + + // 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) + + val position = provider.calculatePosition( + anchorBounds = anchorBounds, + windowSize = windowSize, + layoutDirection = LayoutDirection.Ltr, + popupContentSize = popupContentSize + ) + + // Popup clamps to screen margin (16px) + assertThat(position.x).isEqualTo(16) + // Positioned below anchor: bottom (68) + spacing (4) = 72 + assertThat(position.y).isEqualTo(72) + + // Local caret X is anchor center X (40) - popup X (16) = 24 + assertThat(calculatedLocalCaretX).isEqualTo(24f) + assertThat(calculatedIsCaretOnTop).isTrue() + + // 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_anchorInsideCornerArc_clampsCaretToMinCornerClearance() { + var calculatedLocalCaretX = 0f + + val provider = TooltipPositionProvider( + positioning = TooltipAnchorPosition.Below, + spacing = 4.dp, + screenMargin = 16.dp, + cornerRadius = 16.dp, + caretWidth = 16.dp, + density = Density(1f), + onCaretCalculated = { localCaretX, _ -> + calculatedLocalCaretX = localCaretX + } + ) + + // 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 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 TooltipBubbleShape. + 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) + } + + @Test + fun positionProvider_spaceConstrainedBelow_flipsAbove() { + var calculatedIsCaretOnTop = true + + val provider = TooltipPositionProvider( + 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 tooltip_accessibility_hasTouchTargetButtonRoleSingleLabelAndPoliteLiveRegion() { + composeTestRule.setContent { + MaterialTheme { + TooltipIconButton( + icon = { Box(modifier = Modifier.size(TooltipIconButtonDefaults.IconSize)) }, + contentDescription = "Custom info action", + tooltipText = "Accessibility description test" + ) + } + } + + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG) + .assertWidthIsAtLeast(TooltipIconButtonDefaults.TouchTargetSize) + .assertHeightIsAtLeast(TooltipIconButtonDefaults.TouchTargetSize) + .assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Button)) + .assert( + SemanticsMatcher.expectValue( + SemanticsProperties.ContentDescription, + 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 RichTooltip + composeTestRule.onNodeWithTag(TOOLTIP_ANCHOR_BUTTON_TAG).performTouchInput { click() } + composeTestRule.waitForIdle() + + composeTestRule.onNodeWithTag(TOOLTIP_CONTENT_TAG) + .assert( + SemanticsMatcher.expectValue( + SemanticsProperties.LiveRegion, + LiveRegionMode.Polite + ) + ) + } + + @Test + fun bubbleShape_caretXClamped_doesNotBleedIntoCornerRadius() { + val density = Density(1f) + val size = Size(400f, 150f) + + // Shape with extreme negative caret X + val shapeNegative = TooltipBubbleShape( + localCaretXProvider = { -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 = TooltipBubbleShape( + localCaretXProvider = { 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) + } + + @Test + fun bubbleShape_defersCaretXProviderReadUntilCreateOutline() { + var providerReads = 0 + var dynamicCaretX = 60f + val shape = TooltipBubbleShape( + 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 TooltipBubbleShape 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(Rect(Offset(139f, 1f), Size(2f, 2f))) + } + val intersectAt140 = Path().apply { + op(outlineAt140.path, probeAt140Tip, PathOperation.Intersect) + } + assertThat(intersectAt140.isEmpty).isFalse() + } +}