SharedPlatformWebView.kt
composeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/SharedPlatformWebView.kt
1package eu.friedcutlet.yokan.ui.screens.webview23import androidx.compose.foundation.layout.fillMaxSize4import androidx.compose.runtime.remember5import com.multiplatform.webview.request.RequestInterceptor6import com.multiplatform.webview.request.WebRequest7import com.multiplatform.webview.request.WebRequestInterceptResult8import com.multiplatform.webview.web.WebViewNavigator9import androidx.compose.runtime.Composable10import androidx.compose.runtime.LaunchedEffect11import androidx.compose.runtime.getValue12import androidx.compose.runtime.rememberUpdatedState13import androidx.compose.runtime.snapshotFlow14import androidx.compose.ui.Modifier15import com.multiplatform.webview.cookie.Cookie16import com.multiplatform.webview.web.LoadingState17import com.multiplatform.webview.web.NativeWebView18import com.multiplatform.webview.web.WebView19import com.multiplatform.webview.web.WebViewFactoryParam20import com.multiplatform.webview.web.rememberWebViewNavigator21import com.multiplatform.webview.web.rememberWebViewState22import eu.friedcutlet.yokan.domain.ProfileId23import eu.friedcutlet.yokan.services.catchingNonCancellation24import eu.friedcutlet.yokan.services.http.cookies.CookieJar25import kotlinx.coroutines.flow.distinctUntilChanged26import kotlinx.coroutines.flow.filter2728@Composable29internal fun SharedPlatformWebView(30 url: String,31 cookieJar: CookieJar,32 modifier: Modifier = Modifier,33 userAgent: String? = null,34 onNavigated: (String) -> Unit = {},35 onLoadingProgress: (Float) -> Unit = {},36 interceptUrlPrefix: String? = null,37) {38 val onNavigatedState by rememberUpdatedState(onNavigated)39 val onLoadingProgressState by rememberUpdatedState(onLoadingProgress)40 val interceptPrefix by rememberUpdatedState(interceptUrlPrefix)41 val state = rememberWebViewState(url = url) {42 isJavaScriptEnabled = true43 if (!userAgent.isNullOrBlank()) {44 customUserAgentString = userAgent45 }46 }47 // Consulted for main-frame navigations and server redirects (Android shouldOverrideUrlLoading, iOS navigation policy).48 val interceptor = remember {49 object : RequestInterceptor {50 override fun onInterceptUrlRequest(request: WebRequest, navigator: WebViewNavigator): WebRequestInterceptResult {51 if (!cookieJar.canUseBrowserStorage) return WebRequestInterceptResult.Reject52 val prefix = interceptPrefix ?: return WebRequestInterceptResult.Allow53 if (!request.url.startsWith(prefix)) return WebRequestInterceptResult.Allow54 onNavigatedState(request.url)55 return WebRequestInterceptResult.Reject56 }57 }58 }59 val navigator = rememberWebViewNavigator(requestInterceptor = interceptor)6061 LaunchedEffect(url) {62 seedSharedWebViewCookies(url, cookieJar)63 val current = state.lastLoadedUrl64 if (!current.isNullOrBlank() && current != url) {65 navigator.loadUrl(url)66 }67 }6869 LaunchedEffect(state) {70 snapshotFlow { state.loadingState }71 .distinctUntilChanged()72 .collect { loadingState ->73 val progress = when (loadingState) {74 is LoadingState.Loading -> loadingState.progress75 is LoadingState.Finished -> 1f76 else -> 0.05f77 }78 onLoadingProgressState(progress.coerceIn(0f, 1f))79 }80 }8182 LaunchedEffect(state) {83 snapshotFlow { state.loadingState }84 .filter { it is LoadingState.Finished }85 .collect {86 val current = state.lastLoadedUrl?.takeIf { it.isNotBlank() } ?: url87 harvestSharedWebViewCookies(current, cookieJar)88 onNavigatedState(current)89 }90 }9192 WebView(93 state = state,94 navigator = navigator,95 modifier = modifier.fillMaxSize(),96 factory = remember(cookieJar.profileId) { profileWebViewFactory(cookieJar.profileId) },97 )98}99100/** Creates the rendered view inside [profileId]'s platform browser store (Default: the app-wide one). */101internal expect fun profileWebViewFactory(profileId: ProfileId): (WebViewFactoryParam) -> NativeWebView102103/** Writes [cookie] for [url] into [profileId]'s platform cookie store. */104internal expect suspend fun setProfileWebViewCookie(profileId: ProfileId, url: String, cookie: Cookie)105106/** `Set-Cookie`-style lines the platform store of [profileId] holds for [url]. */107internal expect suspend fun profileWebViewSetCookies(profileId: ProfileId, url: String): List<String>108109private suspend fun seedSharedWebViewCookies(url: String, cookieJar: CookieJar) {110 if (!cookieJar.canUseBrowserStorage) return111 val host = parseSharedWebViewHost(url) ?: return112 val header = cookieJar.cookieHeader(url)113 ?: cookieJar.rawCookieFor(host)114 ?: return115 val secure = url.startsWith("https://", ignoreCase = true)116 header.split(';').forEach { entry ->117 if (!cookieJar.canUseBrowserStorage) return118 val trimmed = entry.trim()119 val eq = trimmed.indexOf('=')120 if (eq <= 0) return@forEach121 val name = trimmed.substring(0, eq).trim()122 val value = trimmed.substring(eq + 1).trim()123 if (name.isBlank() || value.isBlank()) return@forEach124 catchingNonCancellation {125 setProfileWebViewCookie(126 cookieJar.profileId,127 url,128 Cookie(129 name = name,130 value = value,131 domain = host,132 path = "/",133 isSessionOnly = true,134 isSecure = secure,135 ),136 )137 }138 }139}140141private suspend fun harvestSharedWebViewCookies(url: String, cookieJar: CookieJar) {142 if (!cookieJar.canUseBrowserStorage) return143 val setCookies = catchingNonCancellation { profileWebViewSetCookies(cookieJar.profileId, url) }.getOrNull().orEmpty()144 .filter { line ->145 val pair = line.substringBefore(';')146 pair.substringBefore('=').isNotBlank() && pair.substringAfter('=', "").isNotBlank()147 }148 if (setCookies.isNotEmpty() && cookieJar.canUseBrowserStorage) cookieJar.setFromResponse(url, setCookies)149}150151private fun parseSharedWebViewHost(url: String): String? {152 val withoutProtocol = url.substringAfter("://", url)153 val end = withoutProtocol.indexOfFirst { it == '/' || it == '?' || it == '#' }154 val hostPort = if (end == -1) withoutProtocol else withoutProtocol.substring(0, end)155 if (hostPort.isBlank()) return null156 return hostPort.substringBefore(':').lowercase()157}158