Composables
Docs Login
Vela

New chat

package com.composables.vela

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.composables.compose.ripple.rememberRippleIndication
import com.composables.uripainter.rememberUriPainter
import com.composables.vela.components.AlertDialog
import com.composables.vela.components.AppBar
import com.composables.vela.components.AttachmentChip
import com.composables.vela.components.Avatar
import com.composables.vela.components.Button
import com.composables.vela.components.ButtonVariant
import com.composables.vela.components.Composer
import com.composables.vela.components.DrawerItem
import com.composables.vela.components.Icon
import com.composables.vela.components.IconButton
import com.composables.vela.components.Markdown
import com.composables.vela.components.MessageActions
import com.composables.vela.components.ModalBottomSheet
import com.composables.vela.components.OptionGroup
import com.composables.vela.components.OptionRow
import com.composables.vela.components.OptionToggle
import com.composables.vela.components.Rating
import com.composables.vela.components.ScreenScaffold
import com.composables.vela.components.ScrollToLatestButton
import com.composables.vela.components.SearchField
import com.composables.vela.components.SideDrawer
import com.composables.vela.components.SuggestionCard
import com.composables.vela.components.Text
import com.composables.vela.components.TextField
import com.composables.vela.components.ThinkingIndicator
import com.composables.vela.components.Toast
import com.composables.vela.components.ToolChip
import com.composables.vela.components.UserMessage
import com.composables.vela.theme.Camera
import com.composables.vela.theme.Check
import com.composables.vela.theme.DotsThree
import com.composables.vela.theme.Export
import com.composables.vela.theme.File
import com.composables.vela.theme.Folder
import com.composables.vela.theme.Ghost
import com.composables.vela.theme.Globe
import com.composables.vela.theme.Icons
import com.composables.vela.theme.Lightbulb
import com.composables.vela.theme.Menu
import com.composables.vela.theme.NotePencil
import com.composables.vela.theme.PencilSimple
import com.composables.vela.theme.PushPin
import com.composables.vela.theme.PushPinSlash
import com.composables.vela.theme.Space
import com.composables.vela.theme.Theme
import com.composables.vela.theme.Trash
import com.composables.vela.theme.VelaMark
import com.composables.vela.theme.X
import com.composeunstyled.UnstyledButton
import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun NewChatScreen(
    navigateToSettings: () -> Unit,
    navigateToUpgrade: () -> Unit,
    navigateToProjects: () -> Unit,
    navigateToVoiceChat: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Chat(
        null,
        navigateToSettings,
        navigateToUpgrade,
        navigateToProjects,
        navigateToVoiceChat,
        modifier,
    )
}

@Composable
fun ChatScreen(
    navigateToSettings: () -> Unit,
    navigateToUpgrade: () -> Unit,
    navigateToProjects: () -> Unit,
    navigateToVoiceChat: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Chat(
        sampleChats.first(),
        navigateToSettings,
        navigateToUpgrade,
        navigateToProjects,
        navigateToVoiceChat,
        modifier,
    )
}

private val MaxReadingWidth = 720.dp

private val ComposerFadeHeight = 12.dp

private enum class Phase {
    Thinking,
    Streaming,
    Done,
    Stopped,
}

@Stable
private class Turn(
    val id: Int,
    val prompt: String,
    val imageUris: List<String>,
    val response: SampleResponse,
    val thinkLonger: Boolean,
    phase: Phase,
) {
    var variant by mutableIntStateOf(0)
    var phase by mutableStateOf(phase)
    var revealed by mutableIntStateOf(if (phase == Phase.Done) response.variants[0].length else 0)
    var rating by mutableStateOf(Rating.None)
    var height by mutableIntStateOf(0)
    var heightKeptWhileRegenerating by mutableIntStateOf(0)
    val answer: String
        get() = response.variants[variant % response.variants.size]
}

@Stable
private class Conversation(val id: Int, title: String, val period: String, turns: List<Turn>) {
    var title by mutableStateOf(title)
    var pinned by mutableStateOf(false)
    var temporary by mutableStateOf(false)
    val turns = mutableStateListOf<Turn>().apply { addAll(turns) }
    val listState = LazyListState()
}

private fun SampleChat.toConversation(id: Int) =
    Conversation(
        id,
        title,
        period,
        turns.mapIndexed { index, (prompt, response) ->
            Turn(
                index,
                prompt,
                emptyList(),
                response,
                thinkLonger = index == turns.lastIndex,
                phase = Phase.Done,
            )
        },
    )

@Suppress(
    "DEPRECATION"
) // LocalClipboard needs platform-specific clip entries; plain text is enough here.
@Composable
private fun Chat(
    initialChat: SampleChat?,
    navigateToSettings: () -> Unit,
    navigateToUpgrade: () -> Unit,
    navigateToProjects: () -> Unit,
    navigateToVoiceChat: () -> Unit,
    modifier: Modifier = Modifier,
) {
    fun openCamera() {
        // open the camera here
    }

    fun pickFiles() {
        // pick files to attach here
    }

    fun startDictation() {
        // start dictating into the composer here
    }

    fun readAloud(text: String) {
        // read the response aloud here
    }

    fun shareResponse(text: String) {
        // share the response here
    }

    fun shareChat(title: String) {
        // share the chat here
    }

    val history = remember {
        mutableStateListOf<Conversation>().apply {
            sampleChats.forEachIndexed { id, chat -> add(chat.toConversation(id)) }
        }
    }
    var nextId by remember { mutableIntStateOf(sampleChats.size) }
    var current by remember {
        mutableStateOf(
            initialChat?.let { chat -> history[sampleChats.indexOf(chat)] }
                ?: Conversation(nextId++, "New chat", "Today", emptyList())
        )
    }
    val turns = current.turns
    var showChats by remember { mutableStateOf(false) }
    var chatForOptions by remember { mutableStateOf(current) }
    var showOptions by remember { mutableStateOf(false) }
    var pinnedWhenOptionsOpened by remember { mutableStateOf(false) }
    var showRename by remember { mutableStateOf(false) }
    var renameText by remember { mutableStateOf("") }
    var showDelete by remember { mutableStateOf(false) }
    var chatQuery by remember { mutableStateOf("") }
    var draft by remember { mutableStateOf("") }
    val attachments = remember { mutableStateListOf<RecentPhoto>() }
    var model by remember { mutableStateOf(models[1]) }
    var webSearch by remember { mutableStateOf(false) }
    var thinkLonger by remember { mutableStateOf(false) }
    var showModels by remember { mutableStateOf(false) }
    var showAddToChat by remember { mutableStateOf(false) }
    var toast by remember { mutableStateOf<String?>(null) }
    var activeTurn by remember { mutableStateOf<Turn?>(null) }
    var regenerations by remember { mutableIntStateOf(0) }

    val listState = current.listState
    val scope = rememberCoroutineScope()
    val clipboard = LocalClipboardManager.current
    val density = LocalDensity.current
    var topBarHeight by remember { mutableStateOf(0.dp) }
    var bottomBarHeight by remember { mutableStateOf(0.dp) }
    var suggestionsHeight by remember { mutableStateOf(0.dp) }
    val showScrollToLatest by remember {
        derivedStateOf {
            listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 120
        }
    }

    LaunchedEffect(activeTurn, regenerations) {
        val turn = activeTurn ?: return@LaunchedEffect
        turn.phase = Phase.Thinking
        turn.revealed = 0
        delay(if (turn.thinkLonger) 2400 else 700)
        turn.phase = Phase.Streaming
        delay(250)
        val answer = turn.answer
        while (turn.revealed < answer.length) {
            delay(28)
            // Stepping at line ends keeps each step's growth within the reserved footer space, so
            // new blocks never clip.
            val next =
                (turn.revealed + 1 until answer.length).firstOrNull {
                    answer[it] == ' ' || answer[it] == '\n'
                }
            turn.revealed = next ?: answer.length
        }
        turn.phase = Phase.Done
        turn.heightKeptWhileRegenerating = 0
        activeTurn = null
    }
    LaunchedEffect(toast) {
        if (toast != null) {
            delay(1800)
            toast = null
        }
    }

    fun send(prompt: String) {
        val turn =
            Turn(
                turns.size,
                prompt,
                attachments.map { it.uri },
                responseFor(prompt, attachments.isNotEmpty()),
                thinkLonger,
                Phase.Thinking,
            )
        if (current !in history && !current.temporary) {
            current.title = prompt
            history.add(0, current)
        }
        turns += turn
        draft = ""
        attachments.clear()
        activeTurn = turn
        scope.launch { listState.animateScrollToItem(0) }
    }

    fun stop() {
        activeTurn?.let {
            it.phase = Phase.Stopped
            it.heightKeptWhileRegenerating = 0
        }
        activeTurn = null
    }

    fun open(conversation: Conversation) {
        stop()
        showChats = false
        draft = ""
        attachments.clear()
        current = conversation
    }

    fun newChat() {
        if (turns.isEmpty()) {
            current.temporary = false
            showChats = false
        } else open(Conversation(nextId++, "New chat", "Today", emptyList()))
    }

    fun showOptionsFor(conversation: Conversation) {
        chatForOptions = conversation
        pinnedWhenOptionsOpened = conversation.pinned
        showOptions = true
    }

    fun delete(conversation: Conversation) {
        history.remove(conversation)
        if (conversation == current) open(Conversation(nextId++, "New chat", "Today", emptyList()))
        toast = "Chat deleted"
    }

    fun regenerate(turn: Turn) {
        stop()
        turn.heightKeptWhileRegenerating = turn.height
        turn.variant++
        turn.rating = Rating.None
        activeTurn = turn
        regenerations++
    }

    ScreenScaffold(modifier) {
        val horizontalSafe = WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal)

        AnimatedContent(
            targetState = current,
            modifier = Modifier.fillMaxSize(),
            transitionSpec = {
                fadeIn(tween(220, delayMillis = 90)) togetherWith fadeOut(tween(120))
            },
            contentKey = { it.id },
            label = "Conversation",
        ) { conversation ->
            Box(Modifier.fillMaxSize()) {
                if (conversation.turns.isEmpty()) {
                    Greeting(
                        conversation.temporary,
                        Modifier.fillMaxSize()
                            .padding(
                                top = topBarHeight,
                                bottom = bottomBarHeight + suggestionsHeight,
                            ),
                    )
                }
                LazyColumn(
                    state = conversation.listState,
                    reverseLayout = true,
                    modifier =
                        Modifier.align(Alignment.TopCenter)
                            .fillMaxHeight()
                            .widthIn(max = MaxReadingWidth)
                            .fillMaxWidth()
                            .windowInsetsPadding(horizontalSafe),
                    contentPadding =
                        PaddingValues(
                            start = Space * 4,
                            end = Space * 4,
                            top = topBarHeight + Space * 2,
                            bottom = bottomBarHeight + Space,
                        ),
                    verticalArrangement = Arrangement.spacedBy(Space * 6, Alignment.Bottom),
                ) {
                    // No placement animation: a streaming response resizes every word, and
                    // restarting springs made the list jitter.
                    conversation.turns.asReversed().forEach { turn ->
                        item(key = "response-${turn.id}") {
                            Response(
                                turn = turn,
                                latest = turn == conversation.turns.last(),
                                onCopy = {
                                    clipboard.setText(AnnotatedString(turn.answer))
                                    toast = "Copied"
                                },
                                onReadAloud = { readAloud(turn.answer) },
                                onRegenerate = { regenerate(turn) },
                                onShare = { shareResponse(turn.answer) },
                                modifier = Modifier.animateItem(placementSpec = null),
                            )
                        }
                        item(key = "prompt-${turn.id}") {
                            UserMessage(
                                turn.prompt,
                                imageUris = turn.imageUris,
                                modifier = Modifier.animateItem(placementSpec = null),
                            )
                        }
                    }
                }
            }
        }

        AppBar(
            modifier =
                Modifier.align(Alignment.TopCenter).onSizeChanged {
                    topBarHeight = with(density) { it.height.toDp() }
                },
            navigation = {
                IconButton(onClick = { showChats = true }, contentDescription = "Chats") {
                    Icon(Icons.Menu, contentDescription = null, modifier = Modifier.size(24.dp))
                }
            },
            title = {
                if (current.temporary || turns.isNotEmpty()) {
                    Text(
                        if (current.temporary) "Temporary chat" else current.title,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                    )
                }
            },
            actions = {
                when {
                    current.temporary ->
                        IconButton(
                            onClick = {
                                open(Conversation(nextId++, "New chat", "Today", emptyList()))
                            },
                            contentDescription = "Leave temporary chat",
                        ) {
                            Icon(
                                Icons.X,
                                contentDescription = null,
                                modifier = Modifier.size(22.dp),
                            )
                        }
                    turns.isEmpty() ->
                        IconButton(
                            onClick = { current.temporary = true },
                            contentDescription = "Temporary chat",
                        ) {
                            Icon(
                                Icons.Ghost,
                                contentDescription = null,
                                modifier = Modifier.size(24.dp),
                            )
                        }
                    else ->
                        IconButton(
                            onClick = { showOptionsFor(current) },
                            contentDescription = "Chat options",
                        ) {
                            Icon(
                                Icons.DotsThree,
                                contentDescription = null,
                                modifier = Modifier.size(24.dp),
                            )
                        }
                }
                if (turns.isNotEmpty() && !current.temporary) {
                    IconButton(onClick = ::newChat, contentDescription = "New chat") {
                        Icon(
                            Icons.NotePencil,
                            contentDescription = null,
                            modifier = Modifier.size(24.dp),
                        )
                    }
                }
            },
        )

        Toast(
            toast != null,
            toast.orEmpty(),
            Modifier.align(Alignment.TopCenter).padding(top = topBarHeight + Space * 2),
        )

        Column(
            Modifier.align(Alignment.BottomCenter)
                .fillMaxWidth()
                .onSizeChanged { bottomBarHeight = with(density) { it.height.toDp() } }
                .background(
                    Brush.verticalGradient(
                        listOf(Color.Transparent, Theme.colors.background),
                        endY = with(density) { ComposerFadeHeight.toPx() },
                    )
                )
                .windowInsetsPadding(
                    WindowInsets.navigationBars.union(WindowInsets.ime).union(horizontalSafe)
                )
                .padding(top = ComposerFadeHeight, bottom = Space * 2),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(Space * 3),
        ) {
            Composer(
                value = draft,
                onValueChange = { draft = it },
                model = model.name,
                responding = activeTurn != null,
                canSend = draft.isNotBlank() || attachments.isNotEmpty(),
                onSend = { send(draft.trim()) },
                onStop = ::stop,
                onAddClick = { showAddToChat = true },
                onModelClick = { showModels = true },
                onDictateClick = ::startDictation,
                onVoiceClick = navigateToVoiceChat,
                modifier = Modifier.widthIn(max = MaxReadingWidth).padding(horizontal = Space * 3),
                accessories =
                    if (attachments.isEmpty() && !webSearch && !thinkLonger) null
                    else {
                        {
                            attachments.forEach { photo ->
                                AttachmentChip(
                                    photo.uri,
                                    photo.description,
                                    onRemove = { attachments.remove(photo) },
                                )
                            }
                            if (thinkLonger)
                                ToolChip(
                                    "Think longer",
                                    Icons.Lightbulb,
                                    onRemove = { thinkLonger = false },
                                )
                            if (webSearch)
                                ToolChip("Search", Icons.Globe, onRemove = { webSearch = false })
                        }
                    },
            )
        }

        // Outside the measured bar, so the first message doesn't move when the suggestions leave.
        AnimatedVisibility(
            visible = turns.isEmpty(),
            modifier =
                Modifier.align(Alignment.BottomCenter)
                    .padding(bottom = bottomBarHeight)
                    .onSizeChanged { suggestionsHeight = with(density) { it.height.toDp() } },
            enter = fadeIn(),
            exit = fadeOut(),
        ) {
            LazyRow(
                contentPadding = PaddingValues(horizontal = Space * 3),
                horizontalArrangement = Arrangement.spacedBy(Space * 2),
            ) {
                items(suggestions, key = { it.prompt }) { suggestion ->
                    SuggestionCard(
                        suggestion.title,
                        suggestion.description,
                        onClick = { send(suggestion.prompt) },
                    )
                }
            }
        }

        ScrollToLatestButton(
            visible = showScrollToLatest,
            onClick = { scope.launch { listState.animateScrollToItem(0) } },
            modifier =
                Modifier.align(Alignment.BottomCenter)
                    .padding(bottom = (bottomBarHeight - Space * 2).coerceAtLeast(0.dp)),
        )

        SideDrawer(visible = showChats, onDismiss = { showChats = false }) {
            ChatsDrawerContent(
                history = history,
                current = current,
                query = chatQuery,
                onQueryChange = { chatQuery = it },
                onNewChat = ::newChat,
                onOpen = ::open,
                onOptions = ::showOptionsFor,
                onProfileClick = {
                    showChats = false
                    navigateToSettings()
                },
                onProjectsClick = {
                    showChats = false
                    navigateToProjects()
                },
                modifier = Modifier.weight(1f),
            )
        }

        ModalBottomSheet(
            visible = showOptions,
            onDismiss = { showOptions = false },
            title = chatForOptions.title,
        ) {
            OptionGroup {
                OptionRow(
                    title = "Rename",
                    icon = Icons.PencilSimple,
                    onClick = {
                        showOptions = false
                        renameText = chatForOptions.title
                        showRename = true
                    },
                )
                OptionRow(
                    title = if (pinnedWhenOptionsOpened) "Unpin" else "Pin",
                    icon = if (pinnedWhenOptionsOpened) Icons.PushPinSlash else Icons.PushPin,
                    onClick = {
                        showOptions = false
                        chatForOptions.pinned = !chatForOptions.pinned
                        toast = if (chatForOptions.pinned) "Pinned" else "Unpinned"
                    },
                )
                OptionRow(
                    title = "Share",
                    icon = Icons.Export,
                    onClick = {
                        showOptions = false
                        shareChat(chatForOptions.title)
                    },
                )
            }
            OptionGroup {
                OptionRow(
                    title = "Delete",
                    icon = Icons.Trash,
                    destructive = true,
                    onClick = {
                        showOptions = false
                        showDelete = true
                    },
                )
            }
        }

        ModalBottomSheet(
            visible = showRename,
            onDismiss = { showRename = false },
            title = "Rename chat",
        ) {
            TextField(renameText, { renameText = it }, label = "Chat name")
            Button(
                onClick = {
                    chatForOptions.title = renameText.trim()
                    showRename = false
                    toast = "Renamed"
                },
                enabled = renameText.isNotBlank(),
                modifier = Modifier.fillMaxWidth(),
            ) {
                Text("Save")
            }
        }

        AlertDialog(
            visible = showDelete,
            title = "Delete chat?",
            message =
                "\u201c${chatForOptions.title}\u201d will be deleted. This can\u2019t be undone.",
            onDismissRequest = { showDelete = false },
        ) {
            Button(
                onClick = {
                    showDelete = false
                    delete(chatForOptions)
                },
                variant = ButtonVariant.Destructive,
                modifier = Modifier.fillMaxWidth(),
            ) {
                Text("Delete")
            }
            Button(
                onClick = { showDelete = false },
                variant = ButtonVariant.Secondary,
                modifier = Modifier.fillMaxWidth(),
            ) {
                Text("Cancel")
            }
        }

        ModalBottomSheet(
            visible = showModels,
            onDismiss = { showModels = false },
            title = "Model",
        ) {
            OptionGroup {
                models.forEach { option ->
                    OptionRow(
                        title = option.name,
                        description = option.description,
                        badge = option.badge,
                        selected = option == model,
                        enabled = option.available,
                        onClick = {
                            showModels = false
                            if (option.badge != null) navigateToUpgrade() else model = option
                        },
                    )
                }
            }
        }

        ModalBottomSheet(
            visible = showAddToChat,
            onDismiss = { showAddToChat = false },
            title = "Add to chat",
        ) {
            PhotoStrip(
                selected = attachments,
                onCameraClick = {
                    showAddToChat = false
                    openCamera()
                },
                onPhotoClick = { photo ->
                    if (photo in attachments) attachments.remove(photo) else attachments += photo
                },
            )
            OptionGroup {
                OptionRow(
                    title = "Files",
                    description = "PDFs, documents and spreadsheets",
                    icon = Icons.File,
                    onClick = {
                        showAddToChat = false
                        pickFiles()
                    },
                )
            }
            OptionGroup {
                OptionToggle(
                    "Think longer",
                    thinkLonger,
                    { thinkLonger = it },
                    description = "Slower, more careful answers",
                    icon = Icons.Lightbulb,
                )
                OptionToggle(
                    "Web search",
                    webSearch,
                    { webSearch = it },
                    description = "Look up recent information",
                    icon = Icons.Globe,
                )
            }
        }
    }
}

@Composable
private fun Greeting(temporary: Boolean, modifier: Modifier = Modifier) {
    Column(
        modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        if (temporary) {
            Icon(Icons.Ghost, contentDescription = null, modifier = Modifier.size(36.dp))
            Spacer(Modifier.height(Space * 4))
            Text("Temporary chat", style = Theme.typography.display)
            Text(
                "This chat won't appear in your history or be used to improve Vela.",
                color = Theme.colors.onBackgroundMuted,
                style = Theme.typography.body.copy(textAlign = TextAlign.Center),
                modifier = Modifier.widthIn(max = 300.dp),
            )
        } else {
            Icon(
                Icons.VelaMark,
                contentDescription = null,
                modifier = Modifier.size(36.dp),
                tint = Theme.colors.primary,
            )
            Spacer(Modifier.height(Space * 4))
            Text("Good evening, Lex", style = Theme.typography.display)
            Text("What's on your mind?", color = Theme.colors.onBackgroundMuted)
        }
    }
}

@Composable
private fun Response(
    turn: Turn,
    latest: Boolean,
    onCopy: () -> Unit,
    onReadAloud: () -> Unit,
    onRegenerate: () -> Unit,
    onShare: () -> Unit,
    modifier: Modifier = Modifier,
) {
    var animatedHeight by remember { mutableIntStateOf(0) }
    var contentHeight by remember { mutableIntStateOf(0) }
    Column(
        modifier
            .fillMaxWidth()
            .onSizeChanged { animatedHeight = it.height }
            .animateContentSize()
            .heightIn(min = with(LocalDensity.current) { turn.heightKeptWhileRegenerating.toDp() })
            .onSizeChanged {
                contentHeight = it.height
                turn.height = it.height
            },
        verticalArrangement = Arrangement.spacedBy(Space * 3),
    ) {
        if (turn.phase == Phase.Thinking || turn.thinkLonger) {
            ThinkingIndicator(
                thinking = turn.phase == Phase.Thinking,
                seconds = if (turn.thinkLonger) 2 else 1,
                thoughts = turn.response.thoughts,
            )
        }
        if (turn.revealed > 0) Markdown(turn.answer.take(turn.revealed))
        val responseEnded = turn.phase == Phase.Done || turn.phase == Phase.Stopped
        val sizeAnimationCaughtUp = animatedHeight >= contentHeight
        val showFooter = responseEnded && sizeAnimationCaughtUp
        val footerAlpha by animateFloatAsState(if (showFooter) 1f else 0f, label = "Footer")
        // The footer's space is reserved while streaming so newly wrapped lines land in it instead
        // of being clipped.
        if (turn.phase != Phase.Thinking)
            Column(
                Modifier.keepSpaceWhileHidden(hidden = !showFooter).graphicsLayer {
                    alpha = footerAlpha
                },
                verticalArrangement = Arrangement.spacedBy(Space * 3),
            ) {
                MessageActions(
                    rating = turn.rating,
                    onCopy = onCopy,
                    onListen = onReadAloud,
                    onRate = { turn.rating = it },
                    onRegenerate = onRegenerate,
                    onShare = onShare,
                )
                if (latest || turn.phase == Phase.Stopped) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            Icons.VelaMark,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp),
                            tint = Theme.colors.primary,
                        )
                        Spacer(Modifier.weight(1f))
                        Text(
                            if (turn.phase == Phase.Stopped) "You stopped this response."
                            else "Vela can make mistakes. Check important information.",
                            style = Theme.typography.caption,
                            color = Theme.colors.onBackgroundMuted,
                        )
                    }
                }
            }
    }
}

private fun Modifier.keepSpaceWhileHidden(hidden: Boolean): Modifier =
    if (!hidden) this
    else
        layout { measurable, constraints ->
            val placeable = measurable.measure(constraints)
            layout(placeable.width, placeable.height) {}
        }

@Composable
private fun PhotoStrip(
    selected: List<RecentPhoto>,
    onCameraClick: () -> Unit,
    onPhotoClick: (RecentPhoto) -> Unit,
    modifier: Modifier = Modifier,
) {
    LazyRow(modifier, horizontalArrangement = Arrangement.spacedBy(Space * 2)) {
        item(key = "camera") {
            UnstyledButton(
                onClick = onCameraClick,
                modifier =
                    Modifier.size(88.dp)
                        .clip(Theme.shapes.medium)
                        .background(Theme.colors.surfaceVariant),
                indication = rememberRippleIndication(color = Theme.colors.onSurfaceVariant),
                interactionSource = remember { MutableInteractionSource() },
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(Space),
                ) {
                    Icon(Icons.Camera, contentDescription = null, modifier = Modifier.size(22.dp))
                    Text("Camera", style = Theme.typography.caption)
                }
            }
        }
        items(recentPhotos, key = { it.uri }) { photo ->
            val isSelected = photo in selected
            Box(
                Modifier.size(88.dp)
                    .clip(Theme.shapes.medium)
                    .then(
                        if (isSelected)
                            Modifier.border(2.dp, Theme.colors.primary, Theme.shapes.medium)
                        else Modifier
                    )
                    .semantics {
                        role = Role.Checkbox
                        this.selected = isSelected
                    }
            ) {
                UnstyledButton(
                    onClick = { onPhotoClick(photo) },
                    modifier = Modifier.fillMaxSize(),
                    indication = rememberRippleIndication(color = Color.White),
                    interactionSource = remember { MutableInteractionSource() },
                ) {
                    Image(
                        painter =
                            rememberUriPainter(
                                photo.uri,
                                crossfade = 300.milliseconds,
                                contentScale = ContentScale.Crop,
                            ),
                        contentDescription = photo.description,
                        contentScale = ContentScale.Crop,
                        modifier = Modifier.fillMaxSize().background(Theme.colors.surfaceVariant),
                    )
                }
                if (isSelected) {
                    Box(
                        Modifier.align(Alignment.TopEnd)
                            .padding(Space * 1.5f)
                            .size(22.dp)
                            .clip(Theme.shapes.fullyRounded)
                            .background(Theme.colors.primary),
                        contentAlignment = Alignment.Center,
                    ) {
                        Icon(
                            Icons.Check,
                            contentDescription = null,
                            modifier = Modifier.size(14.dp),
                            tint = Theme.colors.onPrimary,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun ChatsDrawerContent(
    history: List<Conversation>,
    current: Conversation,
    query: String,
    onQueryChange: (String) -> Unit,
    onNewChat: () -> Unit,
    onOpen: (Conversation) -> Unit,
    onOptions: (Conversation) -> Unit,
    onProfileClick: () -> Unit,
    onProjectsClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val matches = history.filter { it.title.contains(query.trim(), ignoreCase = true) }
    Column(modifier.fillMaxWidth()) {
        Column(
            Modifier.padding(horizontal = Space * 3).padding(top = Space * 3),
            verticalArrangement = Arrangement.spacedBy(Space * 2),
        ) {
            SearchField(query, onQueryChange, placeholder = "Search chats")
            DrawerItem("New chat", onClick = onNewChat, icon = Icons.NotePencil)
            DrawerItem("Projects", onClick = onProjectsClick, icon = Icons.Folder)
        }
        LazyColumn(
            Modifier.weight(1f),
            contentPadding = PaddingValues(horizontal = Space * 3, vertical = Space * 2),
        ) {
            val sections =
                listOfNotNull(
                    matches.filter { it.pinned }.takeIf { it.isNotEmpty() }?.let { "Pinned" to it }
                ) + matches.filterNot { it.pinned }.groupBy { it.period }.toList()
            sections.forEach { (period, chats) ->
                item(key = "period-$period") {
                    Text(
                        period,
                        style = Theme.typography.caption,
                        color = Theme.colors.onBackgroundMuted,
                        modifier =
                            Modifier.padding(start = Space * 3, top = Space * 4, bottom = Space * 2)
                                .animateItem(),
                    )
                }
                items(chats, key = { it.id }) { chat ->
                    DrawerItem(
                        chat.title,
                        onClick = { onOpen(chat) },
                        selected = chat == current,
                        onLongClick = { onOptions(chat) },
                        modifier = Modifier.animateItem(),
                    )
                }
            }
            if (matches.isEmpty()) {
                item(key = "no-matches") {
                    Text(
                        "No chats match \u201c${query.trim()}\u201d",
                        color = Theme.colors.onBackgroundMuted,
                        modifier = Modifier.padding(Space * 3).animateItem(),
                    )
                }
            }
        }
        Box(Modifier.fillMaxWidth().height(1.dp).background(Theme.colors.border))
        UnstyledButton(
            onClick = onProfileClick,
            modifier = Modifier.fillMaxWidth(),
            contentPadding = PaddingValues(horizontal = Space * 6, vertical = Space * 4),
            contentAlignment = Alignment.CenterStart,
            indication = rememberRippleIndication(color = Theme.colors.onSurface),
            interactionSource = remember { MutableInteractionSource() },
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(Space * 3),
            ) {
                Avatar("Lex")
                Column {
                    Text("Lex", style = Theme.typography.label)
                    Text(
                        "Free plan",
                        style = Theme.typography.caption,
                        color = Theme.colors.onBackgroundMuted,
                    )
                }
            }
        }
    }
}

More screens from Vela

by Alex Styl

Search screens and components

Screen flows

Screens

UI Elements

One Android lesson, every Wednesday

Building Android apps?

What Alex learned building Android apps for 14 years, so you don't have to. Reads in under a minute.

Join 3,500+ Android developers. Unsubscribe any time.

You're subscribed

The next lesson lands in on Wednesday.