InAppWebViewScreen.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/InAppWebViewScreen.kt
1package eu.friedcutlet.yokan.ui.screens.webview23import androidx.compose.foundation.layout.Box4import androidx.compose.foundation.layout.Column5import androidx.compose.foundation.layout.fillMaxSize6import androidx.compose.foundation.layout.fillMaxWidth7import androidx.compose.foundation.layout.padding8import androidx.compose.material.icons.Icons9import androidx.compose.material.icons.automirrored.filled.ArrowBack10import androidx.compose.material.icons.automirrored.filled.ArrowForward11import androidx.compose.material.icons.filled.Close12import androidx.compose.material.icons.filled.Delete13import androidx.compose.material.icons.filled.MoreVert14import androidx.compose.material.icons.filled.OpenInBrowser15import androidx.compose.material.icons.filled.Refresh16import androidx.compose.material.icons.filled.Security17import androidx.compose.material.icons.filled.Share18import androidx.compose.material3.AlertDialog19import androidx.compose.material3.DropdownMenu20import androidx.compose.material3.DropdownMenuItem21import androidx.compose.material3.ExperimentalMaterial3Api22import androidx.compose.material3.Icon23import androidx.compose.material3.IconButton24import androidx.compose.material3.LinearProgressIndicator25import androidx.compose.material3.MaterialTheme26import androidx.compose.material3.OutlinedTextField27import androidx.compose.material3.Surface28import androidx.compose.material3.Text29import androidx.compose.material3.TextButton30import androidx.compose.material3.TopAppBar31import androidx.compose.runtime.Composable32import androidx.compose.runtime.LaunchedEffect33import androidx.compose.runtime.getValue34import androidx.compose.runtime.key35import androidx.compose.runtime.mutableStateOf36import androidx.compose.runtime.remember37import androidx.compose.runtime.setValue38import androidx.compose.ui.Modifier39import androidx.compose.ui.text.style.TextOverflow40import androidx.compose.ui.unit.dp41import androidx.lifecycle.compose.collectAsStateWithLifecycle42import androidx.lifecycle.viewmodel.compose.viewModel43import eu.friedcutlet.yokan.app.YokanRuntime44import eu.friedcutlet.yokan.services.system.openSystemBrowser45import eu.friedcutlet.yokan.ui.navigation.Navigator46import eu.friedcutlet.yokan.ui.navigation.Route47import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold48import eu.friedcutlet.yokan.ui.components.compactDialogWidth49import org.jetbrains.compose.resources.stringResource50import yokan.composeapp.generated.resources.Res51import yokan.composeapp.generated.resources.action_back52import yokan.composeapp.generated.resources.action_cancel53import yokan.composeapp.generated.resources.action_refresh54import yokan.composeapp.generated.resources.ui_close5556@Composable57internal fun InAppWebViewRoute(route: Route.InAppWebView, nav: Navigator) {58 val model = viewModel {59 InAppWebViewViewModel(YokanRuntime.services.webView, YokanRuntime.services.cookieJar, YokanRuntime.settings)60 }61 val state by model.state.collectAsStateWithLifecycle()62 val userAgent = route.userAgent ?: state.defaultUserAgent63 InAppWebViewScreen(64 url = route.url,65 title = route.title,66 progress = state.progress,67 onProgress = model::setProgress,68 onSolveCloudflare = { model.solveCloudflare(state.verificationUrl ?: route.url, userAgent) },69 onImportCookies = { raw -> model.importCookies(route.url, raw) },70 onClearCookies = { model.clearCookies(route.url) },71 onOpenBrowser = { if (model.cookieJar.canUseBrowserStorage) openSystemBrowser(route.url) },72 onBack = nav::back,73 ) { modifier, isObscuredByOverlay ->74 if (state.verificationUrl != null) {75 BrowserVerificationPanel(76 status = state.verificationStatus,77 modifier = modifier,78 onVerify = { model.solveCloudflare(state.verificationUrl ?: route.url, userAgent) },79 onReturn = nav::back,80 )81 } else PlatformWebView(82 url = route.url,83 cookieJar = model.cookieJar,84 modifier = modifier,85 userAgent = userAgent,86 isObscuredByOverlay = isObscuredByOverlay,87 onNavigated = model::syncCookies,88 onLoadingProgress = model::setProgress,89 onVerificationRequired = model::requireBrowserVerification,90 )91 }92}9394/**95 * Full-screen in-app WebView. Used for refreshing Cloudflare cookies or96 * inspecting source pages without leaving the app. The actual rendering97 * happens in the per-platform [PlatformWebView] composable (Android98 * WebView, iOS WKWebView, desktop fallback to system browser).99 */100@OptIn(ExperimentalMaterial3Api::class)101@Composable102internal fun InAppWebViewScreen(103 url: String,104 title: String,105 progress: Float,106 onProgress: (Float) -> Unit,107 onSolveCloudflare: () -> Unit,108 /** Returns true when the cookies were saved. */109 onImportCookies: (String) -> Boolean,110 onClearCookies: () -> Unit,111 onOpenBrowser: () -> Unit,112 onBack: () -> Unit,113 /** The platform WebView; re-mounted on refresh. */114 webView: @Composable (modifier: Modifier, isObscuredByOverlay: Boolean) -> Unit,115) {116 var menuOpen by remember { mutableStateOf(false) }117 var importCookiesDialogOpen by remember { mutableStateOf(false) }118 var refreshNonce by remember { mutableStateOf(0) }119 LaunchedEffect(refreshNonce) {120 onProgress(0.05f)121 }122 if (importCookiesDialogOpen) {123 CookieImportDialog(124 url = url,125 onDismiss = { importCookiesDialogOpen = false },126 onConfirm = { raw ->127 if (onImportCookies(raw)) importCookiesDialogOpen = false128 },129 )130 }131 Scaffold(132 topBar = {133 Column {134 TopAppBar(135 title = {136 Column {137 Text(138 text = title.ifBlank { url },139 maxLines = 1,140 overflow = TextOverflow.Ellipsis,141 style = MaterialTheme.typography.titleMedium,142 )143 if (title.isNotBlank()) {144 Text(145 text = url,146 maxLines = 1,147 overflow = TextOverflow.Ellipsis,148 style = MaterialTheme.typography.bodySmall,149 color = MaterialTheme.colorScheme.onSurfaceVariant,150 )151 }152 }153 },154 navigationIcon = {155 IconButton(onClick = onBack) {156 Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.ui_close))157 }158 },159 actions = {160 // goBack / goForward are not exposed by the common161 // PlatformWebView surface yet — render the icons in a162 // disabled state to preserve the wireframe layout.163 IconButton(onClick = { /* goBack */ }, enabled = false) {164 Icon(165 Icons.AutoMirrored.Filled.ArrowBack,166 contentDescription = stringResource(Res.string.action_back),167 )168 }169 IconButton(onClick = { /* goForward */ }, enabled = false) {170 Icon(171 Icons.AutoMirrored.Filled.ArrowForward,172 contentDescription = "Forward",173 )174 }175 Box {176 IconButton(onClick = { menuOpen = true }) {177 Icon(Icons.Filled.MoreVert, contentDescription = "More")178 }179 DropdownMenu(180 expanded = menuOpen,181 onDismissRequest = { menuOpen = false },182 ) {183 DropdownMenuItem(184 text = { Text(stringResource(Res.string.action_refresh)) },185 leadingIcon = {186 Icon(187 Icons.Filled.Refresh,188 contentDescription = null,189 )190 },191 onClick = {192 menuOpen = false193 refreshNonce++194 },195 )196 DropdownMenuItem(197 text = { Text("Share") },198 leadingIcon = {199 Icon(200 Icons.Filled.Share,201 contentDescription = null,202 )203 },204 onClick = {205 menuOpen = false206 onOpenBrowser()207 },208 )209 DropdownMenuItem(210 text = { Text("Open in browser") },211 leadingIcon = {212 Icon(213 Icons.Filled.OpenInBrowser,214 contentDescription = null,215 )216 },217 onClick = {218 menuOpen = false219 onOpenBrowser()220 },221 )222 DropdownMenuItem(223 text = { Text("Solve Cloudflare") },224 leadingIcon = {225 Icon(226 Icons.Filled.Security,227 contentDescription = null,228 )229 },230 onClick = {231 menuOpen = false232 onSolveCloudflare()233 },234 )235 DropdownMenuItem(236 text = { Text("Import cookies") },237 leadingIcon = {238 Icon(239 Icons.Filled.Security,240 contentDescription = null,241 )242 },243 onClick = {244 menuOpen = false245 importCookiesDialogOpen = true246 },247 )248 DropdownMenuItem(249 text = { Text("Clear cookies") },250 leadingIcon = {251 Icon(252 Icons.Filled.Delete,253 contentDescription = null,254 )255 },256 onClick = {257 menuOpen = false258 onClearCookies()259 },260 )261 }262 }263 },264 )265 if (progress > 0f && progress < 1f) {266 LinearProgressIndicator(267 progress = { progress },268 modifier = Modifier.fillMaxWidth(),269 )270 }271 }272 },273 ) { padding ->274 Box(modifier = Modifier.fillMaxSize().padding(padding)) {275 // The webview body is delegated to per-platform implementations.276 // Wrap in a Surface so the placeholder seen on platforms without a277 // bundled webview engine matches the surrounding scaffolding.278 Surface(279 modifier = Modifier.fillMaxSize(),280 color = MaterialTheme.colorScheme.surface,281 ) {282 // Re-mount the platform view when refresh is requested so the283 // underlying engine reloads the URL.284 key(refreshNonce) {285 webView(Modifier.fillMaxSize(), menuOpen || importCookiesDialogOpen)286 }287 }288 }289 }290}291292@Composable293private fun CookieImportDialog(294 url: String,295 onDismiss: () -> Unit,296 onConfirm: (String) -> Unit,297) {298 var value by remember { mutableStateOf("") }299 AlertDialog(300 onDismissRequest = onDismiss,301 modifier = Modifier.compactDialogWidth(),302 title = { Text("Import cookies") },303 text = {304 Column {305 Text(306 text = hostFromUrl(url)?.let { "Paste a Cookie header for $it." }307 ?: "Paste a Cookie header.",308 style = MaterialTheme.typography.bodyMedium,309 color = MaterialTheme.colorScheme.onSurfaceVariant,310 )311 OutlinedTextField(312 value = value,313 onValueChange = { value = it },314 modifier = Modifier.fillMaxWidth().padding(top = 12.dp),315 label = { Text("Cookie") },316 minLines = 4,317 maxLines = 8,318 )319 }320 },321 confirmButton = {322 TextButton(onClick = { onConfirm(value) }) {323 Text("Import")324 }325 },326 dismissButton = {327 TextButton(onClick = onDismiss) {328 Text(stringResource(Res.string.action_cancel))329 }330 },331 )332}333334internal fun hostFromUrl(url: String): String? {335 val withoutProtocol = url.substringAfter("://", url)336 val hostPort = withoutProtocol337 .substringBefore('/')338 .substringBefore('?')339 .substringBefore('#')340 return hostPort.substringBefore(':').lowercase().takeIf { it.isNotBlank() }341}342343internal fun normaliseCookieInput(raw: String): String? {344 val candidate = cookieHeaderRegex.find(raw)?.groupValues?.getOrNull(1)345 ?: raw.trim().removePrefix("Cookie:").removePrefix("cookie:").trim()346 val pairs = candidate347 .trim()348 .trim('"', '\'')349 .split(';')350 .mapNotNull { entry ->351 val trimmed = entry.trim()352 val eq = trimmed.indexOf('=')353 if (eq <= 0) return@mapNotNull null354 val name = trimmed.substring(0, eq).trim()355 val value = trimmed.substring(eq + 1).trim()356 if (name.lowercase() in cookieAttributeNames) return@mapNotNull null357 if (name.isBlank() || value.isBlank()) return@mapNotNull null358 "$name=$value"359 }360 return pairs.joinToString("; ").takeIf { it.isNotBlank() }361}362363private val cookieHeaderRegex = Regex("""(?i)(?:^|\s|['"])cookie\s*:\s*([^'"\r\n]+)""")364365private val cookieAttributeNames = setOf(366 "domain",367 "expires",368 "httponly",369 "max-age",370 "path",371 "samesite",372 "secure",373)374