Code_Function
stringlengths 13
13.9k
| Message
stringlengths 10
1.46k
|
---|---|
@Composable internal fun DefaultUserReactionItem(item: UserReactionItemState) {UserReactionItem(item = item,modifier = Modifier,)} | Default user reactions item for the user reactions component. |
@Preview @Composable private fun OneUserReactionPreview() {ChatTheme {UserReactions(items = PreviewUserReactionData.oneUserReaction())}} | Preview of the [UserReactions] component with one user reaction. |
@Preview@Composable private fun ManyUserReactionsPreview() {ChatTheme {UserReactions(items = PreviewUserReactionData.manyUserReactions())}} | Preview of the [UserReactions] component with many user reactions. |
@OptIn(ExperimentalFoundationApi::class) @Composable public fun FileAttachmentContent( attachmentState: AttachmentState,modifier: Modifier = Modifier,) {val (message, onItemLongClick) = attachmentState val previewHandlers = ChatTheme.attachmentPreviewHandlers Column(modifier = modifier.combinedClickable( indication = null, interactionSource = remember { MutableInteractionSource() }, onClick = {}, onLongClick = { onItemLongClick(message) })) {for (attachment in message.attachments) {FileAttachmentItem(modifier = Modifier.padding(2.dp).fillMaxWidth().combinedClickable(indication = null,interactionSource = remember { MutableInteractionSource() },onClick = {previewHandlers.firstOrNull { it.canHandle(attachment) }.handleAttachmentPreview(attachment)},onLongClick = { onItemLongClick(message) },),attachment = attachment)}}} | Builds a file attachment message which shows a list of files. |
@Composable public fun FileAttachmentItem(attachment: Attachment,modifier: Modifier = Modifier,) { Surface(modifier = modifier,color = ChatTheme.colors.appBackground,shape = ChatTheme.shapes.attachment) {Row(Modifier.fillMaxWidth().height(50.dp).padding(vertical = 8.dp, horizontal = 8.dp),verticalAlignment = Alignment.CenterVertically) {FileAttachmentImage(attachment = attachment)FileAttachmentDescription(attachment = attachment)FileAttachmentDownloadIcon(attachment = attachment)}}} | Represents each file item in the list of file attachments. |
@Composable private fun FileAttachmentDescription(attachment: Attachment) {Column(modifier = Modifier.fillMaxWidth(0.85f).padding(start = 16.dp, end = 8.dp),horizontalAlignment = Alignment.Start,verticalArrangement = Arrangement.Center) {Text(text = attachment.title ?: attachment.name ?: "",style = ChatTheme.typography.bodyBold,maxLines = 1,overflow = TextOverflow.Ellipsis,color = ChatTheme.colors.textHighEmphasis)Text(text = MediaStringUtil.convertFileSizeByteCount(attachment.fileSize.toLong()),style = ChatTheme.typography.footnote,color = ChatTheme.colors.textLowEmphasis)}} | Displays information about the attachment such as the attachment title and its size in bytes. |
@Composable private fun RowScope.FileAttachmentDownloadIcon(attachment: Attachment) {val permissionHandlers = ChatTheme.permissionHandlerProvider Icon( modifier = Modifier.align(Alignment.Top).padding(end = 2.dp).clickable(interactionSource = remember { MutableInteractionSource() },indication = rememberRipple(bounded = false)) {permissionHandlers.first { it.canHandle(Manifest.permission.WRITE_EXTERNAL_STORAGE) }.apply {onHandleRequest(mapOf(PayloadAttachment to attachment))}},painter = painterResource(id = R.drawable.stream_compose_ic_file_download),contentDescription = stringResource(id = R.string.stream_compose_download),tint = ChatTheme.colors.textHighEmphasis)} | Downloads the given attachment when clicked. |
@Composable public fun FileAttachmentImage(attachment: Attachment) {val isImage = attachment.type == "image"val painter = if (isImage) {val dataToLoad = attachment.imageUrl ?: attachment.upload rememberStreamImagePainter(dataToLoad)} else {painterResource(id = MimeTypeIconProvider.getIconRes(attachment.mimeType))} val shape = if (isImage) ChatTheme.shapes.imageThumbnail else nullval imageModifier = Modifier.size(height = 40.dp, width = 35.dp).let { baseModifier -> if (shape != null) baseModifier.clip(shape) else baseModifier } Image(modifier = imageModifier, painter = painter, contentDescription = null, contentScale = if (isImage) ContentScale.Crop else ContentScale.Fit) } | Represents the image that's shown in file attachments. This can be either an image/icon that represents the file type or a thumbnail in case the file type is an image. |
@Suppress("FunctionName") public fun FileAttachmentFactory(): AttachmentFactory = AttachmentFactory( canHandle = { attachments ->attachments.any { it.isFile() } }, previewContent = @Composable { modifier, attachments, onAttachmentRemoved -> FileAttachmentPreviewContent(modifier = modifier, attachments = attachments, onAttachmentRemoved = onAttachmentRemoved)},content = @Composable { modifier, state ->FileAttachmentContent(modifier = modifier.wrapContentHeight().width(ChatTheme.dimens.attachmentsContentFileWidth),attachmentState = state)},) | An [AttachmentFactory] that validates attachments as files and uses [FileAttachmentContent] to build the UI for the message. |
@Suppress("FunctionName") public fun GiphyAttachmentFactory(giphyInfoType: GiphyInfoType = GiphyInfoType.FIXED_HEIGHT_DOWNSAMPLED,giphySizingMode: GiphySizingMode = GiphySizingMode.ADAPTIVE,contentScale: ContentScale = ContentScale.Crop,): AttachmentFactory =AttachmentFactory(canHandle = { attachments -> attachments.any { it.type == ModelType.attach_giphy } },content = @Composable { modifier, state ->GiphyAttachmentContent(modifier = modifier.wrapContentSize(),attachmentState = state,giphyInfoType = giphyInfoType,giphySizingMode = giphySizingMode,contentScale = contentScale,)},) | An [AttachmentFactory] that validates and shows Giphy attachments using [GiphyAttachmentContent]. Has no "preview content", given that this attachment only exists after being sent. |
@Suppress("FunctionName") public fun ImageAttachmentFactory(): AttachmentFactory = AttachmentFactory( canHandle = { attachments -> attachments.all { it.isMedia() } }, previewContent = { modifier, attachments, onAttachmentRemoved -> ImageAttachmentPreviewContent(modifier = modifier,attachments = attachments, onAttachmentRemoved = onAttachmentRemoved )},content = @Composable { modifier, state ->ImageAttachmentContent(modifier = modifier.width(ChatTheme.dimens.attachmentsContentImageWidth).wrapContentHeight().heightIn(max = ChatTheme.dimens.attachmentsContentImageMaxHeight),attachmentState = state)},) | An [AttachmentFactory] that validates attachments as images and uses [ImageAttachmentContent] to build the UI for the message. |
@Suppress("FunctionName") public fun LinkAttachmentFactory(linkDescriptionMaxLines: Int, ): AttachmentFactory = AttachmentFactory(canHandle = { links -> links.any { it.hasLink() && it.type != ModelType.attach_giphy } }, content = @Composable { modifier, state -> LinkAttachmentContent( modifier = modifier.width(ChatTheme.dimens.attachmentsContentLinkWidth).wrapContentHeight(),attachmentState = state,linkDescriptionMaxLines = linkDescriptionMaxLines)},) | An [AttachmentFactory] that validates attachments as images and uses [LinkAttachmentContent] to build the UI for the message. Has no "preview content", given that this attachment only exists after being sent. |
@Suppress("FunctionName") public fun QuotedAttachmentFactory(): AttachmentFactory = AttachmentFactory(canHandle = {if (it.isEmpty()) return@AttachmentFactory false val attachment = it.first() attachment.isFile() || attachment.isMedia() || attachment.hasLink() },content = @Composable { modifier, attachmentState ->val attachment = attachmentState.message.attachments.first() val isFile = attachment.isFile() val isImage = attachment.isMedia() val isLink = attachment.hasLink() when { isImage || isLink -> ImageAttachmentQuotedContent(modifier = modifier, attachment = attachment) isFile -> FileAttachmentQuotedContent(modifier = modifier, attachment = attachment)}}) | An [AttachmentFactory] that validates attachments as files and uses [ImageAttachmentQuotedContent] in case the attachment is a media attachment or [FileAttachmentQuotedContent] in case the attachment is a file to build the UI for the quoted message. |
@Suppress("FunctionName") public fun UploadAttachmentFactory(): AttachmentFactory = AttachmentFactory( canHandle = { attachments -> attachments.any {it.isUploading() } }, content = @Composable { modifier, state ->FileUploadContent(modifier = modifier.wrapContentHeight().width(ChatTheme.dimens.attachmentsContentFileUploadWidth),attachmentState = state)},) | An [AttachmentFactory] that validates and shows uploading attachments using [FileUploadContent]. Has no "preview content", given that this attachment only exists after being sent. |
public open class AttachmentFactory constructor( public val canHandle: (attachments: List<Attachment>) -> Boolean, public val previewContent: ( @Composable (modifier: Modifier,attachments: List<Attachment>,onAttachmentRemoved: (Attachment) -> Unit,) -> Unit)? = null,public val content: @Composable (modifier: Modifier,attachmentState: AttachmentState,) -> Unit,public val textFormatter: (attachments: Attachment) -> String = Attachment::previewText,) | Holds the information required to build an attachment message. |
public fun defaultFactories( linkDescriptionMaxLines: Int = DEFAULT_LINK_DESCRIPTION_MAX_LINES,giphyInfoType: GiphyInfoType = GiphyInfoType.ORIGINAL,giphySizingMode: GiphySizingMode = GiphySizingMode.ADAPTIVE,contentScale: ContentScale = ContentScale.Crop,):List<AttachmentFactory> = listOf(UploadAttachmentFactory(),LinkAttachmentFactory(linkDescriptionMaxLines),GiphyAttachmentFactory(giphyInfoType = giphyInfoType,giphySizingMode = giphySizingMode,contentScale = contentScale,),ImageAttachmentFactory(),FileAttachmentFactory(),) | Default attachment factories we provide, which can transform image, file and link attachments. |
public fun defaultQuotedFactories(): List<AttachmentFactory> = listOf(QuotedAttachmentFactory())} | Default quoted attachment factories we provide, which can transform image, file and link attachments. |
@Composable public fun ChannelList(modifier: Modifier = Modifier,contentPadding: PaddingValues = PaddingValues(),viewModel: ChannelListViewModel = viewModel(factory =ChannelViewModelFactory(ChatClient.instance(),QuerySortByField.descByName("last_updated"),filters = null)),lazyListState: LazyListState = rememberLazyListState(),onLastItemReached: () -> Unit = { viewModel.loadMore() },onChannelClick: (Channel) -> Unit = {},onChannelLongClick: (Channel) -> Unit = { viewModel.selectChannel(it) },loadingContent: @Composable () -> Unit = { LoadingIndicator(modifier) },emptyContent: @Composable () -> Unit = {DefaultChannelListEmptyContent(modifier) },emptySearchContent: @Composable (String) -> Unit = { searchQuery ->DefaultChannelSearchEmptyContent(searchQuery = searchQuery,modifier = modifier)},helperContent: @Composable BoxScope.() -> Unit = {},loadingMoreContent: @Composable () -> Unit = { DefaultChannelsLoadingMoreIndicator() },itemContent: @Composable (ChannelItemState) -> Unit = { channelItem ->val user by viewModel.user.collectAsState()DefaultChannelItem(channelItem = channelItem,currentUser = user,onChannelClick = onChannelClick,onChannelLongClick =onChannelLongClick)},divider: @Composable () -> Unit = { DefaultChannelItemDivider() },) {val user by viewModel.user.collectAsState()ChannelList(modifier = modifier,contentPadding = contentPadding,channelsState = viewModel.channelsState,currentUser = user,lazyListState = lazyListState,onLastItemReached =onLastItemReached,onChannelClick = onChannelClick,onChannelLongClick = onChannelLongClick,loadingContent = loadingContent,emptyContent = emptyContent,emptySearchContent = emptySearchContent,helperContent = helperContent,loadingMoreContent = loadingMoreContent,itemContent = itemContent,divider = divider)} | Default ChannelList component, that relies on the [ChannelListViewModel] to load the data and show it on the UI. |
@Composable public fun ChannelList( channelsState: ChannelsState,currentUser: User?,modifier: Modifier = Modifier,contentPadding: PaddingValues = PaddingValues(0.dp),lazyListState: LazyListState = rememberLazyListState(),onLastItemReached: () -> Unit = {},onChannelClick: (Channel) -> Unit = {},onChannelLongClick: (Channel) -> Unit = {},loadingContent: @Composable () -> Unit = { DefaultChannelListLoadingIndicator(modifier) },emptyContent: @Composable () -> Unit = { DefaultChannelListEmptyContent(modifier) },emptySearchContent: @Composable (String) -> Unit = { searchQuery ->DefaultChannelSearchEmptyContent(searchQuery = searchQuery,modifier = modifier)},helperContent: @Composable BoxScope.() -> Unit = {},loadingMoreContent: @Composable () -> Unit = {DefaultChannelsLoadingMoreIndicator() },itemContent: @Composable (ChannelItemState) -> Unit = { channelItem ->DefaultChannelItem(channelItem = channelItem,currentUser = currentUser,onChannelClick = onChannelClick,onChannelLongClick = onChannelLongClick)},divider: @Composable () -> Unit = { DefaultChannelItemDivider() },) {val (isLoading, _, _, channels, searchQuery) = channelsState when {isLoading -> loadingContent() !isLoading && channels.isNotEmpty() -> Channels( modifier = modifier, contentPadding = contentPadding, channelsState = channelsState, lazyListState = lazyListState, onLastItemReached = onLastItemReached, helperContent = helperContent, loadingMoreContent = loadingMoreContent, itemContent = itemContent, divider = divider searchQuery.isNotEmpty() -> emptySearchContent(searchQuery) else -> emptyContent()} } | Root Channel list component, that represents different UI, based on the current channel state.This is decoupled from ViewModels, so the user can provide manual and custom data handling,as well as define a completely custom UI component for the channel item.If there is no state, no query active or the data is being loaded, we show the [LoadingIndicator].If there are no results or we're offline, usually due to an error in the API or network, we show an [EmptyContent]. If there is data available and it is not empty, we show [Channels]. |
@Composable internal fun DefaultChannelItem( channelItem: ChannelItemState, currentUser: User?, onChannelClick: (Channel) -> Unit, onChannelLongClick: (Channel) -> Unit, ) {ChannelItem(channelItem = channelItem,currentUser = currentUser,onChannelClick = onChannelClick,onChannelLongClick = onChannelLongClick)} | The default channel item. |
@Composable internal fun DefaultChannelListLoadingIndicator(modifier: Modifier) {LoadingIndicator(modifier)} | Default loading indicator. |
@Composable internal fun DefaultChannelListEmptyContent(modifier: Modifier = Modifier) {EmptyContent(modifier = modifier,painter = painterResource(id = R.drawable.stream_compose_empty_channels),text = stringResource(R.string.stream_compose_channel_list_empty_channels),)} | The default empty placeholder for the case when there are no channels available to the user. |
@Composable internal fun DefaultChannelSearchEmptyContent(searchQuery: String,modifier: Modifier = Modifier,) {EmptyContent(modifier = modifier,painter = painterResource(id = R.drawable.stream_compose_empty_search_results),text = stringResource(R.string.stream_compose_channel_list_empty_search_results, searchQuery),)} | The default empty placeholder for the case when channel search returns no results. |
@Composable public fun DefaultChannelItemDivider() { Spacer(modifier = Modifier.fillMaxWidth().height(0.5.dp).background(color = ChatTheme.colors.borders))} | Represents the default item divider in channel items. |
@Preview(showBackground = true, name = "ChannelList Preview (Content state)")@Composableprivate fun ChannelListForContentStatePreview() {ChannelListPreview(ChannelsState(isLoading = false,channelItems = listOf(ChannelItemState(channel = PreviewChannelData.channelWithImage),ChannelItemState(channel = PreviewChannelData.channelWithMessages),ChannelItemState(channel =PreviewChannelData.channelWithFewMembers),ChannelItemState(channel = PreviewChannelData.channelWithManyMembers),ChannelItemState(channel = PreviewChannelData.channelWithOnlineUser))))} | Preview of [ChannelItem] for a list of channels. Should show a list of channels. |
@Preview(showBackground = true, name = "ChannelList Preview (Empty state)")@Composableprivate fun ChannelListForEmptyStatePreview() {ChannelListPreview(ChannelsState(isLoading = false,channelItems = emptyList()))} | Preview of [ChannelItem] for an empty state.Should show an empty placeholder. |
@Preview(showBackground = true, name = "ChannelList Preview (Loading state)")@Composable private fun ChannelListForLoadingStatePreview() {ChannelListPreview(ChannelsState(isLoading = true))} | Preview of [ChannelItem] for a loading state. Should show a progress indicator. |
@Composable private fun ChannelListPreview(channelsState: ChannelsState) {ChatTheme {ChannelList(modifier = Modifier.fillMaxSize(),channelsState = channelsState, currentUser = PreviewUserData.user1,)}} | Shows [ChannelList] preview for the provided parameters. |
@Composable public fun Channels( channelsState: ChannelsState, lazyListState: LazyListState, onLastItemReached: () -> Unit, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(), helperContent: @Composable BoxScope.() -> Unit = {}, loadingMoreContent: @Composable () -> Unit = { DefaultChannelsLoadingMoreIndicator() }, itemContent: @Composable (ChannelItemState) -> Unit, divider: @Composable () -> Unit, ) { val (_, isLoadingMore, endOfChannels, channelItems) = channelsState Box(modifier = modifier) { LazyColumn( modifier = Modifier.fillMaxSize(), state = lazyListState, horizontalAlignment = Alignment.CenterHorizontally, contentPadding = contentPadding ) { item { DummyFirstChannelItem() } items( items = channelItems, key = { it.channel.cid }) { item ->itemContent(item)divider()}if (isLoadingMore) {item {loadingMoreContent()}}} if (!endOfChannels && channelItems.isNotEmpty()) {LoadMoreHandler(lazyListState) {onLastItemReached() }}helperContent()}} | Builds a list of [ChannelItem] elements, based on [channelsState] and action handlers that it receives. |
@Composable internal fun DefaultChannelsLoadingMoreIndicator() {LoadingFooter(modifier = Modifier.fillMaxWidth())} | The default loading more indicator. |
@Composable private fun DummyFirstChannelItem() {Box(modifier = Modifier.height(1.dp).fillMaxWidth())} | Represents an almost invisible dummy item to be added to the top of the list.If the list is scrolled to the top and a channel new item is added or moved to the position above, then the list will automatically autoscroll to it. |
@OptIn(ExperimentalFoundationApi::class)@Composablepublic fun ChannelItem(channelItem: ChannelItemState,currentUser: User?,onChannelClick: (Channel) -> Unit,onChannelLongClick: (Channel) -> Unit,modifier: Modifier = Modifier,leadingContent: @Composable RowScope.(ChannelItemState) -> Unit = {DefaultChannelItemLeadingContent(channelItem = it,currentUser = currentUser)},centerContent: @Composable RowScope.(ChannelItemState) -> Unit = { DefaultChannelItemCenterContent(channel = it.channel,isMuted = it.isMuted,currentUser = currentUser)},trailingContent: @Composable RowScope.(ChannelItemState) -> Unit = {DefaultChannelItemTrailingContent(channel = it.channel,currentUser = currentUser,)},) {val channel = channelItem.channelval description = stringResource(id = R.string.stream_compose_cd_channel_item)Column(modifier = modifier.fillMaxWidth().wrapContentHeight().semantics { contentDescription = description}.combinedClickable(onClick = { onChannelClick(channel) },onLongClick = { onChannelLongClick(channel) },indication = rememberRipple(),interactionSource = remember { MutableInteractionSource() }),) {Row(modifier = Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically,) {leadingContent(channelItem)centerContent(channelItem)trailingContent(channelItem)}}} | The basic channel item, that shows the channel in a list and exposes single and long click actions. |
@Composable internal fun DefaultChannelItemLeadingContent(channelItem: ChannelItemState,currentUser: User?,) {ChannelAvatar(modifier = Modifier.padding(start = ChatTheme.dimens.channelItemHorizontalPadding,end = 4.dp,top = ChatTheme.dimens.channelItemVerticalPadding,bottom = ChatTheme.dimens.channelItemVerticalPadding).size(ChatTheme.dimens.channelAvatarSize),channel = channelItem.channel,currentUser = currentUser)} | Represents the default leading content of [ChannelItem], that shows the channel avatar. |
@Composableinternal fun RowScope.DefaultChannelItemCenterContent(channel: Channel,isMuted: Boolean,currentUser: User?,) {Column(modifier = Modifier.padding(start = 4.dp, end = 4.dp).weight(1f).wrapContentHeight(),verticalArrangement = Arrangement.Center) {val channelName: (@Composable (modifier: Modifier) -> Unit) = @Composable {Text(modifier = it,text = ChatTheme.channelNameFormatter.formatChannelName(channel, currentUser),style = ChatTheme.typography.bodyBold,fontSize = 16.sp,maxLines = 1,overflow = TextOverflow.Ellipsis,color = ChatTheme.colors.textHighEmphasis,)}if (isMuted) {Row(verticalAlignment = Alignment.CenterVertically) {channelName(Modifier.weight(weight = 1f, fill = false))Icon(modifier = Modifier.padding(start = 8.dp).size(16.dp), painter = painterResource(id = R.drawable.stream_compose_ic_muted),contentDescription = null,tint = ChatTheme.colors.textLowEmphasis,)}} else {channelName(Modifier)} val lastMessageText = channel.getLastMessage(currentUser)?.let { lastMessage -> ChatTheme.messagePreviewFormatter.formatMessagePreview(lastMessage, currentUser)} ?: AnnotatedString("")if (lastMessageText.isNotEmpty()) {Text(text = lastMessageText,maxLines = 1,overflow = TextOverflow.Ellipsis,style = ChatTheme.typography.body,color = ChatTheme.colors.textLowEmphasis,)}}} | Represents the center portion of [ChannelItem], that shows the channel display name and the last message text preview. |
@Composable internal fun RowScope.DefaultChannelItemTrailingContent(channel: Channel,currentUser: User?,) {val lastMessage = channel.getLastMessage(currentUser) if (lastMessage != null) {Column(modifier = Modifier.padding(start = 4.dp,end = ChatTheme.dimens.channelItemHorizontalPadding,top = ChatTheme.dimens.channelItemVerticalPadding,bottom = ChatTheme.dimens.channelItemVerticalPadding).wrapContentHeight().align(Alignment.Bottom),horizontalAlignment = Alignment.End) {val unreadCount = channel.unreadCountif (unreadCount != null && unreadCount > 0) {UnreadCountIndicator(modifier = Modifier.padding(bottom = 4.dp),unreadCount = unreadCount)}val isLastMessageFromCurrentUser = lastMessage.user.id == currentUser?.id Row(verticalAlignment = Alignment.CenterVertically) {if (isLastMessageFromCurrentUser) {MessageReadStatusIcon(channel = channel,message = lastMessage,currentUser = currentUser,modifier = Modifier.padding(end = 8.dp).size(16.dp))} Timestamp(date = channel.lastUpdated)}}}} | Represents the default trailing content for the channel item. By default it shows the the information about the last message for the channel item, such as its read state,timestamp and how many unread messages the user has. |
@Preview(showBackground = true, name = "ChannelItem Preview (Channel with unread)") @Composableprivate fun ChannelItemForChannelWithUnreadMessagesPreview() {ChannelItemPreview(channel = PreviewChannelData.channelWithMessages,currentUser = PreviewUserData.user1)} | Preview of the [ChannelItem] component for a channel with unread messages. Should show unread count badge, delivery indicator and timestamp. |
@Preview(showBackground = true, name = "ChannelItem Preview (Muted channel)") @Composableprivate fun ChannelItemForMutedChannelPreview() {ChannelItemPreview(channel = PreviewChannelData.channelWithMessages,currentUser = PreviewUserData.user1,isMuted = true)} | Preview of [ChannelItem] for a muted channel. Should show a muted icon next to the channel name. |
@Preview(showBackground = true, name = "ChannelItem Preview (Without messages)") @Composableprivate fun ChannelItemForChannelWithoutMessagesPreview() { ChannelItemPreview(channel = PreviewChannelData.channelWithImage, isMuted = false,currentUser = PreviewUserData.user1)} | Preview of [ChannelItem] for a channel without messages. Should show only channel name that is centered vertically. |
@Composable private fun ChannelItemPreview(channel: Channel,isMuted: Boolean = false,currentUser: User? = null,) {ChatTheme {ChannelItem(channelItem = ChannelItemState(channel = channel,isMuted = isMuted),currentUser = currentUser,onChannelClick = {},onChannelLongClick = {})}} | Shows [ChannelItem] preview for the provided parameters. |
@Composable public fun SelectedChannelMenu(selectedChannel: Channel,isMuted: Boolean,currentUser: User?,onChannelOptionClick: (ChannelAction) -> Unit, onDismiss: () -> Unit,modifier: Modifier = Modifier,shape: Shape = ChatTheme.shapes.bottomSheet,overlayColor: Color = ChatTheme.colors.overlay,headerContent: @Composable ColumnScope.() -> Unit = { DefaultSelectedChannelMenuHeaderContent( selectedChannel = selectedChannel,currentUser = currentUser)}, centerContent: @Composable ColumnScope.() -> Unit = {DefaultSelectedChannelMenuCenterContent(selectedChannel = selectedChannel,isMuted = isMuted,onChannelOptionClick = onChannelOptionClick,ownCapabilities = selectedChannel.ownCapabilities)},) {SimpleMenu(modifier = modifier, shape = shape,overlayColor = overlayColor,onDismiss = onDismiss,headerContent = headerContent,centerContent = centerContent)} | Shows special UI when an item is selected. It also prepares the available options for the channel, based on if we're an admin or not. |
@Composable internal fun DefaultSelectedChannelMenuHeaderContent(selectedChannel: Channel,currentUser: User?,) {val channelMembers = selectedChannel.membersval membersToDisplay = if (selectedChannel.isOneToOne(currentUser)) {channelMembers.filter { it.user.id != currentUser?.id }} else {channelMembers } Text(modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 16.dp),textAlign = TextAlign.Center,text = ChatTheme.channelNameFormatter.formatChannelName(selectedChannel, currentUser),style = ChatTheme.typography.title3Bold,color = ChatTheme.colors.textHighEmphasis,maxLines = 1,overflow = TextOverflow.Ellipsis)Text(modifier = Modifier.fillMaxWidth(),textAlign = TextAlign.Center,text = selectedChannel.getMembersStatusText(LocalContext.current, currentUser),style = ChatTheme.typography.footnoteBold,color = ChatTheme.colors.textLowEmphasis,) ChannelMembers(membersToDisplay) } | Represents the default content shown at the top of [SelectedChannelMenu] dialog. |
@Composable internal fun DefaultSelectedChannelMenuCenterContent(selectedChannel: Channel,isMuted: Boolean,onChannelOptionClick: (ChannelAction) -> Unit,ownCapabilities: Set<String>,) {val channelOptions = buildDefaultChannelOptionsState(selectedChannel = selectedChannel,isMuted = isMuted,ownCapabilities = ownCapabilities)ChannelOptions(channelOptions, onChannelOptionClick)} | Represents the default content shown at the center of [SelectedChannelMenu] dialog. |
@Preview(showBackground = true, name = "SelectedChannelMenu Preview (Centered dialog)") @Composableprivate fun SelectedChannelMenuCenteredDialogPreview() {ChatTheme {Box(modifier = Modifier.fillMaxSize()) {SelectedChannelMenu(modifier = Modifier.padding(16.dp).fillMaxWidth().wrapContentHeight().align(Alignment.Center),shape = RoundedCornerShape(16.dp),selectedChannel =PreviewChannelData.channelWithManyMembers,isMuted = false,currentUser = PreviewUserData.user1,onChannelOptionClick = {},onDismiss = {})}}} | Preview of [SelectedChannelMenu] styled as a centered modal dialog. Should show a centered dialog with channel members and channel options. |
@Preview(showBackground = true, name = "SelectedChannelMenu Preview (Bottom sheet dialog)") @Composableprivate fun SelectedChannelMenuBottomSheetDialogPreview() { ChatTheme {Box(modifier = Modifier.fillMaxSize()) {SelectedChannelMenu(modifier = Modifier.fillMaxWidth().wrapContentHeight().align(Alignment.BottomCenter),shape = ChatTheme.shapes.bottomSheet,selectedChannel = PreviewChannelData.channelWithManyMembers,isMuted = false,currentUser = PreviewUserData.user1,onChannelOptionClick = {},onDismiss = {})}}} | Preview of [SelectedChannelMenu] styled as a bottom sheet dialog. Should show a bottom sheet dialog with channel members and channel options. |
@Composable public fun ChannelListHeader(modifier: Modifier = Modifier,title: String = "",currentUser: User? = null,connectionState: ConnectionState ConnectionState.CONNECTED,color: Color = ChatTheme.colors.barsBackground,shape: Shape = ChatTheme.shapes.header,elevation: Dp ChatTheme.dimens.headerElevation,onAvatarClick: (User?) -> Unit = {},onHeaderActionClick: () -> Unit = {},leadingContent: @Composable RowScope.() -> Unit = { DefaultChannelHeaderLeadingContent(currentUser = currentUser,onAvatarClick = onAvatarClick)},centerContent: @Composable RowScope.() -> Unit = { DefaultChannelListHeaderCenterContent( connectionState = connectionState,title = title)},trailingContent: @Composable RowScope.() -> Unit = {DefaultChannelListHeaderTrailingContent(onHeaderActionClick = onHeaderActionClick)},) {Surface(modifier = modifier.fillMaxWidth(),elevation = elevation,color = color,shape = shape) {Row(Modifier.fillMaxWidth().padding(8.dp),verticalAlignment = Alignment.CenterVertically,) {leadingContent()centerContent()trailingContent()}}} | A clean, decoupled UI element that doesn't rely on ViewModels or our custom architecture setup. This allows the user to fully govern how the [ChannelListHeader] behaves, by passing in all the data that's required to display it and drive its actions. |
@Composable internal fun DefaultChannelHeaderLeadingContent(currentUser: User?,onAvatarClick: (User?) -> Unit,) {val size = Modifier.size(40.dp)if (currentUser != null) { UserAvatar(modifier = size,user = currentUser,contentDescription = currentUser.name,showOnlineIndicator = false,onClick = { onAvatarClick(currentUser) })} else {Spacer(modifier = size)}} | Represents the default leading content for the [ChannelListHeader], which is a [UserAvatar]. We show the avatar if the user is available, otherwise we add a spacer to make sure the alignment is correct. |
@Composable internal fun RowScope.DefaultChannelListHeaderCenterContent( connectionState: ConnectionState, title: String,) {when (connectionState) {ConnectionState.CONNECTED -> {Text(modifier = Modifier.weight(1f).wrapContentWidth().padding(horizontal = 16.dp),text = title,style = ChatTheme.typography.title3Bold,maxLines = 1,color = ChatTheme.colors.textHighEmphasis)}ConnectionState.CONNECTING -> NetworkLoadingIndicator(modifier = Modifier.weight(1f))ConnectionState.OFFLINE -> {Text(modifier = Modifier.weight(1f).wrapContentWidth().padding(horizontal = 16.dp),text = stringResource(R.string.stream_compose_disconnected),style = ChatTheme.typography.title3Bold,maxLines = 1,color = ChatTheme.colors.textHighEmphasis)}}} | Represents the channel header's center slot. It either shows a [Text] if [connectionState] is [ConnectionState.CONNECTED], or a [NetworkLoadingIndicator] if there is no connections. |
@OptIn(ExperimentalMaterialApi::class) @Composableinternal fun DefaultChannelListHeaderTrailingContent(onHeaderActionClick: () -> Unit,) {Surface(modifier =Modifier.size(40.dp), onClick = onHeaderActionClick,interactionSource = remember { MutableInteractionSource() },color = ChatTheme.colors.primaryAccent,shape = ChatTheme.shapes.avatar,elevation = 4.dp) {Icon(modifier = Modifier.wrapContentSize(),painter = painterResource(id = R.drawable.stream_compose_ic_new_chat),contentDescription = stringResource(id = R.string.stream_compose_channel_list_header_new_chat),tint = Color.White,)}} | Represents the default trailing content for the [ChannelListHeader], which is an action icon. |
@Preview(name = "ChannelListHeader Preview (Connected state)")@Composableprivate fun ChannelListHeaderForConnectedStatePreview(){ChannelListHeaderPreview(connectionState = ConnectionState.CONNECTED)} | Preview of [ChannelListHeader] for the client that is connected to the WS. Should show a user avatar, a title, and an action button. |
@Preview(name = "ChannelListHeader Preview (Connecting state)") @Composable private fun ChannelListHeaderForConnectingStatePreview() {ChannelListHeaderPreview(connectionState = ConnectionState.CONNECTING)} | Preview of [ChannelListHeader] for the client that is trying to connect to the WS. Should show a user avatar, "Waiting for network" caption, and an action button. |
@Composable private fun ChannelListHeaderPreview(title: String = "Stream Chat",currentUser: User? = PreviewUserData.user1,connectionState: ConnectionState = ConnectionState.CONNECTED,) {ChatTheme {ChannelListHeader(title = title,currentUser = currentUser,connectionState = connectionState)}} | Shows [ChannelListHeader] preview for the provided parameters. |
internal class AboveAnchorPopupPositionProvider : PopupPositionProvider { override fun calculatePosition(anchorBounds: IntRect,windowSize: IntSize,layoutDirection: LayoutDirection,popupContentSize: IntSize,): IntOffset {return IntOffset(x = 0,y = anchorBounds.top - popupContentSize.height)}} | Calculates the position of the suggestion list [Popup] on the screen. |
public fun defaultFormatter( context: Context,maxMembers: Int = 5,): ChannelNameFormatter {return DefaultChannelNameFormatter(context, maxMembers)}}} | Build the default channel name formatter. |
private class DefaultChannelNameFormatter(private val context: Context,private val maxMembers: Int,) : ChannelNameFormatter {} | A simple implementation of [ChannelNameFormatter] that allows to generate a name for a channel based on the following rules: |
override fun formatChannelName(channel: Channel, currentUser: User?): String {return channel.getDisplayName(context, currentUser,R.string.stream_compose_untitled_channel, maxMembers)}} | Generates a name for the given channel. |
public fun Channel.getLastMessage(currentUser: User?): Message? = getPreviewMessage(currentUser) | Returns channel's last regular or system message if exists. Deleted and silent messages, as well as messages from shadow-banned users, are not taken into account. |
public fun Channel.getReadStatuses(userToIgnore: User?): List<Date> { return read.filter { it.user.id != userToIgnore?.id }.mapNotNull { it.lastRead }} | Filters the read status of each person other than the target user. |
public fun Channel.isDistinct(): Boolean = cid.contains("!members") | Checks if the channel is distinct. A distinct channel is a channel created without ID based on members. Internally the server creates a CID which starts with "!members" prefix and is unique for this particular group of users. |
public fun Channel.isOneToOne(currentUser: User?): Boolean { return isDistinct() && members.size == 2 && members.any { it.user.id == currentUser?.id } } | Checks if the channel is a direct conversation between the current user and some other user. A one-to-one chat is basically a corner case of a distinct channel with only 2 members. |
public fun Channel.getMembersStatusText(context: Context, currentUser: User?): String { return getMembersStatusText(context = context,currentUser = currentUser, userOnlineResId = R.string.stream_compose_user_status_online, userLastSeenJustNowResId = R.string.stream_compose_user_status_last_seen_just_now, userLastSeenResId = R.string.stream_compose_user_status_last_seen, memberCountResId = R.plurals.stream_compose_member_count, memberCountWithOnlineResId = R.string.stream_compose_member_count_online,) } | Returns a string describing the member status of the channel: either a member count for a group channel or the last seen text for a direct one-to-one conversation with the current user. |
public fun Channel.getOtherUsers(currentUser: User?): List<User> { val currentUserId = currentUser?.id return if (currentUserId != null) {members.filterNot { it.user.id == currentUserId }} else {members}.map { it.user } } | Returns a list of users that are members of the channel excluding the currently logged in user. |
@Composable @ReadOnlyComposable internal fun initialsGradient(initials: String): Brush {val gradientBaseColors = LocalContext.current.resources.getIntArray(R.array.stream_compose_avatar_gradient_colors)val baseColorIndex = abs(initials.hashCode()) % gradientBaseColors.sizeval baseColor = gradientBaseColors[baseColorIndex]return Brush.linearGradient(listOf(Color(adjustColorBrightness(baseColor, GradientDarkerColorFactor)),Color(adjustColorBrightness(baseColor, GradientLighterColorFactor)),))} | Generates a gradient for an initials avatar based on the user initials. |
public fun Modifier.mirrorRtl(layoutDirection: LayoutDirection): Modifier { return this.scale( scaleX = if (layoutDirection == LayoutDirection.Ltr) 1f else -1f, scaleY = 1f ) } | Applies the given mirroring scaleX based on the [layoutDirection] that's currently configured in the UI. Useful since the Painter from Compose doesn't know how to parse autoMirrored` flags in SVGs. |
@Composable public fun rememberStreamImagePainter( data: Any?, placeholderPainter: Painter? = null, errorPainter: Painter? = null, fallbackPainter: Painter? = errorPainter, onLoading: ((AsyncImagePainter.State.Loading) -> Unit)? = null, onSuccess: ((AsyncImagePainter.State.Success) -> Unit)? = null, onError: ((AsyncImagePainter.State.Error) -> Unit)? = null, contentScale: ContentScale = ContentScale.Fit, filterQuality: FilterQuality = DrawScope.DefaultFilterQuality, ): AsyncImagePainter { return rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current) .data(data).build(), imageLoader = LocalStreamImageLoader.current, placeholder = placeholderPainter, error = errorPainter, fallback = fallbackPainter, contentScale = contentScale, onSuccess = onSuccess, onError = onError, onLoading = onLoading, filterQuality = filterQuality ) } | Wrapper around the [coil.compose.rememberAsyncImagePainter] that plugs in our [LocalStreamImageLoader] singleton that can be used to customize all image loading requests, like adding headers, interceptors and similar. |
public val LocalStreamImageLoader: StreamImageLoaderProvidableCompositionLocal = StreamImageLoaderProvidableCompositionLocal() | A [CompositionLocal] that returns the current [ImageLoader] for the composition. If a local [ImageLoader] has not been provided, it returns the singleton instance of [ImageLoader] in [Coil]. |
@JvmInline public value class StreamImageLoaderProvidableCompositionLocal internal constructor(private val delegate: ProvidableCompositionLocal<ImageLoader?> = staticCompositionLocalOf { null }, ) {public val current: ImageLoader@Composable@ReadOnlyComposableget() = delegate.current ?: LocalContext.current.imageLoader public infix fun provides(value: ImageLoader): ProvidedValue<ImageLoader?> = delegate provides value } | A provider of [CompositionLocal] that returns the current [ImageLoader] for the composition. |
@Composable public fun rememberMessageListState(initialFirstVisibleItemIndex: Int = 0,initialFirstVisibleItemScrollOffset: Int = 0,parentMessageId: String? = null,): LazyListState {val baseListState = rememberLazyListState(initialFirstVisibleItemIndex, initialFirstVisibleItemScrollOffset) return if (parentMessageId != null) { rememberLazyListState() } else { baseListState } } | Provides a [LazyListState] that's tied to a given message list. This is the default behavior, where we keep the base scroll position of the list persisted at all times, while the thread scroll state is always new, whenever we enter a thread. In case you want to customize the behavior, provide the [LazyListState] based on your logic and conditions. |
private class DefaultMessagePreviewFormatter( private val context: Context,private val messageTextStyle: TextStyle,private val senderNameTextStyle: TextStyle,private val attachmentTextFontStyle: TextStyle,private val attachmentFactories: List<AttachmentFactory>,) : MessagePreviewFormatter { | The default implementation of [MessagePreviewFormatter] that allows to generate a preview text for a message with the following spans: sender name, message text, attachments preview text. |
override fun formatMessagePreview(message: Message,currentUser: User?,): AnnotatedString {return buildAnnotatedString {message.let { message ->val messageText = message.text.trim()if (message.isSystem()) {append(messageText)} else {appendSenderName(message = message,currentUser = currentUser,senderNameTextStyle = senderNameTextStyle)appendMessageText(messageText = messageText,messageTextStyle = messageTextStyle)appendAttachmentText(attachments = message.attachments, attachmentFactories = attachmentFactories,attachmentTextStyle = attachmentTextFontStyle)}}}} | Generates a preview text for the given message. |
private fun AnnotatedString.Builder.appendSenderName(message: Message,currentUser: User?,senderNameTextStyle: TextStyle,) {val sender = message.getSenderDisplayName(context, currentUser)if (sender != null) {append("$sender: ")addStyle(SpanStyle(fontStyle = senderNameTextStyle.fontStyle,fontWeight = senderNameTextStyle.fontWeight,fontFamily = senderNameTextStyle.fontFamily),start = 0,end = sender.length)}} | Appends the sender name to the [AnnotatedString]. |
private fun AnnotatedString.Builder.appendMessageText(messageText: String,messageTextStyle: TextStyle,) {if (messageText.isNotEmpty()) {val startIndex = this.lengthappend("$messageText ")addStyle(SpanStyle(fontStyle = messageTextStyle.fontStyle,fontFamily = messageTextStyle.fontFamily),start = startIndex,end = startIndex + messageText.length)}} | Appends the message text to the [AnnotatedString]. |
private fun AnnotatedString.Builder.appendAttachmentText(attachments: List<Attachment>,attachmentFactories: List<AttachmentFactory>,attachmentTextStyle: TextStyle,) {if (attachments.isNotEmpty()) {attachmentFactories.firstOrNull { it.canHandle(attachments) }?.textFormatter?.let { textFormatter ->attachments.mapNotNull { attachment ->textFormatter.invoke(attachment).let { previewText ->previewText.ifEmpty { null }}}.joinToString()}?.let { attachmentText ->val startIndex = this.lengthappend(attachmentText) addStyle(SpanStyle(fontStyle = attachmentTextStyle.fontStyle,fontFamily = attachmentTextStyle.fontFamily),start = startIndex,end = startIndex + attachmentText.length)}}}} | Appends a string representations of [attachments] to the [AnnotatedString]. |
fun getIconRes(mimeType: String?): Int {if (mimeType == null) {return R.drawable.stream_compose_ic_file_generic}return mimeTypesToIconResMap[mimeType] ?: when { mimeType.contains(ModelType.attach_audio) -> R.drawable.stream_compose_ic_file_audio_genericmimeType.contains(ModelType.attach_video) -> R.drawable.stream_compose_ic_file_video_genericelse -> R.drawable.stream_compose_ic_file_generic}} | Returns a drawable resource for the given MIME type. |
private class DefaultReactionIconFactory( private val supportedReactions: Map<String, ReactionDrawable> = mapOf(THUMBS_UP to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_thumbs_up,selectedIconResId = R.drawable.stream_compose_ic_reaction_thumbs_up_selected),LOVE to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_love,selectedIconResId = R.drawable.stream_compose_ic_reaction_love_selected),LOL to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_lol,selectedIconResId = R.drawable.stream_compose_ic_reaction_lol_selected),WUT to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_wut,selectedIconResId = R.drawable.stream_compose_ic_reaction_wut_selected),THUMBS_DOWN to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_thumbs_down,selectedIconResId = R.drawable.stream_compose_ic_reaction_thumbs_down_selected)),) : ReactionIconFactory { } | The default implementation of [ReactionIconFactory] that uses drawable resources to create reaction icons. |
override fun isReactionSupported(type: String): Boolean {return supportedReactions.containsKey(type)} | Checks if the factory is capable of creating an icon for the given reaction type. |
@Composable override fun createReactionIcon(type: String): ReactionIcon {val reactionDrawable = requireNotNull(supportedReactions[type])return ReactionIcon(painter = painterResource(reactionDrawable.iconResId),selectedPainter = painterResource(reactionDrawable.selectedIconResId))} | Creates an instance of [ReactionIcon] for the given reaction type. |
@Composable override fun createReactionIcons(): Map<String, ReactionIcon> {return supportedReactions.mapValues { createReactionIcon(it.key)}} companion object { private const val LOVE: String = "love" private const val THUMBS_UP: String = "like"private const val THUMBS_DOWN: String = "sad"private const val LOL: String = "haha"private const val WUT: String = "wow"}} | Creates [ReactionIcon]s for all the supported reaction types. |
public data class ReactionDrawable(@DrawableRes public val iconResId: Int,@DrawableRes public val selectedIconResId: Int,) | Contains drawable resources for normal and selected reaction states. |
public data class ReactionIcon(val painter: Painter,val selectedPainter: Painter,) {} | Contains [Painter]s for normal and selected states of the reaction icon. |
public fun getFiles(): List<AttachmentMetaData> { return attachmentFilter.filterAttachments(storageHelper.getFileAttachments(context)) } | Loads a list of file metadata from the system and filters it against file types accepted by the backend. |
public fun getMedia(): List<AttachmentMetaData> { return attachmentFilter.filterAttachments(storageHelper.getMediaAttachments(context)) } | Loads a list of media metadata from the system. |
public fun getAttachmentsForUpload(attachments: List<AttachmentMetaData>): List<Attachment> { return getAttachmentsFromMetaData(attachments) } | Transforms a list of [AttachmentMetaData] into a list of [Attachment]s. This is required because we need to prepare the files for upload. |
private fun getAttachmentsFromMetaData(metaData: List<AttachmentMetaData>): List<Attachment> { return metaData.map { val fileFromUri = storageHelper.getCachedFileFromUri(context, it) Attachment( upload = fileFromUri, type = it.type, name = it.title ?: fileFromUri.name ?: "", fileSize = it.size.toInt(), mimeType = it.mimeType ) } } | Loads attachment files from the provided metadata, so that we can upload them. |
public fun getAttachmentsFromUris(uris: List<Uri>): List<Attachment> { return getAttachmentsMetadataFromUris(uris).let(::getAttachmentsFromMetaData) } | Takes a list of file Uris and transforms them into a list of [Attachment]s so that we can upload them. |
public fun getAttachmentsMetadataFromUris(uris: List<Uri>): List<AttachmentMetaData> { return storageHelper.getAttachmentsFromUriList(context, uris) .let(attachmentFilter::filterAttachments) } | Takes a list of file Uris and transforms them into a list of [AttachmentMetaData]. |
public fun User.getLastSeenText(context: Context): String { return getLastSeenText(context = contextuserOnlineResId = R.string.stream_compose_user_status_online,userLastSeenJustNowResId = R.string.stream_compose_user_status_last_seen_just_now,userLastSeenResId = R.string.stream_compose_user_status_last_seen,)} | Returns a string describing the elapsed time since the user was online (was watching the channel). Depending on the elapsed time, the string can have one of the following formats:- Online - Last seen just now - Last seen 13 hours ago |
@Composable public fun AttachmentsPicker(attachmentsPickerViewModel: AttachmentsPickerViewModel,onAttachmentsSelected: (List<Attachment>) -> Unit,onDismiss: () -> Unit, modifier: Modifier = Modifier, tabFactories: List<AttachmentsPickerTabFactory> = ChatTheme.attachmentsPickerTabFactories,shape: Shape = ChatTheme.shapes.bottomSheet,) {var selectedTabIndex by remember { mutableStateOf(0) }Box(modifier = Modifier.fillMaxSize().background(ChatTheme.colors.overlay).clickable(onClick = onDismiss,indication = null,interactionSource = remember { MutableInteractionSource() })) {Card(modifier = modifier.clickable(indication = null,onClick = {},interactionSource = remember { MutableInteractionSource() }),elevation = 4.dp,shape = shape,backgroundColor = ChatTheme.colors.inputBackground,) {Column {AttachmentPickerOptions(hasPickedAttachments = attachmentsPickerViewModel.hasPickedAttachments,tabFactories = tabFactories,tabIndex = selectedTabIndex,onTabClick = { index, attachmentPickerMode -> selectedTabIndex = indexattachmentsPickerViewModel.changeAttachmentPickerMode(attachmentPickerMode) { false }},onSendAttachmentsClick = {onAttachmentsSelected(attachmentsPickerViewModel.getSelectedAttachments())},)Surface(modifier = Modifier.fillMaxSize(),shape = RoundedCornerShape(topStart =16.dp, topEnd = 16.dp),color = ChatTheme.colors.barsBackground,) {tabFactories.getOrNull(selectedTabIndex)?.pickerTabContent(attachments =attachmentsPickerViewModel.attachments,onAttachmentItemSelected = attachmentsPickerViewModel::changeSelectedAttachments,onAttachmentsChanged = { attachmentsPickerViewModel.attachments = it },onAttachmentsSubmitted = {onAttachmentsSelected(attachmentsPickerViewModel.getAttachmentsFromMetaData(it))},)}}}}} | Represents the bottom bar UI that allows users to pick attachments. The picker renders its tabs based on the [tabFactories] parameter. Out of the box we provide factories for images, files and media capture tabs. |
Composable private fun AttachmentPickerOptions( hasPickedAttachments: Boolean, tabFactories: List<AttachmentsPickerTabFactory>, tabIndex: Int, onTabClick: (Int, AttachmentsPickerMode) -> Unit, onSendAttachmentsClick: () -> Unit, ) { Row( Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Row(horizontalArrangement = Arrangement.SpaceEvenly) { tabFactories.forEachIndexed { index, tabFactory -> val isSelected = index == tabIndex val isEnabled = isSelected || (!isSelected && !hasPickedAttachments) IconButton( enabled = isEnabled, content = { tabFactory.pickerTabIcon( isEnabled = isEnabled, isSelected = isSelected ) }, onClick = { onTabClick(index, tabFactory.attachmentsPickerMode) } ) } } Spacer(modifier = Modifier.weight(1f)) IconButton( enabled = hasPickedAttachments, onClick = onSendAttachmentsClick, content = { val layoutDirection = LocalLayoutDirection.current Icon( modifier = Modifier .weight(1f).mirrorRtl(layoutDirection = layoutDirection),painter = painterResource(id = R.drawable.stream_compose_ic_circle_left),contentDescription = stringResource(id = R.string.stream_compose_send_attachment),tint = if (hasPickedAttachments){ChatTheme.colors.primaryAccent} else {ChatTheme.colors.textLowEmphasis})})}} | The options for the Attachment picker. Shows tabs based on the provided list of [tabFactories] and a button to submit the selected attachments. |
@Composable override fun pickerTabIcon(isEnabled: Boolean, isSelected: Boolean) {Icon(painter = painterResource(id =R.drawable.stream_compose_ic_media_picker),contentDescription = stringResource(id = R.string.stream_compose_capture_option),tint = when {isSelected -> ChatTheme.colors.primaryAccentisEnabled -> ChatTheme.colors.textLowEmphasiselse -> ChatTheme.colors.disabled},)} | Emits a camera icon for this tab. |
@OptIn(ExperimentalPermissionsApi::class) @Composable override fun pickerTabContent(attachments: List<AttachmentPickerItemState>,onAttachmentsChanged: (List<AttachmentPickerItemState>) -> Unit,onAttachmentItemSelected: (AttachmentPickerItemState) -> Unit,onAttachmentsSubmitted: (List<AttachmentMetaData>) -> Unit,) {val context = LocalContext.current val requiresCameraPermission = isCameraPermissionDeclared(context) val cameraPermissionState = if (requiresCameraPermission) rememberPermissionState(permission = Manifest.permission.CAMERA) else null val mediaCaptureResultLauncher = rememberLauncherForActivityResult(contract = CaptureMediaContract()) { file: File? -> val attachments = if (file == null) {emptyList()} else {listOf(AttachmentMetaData(context, file))} onAttachmentsSubmitted(attachments) } if (cameraPermissionState == null || cameraPermissionState.status == PermissionStatus.Granted) { Box(modifier = Modifier.fillMaxSize()) { LaunchedEffect(Unit) { mediaCaptureResultLauncher.launch(Unit) } } } else if (cameraPermissionState.status is PermissionStatus.Denied) { MissingPermissionContent(cameraPermissionState) } } | Emits content that allows users to start media capture. |
private fun isCameraPermissionDeclared(context: Context): Boolean { return context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS) .requestedPermissions .contains(Manifest.permission.CAMERA) } | Returns if we need to check for the camera permission or not. |
public fun defaultFactories(imagesTabEnabled: Boolean = true,filesTabEnabled: Boolean = true,mediaCaptureTabEnabled: Boolean = true,): List<AttachmentsPickerTabFactory> {return listOfNotNull(if (imagesTabEnabled) AttachmentsPickerImagesTabFactory() else null,if (filesTabEnabled) AttachmentsPickerFilesTabFactory() else null,if (mediaCaptureTabEnabled) AttachmentsPickerMediaCaptureTabFactory() else null,)} | Builds the default list of attachment picker tab factories. |
@Composable public fun pickerTabContent(attachments: List<AttachmentPickerItemState>,onAttachmentsChanged: (List<AttachmentPickerItemState>) -> Unit,onAttachmentItemSelected: (AttachmentPickerItemState) -> Unit,onAttachmentsSubmitted: (List<AttachmentMetaData>) -> Unit,) | Emits a content for the tab. |
@Composable public fun pickerTabIcon(isEnabled: Boolean, isSelected: Boolean) | Emits an icon for the tab. |
private val filterFlow: MutableStateFlow<FilterObject?> = MutableStateFlow(initialFilters) | State flow that keeps the value of the current [FilterObject] for channels. |
private val querySortFlow: MutableStateFlow<QuerySorter<Channel>> = MutableStateFlow(initialSort) | State flow that keeps the value of the current [QuerySorter] for channels. |
private val queryConfigFlow = filterFlow.filterNotNull().combine(querySortFlow) { filters, sort -> QueryConfig(filters = filters, querySort = sort) } | The currently active query configuration, stored in a [MutableStateFlow]. It's created using the `initialFilters` parameter and the initial sort, but can be changed. |
private val searchQuery = MutableStateFlow("") | The current state of the search input. When changed, it emits a new value in a flow, which queries and loads new data. |
public var channelsState: ChannelsState by mutableStateOf(ChannelsState()) private set | The current state of the channels screen. It holds all the information required to render the UI. |
public var selectedChannel: MutableState<Channel?> = mutableStateOf(null) private set | Currently selected channel, if any. Used to show the bottom drawer information when long tapping on a list item. |
Subsets and Splits