package dev.inmo.postssystem.client.utils

import androidx.compose.runtime.*
import kotlinx.coroutines.*
import org.jetbrains.compose.web.dom.DOMScope
import org.w3c.dom.Element
import kotlin.coroutines.CoroutineContext

fun Composition.linkWithJob(job: Job) {
    job.invokeOnCompletion {
        this@linkWithJob.dispose()
    }
}

fun Composition.linkWithContext(coroutineContext: CoroutineContext) = linkWithJob(coroutineContext.job)

suspend fun <TElement : Element> renderComposableAndLinkToContext(
    root: TElement,
    monotonicFrameClock: MonotonicFrameClock = DefaultMonotonicFrameClock,
    content: @Composable DOMScope<TElement>.() -> Unit
): Composition = org.jetbrains.compose.web.renderComposable(root, monotonicFrameClock, content).apply {
    linkWithContext(
        currentCoroutineContext()
    )
}
