From dd61e127bfc87f4ac9b9513fe67306fc648252c0 Mon Sep 17 00:00:00 2001 From: Harrison Oglesby Date: Tue, 14 Mar 2023 15:22:15 -0700 Subject: [PATCH] Bug 1809809 - create debouncedClickable modifier --- .../org/mozilla/fenix/compose/ext/Modifier.kt | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/app/src/main/java/org/mozilla/fenix/compose/ext/Modifier.kt b/app/src/main/java/org/mozilla/fenix/compose/ext/Modifier.kt index 5a0ffa960a..8816cdcd38 100644 --- a/app/src/main/java/org/mozilla/fenix/compose/ext/Modifier.kt +++ b/app/src/main/java/org/mozilla/fenix/compose/ext/Modifier.kt @@ -4,7 +4,14 @@ package org.mozilla.fenix.compose.ext +import android.os.SystemClock +import androidx.compose.foundation.clickable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.composed import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.Color @@ -49,3 +56,29 @@ fun Modifier.dashedBorder( ) }, ) + +/** + * Used when clickable needs to be debounced to prevent rapid successive clicks + * from calling the onClick function. + * + * @param debounceInterval The length of time to wait between click events in milliseconds + * @param onClick Callback for when item this modifier effects is clicked + */ +fun Modifier.debouncedClickable( + debounceInterval: Long = 1000L, + onClick: () -> Unit, +) = composed { + var lastClickTime: Long by remember { mutableStateOf(0) } + + this.then( + Modifier.clickable( + onClick = { + val currentSystemTime = SystemClock.elapsedRealtime() + if (currentSystemTime - lastClickTime > debounceInterval) { + onClick() + lastClickTime = currentSystemTime + } + }, + ), + ) +}