path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
kotlin-chat/src/main/kotlin/com/example/demo/view/MainView.kt
3817313966
package com.example.demo.view import com.example.demo.app.Styles import javafx.beans.property.SimpleListProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.geometry.Pos import tornadofx.* class MessageAndAuthor(val authorId: String, val message: String); class ChatDescription(val name: String, val id: String, var messages: List<MessageAndAuthor>) class MainView : View("Kotekpsotek Chat") { var displayChatContent = SimpleObjectProperty<ChatDescription?>(null); val messagesChannel = listOf( MessageAndAuthor(authorId = "1", message = "Txt1") ); val chatList = listOf<ChatDescription?>(ChatDescription(name = "Test Name", id = "123", messages = messagesChannel)) override val root = vbox { label("Chat App") { addClass(Styles.heading) style { textFill = c("black") } } vbox { // TODO: Download from websocket server if (chatList.size != 0) { style { padding = box(0.px, 10.px, 0.px, 10.px) } for (chat in chatList) { button(chat?.name ?: "") { setPrefSize(400.0, 50.0) this.alignment = Pos.BASELINE_LEFT style { padding = box(5.px) fontFamily = "Inter; sans-serif" } // Switch to chat action { displayChatContent.value = chat } } } } else { this.alignment = Pos.CENTER label(text = "No chats are here ❌") { style { fontSize = 15.px padding = box(50.px) textFill = c("red") } } } } } }
Make-It-So/start/app/src/androidTest/java/com/example/makeitso/model/service/module/TestFirebaseModule.kt
1759721996
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service.module import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.firestore import com.google.firebase.Firebase import dagger.Module import dagger.Provides import dagger.hilt.components.SingletonComponent import dagger.hilt.testing.TestInstallIn @Module @TestInstallIn(components = [SingletonComponent::class], replaces = [FirebaseModule::class]) object TestFirebaseModule { private const val HOST = "10.0.2.2" private const val AUTH_PORT = 9099 private const val FIRESTORE_PORT = 8080 @Provides fun auth(): FirebaseAuth = Firebase.auth.also { it.useEmulator(HOST, AUTH_PORT) } @Provides fun firestore(): FirebaseFirestore = Firebase.firestore.also { it.useEmulator(HOST, FIRESTORE_PORT) } }
Make-It-So/start/app/src/androidTest/java/com/example/makeitso/MakeItSoTestRunner.kt
1215355492
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso import android.app.Application import android.content.Context import androidx.test.runner.AndroidJUnitRunner import dagger.hilt.android.testing.HiltTestApplication class MakeItSoTestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, HiltTestApplication::class.java.name, context) } }
Make-It-So/start/app/src/androidTest/java/com/example/makeitso/AwesomeTest.kt
2336400148
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso import com.example.makeitso.model.Task import com.example.makeitso.model.service.StorageService import com.google.common.truth.Truth.assertThat import com.google.firebase.firestore.FirebaseFirestore import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import javax.inject.Inject import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.tasks.await import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test @HiltAndroidTest class AwesomeTest { @get:Rule val hilt = HiltAndroidRule(this) @Inject lateinit var storage: StorageService @Inject lateinit var firestore: FirebaseFirestore @Before fun setup() { hilt.inject() runBlocking { firestore.clearPersistence().await() } } @Test fun test() = runTest { val newId = storage.save(Task(title = "Testing")) val result = storage.tasks.first() assertThat(result).containsExactly(Task(id = newId, title = "Testing")) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoMessagingService.kt
106336736
package com.example.makeitso import android.app.NotificationChannel import android.app.NotificationManager import android.app.NotificationManager.IMPORTANCE_DEFAULT import android.app.PendingIntent import android.app.PendingIntent.FLAG_IMMUTABLE import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP import android.os.Build import android.util.Log import androidx.compose.material.ExperimentalMaterialApi import androidx.core.app.NotificationCompat import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import kotlin.random.Random class MakeItSoMessagingService : FirebaseMessagingService() { private val random = Random override fun onMessageReceived(remoteMessage: RemoteMessage) { remoteMessage.notification?.let { message -> sendNotification(message) } } @OptIn(ExperimentalMaterialApi::class) private fun sendNotification(message: RemoteMessage.Notification) { // If you want the notifications to appear when your app is in foreground val intent = Intent(this, MakeItSoActivity::class.java).apply { addFlags(FLAG_ACTIVITY_CLEAR_TOP) } val pendingIntent = PendingIntent.getActivity( this, 0, intent, FLAG_IMMUTABLE ) val channelId = this.getString(R.string.default_notification_channel_id) val notificationBuilder = NotificationCompat.Builder(this, channelId) .setContentTitle(message.title) .setContentText(message.body) .setSmallIcon(R.mipmap.ic_launcher) .setAutoCancel(true) .setContentIntent(pendingIntent) val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(channelId, CHANNEL_NAME, IMPORTANCE_DEFAULT) manager.createNotificationChannel(channel) } manager.notify(random.nextInt(), notificationBuilder.build()) } override fun onNewToken(token: String) { // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // FCM registration token to your app server. Log.d("FCM","New token: $token") } companion object { const val CHANNEL_NAME = "FCM notification channel" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoRoutes.kt
3028692133
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso const val SPLASH_SCREEN = "SplashScreen" const val SETTINGS_SCREEN = "SettingsScreen" const val LOGIN_SCREEN = "LoginScreen" const val SIGN_UP_SCREEN = "SignUpScreen" const val TASKS_SCREEN = "TasksScreen" const val EDIT_TASK_SCREEN = "EditTaskScreen" const val TASK_ID = "taskId" const val TASK_ID_ARG = "?$TASK_ID={$TASK_ID}"
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoHiltApp.kt
1704438359
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MakeItSoHiltApp : Application() {}
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/settings/SettingsUiState.kt
1797455976
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.settings data class SettingsUiState(val isAnonymousAccount: Boolean = true)
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/settings/SettingsScreen.kt
3538698155
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.settings import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import com.example.makeitso.R.drawable as AppIcon import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.card import com.example.makeitso.common.ext.spacer import com.example.makeitso.theme.MakeItSoTheme @ExperimentalMaterialApi @Composable fun SettingsScreen( restartApp: (String) -> Unit, openScreen: (String) -> Unit, viewModel: SettingsViewModel = hiltViewModel() ) { val uiState by viewModel.uiState.collectAsState( initial = SettingsUiState(false) ) SettingsScreenContent( uiState = uiState, onLoginClick = { viewModel.onLoginClick(openScreen) }, onSignUpClick = { viewModel.onSignUpClick(openScreen) }, onSignOutClick = { viewModel.onSignOutClick(restartApp) }, onDeleteMyAccountClick = { viewModel.onDeleteMyAccountClick(restartApp) } ) } @ExperimentalMaterialApi @Composable fun SettingsScreenContent( modifier: Modifier = Modifier, uiState: SettingsUiState, onLoginClick: () -> Unit, onSignUpClick: () -> Unit, onSignOutClick: () -> Unit, onDeleteMyAccountClick: () -> Unit ) { Column( modifier = modifier.fillMaxWidth().fillMaxHeight().verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { BasicToolbar(AppText.settings) Spacer(modifier = Modifier.spacer()) if (uiState.isAnonymousAccount) { RegularCardEditor(AppText.sign_in, AppIcon.ic_sign_in, "", Modifier.card()) { onLoginClick() } RegularCardEditor(AppText.create_account, AppIcon.ic_create_account, "", Modifier.card()) { onSignUpClick() } } else { SignOutCard { onSignOutClick() } DeleteMyAccountCard { onDeleteMyAccountClick() } } } } @ExperimentalMaterialApi @Composable private fun SignOutCard(signOut: () -> Unit) { var showWarningDialog by remember { mutableStateOf(false) } RegularCardEditor(AppText.sign_out, AppIcon.ic_exit, "", Modifier.card()) { showWarningDialog = true } if (showWarningDialog) { AlertDialog( title = { Text(stringResource(AppText.sign_out_title)) }, text = { Text(stringResource(AppText.sign_out_description)) }, dismissButton = { DialogCancelButton(AppText.cancel) { showWarningDialog = false } }, confirmButton = { DialogConfirmButton(AppText.sign_out) { signOut() showWarningDialog = false } }, onDismissRequest = { showWarningDialog = false } ) } } @ExperimentalMaterialApi @Composable private fun DeleteMyAccountCard(deleteMyAccount: () -> Unit) { var showWarningDialog by remember { mutableStateOf(false) } DangerousCardEditor( AppText.delete_my_account, AppIcon.ic_delete_my_account, "", Modifier.card() ) { showWarningDialog = true } if (showWarningDialog) { AlertDialog( title = { Text(stringResource(AppText.delete_account_title)) }, text = { Text(stringResource(AppText.delete_account_description)) }, dismissButton = { DialogCancelButton(AppText.cancel) { showWarningDialog = false } }, confirmButton = { DialogConfirmButton(AppText.delete_my_account) { deleteMyAccount() showWarningDialog = false } }, onDismissRequest = { showWarningDialog = false } ) } } @Preview(showBackground = true) @ExperimentalMaterialApi @Composable fun SettingsScreenPreview() { val uiState = SettingsUiState(isAnonymousAccount = false) MakeItSoTheme { SettingsScreenContent( uiState = uiState, onLoginClick = { }, onSignUpClick = { }, onSignOutClick = { }, onDeleteMyAccountClick = { } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/settings/SettingsViewModel.kt
2551449822
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.settings import com.example.makeitso.LOGIN_SCREEN import com.example.makeitso.SIGN_UP_SCREEN import com.example.makeitso.SPLASH_SCREEN import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.flow.map @HiltViewModel class SettingsViewModel @Inject constructor( logService: LogService, private val accountService: AccountService, private val storageService: StorageService ) : MakeItSoViewModel(logService) { val uiState = accountService.currentUser.map { SettingsUiState(it.isAnonymous) } fun onLoginClick(openScreen: (String) -> Unit) = openScreen(LOGIN_SCREEN) fun onSignUpClick(openScreen: (String) -> Unit) = openScreen(SIGN_UP_SCREEN) fun onSignOutClick(restartApp: (String) -> Unit) { launchCatching { accountService.signOut() restartApp(SPLASH_SCREEN) } } fun onDeleteMyAccountClick(restartApp: (String) -> Unit) { launchCatching { accountService.deleteAccount() restartApp(SPLASH_SCREEN) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/MakeItSoViewModel.kt
2622876676
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.common.snackbar.SnackbarMessage.Companion.toSnackbarMessage import com.example.makeitso.model.service.LogService import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch open class MakeItSoViewModel(private val logService: LogService) : ViewModel() { fun launchCatching(snackbar: Boolean = true, block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch( CoroutineExceptionHandler { _, throwable -> if (snackbar) { SnackbarManager.showMessage(throwable.toSnackbarMessage()) } logService.logNonFatalCrash(throwable) }, block = block ) }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/splash/SplashViewModel.kt
1055890139
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.splash import androidx.compose.runtime.mutableStateOf import com.example.makeitso.SPLASH_SCREEN import com.example.makeitso.TASKS_SCREEN import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.LogService import com.example.makeitso.screens.MakeItSoViewModel import com.google.firebase.auth.FirebaseAuthException import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class SplashViewModel @Inject constructor( configurationService: ConfigurationService, private val accountService: AccountService, logService: LogService ) : MakeItSoViewModel(logService) { val showError = mutableStateOf(false) init { launchCatching { configurationService.fetchConfiguration() } } fun onAppStart(openAndPopUp: (String, String) -> Unit) { showError.value = false if (accountService.hasUser) openAndPopUp(TASKS_SCREEN, SPLASH_SCREEN) else createAnonymousAccount(openAndPopUp) } private fun createAnonymousAccount(openAndPopUp: (String, String) -> Unit) { launchCatching(snackbar = false) { try { accountService.createAnonymousAccount() } catch (ex: FirebaseAuthException) { showError.value = true throw ex } openAndPopUp(TASKS_SCREEN, SPLASH_SCREEN) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/splash/SplashScreen.kt
3162787655
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.splash import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.BasicButton import com.example.makeitso.common.ext.basicButton import com.example.makeitso.theme.MakeItSoTheme import kotlinx.coroutines.delay private const val SPLASH_TIMEOUT = 1000L @Composable fun SplashScreen( openAndPopUp: (String, String) -> Unit, viewModel: SplashViewModel = hiltViewModel() ) { SplashScreenContent( onAppStart = { viewModel.onAppStart(openAndPopUp) }, shouldShowError = viewModel.showError.value ) } @Composable fun SplashScreenContent( modifier: Modifier = Modifier, onAppStart: () -> Unit, shouldShowError: Boolean ) { Column( modifier = modifier .fillMaxWidth() .fillMaxHeight() .background(color = MaterialTheme.colors.background) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { if (shouldShowError) { Text(text = stringResource(AppText.generic_error)) BasicButton(AppText.try_again, Modifier.basicButton()) { onAppStart() } } else { CircularProgressIndicator(color = MaterialTheme.colors.onBackground) } } LaunchedEffect(true) { delay(SPLASH_TIMEOUT) onAppStart() } } @Preview(showBackground = true) @Composable fun SplashScreenPreview() { MakeItSoTheme { SplashScreenContent( onAppStart = { }, shouldShowError = true ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/tasks/TaskActionOption.kt
3225833856
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.tasks enum class TaskActionOption(val title: String) { EditTask("Edit task"), ToggleFlag("Toggle flag"), DeleteTask("Delete task"); companion object { fun getByTitle(title: String): TaskActionOption { values().forEach { action -> if (title == action.title) return action } return EditTask } fun getOptions(hasEditOption: Boolean): List<String> { val options = mutableListOf<String>() values().forEach { taskAction -> if (hasEditOption || taskAction != EditTask) { options.add(taskAction.title) } } return options } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/tasks/TasksViewModel.kt
607458925
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.tasks import androidx.compose.runtime.mutableStateOf import com.example.makeitso.EDIT_TASK_SCREEN import com.example.makeitso.SETTINGS_SCREEN import com.example.makeitso.TASK_ID import com.example.makeitso.model.Task import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.emptyFlow import javax.inject.Inject @HiltViewModel class TasksViewModel @Inject constructor( logService: LogService, private val storageService: StorageService, private val configurationService: ConfigurationService ) : MakeItSoViewModel(logService) { val options = mutableStateOf<List<String>>(listOf()) val tasks = storageService.tasks fun loadTaskOptions() { val hasEditOption = configurationService.isShowTaskEditButtonConfig options.value = TaskActionOption.getOptions(hasEditOption) } fun onTaskCheckChange(task: Task) { launchCatching { storageService.update(task.copy(completed = !task.completed)) } } fun onAddClick(openScreen: (String) -> Unit) = openScreen(EDIT_TASK_SCREEN) fun onSettingsClick(openScreen: (String) -> Unit) = openScreen(SETTINGS_SCREEN) fun onTaskActionClick(openScreen: (String) -> Unit, task: Task, action: String) { when (TaskActionOption.getByTitle(action)) { TaskActionOption.EditTask -> openScreen("$EDIT_TASK_SCREEN?$TASK_ID={${task.id}}") TaskActionOption.ToggleFlag -> onFlagTaskClick(task) TaskActionOption.DeleteTask -> onDeleteTaskClick(task) } } private fun onFlagTaskClick(task: Task) { launchCatching { storageService.update(task.copy(flag = !task.flag)) } } private fun onDeleteTaskClick(task: Task) { launchCatching { storageService.delete(task.id) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/tasks/TaskItem.kt
2498837044
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.tasks import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.makeitso.R.drawable as AppIcon import com.example.makeitso.common.composable.DropdownContextMenu import com.example.makeitso.common.ext.contextMenu import com.example.makeitso.common.ext.hasDueDate import com.example.makeitso.common.ext.hasDueTime import com.example.makeitso.model.Task import com.example.makeitso.theme.DarkOrange import java.lang.StringBuilder @Composable @ExperimentalMaterialApi fun TaskItem( task: Task, options: List<String>, onCheckChange: () -> Unit, onActionClick: (String) -> Unit ) { Card( backgroundColor = MaterialTheme.colors.background, modifier = Modifier.padding(8.dp, 0.dp, 8.dp, 8.dp), ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth(), ) { Checkbox( checked = task.completed, onCheckedChange = { onCheckChange() }, modifier = Modifier.padding(8.dp, 0.dp) ) Column(modifier = Modifier.weight(1f)) { Text(text = task.title, style = MaterialTheme.typography.subtitle2) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text(text = getDueDateAndTime(task), fontSize = 12.sp) } } if (task.flag) { Icon( painter = painterResource(AppIcon.ic_flag), tint = DarkOrange, contentDescription = "Flag" ) } DropdownContextMenu(options, Modifier.contextMenu(), onActionClick) } } } private fun getDueDateAndTime(task: Task): String { val stringBuilder = StringBuilder("") if (task.hasDueDate()) { stringBuilder.append(task.dueDate) stringBuilder.append(" ") } if (task.hasDueTime()) { stringBuilder.append("at ") stringBuilder.append(task.dueTime) } return stringBuilder.toString() }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/tasks/TasksScreen.kt
2455749173
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.tasks import android.annotation.SuppressLint import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.example.makeitso.R.drawable as AppIcon import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.ActionToolbar import com.example.makeitso.common.ext.smallSpacer import com.example.makeitso.common.ext.toolbarActions import com.example.makeitso.model.Task import com.example.makeitso.theme.MakeItSoTheme @Composable @ExperimentalMaterialApi fun TasksScreen( openScreen: (String) -> Unit, viewModel: TasksViewModel = hiltViewModel() ) { TasksScreenContent( onAddClick = viewModel::onAddClick, onSettingsClick = viewModel::onSettingsClick, onTaskCheckChange = viewModel::onTaskCheckChange, onTaskActionClick = viewModel::onTaskActionClick, openScreen = openScreen, viewModel = viewModel ) LaunchedEffect(viewModel) { viewModel.loadTaskOptions() } } @SuppressLint("UnusedMaterialScaffoldPaddingParameter") @Composable @ExperimentalMaterialApi fun TasksScreenContent( modifier: Modifier = Modifier, onAddClick: ((String) -> Unit) -> Unit, onSettingsClick: ((String) -> Unit) -> Unit, onTaskCheckChange: (Task) -> Unit, onTaskActionClick: ((String) -> Unit, Task, String) -> Unit, openScreen: (String) -> Unit, viewModel: TasksViewModel = hiltViewModel() ) { val tasks = viewModel .tasks .collectAsStateWithLifecycle(emptyList()) Scaffold( floatingActionButton = { FloatingActionButton( onClick = { onAddClick(openScreen) }, backgroundColor = MaterialTheme.colors.primary, contentColor = MaterialTheme.colors.onPrimary, modifier = modifier.padding(16.dp) ) { Icon(Icons.Filled.Add, "Add") } } ) { Column(modifier = Modifier .fillMaxWidth() .fillMaxHeight()) { ActionToolbar( title = AppText.tasks, modifier = Modifier.toolbarActions(), endActionIcon = AppIcon.ic_settings, endAction = { onSettingsClick(openScreen) } ) Spacer(modifier = Modifier.smallSpacer()) LazyColumn { val options by viewModel.options items(tasks.value, key = { it.id }) { taskItem -> TaskItem( task = taskItem, //options = listOf(), options = options, onCheckChange = { onTaskCheckChange(taskItem) }, onActionClick = { action -> onTaskActionClick(openScreen, taskItem, action) } ) } } } } } @Preview(showBackground = true) @ExperimentalMaterialApi @Composable fun TasksScreenPreview() { MakeItSoTheme { TasksScreenContent( onAddClick = { }, onSettingsClick = { }, onTaskCheckChange = { }, onTaskActionClick = { _, _, _ -> }, openScreen = { } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/edit_task/EditTaskViewModel.kt
838724084
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.edit_task import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.SavedStateHandle import com.example.makeitso.TASK_ID import com.example.makeitso.common.ext.idFromParameter import com.example.makeitso.model.Task import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import java.text.SimpleDateFormat import java.util.* import javax.inject.Inject @HiltViewModel class EditTaskViewModel @Inject constructor( savedStateHandle: SavedStateHandle, logService: LogService, private val storageService: StorageService, ) : MakeItSoViewModel(logService) { val task = mutableStateOf(Task()) init { val taskId = savedStateHandle.get<String>(TASK_ID) if (taskId != null) { launchCatching { task.value = storageService.getTask(taskId.idFromParameter()) ?: Task() } } } fun onTitleChange(newValue: String) { task.value = task.value.copy(title = newValue) } fun onDescriptionChange(newValue: String) { task.value = task.value.copy(description = newValue) } fun onUrlChange(newValue: String) { task.value = task.value.copy(url = newValue) } fun onDateChange(newValue: Long) { val calendar = Calendar.getInstance(TimeZone.getTimeZone(UTC)) calendar.timeInMillis = newValue val newDueDate = SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH).format(calendar.time) task.value = task.value.copy(dueDate = newDueDate) } fun onTimeChange(hour: Int, minute: Int) { val newDueTime = "${hour.toClockPattern()}:${minute.toClockPattern()}" task.value = task.value.copy(dueTime = newDueTime) } fun onFlagToggle(newValue: String) { val newFlagOption = EditFlagOption.getBooleanValue(newValue) task.value = task.value.copy(flag = newFlagOption) } fun onPriorityChange(newValue: String) { task.value = task.value.copy(priority = newValue) } fun onDoneClick(popUpScreen: () -> Unit) { launchCatching { val editedTask = task.value if (editedTask.id.isBlank()) { storageService.save(editedTask) } else { storageService.update(editedTask) } popUpScreen() } } private fun Int.toClockPattern(): String { return if (this < 10) "0$this" else "$this" } companion object { private const val UTC = "UTC" private const val DATE_FORMAT = "EEE, d MMM yyyy" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/edit_task/EditTaskScreen.kt
4191085042
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.edit_task import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import com.example.makeitso.R.drawable as AppIcon import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.card import com.example.makeitso.common.ext.fieldModifier import com.example.makeitso.common.ext.spacer import com.example.makeitso.common.ext.toolbarActions import com.example.makeitso.model.Priority import com.example.makeitso.model.Task import com.example.makeitso.theme.MakeItSoTheme import com.google.android.material.datepicker.MaterialDatePicker import com.google.android.material.timepicker.MaterialTimePicker import com.google.android.material.timepicker.TimeFormat @Composable @ExperimentalMaterialApi fun EditTaskScreen( popUpScreen: () -> Unit, viewModel: EditTaskViewModel = hiltViewModel() ) { val task by viewModel.task val activity = LocalContext.current as AppCompatActivity EditTaskScreenContent( task = task, onDoneClick = { viewModel.onDoneClick(popUpScreen) }, onTitleChange = viewModel::onTitleChange, onDescriptionChange = viewModel::onDescriptionChange, onUrlChange = viewModel::onUrlChange, onDateChange = viewModel::onDateChange, onTimeChange = viewModel::onTimeChange, onPriorityChange = viewModel::onPriorityChange, onFlagToggle = viewModel::onFlagToggle, activity = activity ) } @Composable @ExperimentalMaterialApi fun EditTaskScreenContent( modifier: Modifier = Modifier, task: Task, onDoneClick: () -> Unit, onTitleChange: (String) -> Unit, onDescriptionChange: (String) -> Unit, onUrlChange: (String) -> Unit, onDateChange: (Long) -> Unit, onTimeChange: (Int, Int) -> Unit, onPriorityChange: (String) -> Unit, onFlagToggle: (String) -> Unit, activity: AppCompatActivity? ) { Column( modifier = modifier.fillMaxWidth().fillMaxHeight().verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { ActionToolbar( title = AppText.edit_task, modifier = Modifier.toolbarActions(), endActionIcon = AppIcon.ic_check, endAction = { onDoneClick() } ) Spacer(modifier = Modifier.spacer()) val fieldModifier = Modifier.fieldModifier() BasicField(AppText.title, task.title, onTitleChange, fieldModifier) BasicField(AppText.description, task.description, onDescriptionChange, fieldModifier) BasicField(AppText.url, task.url, onUrlChange, fieldModifier) Spacer(modifier = Modifier.spacer()) CardEditors(task, onDateChange, onTimeChange, activity) CardSelectors(task, onPriorityChange, onFlagToggle) Spacer(modifier = Modifier.spacer()) } } @ExperimentalMaterialApi @Composable private fun CardEditors( task: Task, onDateChange: (Long) -> Unit, onTimeChange: (Int, Int) -> Unit, activity: AppCompatActivity? ) { RegularCardEditor(AppText.date, AppIcon.ic_calendar, task.dueDate, Modifier.card()) { showDatePicker(activity, onDateChange) } RegularCardEditor(AppText.time, AppIcon.ic_clock, task.dueTime, Modifier.card()) { showTimePicker(activity, onTimeChange) } } @Composable @ExperimentalMaterialApi private fun CardSelectors( task: Task, onPriorityChange: (String) -> Unit, onFlagToggle: (String) -> Unit ) { val prioritySelection = Priority.getByName(task.priority).name CardSelector(AppText.priority, Priority.getOptions(), prioritySelection, Modifier.card()) { newValue -> onPriorityChange(newValue) } val flagSelection = EditFlagOption.getByCheckedState(task.flag).name CardSelector(AppText.flag, EditFlagOption.getOptions(), flagSelection, Modifier.card()) { newValue -> onFlagToggle(newValue) } } private fun showDatePicker(activity: AppCompatActivity?, onDateChange: (Long) -> Unit) { val picker = MaterialDatePicker.Builder.datePicker().build() activity?.let { picker.show(it.supportFragmentManager, picker.toString()) picker.addOnPositiveButtonClickListener { timeInMillis -> onDateChange(timeInMillis) } } } private fun showTimePicker(activity: AppCompatActivity?, onTimeChange: (Int, Int) -> Unit) { val picker = MaterialTimePicker.Builder().setTimeFormat(TimeFormat.CLOCK_24H).build() activity?.let { picker.show(it.supportFragmentManager, picker.toString()) picker.addOnPositiveButtonClickListener { onTimeChange(picker.hour, picker.minute) } } } @Preview(showBackground = true) @ExperimentalMaterialApi @Composable fun EditTaskScreenPreview() { val task = Task( title = "Task title", description = "Task description", flag = true ) MakeItSoTheme { EditTaskScreenContent( task = task, onDoneClick = { }, onTitleChange = { }, onDescriptionChange = { }, onUrlChange = { }, onDateChange = { }, onTimeChange = { _, _ -> }, onPriorityChange = { }, onFlagToggle = { }, activity = null ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/edit_task/EditFlagOption.kt
625423710
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.edit_task enum class EditFlagOption { On, Off; companion object { fun getByCheckedState(checkedState: Boolean?): EditFlagOption { val hasFlag = checkedState ?: false return if (hasFlag) On else Off } fun getBooleanValue(flagOption: String): Boolean { return flagOption == On.name } fun getOptions(): List<String> { val options = mutableListOf<String>() values().forEach { flagOption -> options.add(flagOption.name) } return options } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/sign_up/SignUpScreen.kt
1358001008
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.sign_up import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.basicButton import com.example.makeitso.common.ext.fieldModifier import com.example.makeitso.theme.MakeItSoTheme @Composable fun SignUpScreen( openAndPopUp: (String, String) -> Unit, viewModel: SignUpViewModel = hiltViewModel() ) { val uiState by viewModel.uiState SignUpScreenContent( uiState = uiState, onEmailChange = viewModel::onEmailChange, onPasswordChange = viewModel::onPasswordChange, onRepeatPasswordChange = viewModel::onRepeatPasswordChange, onSignUpClick = { viewModel.onSignUpClick(openAndPopUp) } ) } @Composable fun SignUpScreenContent( modifier: Modifier = Modifier, uiState: SignUpUiState, onEmailChange: (String) -> Unit, onPasswordChange: (String) -> Unit, onRepeatPasswordChange: (String) -> Unit, onSignUpClick: () -> Unit ) { val fieldModifier = Modifier.fieldModifier() BasicToolbar(AppText.create_account) Column( modifier = modifier.fillMaxWidth().fillMaxHeight().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { EmailField(uiState.email, onEmailChange, fieldModifier) PasswordField(uiState.password, onPasswordChange, fieldModifier) RepeatPasswordField(uiState.repeatPassword, onRepeatPasswordChange, fieldModifier) BasicButton(AppText.create_account, Modifier.basicButton()) { onSignUpClick() } } } @Preview(showBackground = true) @Composable fun SignUpScreenPreview() { val uiState = SignUpUiState( email = "[email protected]" ) MakeItSoTheme { SignUpScreenContent( uiState = uiState, onEmailChange = { }, onPasswordChange = { }, onRepeatPasswordChange = { }, onSignUpClick = { } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/sign_up/SignUpViewModel.kt
2706619517
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.sign_up import androidx.compose.runtime.mutableStateOf import com.example.makeitso.R.string as AppText import com.example.makeitso.SETTINGS_SCREEN import com.example.makeitso.SIGN_UP_SCREEN import com.example.makeitso.common.ext.isValidEmail import com.example.makeitso.common.ext.isValidPassword import com.example.makeitso.common.ext.passwordMatches import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.LogService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class SignUpViewModel @Inject constructor( private val accountService: AccountService, logService: LogService ) : MakeItSoViewModel(logService) { var uiState = mutableStateOf(SignUpUiState()) private set private val email get() = uiState.value.email private val password get() = uiState.value.password fun onEmailChange(newValue: String) { uiState.value = uiState.value.copy(email = newValue) } fun onPasswordChange(newValue: String) { uiState.value = uiState.value.copy(password = newValue) } fun onRepeatPasswordChange(newValue: String) { uiState.value = uiState.value.copy(repeatPassword = newValue) } fun onSignUpClick(openAndPopUp: (String, String) -> Unit) { if (!email.isValidEmail()) { SnackbarManager.showMessage(AppText.email_error) return } if (!password.isValidPassword()) { SnackbarManager.showMessage(AppText.password_error) return } if (!password.passwordMatches(uiState.value.repeatPassword)) { SnackbarManager.showMessage(AppText.password_match_error) return } launchCatching { accountService.linkAccount(email, password) openAndPopUp(SETTINGS_SCREEN, SIGN_UP_SCREEN) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/sign_up/SignUpUiState.kt
1737242844
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.sign_up data class SignUpUiState( val email: String = "", val password: String = "", val repeatPassword: String = "" )
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/login/LoginViewModel.kt
4239581162
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.login import androidx.compose.runtime.mutableStateOf import com.example.makeitso.LOGIN_SCREEN import com.example.makeitso.R.string as AppText import com.example.makeitso.SETTINGS_SCREEN import com.example.makeitso.common.ext.isValidEmail import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.LogService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val accountService: AccountService, logService: LogService ) : MakeItSoViewModel(logService) { var uiState = mutableStateOf(LoginUiState()) private set private val email get() = uiState.value.email private val password get() = uiState.value.password fun onEmailChange(newValue: String) { uiState.value = uiState.value.copy(email = newValue) } fun onPasswordChange(newValue: String) { uiState.value = uiState.value.copy(password = newValue) } fun onSignInClick(openAndPopUp: (String, String) -> Unit) { if (!email.isValidEmail()) { SnackbarManager.showMessage(AppText.email_error) return } if (password.isBlank()) { SnackbarManager.showMessage(AppText.empty_password_error) return } launchCatching { accountService.authenticate(email, password) openAndPopUp(SETTINGS_SCREEN, LOGIN_SCREEN) } } fun onForgotPasswordClick() { if (!email.isValidEmail()) { SnackbarManager.showMessage(AppText.email_error) return } launchCatching { accountService.sendRecoveryEmail(email) SnackbarManager.showMessage(AppText.recovery_email_sent) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/login/LoginUiState.kt
3622176427
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.login data class LoginUiState( val email: String = "", val password: String = "" )
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/login/LoginScreen.kt
2163535745
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.login import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.basicButton import com.example.makeitso.common.ext.fieldModifier import com.example.makeitso.common.ext.textButton import com.example.makeitso.theme.MakeItSoTheme @Composable fun LoginScreen( openAndPopUp: (String, String) -> Unit, viewModel: LoginViewModel = hiltViewModel() ) { val uiState by viewModel.uiState LoginScreenContent( uiState = uiState, onEmailChange = viewModel::onEmailChange, onPasswordChange = viewModel::onPasswordChange, onSignInClick = { viewModel.onSignInClick(openAndPopUp) }, onForgotPasswordClick = viewModel::onForgotPasswordClick ) } @Composable fun LoginScreenContent( modifier: Modifier = Modifier, uiState: LoginUiState, onEmailChange: (String) -> Unit, onPasswordChange: (String) -> Unit, onSignInClick: () -> Unit, onForgotPasswordClick: () -> Unit ) { BasicToolbar(AppText.login_details) Column( modifier = modifier .fillMaxWidth() .fillMaxHeight() .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { EmailField(uiState.email, onEmailChange, Modifier.fieldModifier()) PasswordField(uiState.password, onPasswordChange, Modifier.fieldModifier()) BasicButton(AppText.sign_in, Modifier.basicButton()) { onSignInClick() } BasicTextButton(AppText.forgot_password, Modifier.textButton()) { onForgotPasswordClick() } } } @Preview(showBackground = true) @Composable fun LoginScreenPreview() { val uiState = LoginUiState( email = "[email protected]" ) MakeItSoTheme { LoginScreenContent( uiState = uiState, onEmailChange = { }, onPasswordChange = { }, onSignInClick = { }, onForgotPasswordClick = { } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/snackbar/SnackbarMessage.kt
1730361887
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.snackbar import android.content.res.Resources import androidx.annotation.StringRes import com.example.makeitso.R.string as AppText sealed class SnackbarMessage { class StringSnackbar(val message: String) : SnackbarMessage() class ResourceSnackbar(@StringRes val message: Int) : SnackbarMessage() companion object { fun SnackbarMessage.toMessage(resources: Resources): String { return when (this) { is StringSnackbar -> this.message is ResourceSnackbar -> resources.getString(this.message) } } fun Throwable.toSnackbarMessage(): SnackbarMessage { val message = this.message.orEmpty() return if (message.isNotBlank()) StringSnackbar(message) else ResourceSnackbar(AppText.generic_error) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/snackbar/SnackbarManager.kt
368510474
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.snackbar import androidx.annotation.StringRes import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow object SnackbarManager { private val messages: MutableStateFlow<SnackbarMessage?> = MutableStateFlow(null) val snackbarMessages: StateFlow<SnackbarMessage?> get() = messages.asStateFlow() fun showMessage(@StringRes message: Int) { messages.value = SnackbarMessage.ResourceSnackbar(message) } fun showMessage(message: SnackbarMessage) { messages.value = message } fun clearSnackbarState() { messages.value = null } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/ext/StringExt.kt
2117289206
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.ext import android.util.Patterns import java.util.regex.Pattern private const val MIN_PASS_LENGTH = 6 private const val PASS_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{4,}$" fun String.isValidEmail(): Boolean { return this.isNotBlank() && Patterns.EMAIL_ADDRESS.matcher(this).matches() } fun String.isValidPassword(): Boolean { return this.isNotBlank() && this.length >= MIN_PASS_LENGTH && Pattern.compile(PASS_PATTERN).matcher(this).matches() } fun String.passwordMatches(repeated: String): Boolean { return this == repeated } fun String.idFromParameter(): String { return this.substring(1, this.length - 1) }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/ext/TaskExt.kt
1189228462
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.ext import com.example.makeitso.model.Task fun Task?.hasDueDate(): Boolean { return this?.dueDate.orEmpty().isNotBlank() } fun Task?.hasDueTime(): Boolean { return this?.dueTime.orEmpty().isNotBlank() }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/ext/ModifierExt.kt
1490560864
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.ext import androidx.compose.foundation.layout.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp fun Modifier.textButton(): Modifier { return this.fillMaxWidth().padding(16.dp, 8.dp, 16.dp, 0.dp) } fun Modifier.basicButton(): Modifier { return this.fillMaxWidth().padding(16.dp, 8.dp) } fun Modifier.card(): Modifier { return this.padding(16.dp, 0.dp, 16.dp, 8.dp) } fun Modifier.contextMenu(): Modifier { return this.wrapContentWidth() } fun Modifier.alertDialog(): Modifier { return this.wrapContentWidth().wrapContentHeight() } fun Modifier.dropdownSelector(): Modifier { return this.fillMaxWidth() } fun Modifier.fieldModifier(): Modifier { return this.fillMaxWidth().padding(16.dp, 4.dp) } fun Modifier.toolbarActions(): Modifier { return this.wrapContentSize(Alignment.TopEnd) } fun Modifier.spacer(): Modifier { return this.fillMaxWidth().padding(12.dp) } fun Modifier.smallSpacer(): Modifier { return this.fillMaxWidth().height(8.dp) }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/DropdownComposable.kt
2214167780
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.composable import androidx.annotation.StringRes import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @Composable @ExperimentalMaterialApi fun DropdownContextMenu( options: List<String>, modifier: Modifier, onActionClick: (String) -> Unit ) { var isExpanded by remember { mutableStateOf(false) } ExposedDropdownMenuBox( expanded = isExpanded, modifier = modifier, onExpandedChange = { isExpanded = !isExpanded } ) { Icon( modifier = Modifier.padding(8.dp, 0.dp), imageVector = Icons.Default.MoreVert, contentDescription = "More" ) ExposedDropdownMenu( modifier = Modifier.width(180.dp), expanded = isExpanded, onDismissRequest = { isExpanded = false } ) { options.forEach { selectionOption -> DropdownMenuItem( onClick = { isExpanded = false onActionClick(selectionOption) } ) { Text(text = selectionOption) } } } } } @Composable @ExperimentalMaterialApi fun DropdownSelector( @StringRes label: Int, options: List<String>, selection: String, modifier: Modifier, onNewValue: (String) -> Unit ) { var isExpanded by remember { mutableStateOf(false) } ExposedDropdownMenuBox( expanded = isExpanded, modifier = modifier, onExpandedChange = { isExpanded = !isExpanded } ) { TextField( modifier = Modifier.fillMaxWidth(), readOnly = true, value = selection, onValueChange = {}, label = { Text(stringResource(label)) }, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(isExpanded) }, colors = dropdownColors() ) ExposedDropdownMenu(expanded = isExpanded, onDismissRequest = { isExpanded = false }) { options.forEach { selectionOption -> DropdownMenuItem( onClick = { onNewValue(selectionOption) isExpanded = false } ) { Text(text = selectionOption) } } } } } @Composable @ExperimentalMaterialApi private fun dropdownColors(): TextFieldColors { return ExposedDropdownMenuDefaults.textFieldColors( backgroundColor = MaterialTheme.colors.onPrimary, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, trailingIconColor = MaterialTheme.colors.onSurface, focusedTrailingIconColor = MaterialTheme.colors.onSurface, focusedLabelColor = MaterialTheme.colors.primary, unfocusedLabelColor = MaterialTheme.colors.primary ) }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/CardComposable.kt
2132506523
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.composable import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.makeitso.common.ext.dropdownSelector @ExperimentalMaterialApi @Composable fun DangerousCardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, modifier: Modifier, onEditClick: () -> Unit ) { CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.primary, modifier) } @ExperimentalMaterialApi @Composable fun RegularCardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, modifier: Modifier, onEditClick: () -> Unit ) { CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.onSurface, modifier) } @ExperimentalMaterialApi @Composable private fun CardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, onEditClick: () -> Unit, highlightColor: Color, modifier: Modifier ) { Card( backgroundColor = MaterialTheme.colors.onPrimary, modifier = modifier, onClick = onEditClick ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(16.dp) ) { Column(modifier = Modifier.weight(1f)) { Text(stringResource(title), color = highlightColor) } if (content.isNotBlank()) { Text(text = content, modifier = Modifier.padding(16.dp, 0.dp)) } Icon(painter = painterResource(icon), contentDescription = "Icon", tint = highlightColor) } } } @Composable @ExperimentalMaterialApi fun CardSelector( @StringRes label: Int, options: List<String>, selection: String, modifier: Modifier, onNewValue: (String) -> Unit ) { Card(backgroundColor = MaterialTheme.colors.onPrimary, modifier = modifier) { DropdownSelector(label, options, selection, Modifier.dropdownSelector(), onNewValue) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/ToolbarComposable.kt
210640367
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.composable import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource @Composable fun BasicToolbar(@StringRes title: Int) { TopAppBar(title = { Text(stringResource(title)) }, backgroundColor = toolbarColor()) } @Composable fun ActionToolbar( @StringRes title: Int, @DrawableRes endActionIcon: Int, modifier: Modifier, endAction: () -> Unit ) { TopAppBar( title = { Text(stringResource(title)) }, backgroundColor = toolbarColor(), actions = { Box(modifier) { IconButton(onClick = endAction) { Icon(painter = painterResource(endActionIcon), contentDescription = "Action") } } } ) } @Composable private fun toolbarColor(darkTheme: Boolean = isSystemInDarkTheme()): Color { return if (darkTheme) MaterialTheme.colors.secondary else MaterialTheme.colors.primaryVariant }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/PermissionDialogComposable.kt
809064112
package com.example.makeitso.common.composable import androidx.compose.material.AlertDialog import androidx.compose.material.ButtonDefaults import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import com.example.makeitso.common.ext.alertDialog import com.example.makeitso.common.ext.textButton import com.example.makeitso.theme.BrightOrange import com.example.makeitso.R.string as AppText @Composable fun PermissionDialog(onRequestPermission: () -> Unit) { var showWarningDialog by remember { mutableStateOf(true) } if (showWarningDialog) { AlertDialog( modifier = Modifier.alertDialog(), title = { Text(stringResource(id = AppText.notification_permission_title)) }, text = { Text(stringResource(id = AppText.notification_permission_description)) }, confirmButton = { TextButton( onClick = { onRequestPermission() showWarningDialog = false }, modifier = Modifier.textButton(), colors = ButtonDefaults.buttonColors( backgroundColor = BrightOrange, contentColor = Color.White ) ) { Text(text = stringResource(AppText.request_notification_permission)) } }, onDismissRequest = { } ) } } @Composable fun RationaleDialog() { var showWarningDialog by remember { mutableStateOf(true) } if (showWarningDialog) { AlertDialog( modifier = Modifier.alertDialog(), title = { Text(stringResource(id = AppText.notification_permission_title)) }, text = { Text(stringResource(id = AppText.notification_permission_settings)) }, confirmButton = { TextButton( onClick = { showWarningDialog = false }, modifier = Modifier.textButton(), colors = ButtonDefaults.buttonColors( backgroundColor = BrightOrange, contentColor = Color.White ) ) { Text(text = stringResource(AppText.ok)) } }, onDismissRequest = { showWarningDialog = false } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/TextFieldComposable.kt
1385818777
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.composable import androidx.annotation.StringRes import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Lock import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import com.example.makeitso.R.drawable as AppIcon import com.example.makeitso.R.string as AppText @Composable fun BasicField( @StringRes text: Int, value: String, onNewValue: (String) -> Unit, modifier: Modifier = Modifier ) { OutlinedTextField( singleLine = true, modifier = modifier, value = value, onValueChange = { onNewValue(it) }, placeholder = { Text(stringResource(text)) } ) } @Composable fun EmailField(value: String, onNewValue: (String) -> Unit, modifier: Modifier = Modifier) { OutlinedTextField( singleLine = true, modifier = modifier, value = value, onValueChange = { onNewValue(it) }, placeholder = { Text(stringResource(AppText.email)) }, leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = "Email") } ) } @Composable fun PasswordField(value: String, onNewValue: (String) -> Unit, modifier: Modifier = Modifier) { PasswordField(value, AppText.password, onNewValue, modifier) } @Composable fun RepeatPasswordField( value: String, onNewValue: (String) -> Unit, modifier: Modifier = Modifier ) { PasswordField(value, AppText.repeat_password, onNewValue, modifier) } @Composable private fun PasswordField( value: String, @StringRes placeholder: Int, onNewValue: (String) -> Unit, modifier: Modifier = Modifier ) { var isVisible by remember { mutableStateOf(false) } val icon = if (isVisible) painterResource(AppIcon.ic_visibility_on) else painterResource(AppIcon.ic_visibility_off) val visualTransformation = if (isVisible) VisualTransformation.None else PasswordVisualTransformation() OutlinedTextField( modifier = modifier, value = value, onValueChange = { onNewValue(it) }, placeholder = { Text(text = stringResource(placeholder)) }, leadingIcon = { Icon(imageVector = Icons.Default.Lock, contentDescription = "Lock") }, trailingIcon = { IconButton(onClick = { isVisible = !isVisible }) { Icon(painter = icon, contentDescription = "Visibility") } }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), visualTransformation = visualTransformation ) }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/ButtonComposable.kt
2259013003
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.common.composable import androidx.annotation.StringRes import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.sp @Composable fun BasicTextButton(@StringRes text: Int, modifier: Modifier, action: () -> Unit) { TextButton(onClick = action, modifier = modifier) { Text(text = stringResource(text)) } } @Composable fun BasicButton(@StringRes text: Int, modifier: Modifier, action: () -> Unit) { Button( onClick = action, modifier = modifier, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.primary, contentColor = MaterialTheme.colors.onPrimary ) ) { Text(text = stringResource(text), fontSize = 16.sp) } } @Composable fun DialogConfirmButton(@StringRes text: Int, action: () -> Unit) { Button( onClick = action, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.primary, contentColor = MaterialTheme.colors.onPrimary ) ) { Text(text = stringResource(text)) } } @Composable fun DialogCancelButton(@StringRes text: Int, action: () -> Unit) { Button( onClick = action, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.onPrimary, contentColor = MaterialTheme.colors.primary ) ) { Text(text = stringResource(text)) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoAppState.kt
950698670
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso import android.content.res.Resources import androidx.compose.material.ScaffoldState import androidx.compose.runtime.Stable import androidx.navigation.NavHostController import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.common.snackbar.SnackbarMessage.Companion.toMessage import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch @Stable class MakeItSoAppState( val scaffoldState: ScaffoldState, val navController: NavHostController, private val snackbarManager: SnackbarManager, private val resources: Resources, coroutineScope: CoroutineScope ) { init { coroutineScope.launch { snackbarManager.snackbarMessages.filterNotNull().collect { snackbarMessage -> val text = snackbarMessage.toMessage(resources) scaffoldState.snackbarHostState.showSnackbar(text) snackbarManager.clearSnackbarState() } } } fun popUp() { navController.popBackStack() } fun navigate(route: String) { navController.navigate(route) { launchSingleTop = true } } fun navigateAndPopUp(route: String, popUp: String) { navController.navigate(route) { launchSingleTop = true popUpTo(popUp) { inclusive = true } } } fun clearAndNavigate(route: String) { navController.navigate(route) { launchSingleTop = true popUpTo(0) { inclusive = true } } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/theme/Shape.kt
4147254942
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Make-It-So/start/app/src/main/java/com/example/makeitso/theme/Color.kt
853761130
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.theme import androidx.compose.ui.graphics.Color val BrightOrange = Color(0xFFFF8A65) val MediumOrange = Color(0xFFFFA000) val DarkOrange = Color(0xFFF57C00)
Make-It-So/start/app/src/main/java/com/example/makeitso/theme/Theme.kt
1102309055
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors(primary = BrightOrange, primaryVariant = MediumOrange, secondary = DarkOrange) private val LightColorPalette = lightColors(primary = BrightOrange, primaryVariant = MediumOrange, secondary = DarkOrange) @Composable fun MakeItSoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) { val colors = if (darkTheme) DarkColorPalette else LightColorPalette MaterialTheme(colors = colors, typography = Typography, shapes = Shapes, content = content) }
Make-It-So/start/app/src/main/java/com/example/makeitso/theme/Type.kt
2137908583
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp val Typography = Typography( body1 = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp) )
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoApp.kt
1440630700
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso import android.Manifest import android.content.res.Resources import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.padding import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.makeitso.common.composable.PermissionDialog import com.example.makeitso.common.composable.RationaleDialog import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.screens.edit_task.EditTaskScreen import com.example.makeitso.screens.login.LoginScreen import com.example.makeitso.screens.settings.SettingsScreen import com.example.makeitso.screens.sign_up.SignUpScreen import com.example.makeitso.screens.splash.SplashScreen import com.example.makeitso.screens.tasks.TasksScreen import com.example.makeitso.theme.MakeItSoTheme import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.shouldShowRationale import kotlinx.coroutines.CoroutineScope @Composable @ExperimentalMaterialApi fun MakeItSoApp() { MakeItSoTheme { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { RequestNotificationPermissionDialog() } Surface(color = MaterialTheme.colors.background) { val appState = rememberAppState() Scaffold( snackbarHost = { SnackbarHost( hostState = it, modifier = Modifier.padding(8.dp), snackbar = { snackbarData -> Snackbar(snackbarData, contentColor = MaterialTheme.colors.onPrimary) } ) }, scaffoldState = appState.scaffoldState ) { innerPaddingModifier -> NavHost( navController = appState.navController, startDestination = SPLASH_SCREEN, modifier = Modifier.padding(innerPaddingModifier) ) { makeItSoGraph(appState) } } } } } @RequiresApi(Build.VERSION_CODES.TIRAMISU) @OptIn(ExperimentalPermissionsApi::class) @Composable fun RequestNotificationPermissionDialog() { val permissionState = rememberPermissionState(permission = Manifest.permission.POST_NOTIFICATIONS) if (!permissionState.status.isGranted) { if (permissionState.status.shouldShowRationale) RationaleDialog() else PermissionDialog { permissionState.launchPermissionRequest() } } } @Composable fun rememberAppState( scaffoldState: ScaffoldState = rememberScaffoldState(), navController: NavHostController = rememberNavController(), snackbarManager: SnackbarManager = SnackbarManager, resources: Resources = resources(), coroutineScope: CoroutineScope = rememberCoroutineScope() ) = remember(scaffoldState, navController, snackbarManager, resources, coroutineScope) { MakeItSoAppState(scaffoldState, navController, snackbarManager, resources, coroutineScope) } @Composable @ReadOnlyComposable fun resources(): Resources { LocalConfiguration.current return LocalContext.current.resources } @ExperimentalMaterialApi fun NavGraphBuilder.makeItSoGraph(appState: MakeItSoAppState) { composable(SPLASH_SCREEN) { SplashScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp) }) } composable(SETTINGS_SCREEN) { SettingsScreen( restartApp = { route -> appState.clearAndNavigate(route) }, openScreen = { route -> appState.navigate(route) } ) } composable(LOGIN_SCREEN) { LoginScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp) }) } composable(SIGN_UP_SCREEN) { SignUpScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp) }) } composable(TASKS_SCREEN) { TasksScreen(openScreen = { route -> appState.navigate(route) }) } composable( route = "$EDIT_TASK_SCREEN$TASK_ID_ARG", arguments = listOf(navArgument(TASK_ID) { nullable = true defaultValue = null }) ) { EditTaskScreen( popUpScreen = { appState.popUp() } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoActivity.kt
1430978422
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.material.ExperimentalMaterialApi import dagger.hilt.android.AndroidEntryPoint // MakeItSoActivity starts the first composable, which uses material cards that are still experimental. // TODO: Update material dependency and experimental annotations once the API stabilizes. @AndroidEntryPoint @ExperimentalMaterialApi class MakeItSoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MakeItSoApp() } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/User.kt
1403811906
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model data class User( val id: String = "", val isAnonymous: Boolean = true )
Make-It-So/start/app/src/main/java/com/example/makeitso/model/Task.kt
2245931431
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model import com.google.firebase.firestore.DocumentId data class Task( @DocumentId val id: String = "", val title: String = "", val priority: String = "", val dueDate: String = "", val dueTime: String = "", val description: String = "", val url: String = "", val flag: Boolean = false, val completed: Boolean = false, val userId: String = "" )
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/AccountService.kt
3798216034
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service import com.example.makeitso.model.User import kotlinx.coroutines.flow.Flow interface AccountService { val currentUserId: String val hasUser: Boolean val currentUser: Flow<User> suspend fun authenticate(email: String, password: String) suspend fun sendRecoveryEmail(email: String) suspend fun createAnonymousAccount() suspend fun linkAccount(email: String, password: String) suspend fun deleteAccount() suspend fun signOut() }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/impl/ConfigurationServiceImpl.kt
3212164902
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service.impl import com.example.makeitso.BuildConfig import com.example.makeitso.R.xml as AppConfig import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.trace import com.google.firebase.Firebase import com.google.firebase.remoteconfig.get import com.google.firebase.remoteconfig.remoteConfig import com.google.firebase.remoteconfig.remoteConfigSettings import javax.inject.Inject import kotlinx.coroutines.tasks.await class ConfigurationServiceImpl @Inject constructor() : ConfigurationService { private val remoteConfig get() = Firebase.remoteConfig init { if (BuildConfig.DEBUG) { val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 0 } remoteConfig.setConfigSettingsAsync(configSettings) } remoteConfig.setDefaultsAsync(AppConfig.remote_config_defaults) } override suspend fun fetchConfiguration(): Boolean { return remoteConfig.fetchAndActivate().await() } override val isShowTaskEditButtonConfig: Boolean get() = remoteConfig[SHOW_TASK_EDIT_BUTTON_KEY].asBoolean() companion object { private const val SHOW_TASK_EDIT_BUTTON_KEY = "show_task_edit_button" private const val FETCH_CONFIG_TRACE = "fetchConfig" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/impl/LogServiceImpl.kt
2708706399
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service.impl import com.example.makeitso.model.service.LogService import com.google.firebase.crashlytics.crashlytics import com.google.firebase.Firebase import javax.inject.Inject class LogServiceImpl @Inject constructor() : LogService { override fun logNonFatalCrash(throwable: Throwable) = Firebase.crashlytics.recordException(throwable) }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/impl/StorageServiceImpl.kt
1482793090
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service.impl import com.example.makeitso.model.Task import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.StorageService import com.example.makeitso.model.service.trace import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.dataObjects import com.google.firebase.firestore.toObject import kotlinx.coroutines.ExperimentalCoroutinesApi import javax.inject.Inject import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.tasks.await class StorageServiceImpl @Inject constructor(private val firestore: FirebaseFirestore, private val auth: AccountService) : StorageService { @OptIn(ExperimentalCoroutinesApi::class) override val tasks: Flow<List<Task>> get() = auth.currentUser.flatMapLatest { user -> firestore.collection(TASK_COLLECTION).whereEqualTo(USER_ID_FIELD, user.id).dataObjects() } override suspend fun getTask(taskId: String): Task? = firestore.collection(TASK_COLLECTION).document(taskId).get().await().toObject() override suspend fun save(task: Task): String = trace(SAVE_TASK_TRACE) { val taskWithUserId = task.copy(userId = auth.currentUserId) firestore.collection(TASK_COLLECTION).add(taskWithUserId).await().id } override suspend fun update(task: Task): Unit = trace(UPDATE_TASK_TRACE) { firestore.collection(TASK_COLLECTION).document(task.id).set(task).await() } override suspend fun delete(taskId: String) { firestore.collection(TASK_COLLECTION).document(taskId).delete().await() } companion object { private const val USER_ID_FIELD = "userId" private const val TASK_COLLECTION = "tasks" private const val SAVE_TASK_TRACE = "saveTask" private const val UPDATE_TASK_TRACE = "updateTask" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/impl/AccountServiceImpl.kt
2549228533
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service.impl import com.example.makeitso.model.User import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.trace import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.FirebaseAuth import javax.inject.Inject import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.tasks.await class AccountServiceImpl @Inject constructor(private val auth: FirebaseAuth) : AccountService { override val currentUserId: String get() = auth.currentUser?.uid.orEmpty() override val hasUser: Boolean get() = auth.currentUser != null override val currentUser: Flow<User> get() = callbackFlow { val listener = FirebaseAuth.AuthStateListener { auth -> this.trySend(auth.currentUser?.let { User(it.uid, it.isAnonymous) } ?: User()) } auth.addAuthStateListener(listener) awaitClose { auth.removeAuthStateListener(listener) } } override suspend fun authenticate(email: String, password: String) { auth.signInWithEmailAndPassword(email, password).await() } override suspend fun sendRecoveryEmail(email: String) { auth.sendPasswordResetEmail(email).await() } override suspend fun createAnonymousAccount() { auth.signInAnonymously().await() } override suspend fun linkAccount(email: String, password: String): Unit = trace(LINK_ACCOUNT_TRACE) { val credential = EmailAuthProvider.getCredential(email, password) auth.currentUser!!.linkWithCredential(credential).await() } override suspend fun deleteAccount() { auth.currentUser!!.delete().await() } override suspend fun signOut() { if (auth.currentUser!!.isAnonymous) { auth.currentUser!!.delete() } auth.signOut() // Sign the user back in anonymously. createAnonymousAccount() } companion object { private const val LINK_ACCOUNT_TRACE = "linkAccount" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/StorageService.kt
3776703124
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service import com.example.makeitso.model.Task import kotlinx.coroutines.flow.Flow interface StorageService { val tasks: Flow<List<Task>> suspend fun getTask(taskId: String): Task? suspend fun save(task: Task): String suspend fun update(task: Task) suspend fun delete(taskId: String) }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/LogService.kt
1169723534
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service interface LogService { fun logNonFatalCrash(throwable: Throwable) }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/module/FirebaseModule.kt
126683842
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service.module import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.firestore import com.google.firebase.Firebase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) object FirebaseModule { @Provides fun auth(): FirebaseAuth = Firebase.auth @Provides fun firestore(): FirebaseFirestore = Firebase.firestore }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/module/ServiceModule.kt
4097149919
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service.module import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.model.service.impl.AccountServiceImpl import com.example.makeitso.model.service.impl.ConfigurationServiceImpl import com.example.makeitso.model.service.impl.LogServiceImpl import com.example.makeitso.model.service.impl.StorageServiceImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class ServiceModule { @Binds abstract fun provideAccountService(impl: AccountServiceImpl): AccountService @Binds abstract fun provideLogService(impl: LogServiceImpl): LogService @Binds abstract fun provideStorageService(impl: StorageServiceImpl): StorageService @Binds abstract fun provideConfigurationService(impl: ConfigurationServiceImpl): ConfigurationService }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/ConfigurationService.kt
2660525166
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service interface ConfigurationService { suspend fun fetchConfiguration(): Boolean val isShowTaskEditButtonConfig: Boolean }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/Performance.kt
4004830988
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model.service import com.google.firebase.perf.trace import com.google.firebase.perf.metrics.Trace /** * Trace a block with Firebase performance. * * Supports both suspend and regular methods. */ inline fun <T> trace(name: String, block: Trace.() -> T): T = Trace.create(name).trace(block)
Make-It-So/start/app/src/main/java/com/example/makeitso/model/Priority.kt
2868633218
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.model enum class Priority { None, Low, Medium, High; companion object { fun getByName(name: String?): Priority { values().forEach { priority -> if (name == priority.name) return priority } return None } fun getOptions(): List<String> { val options = mutableListOf<String>() values().forEach { priority -> options.add(priority.name) } return options } } }
pempek_arridho/app/src/androidTest/java/com/example/pempekarridho/ExampleInstrumentedTest.kt
2780013099
package com.example.pempekarridho import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.pempekarridho", appContext.packageName) } }
pempek_arridho/app/src/test/java/com/example/pempekarridho/ExampleUnitTest.kt
430766860
package com.example.pempekarridho import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/MainActivity.kt
1252855650
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class MainActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) val btnClick: Button = findViewById(R.id.myButton) btnClick.setOnClickListener(this) } override fun onClick(v: View?) { if (v !=null) { when(v.id){ R.id.myButton -> { val pindahIntent = Intent(this, LoginPageActivity::class.java) startActivity(pindahIntent) } } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/firstpage2.kt
1399321558
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class firstpage2 : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_firstpage2) val btnClick = findViewById<Button>(R.id.fpButton2) btnClick.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.fpButton2 -> { val heIntent = Intent(this, BerandaActivity::class.java) startActivity(heIntent) } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/SelamatActivity.kt
737736961
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class SelamatActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_selamat) val btnClick = findViewById<Button>(R.id.myButton4) btnClick.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.myButton4 -> { val hiIntent = Intent(this, firstpage1::class.java) startActivity(hiIntent) } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/firstpage1.kt
704176085
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class firstpage1 : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_firstpage1) val btnClick = findViewById<Button>(R.id.myButton2) btnClick.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.myButton2 -> { val hiIntent = Intent(this, firstpage2::class.java) startActivity(hiIntent) } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/BerandaActivity.kt
2562729939
package com.example.pempekarridho import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class BerandaActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_beranda) } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/LoginPageActivity.kt
2674885604
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class LoginPageActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login_page) val btnClick = findViewById<Button>(R.id.myButton1) btnClick.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.myButton1 -> { val hiIntent = Intent(this, SelamatActivity::class.java) startActivity(hiIntent) } } } }
MyNavigation/app/src/androidTest/java/com/example/mynavigation/ExampleInstrumentedTest.kt
3151358782
package com.example.mynavigation import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.mynavigation", appContext.packageName) } }
MyNavigation/app/src/test/java/com/example/mynavigation/ExampleUnitTest.kt
3044056294
package com.example.mynavigation import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MyNavigation/app/src/main/java/com/example/mynavigation/MainActivity.kt
4038538502
package com.example.mynavigation import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.navigation.NavigationView class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration : AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.toolbar)) val navHostFragment = supportFragmentManager. findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = navHostFragment.navController //Creating top level destinations //and adding them to the draw appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home, R.id.nav_recent, R.id.nav_favorites, R.id.nav_archive, R.id.nav_bin), findViewById(R.id.drawer_layout) ) setupActionBarWithNavController(navController, appBarConfiguration) findViewById<NavigationView>(R.id.nav_view)?.setupWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
MyNavigation/app/src/main/java/com/example/mynavigation/RecentFragment.kt
2331578904
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [RecentFragment.newInstance] factory method to * create an instance of this fragment. */ class RecentFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_recent, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment RecentFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = RecentFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/SettingsFragment.kt
3791677257
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [SettingsFragment.newInstance] factory method to * create an instance of this fragment. */ class SettingsFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_settings, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SettingsFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = SettingsFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/ArchiveFragment.kt
2062754989
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [ArchiveFragment.newInstance] factory method to * create an instance of this fragment. */ class ArchiveFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_archive, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ArchiveFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = ArchiveFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/HomeFragment.kt
2720406254
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.navigation.Navigation class HomeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_home , container, false) view.findViewById<Button>(R.id.button_home)?.setOnClickListener ( Navigation.createNavigateOnClickListener(R.id.nav_home_to_content, null) ) return view } }
MyNavigation/app/src/main/java/com/example/mynavigation/BinFragment.kt
706842281
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [BinFragment.newInstance] factory method to * create an instance of this fragment. */ class BinFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_bin, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment BinFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = BinFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/FavoritesFragment.kt
2934125883
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [FavoritesFragment.newInstance] factory method to * create an instance of this fragment. */ class FavoritesFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_favorites, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FavoritesFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = FavoritesFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/ContentFragment.kt
1501119856
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [ContentFragment.newInstance] factory method to * create an instance of this fragment. */ class ContentFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_content, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ContentFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = ContentFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
hw4_m5/app/src/androidTest/java/com/example/hw4/ExampleInstrumentedTest.kt
1788569846
package com.example.hw4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.hw4", appContext.packageName) } }
hw4_m5/app/src/test/java/com/example/hw4/ExampleUnitTest.kt
2430224473
package com.example.hw4 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
hw4_m5/app/src/main/java/com/example/hw4/OnBoardingModel.kt
2145399994
package com.example.hw4 data class OnBoardingModel( val title: String? = null, val desc: String? = null, val lottieAnim: Int? = null )
hw4_m5/app/src/main/java/com/example/hw4/App.kt
2272700485
package com.example.hw4 import android.app.Application import androidx.room.Room import com.example.hw4.data.room.AppDatabase import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.HiltAndroidApp import javax.inject.Inject @HiltAndroidApp class App : Application() { companion object { lateinit var appDatabase: AppDatabase } override fun onCreate() { super.onCreate() appDatabase = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "love-file") .allowMainThreadQueries().build() } /*Room.databaseBuilder(applicationContext, AppDatabase::class.java, "love-file") .allowMainThreadQueries().build()*/ }
hw4_m5/app/src/main/java/com/example/hw4/MainActivity.kt
1507524381
package com.example.hw4 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.viewModels import androidx.lifecycle.Observer import androidx.navigation.NavController import androidx.navigation.Navigation.findNavController import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import com.example.hw4.data.local.Pref import com.example.hw4.databinding.ActivityMainBinding import com.example.hw4.remote.LoveModel import com.example.hw4.remote.RetrofitService import dagger.hilt.android.AndroidEntryPoint import retrofit2.Call import retrofit2.Callback import retrofit2.Response import javax.inject.Inject @AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var pref: Pref private lateinit var binding: ActivityMainBinding private var navController: NavController? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController if (!pref.isShow()) { navController?.navigate(R.id.onBoardingFragment) } } }
hw4_m5/app/src/main/java/com/example/hw4/di/AppModule.kt
1637101049
package com.example.hw4.di import android.content.Context import android.content.SharedPreferences import androidx.room.Room import com.example.hw4.data.local.Pref import com.example.hw4.data.room.AppDatabase import com.example.hw4.data.room.LoveDao import com.example.hw4.remote.LoveApi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory @InstallIn(SingletonComponent::class) @Module class AppModule { @Provides fun provideApi(): LoveApi { return Retrofit.Builder().baseUrl("https://love-calculator.p.rapidapi.com/") .addConverterFactory(GsonConverterFactory.create()).build().create(LoveApi::class.java) } @Provides fun provideSharedPreferences(@ApplicationContext context: Context): SharedPreferences { return context.getSharedPreferences(Pref.PREF_NAME, Context.MODE_PRIVATE) } @Provides fun providePref(sharedPreferences: SharedPreferences): Pref { return Pref(sharedPreferences) } @Provides fun provideDatabase(@ApplicationContext context: Context):AppDatabase{ return Room.databaseBuilder(context, AppDatabase::class.java, "love-file") .allowMainThreadQueries().build() } @Provides fun provideDao(appDatabase: AppDatabase):LoveDao{ return appDatabase.getDao() } }
hw4_m5/app/src/main/java/com/example/hw4/HistoryFragment.kt
341922323
package com.example.hw4 import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import com.example.hw4.data.room.LoveDao import com.example.hw4.databinding.FragmentHistoryBinding import com.example.hw4.remote.LoveModel import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class HistoryFragment : Fragment() { @Inject lateinit var dao: LoveDao private val viewModel: LoveViewModel by viewModels() private lateinit var binding: FragmentHistoryBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHistoryBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.getGetDao().observe(viewLifecycleOwner, Observer {loveModelList -> val list = mutableListOf<LoveModel>() loveModelList?.let { list.add(it) } binding.tvListHistory.text =list.joinToString( separator = "\n", transform = { it.toString() }, prefix = "", postfix = "" ) /*list.joinToString(separator = "", prefix = "", postfix = "")*/ }) /* val list = dao.getAll() list.forEach { binding.tvListHistory.text = list.joinToString(separator = "", prefix = "", postfix = "") }*/ } } /* viewModel.getLiveLoveData(etFirstName.text.toString(), etSecondName.text.toString()) .observe(viewLifecycleOwner, Observer { tvResult.text = it.toString() })*/
hw4_m5/app/src/main/java/com/example/hw4/utils/Ext.kt
412421294
package com.example.hw4.utils import android.content.Context import android.widget.ImageView import android.widget.Toast import androidx.fragment.app.Fragment import com.bumptech.glide.Glide fun Context.showToast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } fun Fragment.showToast(msg: String){ Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show() } fun ImageView.loadImage(url: String?){ Glide.with(this).load(url).into(this) }
hw4_m5/app/src/main/java/com/example/hw4/Repository.kt
147820358
package com.example.hw4 import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.hw4.data.room.LoveDao import com.example.hw4.remote.LoveApi import com.example.hw4.remote.LoveModel import com.example.hw4.remote.RetrofitService import retrofit2.Call import retrofit2.Callback import retrofit2.Response import javax.inject.Inject class Repository @Inject constructor(private val api: LoveApi, private val dao: LoveDao) { fun getDao(): LiveData<LoveModel>{ return dao.getAll() } fun getData(firstName: String, secondName: String): MutableLiveData<LoveModel> { val love = MutableLiveData<LoveModel>() api.getLove(firstName, secondName).enqueue(object : Callback<LoveModel> { override fun onResponse(call: Call<LoveModel>, response: Response<LoveModel>) { if (response.isSuccessful) { response.body()?.let { love.postValue(it) dao.insert(it) } } } override fun onFailure(call: Call<LoveModel>, t: Throwable) { Log.e("ololo", "onFailure:${t.message}") } }) return love } }
hw4_m5/app/src/main/java/com/example/hw4/LoveViewModel.kt
829418072
package com.example.hw4 import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import com.example.hw4.remote.LoveModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class LoveViewModel @Inject constructor(private val repository: Repository) : ViewModel() { fun getLiveLoveData(firstName: String, secondName: String): LiveData<LoveModel> { return repository.getData(firstName, secondName) } fun getGetDao(): LiveData<LoveModel>{ return repository.getDao() } }
hw4_m5/app/src/main/java/com/example/hw4/MainFragment.kt
1618039045
package com.example.hw4 import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.viewModels import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.NavController import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.findNavController import com.example.hw4.databinding.FragmentHistoryBinding import com.example.hw4.databinding.FragmentMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainFragment : Fragment() { private lateinit var binding : FragmentMainBinding private val viewModel: LoveViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentMainBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initClickers() } private fun initClickers() { with(binding) { btnGetLove.setOnClickListener { viewModel.getLiveLoveData(etFirstName.text.toString(), etSecondName.text.toString()) .observe(viewLifecycleOwner, Observer { tvResult.text = it.toString() }) } btnHistory.setOnClickListener { findNavController().navigate(R.id.historyFragment) } } } }
hw4_m5/app/src/main/java/com/example/hw4/data/room/LoveDao.kt
943136451
package com.example.hw4.data.room import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.example.hw4.remote.LoveModel @Dao interface LoveDao { @Insert fun insert(lioveModel: LoveModel) /* ORDER BY fname ASC*/ @Query ("SELECT * FROM `love-table` ORDER BY fname ASC") fun getAll(): LiveData<LoveModel> }
hw4_m5/app/src/main/java/com/example/hw4/data/room/AppDatabase.kt
2008963179
package com.example.hw4.data.room import androidx.room.Database import androidx.room.RoomDatabase import com.example.hw4.remote.LoveModel @Database(entities = [LoveModel::class], version = 1) abstract class AppDatabase:RoomDatabase() { abstract fun getDao():LoveDao }
hw4_m5/app/src/main/java/com/example/hw4/data/local/Pref.kt
3893725485
package com.example.hw4.data.local import android.content.Context import android.content.SharedPreferences import javax.inject.Inject class Pref @Inject constructor(private val preferences: SharedPreferences) { fun isShow(): Boolean { return preferences.getBoolean(SHOWED_KEY, false) } fun onShowed() { preferences.edit().putBoolean(SHOWED_KEY, true).apply() } companion object { const val PREF_NAME = "pref.name" const val SHOWED_KEY = "showed.key" } }
hw4_m5/app/src/main/java/com/example/hw4/onboarding/adapter/OnBoardingAdapter.kt
3957033754
package com.example.hw4.onboarding.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.airbnb.lottie.LottieDrawable import com.example.hw4.OnBoardingModel import com.example.hw4.R import com.example.hw4.databinding.ItemOnboardingBinding class OnBoardingAdapter(private val onClick: () -> Unit) : RecyclerView.Adapter<OnBoardingAdapter.OnBoardingViewHolder>() { private val list = arrayListOf<OnBoardingModel>( OnBoardingModel( "Have a good time", "You should take the time to help those who need you", R.raw.love2 ), OnBoardingModel( "Cherishing love", "It is no longer possible for you to cherish love", R.raw.love3 ), OnBoardingModel( "Have a breakup?", "We have the correction for you don't worry \n mayby someone is waiting for you!", R.raw.love4 ), OnBoardingModel("It's funs and many more!", "", R.raw.lovekiss) ) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OnBoardingViewHolder { return OnBoardingViewHolder( ItemOnboardingBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemCount(): Int = list.size override fun onBindViewHolder(holder: OnBoardingViewHolder, position: Int) { holder.bind(list[position]) } inner class OnBoardingViewHolder(private val binding: ItemOnboardingBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(onBoarding: OnBoardingModel) = with(binding) { tvTitle.text = onBoarding.title tvDesc.text = onBoarding.desc btnGetStarted.isVisible = adapterPosition == list.lastIndex onBoarding.lottieAnim?.let { ivBoard.setAnimation(onBoarding.lottieAnim) ivBoard.playAnimation() } btnGetStarted.setOnClickListener { onClick() } } } }
hw4_m5/app/src/main/java/com/example/hw4/onboarding/OnBoardingFragment.kt
962165509
package com.example.hw4.onboarding import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.example.hw4.data.local.Pref import com.example.hw4.databinding.FragmentOnBoardingBinding import com.example.hw4.onboarding.adapter.OnBoardingAdapter import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class OnBoardingFragment : Fragment() { @Inject lateinit var pref: Pref private lateinit var binding: FragmentOnBoardingBinding private val adapter = OnBoardingAdapter(this::onClick) private fun onClick() { pref.onShowed() findNavController().navigateUp() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentOnBoardingBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.viewPager.adapter = adapter binding.indicator.setViewPager(binding.viewPager) } }
hw4_m5/app/src/main/java/com/example/hw4/remote/RetrofitService.kt
2863948930
package com.example.hw4.remote import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory //https://love-calculator.p.rapidapi.com/getPercentage?sname=Alice&fname=John object RetrofitService { val retrofit = Retrofit.Builder().baseUrl("https://love-calculator.p.rapidapi.com/") .addConverterFactory(GsonConverterFactory.create()).build() val api = retrofit.create(LoveApi::class.java) }
hw4_m5/app/src/main/java/com/example/hw4/remote/LoveModel.kt
2939710675
package com.example.hw4.remote import androidx.room.Entity import androidx.room.PrimaryKey @Entity("love-table") data class LoveModel( val fname: String, val sname: String, val percentage: String, val result: String, @PrimaryKey(autoGenerate = true) var id: Int? = null ){ override fun toString(): String { return "\n$percentage \n$fname \n$sname \n$result\n" } }
hw4_m5/app/src/main/java/com/example/hw4/remote/LoveApi.kt
2199092021
package com.example.hw4.remote import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Query //https://love-calculator.p.rapidapi.com/getPercentage?sname=Alice&fname=John /* .addHeader("X-RapidAPI-Key", "62046210eamshb1039cc3a834d5ep160059jsn329f9fbbe521") .addHeader("X-RapidAPI-Host", "love-calculator.p.rapidapi.com")*/ interface LoveApi { @GET("getPercentage") fun getLove(@Query("sname")secondName:String,@Query("fname")firstName:String, @Header("X-RapidAPI-Key")key:String ="62046210eamshb1039cc3a834d5ep160059jsn329f9fbbe521", @Header("X-RapidAPI-Host")host: String="love-calculator.p.rapidapi.com"): Call<LoveModel> }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/util/Constant.kt
2764580886
package com.theminesec.example.headless.util const val TAG = "ClientApp"
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/ClientHeadlessImpl.kt
467447061
package com.theminesec.example.headless import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.dp import com.theminesec.sdk.headless.HeadlessActivity import com.theminesec.sdk.headless.model.transaction.Amount import com.theminesec.sdk.headless.model.transaction.PaymentMethod import com.theminesec.sdk.headless.ui.ThemeProvider import com.theminesec.sdk.headless.ui.UiProvider import com.theminesec.sdk.headless.ui.UiState class ClientHeadlessImpl : HeadlessActivity() { override fun provideTheme(): ThemeProvider = ClientHeadlessThemeProvider() override fun provideUi(): UiProvider = ClientUiProvider() } class ClientHeadlessThemeProvider : ThemeProvider() { override fun provideColors(darkTheme: Boolean): HeadlessColors { return if (darkTheme) { HeadlessColorsDark().copy( primary = Color(0xFFD5A23B).toArgb() ) } else { HeadlessColorsLight().copy( primary = Color(0xFFFFC145).toArgb() ) } } } class ClientUiProvider : UiProvider() { @Composable override fun AmountDisplay(amount: Amount, description: String?) { Box( modifier = Modifier.border(1.dp, Color.Red), contentAlignment = Alignment.Center ) { super.AmountDisplay(amount, description) } } @Composable override fun AcceptanceMarkDisplay(supportedPayments: List<PaymentMethod>, showWallet: Boolean) { Box( modifier = Modifier.border(1.dp, Color.Red), contentAlignment = Alignment.Center ) { super.AcceptanceMarkDisplay(supportedPayments, true) } } @Composable override fun AwaitCardIndicator() { Box( modifier = Modifier .fillMaxSize() .border(1.dp, Color.Red), ) { super.AwaitCardIndicator() } } @Composable override fun ProgressIndicator() { Box( modifier = Modifier.border(1.dp, Color.Red), contentAlignment = Alignment.Center ) { super.ProgressIndicator() } } @Composable override fun UiStateDisplay(modifier: Modifier, uiState: UiState, countdownSec: Int) { Box( modifier = Modifier.border(1.dp, Color.Red), contentAlignment = Alignment.Center ) { super.UiStateDisplay(modifier, uiState, countdownSec) } } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/component/Button.kt
3663776092
package com.theminesec.example.headless.exampleHelper.component import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun Button( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, content: @Composable RowScope.() -> Unit, ) { Button( modifier = modifier .fillMaxWidth() .defaultMinSize(minHeight = 48.dp, minWidth = 72.dp), onClick = onClick, enabled = enabled, colors = ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.onPrimary, ), shape = RoundedCornerShape(size = 8.dp), content = content ) }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/component/ObjectDisplay.kt
4280435690
package com.theminesec.example.headless.exampleHelper.component import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import java.time.LocalDateTime import java.time.format.DateTimeFormatter @Composable fun ObjectDisplay(text: String) { val formatter = remember { DateTimeFormatter.ofPattern("HH:mm:ss.SSS") } Row { Text( style = MaterialTheme.typography.labelSmall, color = Color(0xff28fe14), text = formatter.format(LocalDateTime.now()), modifier = Modifier.padding(end = 8.dp) ) Text( style = MaterialTheme.typography.labelSmall, color = Color(0xff28fe14), text = text ) } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/component/SplitSection.kt
1296104619
package com.theminesec.example.headless.exampleHelper.component import androidx.compose.foundation.background import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.theminesec.example.headless.R @Composable fun SplitSection( upperContent: @Composable () -> Unit, lowerContent: @Composable () -> Unit, ) { val density = LocalDensity.current.density val screenHeight = LocalConfiguration.current.screenHeightDp var upperColumnHeight by remember { // initial 600.dp.value * screen density mutableFloatStateOf(600 * density) } var isDragging by remember { mutableStateOf(false) } val dragState = rememberDraggableState { delta -> upperColumnHeight = (upperColumnHeight + delta) .coerceAtLeast(100 * density) .coerceAtMost((screenHeight - 100) * density) } Column(modifier = Modifier.fillMaxSize()) { Column( modifier = Modifier .height((upperColumnHeight / density).dp) .padding(horizontal = 16.dp) .verticalScroll(rememberScrollState()), ) { Spacer(modifier = Modifier.height(16.dp)) Text(text = stringResource(id = R.string.app_name), style = MaterialTheme.typography.headlineMedium) Spacer(modifier = Modifier.height(16.dp)) upperContent() Spacer(modifier = Modifier.height(16.dp)) } Box( modifier = Modifier .fillMaxWidth() .background(Color.White.copy(if (isDragging) 0.3f else 0.1f)) .padding(8.dp) .draggable( orientation = Orientation.Vertical, state = dragState, onDragStarted = { isDragging = true }, onDragStopped = { isDragging = false } ), contentAlignment = Alignment.Center ) { Box( modifier = Modifier .width(72.dp) .height(6.dp) .background(Color.White.copy(alpha = 0.4f), RoundedCornerShape(8.dp)) ) } Column( modifier = Modifier.fillMaxSize() ) { lowerContent() } } }