-
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathMainActivity.kt
More file actions
809 lines (744 loc) · 33.1 KB
/
Copy pathMainActivity.kt
File metadata and controls
809 lines (744 loc) · 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
package chat.stoat.activities
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.KeyboardShortcutGroup
import android.view.KeyboardShortcutInfo
import android.view.Menu
import android.view.View
import android.view.ViewTreeObserver
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.EaseInOutExpo
import androidx.compose.animation.core.FiniteAnimationSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import chat.stoat.BuildConfig
import chat.stoat.R
import chat.stoat.StoatApplication
import chat.stoat.api.HitRateLimitException
import chat.stoat.api.StoatAPI
import chat.stoat.api.StoatHttp
import chat.stoat.api.api
import chat.stoat.api.routes.microservices.geo.queryGeo
import chat.stoat.api.routes.microservices.health.healthCheck
import chat.stoat.api.routes.onboard.needsOnboarding
import chat.stoat.core.model.schemas.HealthNotice
import chat.stoat.api.settings.Experiments
import chat.stoat.api.settings.GeoStateProvider
import chat.stoat.api.settings.LoadedSettings
import chat.stoat.api.settings.SyncedSettings
import chat.stoat.composables.generic.HealthAlert
import chat.stoat.composables.voice.VoicePermissionSwitch
import chat.stoat.material.EasingTokens
import chat.stoat.ndk.NativeLibraries
import chat.stoat.persistence.KVStorage
import chat.stoat.screens.DefaultDestinationScreen
import chat.stoat.screens.about.AboutScreen
import chat.stoat.screens.about.AttributionScreen
import chat.stoat.screens.chat.ChatRouterScreen
import chat.stoat.screens.chat.standalone.CatchUpScreen
import chat.stoat.screens.chat.views.channel.ChannelScreen
import chat.stoat.screens.create.CreateGroupScreen
import chat.stoat.screens.labs.LabsRootScreen
import chat.stoat.screens.login.LoginGreetingScreen
import chat.stoat.screens.login.LoginScreen
import chat.stoat.screens.login.MfaScreen
import chat.stoat.screens.login2.InitScreen
import chat.stoat.screens.main.MainScreen
import chat.stoat.screens.register.OnboardingScreen
import chat.stoat.screens.register.RegisterDetailsScreen
import chat.stoat.screens.register.RegisterGreetingScreen
import chat.stoat.screens.register.RegisterVerifyScreen
import chat.stoat.screens.services.DiscoverScreen
import chat.stoat.screens.settings.AppearanceSettingsScreen
import chat.stoat.screens.settings.ChangelogsSettingsScreen
import chat.stoat.screens.settings.ChatSettingsScreen
import chat.stoat.screens.settings.DebugSettingsScreen
import chat.stoat.screens.settings.ExperimentsSettingsScreen
import chat.stoat.screens.settings.LanguagePickerSettingsScreen
import chat.stoat.screens.settings.ProfileSettingsScreen
import chat.stoat.screens.settings.SessionSettingsScreen
import chat.stoat.screens.settings.SettingsScreen
import chat.stoat.screens.settings.channel.ChannelSettingsHome
import chat.stoat.screens.settings.channel.ChannelSettingsOverview
import chat.stoat.screens.settings.channel.ChannelSettingsPermissions
import chat.stoat.ui.theme.StoatTheme
import com.google.android.material.color.DynamicColors
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import io.ktor.client.request.get
import io.sentry.android.core.SentryAndroid
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
@SuppressLint("StaticFieldLeak")
class MainActivityViewModel @Inject constructor(
private val kvStorage: KVStorage,
@ApplicationContext private val context: Context
) : ViewModel() {
val nextDestination = MutableStateFlow<String?>(null)
var isConnected = MutableStateFlow(false)
val isReady = MutableStateFlow(false)
val couldNotLogIn = MutableStateFlow(false)
private fun hasInternetConnection(): Boolean {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = connectivityManager.activeNetwork ?: return false
val capabilities =
connectivityManager.getNetworkCapabilities(network) ?: return false
return when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true
else -> false
}
}
private suspend fun canReachStoat(): Boolean {
try {
val res = StoatHttp.get("/".api())
return res.status.value == 200
} catch (e: Exception) {
return false
}
}
private suspend fun startWithDestination(destination: String) {
nextDestination.emit(destination)
isReady.emit(true)
}
private suspend fun startWithoutDestination() {
isReady.emit(true)
}
private fun doPreStartupTasks() {
Log.d("MainActivity", "Performing pre-startup tasks")
viewModelScope.launch {
Log.d("MainActivity", "Hydrating Experiments from KV")
Experiments.hydrateWithKv()
Log.d("MainActivity", "Performing health check")
doHealthCheck()
Log.d("MainActivity", "Performing update geo state")
updateGeoState()
}
}
private suspend fun updateGeoState() {
try {
Log.d("MainActivity", "Querying geo state")
GeoStateProvider.updateGeoState(queryGeo())
} catch (e: Exception) {
Log.e("MainActivity", "Failed to query geo state", e)
}
}
fun checkLoggedInState() {
viewModelScope.launch {
Log.d("MainActivity", "Checking logged in state")
isConnected.emit(hasInternetConnection())
Log.d("MainActivity", "Checking if we can reach Stoat")
if (!isConnected.value) return@launch startWithoutDestination()
Log.d("MainActivity", "We can reach Stoat, checking if we're logged in")
val token = kvStorage.get("sessionToken")
?: return@launch startWithDestination("login/greeting")
val id = kvStorage.get("sessionId") ?: ""
Log.d(
"MainActivity",
"We have a session token, checking if it's valid and if we can still reach Stoat"
)
val canReachStoat = canReachStoat()
val valid = try {
StoatAPI.checkSessionToken(token)
} catch (e: Throwable) {
false
}
if (canReachStoat && !valid) {
Log.d("MainActivity", "Session token is invalid, could not log in")
couldNotLogIn.emit(true)
} else {
try {
Log.d("MainActivity", "Session token is valid, checking onboarding state")
val onboard = needsOnboarding(token)
if (onboard) {
Log.d("MainActivity", "Onboarding state is incomplete, starting onboarding")
startWithDestination("register/onboarding")
return@launch
}
} catch (e: HitRateLimitException) {
Log.e("MainActivity", "Rate limited while checking onboarding state", e)
Toast.makeText(
context,
context.getString(R.string.rate_limit_toast),
Toast.LENGTH_SHORT
).show()
return@launch startWithoutDestination()
} catch (e: Exception) {
Log.e("MainActivity", "Failed to check onboarding state, could not log in", e)
couldNotLogIn.emit(true)
}
try {
Log.d("MainActivity", "Onboarding state is complete, logging in")
StoatAPI.loginAs(token)
StoatAPI.setSessionId(id)
if (Experiments.usePolar.isEnabled) {
startWithDestination("main")
} else {
startWithDestination("chat")
}
} catch (e: Exception) {
Log.e("MainActivity", "Failed to login, could not log in", e)
couldNotLogIn.emit(true)
}
}
}
}
fun logOut() {
viewModelScope.launch {
kvStorage.remove("sessionToken")
kvStorage.remove("sessionId")
startWithDestination("login/greeting")
}
}
fun updateNextDestination(destination: String) {
viewModelScope.launch {
nextDestination.emit(null)
nextDestination.emit(destination)
}
}
val activeAlert = MutableStateFlow<HealthNotice?>(null)
val isAlertActive = MutableStateFlow(false)
private fun doHealthCheck() {
viewModelScope.launch {
try {
val health = healthCheck()
if (health.alert != null) {
activeAlert.emit(health)
isAlertActive.emit(true)
}
} catch (e: Exception) {
Log.e("MainActivity", "Failed to perform health check", e)
}
}
}
fun onDismissHealthAlert() {
viewModelScope.launch {
activeAlert.emit(null)
isAlertActive.emit(false)
}
}
fun onDismissLoginError() {
viewModelScope.launch {
couldNotLogIn.emit(false)
}
}
init {
Log.d("MainActivity", "Starting up")
doPreStartupTasks()
checkLoggedInState()
}
}
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val viewModel by viewModels<MainActivityViewModel>()
// Fix for SDK >=31, where core-splashscreen accidentally removes dynamic colours
// See the other one in DefaultDestinationScreen.kt
override fun onResume() {
super.onResume()
DynamicColors.applyToActivityIfAvailable(this)
DynamicColors.applyToActivitiesIfAvailable(StoatApplication.instance)
@Suppress("DEPRECATION") // We are fixing a bug in the splash screen
window.statusBarColor = Color.Transparent.toArgb()
}
// Same as above for configuration changes (rotation, dark mode, etc.)
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
DynamicColors.applyToActivityIfAvailable(this)
DynamicColors.applyToActivitiesIfAvailable(StoatApplication.instance)
@Suppress("DEPRECATION") // We are fixing a bug in the splash screen
window.statusBarColor = Color.Transparent.toArgb()
}
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(BuildConfig.SENTRY_DSN != "") {
SentryAndroid.init(this) { options ->
options.dsn = BuildConfig.SENTRY_DSN
options.release = BuildConfig.VERSION_NAME
}
}
@Suppress("DEPRECATION") // We are fixing a bug in the splash screen
window.statusBarColor = Color.Transparent.toArgb()
WindowCompat.setDecorFitsSystemWindows(window, false)
StoatAPI.hydrateFromPersistentCache()
setContent {
val windowSizeClass = calculateWindowSizeClass(this)
AppEntrypoint(
windowSizeClass,
viewModel.nextDestination.collectAsState().value,
viewModel.isConnected.collectAsState().value,
viewModel.activeAlert.collectAsState().value,
viewModel.isAlertActive.collectAsState().value,
viewModel.couldNotLogIn.collectAsState().value,
viewModel::logOut,
viewModel::onDismissHealthAlert,
viewModel::onDismissLoginError,
viewModel::checkLoggedInState,
viewModel::updateNextDestination
)
}
val content: View = findViewById(android.R.id.content)
content.viewTreeObserver.addOnPreDrawListener(
object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
// Check whether the initial data is ready.
return if (viewModel.isReady.value) {
// The content is ready. Start drawing.
content.viewTreeObserver.removeOnPreDrawListener(this)
true
} else {
// The content isn't ready. Suspend.
false
}
}
}
)
}
override fun onProvideKeyboardShortcuts(
data: MutableList<KeyboardShortcutGroup>?,
menu: Menu?,
deviceId: Int
) {
val messaging = KeyboardShortcutGroup(
getString(R.string.keyboard_shortcut_messaging),
listOf(
KeyboardShortcutInfo(
getString(R.string.keyboard_shortcut_messaging_new_line),
KeyEvent.KEYCODE_ENTER,
0
),
KeyboardShortcutInfo(
getString(R.string.keyboard_shortcut_messaging_send_message),
KeyEvent.KEYCODE_ENTER,
KeyEvent.META_CTRL_ON
)
)
)
data?.add(messaging)
}
companion object {
init {
NativeLibraries.init()
}
}
}
val StoatTweenInt: FiniteAnimationSpec<IntOffset> = tween(400, easing = EaseInOutExpo)
val StoatTweenFloat: FiniteAnimationSpec<Float> = tween(400, easing = EaseInOutExpo)
val StoatTweenDp: FiniteAnimationSpec<Dp> = tween(400, easing = EaseInOutExpo)
val StoatTweenColour: FiniteAnimationSpec<Color> = tween(400, easing = EaseInOutExpo)
val NavTweenInt: FiniteAnimationSpec<IntOffset> = tween(350, easing = EaseInOutExpo)
val NavTweenFloat: FiniteAnimationSpec<Float> = tween(350, easing = EaseInOutExpo)
// This composable handles the main compose entrypoint of the app, provides the main navigation
// graph, and handles the animation and layout for the voice chat UI.
@Composable
fun AppEntrypoint(
windowSizeClass: WindowSizeClass,
nextDestination: String?,
isConnected: Boolean,
healthNotice: HealthNotice?,
isHealthAlertActive: Boolean,
couldNotLogIn: Boolean,
onLogout: () -> Unit = {},
onDismissHealthAlert: () -> Unit = {},
onDismissLoginError: () -> Unit = {},
onRetryConnection: () -> Unit,
onUpdateNextDestination: (String) -> Unit = {}
) {
var showVoiceUI by rememberSaveable { mutableStateOf(false) }
var voiceChannelId by rememberSaveable { mutableStateOf<String?>(null) }
val chatUIScale by animateFloatAsState(
if (showVoiceUI) 0.8f else 1.0f,
animationSpec = tween(
durationMillis = 300,
easing = EasingTokens.EmphasizedDecelerate
)
)
val chatUIOpacity by animateFloatAsState(
if (showVoiceUI) 0.8f else 1.0f,
animationSpec = tween(
durationMillis = 300,
easing = EasingTokens.EmphasizedDecelerate
)
)
BackHandler(showVoiceUI) {
showVoiceUI = false
}
val keyboardController = LocalSoftwareKeyboardController.current
LaunchedEffect(showVoiceUI) {
if (showVoiceUI) keyboardController?.hide()
}
val navController = rememberNavController()
StoatTheme(
requestedTheme = LoadedSettings.theme,
requestedUserInterfaceFont = LoadedSettings.font,
colourOverrides = SyncedSettings.android.colourOverrides
) {
Box(
Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.surfaceContainerLowest)
) {
Surface(
modifier = Modifier
.fillMaxSize()
.scale(chatUIScale)
.alpha(chatUIOpacity),
color = MaterialTheme.colorScheme.background
) {
if (isHealthAlertActive) {
healthNotice?.let {
HealthAlert(notice = healthNotice, onDismiss = onDismissHealthAlert)
}
}
if (couldNotLogIn) {
AlertDialog(
onDismissRequest = {
// no-op
},
title = {
Text(stringResource(R.string.could_not_log_in_heading))
},
text = {
Text(stringResource(R.string.could_not_log_in_body))
},
confirmButton = {
TextButton(
onClick = {
onDismissLoginError()
onRetryConnection()
}
) {
Text(stringResource(R.string.could_not_log_in_cta_try_again))
}
},
dismissButton = {
TextButton(
onClick = {
onDismissLoginError()
onLogout()
}
) {
Text(stringResource(R.string.could_not_log_in_cta_logout))
}
}
)
}
NavHost(
navController = navController,
startDestination = "default",
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = NavTweenInt,
initialOffset = { it / 3 }
) + fadeIn(animationSpec = NavTweenFloat)
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = NavTweenInt,
targetOffset = { it / 3 }
) + fadeOut(animationSpec = NavTweenFloat)
},
popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = NavTweenInt,
initialOffset = { it / 3 }
) + fadeIn(animationSpec = NavTweenFloat)
},
popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = NavTweenInt,
targetOffset = { it / 2 }
) + fadeOut(animationSpec = NavTweenFloat)
}
) {
composable("default") {
DefaultDestinationScreen(
navController,
nextDestination,
isConnected,
onRetryConnection
)
}
composable("login/greeting") { LoginGreetingScreen(navController) }
composable("login/login") { LoginScreen(navController) }
composable("login/mfa/{mfaTicket}/{allowedAuthTypes}") { backStackEntry ->
val mfaTicket = backStackEntry.arguments?.getString("mfaTicket") ?: ""
val allowedAuthTypes =
backStackEntry.arguments?.getString("allowedAuthTypes") ?: ""
MfaScreen(navController, allowedAuthTypes, mfaTicket)
}
composable("register/greeting") { RegisterGreetingScreen(navController) }
composable("register/details") { RegisterDetailsScreen(navController) }
composable("register/verify/{email}") { backStackEntry ->
val email = backStackEntry.arguments?.getString("email") ?: ""
RegisterVerifyScreen(navController, email)
}
composable("register/onboarding") {
OnboardingScreen(
navController,
onOnboardingComplete = {
onUpdateNextDestination("chat")
navController.popBackStack(
navController.graph.startDestinationRoute!!,
inclusive = true
)
navController.navigate("default")
}
)
}
composable("login2/init") { InitScreen(navController, windowSizeClass) }
// This is only used outside of Polar mode
// Otherwise you may be looking for "main" right below
composable(
"chat",
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Up,
animationSpec = tween(
400,
easing = EasingTokens.EmphasizedDecelerate
),
initialOffset = { it / 3 }
) + fadeIn(animationSpec = StoatTweenFloat)
}
) {
ChatRouterScreen(
navController,
windowSizeClass,
disableBackHandler = showVoiceUI,
onNullifiedUser = {
onRetryConnection()
navController.popBackStack(
navController.graph.startDestinationRoute!!,
inclusive = true
)
navController.navigate("default")
},
onEnterVoiceUI = { channelId ->
showVoiceUI = true
voiceChannelId = channelId
},
)
}
// This is only the main screen in Polar mode
// Otherwise you may be looking for "chat" right above
composable(
"main",
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Up,
animationSpec = tween(
400,
easing = EasingTokens.EmphasizedDecelerate
),
initialOffset = { it / 3 }
) + fadeIn(animationSpec = StoatTweenFloat) + scaleIn(
animationSpec = tween(
400,
easing = EasingTokens.EmphasizedDecelerate
),
initialScale = 0.8f,
transformOrigin = TransformOrigin.Center
)
}
) {
MainScreen(navController)
}
composable(
"main/conversation/{channelId}",
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(
600,
easing = EasingTokens.EmphasizedDecelerate
),
initialOffset = { it }
) + fadeIn(animationSpec = StoatTweenFloat)
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(
600,
easing = EasingTokens.EmphasizedDecelerate
),
targetOffset = { it }
) + fadeOut(animationSpec = StoatTweenFloat)
}
) { backStackEntry ->
val channelId = backStackEntry.arguments?.getString("channelId") ?: ""
ChannelScreen(
channelId = channelId,
onToggleDrawer = {},
useDrawer = false,
useBackButton = true,
backButtonAction = {
navController.popBackStack()
},
useChatUI = true
)
}
composable("catchup") { CatchUpScreen(navController) }
composable("create/group") { CreateGroupScreen(navController) }
composable("discover") { DiscoverScreen(navController) }
composable("settings") { SettingsScreen(navController) }
composable("settings/profile") { ProfileSettingsScreen(navController) }
composable("settings/sessions") { SessionSettingsScreen(navController) }
composable("settings/appearance") { AppearanceSettingsScreen(navController) }
composable("settings/chat") { ChatSettingsScreen(navController) }
composable("settings/debug") { DebugSettingsScreen(navController) }
composable("settings/experiments") { ExperimentsSettingsScreen(navController) }
composable("settings/changelogs") { ChangelogsSettingsScreen(navController) }
composable("settings/language") { LanguagePickerSettingsScreen(navController) }
composable("settings/channel/{channelId}") { backStackEntry ->
val channelId = backStackEntry.arguments?.getString("channelId") ?: ""
ChannelSettingsHome(navController, channelId)
}
composable("settings/channel/{channelId}/overview") { backStackEntry ->
val channelId = backStackEntry.arguments?.getString("channelId") ?: ""
ChannelSettingsOverview(navController, channelId)
}
composable("settings/channel/{channelId}/permissions") { backStackEntry ->
val channelId = backStackEntry.arguments?.getString("channelId") ?: ""
ChannelSettingsPermissions(navController, channelId)
}
composable("about") { AboutScreen(navController) }
composable("about/oss") { AttributionScreen(navController) }
composable("labs") { LabsRootScreen(navController) }
}
}
if (showVoiceUI) { // if tapped outside the voice UI, close it
Box(
Modifier
.fillMaxSize()
.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) {
showVoiceUI = false
}
)
}
AnimatedVisibility(
visible = showVoiceUI,
modifier = Modifier.align(Alignment.BottomCenter),
enter = slideInVertically(
initialOffsetY = { it -> it },
animationSpec = tween(
durationMillis = 300,
easing = EasingTokens.EmphasizedDecelerate
)
),
exit = slideOutVertically(
targetOffsetY = { it -> it },
animationSpec = tween(
durationMillis = 300,
easing = EasingTokens.EmphasizedDecelerate
)
)
) {
// We need a box as applying the padding elsewhere leads to either
// janky animation or layout
Box(Modifier.safeDrawingPadding()) {
Card(
Modifier
.fillMaxWidth()
.widthIn(max = 600.dp)
.padding(8.dp)
) {
VoicePermissionSwitch(
onCancel = {
showVoiceUI = false
}
) {
LaunchedEffect(Unit) {
showVoiceUI = false
voiceChannelId = null
}
voiceChannelId?.let {
/*VoiceSheet(
it,
onDisconnect = {
showVoiceUI = false
voiceChannelId = null
}
)*/
}
}
}
}
}
}
}
}