Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ import io.getstream.chat.android.core.internal.coroutines.DispatcherProvider
import io.getstream.chat.android.models.Message
import io.getstream.chat.android.state.extensions.watchChannelAsState
import io.getstream.chat.android.ui.common.feature.messages.composer.MessageComposerController
import io.getstream.chat.android.ui.common.feature.messages.composer.internal.ComposerStateSaver
import io.getstream.chat.android.ui.common.feature.messages.composer.internal.NoOpComposerStateSaver
import io.getstream.chat.android.ui.common.feature.messages.composer.internal.SavedStateComposerStateSaver
import io.getstream.chat.android.ui.common.feature.messages.composer.mention.DefaultUserLookupHandler
import io.getstream.chat.android.ui.common.feature.messages.composer.mention.UserLookupHandler
import io.getstream.chat.android.ui.common.feature.messages.list.DateSeparatorHandler
Expand Down Expand Up @@ -123,21 +126,7 @@ public class MessagesViewModelFactory(
*/
private val factories: Map<Class<*>, () -> ViewModel> = mapOf(
MessageComposerViewModel::class.java to {
MessageComposerViewModel(
MessageComposerController(
chatClient = chatClient,
channelState = channelStateFlow,
mediaRecorder = mediaRecorder,
userLookupHandler = userLookupHandler,
fileToUri = fileToUriConverter,
channelCid = channelId,
config = MessageComposerController.Config(
maxAttachmentCount = maxAttachmentCount,
isLinkPreviewEnabled = isComposerLinkPreviewEnabled,
isDraftMessageEnabled = isComposerDraftMessageEnabled,
),
),
)
createMessageComposerViewModel(NoOpComposerStateSaver)
},
MessageListViewModel::class.java to {
MessageListViewModel(
Expand Down Expand Up @@ -190,6 +179,11 @@ public class MessagesViewModelFactory(
* that do not require a [SavedStateHandle].
*/
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
if (modelClass == MessageComposerViewModel::class.java) {
val savedStateHandle = extras.createSavedStateHandle()
@Suppress("UNCHECKED_CAST")
return createMessageComposerViewModel(SavedStateComposerStateSaver(savedStateHandle)) as T
}
if (modelClass == AttachmentsPickerViewModel::class.java) {
val savedStateHandle = extras.createSavedStateHandle()
@Suppress("UNCHECKED_CAST")
Expand All @@ -201,4 +195,23 @@ public class MessagesViewModelFactory(
}
return create(modelClass)
}

private fun createMessageComposerViewModel(stateSaver: ComposerStateSaver): MessageComposerViewModel {
return MessageComposerViewModel(
MessageComposerController(
chatClient = chatClient,
channelState = channelStateFlow,
mediaRecorder = mediaRecorder,
userLookupHandler = userLookupHandler,
fileToUri = fileToUriConverter,
channelCid = channelId,
config = MessageComposerController.Config(
maxAttachmentCount = maxAttachmentCount,
isLinkPreviewEnabled = isComposerLinkPreviewEnabled,
isDraftMessageEnabled = isComposerDraftMessageEnabled,
),
stateSaver = stateSaver,
),
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import io.getstream.chat.android.state.plugin.state.global.GlobalState
import io.getstream.chat.android.test.TestCoroutineExtension
import io.getstream.chat.android.test.asCall
import io.getstream.chat.android.ui.common.feature.messages.composer.MessageComposerController
import io.getstream.chat.android.ui.common.feature.messages.composer.internal.NoOpComposerStateSaver
import io.getstream.chat.android.ui.common.feature.messages.composer.mention.DefaultUserLookupHandler
import io.getstream.chat.android.ui.common.feature.messages.composer.mention.Mention
import io.getstream.chat.android.ui.common.feature.messages.composer.mention.MentionType
Expand Down Expand Up @@ -475,6 +476,7 @@ internal class MessageComposerViewModelTest {
),
channelState = MutableStateFlow(channelState),
globalState = MutableStateFlow(globalState),
stateSaver = NoOpComposerStateSaver,
),
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,14 @@ public final class io/getstream/chat/android/ui/common/feature/messages/composer
public static final fun canUploadFile (Lio/getstream/chat/android/ui/common/state/messages/composer/MessageComposerState;)Z
}

public final class io/getstream/chat/android/ui/common/feature/messages/composer/internal/ParcelableAttachment$Creator : android/os/Parcelable$Creator {
public fun <init> ()V
public final fun createFromParcel (Landroid/os/Parcel;)Lio/getstream/chat/android/ui/common/feature/messages/composer/internal/ParcelableAttachment;
public synthetic fun createFromParcel (Landroid/os/Parcel;)Ljava/lang/Object;
public final fun newArray (I)[Lio/getstream/chat/android/ui/common/feature/messages/composer/internal/ParcelableAttachment;
public synthetic fun newArray (I)[Ljava/lang/Object;
}

public abstract interface class io/getstream/chat/android/ui/common/feature/messages/composer/mention/CompatUserLookupHandler {
public abstract fun handleCompatUserLookup (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lkotlin/jvm/functions/Function0;
}
Expand Down
1 change: 1 addition & 0 deletions stream-chat-android-ui-common/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ plugins {
alias(libs.plugins.stream.android.library)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.kotlin.parcelize)
alias(libs.plugins.android.junit5)
alias(libs.plugins.androidx.baseline.profile)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import io.getstream.chat.android.models.PollConfig
import io.getstream.chat.android.models.User
import io.getstream.chat.android.state.extensions.globalStateFlow
import io.getstream.chat.android.state.plugin.state.global.GlobalState
import io.getstream.chat.android.ui.common.feature.messages.composer.internal.ComposerStateSaver
import io.getstream.chat.android.ui.common.feature.messages.composer.mention.Mention
import io.getstream.chat.android.ui.common.feature.messages.composer.mention.UserLookupHandler
import io.getstream.chat.android.ui.common.feature.messages.composer.typing.TypingSuggester
Expand Down Expand Up @@ -102,6 +103,7 @@ import java.util.regex.Pattern
* @param fileToUri The function used to convert a file to a URI.
* @param config The configuration for the message composer.
* @param globalState A flow emitting the current [GlobalState].
* @param stateSaver Store for persisting composer state across process death.
*/
@OptIn(ExperimentalCoroutinesApi::class)
@InternalStreamChatApi
Expand All @@ -115,6 +117,7 @@ public class MessageComposerController(
fileToUri: (File) -> String,
private val config: Config = Config(),
private val globalState: Flow<GlobalState> = chatClient.globalStateFlow,
private val stateSaver: ComposerStateSaver,
) {

private val channelType = channelCid.cidToTypeAndId().first
Expand Down Expand Up @@ -371,6 +374,8 @@ public class MessageComposerController(
* Sets up the data loading operations such as observing the maximum allowed message length.
*/
init {
restoreAttachmentsFromStateSaver()

channelState
.filterNotNull()
.flatMapLatest { it.channelConfig }
Expand Down Expand Up @@ -400,6 +405,14 @@ public class MessageComposerController(
setupComposerState()
}

private fun restoreAttachmentsFromStateSaver() {
val restoredAttachments = stateSaver.restoreAttachments()
?.filter { it.upload == null || it.upload!!.exists() }
if (!restoredAttachments.isNullOrEmpty()) {
selectedAttachments.value = restoredAttachments
}
}

/**
* Sets up the observing operations for various composer states.
*/
Expand Down Expand Up @@ -502,6 +515,10 @@ public class MessageComposerController(
}
}.launchIn(scope)
}

selectedAttachments
.onEach { attachments -> stateSaver.saveAttachments(attachments) }
.launchIn(scope)
}

/**
Expand Down Expand Up @@ -675,6 +692,7 @@ public class MessageComposerController(
selectedAttachments.value = emptyList()
validationErrors.value = emptyList()
alsoSendToChannel.value = false
stateSaver.clear()
}

private suspend fun clearDraftMessage(messageMode: MessageMode) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2014-2026 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.ui.common.feature.messages.composer.internal

import io.getstream.chat.android.core.internal.InternalStreamChatApi
import io.getstream.chat.android.models.Attachment

/**
* Abstraction for persisting and restoring message composer state across process death.
*
* The controller interacts with this interface only — no Android framework imports required.
*/
@InternalStreamChatApi
public interface ComposerStateSaver {

/**
* Save the attachments from the composer.
*
* Implementations should be cheap to call frequently — this is invoked
* on every change to the attachment list.
*/
public fun saveAttachments(attachments: List<Attachment>)

/**
* Restores the attachments to the composer.
*/
public fun restoreAttachments(): List<Attachment>?

/**
* Clears the stored state.
*/
public fun clear()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2014-2026 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.ui.common.feature.messages.composer.internal

import io.getstream.chat.android.core.internal.InternalStreamChatApi
import io.getstream.chat.android.models.Attachment

/**
* A [ComposerStateSaver] that does nothing.
*
* Used as a fallback when the ViewModel is created without [CreationExtras]
* (e.g. via the legacy [ViewModelProvider.Factory.create] overload).
* Composer state will not survive process death in this case.
*/
@InternalStreamChatApi
public object NoOpComposerStateSaver : ComposerStateSaver {
override fun saveAttachments(attachments: List<Attachment>): Unit = Unit
override fun restoreAttachments(): List<Attachment>? = null
override fun clear(): Unit = Unit
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright (c) 2014-2026 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.getstream.chat.android.ui.common.feature.messages.composer.internal

import android.os.Parcelable
import io.getstream.chat.android.models.Attachment
import kotlinx.parcelize.Parcelize
import kotlinx.parcelize.RawValue
import java.io.File

/**
* A Parcelable subset of [Attachment] containing only the fields that are populated
* at compose time (before upload). Fields like `imageUrl`, `thumbUrl`, `assetUrl`,
* `uploadState`, etc. are populated after upload and are intentionally excluded.
*/
@Parcelize
internal data class ParcelableAttachment(
val uploadPath: String?,
val type: String?,
val name: String?,
val fileSize: Int,
val mimeType: String?,
val title: String?,
val extraData: Map<String, @RawValue Any>,
) : Parcelable

/**
* Converts an [Attachment] to a [ParcelableAttachment] for persistence via [SavedStateHandle].
*/
internal fun Attachment.toParcelable(): ParcelableAttachment = ParcelableAttachment(
uploadPath = upload?.absolutePath,
type = type,
name = name,
fileSize = fileSize,
mimeType = mimeType,
title = title,
extraData = extraData,
)

/**
* Converts a [ParcelableAttachment] back to an [Attachment].
*/
internal fun ParcelableAttachment.toAttachment(): Attachment = Attachment(
upload = uploadPath?.let { File(it) },
type = type,
name = name,
fileSize = fileSize,
mimeType = mimeType,
title = title,
extraData = extraData,
)

/**
* Checks whether all extra data values in the given attachments are safe to parcel.
* Returns `true` if all values can be written to a [android.os.Parcel] without crashing.
*/
internal fun List<Attachment>.areExtraDataParcelSafe(): Boolean =
all { attachment -> attachment.extraData.values.all { it.isParcelSafe() } }

/**
* Recursively checks whether a value can be safely written via [android.os.Parcel.writeValue].
*/
private fun Any.isParcelSafe(): Boolean = when (this) {
is String, is Int, is Long, is Float, is Double, is Boolean, is Byte, is Short -> true
is BooleanArray, is ByteArray, is FloatArray, is IntArray, is LongArray, is DoubleArray -> true
is List<*> -> all { it == null || it.isParcelSafe() }
is Map<*, *> -> all { (k, v) -> k is String && (v == null || v.isParcelSafe()) }
else -> false
Comment thread
aleksandar-apostolov marked this conversation as resolved.
}
Loading
Loading