Refactor UI components in ChatsListScreen, ForwardChatPickerBottomSheet, and SearchScreen for improved readability and maintainability; adjust text color alpha values, streamline imports, and enhance keyboard handling functionality.

This commit is contained in:
2026-01-17 21:09:47 +05:00
parent c9136ed499
commit a3810af4a0
11 changed files with 3763 additions and 3226 deletions

View File

@@ -18,7 +18,7 @@ android {
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables { useSupportLibrary = true }
// Optimize Lottie animations
manifestPlaceholders["enableLottieOptimizations"] = "true"
}
@@ -93,7 +93,7 @@ dependencies {
// Crypto libraries for key generation
implementation("org.bitcoinj:bitcoinj-core:0.16.2")
implementation("org.bouncycastle:bcprov-jdk15to18:1.77")
// Google Tink for XChaCha20-Poly1305
implementation("com.google.crypto.tink:tink-android:1.10.0")
@@ -121,7 +121,7 @@ dependencies {
testImplementation("io.mockk:mockk:1.13.8")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
testImplementation("androidx.arch.core:core-testing:2.2.0")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation(platform("androidx.compose:compose-bom:2023.10.01"))
@@ -129,3 +129,4 @@ dependencies {
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}
}

164
app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,164 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
# ============================================================
# Firebase Cloud Messaging
# ============================================================
-keep class com.google.firebase.** { *; }
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.firebase.**
-dontwarn com.google.android.gms.**
# Keep FirebaseMessagingService
-keep class * extends com.google.firebase.messaging.FirebaseMessagingService {
*;
}
-keep class com.rosetta.messenger.push.RosettaFirebaseMessagingService { *; }
# Keep notification data models
-keepclassmembers class * {
@com.google.firebase.messaging.RemoteMessage$MessageNotificationKeys <fields>;
}
# ============================================================
# Kotlin & Coroutines
# ============================================================
-keep class kotlinx.coroutines.** { *; }
-dontwarn kotlinx.coroutines.**
# Keep Kotlin metadata
-keep class kotlin.Metadata { *; }
# ============================================================
# Room Database
# ============================================================
-keep class * extends androidx.room.RoomDatabase
-keep @androidx.room.Entity class *
-keepclassmembers class * {
@androidx.room.* <methods>;
}
-keep class com.rosetta.messenger.database.** { *; }
# ============================================================
# Crypto & Security
# ============================================================
# BouncyCastle
-keep class org.bouncycastle.** { *; }
-dontwarn org.bouncycastle.**
# Tink (XChaCha20-Poly1305)
-keep class com.google.crypto.tink.** { *; }
-dontwarn com.google.crypto.tink.**
# BitcoinJ
-keep class org.bitcoinj.** { *; }
-dontwarn org.bitcoinj.**
# Security Crypto
-keep class androidx.security.crypto.** { *; }
-dontwarn androidx.security.crypto.**
# Keep crypto classes
-keep class com.rosetta.messenger.crypto.** { *; }
# ============================================================
# Compose
# ============================================================
-keep class androidx.compose.** { *; }
-dontwarn androidx.compose.**
# Keep @Composable functions
-keepclassmembers class * {
@androidx.compose.runtime.Composable <methods>;
}
# ============================================================
# Data Models
# ============================================================
# Keep all data classes
-keep class com.rosetta.messenger.data.** { *; }
-keep class com.rosetta.messenger.network.** { *; }
# Keep Parcelable
-keepclassmembers class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
# ============================================================
# Serialization
# ============================================================
# Keep serialization info
-keepattributes *Annotation*
-keepattributes Signature
-keepattributes InnerClasses
-keepattributes EnclosingMethod
# Gson
-keep class com.google.gson.** { *; }
-keepclassmembers class * {
@com.google.gson.annotations.SerializedName <fields>;
}
# ============================================================
# AndroidX & Material
# ============================================================
-keep class com.google.android.material.** { *; }
-dontwarn com.google.android.material.**
-keep class androidx.** { *; }
-dontwarn androidx.**
# ============================================================
# Reflection & Native
# ============================================================
-keepattributes RuntimeVisibleAnnotations
-keepattributes RuntimeInvisibleAnnotations
-keepattributes RuntimeVisibleParameterAnnotations
-keepattributes RuntimeInvisibleParameterAnnotations
# Keep native methods
-keepclasseswithmembernames class * {
native <methods>;
}
# ============================================================
# Debugging (remove in production)
# ============================================================
-keepattributes SourceFile,LineNumberTable
-renamesourcefileattribute SourceFile
# ============================================================
# WebSocket (if using OkHttp)
# ============================================================
-dontwarn okhttp3.**
-dontwarn okio.**
-keep class okhttp3.** { *; }
-keep class okio.** { *; }
# ============================================================
# Lottie Animations
# ============================================================
-keep class com.airbnb.lottie.** { *; }
-dontwarn com.airbnb.lottie.**
# ============================================================
# Coil Image Loading
# ============================================================
-keep class coil.** { *; }
-dontwarn coil.**

View File

@@ -13,9 +13,9 @@ import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* Координатор переходов между системной клавиатурой и emoji панелью.
* Реализует Telegram-style плавные анимации.
*
* Координатор переходов между системной клавиатурой и emoji панелью. Реализует Telegram-style
* плавные анимации.
*
* Ключевые принципы:
* - 250ms duration (как в Telegram AdjustPanLayoutHelper)
* - Немедленное резервирование места
@@ -23,249 +23,252 @@ import androidx.compose.ui.unit.dp
* - Синхронизация всех переходов
*/
class KeyboardTransitionCoordinator {
companion object {
const val TRANSITION_DURATION = 250L
const val SHORT_DELAY = 50L
private const val TAG = "KeyboardTransition"
}
// ============ Состояния переходов ============
enum class TransitionState {
IDLE, // Ничего не происходит
KEYBOARD_TO_EMOJI, // Keyboard → Emoji
EMOJI_TO_KEYBOARD, // Emoji → Keyboard
KEYBOARD_OPENING, // Только keyboard открывается
EMOJI_OPENING, // Только emoji открывается
KEYBOARD_CLOSING, // Только keyboard закрывается
EMOJI_CLOSING // Только emoji закрывается
IDLE, // Ничего не происходит
KEYBOARD_TO_EMOJI, // Keyboard → Emoji
EMOJI_TO_KEYBOARD, // Emoji → Keyboard
KEYBOARD_OPENING, // Только keyboard открывается
EMOJI_OPENING, // Только emoji открывается
KEYBOARD_CLOSING, // Только keyboard закрывается
EMOJI_CLOSING // Только emoji закрывается
}
// ============ Основное состояние ============
var currentState by mutableStateOf(TransitionState.IDLE)
private set
var transitionProgress by mutableFloatStateOf(0f)
private set
// ============ Высоты ============
var keyboardHeight by mutableStateOf(0.dp)
var emojiHeight by mutableStateOf(0.dp)
// 🔥 Сохраняем максимальную высоту клавиатуры для правильного восстановления emoji
private var maxKeyboardHeight by mutableStateOf(0.dp)
// ============ Флаги видимости ============
var isKeyboardVisible by mutableStateOf(false)
var isEmojiVisible by mutableStateOf(false)
var isTransitioning by mutableStateOf(false)
private set
// 🔥 Показывается ли сейчас Box с эмодзи (включая анимацию fade-out)
// Используется для отключения imePadding пока Box виден
var isEmojiBoxVisible by mutableStateOf(false)
// 🔥 Коллбэк для показа emoji (сохраняем для вызова после закрытия клавиатуры)
private var pendingShowEmojiCallback: (() -> Unit)? = null
// 📊 Для умного логирования (не каждый фрейм)
private var lastLogTime = 0L
private var lastLoggedHeight = -1f
/**
* Переход от системной клавиатуры к emoji панели.
*
* 🔥 КЛЮЧЕВОЕ ИЗМЕНЕНИЕ: Показываем emoji СРАЗУ!
* Не ждем закрытия клавиатуры - emoji начинает выезжать синхронно.
*
* 🔥 КЛЮЧЕВОЕ ИЗМЕНЕНИЕ: Показываем emoji СРАЗУ! Не ждем закрытия клавиатуры - emoji начинает
* выезжать синхронно.
*/
fun requestShowEmoji(
hideKeyboard: () -> Unit,
showEmoji: () -> Unit
) {
fun requestShowEmoji(hideKeyboard: () -> Unit, showEmoji: () -> Unit) {
currentState = TransitionState.KEYBOARD_TO_EMOJI
isTransitioning = true
// 🔥 Гарантируем что emojiHeight = maxKeyboardHeight (не меняется при закрытии клавиатуры)
if (maxKeyboardHeight > 0.dp) {
emojiHeight = maxKeyboardHeight
}
// 🔥 ПОКАЗЫВАЕМ EMOJI СРАЗУ! Не ждем закрытия клавиатуры
showEmoji()
isEmojiVisible = true // 🔥 ВАЖНО: Устанавливаем флаг видимости emoji!
// Теперь скрываем клавиатуру (она будет закрываться синхронно с появлением emoji)
Log.d(TAG, " ⌨️ Hiding keyboard...")
try {
hideKeyboard()
Log.d(TAG, " ✅ hideKeyboard() completed")
} catch (e: Exception) {
}
} catch (e: Exception) {}
isKeyboardVisible = false
currentState = TransitionState.IDLE
isTransitioning = false
// Очищаем pending callback - больше не нужен
pendingShowEmojiCallback = null
}
// ============ Главный метод: Emoji → Keyboard ============
/**
* Переход от emoji панели к системной клавиатуре.
* Telegram паттерн: показать клавиатуру и плавно скрыть emoji.
* Переход от emoji панели к системной клавиатуре. Telegram паттерн: показать клавиатуру и
* плавно скрыть emoji.
*/
fun requestShowKeyboard(
showKeyboard: () -> Unit,
hideEmoji: () -> Unit
) {
fun requestShowKeyboard(showKeyboard: () -> Unit, hideEmoji: () -> Unit) {
// 🔥 Отменяем pending emoji callback если он есть (предотвращаем конфликт)
if (pendingShowEmojiCallback != null) {
pendingShowEmojiCallback = null
}
currentState = TransitionState.EMOJI_TO_KEYBOARD
isTransitioning = true
// Шаг 1: Показать системную клавиатуру
try {
showKeyboard()
} catch (e: Exception) {
}
} catch (e: Exception) {}
// Шаг 2: Через небольшую задержку скрыть emoji
Handler(Looper.getMainLooper()).postDelayed({
try {
hideEmoji()
isEmojiVisible = false
isKeyboardVisible = true
// Через время анимации завершаем переход
Handler(Looper.getMainLooper()).postDelayed({
currentState = TransitionState.IDLE
isTransitioning = false
}, TRANSITION_DURATION)
} catch (e: Exception) {
currentState = TransitionState.IDLE
isTransitioning = false
}
}, SHORT_DELAY)
Handler(Looper.getMainLooper())
.postDelayed(
{
try {
hideEmoji()
isEmojiVisible = false
isKeyboardVisible = true
// Через время анимации завершаем переход
Handler(Looper.getMainLooper())
.postDelayed(
{
currentState = TransitionState.IDLE
isTransitioning = false
},
TRANSITION_DURATION
)
} catch (e: Exception) {
currentState = TransitionState.IDLE
isTransitioning = false
}
},
SHORT_DELAY
)
}
// ============ Простые переходы ============
/**
* Открыть только emoji панель (без клавиатуры).
*/
/** Открыть только emoji панель (без клавиатуры). */
fun openEmojiOnly(showEmoji: () -> Unit) {
currentState = TransitionState.EMOJI_OPENING
isTransitioning = true
// Установить высоту emoji равной сохраненной высоте клавиатуры
if (emojiHeight == 0.dp && keyboardHeight > 0.dp) {
emojiHeight = keyboardHeight
}
showEmoji()
isEmojiVisible = true
Handler(Looper.getMainLooper()).postDelayed({
currentState = TransitionState.IDLE
isTransitioning = false
}, TRANSITION_DURATION)
Handler(Looper.getMainLooper())
.postDelayed(
{
currentState = TransitionState.IDLE
isTransitioning = false
},
TRANSITION_DURATION
)
}
/**
* Закрыть emoji панель.
*/
/** Закрыть emoji панель. */
fun closeEmoji(hideEmoji: () -> Unit) {
currentState = TransitionState.EMOJI_CLOSING
isTransitioning = true
hideEmoji()
isEmojiVisible = false
Handler(Looper.getMainLooper()).postDelayed({
currentState = TransitionState.IDLE
isTransitioning = false
}, TRANSITION_DURATION)
Handler(Looper.getMainLooper())
.postDelayed(
{
currentState = TransitionState.IDLE
isTransitioning = false
},
TRANSITION_DURATION
)
}
/**
* Закрыть системную клавиатуру.
*/
/** Закрыть системную клавиатуру. */
fun closeKeyboard(hideKeyboard: () -> Unit) {
currentState = TransitionState.KEYBOARD_CLOSING
isTransitioning = true
hideKeyboard()
isKeyboardVisible = false
Handler(Looper.getMainLooper()).postDelayed({
currentState = TransitionState.IDLE
isTransitioning = false
}, TRANSITION_DURATION)
Handler(Looper.getMainLooper())
.postDelayed(
{
currentState = TransitionState.IDLE
isTransitioning = false
},
TRANSITION_DURATION
)
}
// ============ Вспомогательные методы ============
/**
* Обновить высоту клавиатуры из IME.
*/
/** Обновить высоту клавиатуры из IME. */
fun updateKeyboardHeight(height: Dp) {
val now = System.currentTimeMillis()
val heightChanged = kotlin.math.abs(height.value - lastLoggedHeight) > 5f
// Логируем раз в 50ms ИЛИ при значительном изменении высоты (>5dp)
if (heightChanged && (now - lastLogTime > 50 || lastLoggedHeight < 0)) {
lastLogTime = now
lastLoggedHeight = height.value
}
if (height > 100.dp && height != keyboardHeight) {
keyboardHeight = height
// 🔥 Сохраняем максимальную высоту
if (height > maxKeyboardHeight) {
maxKeyboardHeight = height
}
// Если emoji высота не установлена, синхронизировать
if (emojiHeight == 0.dp) {
emojiHeight = height
}
} else if (height == 0.dp && keyboardHeight != 0.dp) {
// 🔥 Клавиатура закрывается - восстанавливаем emojiHeight до МАКСИМАЛЬНОЙ высоты
// Восстанавливаем emojiHeight до максимальной высоты
if (maxKeyboardHeight > 0.dp) {
emojiHeight = maxKeyboardHeight
}
// Обнуляем keyboardHeight
keyboardHeight = 0.dp
}
// 🔥 УБРАН pending callback - теперь emoji показывается сразу в requestShowEmoji()
}
/**
* Обновить высоту emoji панели.
*/
/** Обновить высоту emoji панели. */
fun updateEmojiHeight(height: Dp) {
if (height > 0.dp && height != emojiHeight) {
emojiHeight = height
}
}
/**
* Синхронизировать высоты (emoji = keyboard).
*
* 🔥 ВАЖНО: Синхронизируем ТОЛЬКО когда клавиатура ОТКРЫВАЕТСЯ!
* При закрытии клавиатуры emojiHeight должна оставаться фиксированной!
*
* 🔥 ВАЖНО: Синхронизируем ТОЛЬКО когда клавиатура ОТКРЫВАЕТСЯ! При закрытии клавиатуры
* emojiHeight должна оставаться фиксированной!
*/
fun syncHeights() {
// 🔥 Синхронизируем ТОЛЬКО если клавиатура ОТКРЫТА и высота больше текущей emoji
@@ -273,10 +276,10 @@ class KeyboardTransitionCoordinator {
emojiHeight = keyboardHeight
}
}
/**
* Инициализация высоты emoji панели (для pre-rendered подхода).
* Должна быть вызвана при старте для избежания 0dp высоты.
* Инициализация высоты emoji панели (для pre-rendered подхода). Должна быть вызвана при старте
* для избежания 0dp высоты.
*/
fun initializeEmojiHeight(height: Dp) {
if (emojiHeight == 0.dp && height > 0.dp) {
@@ -284,10 +287,10 @@ class KeyboardTransitionCoordinator {
maxKeyboardHeight = height
}
}
/**
* Получить текущую высоту для резервирования места.
* Telegram паттерн: всегда резервировать максимум из двух.
* Получить текущую высоту для резервирования места. Telegram паттерн: всегда резервировать
* максимум из двух.
*/
fun getReservedHeight(): Dp {
return when {
@@ -297,17 +300,13 @@ class KeyboardTransitionCoordinator {
else -> 0.dp
}
}
/**
* Проверка, можно ли начать новый переход.
*/
/** Проверка, можно ли начать новый переход. */
fun canStartTransition(): Boolean {
return !isTransitioning
}
/**
* Сброс состояния (для отладки).
*/
/** Сброс состояния (для отладки). */
fun reset() {
currentState = TransitionState.IDLE
isTransitioning = false
@@ -315,17 +314,12 @@ class KeyboardTransitionCoordinator {
isEmojiVisible = false
transitionProgress = 0f
}
/**
* Логирование текущего состояния.
*/
fun logState() {
}
/** Логирование текущего состояния. */
fun logState() {}
}
/**
* Composable для создания и запоминания coordinator'а.
*/
/** Composable для создания и запоминания coordinator'а. */
@Composable
fun rememberKeyboardTransitionCoordinator(): KeyboardTransitionCoordinator {
return remember { KeyboardTransitionCoordinator() }

View File

@@ -350,7 +350,7 @@ fun MainScreen(
onToggleTheme: () -> Unit = {},
onLogout: () -> Unit = {}
) {
val accountName = account?.publicKey ?: "04c266b98ae5"
val accountName = account?.name ?: "Account"
val accountPhone = account?.publicKey?.take(16)?.let {
"+${it.take(1)} ${it.substring(1, 4)} ${it.substring(4, 7)}${it.substring(7)}"
} ?: "+7 775 9932587"

View File

@@ -5,7 +5,6 @@ import androidx.compose.animation.core.*
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
@@ -35,21 +34,38 @@ import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SetPasswordScreen(
seedPhrase: List<String>,
isDarkTheme: Boolean,
onBack: () -> Unit,
onAccountCreated: (DecryptedAccount) -> Unit
seedPhrase: List<String>,
isDarkTheme: Boolean,
onBack: () -> Unit,
onAccountCreated: (DecryptedAccount) -> Unit
) {
val themeAnimSpec = tween<Color>(durationMillis = 500, easing = CubicBezierEasing(0.4f, 0f, 0.2f, 1f))
val backgroundColor by animateColorAsState(if (isDarkTheme) AuthBackground else AuthBackgroundLight, animationSpec = themeAnimSpec)
val textColor by animateColorAsState(if (isDarkTheme) Color.White else Color.Black, animationSpec = themeAnimSpec)
val secondaryTextColor by animateColorAsState(if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666), animationSpec = themeAnimSpec)
val cardColor by animateColorAsState(if (isDarkTheme) AuthSurface else AuthSurfaceLight, animationSpec = themeAnimSpec)
val themeAnimSpec =
tween<Color>(durationMillis = 500, easing = CubicBezierEasing(0.4f, 0f, 0.2f, 1f))
val backgroundColor by
animateColorAsState(
if (isDarkTheme) AuthBackground else AuthBackgroundLight,
animationSpec = themeAnimSpec
)
val textColor by
animateColorAsState(
if (isDarkTheme) Color.White else Color.Black,
animationSpec = themeAnimSpec
)
val secondaryTextColor by
animateColorAsState(
if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666),
animationSpec = themeAnimSpec
)
val cardColor by
animateColorAsState(
if (isDarkTheme) AuthSurface else AuthSurfaceLight,
animationSpec = themeAnimSpec
)
val context = LocalContext.current
val accountManager = remember { AccountManager(context) }
val scope = rememberCoroutineScope()
var password by remember { mutableStateOf("") }
var confirmPassword by remember { mutableStateOf("") }
var passwordVisible by remember { mutableStateOf(false) }
@@ -57,492 +73,540 @@ fun SetPasswordScreen(
var isCreating by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
var visible by remember { mutableStateOf(false) }
// Track keyboard visibility
val view = androidx.compose.ui.platform.LocalView.current
var isKeyboardVisible by remember { mutableStateOf(false) }
DisposableEffect(view) {
val listener = android.view.ViewTreeObserver.OnGlobalLayoutListener {
val rect = android.graphics.Rect()
view.getWindowVisibleDisplayFrame(rect)
val screenHeight = view.rootView.height
val keypadHeight = screenHeight - rect.bottom
isKeyboardVisible = keypadHeight > screenHeight * 0.15
}
val listener =
android.view.ViewTreeObserver.OnGlobalLayoutListener {
val rect = android.graphics.Rect()
view.getWindowVisibleDisplayFrame(rect)
val screenHeight = view.rootView.height
val keypadHeight = screenHeight - rect.bottom
isKeyboardVisible = keypadHeight > screenHeight * 0.15
}
view.viewTreeObserver.addOnGlobalLayoutListener(listener)
onDispose {
view.viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
onDispose { view.viewTreeObserver.removeOnGlobalLayoutListener(listener) }
}
LaunchedEffect(Unit) {
visible = true
}
LaunchedEffect(Unit) { visible = true }
val passwordsMatch = password == confirmPassword && password.isNotEmpty()
val isPasswordWeak = password.isNotEmpty() && password.length < 6
val canContinue = passwordsMatch && !isCreating
Box(
modifier = Modifier
.fillMaxSize()
.background(backgroundColor)
) {
Column(
modifier = Modifier
.fillMaxSize()
.statusBarsPadding()
) {
Box(modifier = Modifier.fillMaxSize().background(backgroundColor)) {
Column(modifier = Modifier.fillMaxSize().statusBarsPadding()) {
// Top Bar
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = onBack, enabled = !isCreating) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "Back",
tint = textColor.copy(alpha = 0.6f)
imageVector = Icons.Default.ArrowBack,
contentDescription = "Back",
tint = textColor.copy(alpha = 0.6f)
)
}
Spacer(modifier = Modifier.weight(1f))
Text(
text = "Set Password",
fontSize = 18.sp,
fontWeight = FontWeight.SemiBold,
color = textColor
text = "Set Password",
fontSize = 18.sp,
fontWeight = FontWeight.SemiBold,
color = textColor
)
Spacer(modifier = Modifier.weight(1f))
Spacer(modifier = Modifier.width(48.dp))
}
Column(
modifier = Modifier
.fillMaxSize()
.imePadding()
.padding(horizontal = 24.dp)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
modifier =
Modifier.fillMaxSize()
.imePadding()
.padding(horizontal = 24.dp)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(if (isKeyboardVisible) 8.dp else 16.dp))
// Lock Icon - smaller when keyboard is visible
val iconSize by animateDpAsState(
targetValue = if (isKeyboardVisible) 48.dp else 80.dp,
animationSpec = tween(300, easing = FastOutSlowInEasing)
)
val iconInnerSize by animateDpAsState(
targetValue = if (isKeyboardVisible) 24.dp else 40.dp,
animationSpec = tween(300, easing = FastOutSlowInEasing)
)
val iconSize by
animateDpAsState(
targetValue = if (isKeyboardVisible) 48.dp else 80.dp,
animationSpec = tween(300, easing = FastOutSlowInEasing)
)
val iconInnerSize by
animateDpAsState(
targetValue = if (isKeyboardVisible) 24.dp else 40.dp,
animationSpec = tween(300, easing = FastOutSlowInEasing)
)
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(500)) + scaleIn(
initialScale = 0.5f,
animationSpec = tween(500, easing = FastOutSlowInEasing)
)
visible = visible,
enter =
fadeIn(tween(500)) +
scaleIn(
initialScale = 0.5f,
animationSpec =
tween(500, easing = FastOutSlowInEasing)
)
) {
Box(
modifier = Modifier
.size(iconSize)
.clip(RoundedCornerShape(if (isKeyboardVisible) 12.dp else 20.dp))
.background(PrimaryBlue.copy(alpha = 0.1f)),
contentAlignment = Alignment.Center
modifier =
Modifier.size(iconSize)
.clip(
RoundedCornerShape(
if (isKeyboardVisible) 12.dp else 20.dp
)
)
.background(PrimaryBlue.copy(alpha = 0.1f)),
contentAlignment = Alignment.Center
) {
Icon(
Icons.Default.Lock,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(iconInnerSize)
Icons.Default.Lock,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(iconInnerSize)
)
}
}
Spacer(modifier = Modifier.height(if (isKeyboardVisible) 12.dp else 24.dp))
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(500, delayMillis = 100)) + slideInVertically(
initialOffsetY = { -20 },
animationSpec = tween(500, delayMillis = 100)
)
visible = visible,
enter =
fadeIn(tween(500, delayMillis = 100)) +
slideInVertically(
initialOffsetY = { -20 },
animationSpec = tween(500, delayMillis = 100)
)
) {
Text(
text = "Protect Your Account",
fontSize = if (isKeyboardVisible) 20.sp else 24.sp,
fontWeight = FontWeight.Bold,
color = textColor
text = "Protect Your Account",
fontSize = if (isKeyboardVisible) 20.sp else 24.sp,
fontWeight = FontWeight.Bold,
color = textColor
)
}
Spacer(modifier = Modifier.height(if (isKeyboardVisible) 6.dp else 8.dp))
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(500, delayMillis = 200))
visible = visible,
enter = fadeIn(tween(500, delayMillis = 200))
) {
Text(
text = "This password encrypts your keys locally.\nYou'll need it to unlock Rosetta.",
fontSize = if (isKeyboardVisible) 12.sp else 14.sp,
color = secondaryTextColor,
textAlign = TextAlign.Center,
lineHeight = if (isKeyboardVisible) 16.sp else 20.sp
text =
"This password encrypts your keys locally.\nYou'll need it to unlock Rosetta.",
fontSize = if (isKeyboardVisible) 12.sp else 14.sp,
color = secondaryTextColor,
textAlign = TextAlign.Center,
lineHeight = if (isKeyboardVisible) 16.sp else 20.sp
)
}
Spacer(modifier = Modifier.height(if (isKeyboardVisible) 16.dp else 32.dp))
// Password Field
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(500, delayMillis = 300)) + slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(500, delayMillis = 300)
)
visible = visible,
enter =
fadeIn(tween(500, delayMillis = 300)) +
slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(500, delayMillis = 300)
)
) {
OutlinedTextField(
value = password,
onValueChange = {
password = it
error = null
},
label = { Text("Password") },
placeholder = { Text("Enter password") },
singleLine = true,
visualTransformation = if (passwordVisible)
VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
IconButton(onClick = { passwordVisible = !passwordVisible }) {
Icon(
imageVector = if (passwordVisible)
Icons.Default.VisibilityOff else Icons.Default.Visibility,
contentDescription = if (passwordVisible) "Hide" else "Show"
)
}
},
colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = PrimaryBlue,
unfocusedBorderColor = if (isDarkTheme) Color(0xFF4A4A4A) else Color(0xFFD0D0D0),
focusedLabelColor = PrimaryBlue,
cursorColor = PrimaryBlue,
focusedTextColor = textColor,
unfocusedTextColor = textColor
),
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Next
value = password,
onValueChange = {
password = it
error = null
},
label = { Text("Password") },
placeholder = { Text("Enter password") },
singleLine = true,
visualTransformation =
if (passwordVisible) VisualTransformation.None
else PasswordVisualTransformation(),
trailingIcon = {
IconButton(onClick = { passwordVisible = !passwordVisible }) {
Icon(
imageVector =
if (passwordVisible) Icons.Default.VisibilityOff
else Icons.Default.Visibility,
contentDescription =
if (passwordVisible) "Hide" else "Show"
)
}
},
colors =
OutlinedTextFieldDefaults.colors(
focusedBorderColor = PrimaryBlue,
unfocusedBorderColor =
if (isDarkTheme) Color(0xFF4A4A4A)
else Color(0xFFD0D0D0),
focusedLabelColor = PrimaryBlue,
cursorColor = PrimaryBlue,
focusedTextColor = textColor,
unfocusedTextColor = textColor
),
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp),
keyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Next
)
)
)
}
// Password strength indicator
if (password.isNotEmpty()) {
Spacer(modifier = Modifier.height(8.dp))
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(400, delayMillis = 350)) + slideInHorizontally(
initialOffsetX = { -30 },
animationSpec = tween(400, delayMillis = 350)
)
visible = visible,
enter =
fadeIn(tween(400, delayMillis = 350)) +
slideInHorizontally(
initialOffsetX = { -30 },
animationSpec = tween(400, delayMillis = 350)
)
) {
Column(modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
val strength = when {
password.length < 6 -> "Weak"
password.length < 10 -> "Medium"
else -> "Strong"
}
val strengthColor = when {
password.length < 6 -> Color(0xFFE53935)
password.length < 10 -> Color(0xFFFFA726)
else -> Color(0xFF4CAF50)
}
val strength =
when {
password.length < 6 -> "Weak"
password.length < 10 -> "Medium"
else -> "Strong"
}
val strengthColor =
when {
password.length < 6 -> Color(0xFFE53935)
password.length < 10 -> Color(0xFFFFA726)
else -> Color(0xFF4CAF50)
}
Icon(
imageVector = Icons.Default.Shield,
contentDescription = null,
tint = strengthColor,
modifier = Modifier.size(16.dp)
imageVector = Icons.Default.Shield,
contentDescription = null,
tint = strengthColor,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "Password strength: $strength",
fontSize = 12.sp,
color = strengthColor
text = "Password strength: $strength",
fontSize = 12.sp,
color = strengthColor
)
}
// Warning for weak passwords
if (isPasswordWeak) {
Spacer(modifier = Modifier.height(4.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(8.dp))
.background(Color(0xFFE53935).copy(alpha = 0.1f))
.padding(8.dp),
verticalAlignment = Alignment.Top
modifier =
Modifier.fillMaxWidth()
.clip(RoundedCornerShape(8.dp))
.background(
Color(0xFFE53935).copy(alpha = 0.1f)
)
.padding(8.dp),
verticalAlignment = Alignment.Top
) {
Icon(
imageVector = Icons.Default.Warning,
contentDescription = null,
tint = Color(0xFFE53935),
modifier = Modifier.size(16.dp)
imageVector = Icons.Default.Warning,
contentDescription = null,
tint = Color(0xFFE53935),
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Your password is too weak. Consider using at least 6 characters for better security.",
fontSize = 11.sp,
color = Color(0xFFE53935),
lineHeight = 14.sp
text =
"Your password is too weak. Consider using at least 6 characters for better security.",
fontSize = 11.sp,
color = Color(0xFFE53935),
lineHeight = 14.sp
)
}
}
}
}
}
Spacer(modifier = Modifier.height(16.dp))
// Confirm Password Field
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(500, delayMillis = 400)) + slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(500, delayMillis = 400)
)
visible = visible,
enter =
fadeIn(tween(500, delayMillis = 400)) +
slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(500, delayMillis = 400)
)
) {
OutlinedTextField(
value = confirmPassword,
onValueChange = {
confirmPassword = it
error = null
},
label = { Text("Confirm Password") },
placeholder = { Text("Re-enter password") },
singleLine = true,
visualTransformation = if (confirmPasswordVisible)
VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
IconButton(onClick = { confirmPasswordVisible = !confirmPasswordVisible }) {
Icon(
imageVector = if (confirmPasswordVisible)
Icons.Default.VisibilityOff else Icons.Default.Visibility,
contentDescription = if (confirmPasswordVisible) "Hide" else "Show"
)
}
},
isError = confirmPassword.isNotEmpty() && !passwordsMatch,
colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = PrimaryBlue,
unfocusedBorderColor = if (isDarkTheme) Color(0xFF4A4A4A) else Color(0xFFD0D0D0),
focusedLabelColor = PrimaryBlue,
cursorColor = PrimaryBlue,
focusedTextColor = textColor,
unfocusedTextColor = textColor
),
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done
value = confirmPassword,
onValueChange = {
confirmPassword = it
error = null
},
label = { Text("Confirm Password") },
placeholder = { Text("Re-enter password") },
singleLine = true,
visualTransformation =
if (confirmPasswordVisible) VisualTransformation.None
else PasswordVisualTransformation(),
trailingIcon = {
IconButton(
onClick = {
confirmPasswordVisible = !confirmPasswordVisible
}
) {
Icon(
imageVector =
if (confirmPasswordVisible)
Icons.Default.VisibilityOff
else Icons.Default.Visibility,
contentDescription =
if (confirmPasswordVisible) "Hide" else "Show"
)
}
},
isError = confirmPassword.isNotEmpty() && !passwordsMatch,
colors =
OutlinedTextFieldDefaults.colors(
focusedBorderColor = PrimaryBlue,
unfocusedBorderColor =
if (isDarkTheme) Color(0xFF4A4A4A)
else Color(0xFFD0D0D0),
focusedLabelColor = PrimaryBlue,
cursorColor = PrimaryBlue,
focusedTextColor = textColor,
unfocusedTextColor = textColor
),
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp),
keyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done
)
)
)
}
// Match indicator
if (confirmPassword.isNotEmpty()) {
Spacer(modifier = Modifier.height(8.dp))
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(400, delayMillis = 450)) + slideInHorizontally(
initialOffsetX = { -30 },
animationSpec = tween(400, delayMillis = 450)
)
visible = visible,
enter =
fadeIn(tween(400, delayMillis = 450)) +
slideInHorizontally(
initialOffsetX = { -30 },
animationSpec = tween(400, delayMillis = 450)
)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
val matchIcon = if (passwordsMatch) Icons.Default.Check else Icons.Default.Close
val matchColor = if (passwordsMatch) Color(0xFF4CAF50) else Color(0xFFE53935)
val matchText = if (passwordsMatch) "Passwords match" else "Passwords don't match"
val matchIcon =
if (passwordsMatch) Icons.Default.Check else Icons.Default.Close
val matchColor =
if (passwordsMatch) Color(0xFF4CAF50) else Color(0xFFE53935)
val matchText =
if (passwordsMatch) "Passwords match"
else "Passwords don't match"
Icon(
imageVector = matchIcon,
contentDescription = null,
tint = matchColor,
modifier = Modifier.size(16.dp)
imageVector = matchIcon,
contentDescription = null,
tint = matchColor,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = matchText,
fontSize = 12.sp,
color = matchColor
)
}
Text(text = matchText, fontSize = 12.sp, color = matchColor)
}
}
}
// Error message
error?.let { errorMsg ->
Spacer(modifier = Modifier.height(16.dp))
AnimatedVisibility(
visible = true,
enter = fadeIn(tween(300)) + scaleIn(initialScale = 0.9f)
visible = true,
enter = fadeIn(tween(300)) + scaleIn(initialScale = 0.9f)
) {
Text(
text = errorMsg,
fontSize = 14.sp,
color = Color(0xFFE53935),
textAlign = TextAlign.Center
text = errorMsg,
fontSize = 14.sp,
color = Color(0xFFE53935),
textAlign = TextAlign.Center
)
}
}
Spacer(modifier = Modifier.weight(1f))
// Info - hide when keyboard is visible
AnimatedVisibility(
visible = visible && !isKeyboardVisible,
enter = fadeIn(tween(400)) + slideInVertically(
initialOffsetY = { 30 },
animationSpec = tween(400)
) + scaleIn(
initialScale = 0.9f,
animationSpec = tween(400)
),
exit = fadeOut(tween(300)) + slideOutVertically(
targetOffsetY = { 30 },
animationSpec = tween(300)
) + scaleOut(
targetScale = 0.9f,
animationSpec = tween(300)
)
visible = visible && !isKeyboardVisible,
enter =
fadeIn(tween(400)) +
slideInVertically(
initialOffsetY = { 30 },
animationSpec = tween(400)
) +
scaleIn(initialScale = 0.9f, animationSpec = tween(400)),
exit =
fadeOut(tween(300)) +
slideOutVertically(
targetOffsetY = { 30 },
animationSpec = tween(300)
) +
scaleOut(targetScale = 0.9f, animationSpec = tween(300))
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.background(cardColor)
.padding(16.dp),
verticalAlignment = Alignment.Top
modifier =
Modifier.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.background(cardColor)
.padding(16.dp),
verticalAlignment = Alignment.Top
) {
Icon(
imageVector = Icons.Default.Info,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(20.dp)
imageVector = Icons.Default.Info,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(20.dp)
)
Spacer(modifier = Modifier.width(12.dp))
Text(
text = "Your password is never stored or sent anywhere. It's only used to encrypt your keys locally.",
fontSize = 13.sp,
color = secondaryTextColor,
lineHeight = 18.sp
text =
"Your password is never stored or sent anywhere. It's only used to encrypt your keys locally.",
fontSize = 13.sp,
color = secondaryTextColor,
lineHeight = 18.sp
)
}
}
Spacer(modifier = Modifier.height(16.dp))
// Create Account Button
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(500, delayMillis = 600)) + slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(500, delayMillis = 600)
)
visible = visible,
enter =
fadeIn(tween(500, delayMillis = 600)) +
slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(500, delayMillis = 600)
)
) {
Button(
onClick = {
if (!passwordsMatch) {
error = "Passwords don't match"
return@Button
onClick = {
if (!passwordsMatch) {
error = "Passwords don't match"
return@Button
}
isCreating = true
scope.launch {
try {
// Generate keys from seed phrase
val keyPair =
CryptoManager.generateKeyPairFromSeed(seedPhrase)
// Encrypt private key and seed phrase
val encryptedPrivateKey =
CryptoManager.encryptWithPassword(
keyPair.privateKey,
password
)
val encryptedSeedPhrase =
CryptoManager.encryptWithPassword(
seedPhrase.joinToString(" "),
password
)
// Save account with truncated public key as name
val truncatedKey =
"${keyPair.publicKey.take(6)}...${keyPair.publicKey.takeLast(4)}"
val account =
EncryptedAccount(
publicKey = keyPair.publicKey,
encryptedPrivateKey = encryptedPrivateKey,
encryptedSeedPhrase = encryptedSeedPhrase,
name = truncatedKey
)
accountManager.saveAccount(account)
accountManager.setCurrentAccount(keyPair.publicKey)
// 🔌 Connect to server and authenticate
val privateKeyHash =
CryptoManager.generatePrivateKeyHash(
keyPair.privateKey
)
ProtocolManager.connect()
// Give WebSocket time to connect before authenticating
kotlinx.coroutines.delay(500)
ProtocolManager.authenticate(
keyPair.publicKey,
privateKeyHash
)
// Create DecryptedAccount to pass to callback
val decryptedAccount =
DecryptedAccount(
publicKey = keyPair.publicKey,
privateKey = keyPair.privateKey,
seedPhrase = seedPhrase,
privateKeyHash = privateKeyHash,
name = truncatedKey
)
onAccountCreated(decryptedAccount)
} catch (e: Exception) {
error = "Failed to create account: ${e.message}"
isCreating = false
}
}
},
enabled = canContinue,
modifier = Modifier.fillMaxWidth().height(56.dp),
colors =
ButtonDefaults.buttonColors(
containerColor = PrimaryBlue,
contentColor = Color.White,
disabledContainerColor = PrimaryBlue.copy(alpha = 0.5f),
disabledContentColor = Color.White.copy(alpha = 0.5f)
),
shape = RoundedCornerShape(12.dp)
) {
if (isCreating) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
color = Color.White,
strokeWidth = 2.dp
)
} else {
Text(
text = "Create Account",
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold
)
}
isCreating = true
scope.launch {
try {
// Generate keys from seed phrase
val keyPair = CryptoManager.generateKeyPairFromSeed(seedPhrase)
// Encrypt private key and seed phrase
val encryptedPrivateKey = CryptoManager.encryptWithPassword(
keyPair.privateKey, password
)
val encryptedSeedPhrase = CryptoManager.encryptWithPassword(
seedPhrase.joinToString(" "), password
)
// Save account with truncated public key as name
val truncatedKey = "${keyPair.publicKey.take(6)}...${keyPair.publicKey.takeLast(4)}"
val account = EncryptedAccount(
publicKey = keyPair.publicKey,
encryptedPrivateKey = encryptedPrivateKey,
encryptedSeedPhrase = encryptedSeedPhrase,
name = truncatedKey
)
accountManager.saveAccount(account)
accountManager.setCurrentAccount(keyPair.publicKey)
// 🔌 Connect to server and authenticate
val privateKeyHash = CryptoManager.generatePrivateKeyHash(keyPair.privateKey)
ProtocolManager.connect()
// Give WebSocket time to connect before authenticating
kotlinx.coroutines.delay(500)
ProtocolManager.authenticate(keyPair.publicKey, privateKeyHash)
// Create DecryptedAccount to pass to callback
val decryptedAccount = DecryptedAccount(
publicKey = keyPair.publicKey,
privateKey = keyPair.privateKey,
seedPhrase = seedPhrase,
privateKeyHash = privateKeyHash,
name = truncatedKey
)
onAccountCreated(decryptedAccount)
} catch (e: Exception) {
error = "Failed to create account: ${e.message}"
isCreating = false
}
}
},
enabled = canContinue,
modifier = Modifier
.fillMaxWidth()
.height(56.dp),
colors = ButtonDefaults.buttonColors(
containerColor = PrimaryBlue,
contentColor = Color.White,
disabledContainerColor = PrimaryBlue.copy(alpha = 0.5f),
disabledContentColor = Color.White.copy(alpha = 0.5f)
),
shape = RoundedCornerShape(12.dp)
) {
if (isCreating) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
color = Color.White,
strokeWidth = 2.dp
)
} else {
Text(
text = "Create Account",
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold
)
}
} }
}
Spacer(modifier = Modifier.height(32.dp))
}
}

View File

@@ -3,7 +3,6 @@ package com.rosetta.messenger.ui.auth
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -14,7 +13,6 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
@@ -24,7 +22,6 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.*
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
// Auth colors
val AuthBackground = Color(0xFF1B1B1B)
@@ -34,229 +31,232 @@ val AuthSurfaceLight = Color(0xFFF5F5F5)
@Composable
fun WelcomeScreen(
isDarkTheme: Boolean,
hasExistingAccount: Boolean = false,
onBack: () -> Unit = {},
onCreateSeed: () -> Unit,
onImportSeed: () -> Unit
isDarkTheme: Boolean,
hasExistingAccount: Boolean = false,
onBack: () -> Unit = {},
onCreateSeed: () -> Unit,
onImportSeed: () -> Unit
) {
val themeAnimSpec = tween<Color>(durationMillis = 500, easing = CubicBezierEasing(0.4f, 0f, 0.2f, 1f))
val backgroundColor by animateColorAsState(if (isDarkTheme) AuthBackground else AuthBackgroundLight, animationSpec = themeAnimSpec)
val textColor by animateColorAsState(if (isDarkTheme) Color.White else Color.Black, animationSpec = themeAnimSpec)
val secondaryTextColor by animateColorAsState(if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666), animationSpec = themeAnimSpec)
val themeAnimSpec =
tween<Color>(durationMillis = 500, easing = CubicBezierEasing(0.4f, 0f, 0.2f, 1f))
val backgroundColor by
animateColorAsState(
if (isDarkTheme) AuthBackground else AuthBackgroundLight,
animationSpec = themeAnimSpec
)
val textColor by
animateColorAsState(
if (isDarkTheme) Color.White else Color.Black,
animationSpec = themeAnimSpec
)
val secondaryTextColor by
animateColorAsState(
if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666),
animationSpec = themeAnimSpec
)
// Sync navigation bar color with background
val view = LocalView.current
SideEffect {
val window = (view.context as? android.app.Activity)?.window
window?.navigationBarColor = backgroundColor.toArgb()
}
// Animation for Lottie
val lockComposition by rememberLottieComposition(LottieCompositionSpec.Asset("lottie/lock.json"))
val lockProgress by animateLottieCompositionAsState(
composition = lockComposition,
iterations = 1, // Play once
speed = 1f
)
val lockComposition by
rememberLottieComposition(LottieCompositionSpec.Asset("lottie/lock.json"))
val lockProgress by
animateLottieCompositionAsState(
composition = lockComposition,
iterations = 1, // Play once
speed = 1f
)
// Entry animation
var visible by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { visible = true }
Box(
modifier = Modifier
.fillMaxSize()
.background(backgroundColor)
) {
Box(modifier = Modifier.fillMaxSize().background(backgroundColor)) {
// Back button when coming from UnlockScreen
if (hasExistingAccount) {
IconButton(
onClick = onBack,
modifier = Modifier
.statusBarsPadding()
.padding(4.dp)
) {
IconButton(onClick = onBack, modifier = Modifier.statusBarsPadding().padding(4.dp)) {
Icon(
Icons.Default.ArrowBack,
contentDescription = "Back",
tint = textColor.copy(alpha = 0.6f)
Icons.Default.ArrowBack,
contentDescription = "Back",
tint = textColor.copy(alpha = 0.6f)
)
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 24.dp)
.statusBarsPadding(),
horizontalAlignment = Alignment.CenterHorizontally
modifier = Modifier.fillMaxSize().padding(horizontal = 24.dp).statusBarsPadding(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.weight(0.15f))
// Animated Lock Icon
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(600)) + scaleIn(tween(600, easing = FastOutSlowInEasing))
visible = visible,
enter = fadeIn(tween(600)) + scaleIn(tween(600, easing = FastOutSlowInEasing))
) {
Box(
modifier = Modifier.size(180.dp),
contentAlignment = Alignment.Center
) {
Box(modifier = Modifier.size(180.dp), contentAlignment = Alignment.Center) {
lockComposition?.let { comp ->
LottieAnimation(
composition = comp,
progress = { lockProgress },
modifier = Modifier.fillMaxSize()
composition = comp,
progress = { lockProgress },
modifier = Modifier.fillMaxSize()
)
}
}
}
Spacer(modifier = Modifier.height(32.dp))
// Title
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(600, delayMillis = 200)) + slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(600, delayMillis = 200)
)
visible = visible,
enter =
fadeIn(tween(600, delayMillis = 200)) +
slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(600, delayMillis = 200)
)
) {
Text(
text = "Your Keys,\nYour Messages",
fontSize = 32.sp,
fontWeight = FontWeight.Bold,
color = textColor,
textAlign = TextAlign.Center,
lineHeight = 40.sp
text = "Your Keys,\nYour Messages",
fontSize = 32.sp,
fontWeight = FontWeight.Bold,
color = textColor,
textAlign = TextAlign.Center,
lineHeight = 40.sp
)
}
Spacer(modifier = Modifier.height(16.dp))
// Subtitle
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(600, delayMillis = 300)) + slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(600, delayMillis = 300)
)
visible = visible,
enter =
fadeIn(tween(600, delayMillis = 300)) +
slideInVertically(
initialOffsetY = { 50 },
animationSpec = tween(600, delayMillis = 300)
)
) {
Text(
text = "Secure messaging with\ncryptographic keys",
fontSize = 16.sp,
color = secondaryTextColor,
textAlign = TextAlign.Center,
lineHeight = 24.sp,
modifier = Modifier.padding(horizontal = 8.dp)
text = "Secure messaging with\ncryptographic keys",
fontSize = 16.sp,
color = secondaryTextColor,
textAlign = TextAlign.Center,
lineHeight = 24.sp,
modifier = Modifier.padding(horizontal = 8.dp)
)
}
Spacer(modifier = Modifier.height(24.dp))
// Features list with icons - placed above buttons
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(600, delayMillis = 400))
) {
AnimatedVisibility(visible = visible, enter = fadeIn(tween(600, delayMillis = 400))) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
CompactFeatureItem(
icon = Icons.Default.Security,
text = "Encrypted",
isDarkTheme = isDarkTheme,
textColor = textColor
icon = Icons.Default.Security,
text = "Encrypted",
isDarkTheme = isDarkTheme,
textColor = textColor
)
CompactFeatureItem(
icon = Icons.Default.NoAccounts,
text = "No Phone",
isDarkTheme = isDarkTheme,
textColor = textColor
icon = Icons.Default.NoAccounts,
text = "No Phone",
isDarkTheme = isDarkTheme,
textColor = textColor
)
CompactFeatureItem(
icon = Icons.Default.Key,
text = "Your Keys",
isDarkTheme = isDarkTheme,
textColor = textColor
icon = Icons.Default.Key,
text = "Your Keys",
isDarkTheme = isDarkTheme,
textColor = textColor
)
}
}
Spacer(modifier = Modifier.height(32.dp))
// Create Seed Button
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(600, delayMillis = 500)) + slideInVertically(
initialOffsetY = { 100 },
animationSpec = tween(600, delayMillis = 500)
)
visible = visible,
enter =
fadeIn(tween(600, delayMillis = 500)) +
slideInVertically(
initialOffsetY = { 100 },
animationSpec = tween(600, delayMillis = 500)
)
) {
Button(
onClick = onCreateSeed,
modifier = Modifier
.fillMaxWidth()
.height(56.dp),
colors = ButtonDefaults.buttonColors(
containerColor = PrimaryBlue,
contentColor = Color.White
),
shape = RoundedCornerShape(16.dp),
elevation = ButtonDefaults.buttonElevation(
defaultElevation = 0.dp,
pressedElevation = 0.dp
)
onClick = onCreateSeed,
modifier = Modifier.fillMaxWidth().height(56.dp),
colors =
ButtonDefaults.buttonColors(
containerColor = PrimaryBlue,
contentColor = Color.White
),
shape = RoundedCornerShape(16.dp),
elevation =
ButtonDefaults.buttonElevation(
defaultElevation = 0.dp,
pressedElevation = 0.dp
)
) {
Icon(
imageVector = Icons.Default.Key,
contentDescription = null,
modifier = Modifier.size(22.dp)
imageVector = Icons.Default.Key,
contentDescription = null,
modifier = Modifier.size(22.dp)
)
Spacer(modifier = Modifier.width(12.dp))
Text(
text = "Generate New Seed Phrase",
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold
text = "Generate New Seed Phrase",
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold
)
}
}
Spacer(modifier = Modifier.height(12.dp))
// Import Seed Button
AnimatedVisibility(
visible = visible,
enter = fadeIn(tween(600, delayMillis = 600)) + slideInVertically(
initialOffsetY = { 100 },
animationSpec = tween(600, delayMillis = 600)
)
visible = visible,
enter =
fadeIn(tween(600, delayMillis = 600)) +
slideInVertically(
initialOffsetY = { 100 },
animationSpec = tween(600, delayMillis = 600)
)
) {
TextButton(
onClick = onImportSeed,
modifier = Modifier
.fillMaxWidth()
.height(56.dp),
shape = RoundedCornerShape(16.dp)
onClick = onImportSeed,
modifier = Modifier.fillMaxWidth().height(56.dp),
shape = RoundedCornerShape(16.dp)
) {
Icon(
imageVector = Icons.Default.Download,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = PrimaryBlue
imageVector = Icons.Default.Download,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = PrimaryBlue
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "I Already Have a Seed Phrase",
fontSize = 15.sp,
fontWeight = FontWeight.Medium,
color = PrimaryBlue
text = "I Already Have a Seed Phrase",
fontSize = 15.sp,
fontWeight = FontWeight.Medium,
color = PrimaryBlue
)
}
}
Spacer(modifier = Modifier.weight(0.15f))
}
}
@@ -264,70 +264,62 @@ fun WelcomeScreen(
@Composable
private fun CompactFeatureItem(
icon: androidx.compose.ui.graphics.vector.ImageVector,
text: String,
isDarkTheme: Boolean,
textColor: Color
icon: androidx.compose.ui.graphics.vector.ImageVector,
text: String,
isDarkTheme: Boolean,
textColor: Color
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Box(
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.background(PrimaryBlue.copy(alpha = 0.12f)),
contentAlignment = Alignment.Center
modifier =
Modifier.size(48.dp)
.clip(CircleShape)
.background(PrimaryBlue.copy(alpha = 0.12f)),
contentAlignment = Alignment.Center
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(24.dp)
imageVector = icon,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(24.dp)
)
}
Text(
text = text,
fontSize = 13.sp,
color = textColor.copy(alpha = 0.8f),
fontWeight = FontWeight.Medium,
textAlign = TextAlign.Center
text = text,
fontSize = 13.sp,
color = textColor.copy(alpha = 0.8f),
fontWeight = FontWeight.Medium,
textAlign = TextAlign.Center
)
}
}
@Composable
private fun FeatureItem(
icon: androidx.compose.ui.graphics.vector.ImageVector,
text: String,
isDarkTheme: Boolean,
textColor: Color
icon: androidx.compose.ui.graphics.vector.ImageVector,
text: String,
isDarkTheme: Boolean,
textColor: Color
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Box(
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.background(PrimaryBlue.copy(alpha = 0.15f)),
contentAlignment = Alignment.Center
modifier =
Modifier.size(40.dp)
.clip(CircleShape)
.background(PrimaryBlue.copy(alpha = 0.15f)),
contentAlignment = Alignment.Center
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(20.dp)
imageVector = icon,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(20.dp)
)
}
Spacer(modifier = Modifier.width(16.dp))
Text(
text = text,
fontSize = 15.sp,
color = textColor,
fontWeight = FontWeight.Medium
)
Text(text = text, fontSize = 15.sp, color = textColor, fontWeight = FontWeight.Medium)
}
}

View File

@@ -534,38 +534,10 @@ fun ChatsListScreen(
Spacer(modifier = Modifier.height(6.dp))
// Connection status indicator
Row(
verticalAlignment = Alignment.CenterVertically,
modifier =
Modifier.clickable { showStatusDialog = true }
) {
val statusColor =
when (protocolState) {
ProtocolState.AUTHENTICATED -> Color(0xFF4ADE80)
ProtocolState.CONNECTING,
ProtocolState.CONNECTED,
ProtocolState.HANDSHAKING -> Color(0xFFFBBF24)
else -> Color(0xFFF87171)
}
val statusText =
when (protocolState) {
ProtocolState.AUTHENTICATED -> "Online"
ProtocolState.CONNECTING,
ProtocolState.CONNECTED,
ProtocolState.HANDSHAKING -> "Connecting..."
else -> "Offline"
}
Box(
modifier =
Modifier.size(8.dp)
.clip(CircleShape)
.background(statusColor)
)
Spacer(modifier = Modifier.width(6.dp))
// Username display
if (accountName.isNotEmpty()) {
Text(
text = statusText,
text = "@$accountName",
fontSize = 13.sp,
color = Color.White.copy(alpha = 0.85f)
)
@@ -864,7 +836,9 @@ fun ChatsListScreen(
ProtocolState
.AUTHENTICATED
)
textColor.copy(alpha = 0.6f)
textColor.copy(
alpha = 0.6f
)
else
textColor.copy(
alpha = 0.5f

View File

@@ -9,14 +9,13 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
@@ -24,13 +23,12 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.data.ForwardManager
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import kotlinx.coroutines.launch
/**
* 📨 BottomSheet для выбора чата при Forward сообщений
*
*
* Логика как в десктопной версии:
* 1. Показывает список диалогов
* 2. При выборе диалога - переходит в чат с сообщениями в Reply панели
@@ -38,25 +36,23 @@ import java.util.*
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ForwardChatPickerBottomSheet(
dialogs: List<DialogUiModel>,
isDarkTheme: Boolean,
currentUserPublicKey: String,
onDismiss: () -> Unit,
onChatSelected: (String) -> Unit
dialogs: List<DialogUiModel>,
isDarkTheme: Boolean,
currentUserPublicKey: String,
onDismiss: () -> Unit,
onChatSelected: (String) -> Unit
) {
val sheetState = rememberModalBottomSheetState(
skipPartiallyExpanded = false
)
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
val scope = rememberCoroutineScope()
val backgroundColor = if (isDarkTheme) Color(0xFF1C1C1E) else Color.White
val textColor = if (isDarkTheme) Color.White else Color.Black
val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE8E8E8)
val forwardMessages by ForwardManager.forwardMessages.collectAsState()
val messagesCount = forwardMessages.size
// 🔥 Функция для красивого закрытия с анимацией
fun dismissWithAnimation() {
scope.launch {
@@ -64,249 +60,232 @@ fun ForwardChatPickerBottomSheet(
onDismiss()
}
}
ModalBottomSheet(
onDismissRequest = { dismissWithAnimation() },
sheetState = sheetState,
containerColor = backgroundColor,
dragHandle = {
// Кастомный handle
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(8.dp))
Box(
modifier = Modifier
.width(36.dp)
.height(5.dp)
.clip(RoundedCornerShape(2.5.dp))
.background(
if (isDarkTheme) Color(0xFF4A4A4A) else Color(0xFFD1D1D6)
)
)
Spacer(modifier = Modifier.height(16.dp))
}
},
shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
onDismissRequest = { dismissWithAnimation() },
sheetState = sheetState,
containerColor = backgroundColor,
dragHandle = {
// Кастомный handle
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(8.dp))
Box(
modifier =
Modifier.width(36.dp)
.height(5.dp)
.clip(RoundedCornerShape(2.5.dp))
.background(
if (isDarkTheme) Color(0xFF4A4A4A)
else Color(0xFFD1D1D6)
)
)
Spacer(modifier = Modifier.height(16.dp))
}
},
shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
) {
Column(modifier = Modifier.fillMaxWidth().navigationBarsPadding()) {
// Header
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
// Иконка и заголовок
Row(
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
// 🔥 Красивая иконка Forward
Icon(
Icons.Filled.ArrowForward,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier
.size(24.dp)
Icons.Filled.ArrowForward,
contentDescription = null,
tint = PrimaryBlue,
modifier = Modifier.size(24.dp)
)
Spacer(modifier = Modifier.width(12.dp))
Column {
Text(
text = "Forward to",
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
color = textColor
text = "Forward to",
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
color = textColor
)
Text(
text = "$messagesCount message${if (messagesCount > 1) "s" else ""} selected",
fontSize = 14.sp,
color = secondaryTextColor
text =
"$messagesCount message${if (messagesCount > 1) "s" else ""} selected",
fontSize = 14.sp,
color = secondaryTextColor
)
}
}
// Кнопка закрытия с анимацией
IconButton(onClick = { dismissWithAnimation() }) {
Icon(
Icons.Default.Close,
contentDescription = "Close",
tint = secondaryTextColor.copy(alpha = 0.6f)
Icons.Default.Close,
contentDescription = "Close",
tint = secondaryTextColor.copy(alpha = 0.6f)
)
}
}
Spacer(modifier = Modifier.height(12.dp))
Divider(
color = dividerColor,
thickness = 0.5.dp
)
Divider(color = dividerColor, thickness = 0.5.dp)
// Список диалогов
if (dialogs.isEmpty()) {
// Empty state
Box(
modifier = Modifier
.fillMaxWidth()
.height(200.dp),
contentAlignment = Alignment.Center
modifier = Modifier.fillMaxWidth().height(200.dp),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "No chats yet",
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
color = secondaryTextColor
text = "No chats yet",
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
color = secondaryTextColor
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Start a conversation first",
fontSize = 14.sp,
color = secondaryTextColor.copy(alpha = 0.7f)
text = "Start a conversation first",
fontSize = 14.sp,
color = secondaryTextColor.copy(alpha = 0.7f)
)
}
}
} else {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 300.dp, max = 400.dp) // 🔥 Минимальная высота для лучшего UX
modifier =
Modifier.fillMaxWidth()
.heightIn(
min = 300.dp,
max = 400.dp
) // 🔥 Минимальная высота для лучшего UX
) {
items(dialogs, key = { it.opponentKey }) { dialog ->
ForwardDialogItem(
dialog = dialog,
isDarkTheme = isDarkTheme,
isSavedMessages = dialog.opponentKey == currentUserPublicKey,
onClick = {
onChatSelected(dialog.opponentKey)
}
dialog = dialog,
isDarkTheme = isDarkTheme,
isSavedMessages = dialog.opponentKey == currentUserPublicKey,
onClick = { onChatSelected(dialog.opponentKey) }
)
// Сепаратор между диалогами
if (dialog != dialogs.last()) {
Divider(
modifier = Modifier.padding(start = 76.dp),
color = dividerColor,
thickness = 0.5.dp
modifier = Modifier.padding(start = 76.dp),
color = dividerColor,
thickness = 0.5.dp
)
}
}
}
}
// Нижний padding
Spacer(modifier = Modifier.height(16.dp))
}
}
}
/**
* Элемент диалога в списке выбора для Forward
*/
/** Элемент диалога в списке выбора для Forward */
@Composable
private fun ForwardDialogItem(
dialog: DialogUiModel,
isDarkTheme: Boolean,
isSavedMessages: Boolean = false,
onClick: () -> Unit
dialog: DialogUiModel,
isDarkTheme: Boolean,
isSavedMessages: Boolean = false,
onClick: () -> Unit
) {
val textColor = if (isDarkTheme) Color.White else Color.Black
val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
val avatarColors = remember(dialog.opponentKey, isDarkTheme) {
getAvatarColor(dialog.opponentKey, isDarkTheme)
}
val displayName = remember(dialog.opponentTitle, dialog.opponentKey, isSavedMessages) {
when {
isSavedMessages -> "Saved Messages"
dialog.opponentTitle.isNotEmpty() -> dialog.opponentTitle
else -> dialog.opponentKey.take(8)
}
}
val initials = remember(dialog.opponentTitle, dialog.opponentKey, isSavedMessages) {
when {
isSavedMessages -> "📁"
dialog.opponentTitle.isNotEmpty() -> {
dialog.opponentTitle
.split(" ")
.take(2)
.mapNotNull { it.firstOrNull()?.uppercase() }
.joinToString("")
val avatarColors =
remember(dialog.opponentKey, isDarkTheme) {
getAvatarColor(dialog.opponentKey, isDarkTheme)
}
else -> dialog.opponentKey.take(2).uppercase()
}
}
val displayName =
remember(dialog.opponentTitle, dialog.opponentKey, isSavedMessages) {
when {
isSavedMessages -> "Saved Messages"
dialog.opponentTitle.isNotEmpty() -> dialog.opponentTitle
else -> dialog.opponentKey.take(8)
}
}
val initials =
remember(dialog.opponentTitle, dialog.opponentKey, isSavedMessages) {
when {
isSavedMessages -> "📁"
dialog.opponentTitle.isNotEmpty() -> {
dialog.opponentTitle
.split(" ")
.take(2)
.mapNotNull { it.firstOrNull()?.uppercase() }
.joinToString("")
}
else -> dialog.opponentKey.take(2).uppercase()
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically
modifier =
Modifier.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically
) {
// Avatar
Box(
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.background(
if (isSavedMessages) PrimaryBlue.copy(alpha = 0.15f)
else avatarColors.backgroundColor
),
contentAlignment = Alignment.Center
modifier =
Modifier.size(48.dp)
.clip(CircleShape)
.background(
if (isSavedMessages) PrimaryBlue.copy(alpha = 0.15f)
else avatarColors.backgroundColor
),
contentAlignment = Alignment.Center
) {
Text(
text = initials,
color = if (isSavedMessages) PrimaryBlue else avatarColors.textColor,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp
text = initials,
color = if (isSavedMessages) PrimaryBlue else avatarColors.textColor,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp
)
}
Spacer(modifier = Modifier.width(12.dp))
// Info
Column(
modifier = Modifier.weight(1f)
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = displayName,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
color = textColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
text = displayName,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
color = textColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.height(2.dp))
Text(
text = if (isSavedMessages) "Your personal notes" else dialog.lastMessage.ifEmpty { "No messages" },
fontSize = 14.sp,
color = secondaryTextColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
text =
if (isSavedMessages) "Your personal notes"
else dialog.lastMessage.ifEmpty { "No messages" },
fontSize = 14.sp,
color = secondaryTextColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
// Online indicator
if (!isSavedMessages && dialog.isOnline == 1) {
Box(
modifier = Modifier
.size(10.dp)
.clip(CircleShape)
.background(Color(0xFF34C759))
)
Box(modifier = Modifier.size(10.dp).clip(CircleShape).background(Color(0xFF34C759)))
}
}
}

View File

@@ -1,5 +1,7 @@
package com.rosetta.messenger.ui.chats
import android.content.Context
import android.view.inputmethod.InputMethodManager
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.*
@@ -21,8 +23,6 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView
import android.content.Context
import android.view.inputmethod.InputMethodManager
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -36,260 +36,251 @@ import com.rosetta.messenger.network.SearchUser
// Primary Blue color
private val PrimaryBlue = Color(0xFF54A9EB)
/**
* Отдельная страница поиска пользователей
* Хедер на всю ширину с полем ввода
*/
/** Отдельная страница поиска пользователей Хедер на всю ширину с полем ввода */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchScreen(
privateKeyHash: String,
currentUserPublicKey: String,
isDarkTheme: Boolean,
protocolState: ProtocolState,
onBackClick: () -> Unit,
onUserSelect: (SearchUser) -> Unit
privateKeyHash: String,
currentUserPublicKey: String,
isDarkTheme: Boolean,
protocolState: ProtocolState,
onBackClick: () -> Unit,
onUserSelect: (SearchUser) -> Unit
) {
// Context и View для мгновенного закрытия клавиатуры
val context = LocalContext.current
val view = LocalView.current
val focusManager = LocalFocusManager.current
// 🔥 Функция мгновенного закрытия клавиатуры
val hideKeyboardInstantly: () -> Unit = {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
focusManager.clearFocus()
}
// Цвета ТОЧНО как в ChatsListScreen
val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFFFFFFF)
val textColor = if (isDarkTheme) Color.White else Color(0xFF1a1a1a)
val secondaryTextColor = if (isDarkTheme) Color(0xFFB0B0B0) else Color(0xFF6c757d)
val surfaceColor = if (isDarkTheme) Color(0xFF1E1E1E) else Color.White
// Search ViewModel
val searchViewModel = remember { SearchUsersViewModel() }
val searchQuery by searchViewModel.searchQuery.collectAsState()
val searchResults by searchViewModel.searchResults.collectAsState()
val isSearching by searchViewModel.isSearching.collectAsState()
// Recent users (не текстовые запросы, а пользователи)
val recentUsers by RecentSearchesManager.recentUsers.collectAsState()
// Preload Lottie composition for search animation
val searchLottieComposition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.search))
val searchLottieComposition by
rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.search))
// Устанавливаем аккаунт для RecentSearchesManager
LaunchedEffect(currentUserPublicKey) {
if (currentUserPublicKey.isNotEmpty()) {
RecentSearchesManager.setAccount(currentUserPublicKey)
}
}
// Устанавливаем privateKeyHash
LaunchedEffect(privateKeyHash) {
if (privateKeyHash.isNotEmpty()) {
searchViewModel.setPrivateKeyHash(privateKeyHash)
}
}
// Focus requester для автофокуса
val focusRequester = remember { FocusRequester() }
// Автофокус при открытии
LaunchedEffect(Unit) {
kotlinx.coroutines.delay(100)
focusRequester.requestFocus()
}
Scaffold(
topBar = {
// Кастомный header с полем ввода на всю ширину
Surface(
modifier = Modifier.fillMaxWidth(),
color = backgroundColor
) {
Row(
modifier = Modifier
.fillMaxWidth()
.statusBarsPadding()
.height(64.dp)
.padding(horizontal = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
// Кнопка назад - с мгновенным закрытием клавиатуры
IconButton(onClick = {
hideKeyboardInstantly()
onBackClick()
}) {
Icon(
Icons.Default.ArrowBack,
contentDescription = "Back",
tint = textColor.copy(alpha = 0.6f)
)
}
// Поле ввода на всю оставшуюся ширину
Box(
modifier = Modifier
.weight(1f)
.padding(end = 8.dp)
topBar = {
// Кастомный header с полем ввода на всю ширину
Surface(modifier = Modifier.fillMaxWidth(), color = backgroundColor) {
Row(
modifier =
Modifier.fillMaxWidth()
.statusBarsPadding()
.height(64.dp)
.padding(horizontal = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
TextField(
value = searchQuery,
onValueChange = { searchViewModel.onSearchQueryChange(it) },
placeholder = {
Text(
"Search users...",
color = secondaryTextColor.copy(alpha = 0.7f),
fontSize = 16.sp
)
},
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
focusedTextColor = textColor,
unfocusedTextColor = textColor,
cursorColor = PrimaryBlue,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
textStyle = androidx.compose.ui.text.TextStyle(
fontSize = 16.sp,
fontWeight = FontWeight.Normal
),
singleLine = true,
enabled = protocolState == ProtocolState.AUTHENTICATED,
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester)
)
// Подчеркивание
Box(
modifier = Modifier
.align(Alignment.BottomCenter)
.fillMaxWidth()
.height(2.dp)
.background(
PrimaryBlue.copy(alpha = 0.8f),
RoundedCornerShape(1.dp)
)
)
}
// Кнопка очистки
AnimatedVisibility(
visible = searchQuery.isNotEmpty(),
enter = fadeIn(tween(150)) + scaleIn(tween(150)),
exit = fadeOut(tween(150)) + scaleOut(tween(150))
) {
IconButton(onClick = { searchViewModel.clearSearchQuery() }) {
// Кнопка назад - с мгновенным закрытием клавиатуры
IconButton(
onClick = {
hideKeyboardInstantly()
onBackClick()
}
) {
Icon(
Icons.Default.Clear,
contentDescription = "Clear",
tint = secondaryTextColor.copy(alpha = 0.6f)
Icons.Default.ArrowBack,
contentDescription = "Back",
tint = textColor.copy(alpha = 0.6f)
)
}
// Поле ввода на всю оставшуюся ширину
Box(modifier = Modifier.weight(1f).padding(end = 8.dp)) {
TextField(
value = searchQuery,
onValueChange = { searchViewModel.onSearchQueryChange(it) },
placeholder = {
Text(
"Search users...",
color = secondaryTextColor.copy(alpha = 0.7f),
fontSize = 16.sp
)
},
colors =
TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
focusedTextColor = textColor,
unfocusedTextColor = textColor,
cursorColor = PrimaryBlue,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
textStyle =
androidx.compose.ui.text.TextStyle(
fontSize = 16.sp,
fontWeight = FontWeight.Normal
),
singleLine = true,
enabled = protocolState == ProtocolState.AUTHENTICATED,
modifier =
Modifier.fillMaxWidth().focusRequester(focusRequester)
)
// Подчеркивание
Box(
modifier =
Modifier.align(Alignment.BottomCenter)
.fillMaxWidth()
.height(2.dp)
.background(
PrimaryBlue.copy(alpha = 0.8f),
RoundedCornerShape(1.dp)
)
)
}
// Кнопка очистки
AnimatedVisibility(
visible = searchQuery.isNotEmpty(),
enter = fadeIn(tween(150)) + scaleIn(tween(150)),
exit = fadeOut(tween(150)) + scaleOut(tween(150))
) {
IconButton(onClick = { searchViewModel.clearSearchQuery() }) {
Icon(
Icons.Default.Clear,
contentDescription = "Clear",
tint = secondaryTextColor.copy(alpha = 0.6f)
)
}
}
}
}
}
},
containerColor = backgroundColor
},
containerColor = backgroundColor
) { paddingValues ->
// Контент - показываем recent users если поле пустое, иначе результаты
Box(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
) {
Box(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
if (searchQuery.isEmpty() && recentUsers.isNotEmpty()) {
// Recent Users с аватарками
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(vertical = 8.dp)
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(vertical = 8.dp)
) {
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
modifier =
Modifier.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
"Recent",
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
color = secondaryTextColor
"Recent",
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
color = secondaryTextColor
)
TextButton(onClick = { RecentSearchesManager.clearAll() }) {
Text(
"Clear All",
fontSize = 13.sp,
color = PrimaryBlue
)
Text("Clear All", fontSize = 13.sp, color = PrimaryBlue)
}
}
}
items(recentUsers, key = { it.publicKey }) { user ->
RecentUserItem(
user = user,
isDarkTheme = isDarkTheme,
textColor = textColor,
secondaryTextColor = secondaryTextColor,
onClick = {
hideKeyboardInstantly()
RecentSearchesManager.addUser(user)
onUserSelect(user)
},
onRemove = {
RecentSearchesManager.removeUser(user.publicKey)
}
user = user,
isDarkTheme = isDarkTheme,
textColor = textColor,
secondaryTextColor = secondaryTextColor,
onClick = {
hideKeyboardInstantly()
RecentSearchesManager.addUser(user)
onUserSelect(user)
},
onRemove = { RecentSearchesManager.removeUser(user.publicKey) }
)
}
}
} else {
// Search Results
// Проверяем, не ищет ли пользователь сам себя (Saved Messages)
val isSavedMessagesSearch = searchQuery.trim().let { query ->
query.equals(currentUserPublicKey, ignoreCase = true) ||
query.equals(currentUserPublicKey.take(8), ignoreCase = true) ||
query.equals(currentUserPublicKey.takeLast(8), ignoreCase = true)
}
// Если ищем себя - показываем Saved Messages как первый результат
val resultsWithSavedMessages = if (isSavedMessagesSearch && searchResults.none { it.publicKey == currentUserPublicKey }) {
listOf(
SearchUser(
title = "Saved Messages",
username = "",
publicKey = currentUserPublicKey,
verified = 0,
online = 1
)
) + searchResults.filter { it.publicKey != currentUserPublicKey }
} else {
searchResults
}
SearchResultsList(
searchResults = resultsWithSavedMessages,
isSearching = isSearching,
currentUserPublicKey = currentUserPublicKey,
isDarkTheme = isDarkTheme,
preloadedComposition = searchLottieComposition,
onUserClick = { user ->
// Мгновенно закрываем клавиатуру
hideKeyboardInstantly()
// Сохраняем пользователя в историю (кроме Saved Messages)
if (user.publicKey != currentUserPublicKey) {
RecentSearchesManager.addUser(user)
val isSavedMessagesSearch =
searchQuery.trim().let { query ->
query.equals(currentUserPublicKey, ignoreCase = true) ||
query.equals(currentUserPublicKey.take(8), ignoreCase = true) ||
query.equals(
currentUserPublicKey.takeLast(8),
ignoreCase = true
)
}
// Если ищем себя - показываем Saved Messages как первый результат
val resultsWithSavedMessages =
if (isSavedMessagesSearch &&
searchResults.none { it.publicKey == currentUserPublicKey }
) {
listOf(
SearchUser(
title = "Saved Messages",
username = "",
publicKey = currentUserPublicKey,
verified = 0,
online = 1
)
) + searchResults.filter { it.publicKey != currentUserPublicKey }
} else {
searchResults
}
SearchResultsList(
searchResults = resultsWithSavedMessages,
isSearching = isSearching,
currentUserPublicKey = currentUserPublicKey,
isDarkTheme = isDarkTheme,
preloadedComposition = searchLottieComposition,
onUserClick = { user ->
// Мгновенно закрываем клавиатуру
hideKeyboardInstantly()
// Сохраняем пользователя в историю (кроме Saved Messages)
if (user.publicKey != currentUserPublicKey) {
RecentSearchesManager.addUser(user)
}
onUserSelect(user)
}
onUserSelect(user)
}
)
}
}
@@ -298,91 +289,85 @@ fun SearchScreen(
@Composable
private fun RecentUserItem(
user: SearchUser,
isDarkTheme: Boolean,
textColor: Color,
secondaryTextColor: Color,
onClick: () -> Unit,
onRemove: () -> Unit
user: SearchUser,
isDarkTheme: Boolean,
textColor: Color,
secondaryTextColor: Color,
onClick: () -> Unit,
onRemove: () -> Unit
) {
val displayName = user.title.ifEmpty {
user.username.ifEmpty {
user.publicKey.take(8) + "..."
}
}
val displayName =
user.title.ifEmpty { user.username.ifEmpty { user.publicKey.take(8) + "..." } }
// Используем getInitials из ChatsListScreen
val initials = getInitials(displayName)
// Используем getAvatarColor из ChatsListScreen для правильных цветов
val avatarColors = getAvatarColor(user.publicKey, isDarkTheme)
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically
modifier =
Modifier.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
// Avatar
Box(
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.background(avatarColors.backgroundColor),
contentAlignment = Alignment.Center
modifier =
Modifier.size(48.dp)
.clip(CircleShape)
.background(avatarColors.backgroundColor),
contentAlignment = Alignment.Center
) {
Text(
text = initials,
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold,
color = avatarColors.textColor
text = initials,
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold,
color = avatarColors.textColor
)
}
Spacer(modifier = Modifier.width(12.dp))
// Name and username
Column(modifier = Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = displayName,
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
color = textColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
text = displayName,
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
color = textColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
if (user.verified != 0) {
Spacer(modifier = Modifier.width(4.dp))
Icon(
Icons.Default.Verified,
contentDescription = "Verified",
tint = PrimaryBlue,
modifier = Modifier.size(16.dp)
Icons.Default.Verified,
contentDescription = "Verified",
tint = PrimaryBlue,
modifier = Modifier.size(16.dp)
)
}
}
if (user.username.isNotEmpty()) {
Text(
text = "@${user.username}",
fontSize = 14.sp,
color = secondaryTextColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
text = "@${user.username}",
fontSize = 14.sp,
color = secondaryTextColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
// Remove button
IconButton(
onClick = onRemove,
modifier = Modifier.size(40.dp)
) {
IconButton(onClick = onRemove, modifier = Modifier.size(40.dp)) {
Icon(
Icons.Default.Close,
contentDescription = "Remove",
tint = secondaryTextColor.copy(alpha = 0.6f),
modifier = Modifier.size(20.dp)
Icons.Default.Close,
contentDescription = "Remove",
tint = secondaryTextColor.copy(alpha = 0.6f),
modifier = Modifier.size(20.dp)
)
}
}