class LoginStateManager(private val context: Context) {
private val prefs: SharedPreferences = context.getSharedPreferences(
"osticket_prefs",
Context.MODE_PRIVATE
)
@Composable
fun LoginScreen(onLoginSuccess: (Boolean) -> Unit) {
var showWebView by remember { mutableStateOf(false) }
var isAdminLogin by remember { mutableStateOf(false) }
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun CustomWebView(
url: String,
onUrlChange: (String) -> Unit = {},
onLoadingStateChange: (Boolean) -> Unit = {},
onCookiesReceived: (List) -> Unit = {},
onError: (String) -> Unit = {},
onPageFinished: () -> Unit = {},
enableJavaScript: Boolean = true,
allowZoom: Boolean = false,
userAgent: String? = null
) {
val context = LocalContext.current
val cookieManager = CookieManager.getInstance().apply {
setAcceptCookie(true)
}
code
// Remember the WebView to preserve its state across recompositions
val webView = remember {
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// Set third party cookies for this specific WebView instance
cookieManager.setAcceptThirdPartyCookies(this, true)
// Initialize WebViewClient with overridden methods
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
onLoadingStateChange(true)
url?.let { onUrlChange(it) }
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
onLoadingStateChange(false)
getCurrentCookies(view)
onPageFinished()
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
request?.url?.toString()?.let { onUrlChange(it) }
return false
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
error?.description?.toString()?.let { onError(it) }
}
private fun getCurrentCookies(view: WebView?) {
view?.url?.let { currentUrl ->
val cookies = cookieManager.getCookie(currentUrl)?.split(";")?.mapNotNull { cookieString ->
val parts = cookieString.trim().split("=", limit = 2)
if (parts.size == 2) {
Cookie(parts[0], parts[1])
} else {
null
}
} ?: emptyList()
onCookiesReceived(cookies)
}
}
}
webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
Log.d(
"WebView",
"${consoleMessage?.message()} -- From line ${consoleMessage?.lineNumber()} of ${consoleMessage?.sourceId()}"
)
return true
}
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
onLoadingStateChange(newProgress < 100)
}
}
// Configure WebView settings
settings.apply {
javaScriptEnabled = enableJavaScript
domStorageEnabled = true
javaScriptCanOpenWindowsAutomatically = true
loadWithOverviewMode = true
useWideViewPort = true
allowContentAccess = true
allowFileAccess = true
builtInZoomControls = allowZoom
displayZoomControls = false
setSupportZoom(allowZoom)
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
defaultTextEncodingName = "utf-8"
cacheMode = WebSettings.LOAD_DEFAULT // Enable caching
userAgent?.let { userAgentString = it }
// Enable database
databaseEnabled = true
}
// Load the initial URL once
loadUrl(url)
}
}
// Modified DisposableEffect to preserve state
DisposableEffect(Unit) {
onDispose {
webView.stopLoading()
// Don't clear cache or cookies
webView.loadUrl("about:blank")
// Only remove views, don't destroy the WebView
webView.removeAllViews()
}
}
// Embed the WebView into the Compose UI
AndroidView(
factory = { webView },
update = { /* No-op to prevent reloading */ }
)
}
// Data class for cookies
data class Cookie(
val name: String,
val value: String
)
// Example usage:
@Composable
fun WebViewScreen(url: String) {
var currentUrl by remember { mutableStateOf("") }
var isLoading by remember { mutableStateOf(true) }
var cookies by remember { mutableStateOf<List>(emptyList()) }
var error by remember { mutableStateOf<String?>(null) }
To add the https://digital-land.org/osticket/scp/profile.php#preferences URL to the admin-only settings and position the logout option below it in your osTicket Android application using Kotlin and Jetpack Compose, follow these steps:
Add a New Route for Preferences in DashboardScreen.kt
Modify the SettingsScreen to Include the Preferences Option for Admins
Ensure Proper Navigation and Layout
Below is a detailed guide with code snippets to help you implement this feature.
1. Add a New Route for Preferences in DashboardScreen.kt
First, you need to define a new route in the NavHost within your DashboardScreen. This route will handle the display of the preferences page using the existing WebViewScreen composable.
Step-by-Step Instructions:
a. Define a New Route for Admin Preferences
In your DashboardScreen.kt, locate the NavHost setup. You'll need to add a new composable route for the admin preferences.
If you prefer to manage routes through the Screen sealed class, you can add the new route there as well.
kotlin
// Inside DashboardScreen.kt or a separate Screen.kt file
sealed class Screen(val route: String, val label: String, val icon: ImageVector) {
// Existing Admin/Agent screens
object AdminTickets : Screen("admin_tickets", "Tickets", Icons.Default.List)
object Tasks : Screen("tasks", "Tasks", Icons.Default.Check)
object Users : Screen("users", "Users", Icons.Default.Person)
object Other : Screen("other", "Settings", Icons.Default.Settings)
// **New Admin Preferences Screen**
object AdminPreferences : Screen("admin_preferences", "Preferences", Icons.Default.Settings)
// Existing User screens
object UserTickets : Screen("user_tickets", "My Tickets", Icons.Default.List)
object UserProfile : Screen("user_profile", "Profile", Icons.Default.Person)
object UserSettings : Screen("user_settings", "Settings", Icons.Default.Settings)
}
Then update the NavHost accordingly:
kotlin
// Replace the string "admin_preferences" with Screen.AdminPreferences.route
composable(Screen.AdminPreferences.route) {
WebViewScreen(url = "https://digital-land.org/osticket/scp/profile.php#preferences")
}
2. Modify the SettingsScreen to Include the Preferences Option for Admins
Next, you'll update the SettingsScreen composable to include a button that navigates to the admin preferences URL only when the user is an admin. The logout button will remain below this new option.
Step-by-Step Instructions:
a. Update the SettingsScreen Composable
Modify the SettingsScreen to accept a navigation lambda (onNavigate) that allows it to navigate to different routes. This will enable the settings screen to navigate to the new preferences route when the admin clicks the Preferences button.
Ensure that the CustomWebView and other related composables are correctly handling the navigation and state.
Summary
By following the steps above, you've successfully added an admin-only preference link to your settings screen and positioned the logout button below it. This approach ensures a clean navigation flow and maintains the separation of concerns within your composables.
Key Points:
Conditional UI Rendering: Use isAdmin to conditionally show UI components.
Navigation Handling: Utilize NavController to navigate between different composables.
State Management: Manage loading states and errors within your WebViewScreen.
User Experience: Implement back navigation to enhance usability.
Feel free to further customize the UI elements and navigation behavior to best fit your application's requirements.