Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add basic chat app, that sends and receives messages using ChatApi #10

Merged
merged 1 commit into from
Sep 6, 2024

Conversation

ttypic
Copy link
Collaborator

@ttypic ttypic commented Sep 3, 2024

Add some functionality to the sample app

Summary by CodeRabbit

  • New Features

    • Introduced a chat interface in the app, allowing users to load and send messages in a chat room.
    • Added functionality to read local properties for sensitive keys, enhancing security and flexibility in build configurations.
    • Adjusted the layout behavior to prevent UI elements from being obscured by the on-screen keyboard.
  • Bug Fixes

    • Improved handling of message input and sending status to ensure a smoother user experience.
  • Chores

    • Updated indentation settings for better code readability.
    • Enhanced build configuration to enable BuildConfig as bytecode for more efficient access at runtime.

Copy link

coderabbitai bot commented Sep 3, 2024

Walkthrough

The changes involve updates to the Android project configuration and the MainActivity class. The build.gradle.kts file now supports reading local properties for sensitive keys, while the MainActivity has been enhanced to include a new chat interface. Additionally, the gradle.properties file has a new configuration option to improve BuildConfig capabilities. Import layout settings and indentation rules have also been simplified.

Changes

Files Change Summary
.editorconfig Modified ij_kotlin_imports_layout to a simpler configuration, reducing specificity in import layout.
.idea/codeStyles/Project.xml Adjusted INDENT_SIZE and TAB_SIZE from 2 to 4; removed several language-specific code style settings.
example/build.gradle.kts Added getLocalProperty function to read local properties; modified android block for ABLY_KEY; enabled buildConfig.
example/src/main/AndroidManifest.xml Added android:windowSoftInputMode="adjustResize" to <activity> for better keyboard handling.
example/src/main/java/com/ably/chat/example/MainActivity.kt Replaced Greeting function with Chat, implementing a chat interface with state management and message handling.
gradle.properties Introduced android.enableBuildConfigAsBytecode=true to enhance BuildConfig capabilities.

Poem

🐇 In the meadow where rabbits play,
New features hop in, brightening the day!
With chat and keys, oh what a delight,
Our code now dances, taking flight!
So let's celebrate, with joy and cheer,
For every change brings us near! 🌼✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 727b8d2 and 1a5dea1.

Files selected for processing (3)
  • example/build.gradle.kts (4 hunks)
  • example/src/main/java/com/ably/chat/example/MainActivity.kt (2 hunks)
  • gradle.properties (1 hunks)
Additional comments not posted (5)
gradle.properties (1)

19-19: LGTM!

The code change is approved.

example/build.gradle.kts (4)

1-3: LGTM!

The imports are necessary for the getLocalProperty function.


26-27: LGTM!

The change is useful for managing sensitive keys like ABLY_KEY without hardcoding them in the source code. The getLocalProperty function is used correctly to read the value of ABLY_KEY from the local properties file.


47-47: LGTM!

Enabling the buildConfig feature is necessary for the new buildConfigField declaration for ABLY_KEY to be recognized during the build process.


79-87: LGTM!

The getLocalProperty function is well-implemented and follows best practices:

  • It handles the case when the local properties file does not exist by returning null.
  • It uses InputStreamReader with UTF-8 charset to read the file contents.
  • It closes the reader properly using the use function.

The function is useful for reading sensitive keys from a local properties file without hardcoding them in the source code.

Comment on lines 62 to 119
fun AblyChat(chatApi: ChatApi, modifier: Modifier = Modifier) {
var messageText by remember { mutableStateOf(TextFieldValue("")) }
var sending by remember { mutableStateOf(false) }
var messages by remember { mutableStateOf(listOf<Message>()) }
val coroutineScope = rememberCoroutineScope()

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
AblyChatExampleTheme {
Greeting("Android")
val roomId = "my-room"

Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceBetween,
) {
Button(modifier = modifier.align(Alignment.CenterHorizontally), onClick = {
coroutineScope.launch {
messages = chatApi.getMessages(roomId, QueryOptions()).items
}
}) {
Text("Load")
}

LazyColumn(
modifier = Modifier.weight(1f).padding(16.dp),
) {
items(messages.size) { index ->
Text(text = messages[index].text)
}
}

Row(
modifier = Modifier.padding(16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
TextField(
value = messageText,
onValueChange = { messageText = it },
modifier = Modifier.weight(1f),
readOnly = sending,
)
Button(enabled = !sending, onClick = {
sending = true
coroutineScope.launch {
chatApi.sendMessage(
roomId,
SendMessageParams(
text = messageText.text,
),
)
messageText = TextFieldValue("")
sending = false
}
}) {
Text("Send")
}
}
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve the reusability and accessibility of the AblyChat function.

The AblyChat function is well-structured and uses appropriate Jetpack Compose components and state management techniques. However, there are a few areas that can be improved:

  1. Pass the roomId as a parameter to make the function more reusable.
  2. Use the items extension function instead of itemsIndexed for better performance.
  3. Use the OutlinedTextField component for better accessibility.
  4. Use the OutlinedButton component for better accessibility.
  5. Disable the Button when the message text is empty.
  6. Show a loading indicator when a message is being sent.
  7. Show an error message if sending a message fails.
  8. Show a success message if sending a message succeeds.

Apply this diff to implement the suggested improvements:

-fun AblyChat(chatApi: ChatApi, modifier: Modifier = Modifier) {
+fun AblyChat(chatApi: ChatApi, roomId: String, modifier: Modifier = Modifier) {
     var messageText by remember { mutableStateOf(TextFieldValue("")) }
     var sending by remember { mutableStateOf(false) }
+    var sendingError by remember { mutableStateOf(false) }
+    var sendingSuccess by remember { mutableStateOf(false) }
     var messages by remember { mutableStateOf(listOf<Message>()) }
     val coroutineScope = rememberCoroutineScope()
 
-    val roomId = "my-room"
-
     Column(
         modifier = Modifier.fillMaxSize(),
         verticalArrangement = Arrangement.SpaceBetween,
     ) {
-        Button(modifier = modifier.align(Alignment.CenterHorizontally), onClick = {
+        OutlinedButton(modifier = modifier.align(Alignment.CenterHorizontally), onClick = {
             coroutineScope.launch {
                 messages = chatApi.getMessages(roomId, QueryOptions()).items
             }
         }) {
             Text("Load")
         }
 
         LazyColumn(
             modifier = Modifier.weight(1f).padding(16.dp),
         ) {
-            items(messages.size) { index ->
-                Text(text = messages[index].text)
+            items(messages) { message ->
+                Text(text = message.text)
             }
         }
 
         Row(
             modifier = Modifier.padding(16.dp),
             horizontalArrangement = Arrangement.spacedBy(8.dp),
         ) {
-            TextField(
+            OutlinedTextField(
                 value = messageText,
                 onValueChange = { messageText = it },
                 modifier = Modifier.weight(1f),
                 readOnly = sending,
             )
-            Button(enabled = !sending, onClick = {
+            OutlinedButton(
+                enabled = !sending && messageText.text.isNotEmpty(),
+                onClick = {
                     sending = true
+                    sendingError = false
+                    sendingSuccess = false
                     coroutineScope.launch {
-                        chatApi.sendMessage(
-                            roomId,
-                            SendMessageParams(
-                                text = messageText.text,
-                            ),
-                        )
+                        try {
+                            chatApi.sendMessage(
+                                roomId,
+                                SendMessageParams(
+                                    text = messageText.text,
+                                ),
+                            )
+                            sendingSuccess = true
+                        } catch (e: Exception) {
+                            sendingError = true
+                        }
                         messageText = TextFieldValue("")
                         sending = false
                     }
                 }
             ) {
-                Text("Send")
+                when {
+                    sending -> {
+                        CircularProgressIndicator(
+                            modifier = Modifier.size(24.dp),
+                            strokeWidth = 2.dp,
+                        )
+                    }
+                    sendingError -> {
+                        Text("Error")
+                    }
+                    sendingSuccess -> {
+                        Text("Sent")
+                    }
+                    else -> {
+                        Text("Send")
+                    }
+                }
             }
         }
     }
 }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fun AblyChat(chatApi: ChatApi, modifier: Modifier = Modifier) {
var messageText by remember { mutableStateOf(TextFieldValue("")) }
var sending by remember { mutableStateOf(false) }
var messages by remember { mutableStateOf(listOf<Message>()) }
val coroutineScope = rememberCoroutineScope()
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
AblyChatExampleTheme {
Greeting("Android")
val roomId = "my-room"
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceBetween,
) {
Button(modifier = modifier.align(Alignment.CenterHorizontally), onClick = {
coroutineScope.launch {
messages = chatApi.getMessages(roomId, QueryOptions()).items
}
}) {
Text("Load")
}
LazyColumn(
modifier = Modifier.weight(1f).padding(16.dp),
) {
items(messages.size) { index ->
Text(text = messages[index].text)
}
}
Row(
modifier = Modifier.padding(16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
TextField(
value = messageText,
onValueChange = { messageText = it },
modifier = Modifier.weight(1f),
readOnly = sending,
)
Button(enabled = !sending, onClick = {
sending = true
coroutineScope.launch {
chatApi.sendMessage(
roomId,
SendMessageParams(
text = messageText.text,
),
)
messageText = TextFieldValue("")
sending = false
}
}) {
Text("Send")
}
}
}
}
fun AblyChat(chatApi: ChatApi, roomId: String, modifier: Modifier = Modifier) {
var messageText by remember { mutableStateOf(TextFieldValue("")) }
var sending by remember { mutableStateOf(false) }
var sendingError by remember { mutableStateOf(false) }
var sendingSuccess by remember { mutableStateOf(false) }
var messages by remember { mutableStateOf(listOf<Message>()) }
val coroutineScope = rememberCoroutineScope()
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceBetween,
) {
OutlinedButton(modifier = modifier.align(Alignment.CenterHorizontally), onClick = {
coroutineScope.launch {
messages = chatApi.getMessages(roomId, QueryOptions()).items
}
}) {
Text("Load")
}
LazyColumn(
modifier = Modifier.weight(1f).padding(16.dp),
) {
items(messages) { message ->
Text(text = message.text)
}
}
Row(
modifier = Modifier.padding(16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(
value = messageText,
onValueChange = { messageText = it },
modifier = Modifier.weight(1f),
readOnly = sending,
)
OutlinedButton(
enabled = !sending && messageText.text.isNotEmpty(),
onClick = {
sending = true
sendingError = false
sendingSuccess = false
coroutineScope.launch {
try {
chatApi.sendMessage(
roomId,
SendMessageParams(
text = messageText.text,
),
)
sendingSuccess = true
} catch (e: Exception) {
sendingError = true
}
messageText = TextFieldValue("")
sending = false
}
}
) {
when {
sending -> {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
strokeWidth = 2.dp,
)
}
sendingError -> {
Text("Error")
}
sendingSuccess -> {
Text("Sent")
}
else -> {
Text("Send")
}
}
}
}
}
}

@ttypic ttypic force-pushed the ECO-4962/chat-api-implementation branch 4 times, most recently from 5c3bcaf to 783cd4a Compare September 5, 2024 12:14
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1a5dea1 and 7c0ec73.

Files selected for processing (6)
  • .editorconfig (1 hunks)
  • .idea/codeStyles/Project.xml (2 hunks)
  • example/build.gradle.kts (4 hunks)
  • example/src/main/AndroidManifest.xml (2 hunks)
  • example/src/main/java/com/ably/chat/example/MainActivity.kt (2 hunks)
  • gradle.properties (1 hunks)
Files skipped from review due to trivial changes (2)
  • .editorconfig
  • .idea/codeStyles/Project.xml
Files skipped from review as they are similar to previous changes (2)
  • example/build.gradle.kts
  • gradle.properties
Additional comments not posted (6)
example/src/main/AndroidManifest.xml (1)

16-16: Approved: Addition of android:windowSoftInputMode="adjustResize"

This change is crucial for chat applications as it prevents the keyboard from covering important UI elements, such as the message input field. Good attention to detail in enhancing user experience.

example/src/main/java/com/ably/chat/example/MainActivity.kt (5)

44-44: Approved: Initialization of RealtimeClient and ChatApi

The initialization of RealtimeClient with appropriate client options and the setup of ChatApi are well-implemented. Using a random client ID for each instance of the app is a good practice for identifying different users in a chat environment.

Also applies to: 49-56


61-61: Approved: Integration of Chat function in UI

The integration of the Chat function within the Scaffold layout ensures that the chat interface is properly managed within the app's UI hierarchy. This setup facilitates a clean and functional user interface.


72-119: Approved: Implementation of Chat function

The Chat function is well-structured, utilizing Jetpack Compose's powerful features for state management and layout. The use of remember and mutableStateOf for managing the state of messages and the sending status is appropriate. The coroutine setup for fetching and sending messages is correctly implemented.


121-142: Approved: MessageBubble Composable Function

The MessageBubble function is a good example of modular code. It encapsulates the UI logic for displaying individual messages, which enhances readability and maintainability. The conditional arrangement and coloring based on the message's owner are well-thought-out, improving the user experience by making it easy to distinguish between sent and received messages.


146-171: Approved: ChatInputField Composable Function

The ChatInputField function effectively handles user input for sending messages. It appropriately disables the input field when a message is being sent, preventing user actions during transmission. The layout and functionality are well-implemented, contributing to a smooth user experience.

@ttypic ttypic merged commit 8ba96d6 into ECO-4962/chat-api-implementation Sep 6, 2024
1 check passed
@ttypic ttypic deleted the feat/basic-example-app branch September 6, 2024 12:59
@ttypic ttypic restored the feat/basic-example-app branch September 6, 2024 13:02
@ttypic ttypic deleted the feat/basic-example-app branch October 18, 2024 11:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant