Continuing the work I did with Yowwlr, the Twitter for Cats client that I started building to show how to use Flexbox, I thought the next thing to tackle would be a clone of Twitter’s “messages” tab, which is essentially a chat interface showing bubbles when a user wants to chat. Digging into Twitter, which is a deceptively simple-looking app, you notice several peculiarities. Some of them are a little too complicated for this article, like the little speech arrow that’s added on to the bubble, but only in the case of the last part of the chat. Many elements, however, are easily clonable in a NativeScript app. I turned my attention to building a realistic chat UI similar to Twitter’s using Firebase database’s realtime features, and
duplicating this interface for both Android and iOS. Here’s an example of Twitter’s chat interface, as a reference:
Note the static chat box that sits on top of the Tab navigation. A ScrollView needs to sit on top of that. The first part of this challenge, then, involves going back to our tried-and-true StackLayout, which embeds a ScrollView on the top and a StackLayout on the bottom:
In the ScrollView, which forces the textfield and button to the bottom by maintaining 90% height, we do some sneaky things to differentiate the style of chat depending on who’s chatting. As in Twitter, if your own chat shows in the window, you don’t see your own image and the chat bubble is aligned right. If you’re watching your friend chat to you, those bubbles are aligned left and you see an image of the person (or cat) who’s chatting.
Note: In the actual Twitter app, you see a list of potential chat-mates, choose one, and then initiate a chat. I didn’t built out that part but it wouldn’t be hard to implement. For this demo, I manually added a chat-mate as the recipient.
Differentiating your own chat words from a chat-mate's is done via CSS and some data-bound properties. Within a ListView's template, I added a StackLayout with a label and an image. The StackLayout has a class that switches depending on the identity of the users, and its horizontalAlignment switches from left to right as well. The image of the user similarly switches visibility based on the user’s status.
Logging into the Yowwlr app as two different users, we can test our interface cross-platform:
Another challenge was to make the ListView display the data in reverse order. I did this by sorting the data coming from the chats in reverse order (newest on the bottom). Once received, the array is sorted by date, in reverse: