package eu.friedcutlet.yokan.ui.screens.novel import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LocalLifecycleOwner import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent import kotlinx.coroutines.Job /** Parsed links retain the chapter and screen which created them. */ @Composable internal fun rememberNovelOpenLink( content: ProfileReaderContent, chapterId: Long, onOpenLink: (String) -> Unit, ): (String) -> Unit { val scope = rememberCoroutineScope() val lifecycle = LocalLifecycleOwner.current.lifecycle val binding = remember(content, chapterId, lifecycle) { NovelContentLinkBinding(content, Job(scope.coroutineContext[Job])) { lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) } } val currentOpenLink by rememberUpdatedState(onOpenLink) DisposableEffect(binding) { onDispose { binding.close() } } return remember(binding) { { link -> if (binding.active()) currentOpenLink(link) } } } internal class NovelContentLinkBinding( private val content: ProfileReaderContent, private val job: Job, private val isScreenActive: () -> Boolean, ) { fun active(): Boolean = job.isActive && content.isAvailable && isScreenActive() fun close() = job.cancel() }