feat: Implement keyboard height provider and optimize emoji picker animations
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
package com.rosetta.messenger.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* 🎯 KEYBOARD HEIGHT PROVIDER
|
||||
*
|
||||
* Вдохновлено Telegram's EmojiView.java:
|
||||
* - Сохраняет высоту клавиатуры в SharedPreferences
|
||||
* - Использует сохранённую высоту для emoji picker
|
||||
* - Обновляет при изменении высоты клавиатуры
|
||||
*
|
||||
* Telegram код:
|
||||
* ```java
|
||||
* keyboardHeight = MessagesController.getGlobalEmojiSettings()
|
||||
* .getInt("kbd_height", AndroidUtilities.dp(200));
|
||||
* ```
|
||||
*/
|
||||
object KeyboardHeightProvider {
|
||||
private const val PREFS_NAME = "emoji_keyboard_prefs"
|
||||
private const val KEY_KEYBOARD_HEIGHT = "kbd_height"
|
||||
private const val DEFAULT_HEIGHT_DP = 280 // Telegram uses 200, we use 280
|
||||
|
||||
/**
|
||||
* Получить сохранённую высоту клавиатуры
|
||||
*/
|
||||
fun getSavedKeyboardHeight(context: Context): Int {
|
||||
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
val defaultPx = dpToPx(context, DEFAULT_HEIGHT_DP)
|
||||
val savedPx = prefs.getInt(KEY_KEYBOARD_HEIGHT, defaultPx)
|
||||
val isDefault = savedPx == defaultPx
|
||||
|
||||
android.util.Log.d("KeyboardHeight", "📖 getSavedKeyboardHeight: ${savedPx}px (${pxToDp(context, savedPx)}dp) ${if (isDefault) "[DEFAULT]" else "[SAVED]"}")
|
||||
return savedPx
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранить высоту клавиатуры
|
||||
*/
|
||||
fun saveKeyboardHeight(context: Context, heightPx: Int) {
|
||||
if (heightPx > 0) {
|
||||
val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
val oldHeight = prefs.getInt(KEY_KEYBOARD_HEIGHT, -1)
|
||||
val changed = oldHeight != heightPx
|
||||
|
||||
prefs.edit().putInt(KEY_KEYBOARD_HEIGHT, heightPx).apply()
|
||||
|
||||
if (changed) {
|
||||
android.util.Log.d("KeyboardHeight", "💾 SAVED keyboard height: ${heightPx}px (${pxToDp(context, heightPx)}dp) [WAS: ${oldHeight}px]")
|
||||
} else {
|
||||
android.util.Log.v("KeyboardHeight", "💾 Same keyboard height: ${heightPx}px (no change)")
|
||||
}
|
||||
} else {
|
||||
android.util.Log.w("KeyboardHeight", "⚠️ Attempted to save invalid height: ${heightPx}px")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить длительность анимации клавиатуры
|
||||
* Telegram использует: AdjustPanLayoutHelper.keyboardDuration (250ms обычно)
|
||||
*/
|
||||
fun getKeyboardAnimationDuration(): Long = 250L
|
||||
|
||||
// Helper functions
|
||||
private fun dpToPx(context: Context, dp: Int): Int {
|
||||
val density = context.resources.displayMetrics.density
|
||||
return (dp * density).toInt()
|
||||
}
|
||||
|
||||
private fun pxToDp(context: Context, px: Int): Int {
|
||||
val density = context.resources.displayMetrics.density
|
||||
return (px / density).toInt()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composable для получения высоты клавиатуры из SharedPreferences
|
||||
* НЕ использует remember - всегда берет актуальное значение из SharedPreferences
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSavedKeyboardHeight(): Dp {
|
||||
val context = LocalContext.current
|
||||
|
||||
// 🔥 НЕ используем remember - каждый раз читаем актуальное значение
|
||||
val heightPx = KeyboardHeightProvider.getSavedKeyboardHeight(context)
|
||||
val density = context.resources.displayMetrics.density
|
||||
val heightDp = (heightPx / density).dp
|
||||
|
||||
android.util.Log.d("KeyboardHeight", "🎯 rememberSavedKeyboardHeight: ${heightDp} (${heightPx}px, density=${density})")
|
||||
|
||||
return heightDp
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import coil.compose.AsyncImage
|
||||
@@ -44,9 +45,10 @@ import kotlinx.coroutines.launch
|
||||
* 2. LazyGrid с оптимизированными настройками (beyondBoundsLayout)
|
||||
* 3. Hardware layer для анимаций
|
||||
* 4. Минимум recomposition (derivedStateOf, remember keys)
|
||||
* 5. Smooth slide + fade transitions
|
||||
* 5. Smooth slide + fade transitions (Telegram-style)
|
||||
* 6. Coil оптимизация (hardware acceleration, size limits)
|
||||
* 7. Нет лишних indications/ripples
|
||||
* 7. SharedPreferences для сохранения высоты клавиатуры (как в Telegram)
|
||||
* 8. keyboardDuration для синхронизации с системной клавиатурой
|
||||
*
|
||||
* @param isVisible Видимость панели
|
||||
* @param isDarkTheme Темная/светлая тема
|
||||
@@ -63,36 +65,47 @@ fun OptimizedEmojiPicker(
|
||||
onClose: () -> Unit = {},
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
// 🎭 Быстрая и плавная анимация (как в Telegram)
|
||||
// 🔥 Используем сохранённую высоту клавиатуры (как в Telegram)
|
||||
val savedKeyboardHeight = rememberSavedKeyboardHeight()
|
||||
|
||||
// 🔥 Telegram's keyboardDuration для синхронизации анимации
|
||||
val animationDuration = KeyboardHeightProvider.getKeyboardAnimationDuration().toInt()
|
||||
|
||||
// 🔥 Логирование изменений видимости
|
||||
LaunchedEffect(isVisible) {
|
||||
android.util.Log.d("EmojiPicker", "🎭 OptimizedEmojiPicker visibility changed: $isVisible (height=${savedKeyboardHeight}, animDuration=${animationDuration}ms)")
|
||||
}
|
||||
|
||||
// 🎭 Telegram-style анимация: используем сохранённую длительность
|
||||
AnimatedVisibility(
|
||||
visible = isVisible,
|
||||
enter = slideInVertically(
|
||||
initialOffsetY = { it },
|
||||
animationSpec = tween(
|
||||
durationMillis = 180, // 🔥 Быстрее!
|
||||
durationMillis = animationDuration, // 🔥 Telegram's 250ms
|
||||
easing = FastOutSlowInEasing
|
||||
)
|
||||
) + fadeIn(
|
||||
animationSpec = tween(
|
||||
durationMillis = 120,
|
||||
durationMillis = animationDuration / 2,
|
||||
easing = LinearEasing
|
||||
)
|
||||
),
|
||||
exit = slideOutVertically(
|
||||
targetOffsetY = { it },
|
||||
animationSpec = tween(
|
||||
durationMillis = 150, // 🔥 Быстрое закрытие
|
||||
durationMillis = (animationDuration * 0.8).toInt(), // 🔥 Быстрое закрытие (200ms)
|
||||
easing = FastOutLinearInEasing
|
||||
)
|
||||
) + fadeOut(
|
||||
animationSpec = tween(
|
||||
durationMillis = 100,
|
||||
durationMillis = (animationDuration * 0.6).toInt(),
|
||||
easing = LinearEasing
|
||||
)
|
||||
),
|
||||
modifier = modifier
|
||||
) {
|
||||
// 🎨 Hardware layer для анимаций (GPU ускорение)
|
||||
// 🎨 Hardware layer для анимаций (GPU ускорение - как в Telegram)
|
||||
Box(
|
||||
modifier = Modifier.graphicsLayer {
|
||||
// Используем hardware layer только во время анимации
|
||||
@@ -103,7 +116,8 @@ fun OptimizedEmojiPicker(
|
||||
) {
|
||||
EmojiPickerContent(
|
||||
isDarkTheme = isDarkTheme,
|
||||
onEmojiSelected = onEmojiSelected
|
||||
onEmojiSelected = onEmojiSelected,
|
||||
keyboardHeight = savedKeyboardHeight
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -115,7 +129,8 @@ fun OptimizedEmojiPicker(
|
||||
@Composable
|
||||
private fun EmojiPickerContent(
|
||||
isDarkTheme: Boolean,
|
||||
onEmojiSelected: (String) -> Unit
|
||||
onEmojiSelected: (String) -> Unit,
|
||||
keyboardHeight: Dp
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var selectedCategory by remember { mutableStateOf(EMOJI_CATEGORIES[0]) }
|
||||
@@ -126,13 +141,19 @@ private fun EmojiPickerContent(
|
||||
var shouldRenderContent by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
android.util.Log.d("EmojiPicker", "🚀 EmojiPickerContent started, keyboardHeight=$keyboardHeight")
|
||||
|
||||
// Ждём 1 кадр чтобы анимация началась плавно
|
||||
kotlinx.coroutines.delay(16) // ~1 frame at 60fps
|
||||
shouldRenderContent = true
|
||||
android.util.Log.d("EmojiPicker", "✅ Content rendering enabled after 16ms delay")
|
||||
|
||||
// Загружаем эмодзи если еще не загружены
|
||||
if (!OptimizedEmojiCache.isLoaded) {
|
||||
android.util.Log.d("EmojiPicker", "📦 Starting emoji preload...")
|
||||
OptimizedEmojiCache.preload(context)
|
||||
} else {
|
||||
android.util.Log.d("EmojiPicker", "✅ Emojis already loaded")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,9 +170,11 @@ private fun EmojiPickerContent(
|
||||
|
||||
// 🚀 При смене категории плавно скроллим наверх
|
||||
LaunchedEffect(selectedCategory) {
|
||||
android.util.Log.d("EmojiPicker", "📂 Category changed: ${selectedCategory.key} (${displayedEmojis.size} emojis)")
|
||||
if (displayedEmojis.isNotEmpty()) {
|
||||
scope.launch {
|
||||
gridState.animateScrollToItem(0)
|
||||
android.util.Log.v("EmojiPicker", "⬆️ Scrolled to top")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -164,7 +187,7 @@ private fun EmojiPickerContent(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(350.dp) // Фиксированная высота как у клавиатуры
|
||||
.height(height = keyboardHeight) // 🔥 Используем сохранённую высоту (как в Telegram)
|
||||
.background(panelBackground)
|
||||
) {
|
||||
// 🔥 Показываем пустую панель пока не готово
|
||||
|
||||
Reference in New Issue
Block a user