Apache Solr open-source search software
chore: Migrate off Decompose/MVIKotlin/Essenty stack (#4929)
Christos Malliaridisc8ab71430f6e
diff --git a/changelog/unreleased/migrate-new-ui-off-decompose-mvikotlin.yml b/changelog/unreleased/migrate-new-ui-off-decompose-mvikotlin.ymlnew file mode 100644index 00000000000..616365e9688--- /dev/null+++ b/changelog/unreleased/migrate-new-ui-off-decompose-mvikotlin.yml@@ -0,0 +1,8 @@+title: Migrate the new UI off Decompose, MVIKotlin and Essenty to AndroidX ViewModel and Navigation 3+type: other+authors:+ - name: Christos Malliaridis+ nick: malliaridis+links:+ - name: GITHUB#4929+ url: https://github.com/apache/solr/pull/4929diff --git a/dev-docs/ui/component-development.adoc b/dev-docs/ui/component-development.adocindex 083abf63658..66522b7a0eb 100644--- a/dev-docs/ui/component-development.adoc+++ b/dev-docs/ui/component-development.adoc@@ -8,10 +8,13 @@ The following list contains a possible approach for implementing a new UI compon1. Create a new design or start with an existing design, see for example Figma2. Validate the use case and analyze the components that may be used for the implementation3. Create Composables that represent the UI component(s) and use placeholders for data population-4. Create a component interface and implementation with the UI state and UI component interactions-5. Create previews with preview component implementations to check the UI implementation-6. Create a store and store provider for fetching resources and interacting with Solr backend-7. Implement the client used by the store provider+4. Define the UI state class and the interactions of the UI component, and create a view model+(or a state holder) for them+5. Create previews with fake UI state to check the UI implementation+6. Create a repository for fetching resources and interacting with Solr backend, and use cases+for the logic on top of it+7. Create the component interface and implementation that provides the repository, the use cases+and the view model8. Write tests and test the new component9. If not already done, integrate the component in the existing application10. If not already done, extract resources like texts to allow internationalization and localization@@ -21,30 +24,45 @@ of how things are implemented, what they have in common, and how each technology== Component's Logic-=== Components (Decompose)+=== Components-The component integration interacts with the UI composables and the state store.+The component provides everything the UI needs to get started: the dependencies of the logic+(repositories and use cases) and factory methods for creating view models. The composables use+these factory methods to retrieve their view model:-The implementation of the component interface "catches" user inputs like clicks and passes them-to the store as ``Intent``s. The intents are then handled by the store implementation and-may send a request to the backend and / or update the store state. The component is consuming-and mapping the store state to the UI state. So once the store state is updated, it will-reflect the changes in the UI.+[source,kotlin]+----+val viewModel = viewModel { component.createEnvironmentViewModel() }+val uiState by viewModel.uiState.collectAsState()+-----=== State Stores and Store Providers+The component does not hold any state. This keeps components simple, and allows replacing+the dependencies with fake ones in tests and previews.-The state stores manage the state of the application, but independent of the state that is-represented in the UI. Instances are created by store providers that hold the logic of the-store.+=== View Models and State Holders-Store providers consist of three elements:+The view model and the state holder manage the state of a screen or section. They "catch" user+inputs like clicks through function calls, for example `viewModel.connect()`. The state+holder handles them, may call a use case to send a request to the backend, and updates the UI+state. So once the state is updated, it will reflect the changes in the UI.-- an executor implementation that consumes actions and intents and creates messages and labels-- a reducer that updates the store state with the messages produced by the executor-- a function for retrieving an instance of the store+- The UI state is exposed as a `StateFlow` and is usually a single immutable data class+(`[Name]UiState`) that has default values for all properties.+- Events that are meant for the parent (like navigating away) are exposed as a `SharedFlow`.+Events are not part of the state, as they should be handled only once.+- Coroutines are launched in the provided scope. Blocking work like network requests is switched+to the IO dispatcher of the injected `AppDispatchers`, so that tests can replace it.-The store provider does also define the interface for the client that has to be provided in-order for the executor to make API calls and interact with the Solr backend.+The logic lives in a plain state holder class that receives the coroutine scope as a parameter,+and a thin view model wraps it with `viewModelScope`. Keeping the logic out of the `ViewModel`+makes it possible to test it without any additional setup and to share it between view models.++=== Use Cases and Repositories++Repositories define the requests against the Solr API and return a `Result`. Use cases wrap a+single piece of logic on top of them, like validating an input, mapping errors or deciding what+to do with a response. State holders only depend on use case interfaces, which keeps the+state holders free of API details and easy to test with fake use cases.== Component's Visuals@@ -91,11 +109,31 @@ and https://developer.android.com/codelabs/jetpack-compose-accessibility#0[Codel=== Navigation and Child ComponentsSome components may have navigation elements and will load other components inside a frame layout.-Since components hold a hierarchical context that needs to be managed somehow, child components-(also used in navigation) are instantiated in a slightly different manner.--Decompose provides https://arkivanov.github.io/Decompose/navigation/overview/[a few examples]-and details of the process behind the navigation and child components.+The navigation state is a back stack that is owned by the view model of the component, and the+composable renders it with `NavDisplay`. Each destination is described by a serializable+navigation key that implements `NavKey`, for example:++[source,kotlin]+----+@Serializable+sealed interface MainScene : NavKey {+ @Serializable+ data object Cluster : MainScene+ // ...+}+----++The composable maps each key to the content of the destination in the `entryProvider`. Use the+`ViewModel` scope of the navigation entry (`rememberViewModelStoreNavEntryDecorator()`), so that+the view models of a destination are cleared once it is removed from the back stack.++Components of child destinations are provided by the parent component, and the composables of the+children report what the parent needs to know via events (`SharedFlow`s) or callbacks. The parent+then handles these by updating its back stack, see `RootViewModel` for an example.++The+https://developer.android.com/guide/navigation/navigation-3[Navigation 3 documentation]+provides more details about the concepts and recipes for common navigation use cases.== Additional Notesdiff --git a/dev-docs/ui/introduction.adoc b/dev-docs/ui/introduction.adocindex 906bb00b3ba..32ae966897d 100644--- a/dev-docs/ui/introduction.adoc+++ b/dev-docs/ui/introduction.adoc@@ -18,4 +18,4 @@ the documentation is covering the following topics for new and experienced devel== NotesAll the references to files and directories in the UI documentation are from within-the `solr/ui` module, if not otherwise stated.\ No newline at end of file+the `ui` module, if not otherwise stated.\ No newline at end of filediff --git a/dev-docs/ui/module-structure.adoc b/dev-docs/ui/module-structure.adocindex 5b678e4a9a3..a1082e431db 100644--- a/dev-docs/ui/module-structure.adoc+++ b/dev-docs/ui/module-structure.adoc@@ -16,34 +16,57 @@ if not the same, structure and files.The logical part of a simple component (`org/apache/solr/ui/components`) usually consists of:-- **The component interface** (`[ComponentName]Component.kt`), that defines the UI state and the-interaction options,+- **The component interface** (`[ComponentName]Component.kt`), that provides the dependencies of+the component (repositories and use cases) and factory methods for creating its view models. It+does not hold any state itself,-- **The store interface** (`store/[ComponentName]Store.kt`), that defines the (Solr) API state,-intents for interacting with the state and optional labels (fire-and-forget events),+- **The component implementation** (`integration/Default[ComponentName]Component.kt`), that+creates the dependencies lazily and passes them to the view models it creates. Some components+keep the interface and the implementation together in a `di` package instead (see `configsets`),-- **The store provider** (`store/[ComponentName]StoreProvider.kt`), that defines an API client-interface that is used for making requests against the Solr API by consuming intents,-updates the state and publishes labels,+- **The repository interface** (`repository/[ComponentName]Repository.kt`), that defines the+requests that can be made against the (Solr) API, and its implementation (usually+`data/Http[ComponentName]Repository.kt`), that uses a preconfigured HTTP client,-- **The implementations** (`integration/*`), including component-specific mappings-(`integration/Mappers.kt`) and interface implementations (like-`integration/[Variant][ComponentName]Component.kt`),+- **The use cases** (`domain/*UseCase.kt`), that encapsulate a single piece of business logic like+loading, validating or mapping errors. They are defined as an interface and have a default+implementation (`Default[Name]UseCase`) that is using the repository,-- **Component-specific data classes** (`domain/*`), that are used only by the UI module+- **The state holder** (`viewmodel/[ComponentName]StateHolder.kt`), a plain class that holds the+UI state as `StateFlow` and emits events as `SharedFlow`. It is created with a `CoroutineScope`,+so that it can be tested without Android or UI dependencies. The UI state class+(`[ComponentName]UiState`) is defined next to it,++- **The view model** (`viewmodel/[ComponentName]ViewModel.kt`), that is created by the component+implementation and provides the scope for the state holder. It exposes the state, the events and+the functions that the UI can call. Simple components may implement their state in the view model+directly,++- **Component-specific events** (`domain/*Event.kt`), that are emitted by the state holder to let+the parent (for example the screen that navigates) know that something happened,- **Component-specific API classes** (`data/*`), that are used for representing API requests /responses.-Some components may use multiple stores to consume different API endpoints or no store at all-if no API interaction is necessary. Multiple components may also be used to simplify the complexity-or separate the responsibilities into smaller UI elements.+Some components may use multiple repositories to consume different API endpoints or none at all+if no API interaction is necessary. Multiple state holders may also be used to simplify the+complexity or separate the responsibilities into smaller UI elements, and can be shared between+view models (see `configsets`). The `auth` component, for example, uses one state holder per+authentication method and a parent state holder that holds the shared state.Component data classes for API and internal use may also be merged and used interchangeably toreduce overall complexity. However, this affects the separation of concerns and may requirein a later state the separation and mapping again.-This structure is strongly inspired by Decompose's https://arkivanov.github.io/Decompose/samples/[samples].+=== Navigation++The screens and sections are navigated with Navigation 3. The navigation state is a back stack+of navigation keys (`RootScene`, `MainScene`, `ConfigsetsScene`) that is owned by a view model+(`RootViewModel`, `MainViewModel`, `ConfigsetsRouteViewModel`). The parent components provide the+components of the screens they display, like `RootComponent.createStartComponent()`.++Screens report user flows to their parent via events, like `StartEvent` or `AuthenticationEvent`.+The parent view model handles the event by changing the back stack.== User Interface (UI)@@ -61,9 +84,13 @@ Theme-related classes, functions and variables are all placed inside `.ui.theme`is making strong use of and customizes Material 3. You can find more information aboutCompose and Material 3 at https://m3.material.io/develop/android/jetpack-compose[Material Design - Jetpack Compose].-Composables may accept a component interface and be stateful, or simply hoist the entire-state via parameters and be stateless. For more information about state hoisting,-you can have a look at https://developer.android.com/develop/ui/compose/state[Managing state].+Composables may accept a component, retrieve the view model from it and therefore be stateful, or+simply hoist the entire state via parameters and be stateless. A common approach is to provide both:+a stateful composable that connects the view model to a stateless composable of the same name that+takes the UI state and callbacks (for example `StartContent(component, onEvent)` and+`StartContent(uiState, onSolrUrlChange, onConnect)`). The stateless variants are used for+previews and UI tests, as they do not need any further setup. For more information about state+hoisting, you can have a look at https://developer.android.com/develop/ui/compose/state[Managing state].=== Compose Resourcesdiff --git a/dev-docs/ui/technology-overview.adoc b/dev-docs/ui/technology-overview.adocindex 440eb158c5d..59deabcc39c 100644--- a/dev-docs/ui/technology-overview.adoc+++ b/dev-docs/ui/technology-overview.adoc@@ -53,31 +53,30 @@ and adaptive user experience.The https://m3.material.io/[Material 3 website] gives a good introduction into user interfacedesign and Material 3.-=== Decompose+=== AndroidX Lifecycle (ViewModel)-Decompose is a library for managing the lifecycle of components in Compose Multiplatform-applications. It provides tools for navigating between screens and managing state across-different parts of an application.+The UI state and the logic behind a screen are held by a+https://developer.android.com/topic/libraries/architecture/viewmodel[ViewModel]. A `ViewModel`+survives recompositions, provides a `viewModelScope` for coroutines that is cancelled+automatically once the `ViewModel` is cleared, and can be created from within a composable with+`viewModel { ... }`.-The main features of Decompose include navigation, state management and component lifecycle.-You can find out more and get started via the https://arkivanov.github.io/Decompose/[Decompose documentation].+The state itself is exposed as `StateFlow` and one-shot events as `SharedFlow`, which makes the+data flow between the UI and the logic unidirectional: the UI renders the state and forwards user+interactions to the `ViewModel`, which updates the state.-=== MVIKotlin+The libraries are used through their Compose Multiplatform ports that are published by JetBrains+(`org.jetbrains.androidx.lifecycle`). Most of the Android documentation therefore applies to the UI+module as well, but keep in mind that some Android-specific features are not available on all+targets.-MVIKotlin is a library for implementing the Model-View-Intent (MVI) architecture pattern in-Kotlin applications. It is particularly useful for managing complex state and side effects in a-predictable manner. In combination with Decompose it provides a great foundation and-unified structure for the UI components.+=== Navigation 3-You can find out more at https://arkivanov.github.io/MVIKotlin/.+https://developer.android.com/guide/navigation/navigation-3[Navigation 3] is used for navigating+between screens and sections. The navigation state is a simple back stack (a list of navigation+keys) that is owned by a `ViewModel`, and the `NavDisplay` composable renders the entry on top+of the back stack. The `ViewModel` scopes provided by the navigation entries make sure that the+`ViewModel`s of an entry are cleared once the entry is removed from the back stack.-=== Essenty--Essenty is a collection of utility libraries that complement the Kotlin ecosystem,-particularly useful in Compose Multiplatform projects. It includes tools for handling events,-lifecycles, and other common tasks in a type-safe and idiomatic way.--Similar to MVIKotlin, it adds the foundation and structure of the UI module and plays an-essential part in Decompose.--For more information, you can have a look at https://github.com/arkivanov/Essenty[GitHub - Essenty].+Navigating therefore means to change the back stack. This makes the navigation logic easy to+test without any UI.diff --git a/dev-docs/ui/testing-and-deployment.adoc b/dev-docs/ui/testing-and-deployment.adocindex 9c108eaf17e..9d8986b9556 100644--- a/dev-docs/ui/testing-and-deployment.adoc+++ b/dev-docs/ui/testing-and-deployment.adoc@@ -32,7 +32,7 @@ To launch the JVM client, you can use:[source,bash]-----./gradlew :solr:ui:run+./gradlew -p ui :desktopApp:run----To run the app on the web, you can launch the web target with:@@ -40,7 +40,7 @@ To run the app on the web, you can launch the web target with:[source,bash]----# not recommended for the above reasons-./gradlew :solr:ui:wasmJsBrowserRun+./gradlew -p ui :webApp:wasmJsBrowserDevelopmentRun----Build times may be a bit longer than with the standalone JVM build.@@ -48,7 +48,8 @@ Build times may be a bit longer than with the standalone JVM build.=== Integration TestsThe integration tests of the module focus on testing the implementation found in-`org.apache.solr.ui.views`. That includes all UI elements / composables. Integration tests+`org.apache.solr.ui.views`. That includes all UI elements / composables. Prefer testing the+stateless composables, as they only need a UI state and callbacks. Integration testsmay test entire flows as well, but require a suitable testing environment.Since UI tests require a more complex and platform-specific testing environment, they are disabled@@ -61,8 +62,34 @@ Unit tests test the implementation found in `org.apache.solr.ui.components`. Thaincludes the logical part of the new UI and does not have any constraints to the UI part.Therefore, they can be executed in the automation pipelines easily.-The unit tests use mocks for the API and test mainly the behavior and state changes of the-components to confirm correct component state transitions with specific inputs.+The unit tests mainly cover the state holders (`viewmodel/*StateHolder.kt`) and the use cases.+They use fake use cases or repositories (or an HTTP client with a mocked engine) for the API, and+test the behavior and state changes to confirm correct state transitions and emitted events with+specific inputs.++State holders receive their coroutine scope and dispatchers as parameters, which allows running+them with the test scheduler without any other setup:++[source,kotlin]+----+@Test+fun `WHEN initialized THEN system data fetched`() = runTest {+ val stateHolder = EnvironmentStateHolder(+ scope = this,+ loadSystemDataUseCase = fakeLoadSystemDataUseCase,+ loadJavaPropertiesUseCase = fakeLoadJavaPropertiesUseCase,+ dispatchers = TestDispatchers(UnconfinedTestDispatcher(testScheduler)),+ )+ advanceUntilIdle()++ assertEquals(expectedSolrHome, stateHolder.uiState.value.solrHome)+}+----++State holders that collect flows for as long as they exist (like the authentication state+holder) should be created with `backgroundScope` instead, so that the test does not wait for them.+Events are `SharedFlow`s without replay. To test them, collect them in the `backgroundScope`+before triggering the action.== Deployment@@ -78,16 +105,16 @@ you can use:[source,bash]-----./gradlew :solr:ui:packageDistributionForCurrentOS+./gradlew -p ui :desktopApp:packageDistributionForCurrentOS-----The distribution can be found at `solr/ui/build/compose/binaries/main/[deb|msi|dmg]/`.+The distribution can be found at `ui/desktopApp/build/compose/binaries/main/[deb|msi|dmg]/`.To build the JVM target for production, you can use:[source,bash]-----./gradlew :solr:ui:packageReleaseDistributionForCurrentOS+./gradlew -p ui :desktopApp:packageReleaseDistributionForCurrentOS----Platform-specific gradle tasks exist as well, but you cannot build for a@@ -98,10 +125,10 @@ If the client machine has Java installed, you can also generate an UberJar:[source,bash]----# for development-./gradlew :solr:ui:packageUberJarForCurrentOs+./gradlew -p ui :desktopApp:packageUberJarForCurrentOS# for production-./gradlew :solr:ui:packageReleaseUberJarForCurrentOs+./gradlew -p ui :desktopApp:packageReleaseUberJarForCurrentOS----When building the entire Solr project, the wasmJs target is included in the build artifacts.diff --git a/ui/README.md b/ui/README.mdindex 734d8576f58..ba22d7a7db0 100644--- a/ui/README.md+++ b/ui/README.md@@ -43,7 +43,7 @@ If you load the module in your IDE, the IDE may create a new gradle wrapper undegradlew/gradle.bat files under `ui/`. In this case make sure the wrapper is on the same version as the root project(see `gradle/wrapper/gradle-wrapper.properties`) to avoid any build issues later on CI.-To build and run the desktop client simply run from the root directory `./gradlew -p :desktopApp:run`, or if you+To build and run the desktop client simply run from the root directory `./gradlew -p ui :desktopApp:run`, or if youloaded the module separately from inside `ui/` (new root) `./gradlew :desktopApp:run`.The desktop app is running a standalone client and therefore need a solr instance / backend to connect with.@@ -59,7 +59,7 @@ or build from source by setting `solr.ui.buildFromSource=true`. Once the Solr prVarious references are included in the webapp for already migrated pages.> Note that the standalone WebAssembly app executed via-> `./gradlew :webApp:wasmJsBrowserRun` runs on port `8080` and will run+> `./gradlew :webApp:wasmJsBrowserDevelopmentRun` runs on port `8080` and will run> into CORS exceptions. Therefore, the usage of it for development is> discouraged.>diff --git a/ui/desktopApp/build.gradle.kts b/ui/desktopApp/build.gradle.ktsindex 097d51cfdad..44938836881 100644--- a/ui/desktopApp/build.gradle.kts+++ b/ui/desktopApp/build.gradle.kts@@ -30,12 +30,6 @@ dependencies {implementation(libs.kotlinx.coroutines.swing)implementation(libs.compose.material3)- implementation(libs.essenty.lifecycle)- implementation(libs.decompose.decompose)- implementation(libs.decompose.extensions.compose)- implementation(libs.mvikotlin.main)- implementation(libs.mvikotlin.mvikotlin)-implementation(libs.compose.uiToolingPreview)}diff --git a/ui/desktopApp/src/main/kotlin/org/apache/solr/ui/Main.kt b/ui/desktopApp/src/main/kotlin/org/apache/solr/ui/Main.ktindex 9da8c84fdc3..ec476ec796d 100644--- a/ui/desktopApp/src/main/kotlin/org/apache/solr/ui/Main.kt+++ b/ui/desktopApp/src/main/kotlin/org/apache/solr/ui/Main.kt@@ -23,16 +23,9 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.window.Windowimport androidx.compose.ui.window.applicationimport androidx.compose.ui.window.rememberWindowState-import com.arkivanov.decompose.DefaultComponentContext-import com.arkivanov.decompose.extensions.compose.lifecycle.LifecycleController-import com.arkivanov.essenty.lifecycle.LifecycleRegistry-import com.arkivanov.mvikotlin.core.utils.setMainThreadId-import com.arkivanov.mvikotlin.main.store.DefaultStoreFactoryimport java.awt.Dimension-import kotlinx.coroutines.Dispatchersimport org.apache.solr.ui.components.root.RootComponentimport org.apache.solr.ui.components.root.integration.SimpleRootComponent-import org.apache.solr.ui.utils.DefaultAppComponentContextimport org.apache.solr.ui.utils.getDefaultClientimport org.apache.solr.ui.views.root.RootContentimport org.apache.solr.ui.views.theme.SolrTheme@@ -40,35 +33,16 @@ import org.apache.solr.ui.views.theme.SolrTheme/*** Entry point of the Compose application for all JVM-based (desktop) targets.*- * This function sets up the lifecycle management and instantiates the [RootComponent] with the- * [DefaultAppComponentContext] that is used by all child components.+ * This function instantiates the [RootComponent] that is used by all screens.*/fun main() {- val lifecycle = LifecycleRegistry()- val componentContext = DefaultAppComponentContext(- componentContext = DefaultComponentContext(lifecycle = lifecycle),- mainContext = Dispatchers.Main,- ioContext = Dispatchers.IO,- )-- val storeFactory = DefaultStoreFactory()-// TODO Let the user provide the URL via input field on desktopval httpClient = getDefaultClient()- val root: RootComponent = runOnUiThread {- setMainThreadId(Thread.currentThread().threadId())-- SimpleRootComponent(- componentContext = componentContext,- storeFactory = storeFactory,- httpClient = httpClient,- )- }+ val root: RootComponent = SimpleRootComponent(httpClient = httpClient)application {val windowState = rememberWindowState()- LifecycleController(lifecycle, windowState)Window(onCloseRequest = ::exitApplication,diff --git a/ui/gradle/libs.versions.toml b/ui/gradle/libs.versions.tomlindex f291492f3ab..f9bf18970a1 100644--- a/ui/gradle/libs.versions.toml+++ b/ui/gradle/libs.versions.toml@@ -17,14 +17,11 @@ androidx-adaptive = "1.3.0-rc01"androidx-lifecycle = "2.11.0"androidx-navigation3 = "1.1.2"compose = "1.12.1"-decompose = "3.5.0"-essenty = "2.6.0"kotlin = "2.4.20"kotlinx-coroutines = "1.11.0"kotlinx-serialization = "1.11.0"ktor = "3.6.0"material3 = "1.12.0-alpha03"-mvikotlin = "4.4.0"nlopez-compose = "0.6.2"oshai-logging = "8.0.4"squareup-okio = "3.18.2"@@ -51,9 +48,6 @@ compose-runtime = { module = "org.jetbrains.compose.runtime:runtime", version.recompose-ui = { module = "org.jetbrains.compose.ui:ui", version.ref = "compose" }compose-uiTest = { module = "org.jetbrains.compose.ui:ui-test", version.ref = "compose" }compose-uiToolingPreview = { module = "org.jetbrains.compose.ui:ui-tooling-preview", version.ref = "compose" }-decompose-decompose = { module = "com.arkivanov.decompose:decompose", version.ref = "decompose" }-decompose-extensions-compose = { module = "com.arkivanov.decompose:extensions-compose", version.ref = "decompose" }-essenty-lifecycle = { module = "com.arkivanov.essenty:lifecycle", version.ref = "essenty" }kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }kotlinx-coroutines-swing = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-swing", version.ref = "kotlinx-coroutines" }kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }@@ -70,10 +64,6 @@ ktor-client-serialization-json = { module = "io.ktor:ktor-serialization-kotlinx-ktor-server-cio = { module = "io.ktor:ktor-server-cio" }ktor-server-core = { module = "io.ktor:ktor-server-core" }ktor-server-htmlBuilder = { module = "io.ktor:ktor-server-html-builder" }-mvikotlin-extensions-coroutines = { module = "com.arkivanov.mvikotlin:mvikotlin-extensions-coroutines", version.ref = "mvikotlin" }-mvikotlin-logging = { module = "com.arkivanov.mvikotlin:mvikotlin-logging", version.ref = "mvikotlin" }-mvikotlin-main = { module = "com.arkivanov.mvikotlin:mvikotlin-main", version.ref = "mvikotlin" }-mvikotlin-mvikotlin = { module = "com.arkivanov.mvikotlin:mvikotlin", version.ref = "mvikotlin" }nlopez-compose-ktlintrules = { module = "io.nlopez.compose.rules:ktlint", version.ref = "nlopez-compose" }oshai-logging = { module = "io.github.oshai:kotlin-logging", version.ref = "oshai-logging" }squareup-okio = { module = "com.squareup.okio:okio", version.ref = "squareup-okio" }diff --git a/ui/shared/build.gradle.kts b/ui/shared/build.gradle.ktsindex 6ab3255f623..e93ee36ce44 100644--- a/ui/shared/build.gradle.kts+++ b/ui/shared/build.gradle.kts@@ -55,13 +55,6 @@ kotlin {implementation(libs.kotlinx.serialization.json)implementation(libs.kotlinx.coroutines.core)- implementation(libs.decompose.decompose)- implementation(libs.essenty.lifecycle)- implementation(libs.decompose.extensions.compose)- implementation(libs.mvikotlin.extensions.coroutines)- implementation(libs.mvikotlin.mvikotlin)- implementation(libs.mvikotlin.main)-api(project.dependencies.platform(libs.ktor.bom))api(libs.ktor.client.core)implementation(libs.ktor.client.auth)diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/AuthenticationComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/AuthenticationComponent.ktindex 5006ccc929c..9d14dae0029 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/AuthenticationComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/AuthenticationComponent.kt@@ -17,79 +17,49 @@package org.apache.solr.ui.components.auth-import com.arkivanov.decompose.router.slot.ChildSlot-import com.arkivanov.decompose.value.Value-import kotlinx.coroutines.flow.StateFlow-import kotlinx.serialization.Serializable-import org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.domain.AuthOption-import org.jetbrains.compose.resources.StringResource+import org.apache.solr.ui.components.auth.domain.BasicAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.CreateOAuthAuthorizationUseCase+import org.apache.solr.ui.components.auth.domain.OAuthAuthenticateUseCase+import org.apache.solr.ui.components.auth.repository.BasicAuthRepository+import org.apache.solr.ui.components.auth.repository.OAuthRepository+import org.apache.solr.ui.components.auth.viewmodel.AuthenticationViewModel/*** The authentication component takes care of the authentication processes. This typically includes* user authentication with credentials, tokens or certificates.** Note that Solr does not support multiple authentication methods of the same type with the- * MultiAuthPlugin, so there will be always up to one instance per method, hence the component-based- * child slots for each method.+ * MultiAuthPlugin, so there will be always up to one authentication option per method.*/interface AuthenticationComponent {/**- * Component state flow.+ * Dependencies provided by the application.*/- val model: StateFlow<Model>+ val basicAuthRepository: BasicAuthRepository/**- * A child slot that holds the [BasicAuthComponent] for user authentication with credentials- * (basic auth) if it is supported.+ * Dependencies provided by the application.*/- val basicAuthSlot: Value<ChildSlot<BasicAuthConfiguration, BasicAuthComponent>>+ val oAuthRepository: OAuthRepository/**- * A child slot that holds the [OAuthComponent] for user authentication with OAuth- * (bearer token) if it is supported.+ * Use case responsible for authenticating with credentials (basic auth).*/- val oAuthSlot: Value<ChildSlot<OAuthConfiguration, OAuthComponent>>-- @Serializable- data class BasicAuthConfiguration(val method: AuthMethod.BasicAuthMethod = AuthMethod.BasicAuthMethod())-- @Serializable- data class OAuthConfiguration(val method: AuthMethod.OAuthMethod)+ val basicAuthenticateUseCase: BasicAuthenticateUseCase/**- * Aborts the authentication attempt.+ * Use case responsible for creating OAuth authorization requests.*/- fun onAbort()+ val createOAuthAuthorizationUseCase: CreateOAuthAuthorizationUseCase/**- * Model data class that represents the component state.- *- * @property url URL of the Solr instance the user is trying to connect.- * @property methods List of authentication methods to render.- * @property isAuthenticating Whether a connection is currently established.- * @property error The error that may have occurred.+ * Use case responsible for authenticating with OAuth.*/- data class Model(- val url: String = "",- val methods: List<AuthMethod> = emptyList(),- val isAuthenticating: Boolean = false,- val error: StringResource? = null,- )-- sealed interface Output {+ val oAuthAuthenticateUseCase: OAuthAuthenticateUseCase- /**- * Emitted when the user successfully authenticated against the Solr instance.- *- * @property option The final authentication option that succeeded.- */- data class OnAuthenticated(val option: AuthOption) : Output-- /**- * Emitted when the user aborts the authentication flow.- */- data object OnAbort : Output- }+ /**+ * Factory method to create a [AuthenticationViewModel] instance.+ */+ fun createAuthenticationViewModel(): AuthenticationViewModel}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/BasicAuthComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/BasicAuthComponent.ktdeleted file mode 100644index c243ad8ccbb..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/BasicAuthComponent.kt+++ /dev/null@@ -1,98 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth--import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.domain.AuthMethod--/**- * Component interface that is handling basic authentication with username and password.- */-interface BasicAuthComponent {-- val model: StateFlow<Model>-- /**- * Function that handles username changes.- */- fun onChangeUsername(username: String)-- /**- * Function that handles password changes.- */- fun onChangePassword(password: String)-- /**- * Tries to authenticate the user with the given username and password.- */- fun onAuthenticate()-- /**- * Data class model that represents the [BasicAuthComponent] state.- *- * @property realm The basic auth realm the user is supposed to provide the credentials for.- * @property username The username that is currently typed in.- * @property password The password that is currently typed in.- * @property hasError Whether the current input has an error. This is a simplified variant that- * does not distinguish input fields.- */- data class Model(- val realm: String? = null,- val username: String = "",- val password: String = "",- val hasError: Boolean = false,- )-- sealed interface Output {-- /**- * Output that is emitted when a connection process is started.- */- data object Authenticating : Output-- /**- * Output that is emitted when the user successfully connected to the server- * with the credentials.- *- * The username and password are passed to the parent to configure a client- * with basic auth and pass it to other instances for further use.- *- * @property method The method that was used for authentication.- * @property username The username that was used for authentication.- * @property password The password that was used for authentication.- */- data class Authenticated(- val method: AuthMethod.BasicAuthMethod,- val username: String,- val password: String,- ) : Output-- /**- * Output that is emitted when an authentication error occurs, for example, in case- * of invalid credentials.- *- * @property error The error that was thrown during a connection establishment.- */- data class AuthenticationFailed(val error: Throwable) : Output-- /**- * Output that allows resetting any error reported via [AuthenticationFailed].- */- data object ErrorReset : Output- }-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/OAuthComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/OAuthComponent.ktdeleted file mode 100644index 722d5156c2d..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/OAuthComponent.kt+++ /dev/null@@ -1,82 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth--import kotlinx.coroutines.flow.Flow-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.auth.store.OAuthStore.Label-import org.apache.solr.ui.domain.AuthMethod--/**- * Component interface that is handling basic authentication with username and password.- */-interface OAuthComponent {-- val model: StateFlow<Model>-- val labels: Flow<Label>-- /**- * Tries to authenticate the user with the given authorization URL.- */- fun onAuthenticate()-- /**- * Data class model that represents the [OAuthComponent] state.- *- * @property realm The OAuth realm the user is supposed to authenticate against.- * @property hasError Whether the current input has an error.- */- data class Model(- val realm: String? = null,- val hasError: Boolean = false,- )-- sealed interface Output {-- /**- * Output that is emitted when a connection process is started.- */- data object Authenticating : Output-- /**- * Output that is emitted when the user successfully connected to the server- * with the oauth method.- *- * @property method The method that was used for authentication.- */- data class Authenticated(- val accessToken: String,- val method: AuthMethod.OAuthMethod,- val refreshToken: String? = null,- ) : Output-- /**- * Output that is emitted when an authentication error occurs, for example, in case- * of timeout or invalid configuration.- *- * @property error The error that was thrown during a connection establishment.- */- data class AuthenticationFailed(val error: Throwable) : Output-- /**- * Output that allows resetting any error reported via [AuthenticationFailed].- */- data object ErrorReset : Output- }-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/HttpBasicAuthStoreClient.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/data/HttpBasicAuthRepository.ktsimilarity index 87%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/HttpBasicAuthStoreClient.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/data/HttpBasicAuthRepository.ktindex 6b7183d69f6..8b8a189bf76 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/HttpBasicAuthStoreClient.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/data/HttpBasicAuthRepository.kt@@ -15,24 +15,24 @@* limitations under the License.*/-package org.apache.solr.ui.components.auth.integration+package org.apache.solr.ui.components.auth.dataimport io.ktor.client.HttpClientimport io.ktor.client.plugins.timeoutimport io.ktor.client.request.basicAuthimport io.ktor.client.request.getimport io.ktor.http.HttpStatusCode-import org.apache.solr.ui.components.auth.store.BasicAuthStoreProvider+import org.apache.solr.ui.components.auth.repository.BasicAuthRepositoryimport org.apache.solr.ui.errors.UnauthorizedExceptionimport org.apache.solr.ui.errors.UnknownResponseException/**- * HTTP client implementation of the basic auth store.+ * HTTP repository implementation for basic authentication.** @property httpClient A preconfigured HTTP client that has the base URL of a Solr instance* already set.*/-class HttpBasicAuthStoreClient(private val httpClient: HttpClient) : BasicAuthStoreProvider.Client {+class HttpBasicAuthRepository(private val httpClient: HttpClient) : BasicAuthRepository {override suspend fun authenticate(username: String,password: String,diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.ktsimilarity index 80%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.ktindex 3ad4b909293..6b4229a3fb4 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.kt@@ -15,20 +15,20 @@* limitations under the License.*/-package org.apache.solr.ui.components.auth.integration+package org.apache.solr.ui.components.auth.dataimport io.ktor.client.HttpClientimport io.ktor.client.plugins.auth.providers.BearerTokens-import org.apache.solr.ui.components.auth.store.OAuthStoreProvider+import org.apache.solr.ui.components.auth.repository.OAuthRepositoryimport org.apache.solr.ui.domain.OAuthData/**- * OAuth store implementation that uses a server instance for handling callbacks.+ * OAuth repository implementation that uses a server instance for handling callbacks.** @property httpClient A preconfigured HTTP client that has the base URL of a Solr instance* already set.*/-expect class PlatformOAuthStoreClient(httpClient: HttpClient) : OAuthStoreProvider.Client {+expect class PlatformOAuthRepository(httpClient: HttpClient) : OAuthRepository {override suspend fun authenticate(state: String,verifier: String,diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/AuthEvents.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/AuthEvents.ktnew file mode 100644index 00000000000..4cc8739227d--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/AuthEvents.kt@@ -0,0 +1,110 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.domain++import io.ktor.http.Url+import org.apache.solr.ui.domain.AuthMethod+import org.apache.solr.ui.domain.AuthOption++/**+ * Events emitted by the authentication screen that are meant to be handled by the parent.+ */+sealed interface AuthenticationEvent {++ /**+ * Emitted when the user successfully authenticated against the Solr instance.+ *+ * @property option The final authentication option that succeeded.+ */+ data class Authenticated(val option: AuthOption) : AuthenticationEvent++ /**+ * Emitted when the user aborts the authentication flow.+ */+ data object Aborted : AuthenticationEvent+}++/**+ * Events emitted by the basic authentication state holder.+ */+sealed interface BasicAuthEvent {++ /**+ * Emitted when a connection process is started.+ */+ data object AuthenticationStarted : BasicAuthEvent++ /**+ * Emitted when the user successfully connected to the server with the credentials.+ *+ * @property method The method that was used for authentication.+ * @property username The username that was used for authentication.+ * @property password The password that was used for authentication.+ */+ data class Authenticated(+ val method: AuthMethod.BasicAuthMethod,+ val username: String,+ val password: String,+ ) : BasicAuthEvent++ /**+ * Emitted when an authentication error occurs, for example, in case of invalid credentials.+ *+ * @property error The error that occurred during the connection establishment.+ */+ data class AuthenticationFailed(val error: Throwable) : BasicAuthEvent++ /**+ * Emitted when an error reported via [AuthenticationFailed] is reset.+ */+ data object ErrorReset : BasicAuthEvent+}++/**+ * Events emitted by the OAuth state holder.+ */+sealed interface OAuthEvent {++ /**+ * Emitted when a connection process is started.+ *+ * @property url The URL of the identity provider to open for authentication.+ */+ data class AuthenticationStarted(val url: Url) : OAuthEvent++ /**+ * Emitted when the user successfully connected to the server with the OAuth method.+ *+ * @property method The method that was used for authentication.+ * @property accessToken The access token that was issued.+ * @property refreshToken The refresh token that was issued, if any.+ */+ data class Authenticated(+ val method: AuthMethod.OAuthMethod,+ val accessToken: String,+ val refreshToken: String? = null,+ ) : OAuthEvent++ /**+ * Emitted when an authentication error occurs, for example, in case of timeout or invalid+ * configuration.+ *+ * @property error The error that occurred during the connection establishment.+ */+ data class AuthenticationFailed(val error: Throwable) : OAuthEvent+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/AuthenticationErrors.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/AuthenticationErrors.ktnew file mode 100644index 00000000000..9d48c77aaf0--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/AuthenticationErrors.kt@@ -0,0 +1,42 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.domain++import kotlin.coroutines.cancellation.CancellationException+import org.apache.solr.ui.errors.InvalidCredentialsException+import org.apache.solr.ui.errors.UnauthorizedException+import org.apache.solr.ui.utils.parseError++/**+ * Runs the authentication [block] and normalizes its errors.+ *+ * An unauthorized response is mapped to an [InvalidCredentialsException], as it means that the+ * credentials are invalid. Errors that are thrown are platform-specific and are parsed with+ * [parseError]. Cancellations are rethrown.+ */+internal inline fun <T> authenticationCatching(block: () -> Result<T>): Result<T> = try {+ val result = block()+ when (result.exceptionOrNull()) {+ is UnauthorizedException -> Result.failure(InvalidCredentialsException())+ else -> result+ }+} catch (e: CancellationException) {+ throw e+} catch (e: Throwable) {+ Result.failure(parseError(e))+}diff --git a/ui/desktopApp/src/main/kotlin/org/apache/solr/ui/Utils.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/BasicAuthenticateUseCase.ktsimilarity index 55%rename from ui/desktopApp/src/main/kotlin/org/apache/solr/ui/Utils.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/BasicAuthenticateUseCase.ktindex 5e8d1193f32..d8c391eeba5 100644--- a/ui/desktopApp/src/main/kotlin/org/apache/solr/ui/Utils.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/BasicAuthenticateUseCase.kt@@ -15,31 +15,21 @@* limitations under the License.*/-package org.apache.solr.ui--import javax.swing.SwingUtilities+package org.apache.solr.ui.components.auth.domain/**- * Ensures that a code [block] is executed on the UI thread.+ * Use case for authenticating with a username and password (basic authentication).*/-internal fun <T> runOnUiThread(block: () -> T): T {- if (SwingUtilities.isEventDispatchThread()) {- return block()- }-- var error: Throwable? = null- var result: T? = null-- SwingUtilities.invokeAndWait {- try {- result = block()- } catch (e: Throwable) {- error = e- }- }-- error?.also { throw it }+interface BasicAuthenticateUseCase {- @Suppress("UNCHECKED_CAST")- return result as T+ /**+ * Authenticates the user with the given credentials.+ *+ * @param username The username to use.+ * @param password The password to use.+ * @return Success if the credentials authenticated the user. Otherwise, a failure with the+ * error that occurred, where invalid credentials are reported as+ * [org.apache.solr.ui.errors.InvalidCredentialsException].+ */+ suspend operator fun invoke(username: String, password: String): Result<Unit>}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/Mappers.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/DefaultBasicAuthenticateUseCase.ktsimilarity index 64%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/Mappers.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/DefaultBasicAuthenticateUseCase.ktindex 3a8f89a7264..c3476a4092e 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/Mappers.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/DefaultBasicAuthenticateUseCase.kt@@ -15,15 +15,14 @@* limitations under the License.*/-package org.apache.solr.ui.components.environment.integration+package org.apache.solr.ui.components.auth.domain-import org.apache.solr.ui.components.environment.EnvironmentComponent-import org.apache.solr.ui.components.environment.store.EnvironmentStore+import org.apache.solr.ui.components.auth.repository.BasicAuthRepository-internal val environmentStateToModel: (EnvironmentStore.State) -> EnvironmentComponent.Model = {- EnvironmentComponent.Model(- versions = it.lucene,- jvm = it.jvm,- javaProperties = it.javaProperties,- )+internal class DefaultBasicAuthenticateUseCase(+ private val repository: BasicAuthRepository,+) : BasicAuthenticateUseCase {++ override suspend fun invoke(username: String, password: String): Result<Unit> =+ authenticationCatching { repository.authenticate(username, password) }}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/DefaultOAuthUseCases.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/DefaultOAuthUseCases.ktnew file mode 100644index 00000000000..064ef7b567d--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/DefaultOAuthUseCases.kt@@ -0,0 +1,64 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.domain++import io.ktor.client.plugins.auth.providers.BearerTokens+import io.ktor.http.ParametersBuilder+import io.ktor.http.URLBuilder+import org.apache.solr.ui.components.auth.generateCodeChallenge+import org.apache.solr.ui.components.auth.generateCodeVerifier+import org.apache.solr.ui.components.auth.generateOAuthState+import org.apache.solr.ui.components.auth.getRedirectUri+import org.apache.solr.ui.components.auth.repository.OAuthRepository+import org.apache.solr.ui.domain.AuthMethod++internal class DefaultCreateOAuthAuthorizationUseCase : CreateOAuthAuthorizationUseCase {++ override fun invoke(method: AuthMethod.OAuthMethod): OAuthAuthorization {+ val verifier = generateCodeVerifier()+ val challenge = generateCodeChallenge(verifier)+ val state = generateOAuthState()+ val url = URLBuilder(method.data.authorizationEndpoint)+ .apply {+ encodedParameters = ParametersBuilder().apply {+ set("client_id", method.data.clientId)+ set("scope", method.data.scope)+ set("redirect_uri", getRedirectUri())+ set("response_type", "code")+ set("code_challenge_method", "S256")+ set("code_challenge", challenge)+ set("state", state)+ }+ }+ .build()++ return OAuthAuthorization(url = url, state = state, verifier = verifier)+ }+}++internal class DefaultOAuthAuthenticateUseCase(+ private val repository: OAuthRepository,+) : OAuthAuthenticateUseCase {++ override suspend fun invoke(+ authorization: OAuthAuthorization,+ method: AuthMethod.OAuthMethod,+ ): Result<BearerTokens> = authenticationCatching {+ repository.authenticate(authorization.state, authorization.verifier, method.data)+ }+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/OAuthUseCases.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/OAuthUseCases.ktnew file mode 100644index 00000000000..8c5bd374600--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/domain/OAuthUseCases.kt@@ -0,0 +1,69 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.domain++import io.ktor.client.plugins.auth.providers.BearerTokens+import io.ktor.http.Url+import org.apache.solr.ui.domain.AuthMethod++/**+ * An OAuth authorization request that uses the authorization code flow with PKCE.+ *+ * @property url The URL of the identity provider the user has to open for authorizing the app.+ * @property state The state value used in the authorization flow.+ * @property verifier The code verifier used in the authorization flow.+ */+data class OAuthAuthorization(+ val url: Url,+ val state: String,+ val verifier: String,+)++/**+ * Use case for preparing an OAuth authorization request.+ */+interface CreateOAuthAuthorizationUseCase {++ /**+ * Creates a new authorization request for the given [method].+ *+ * @param method The OAuth method to create the authorization request for.+ */+ operator fun invoke(method: AuthMethod.OAuthMethod): OAuthAuthorization+}++/**+ * Use case for authenticating with OAuth.+ */+interface OAuthAuthenticateUseCase {++ /**+ * Waits for the user to authorize the [authorization] request and exchanges the result for+ * tokens.+ *+ * @param authorization The authorization request the user is expected to authorize.+ * @param method The OAuth method the authorization request was created for.+ * @return The tokens if the user has successfully authenticated. Otherwise, a failure with the+ * error that occurred, where invalid credentials are reported as+ * [org.apache.solr.ui.errors.InvalidCredentialsException].+ */+ suspend operator fun invoke(+ authorization: OAuthAuthorization,+ method: AuthMethod.OAuthMethod,+ ): Result<BearerTokens>+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultAuthenticationComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultAuthenticationComponent.ktindex 5c2e5c0a1c2..025680ee09d 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultAuthenticationComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultAuthenticationComponent.kt@@ -17,166 +17,66 @@package org.apache.solr.ui.components.auth.integration-import com.arkivanov.decompose.router.slot.ChildSlot-import com.arkivanov.decompose.router.slot.SlotNavigation-import com.arkivanov.decompose.router.slot.activate-import com.arkivanov.decompose.router.slot.childSlot-import com.arkivanov.decompose.value.Value-import com.arkivanov.mvikotlin.core.instancekeeper.getStore-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.stateFlowimport io.ktor.client.HttpClientimport io.ktor.http.Url-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.SupervisorJobimport org.apache.solr.ui.components.auth.AuthenticationComponent-import org.apache.solr.ui.components.auth.AuthenticationComponent.BasicAuthConfiguration-import org.apache.solr.ui.components.auth.AuthenticationComponent.OAuthConfiguration-import org.apache.solr.ui.components.auth.AuthenticationComponent.Output-import org.apache.solr.ui.components.auth.AuthenticationComponent.Output.OnAuthenticated-import org.apache.solr.ui.components.auth.BasicAuthComponent-import org.apache.solr.ui.components.auth.OAuthComponent-import org.apache.solr.ui.components.auth.store.AuthenticationStore.Intent-import org.apache.solr.ui.components.auth.store.AuthenticationStoreProvider+import org.apache.solr.ui.components.auth.data.HttpBasicAuthRepository+import org.apache.solr.ui.components.auth.data.PlatformOAuthRepository+import org.apache.solr.ui.components.auth.domain.BasicAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.CreateOAuthAuthorizationUseCase+import org.apache.solr.ui.components.auth.domain.DefaultBasicAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.DefaultCreateOAuthAuthorizationUseCase+import org.apache.solr.ui.components.auth.domain.DefaultOAuthAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.OAuthAuthenticateUseCase+import org.apache.solr.ui.components.auth.repository.BasicAuthRepository+import org.apache.solr.ui.components.auth.repository.OAuthRepository+import org.apache.solr.ui.components.auth.viewmodel.AuthenticationViewModelimport org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.domain.AuthOption-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.utils.coroutineScope-import org.apache.solr.ui.utils.map+import org.apache.solr.ui.utils.AppDispatchers+import org.apache.solr.ui.utils.platformDispatchers/*** Default implementation of the [AuthenticationComponent].*- * @param componentContext Application component context.- * @param storeFactory Store factory to pass to the store provider.* @param httpClient HTTP client to use for API interactions. The client has to be pre-configured* with a base URL pointing to a Solr instance.+ * @param url The URL of the Solr instance the user is authenticating against.* @param methods A list of authentication methods that are supported by the Solr instance the* [httpClient] is pointing to.- * @property output Output handler that is used to send outputs from this component.*/class DefaultAuthenticationComponent(- componentContext: AppComponentContext,- storeFactory: StoreFactory,httpClient: HttpClient,private val url: Url,- methods: List<AuthMethod>,- private val output: (Output) -> Unit,-) : AuthenticationComponent,- AppComponentContext by componentContext {+ private val methods: List<AuthMethod>,+ private val dispatchers: AppDispatchers = platformDispatchers(),+) : AuthenticationComponent {- private val mainScope = coroutineScope(SupervisorJob() + mainContext)- private val ioScope = coroutineScope(SupervisorJob() + ioContext)-- private val store = instanceKeeper.getStore {- AuthenticationStoreProvider(- storeFactory = storeFactory,- mainContext = mainScope.coroutineContext,- ioContext = ioScope.coroutineContext,- url = url,- methods = methods,- ).provide()+ override val basicAuthRepository: BasicAuthRepository by lazy {+ HttpBasicAuthRepository(httpClient)}- private val basicAuthNavigation = SlotNavigation<BasicAuthConfiguration>()- private val oauthNavigation = SlotNavigation<OAuthConfiguration>()-- @OptIn(ExperimentalCoroutinesApi::class)- override val model = store.stateFlow.map(mainScope, authStateToModel)-- override val basicAuthSlot: Value<ChildSlot<BasicAuthConfiguration, BasicAuthComponent>> =- childSlot(- source = basicAuthNavigation,- key = "BasicAuthSlot",- serializer = BasicAuthConfiguration.serializer(),- handleBackButton = true,- ) { config, childComponentContext ->- DefaultBasicAuthComponent(- componentContext = childComponentContext,- storeFactory = storeFactory,- httpClient = httpClient,- method = config.method,- output = ::basicAuthOutput,- )- }-- override val oAuthSlot: Value<ChildSlot<OAuthConfiguration, OAuthComponent>> =- childSlot(- source = oauthNavigation,- key = "OAuthChildSlot",- serializer = OAuthConfiguration.serializer(),- handleBackButton = true,- ) { config, childComponentContext ->- DefaultOAuthComponent(- componentContext = childComponentContext,- storeFactory = storeFactory,- httpClient = httpClient,- method = config.method,- output = ::oAuthOutput,- )- }-- init {- methods.forEach { method ->- when (method) {- is AuthMethod.BasicAuthMethod ->- basicAuthNavigation.activate(configuration = BasicAuthConfiguration(method))-- is AuthMethod.OAuthMethod -> oauthNavigation.activate(- configuration = OAuthConfiguration(method),- )-- is AuthMethod.Unknown -> {} // TODO Handle unknown auth methods- }- }+ override val oAuthRepository: OAuthRepository by lazy {+ PlatformOAuthRepository(httpClient)}- /**- * Output handler function that handles the outputs from [BasicAuthComponent]s.- *- * @param output The output of the component to handle- */- private fun basicAuthOutput(output: BasicAuthComponent.Output): Unit = when (output) {- is BasicAuthComponent.Output.Authenticated -> output(- OnAuthenticated(- option = AuthOption.BasicAuthOption(- url = url,- username = output.username,- password = output.password,- realm = output.method.realm,- ),- ),- )-- is BasicAuthComponent.Output.Authenticating -> store.accept(Intent.StartAuthenticating)-- is BasicAuthComponent.Output.AuthenticationFailed -> store.accept(- intent = Intent.FailAuthentication(output.error),- )-- is BasicAuthComponent.Output.ErrorReset -> store.accept(intent = Intent.ResetError)+ override val basicAuthenticateUseCase: BasicAuthenticateUseCase by lazy {+ DefaultBasicAuthenticateUseCase(basicAuthRepository)}- private fun oAuthOutput(output: OAuthComponent.Output): Unit = when (output) {- is OAuthComponent.Output.Authenticating -> store.accept(Intent.StartAuthenticating)-- is OAuthComponent.Output.Authenticated -> output(- OnAuthenticated(- option = AuthOption.OAuthOption(- url = url,- accessToken = output.accessToken,- refreshToken = output.refreshToken,- realm = output.method.realm,- ),- ),- )-- is OAuthComponent.Output.AuthenticationFailed -> store.accept(- intent = Intent.FailAuthentication(output.error),- )+ override val createOAuthAuthorizationUseCase: CreateOAuthAuthorizationUseCase by lazy {+ DefaultCreateOAuthAuthorizationUseCase()+ }- is OAuthComponent.Output.ErrorReset -> store.accept(intent = Intent.ResetError)+ override val oAuthAuthenticateUseCase: OAuthAuthenticateUseCase by lazy {+ DefaultOAuthAuthenticateUseCase(oAuthRepository)}- override fun onAbort() = output(Output.OnAbort)+ override fun createAuthenticationViewModel(): AuthenticationViewModel = AuthenticationViewModel(+ url = url,+ methods = methods,+ basicAuthenticateUseCase = basicAuthenticateUseCase,+ createOAuthAuthorizationUseCase = createOAuthAuthorizationUseCase,+ oAuthAuthenticateUseCase = oAuthAuthenticateUseCase,+ dispatchers = dispatchers,+ )}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultBasicAuthComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultBasicAuthComponent.ktdeleted file mode 100644index 5cd934c9d74..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultBasicAuthComponent.kt+++ /dev/null@@ -1,91 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.integration--import com.arkivanov.mvikotlin.core.instancekeeper.getStore-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.labels-import com.arkivanov.mvikotlin.extensions.coroutines.stateFlow-import io.ktor.client.HttpClient-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.flow.launchIn-import kotlinx.coroutines.flow.onEach-import org.apache.solr.ui.components.auth.BasicAuthComponent-import org.apache.solr.ui.components.auth.BasicAuthComponent.Output-import org.apache.solr.ui.components.auth.store.BasicAuthStore-import org.apache.solr.ui.components.auth.store.BasicAuthStore.Intent-import org.apache.solr.ui.components.auth.store.BasicAuthStoreProvider-import org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.utils.coroutineScope-import org.apache.solr.ui.utils.map--class DefaultBasicAuthComponent(- componentContext: AppComponentContext,- storeFactory: StoreFactory,- httpClient: HttpClient,- method: AuthMethod.BasicAuthMethod,- private val output: (Output) -> Unit,-) : BasicAuthComponent,- AppComponentContext by componentContext {-- private val mainScope = coroutineScope(SupervisorJob() + mainContext)- private val ioScope = coroutineScope(SupervisorJob() + ioContext)-- private val store = instanceKeeper.getStore {- BasicAuthStoreProvider(- storeFactory = storeFactory,- client = HttpBasicAuthStoreClient(httpClient),- mainContext = mainScope.coroutineContext,- ioContext = ioScope.coroutineContext,- method = method,- ).provide()- }-- @OptIn(ExperimentalCoroutinesApi::class)- override val model = store.stateFlow.map(mainScope, stateToBasicAuthModel)-- init {- store.labels.onEach { label ->- when (label) {- is BasicAuthStore.Label.Authenticated -> output(- Output.Authenticated(- method = label.method,- username = label.username,- password = label.password,- ),- )-- is BasicAuthStore.Label.AuthenticationFailed -> output(- Output.AuthenticationFailed(error = label.error),- )-- is BasicAuthStore.Label.AuthenticationStarted -> output(Output.Authenticating)-- is BasicAuthStore.Label.ErrorReset -> output(Output.ErrorReset)- }- }.launchIn(mainScope)- }-- override fun onChangeUsername(username: String) = store.accept(Intent.UpdateUsername(username))-- override fun onChangePassword(password: String) = store.accept(Intent.UpdatePassword(password))-- override fun onAuthenticate() = store.accept(Intent.Authenticate)-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultOAuthComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultOAuthComponent.ktdeleted file mode 100644index d35806303cb..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/DefaultOAuthComponent.kt+++ /dev/null@@ -1,92 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.integration--import com.arkivanov.mvikotlin.core.instancekeeper.getStore-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.labels-import com.arkivanov.mvikotlin.extensions.coroutines.stateFlow-import io.ktor.client.HttpClient-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.flow.Flow-import kotlinx.coroutines.flow.launchIn-import kotlinx.coroutines.flow.onEach-import org.apache.solr.ui.components.auth.OAuthComponent-import org.apache.solr.ui.components.auth.OAuthComponent.Output-import org.apache.solr.ui.components.auth.store.OAuthStore-import org.apache.solr.ui.components.auth.store.OAuthStore.Intent-import org.apache.solr.ui.components.auth.store.OAuthStoreProvider-import org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.utils.coroutineScope-import org.apache.solr.ui.utils.map--class DefaultOAuthComponent(- componentContext: AppComponentContext,- storeFactory: StoreFactory,- httpClient: HttpClient,- method: AuthMethod.OAuthMethod,- private val output: (Output) -> Unit,-) : OAuthComponent,- AppComponentContext by componentContext {-- private val mainScope = coroutineScope(SupervisorJob() + mainContext)- private val ioScope = coroutineScope(SupervisorJob() + ioContext)-- private val store = instanceKeeper.getStore {- OAuthStoreProvider(- storeFactory = storeFactory,- client = PlatformOAuthStoreClient(httpClient),- mainContext = mainScope.coroutineContext,- ioContext = ioScope.coroutineContext,- method = method,- ).provide()- }-- @OptIn(ExperimentalCoroutinesApi::class)- override val model = store.stateFlow.map(mainScope, stateToOAuthModel)-- override val labels: Flow<OAuthStore.Label> = store.labels-- init {- store.labels.onEach { label ->- when (label) {- is OAuthStore.Label.Authenticated -> output(- Output.Authenticated(- method = label.method,- accessToken = label.accessToken,- refreshToken = label.refreshToken,- ),- )-- is OAuthStore.Label.AuthenticationFailed -> output(- Output.AuthenticationFailed(error = label.error),- )-- is OAuthStore.Label.AuthenticationStarted -> {- output(Output.Authenticating)- }-- is OAuthStore.Label.ErrorReset -> output(Output.ErrorReset)- }- }.launchIn(mainScope)- }-- override fun onAuthenticate() = store.accept(Intent.Authenticate)-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/Mappers.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/Mappers.ktdeleted file mode 100644index dbc2b513142..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/integration/Mappers.kt+++ /dev/null@@ -1,59 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.integration--import org.apache.solr.ui.components.auth.AuthenticationComponent-import org.apache.solr.ui.components.auth.BasicAuthComponent-import org.apache.solr.ui.components.auth.OAuthComponent-import org.apache.solr.ui.components.auth.store.AuthenticationStore-import org.apache.solr.ui.components.auth.store.BasicAuthStore-import org.apache.solr.ui.components.auth.store.OAuthStore-import org.apache.solr.ui.errors.InvalidCredentialsException-import org.apache.solr.ui.shared.generated.resources.Res-import org.apache.solr.ui.shared.generated.resources.error_invalid_credentials-import org.apache.solr.ui.shared.generated.resources.error_unknown--internal val authStateToModel: (AuthenticationStore.State) -> AuthenticationComponent.Model = {- AuthenticationComponent.Model(- url = it.url.toString(),- methods = it.methods,- isAuthenticating = it.isAuthenticating,- error = it.error?.let { error ->- when (error) {- is InvalidCredentialsException -> Res.string.error_invalid_credentials- else -> Res.string.error_unknown- }- },- )-}--internal val stateToBasicAuthModel: (BasicAuthStore.State) -> BasicAuthComponent.Model = {- BasicAuthComponent.Model(- realm = it.method.realm,- username = it.username,- password = it.password,- hasError = it.error != null,- )-}--internal val stateToOAuthModel: (OAuthStore.State) -> OAuthComponent.Model = {- OAuthComponent.Model(- realm = it.method.realm,- hasError = it.error != null,- )-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/repository/BasicAuthRepository.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/repository/BasicAuthRepository.ktnew file mode 100644index 00000000000..f88eb74c8b6--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/repository/BasicAuthRepository.kt@@ -0,0 +1,33 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.repository++/**+ * Repository interface for authenticating with basic authentication.+ */+interface BasicAuthRepository {++ /**+ * Authenticates the user with the current Solr instance.+ *+ * @param username The username to use.+ * @param password The password to use.+ * @return Returns success results iff the credentials authenticated the user.+ */+ suspend fun authenticate(username: String, password: String): Result<Unit>+}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestOAuthData.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/repository/OAuthRepository.ktsimilarity index 55%rename from ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestOAuthData.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/repository/OAuthRepository.ktindex de32ba074e1..89915980198 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestOAuthData.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/repository/OAuthRepository.kt@@ -15,17 +15,23 @@* limitations under the License.*/-package org.apache.solr.ui.views.auth+package org.apache.solr.ui.components.auth.repository-import io.ktor.http.Url-import org.apache.solr.ui.domain.AuthorizationFlow+import io.ktor.client.plugins.auth.providers.BearerTokensimport org.apache.solr.ui.domain.OAuthData-internal val TestOAuthData = OAuthData(- clientId = "client-id",- authorizationFlow = AuthorizationFlow.CodePKCE,- scope = "openid solr",- redirectUris = listOf(Url("http://127.0.0.1:8088")),- authorizationEndpoint = Url("http://127.0.0.1:3000/auth"),- tokenEndpoint = Url("http://127.0.0.1:3000/token"),-)+/**+ * Repository interface for authenticating with OAuth.+ */+interface OAuthRepository {++ /**+ * Authenticates the user with the current Solr instance.+ *+ * @param state The state value used in the authorization flow with PKCE.+ * @param verifier Code verifier used in the authorization flow with PKCE.+ * @param data The OAuth data to use for the auth flow.+ * @return Returns success results iff the user has successfully authenticated.+ */+ suspend fun authenticate(state: String, verifier: String, data: OAuthData): Result<BearerTokens>+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/AuthenticationStore.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/AuthenticationStore.ktdeleted file mode 100644index 6205beaac4c..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/AuthenticationStore.kt+++ /dev/null@@ -1,65 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.store--import com.arkivanov.mvikotlin.core.store.Store-import io.ktor.http.Url-import org.apache.solr.ui.components.auth.store.AuthenticationStore.Intent-import org.apache.solr.ui.components.auth.store.AuthenticationStore.Label-import org.apache.solr.ui.components.auth.store.AuthenticationStore.State-import org.apache.solr.ui.domain.AuthMethod--interface AuthenticationStore : Store<Intent, State, Label> {-- sealed interface Intent {-- /**- * Intent for indicating that an authentication flow is in process.- */- data object StartAuthenticating : Intent-- /**- * Intent for when an authentication error occurs.- */- data class FailAuthentication(val error: Throwable) : Intent-- /**- * Intent for resetting any errors set via [FailAuthentication].- */- data object ResetError : Intent- }-- sealed interface Label {- // TODO Add labels for the authentication store- }-- /**- * State class that holds the data of the [AuthenticationStore].- *- * @property methods Authentication methods that are configured and can be used- * for authentication.- * @property isAuthenticating Whether an authentication process is currently running.- * @property error The authentication error in case something went wrong.- */- data class State(- val url: Url = Url(""),- val methods: List<AuthMethod> = emptyList(),- val isAuthenticating: Boolean = false,- val error: Throwable? = null,- )-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/AuthenticationStoreProvider.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/AuthenticationStoreProvider.ktdeleted file mode 100644index 7fb9c43cc61..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/AuthenticationStoreProvider.kt+++ /dev/null@@ -1,99 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.store--import com.arkivanov.mvikotlin.core.store.Reducer-import com.arkivanov.mvikotlin.core.store.SimpleBootstrapper-import com.arkivanov.mvikotlin.core.store.Store-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.CoroutineExecutor-import io.ktor.http.Url-import kotlin.coroutines.CoroutineContext-import org.apache.solr.ui.components.auth.store.AuthenticationStore.Intent-import org.apache.solr.ui.components.auth.store.AuthenticationStore.Label-import org.apache.solr.ui.components.auth.store.AuthenticationStore.State-import org.apache.solr.ui.domain.AuthMethod--/**- * The store provider that holds the business logic of the [AuthenticationStore].- *- * The main role of this store provider is to hold and manage a shared authentication state that can- * be used across all authentication options available to the user. This state can contain a shared- * error state, an "authenticating" state and various other data that need to be in sync if multiple- * authentication options are available at the same time.- *- * @property storeFactory The store factory used for creating new stores.- * @property mainContext Coroutine context where main thread tasks are executed.- * @property ioContext Coroutine context for input/output (network transaction).- * @property url The URL of the Solr instance the user is authenticating against.- * @property methods A list of authentications methods that are supported.- */-class AuthenticationStoreProvider(- private val storeFactory: StoreFactory,- private val mainContext: CoroutineContext,- private val ioContext: CoroutineContext,- private val url: Url,- private val methods: List<AuthMethod>,-) {-- fun provide(): AuthenticationStore = object :- AuthenticationStore,- Store<Intent, State, Label> by storeFactory.create(- name = "AuthStore",- initialState = State(url = url, methods = methods),- bootstrapper = SimpleBootstrapper(),- executorFactory = ::ExecutorImpl,- reducer = ReducerImpl,- ) {}-- private sealed interface Message {- /**- * Message that is dispatched when an authentication process is started.- */- data object AuthenticationStarted : Message-- /**- * Message that is dispatched when an authentication error occurred.- */- data class AuthenticationFailed(val error: Throwable) : Message-- /**- * Message that is dispatched when the errors are reset.- */- data object ErrorReset : Message- }-- private inner class ExecutorImpl : CoroutineExecutor<Intent, Unit, State, Message, Label>(mainContext) {- override fun executeIntent(intent: Intent) = when (intent) {- is Intent.StartAuthenticating -> dispatch(Message.AuthenticationStarted)- is Intent.FailAuthentication -> dispatch(Message.AuthenticationFailed(intent.error))- is Intent.ResetError -> dispatch(Message.ErrorReset)- }- }-- /**- * Reducer implementation that consumes [Message]s and updates the store's [State].- */- private object ReducerImpl : Reducer<State, Message> {- override fun State.reduce(msg: Message): State = when (msg) {- is Message.AuthenticationStarted -> copy(isAuthenticating = true)- is Message.AuthenticationFailed -> copy(error = msg.error, isAuthenticating = false)- is Message.ErrorReset -> copy(error = null)- }- }-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/BasicAuthStore.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/BasicAuthStore.ktdeleted file mode 100644index 5a6c3c5236f..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/BasicAuthStore.kt+++ /dev/null@@ -1,91 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.store--import com.arkivanov.mvikotlin.core.store.Store-import org.apache.solr.ui.components.auth.store.BasicAuthStore.Intent-import org.apache.solr.ui.components.auth.store.BasicAuthStore.Label-import org.apache.solr.ui.components.auth.store.BasicAuthStore.State-import org.apache.solr.ui.domain.AuthMethod.BasicAuthMethod--interface BasicAuthStore : Store<Intent, State, Label> {-- /**- * Intent for interacting with the basic auth store.- */- sealed interface Intent {-- /**- * Intent for updating the username value.- */- data class UpdateUsername(val username: String) : Intent-- /**- * Intent for updating the password value.- */- data class UpdatePassword(val password: String) : Intent-- /**- * Intent for initiating an authentication attempt with the current credentials.- */- data object Authenticate : Intent- }-- sealed interface Label {-- /**- * Label that is published when a new authentication process starts.- */- data object AuthenticationStarted : Label-- /**- * Label that is published when the user successfully authenticated to the Solr instance.- *- * @property method The method that was used for authentication.- * @property username The username that was used for authentication.- * @property password The password that was used for authentication.- */- data class Authenticated(- val method: BasicAuthMethod,- val username: String,- val password: String,- ) : Label-- /**- * Label that is published when the authentication process failed with an error.- *- * @property error The error that occurred during the authentication process.- */- data class AuthenticationFailed(val error: Throwable) : Label-- /**- * Label that is published whenever the error state resets.- */- data object ErrorReset : Label- }-- /**- * State class that holds the data of the [BasicAuthStore].- */- data class State(- val method: BasicAuthMethod = BasicAuthMethod(),- val username: String = "",- val password: String = "",- val error: Throwable? = null,- )-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/BasicAuthStoreProvider.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/BasicAuthStoreProvider.ktdeleted file mode 100644index 499c804a673..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/BasicAuthStoreProvider.kt+++ /dev/null@@ -1,145 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.store--import com.arkivanov.mvikotlin.core.store.Reducer-import com.arkivanov.mvikotlin.core.store.SimpleBootstrapper-import com.arkivanov.mvikotlin.core.store.Store-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.CoroutineExecutor-import kotlin.coroutines.CoroutineContext-import kotlinx.coroutines.CoroutineExceptionHandler-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import org.apache.solr.ui.components.auth.store.BasicAuthStore.Intent-import org.apache.solr.ui.components.auth.store.BasicAuthStore.Label-import org.apache.solr.ui.components.auth.store.BasicAuthStore.State-import org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.errors.InvalidCredentialsException-import org.apache.solr.ui.errors.UnauthorizedException-import org.apache.solr.ui.utils.parseError--class BasicAuthStoreProvider(- private val storeFactory: StoreFactory,- private val client: Client,- private val mainContext: CoroutineContext,- private val ioContext: CoroutineContext,- private val method: AuthMethod.BasicAuthMethod,-) {-- fun provide(): BasicAuthStore = object :- BasicAuthStore,- Store<Intent, State, Label> by storeFactory.create(- name = "BasicAuthStore",- initialState = State(method = method),- bootstrapper = SimpleBootstrapper(),- executorFactory = ::ExecutorImpl,- reducer = ReducerImpl,- ) {}-- private sealed interface Message {-- /**- * Message that is dispatched when the username was successfully updated.- */- data class UsernameUpdated(val username: String) : Message-- /**- * Message that is dispatched when the password was successfully updated.- */- data class PasswordUpdated(val password: String) : Message-- /**- * Message that is dispatched when an authentication error occurred.- */- data class AuthenticationFailed(val error: Throwable) : Message- }-- private inner class ExecutorImpl : CoroutineExecutor<Intent, Unit, State, Message, Label>(mainContext) {- override fun executeIntent(intent: Intent) {- when (intent) {- is Intent.Authenticate -> authenticate()-- is Intent.UpdateUsername -> {- state().error?.let { publish(Label.ErrorReset) }- dispatch(Message.UsernameUpdated(intent.username))- }-- is Intent.UpdatePassword -> {- state().error?.let { publish(Label.ErrorReset) }- dispatch(Message.PasswordUpdated(intent.password))- }- }- }-- private fun authenticate(): Unit = with(state()) {- publish(Label.AuthenticationStarted)- scope.launch(- context = CoroutineExceptionHandler { _, throwable ->- // error returned here is platform-specific and needs further parsing- publish(Label.AuthenticationFailed(error = parseError(throwable)))- dispatch(Message.AuthenticationFailed(error = parseError(throwable)))- },- ) {- withContext(ioContext) {- client.authenticate(username, password)- }.onSuccess {- // Authentication succeeded with the given credentials- publish(Label.Authenticated(method, username, password))- }.onFailure { error ->- handleConnectionError(error)- }- }- }-- private fun handleConnectionError(error: Throwable) {- val mappedError: Throwable = when (error) {- // Unauthorized response means that the credentials are invalid- is UnauthorizedException -> InvalidCredentialsException()-- else -> error- }-- dispatch(Message.AuthenticationFailed(mappedError))- publish(Label.AuthenticationFailed(mappedError))- }- }-- /**- * Reducer implementation that consumes [Message]s and updates the store's [State].- */- private object ReducerImpl : Reducer<State, Message> {- override fun State.reduce(msg: Message): State = when (msg) {- is Message.UsernameUpdated -> copy(username = msg.username, error = null)- is Message.PasswordUpdated -> copy(password = msg.password, error = null)- is Message.AuthenticationFailed -> copy(error = msg.error)- }- }-- interface Client {-- /**- * Authenticates the user with the current Solr instance.- *- * @param username The username to use.- * @param password The password to use.- * @return Returns success results ifF the credentials authenticated the user.- */- suspend fun authenticate(username: String, password: String): Result<Unit>- }-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/OAuthStore.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/OAuthStore.ktdeleted file mode 100644index 0e596ab1180..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/OAuthStore.kt+++ /dev/null@@ -1,80 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.store--import com.arkivanov.mvikotlin.core.store.Store-import io.ktor.http.Url-import org.apache.solr.ui.components.auth.store.OAuthStore.Intent-import org.apache.solr.ui.components.auth.store.OAuthStore.Label-import org.apache.solr.ui.components.auth.store.OAuthStore.State-import org.apache.solr.ui.domain.AuthMethod.OAuthMethod--interface OAuthStore : Store<Intent, State, Label> {-- /**- * Intent for interacting with the OAuth store.- */- sealed interface Intent {-- /**- * Intent for initiating an authentication attempt with the current OAuth configuration.- */- data object Authenticate : Intent- }-- sealed interface Label {-- /**- * Label that is published when a new authentication process starts.- *- * @property url The URL of the identity provider to open for authentication.- */- data class AuthenticationStarted(val url: Url) : Label-- /**- * Label that is published when the user successfully authenticated to the Solr instance.- *- * @property method The method that was used for authentication.- */- data class Authenticated(- val method: OAuthMethod,- val accessToken: String,- val refreshToken: String? = null,- ) : Label-- /**- * Label that is published when the authentication process failed with an error.- *- * @property error The error that occurred during the authentication process.- */- data class AuthenticationFailed(val error: Throwable) : Label-- /**- * Label that is published whenever the error state resets.- */- data object ErrorReset : Label- }-- /**- * State class that holds the data of the [OAuthStore].- */- data class State(- val method: OAuthMethod,- val error: Throwable? = null,- )-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/OAuthStoreProvider.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/OAuthStoreProvider.ktdeleted file mode 100644index 752d2141415..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/store/OAuthStoreProvider.kt+++ /dev/null@@ -1,161 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.store--import com.arkivanov.mvikotlin.core.store.Reducer-import com.arkivanov.mvikotlin.core.store.SimpleBootstrapper-import com.arkivanov.mvikotlin.core.store.Store-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.CoroutineExecutor-import io.ktor.client.plugins.auth.providers.BearerTokens-import io.ktor.http.ParametersBuilder-import io.ktor.http.URLBuilder-import io.ktor.utils.io.CancellationException-import kotlin.coroutines.CoroutineContext-import kotlinx.coroutines.Job-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import org.apache.solr.ui.components.auth.generateCodeChallenge-import org.apache.solr.ui.components.auth.generateCodeVerifier-import org.apache.solr.ui.components.auth.generateOAuthState-import org.apache.solr.ui.components.auth.getRedirectUri-import org.apache.solr.ui.components.auth.store.OAuthStore.Intent-import org.apache.solr.ui.components.auth.store.OAuthStore.Label-import org.apache.solr.ui.components.auth.store.OAuthStore.State-import org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.domain.OAuthData-import org.apache.solr.ui.errors.InvalidCredentialsException-import org.apache.solr.ui.errors.UnauthorizedException-import org.apache.solr.ui.utils.parseError--class OAuthStoreProvider(- private val storeFactory: StoreFactory,- private val client: Client,- private val mainContext: CoroutineContext,- private val ioContext: CoroutineContext,- private val method: AuthMethod.OAuthMethod,-) {-- fun provide(): OAuthStore = object :- OAuthStore,- Store<Intent, State, Label> by storeFactory.create(- name = "OAuthStore",- initialState = State(method = method),- bootstrapper = SimpleBootstrapper(),- executorFactory = ::ExecutorImpl,- reducer = ReducerImpl,- ) {}-- private sealed interface Message {- /**- * Message that is dispatched when an authentication error occurred.- */- data class AuthenticationFailed(val error: Throwable) : Message- }-- private inner class ExecutorImpl : CoroutineExecutor<Intent, Unit, State, Message, Label>(mainContext) {-- private var authJob: Job? = null-- override fun executeIntent(intent: Intent) {- when (intent) {- is Intent.Authenticate -> authenticate()- }- }-- private fun authenticate(): Unit = with(state()) {- val verifier = generateCodeVerifier()- val challenge = generateCodeChallenge(verifier)- val oAuthState = generateOAuthState()- val authorizeUrl = URLBuilder(method.data.authorizationEndpoint)- .apply {- encodedParameters = ParametersBuilder().apply {- set("client_id", method.data.clientId)- set("scope", method.data.scope)- set("redirect_uri", getRedirectUri())- set("response_type", "code")- set("code_challenge_method", "S256")- set("code_challenge", challenge)- set("state", oAuthState)- }- }- .build()-- authJob?.cancel()- authJob = scope.launch {- publish(Label.AuthenticationStarted(url = authorizeUrl))- try {- withContext(ioContext) {- client.authenticate(oAuthState, verifier, method.data)- }.onSuccess {- // Authentication succeeded with the given credentials- publish(- Label.Authenticated(- method = method,- accessToken = it.accessToken,- refreshToken = it.refreshToken,- ),- )- }.onFailure { error ->- handleConnectionError(error)- }- } catch (error: CancellationException) {- throw error- } catch (throwable: Throwable) {- val parsed = parseError(throwable)- publish(Label.AuthenticationFailed(error = parsed))- dispatch(Message.AuthenticationFailed(error = parsed))- }- }- }-- private fun handleConnectionError(error: Throwable) {- val mappedError: Throwable = when (error) {- // Unauthorized response means that the credentials are invalid- is UnauthorizedException -> InvalidCredentialsException()-- else -> error- }-- dispatch(Message.AuthenticationFailed(mappedError))- publish(Label.AuthenticationFailed(mappedError))- }- }-- /**- * Reducer implementation that consumes [Message]s and updates the store's [State].- */- private object ReducerImpl : Reducer<State, Message> {- override fun State.reduce(msg: Message): State = when (msg) {- is Message.AuthenticationFailed -> copy(error = msg.error)- }- }-- interface Client {-- /**- * Authenticates the user with the current Solr instance.- *- * @param state The state value used in the authorization flow with PKCE.- * @param verifier Code verifier used in the authorization flow with PKCE.- * @param data The OAuth data to use for the auth flow.- * @return Returns success results iff the user has successfully authenticated.- */- suspend fun authenticate(state: String, verifier: String, data: OAuthData): Result<BearerTokens>- }-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationStateHolder.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationStateHolder.ktnew file mode 100644index 00000000000..5bfd4564359--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationStateHolder.kt@@ -0,0 +1,205 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.viewmodel++import io.ktor.http.Url+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.CoroutineStart+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import org.apache.solr.ui.components.auth.domain.AuthenticationEvent+import org.apache.solr.ui.components.auth.domain.BasicAuthEvent+import org.apache.solr.ui.components.auth.domain.BasicAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.CreateOAuthAuthorizationUseCase+import org.apache.solr.ui.components.auth.domain.OAuthAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.OAuthEvent+import org.apache.solr.ui.domain.AuthMethod+import org.apache.solr.ui.domain.AuthOption+import org.apache.solr.ui.errors.InvalidCredentialsException+import org.apache.solr.ui.shared.generated.resources.Res+import org.apache.solr.ui.shared.generated.resources.error_invalid_credentials+import org.apache.solr.ui.shared.generated.resources.error_unknown+import org.apache.solr.ui.utils.AppDispatchers+import org.jetbrains.compose.resources.StringResource++/**+ * State holder of the authentication screen that takes care of the authentication processes.+ *+ * The main role of this state holder is to hold and manage a shared authentication state that can+ * be used across all authentication options available to the user. This state can contain a shared+ * error state, an "authenticating" state and various other data that need to be in sync if multiple+ * authentication options are available at the same time.+ *+ * Note that Solr does not support multiple authentication methods of the same type with the+ * MultiAuthPlugin, so there will be always up to one state holder per method ([basicAuth] and+ * [oAuth]), and they exist only if the respective method is supported.+ *+ * @property url The URL of the Solr instance the user is authenticating against.+ * @param methods The authentication methods that are supported by the Solr instance.+ */+class AuthenticationStateHolder(+ private val scope: CoroutineScope,+ private val url: Url,+ methods: List<AuthMethod>,+ basicAuthenticateUseCase: BasicAuthenticateUseCase,+ createOAuthAuthorizationUseCase: CreateOAuthAuthorizationUseCase,+ oAuthAuthenticateUseCase: OAuthAuthenticateUseCase,+ dispatchers: AppDispatchers,+) {++ /**+ * State holder for authentication with credentials (basic auth), if it is supported.+ */+ val basicAuth: BasicAuthStateHolder? = methods+ .filterIsInstance<AuthMethod.BasicAuthMethod>()+ .lastOrNull()+ ?.let { method ->+ BasicAuthStateHolder(+ scope = scope,+ method = method,+ basicAuthenticateUseCase = basicAuthenticateUseCase,+ dispatchers = dispatchers,+ )+ }++ /**+ * State holder for authentication with OAuth (bearer token), if it is supported.+ */+ val oAuth: OAuthStateHolder? = methods+ .filterIsInstance<AuthMethod.OAuthMethod>()+ .lastOrNull()+ ?.let { method ->+ OAuthStateHolder(+ scope = scope,+ method = method,+ createOAuthAuthorizationUseCase = createOAuthAuthorizationUseCase,+ oAuthAuthenticateUseCase = oAuthAuthenticateUseCase,+ dispatchers = dispatchers,+ )+ }++ /**+ * UI state of the authentication screen.+ */+ val uiState: StateFlow<AuthenticationUiState>+ field = MutableStateFlow(AuthenticationUiState(url = url.toString(), methods = methods))++ /**+ * Events emitted by the state holder that are meant to be handled by the parent.+ */+ val events: SharedFlow<AuthenticationEvent>+ field = MutableSharedFlow<AuthenticationEvent>(extraBufferCapacity = 1)++ /**+ * URLs of the identity provider that are supposed to be opened for authorizing the user.+ */+ val authorizationUrls: SharedFlow<Url>+ field = MutableSharedFlow<Url>(extraBufferCapacity = 1)++ init {+ // Undispatched start makes sure the collectors are subscribed before anyone can emit+ basicAuth?.let { holder ->+ scope.launch(start = CoroutineStart.UNDISPATCHED) {+ holder.events.collect(::handleBasicAuthEvent)+ }+ }+ oAuth?.let { holder ->+ scope.launch(start = CoroutineStart.UNDISPATCHED) {+ holder.events.collect(::handleOAuthEvent)+ }+ }+ }++ /**+ * Aborts the authentication attempt.+ */+ fun abort() {+ scope.launch { events.emit(AuthenticationEvent.Aborted) }+ }++ private suspend fun handleBasicAuthEvent(event: BasicAuthEvent) = when (event) {+ is BasicAuthEvent.AuthenticationStarted -> startAuthenticating()++ is BasicAuthEvent.Authenticated -> events.emit(+ AuthenticationEvent.Authenticated(+ option = AuthOption.BasicAuthOption(+ url = url,+ username = event.username,+ password = event.password,+ realm = event.method.realm,+ ),+ ),+ )++ is BasicAuthEvent.AuthenticationFailed -> failAuthentication(event.error)++ is BasicAuthEvent.ErrorReset -> resetError()+ }++ private suspend fun handleOAuthEvent(event: OAuthEvent) = when (event) {+ is OAuthEvent.AuthenticationStarted -> {+ startAuthenticating()+ authorizationUrls.emit(event.url)+ }++ is OAuthEvent.Authenticated -> events.emit(+ AuthenticationEvent.Authenticated(+ option = AuthOption.OAuthOption(+ url = url,+ accessToken = event.accessToken,+ refreshToken = event.refreshToken,+ realm = event.method.realm,+ ),+ ),+ )++ is OAuthEvent.AuthenticationFailed -> failAuthentication(event.error)+ }++ private fun startAuthenticating() = uiState.update { it.copy(isAuthenticating = true) }++ private fun failAuthentication(error: Throwable) = uiState.update {+ it.copy(error = error.toErrorResource(), isAuthenticating = false)+ }++ private fun resetError() = uiState.update { it.copy(error = null) }+}++/**+ * UI state of the authentication screen.+ *+ * @property url URL of the Solr instance the user is trying to connect.+ * @property methods List of authentication methods to render.+ * @property isAuthenticating Whether a connection is currently established.+ * @property error The error that may have occurred.+ */+data class AuthenticationUiState(+ val url: String = "",+ val methods: List<AuthMethod> = emptyList(),+ val isAuthenticating: Boolean = false,+ val error: StringResource? = null,+)++private fun Throwable.toErrorResource(): StringResource = when (this) {+ is InvalidCredentialsException -> Res.string.error_invalid_credentials+ else -> Res.string.error_unknown+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationViewModel.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationViewModel.ktnew file mode 100644index 00000000000..fe562a29d26--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationViewModel.kt@@ -0,0 +1,77 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.viewmodel++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import io.ktor.http.Url+import org.apache.solr.ui.components.auth.domain.BasicAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.CreateOAuthAuthorizationUseCase+import org.apache.solr.ui.components.auth.domain.OAuthAuthenticateUseCase+import org.apache.solr.ui.domain.AuthMethod+import org.apache.solr.ui.utils.AppDispatchers++class AuthenticationViewModel(+ url: Url,+ methods: List<AuthMethod>,+ basicAuthenticateUseCase: BasicAuthenticateUseCase,+ createOAuthAuthorizationUseCase: CreateOAuthAuthorizationUseCase,+ oAuthAuthenticateUseCase: OAuthAuthenticateUseCase,+ dispatchers: AppDispatchers,+) : ViewModel() {++ private val authenticationState = AuthenticationStateHolder(+ scope = viewModelScope,+ url = url,+ methods = methods,+ basicAuthenticateUseCase = basicAuthenticateUseCase,+ createOAuthAuthorizationUseCase = createOAuthAuthorizationUseCase,+ oAuthAuthenticateUseCase = oAuthAuthenticateUseCase,+ dispatchers = dispatchers,+ )++ /**+ * UI state of the authentication screen.+ */+ val uiState = authenticationState.uiState++ /**+ * Events emitted by the authentication screen.+ */+ val events = authenticationState.events++ /**+ * URLs of the identity provider that are supposed to be opened for authorizing the user.+ */+ val authorizationUrls = authenticationState.authorizationUrls++ /**+ * State holder for authentication with credentials (basic auth), if it is supported.+ */+ val basicAuth = authenticationState.basicAuth++ /**+ * State holder for authentication with OAuth (bearer token), if it is supported.+ */+ val oAuth = authenticationState.oAuth++ /**+ * Aborts the authentication attempt.+ */+ fun abort() = authenticationState.abort()+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/BasicAuthStateHolder.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/BasicAuthStateHolder.ktnew file mode 100644index 00000000000..466abd7aafd--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/BasicAuthStateHolder.kt@@ -0,0 +1,123 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.viewmodel++import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import org.apache.solr.ui.components.auth.domain.BasicAuthEvent+import org.apache.solr.ui.components.auth.domain.BasicAuthenticateUseCase+import org.apache.solr.ui.domain.AuthMethod+import org.apache.solr.ui.utils.AppDispatchers++/**+ * State holder that handles basic authentication with username and password.+ *+ * @property method The basic auth method the user is authenticating with.+ */+class BasicAuthStateHolder(+ private val scope: CoroutineScope,+ private val method: AuthMethod.BasicAuthMethod,+ private val basicAuthenticateUseCase: BasicAuthenticateUseCase,+ private val dispatchers: AppDispatchers,+) {++ /**+ * UI state of the basic authentication form.+ */+ val uiState: StateFlow<BasicAuthUiState>+ field = MutableStateFlow(BasicAuthUiState(realm = method.realm))++ /**+ * Events emitted by the state holder.+ */+ val events: SharedFlow<BasicAuthEvent>+ field = MutableSharedFlow<BasicAuthEvent>(extraBufferCapacity = 1)++ /**+ * Updates the username that is typed in.+ *+ * @param username The new username.+ */+ fun changeUsername(username: String) {+ resetError()+ uiState.update { it.copy(username = username, hasError = false) }+ }++ /**+ * Updates the password that is typed in.+ *+ * @param password The new password.+ */+ fun changePassword(password: String) {+ resetError()+ uiState.update { it.copy(password = password, hasError = false) }+ }++ /**+ * Tries to authenticate the user with the username and password that are currently typed in.+ */+ fun authenticate() {+ val username = uiState.value.username+ val password = uiState.value.password++ scope.launch {+ events.emit(BasicAuthEvent.AuthenticationStarted)++ withContext(dispatchers.io) {+ basicAuthenticateUseCase(username, password)+ }.onSuccess {+ // Authentication succeeded with the given credentials+ events.emit(BasicAuthEvent.Authenticated(method, username, password))+ }.onFailure { error ->+ uiState.update { it.copy(hasError = true) }+ events.emit(BasicAuthEvent.AuthenticationFailed(error))+ }+ }+ }++ /**+ * Notifies listeners about the reset of the error, if there is one.+ */+ private fun resetError() {+ if (uiState.value.hasError) {+ scope.launch { events.emit(BasicAuthEvent.ErrorReset) }+ }+ }+}++/**+ * UI state of the basic authentication form.+ *+ * @property realm The basic auth realm the user is supposed to provide the credentials for.+ * @property username The username that is currently typed in.+ * @property password The password that is currently typed in.+ * @property hasError Whether the current input has an error. This is a simplified variant that+ * does not distinguish input fields.+ */+data class BasicAuthUiState(+ val realm: String? = null,+ val username: String = "",+ val password: String = "",+ val hasError: Boolean = false,+)diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/OAuthStateHolder.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/OAuthStateHolder.ktnew file mode 100644index 00000000000..e506cf30aea--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/auth/viewmodel/OAuthStateHolder.kt@@ -0,0 +1,100 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.viewmodel++import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import org.apache.solr.ui.components.auth.domain.CreateOAuthAuthorizationUseCase+import org.apache.solr.ui.components.auth.domain.OAuthAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.OAuthEvent+import org.apache.solr.ui.domain.AuthMethod+import org.apache.solr.ui.utils.AppDispatchers++/**+ * State holder that handles authentication with OAuth via an identity provider.+ *+ * @property method The OAuth method the user is authenticating with.+ */+class OAuthStateHolder(+ private val scope: CoroutineScope,+ private val method: AuthMethod.OAuthMethod,+ private val createOAuthAuthorizationUseCase: CreateOAuthAuthorizationUseCase,+ private val oAuthAuthenticateUseCase: OAuthAuthenticateUseCase,+ private val dispatchers: AppDispatchers,+) {++ private var authJob: Job? = null++ /**+ * UI state of the OAuth authentication.+ */+ val uiState: StateFlow<OAuthUiState>+ field = MutableStateFlow(OAuthUiState(realm = method.realm))++ /**+ * Events emitted by the state holder.+ */+ val events: SharedFlow<OAuthEvent>+ field = MutableSharedFlow<OAuthEvent>(extraBufferCapacity = 1)++ /**+ * Starts an authentication attempt with the OAuth method.+ */+ fun authenticate() {+ val authorization = createOAuthAuthorizationUseCase(method)++ authJob?.cancel()+ authJob = scope.launch {+ events.emit(OAuthEvent.AuthenticationStarted(url = authorization.url))++ withContext(dispatchers.io) {+ oAuthAuthenticateUseCase(authorization, method)+ }.onSuccess {+ // Authentication succeeded with the given credentials+ events.emit(+ OAuthEvent.Authenticated(+ method = method,+ accessToken = it.accessToken,+ refreshToken = it.refreshToken,+ ),+ )+ }.onFailure { error ->+ uiState.update { it.copy(hasError = true) }+ events.emit(OAuthEvent.AuthenticationFailed(error))+ }+ }+ }+}++/**+ * UI state of the OAuth authentication.+ *+ * @property realm The OAuth realm the user is supposed to authenticate against.+ * @property hasError Whether the current input has an error.+ */+data class OAuthUiState(+ val realm: String? = null,+ val hasError: Boolean = false,+)diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/ClusterComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/ClusterComponent.ktindex 604a460bf24..583540c7512 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/ClusterComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/ClusterComponent.kt@@ -17,10 +17,7 @@package org.apache.solr.ui.components.cluster-import kotlinx.serialization.Serializable-import org.apache.solr.ui.components.cluster.ClusterComponent.Child-import org.apache.solr.ui.components.cluster.ClusterComponent.ClusterTab-import org.apache.solr.ui.components.navigation.TabNavigationComponent+import org.apache.solr.ui.components.cluster.viewmodel.ClusterViewModel/*** Cluster component that represents our current Cluster section.@@ -28,20 +25,10 @@ import org.apache.solr.ui.components.navigation.TabNavigationComponent* The cluster section's goal is to provide a "physical" representation of the connected Solr* instance.*/-interface ClusterComponent : TabNavigationComponent<ClusterTab, Child> {+interface ClusterComponent {- sealed interface Child {- data object Zookeeper : Child-- data object Nodes : Child-- data object Cores : Child- }-- @Serializable- enum class ClusterTab {- Zookeeper,- Nodes,- Cores,- }+ /**+ * Factory method to create a [ClusterViewModel] instance.+ */+ fun createClusterViewModel(): ClusterViewModel}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/integration/DefaultClusterComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/integration/DefaultClusterComponent.ktindex 02f230f5901..e9e9af0068c 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/integration/DefaultClusterComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/integration/DefaultClusterComponent.kt@@ -17,41 +17,13 @@package org.apache.solr.ui.components.cluster.integration-import com.arkivanov.decompose.router.slot.ChildSlot-import com.arkivanov.decompose.router.slot.SlotNavigation-import com.arkivanov.decompose.router.slot.activate-import com.arkivanov.decompose.router.slot.childSlot-import com.arkivanov.decompose.value.Valueimport org.apache.solr.ui.components.cluster.ClusterComponent-import org.apache.solr.ui.components.cluster.ClusterComponent.Child-import org.apache.solr.ui.components.cluster.ClusterComponent.ClusterTab-import org.apache.solr.ui.components.navigation.TabNavigationComponent-import org.apache.solr.ui.utils.AppComponentContext+import org.apache.solr.ui.components.cluster.viewmodel.ClusterViewModel-class DefaultClusterComponent(- componentContext: AppComponentContext,-) : ClusterComponent,- AppComponentContext by componentContext,- TabNavigationComponent<ClusterTab, Child> {-- private val navigation = SlotNavigation<ClusterTab>()-- override val tabSlot: Value<ChildSlot<ClusterTab, Child>> = childSlot(- source = navigation,- serializer = ClusterTab.serializer(),- handleBackButton = true,- childFactory = { configuration, childContext ->- when (configuration) {- ClusterTab.Zookeeper -> Child.Zookeeper- ClusterTab.Nodes -> Child.Nodes- ClusterTab.Cores -> Child.Cores- }- },- )-- init {- navigation.activate(configuration = ClusterTab.Zookeeper)- }+/**+ * Default implementation of [ClusterComponent].+ */+class DefaultClusterComponent : ClusterComponent {- override fun onNavigate(tab: ClusterTab) = navigation.activate(configuration = tab)+ override fun createClusterViewModel(): ClusterViewModel = ClusterViewModel()}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/start/TestStartComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/viewmodel/ClusterViewModel.ktsimilarity index 52%rename from ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/start/TestStartComponent.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/viewmodel/ClusterViewModel.ktindex dfe0ef1307e..c1b1183dd9a 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/start/TestStartComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/cluster/viewmodel/ClusterViewModel.kt@@ -15,25 +15,41 @@* limitations under the License.*/-package org.apache.solr.ui.views.start+package org.apache.solr.ui.components.cluster.viewmodel+import androidx.lifecycle.ViewModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.start.StartComponent-import org.apache.solr.ui.components.start.StartComponent.Model+import kotlinx.coroutines.flow.update-class TestStartComponent(model: Model = Model()) : StartComponent {+/**+ * View model of the cluster section.+ *+ * The cluster section's goal is to provide a "physical" representation of the connected Solr+ * instance.+ */+class ClusterViewModel : ViewModel() {- override val model: StateFlow<Model> = MutableStateFlow(model)+ /**+ * UI state of the cluster section.+ */+ val uiState: StateFlow<ClusterUiState>+ field = MutableStateFlow(ClusterUiState())- var solrUrl = ""- var onConnectClicked = false+ /**+ * Switches to the cluster [tab] that was provided.+ *+ * @param tab The tab to select.+ */+ fun selectTab(tab: ClusterTab) = uiState.update { it.copy(selectedTab = tab) }+}- override fun onSolrUrlChange(url: String) {- solrUrl = url- }+data class ClusterUiState(+ val selectedTab: ClusterTab = ClusterTab.Zookeeper,+)- override fun onConnect() {- onConnectClicked = true- }+enum class ClusterTab {+ Zookeeper,+ Nodes,+ Cores,}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/EnvironmentComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/EnvironmentComponent.ktindex 1942b746b1f..044df18856f 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/EnvironmentComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/EnvironmentComponent.kt@@ -17,24 +17,33 @@package org.apache.solr.ui.components.environment-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.environment.data.JavaProperty-import org.apache.solr.ui.components.environment.data.JvmData-import org.apache.solr.ui.components.environment.data.Versions+import org.apache.solr.ui.components.environment.domain.LoadJavaPropertiesUseCase+import org.apache.solr.ui.components.environment.domain.LoadSystemDataUseCase+import org.apache.solr.ui.components.environment.repository.EnvironmentRepository+import org.apache.solr.ui.components.environment.viewmodel.EnvironmentViewModel/*** Component interface that represents the environment section.*/interface EnvironmentComponent {- val model: StateFlow<Model>+ /**+ * Dependencies provided by the application.+ */+ val environmentRepository: EnvironmentRepository++ /**+ * Use case responsible for loading the system data.+ */+ val loadSystemDataUseCase: LoadSystemDataUseCase++ /**+ * Use case responsible for loading the java properties.+ */+ val loadJavaPropertiesUseCase: LoadJavaPropertiesUseCase/**- * State class that holds values of the [EnvironmentComponent]'s sate.+ * Factory method to create a [EnvironmentViewModel] instance.*/- data class Model(- val versions: Versions = Versions(),- val jvm: JvmData = JvmData(),- val javaProperties: List<JavaProperty> = emptyList(),- )+ fun createEnvironmentViewModel(): EnvironmentViewModel}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/HttpEnvironmentStoreClient.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/data/HttpEnvironmentRepository.ktsimilarity index 82%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/HttpEnvironmentStoreClient.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/data/HttpEnvironmentRepository.ktindex fb8b6e37d87..854967bd6c2 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/HttpEnvironmentStoreClient.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/data/HttpEnvironmentRepository.kt@@ -15,19 +15,16 @@* limitations under the License.*/-package org.apache.solr.ui.components.environment.integration+package org.apache.solr.ui.components.environment.dataimport io.ktor.client.HttpClientimport io.ktor.client.call.bodyimport io.ktor.client.request.getimport io.ktor.http.isSuccess-import org.apache.solr.ui.components.environment.data.JavaPropertiesResponse-import org.apache.solr.ui.components.environment.data.JavaProperty-import org.apache.solr.ui.components.environment.data.SystemData-import org.apache.solr.ui.components.environment.store.EnvironmentStoreProvider+import org.apache.solr.ui.components.environment.repository.EnvironmentRepository/**- * Client implementation of the [EnvironmentStoreProvider.Client] that makes use+ * Repository implementation of the [EnvironmentRepository] that makes use* of a preconfigured HTTP client for accessing the Solr API.** @property httpClient HTTP client to use for accessing the API. The client has to be@@ -35,9 +32,9 @@ import org.apache.solr.ui.components.environment.store.EnvironmentStoreProvider* should also include the necessary authentication data if authentication / authorization* is enabled.*/-class HttpEnvironmentStoreClient(+class HttpEnvironmentRepository(private val httpClient: HttpClient,-) : EnvironmentStoreProvider.Client {+) : EnvironmentRepository {override suspend fun getSystemData(): Result<SystemData> {val response = httpClient.get("api/node/system")diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/DefaultLoadJavaPropertiesUseCase.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/DefaultLoadJavaPropertiesUseCase.ktnew file mode 100644index 00000000000..076fb930368--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/DefaultLoadJavaPropertiesUseCase.kt@@ -0,0 +1,27 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.environment.domain++import org.apache.solr.ui.components.environment.data.JavaProperty+import org.apache.solr.ui.components.environment.repository.EnvironmentRepository++internal class DefaultLoadJavaPropertiesUseCase(+ private val repository: EnvironmentRepository,+) : LoadJavaPropertiesUseCase {+ override suspend fun invoke(): Result<List<JavaProperty>> = repository.getJavaProperties()+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/AppComponentContext.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/DefaultLoadSystemDataUseCase.ktsimilarity index 66%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/AppComponentContext.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/DefaultLoadSystemDataUseCase.ktindex 3403a82dd00..2d59ae06b41 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/AppComponentContext.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/DefaultLoadSystemDataUseCase.kt@@ -15,14 +15,13 @@* limitations under the License.*/-package org.apache.solr.ui.utils+package org.apache.solr.ui.components.environment.domain-import com.arkivanov.decompose.GenericComponentContext+import org.apache.solr.ui.components.environment.data.SystemData+import org.apache.solr.ui.components.environment.repository.EnvironmentRepository-/**- * The application component context that provides basic functionality to all components, including- * a lifecycle, state preservation, navigation handling and coroutine contexts.- */-interface AppComponentContext :- GenericComponentContext<AppComponentContext>,- CoroutineContextOwner+internal class DefaultLoadSystemDataUseCase(+ private val repository: EnvironmentRepository,+) : LoadSystemDataUseCase {+ override suspend fun invoke(): Result<SystemData> = repository.getSystemData()+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/LoadJavaPropertiesUseCase.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/LoadJavaPropertiesUseCase.ktnew file mode 100644index 00000000000..ea513eb4de3--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/LoadJavaPropertiesUseCase.kt@@ -0,0 +1,33 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.environment.domain++import org.apache.solr.ui.components.environment.data.JavaProperty++/**+ * Use case for loading the java properties of the connected Solr node.+ */+interface LoadJavaPropertiesUseCase {++ /**+ * Default invocation for loading the java properties.+ *+ * @return A Result containing the list of [JavaProperty]s.+ */+ suspend operator fun invoke(): Result<List<JavaProperty>>+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/navigation/NavigationComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/LoadSystemDataUseCase.ktsimilarity index 67%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/navigation/NavigationComponent.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/LoadSystemDataUseCase.ktindex 1ecdb1bfe20..65a91f1a000 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/navigation/NavigationComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/domain/LoadSystemDataUseCase.kt@@ -15,17 +15,19 @@* limitations under the License.*/-package org.apache.solr.ui.components.navigation+package org.apache.solr.ui.components.environment.domain++import org.apache.solr.ui.components.environment.data.SystemData/**- * Interface that provides the basic functionality for any navigation component. Navigation- * components can use this interface as base and extend it.+ * Use case for loading the system data of the connected Solr node.*/-interface NavigationComponent {+interface LoadSystemDataUseCase {/**- * This method is called when the user navigates back. It is used to perform any necessary- * actions or updates.+ * Default invocation for loading the system data.+ *+ * @return A Result containing the system data.*/- fun onNavigateBack()+ suspend operator fun invoke(): Result<SystemData>}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/DefaultEnvironmentComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/DefaultEnvironmentComponent.ktindex 0be5982d4b2..2bd568502c2 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/DefaultEnvironmentComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/integration/DefaultEnvironmentComponent.kt@@ -17,40 +17,45 @@package org.apache.solr.ui.components.environment.integration-import com.arkivanov.mvikotlin.core.instancekeeper.getStore-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.stateFlowimport io.ktor.client.HttpClient-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.SupervisorJobimport org.apache.solr.ui.components.environment.EnvironmentComponent-import org.apache.solr.ui.components.environment.store.EnvironmentStoreProvider-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.utils.coroutineScope-import org.apache.solr.ui.utils.map+import org.apache.solr.ui.components.environment.data.HttpEnvironmentRepository+import org.apache.solr.ui.components.environment.domain.DefaultLoadJavaPropertiesUseCase+import org.apache.solr.ui.components.environment.domain.DefaultLoadSystemDataUseCase+import org.apache.solr.ui.components.environment.domain.LoadJavaPropertiesUseCase+import org.apache.solr.ui.components.environment.domain.LoadSystemDataUseCase+import org.apache.solr.ui.components.environment.repository.EnvironmentRepository+import org.apache.solr.ui.components.environment.viewmodel.EnvironmentViewModel+import org.apache.solr.ui.utils.AppDispatchers+import org.apache.solr.ui.utils.platformDispatchers/*** Default implementation of the [EnvironmentComponent].+ *+ * This implementation is using HTTP for environment operations.+ *+ * @param httpClient The pre-configured HTTP client to use for environment operations.*/class DefaultEnvironmentComponent(- componentContext: AppComponentContext,- storeFactory: StoreFactory,httpClient: HttpClient,-) : EnvironmentComponent,- AppComponentContext by componentContext {+ private val dispatchers: AppDispatchers = platformDispatchers(),+) : EnvironmentComponent {- private val mainScope = coroutineScope(SupervisorJob() + mainContext)- private val ioScope = coroutineScope(SupervisorJob() + ioContext)+ override val environmentRepository: EnvironmentRepository by lazy {+ HttpEnvironmentRepository(httpClient)+ }++ override val loadSystemDataUseCase: LoadSystemDataUseCase by lazy {+ DefaultLoadSystemDataUseCase(environmentRepository)+ }- private val store = instanceKeeper.getStore {- EnvironmentStoreProvider(- storeFactory = storeFactory,- client = HttpEnvironmentStoreClient(httpClient),- mainContext = mainScope.coroutineContext,- ioContext = ioScope.coroutineContext,- ).provide()+ override val loadJavaPropertiesUseCase: LoadJavaPropertiesUseCase by lazy {+ DefaultLoadJavaPropertiesUseCase(environmentRepository)}- @OptIn(ExperimentalCoroutinesApi::class)- override val model = store.stateFlow.map(mainScope, environmentStateToModel)+ override fun createEnvironmentViewModel(): EnvironmentViewModel = EnvironmentViewModel(+ loadSystemDataUseCase = loadSystemDataUseCase,+ loadJavaPropertiesUseCase = loadJavaPropertiesUseCase,+ dispatchers = dispatchers,+ )}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/store/MockedEnvironmentStoreClient.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/repository/EnvironmentRepository.ktsimilarity index 64%rename from ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/store/MockedEnvironmentStoreClient.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/repository/EnvironmentRepository.ktindex 5f21a885c8f..64b6748b0b7 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/store/MockedEnvironmentStoreClient.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/repository/EnvironmentRepository.kt@@ -15,17 +15,27 @@* limitations under the License.*/-package org.apache.solr.ui.components.environment.store+package org.apache.solr.ui.components.environment.repositoryimport org.apache.solr.ui.components.environment.data.JavaPropertyimport org.apache.solr.ui.components.environment.data.SystemData-class MockedEnvironmentStoreClient(- private val onGetSystemData: () -> Result<SystemData>,- private val onGetJavaProperties: () -> Result<List<JavaProperty>>,-) : EnvironmentStoreProvider.Client {+/**+ * Repository interface for fetching environment information.+ */+interface EnvironmentRepository {- override suspend fun getSystemData(): Result<SystemData> = onGetSystemData()+ /**+ * Fetches a set of system data.+ *+ * @return Result with the system data fetched.+ */+ suspend fun getSystemData(): Result<SystemData>- override suspend fun getJavaProperties(): Result<List<JavaProperty>> = onGetJavaProperties()+ /**+ * Fetches the configured java properties.+ *+ * @return Result with a list of [JavaProperty]s.+ */+ suspend fun getJavaProperties(): Result<List<JavaProperty>>}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStore.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStore.ktdeleted file mode 100644index 7f8c87da0c1..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStore.kt+++ /dev/null@@ -1,63 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.environment.store--import com.arkivanov.mvikotlin.core.store.Store-import org.apache.solr.ui.components.environment.data.JavaProperty-import org.apache.solr.ui.components.environment.data.JvmData-import org.apache.solr.ui.components.environment.data.SecurityConfig-import org.apache.solr.ui.components.environment.data.SystemInformation-import org.apache.solr.ui.components.environment.data.SystemMode-import org.apache.solr.ui.components.environment.data.Versions-import org.apache.solr.ui.components.environment.store.EnvironmentStore.Intent-import org.apache.solr.ui.components.environment.store.EnvironmentStore.State--/**- * State store interface of the environment.- *- * Implementations of this state store manage detailed information of the environment.- */-internal interface EnvironmentStore : Store<Intent, State, Nothing> {-- /**- * Intent for interacting with the environment store.- */- sealed interface Intent {-- /**- * Intent for requesting system data.- */- data object FetchSystemData : Intent- }-- /**- * State class that holds the data of the [EnvironmentStore].- */- data class State(- val mode: SystemMode = SystemMode.Unknown,- val zkHost: String = "",- val solrHome: String = "",- val coreRoot: String = "",- val lucene: Versions = Versions(),- val jvm: JvmData = JvmData(),- val security: SecurityConfig = SecurityConfig(),- val system: SystemInformation = SystemInformation(),- val node: String = "",- val javaProperties: List<JavaProperty> = emptyList(),- )-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStoreProvider.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStoreProvider.ktdeleted file mode 100644index 1f62238020f..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStoreProvider.kt+++ /dev/null@@ -1,177 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.environment.store--import com.arkivanov.mvikotlin.core.store.Reducer-import com.arkivanov.mvikotlin.core.store.SimpleBootstrapper-import com.arkivanov.mvikotlin.core.store.Store-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.CoroutineExecutor-import kotlin.coroutines.CoroutineContext-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import org.apache.solr.ui.components.environment.data.JavaProperty-import org.apache.solr.ui.components.environment.data.SystemData-import org.apache.solr.ui.components.environment.store.EnvironmentStore.Intent-import org.apache.solr.ui.components.environment.store.EnvironmentStore.State--/**- * Store provider that [provide]s instances of [EnvironmentStore].- *- * @property storeFactory Store factory to use for creating the store.- * @property client Client implementation to use for resolving [Intent]s and [Action]s.- * @property ioContext Coroutine context used for IO activity.- */-internal class EnvironmentStoreProvider(- private val storeFactory: StoreFactory,- private val client: Client,- private val mainContext: CoroutineContext,- private val ioContext: CoroutineContext,-) {-- fun provide(): EnvironmentStore = object :- EnvironmentStore,- Store<Intent, State, Nothing> by storeFactory.create(- name = "EnvironmentStore",- initialState = State(),- bootstrapper = SimpleBootstrapper(Action.FetchInitialSystemData),- executorFactory = ::ExecutorImpl,- reducer = ReducerImpl,- ) {}-- private sealed interface Action {-- /**- * Action used for initiating the initial fetch of environment data.- */- data object FetchInitialSystemData : Action- }-- private sealed interface Message {-- /**- * Message that is dispatched when system data have been retrieved / updated.- *- * @property data New system data that have been received.- */- data class SystemDataUpdated(val data: SystemData) : Message-- /**- * Message that is dispatched when java properties have been retrieved / updated.- *- * @property properties New list of java properties.- */- data class JavaPropertiesUpdated(val properties: List<JavaProperty>) : Message- }-- private inner class ExecutorImpl : CoroutineExecutor<Intent, Action, State, Message, Nothing>(mainContext) {-- override fun executeAction(action: Action) = when (action) {- Action.FetchInitialSystemData -> {- fetchSystemData()- fetchJavaProperties()- }- }-- override fun executeIntent(intent: Intent) {- when (intent) {- Intent.FetchSystemData -> {- fetchSystemData()- fetchJavaProperties()- }- }- }-- /**- * Fetches the system data that are part of the environment state.- *- * If successful, a [Message.SystemDataUpdated] with the new properties is dispatched.- */- private fun fetchSystemData() {- scope.launch {- // TODO Add coroutine exception handler- withContext(ioContext) {- client.getSystemData()- }.onSuccess {- dispatch(Message.SystemDataUpdated(it))- }- // TODO Add error handling- }- }-- /**- * Fetches the java properties that are part of the environment state.- *- * If successful, a [Message.JavaPropertiesUpdated] with the new properties is dispatched.- */- private fun fetchJavaProperties() {- scope.launch {- // TODO Add coroutine exception handler- withContext(ioContext) {- client.getJavaProperties()- }.onSuccess {- dispatch(Message.JavaPropertiesUpdated(it))- }- // TODO Add error handling- }- }- }-- /**- * Reducer implementation that consumes [Message]s and updates the store's [State].- */- private object ReducerImpl : Reducer<State, Message> {- override fun State.reduce(msg: Message): State = when (msg) {- is Message.SystemDataUpdated -> copy(- mode = msg.data.mode,- zkHost = msg.data.zkHost,- solrHome = msg.data.solrHome,- coreRoot = msg.data.coreRoot,- lucene = msg.data.lucene,- jvm = msg.data.jvm,- security = msg.data.security,- system = msg.data.system,- node = msg.data.node,- )-- is Message.JavaPropertiesUpdated -> copy(- javaProperties = msg.properties,- )- }- }-- /**- * Client interface for fetching environment information.- */- interface Client {-- /**- * Fetches a set of system data.- *- * @return Result with the system data fetched.- */- suspend fun getSystemData(): Result<SystemData>-- /**- * Fetches the configured java properties.- *- * @return Result with a list of [JavaProperty]s.- */- suspend fun getJavaProperties(): Result<List<JavaProperty>>- }-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentStateHolder.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentStateHolder.ktnew file mode 100644index 00000000000..86fce59c166--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentStateHolder.kt@@ -0,0 +1,120 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.environment.viewmodel++import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import org.apache.solr.ui.components.environment.data.JavaProperty+import org.apache.solr.ui.components.environment.data.JvmData+import org.apache.solr.ui.components.environment.data.SecurityConfig+import org.apache.solr.ui.components.environment.data.SystemInformation+import org.apache.solr.ui.components.environment.data.SystemMode+import org.apache.solr.ui.components.environment.data.Versions+import org.apache.solr.ui.components.environment.domain.LoadJavaPropertiesUseCase+import org.apache.solr.ui.components.environment.domain.LoadSystemDataUseCase+import org.apache.solr.ui.utils.AppDispatchers++/**+ * State holder of the environment that manages detailed information of the environment.+ *+ * The environment data is fetched initially, and can be fetched again with [fetchSystemData].+ */+class EnvironmentStateHolder(+ private val scope: CoroutineScope,+ private val loadSystemDataUseCase: LoadSystemDataUseCase,+ private val loadJavaPropertiesUseCase: LoadJavaPropertiesUseCase,+ private val dispatchers: AppDispatchers,+) {++ /**+ * UI state of the environment.+ */+ val uiState: StateFlow<EnvironmentUiState>+ field = MutableStateFlow(EnvironmentUiState())++ init {+ fetchSystemData()+ }++ /**+ * Fetches the system data and the java properties that are part of the environment state.+ */+ fun fetchSystemData() {+ loadSystemData()+ loadJavaProperties()+ }++ /**+ * Fetches the system data that are part of the environment state.+ *+ * If successful, the state is updated with the new system data.+ */+ private fun loadSystemData() = scope.launch {+ // TODO Add coroutine exception handler+ withContext(dispatchers.io) {+ loadSystemDataUseCase()+ }.onSuccess { data ->+ uiState.update {+ it.copy(+ mode = data.mode,+ zkHost = data.zkHost,+ solrHome = data.solrHome,+ coreRoot = data.coreRoot,+ lucene = data.lucene,+ jvm = data.jvm,+ security = data.security,+ system = data.system,+ node = data.node,+ )+ }+ }+ // TODO Add error handling+ }++ /**+ * Fetches the java properties that are part of the environment state.+ *+ * If successful, the state is updated with the new java properties.+ */+ private fun loadJavaProperties() = scope.launch {+ // TODO Add coroutine exception handler+ withContext(dispatchers.io) {+ loadJavaPropertiesUseCase()+ }.onSuccess { properties ->+ uiState.update { it.copy(javaProperties = properties) }+ }+ // TODO Add error handling+ }+}++data class EnvironmentUiState(+ val mode: SystemMode = SystemMode.Unknown,+ val zkHost: String = "",+ val solrHome: String = "",+ val coreRoot: String = "",+ val lucene: Versions = Versions(),+ val jvm: JvmData = JvmData(),+ val security: SecurityConfig = SecurityConfig(),+ val system: SystemInformation = SystemInformation(),+ val node: String = "",+ val javaProperties: List<JavaProperty> = emptyList(),+)diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentViewModel.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentViewModel.ktnew file mode 100644index 00000000000..6fc00e5cf6a--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentViewModel.kt@@ -0,0 +1,48 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.environment.viewmodel++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import org.apache.solr.ui.components.environment.domain.LoadJavaPropertiesUseCase+import org.apache.solr.ui.components.environment.domain.LoadSystemDataUseCase+import org.apache.solr.ui.utils.AppDispatchers++class EnvironmentViewModel(+ loadSystemDataUseCase: LoadSystemDataUseCase,+ loadJavaPropertiesUseCase: LoadJavaPropertiesUseCase,+ dispatchers: AppDispatchers,+) : ViewModel() {++ private val environmentState = EnvironmentStateHolder(+ scope = viewModelScope,+ loadSystemDataUseCase = loadSystemDataUseCase,+ loadJavaPropertiesUseCase = loadJavaPropertiesUseCase,+ dispatchers = dispatchers,+ )++ /**+ * UI state of the environment.+ */+ val uiState = environmentState.uiState++ /**+ * Fetches the system data and the java properties again.+ */+ fun fetchSystemData() = environmentState.fetchSystemData()+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/logging/integration/DefaultLoggingComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/logging/integration/DefaultLoggingComponent.ktindex cb86c9623a6..954eac6eb1c 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/logging/integration/DefaultLoggingComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/logging/integration/DefaultLoggingComponent.kt@@ -17,12 +17,9 @@package org.apache.solr.ui.components.logging.integration-import com.arkivanov.mvikotlin.core.store.StoreFactoryimport org.apache.solr.ui.components.logging.LoggingComponent-import org.apache.solr.ui.utils.AppComponentContext-class DefaultLoggingComponent(- componentContext: AppComponentContext,- storeFactory: StoreFactory,-) : LoggingComponent,- AppComponentContext by componentContext+/**+ * Default implementation of [LoggingComponent].+ */+class DefaultLoggingComponent : LoggingComponentdiff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/MainComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/MainComponent.ktindex de40d86b586..b44aece9d90 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/MainComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/MainComponent.kt@@ -17,14 +17,11 @@package org.apache.solr.ui.components.main-import com.arkivanov.decompose.router.stack.ChildStack-import com.arkivanov.decompose.value.Valueimport org.apache.solr.ui.components.cluster.ClusterComponentimport org.apache.solr.ui.components.configsets.di.ConfigsetsComponentimport org.apache.solr.ui.components.environment.EnvironmentComponentimport org.apache.solr.ui.components.logging.LoggingComponent-import org.apache.solr.ui.components.navigation.NavigationComponent-import org.apache.solr.ui.views.navigation.MainMenu+import org.apache.solr.ui.components.main.viewmodel.MainViewModel/*** Main component of the application that is used as base for users with access.@@ -32,72 +29,42 @@ import org.apache.solr.ui.views.navigation.MainMenu* Note that this component can be accessed if the user is either authenticated or if the Solr* instance accessed does not have any authentication enabled.*/-interface MainComponent : NavigationComponent {+interface MainComponent {- /**- * Child stack that holds the navigation state.- */- val childStack: Value<ChildStack<*, Child>>+ // TODO Add DashboardComponent once available- /**- * Handles navigation requests from a navigation menu.- *- * @param menuItem The destination to navigate to.- */- fun onNavigate(menuItem: MainMenu)+ // TODO Add MetricsComponent once available/**- * Handles logout requests.+ * Component of the cluster section.*/- fun onLogout()+ val clusterComponent: ClusterComponent++ // TODO Add SecurityComponent once available/**- * Child interface that defines all available children of the [MainComponent].+ * Component of the configsets section.*/- sealed interface Child {-- // TODO Uncomment once DashboardComponent available- // data class Dashboard(val component: DashboardComponent): Child-- // TODO Uncomment once MetricsComponent available- // data class Metrics(val component: MetricsComponent): Child-- data class Cluster(val component: ClusterComponent) : Child-- // TODO Uncomment once SecurityComponent available- // data class Security(val component: SecurityComponent): Child+ val configsetsComponent: ConfigsetsComponent- data class Configsets(val component: ConfigsetsComponent) : Child+ // TODO Add CollectionsComponent once available- // TODO Uncomment once MetricsComponent available- // data class Collections(val component: CollectionsComponent): Child+ // TODO Add QueriesAndOperationsComponent once available- // TODO Uncomment once QueriesAndOperationsComponent available- // data class QueriesAndOperations(val component: QueriesAndOperationsComponent): Child-- /**- * Child that leads to the environment section.- *- * @property component Component that holds the state of this child.- */- data class Environment(val component: EnvironmentComponent) : Child-- /**- * Child that leads to the logging section.- *- * @property component Component that holds the state of this child.- */- data class Logging(val component: LoggingComponent) : Child+ /**+ * Component of the environment section.+ */+ val environmentComponent: EnvironmentComponent- // TODO Uncomment once ThreadDump available- // data class ThreadDump(val component: ThreadDumpComponent): Child- }+ /**+ * Component of the logging section.+ */+ val loggingComponent: LoggingComponent- sealed interface Output {+ // TODO Add ThreadDumpComponent once available- /**- * Output that is returned when the user logs out.- */- data object UserLoggedOut : Output- }+ /**+ * Factory method to create a [MainViewModel] instance.+ */+ fun createMainViewModel(): MainViewModel}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/navigation/TabNavigationComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/domain/MainEvent.ktsimilarity index 72%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/navigation/TabNavigationComponent.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/domain/MainEvent.ktindex 7c5b7d4f57b..7f6f823e726 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/navigation/TabNavigationComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/domain/MainEvent.kt@@ -15,15 +15,15 @@* limitations under the License.*/-package org.apache.solr.ui.components.navigation+package org.apache.solr.ui.components.main.domain-import com.arkivanov.decompose.router.slot.ChildSlot-import com.arkivanov.decompose.value.Value-import kotlinx.serialization.Serializable--interface TabNavigationComponent<T : Any, C : Any> {-- val tabSlot: Value<ChildSlot<T, C>>+/**+ * Events emitted by the main screen that are meant to be handled by the parent.+ */+sealed interface MainEvent {- fun onNavigate(tab: T)+ /**+ * Emitted when the user logs out.+ */+ data object UserLoggedOut : MainEvent}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/integration/DefaultMainComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/integration/DefaultMainComponent.ktindex d3374d0b49a..75eb163a165 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/integration/DefaultMainComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/integration/DefaultMainComponent.kt@@ -17,14 +17,7 @@package org.apache.solr.ui.components.main.integration-import com.arkivanov.decompose.router.stack.ChildStack-import com.arkivanov.decompose.router.stack.StackNavigation-import com.arkivanov.decompose.router.stack.bringToFront-import com.arkivanov.decompose.router.stack.childStack-import com.arkivanov.decompose.value.Value-import com.arkivanov.mvikotlin.core.store.StoreFactoryimport io.ktor.client.HttpClient-import kotlinx.serialization.Serializableimport org.apache.solr.ui.components.cluster.ClusterComponentimport org.apache.solr.ui.components.cluster.integration.DefaultClusterComponentimport org.apache.solr.ui.components.configsets.di.ConfigsetsComponent@@ -34,186 +27,30 @@ import org.apache.solr.ui.components.environment.integration.DefaultEnvironmentCimport org.apache.solr.ui.components.logging.LoggingComponentimport org.apache.solr.ui.components.logging.integration.DefaultLoggingComponentimport org.apache.solr.ui.components.main.MainComponent-import org.apache.solr.ui.components.main.MainComponent.Child-import org.apache.solr.ui.components.main.MainComponent.Output-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.views.navigation.MainMenu+import org.apache.solr.ui.components.main.viewmodel.MainViewModel-class DefaultMainComponent internal constructor(- componentContext: AppComponentContext,- storeFactory: StoreFactory,- destination: String? = null,- private val clusterComponent: (AppComponentContext) -> ClusterComponent,- private val configsetsComponent: () -> ConfigsetsComponent,- private val environmentComponent: (AppComponentContext) -> EnvironmentComponent,- private val loggingComponent: (AppComponentContext) -> LoggingComponent,- private val output: (Output) -> Unit,-) : MainComponent,- AppComponentContext by componentContext {-- private val navigation = StackNavigation<Configuration>()- private val stack = childStack(- source = navigation,- serializer = Configuration.serializer(),- initialStack = { calculateInitialStack(destination) },- handleBackButton = true,- childFactory = ::createChild,- )- override val childStack: Value<ChildStack<*, Child>> = stack-- constructor(- componentContext: AppComponentContext,- storeFactory: StoreFactory,- httpClient: HttpClient,- destination: String? = null,- output: (Output) -> Unit,- ) : this(- componentContext = componentContext,- storeFactory = storeFactory,- destination = destination,- output = output,- clusterComponent = { childContext ->- DefaultClusterComponent(- componentContext = childContext,- )- },- configsetsComponent = { DefaultConfigsetsComponent(httpClient = httpClient) },- environmentComponent = { childContext ->- DefaultEnvironmentComponent(- componentContext = childContext,- storeFactory = storeFactory,- httpClient = httpClient,- )- },- loggingComponent = { childContext ->- DefaultLoggingComponent(- componentContext = childContext,- storeFactory = storeFactory,- )- },- )+/**+ * Default implementation of the [MainComponent].+ *+ * @param httpClient The pre-configured HTTP client to use for the sections' operations.+ * @param destination The section to show initially, if any.+ */+class DefaultMainComponent(+ private val httpClient: HttpClient,+ private val destination: String? = null,+) : MainComponent {- override fun onNavigate(menuItem: MainMenu) = navigation.bringToFront(menuItem.toConfiguration())+ override val clusterComponent: ClusterComponent by lazy { DefaultClusterComponent() }- override fun onNavigateBack() {- TODO("Not yet implemented")+ override val configsetsComponent: ConfigsetsComponent by lazy {+ DefaultConfigsetsComponent(httpClient = httpClient)}- override fun onLogout() = output(Output.UserLoggedOut)-- /**- * Calculates the initial stack based on the destination provided.- */- private fun calculateInitialStack(destination: String?): List<Configuration> = listOf(- when (destination) {- "cluster" -> Configuration.Cluster- "configsets" -> Configuration.Configsets- "environment" -> Configuration.Environment- "logging" -> Configuration.Logging- else -> Configuration.Configsets- },- )-- private fun createChild(- configuration: Configuration,- componentContext: AppComponentContext,- ): Child = when (configuration) {- // TODO Uncomment once Dashboard available- // Configuration.Dashboard ->- // NavigationComponent.Child.Dashboard(dashboardComponent(componentContext))-- // TODO Uncomment once Metrics available- // Configuration.Metrics ->- // NavigationComponent.Child.Metrics(metricsComponent(componentContext))-- Configuration.Cluster -> Child.Cluster(clusterComponent(componentContext))-- // TODO Uncomment once Security available- // Configuration.Security ->- // NavigationComponent.Child.Security(securityComponent(componentContext))-- Configuration.Configsets -> Child.Configsets(configsetsComponent())-- // TODO Uncomment once Collections available- // Configuration.Collections ->- // NavigationComponent.Child.Collections(collectionsComponent(componentContext))-- // TODO Uncomment once QueriesAndOperations available- // Configuration.QueriesAndOperations ->- // NavigationComponent.Child.QueriesAndOperations(queriesAndOperationsComponent(componentContext))-- Configuration.Environment -> Child.Environment(environmentComponent(componentContext))-- Configuration.Logging -> Child.Logging(loggingComponent(componentContext))-- // TODO Uncomment once ThreadDump available- // Configuration.ThreadDump ->- // NavigationComponent.Child.ThreadDump(threadDumpComponent(componentContext))-- // TODO Remove else case once all destinations are available- else -> throw NotImplementedError("Navigation to $configuration not implemented yet.")+ override val environmentComponent: EnvironmentComponent by lazy {+ DefaultEnvironmentComponent(httpClient = httpClient)}- /**- * Configuration that provides information for navigating to supported destinations.- *- * This configuration is used by both UI and business logic and therefore publicly available.- * Note that configurations are usually private to the implementation and not available in the- * interface level (therefore neither in the UI). Providing this class in the interface- * simplifies additional mappings that would otherwise be necessary. Leaking the configuration- * with the component's interface prevents the implementations from storing sensible /- * component-internal information in the configurations. Therefore, if any implementation in the- * future needs to store information in the configuration, this interface should be replaced- * with an enum and mapped accordingly per implementation.- *- * Use this practice only if really necessary.- *- * Changes to this interface have impact on both UI and business logic.- */- @Serializable- private sealed interface Configuration {-- @Serializable- data object Dashboard : Configuration-- @Serializable- data object Metrics : Configuration-- @Serializable- data object Cluster : Configuration-- @Serializable- data object Security : Configuration-- @Serializable- data object Configsets : Configuration+ override val loggingComponent: LoggingComponent by lazy { DefaultLoggingComponent() }- @Serializable- data object Collections : Configuration-- @Serializable- data object IndexAndQuery : Configuration-- @Serializable- data object Environment : Configuration-- @Serializable- data object Logging : Configuration-- @Serializable- data object ThreadDump : Configuration- }-- private fun MainMenu.toConfiguration(): Configuration = when (this) {- MainMenu.Dashboard -> Configuration.Dashboard- MainMenu.Metrics -> Configuration.Metrics- MainMenu.Cluster -> Configuration.Cluster- MainMenu.Security -> Configuration.Security- MainMenu.Configsets -> Configuration.Configsets- MainMenu.Collections -> Configuration.Collections- MainMenu.IndexAndQuery -> Configuration.IndexAndQuery- MainMenu.Environment -> Configuration.Environment- MainMenu.Logging -> Configuration.Logging- MainMenu.ThreadDump -> Configuration.ThreadDump- }+ override fun createMainViewModel(): MainViewModel = MainViewModel(destination = destination)}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/integration/Mappers.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/integration/Mappers.ktdeleted file mode 100644index e0d85987371..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/integration/Mappers.kt+++ /dev/null@@ -1,34 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.main.integration--import org.apache.solr.ui.components.main.MainComponent-import org.apache.solr.ui.components.root.RootComponent-import org.apache.solr.ui.views.navigation.MainMenu--val MainComponent.Child.asMainMenu: MainMenu- get() = when (this) {- // TODO Add additional mappings once more children are supported- is MainComponent.Child.Cluster -> MainMenu.Cluster-- is MainComponent.Child.Configsets -> MainMenu.Configsets-- is MainComponent.Child.Environment -> MainMenu.Environment-- is MainComponent.Child.Logging -> MainMenu.Logging- }diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/viewmodel/MainViewModel.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/viewmodel/MainViewModel.ktnew file mode 100644index 00000000000..95df51c08a5--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/main/viewmodel/MainViewModel.kt@@ -0,0 +1,139 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.main.viewmodel++import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.snapshots.Snapshot+import androidx.compose.runtime.snapshots.SnapshotStateList+import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import androidx.navigation3.runtime.NavKey+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.launch+import kotlinx.serialization.Serializable+import org.apache.solr.ui.components.main.domain.MainEvent+import org.apache.solr.ui.views.navigation.MainMenu++/**+ * View model of the main section that is used as base for users with access.+ *+ * Note that this section can be accessed if the user is either authenticated or if the Solr+ * instance accessed does not have any authentication enabled.+ *+ * @param destination The section to show initially. Falls back to the configsets section if the+ * destination is missing or not supported.+ */+class MainViewModel(destination: String? = null) : ViewModel() {++ /**+ * The back stack that holds the navigation state.+ */+ val backStack: SnapshotStateList<MainScene> = mutableStateListOf(initialScene(destination))++ /**+ * Events emitted by the view model.+ */+ val events: SharedFlow<MainEvent>+ field = MutableSharedFlow<MainEvent>(extraBufferCapacity = 1)++ /**+ * Handles navigation requests from a navigation menu. The destination is brought to the front+ * of the back stack, so that returning to a section keeps its state.+ *+ * @param menuItem The destination to navigate to.+ */+ fun navigate(menuItem: MainMenu) {+ val scene = menuItem.toScene()+ if (backStack.lastOrNull() == scene) return++ Snapshot.withMutableSnapshot {+ backStack.remove(scene)+ backStack.add(scene)+ }+ }++ /**+ * Navigates back to the previous section, if there is any.+ */+ fun navigateBack() {+ if (backStack.size > 1) backStack.removeLastOrNull()+ }++ /**+ * Handles logout requests.+ */+ fun logout() {+ viewModelScope.launch { events.emit(MainEvent.UserLoggedOut) }+ }++ /**+ * Calculates the initial scene based on the destination provided.+ */+ private fun initialScene(destination: String?): MainScene = when (destination) {+ "cluster" -> MainScene.Cluster+ "configsets" -> MainScene.Configsets+ "environment" -> MainScene.Environment+ "logging" -> MainScene.Logging+ else -> MainScene.Configsets+ }+}++/**+ * The sections of the main screen that can be navigated to.+ */+@Serializable+sealed interface MainScene : NavKey {++ @Serializable+ data object Cluster : MainScene++ @Serializable+ data object Configsets : MainScene++ @Serializable+ data object Environment : MainScene++ @Serializable+ data object Logging : MainScene+}++/**+ * Maps a menu item to the scene it leads to.+ */+private fun MainMenu.toScene(): MainScene = when (this) {+ // TODO Add additional mappings once more sections are supported+ MainMenu.Cluster -> MainScene.Cluster+ MainMenu.Configsets -> MainScene.Configsets+ MainMenu.Environment -> MainScene.Environment+ MainMenu.Logging -> MainScene.Logging++ // TODO Remove else case once all destinations are available+ else -> throw NotImplementedError("Navigation to $this not implemented yet.")+}++/**+ * The menu item that leads to this scene.+ */+val MainScene.menuItem: MainMenu+ get() = when (this) {+ MainScene.Cluster -> MainMenu.Cluster+ MainScene.Configsets -> MainMenu.Configsets+ MainScene.Environment -> MainMenu.Environment+ MainScene.Logging -> MainMenu.Logging+ }diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/RootComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/RootComponent.ktindex be742610ad8..33917a311ac 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/RootComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/RootComponent.kt@@ -17,28 +17,45 @@package org.apache.solr.ui.components.root-import com.arkivanov.decompose.router.stack.ChildStack-import com.arkivanov.decompose.value.Value+import io.ktor.http.Urlimport org.apache.solr.ui.components.auth.AuthenticationComponentimport org.apache.solr.ui.components.main.MainComponent+import org.apache.solr.ui.components.root.viewmodel.RootViewModelimport org.apache.solr.ui.components.start.StartComponent+import org.apache.solr.ui.domain.AuthMethod+import org.apache.solr.ui.domain.AuthOption/*** Root component used by each target as an entry point to the application.*- * This component checks the information available at start time and redirects the user accordingly.- * Implementations may check user session, access level, destination and more.+ * This component provides the components of the screens the user is redirected to, depending on+ * the information available at start time. Implementations may check user session, access level,+ * destination and more.*/interface RootComponent {- val childStack: Value<ChildStack<*, Child>>-- sealed interface Child {-- data class Start(val component: StartComponent) : Child-- data class Main(val component: MainComponent) : Child-- data class Authentication(val component: AuthenticationComponent) : Child- }+ /**+ * Factory method to create a [RootViewModel] instance.+ */+ fun createRootViewModel(): RootViewModel++ /**+ * Factory method to create the component of the start screen.+ */+ fun createStartComponent(): StartComponent++ /**+ * Factory method to create the component of the authentication screen.+ *+ * @param url The URL of the Solr instance the user is authenticating against.+ * @param methods The authentication methods that can be used to authenticate the user.+ */+ fun createAuthenticationComponent(url: Url, methods: List<AuthMethod>): AuthenticationComponent++ /**+ * Factory method to create the component of the main screen.+ *+ * @param authOption The option that was used to authenticate the user.+ */+ fun createMainComponent(authOption: AuthOption): MainComponent}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/integration/SimpleRootComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/integration/SimpleRootComponent.ktindex 7ab0a161ee1..57f4baab8d0 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/integration/SimpleRootComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/integration/SimpleRootComponent.kt@@ -17,30 +17,18 @@package org.apache.solr.ui.components.root.integration-import com.arkivanov.decompose.router.stack.ChildStack-import com.arkivanov.decompose.router.stack.StackNavigation-import com.arkivanov.decompose.router.stack.childStack-import com.arkivanov.decompose.router.stack.pop-import com.arkivanov.decompose.router.stack.pushNew-import com.arkivanov.decompose.router.stack.replaceAll-import com.arkivanov.decompose.value.Value-import com.arkivanov.mvikotlin.core.store.StoreFactoryimport io.ktor.client.HttpClientimport io.ktor.http.Url-import kotlinx.serialization.Serializableimport org.apache.solr.ui.components.auth.AuthenticationComponentimport org.apache.solr.ui.components.auth.integration.DefaultAuthenticationComponentimport org.apache.solr.ui.components.main.MainComponentimport org.apache.solr.ui.components.main.integration.DefaultMainComponentimport org.apache.solr.ui.components.root.RootComponent-import org.apache.solr.ui.components.root.RootComponent.Child.Authentication-import org.apache.solr.ui.components.root.RootComponent.Child.Main-import org.apache.solr.ui.components.root.RootComponent.Child.Start+import org.apache.solr.ui.components.root.viewmodel.RootViewModelimport org.apache.solr.ui.components.start.StartComponentimport org.apache.solr.ui.components.start.integration.DefaultStartComponentimport org.apache.solr.ui.domain.AuthMethodimport org.apache.solr.ui.domain.AuthOption-import org.apache.solr.ui.utils.AppComponentContextimport org.apache.solr.ui.utils.getDefaultClientimport org.apache.solr.ui.utils.getHttpClientWithAuthOption@@ -50,147 +38,30 @@ import org.apache.solr.ui.utils.getHttpClientWithAuthOption** This component is used only temporary and will be replaced in the future with an implementation* that checks the access level of the user before redirecting.+ *+ * @param httpClient The pre-configured HTTP client to use for connecting to a Solr instance.+ * @param destination The section to show initially after the user has access, if any.*/class SimpleRootComponent(- componentContext: AppComponentContext,- storeFactory: StoreFactory,- private val startComponent: (AppComponentContext, (StartComponent.Output) -> Unit) -> StartComponent,- private val mainComponent: (AppComponentContext, AuthOption, (MainComponent.Output) -> Unit) -> MainComponent,- private val authenticationComponent: AuthenticationComponentProducer,-) : RootComponent,- AppComponentContext by componentContext {+ private val httpClient: HttpClient,+ private val destination: String? = null,+) : RootComponent {- private val navigation = StackNavigation<Configuration>()- private val stack = childStack(- source = navigation,- serializer = Configuration.serializer(),- initialStack = { listOf(Configuration.Start) },- handleBackButton = true,- childFactory = ::createChild,- )+ override fun createRootViewModel(): RootViewModel = RootViewModel()- override val childStack: Value<ChildStack<*, RootComponent.Child>> = stack+ override fun createStartComponent(): StartComponent = DefaultStartComponent(httpClient = httpClient)- constructor(- componentContext: AppComponentContext,- storeFactory: StoreFactory,- httpClient: HttpClient,- destination: String? = null,- ) : this(- componentContext = componentContext,- storeFactory = storeFactory,- startComponent = { childContext, output ->- DefaultStartComponent(- componentContext = childContext,- storeFactory = storeFactory,- httpClient = httpClient,- output = output,- )- },- mainComponent = { childContext, authOption, output ->- DefaultMainComponent(- componentContext = childContext,- storeFactory = storeFactory,- httpClient = getHttpClientWithAuthOption(authOption),- destination = destination,- output = output,- )- },- authenticationComponent = { childContext, url, methods, output ->- DefaultAuthenticationComponent(- componentContext = childContext,- storeFactory = storeFactory,- httpClient = getDefaultClient(url),- url = url,- methods = methods,- output = output,- )- },+ override fun createAuthenticationComponent(+ url: Url,+ methods: List<AuthMethod>,+ ): AuthenticationComponent = DefaultAuthenticationComponent(+ httpClient = getDefaultClient(url),+ url = url,+ methods = methods,)- private fun createChild(- configuration: Configuration,- componentContext: AppComponentContext,- ): RootComponent.Child = when (configuration) {- is Configuration.Start -> Start(startComponent(componentContext, ::startOutput))-- is Configuration.Main -> Main(mainComponent(componentContext, configuration.authOption, ::mainOutput))-- is Configuration.Authentication -> Authentication(- authenticationComponent(- componentContext,- configuration.url,- configuration.methods,- ::authenticationOutput,- ),- )- }-- /**- * Output handler for any output returned by the [StartComponent].- *- * @param output The output returned by the start component implementation.- */- private fun startOutput(output: StartComponent.Output) = when (output) {- is StartComponent.Output.OnAuthRequired -> navigation.pushNew(- Configuration.Authentication(- url = output.url,- methods = output.methods,- ),- )-- is StartComponent.Output.OnConnected ->- navigation.replaceAll(Configuration.Main(authOption = AuthOption.None(url = output.url)))- }-- /**- * Output handler for any output returned by the [MainComponent].- *- * @param output The output returned by the main component implementation.- */- private fun mainOutput(output: MainComponent.Output) = when (output) {- is MainComponent.Output.UserLoggedOut -> navigation.replaceAll(Configuration.Start)- }-- /**- * Output handler for any output returned by the [AuthenticationComponent].- *- * @param output The output returned by the authentication component implementation.- */- private fun authenticationOutput(output: AuthenticationComponent.Output) = when (output) {- is AuthenticationComponent.Output.OnAuthenticated ->- navigation.replaceAll(Configuration.Main(authOption = output.option))-- is AuthenticationComponent.Output.OnAbort -> navigation.pop()- }-- @Serializable- private sealed interface Configuration {-- @Serializable- data object Start : Configuration-- /**- * Configuration for pending authentication actions.- *- * @property url The URL where the user is not authenticated.- * @property methods List of methods that can be used to authenticate the user- * again.- */- @Serializable- data class Authentication(val url: Url, val methods: List<AuthMethod>) : Configuration-- @Serializable- data class Main(val authOption: AuthOption) : Configuration- }+ override fun createMainComponent(authOption: AuthOption): MainComponent = DefaultMainComponent(+ httpClient = getHttpClientWithAuthOption(authOption),+ destination = destination,+ )}--/**- * The authentication component producer (alias)- */-private typealias AuthenticationComponentProducer = (- AppComponentContext,- Url,- List<AuthMethod>,- (AuthenticationComponent.Output) -> Unit,-) -> AuthenticationComponentdiff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/viewmodel/RootViewModel.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/viewmodel/RootViewModel.ktnew file mode 100644index 00000000000..bc83d1497be--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/root/viewmodel/RootViewModel.kt@@ -0,0 +1,124 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.root.viewmodel++import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.snapshots.Snapshot+import androidx.compose.runtime.snapshots.SnapshotStateList+import androidx.lifecycle.ViewModel+import androidx.navigation3.runtime.NavKey+import io.ktor.http.Url+import kotlinx.serialization.Serializable+import org.apache.solr.ui.components.auth.domain.AuthenticationEvent+import org.apache.solr.ui.components.main.domain.MainEvent+import org.apache.solr.ui.components.start.domain.StartEvent+import org.apache.solr.ui.domain.AuthMethod+import org.apache.solr.ui.domain.AuthOption++/**+ * View model that manages the navigation between the top-level screens of the application.+ *+ * The view model checks the events emitted by the screens and redirects the user accordingly.+ * This implementation does not check the user's access level and redirects to the requested+ * destination. It is used only temporary and will be replaced in the future with an implementation+ * that checks the access level of the user before redirecting.+ */+class RootViewModel : ViewModel() {++ /**+ * The back stack that holds the navigation state.+ */+ val backStack: SnapshotStateList<RootScene> = mutableStateListOf(RootScene.Start)++ /**+ * Event handler for any event emitted by the start screen.+ *+ * @param event The event emitted by the start screen.+ */+ fun onStartEvent(event: StartEvent) = when (event) {+ is StartEvent.AuthRequired -> backStack.add(+ RootScene.Authentication(+ url = event.url,+ methods = event.methods,+ ),+ )++ is StartEvent.Connected ->+ replaceAll(RootScene.Main(authOption = AuthOption.None(url = event.url)))+ }++ /**+ * Event handler for any event emitted by the authentication screen.+ *+ * @param event The event emitted by the authentication screen.+ */+ fun onAuthenticationEvent(event: AuthenticationEvent) = when (event) {+ is AuthenticationEvent.Authenticated ->+ replaceAll(RootScene.Main(authOption = event.option))++ is AuthenticationEvent.Aborted -> navigateBack()+ }++ /**+ * Event handler for any event emitted by the main screen.+ *+ * @param event The event emitted by the main screen.+ */+ fun onMainEvent(event: MainEvent) = when (event) {+ is MainEvent.UserLoggedOut -> replaceAll(RootScene.Start)+ }++ /**+ * Navigates back to the previous screen, if there is any.+ */+ fun navigateBack() {+ if (backStack.size > 1) backStack.removeLastOrNull()+ }++ private fun replaceAll(scene: RootScene) = Snapshot.withMutableSnapshot {+ backStack.clear()+ backStack.add(scene)+ }+}++/**+ * The top-level screens of the application.+ */+@Serializable+sealed interface RootScene : NavKey {++ @Serializable+ data object Start : RootScene++ /**+ * Scene for pending authentication actions.+ *+ * @property url The URL where the user is not authenticated.+ * @property methods List of methods that can be used to authenticate the user again.+ */+ @Serializable+ data class Authentication(val url: Url, val methods: List<AuthMethod>) : RootScene++ /**+ * Scene for users that have access.+ *+ * @property authOption The option that was used to authenticate the user.+ */+ @Serializable+ data class Main(val authOption: AuthOption) : RootScene+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/StartComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/StartComponent.ktindex 366afb0b945..c95366fbd2a 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/StartComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/StartComponent.kt@@ -17,59 +17,27 @@package org.apache.solr.ui.components.start-import io.ktor.http.Url-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.domain.AuthMethod-import org.jetbrains.compose.resources.StringResource+import org.apache.solr.ui.components.start.domain.ConnectUseCase+import org.apache.solr.ui.components.start.repository.StartRepository+import org.apache.solr.ui.components.start.viewmodel.StartViewModel/*** Component interface that represents the start screen.*/interface StartComponent {- val model: StateFlow<Model>-- /**- * Function for when the input value for the Solr URL changes.- *- * @param url The new URL value- */- fun onSolrUrlChange(url: String)-/**- * Called when the user wants to connect with the current [Model.url].+ * Dependencies provided by the application.*/- fun onConnect()+ val startRepository: StartRepository/**- * State class that holds values of the [StartComponent]'s sate.+ * Use case responsible for connecting to a Solr instance.*/- data class Model(- val url: String = "",- val isConnecting: Boolean = false,- val error: StringResource? = null,- )+ val connectUseCase: ConnectUseCase/**- * Possible component outputs that may be emitted to the parent component.+ * Factory method to create a [StartViewModel] instance.*/- sealed interface Output {-- /**- * Emitted when a connection to a Solr instance has been- * established and no authentication is required.- *- * @property url The URL the connection was established.- */- data class OnConnected(val url: Url) : Output-- /**- * Emitted when a connection to a Solr instance has been established and authentication- * is needed.- *- * @property url The URL the connection was established but requires authentication.- * @property methods List of authentication methods that can be used for authenticating.- */- data class OnAuthRequired(val url: Url, val methods: List<AuthMethod>) : Output- }+ fun createStartViewModel(): StartViewModel}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/HttpStartStoreClient.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/data/HttpStartRepository.ktsimilarity index 95%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/HttpStartStoreClient.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/data/HttpStartRepository.ktindex d3cdec5b2a8..3b9a1a4fe1f 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/HttpStartStoreClient.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/data/HttpStartRepository.kt@@ -15,7 +15,7 @@* limitations under the License.*/-package org.apache.solr.ui.components.start.integration+package org.apache.solr.ui.components.start.dataimport io.github.oshai.kotlinlogging.KotlinLoggingimport io.ktor.client.HttpClient@@ -28,7 +28,7 @@ import io.ktor.http.Urlimport io.ktor.http.pathimport kotlin.io.encoding.Base64import kotlinx.serialization.json.Json-import org.apache.solr.ui.components.start.store.StartStoreProvider+import org.apache.solr.ui.components.start.repository.StartRepositoryimport org.apache.solr.ui.data.SolrAuthDataimport org.apache.solr.ui.domain.AuthMethodimport org.apache.solr.ui.errors.UnauthorizedException@@ -37,7 +37,7 @@ import org.apache.solr.ui.errors.UnknownResponseExceptionprivate val logger = KotlinLogging.logger {}/**- * Client implementation of the [StartStoreProvider.Client] that makes use+ * Repository implementation of the [StartRepository] that makes use* of a preconfigured HTTP client for accessing the Solr API.** @property httpClient HTTP client to use for accessing the API. The client has to be@@ -45,9 +45,9 @@ private val logger = KotlinLogging.logger {}* should also include the necessary authentication data if authentication / authorization* is enabled.*/-class HttpStartStoreClient(+class HttpStartRepository(private val httpClient: HttpClient,-) : StartStoreProvider.Client {+) : StartRepository {override suspend fun connect(url: Url): Result<Unit> {val url = URLBuilder(url).apply {diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/Mappers.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/data/Mappers.ktsimilarity index 59%rename from ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/Mappers.ktrename to ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/data/Mappers.ktindex 798a3a86bfb..0a515e843bd 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/Mappers.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/data/Mappers.kt@@ -15,35 +15,12 @@* limitations under the License.*/-package org.apache.solr.ui.components.start.integration+package org.apache.solr.ui.components.start.data-import io.ktor.client.network.sockets.ConnectTimeoutException-import io.ktor.http.URLParserExceptionimport io.ktor.http.Url-import org.apache.solr.ui.components.start.StartComponent-import org.apache.solr.ui.components.start.store.StartStoreimport org.apache.solr.ui.data.SolrAuthDataimport org.apache.solr.ui.domain.AuthorizationFlowimport org.apache.solr.ui.domain.OAuthData-import org.apache.solr.ui.errors.HostNotFoundException-import org.apache.solr.ui.shared.generated.resources.Res-import org.apache.solr.ui.shared.generated.resources.error_invalid_url-import org.apache.solr.ui.shared.generated.resources.error_solr_host_not_found-import org.apache.solr.ui.shared.generated.resources.error_unknown--internal val startStateToModel: (StartStore.State) -> StartComponent.Model = {- StartComponent.Model(- url = it.url,- error = it.error?.let { error ->- when (error) {- is URLParserException -> Res.string.error_invalid_url- is HostNotFoundException -> Res.string.error_solr_host_not_found- is ConnectTimeoutException -> Res.string.error_solr_host_not_found- else -> Res.string.error_unknown- }- },- )-}internal fun SolrAuthData.toOAuthData() = OAuthData(clientId = clientId,diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/ConnectUseCase.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/ConnectUseCase.ktnew file mode 100644index 00000000000..3119ca434ba--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/ConnectUseCase.kt@@ -0,0 +1,63 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.start.domain++import io.ktor.http.Url+import org.apache.solr.ui.domain.AuthMethod++/**+ * Use case for connecting to a Solr instance.+ */+interface ConnectUseCase {++ /**+ * Tries to connect to the Solr instance at the given [url].+ *+ * @param url The URL of the Solr instance. If blank, the default Solr URL is used.+ * @return The result of the connection attempt.+ */+ suspend operator fun invoke(url: String): ConnectResult+}++/**+ * Result of a connection attempt.+ */+sealed interface ConnectResult {++ /**+ * The connection was established and no authentication is required.+ *+ * @property url URL of the Solr instance.+ */+ data class Connected(val url: Url) : ConnectResult++ /**+ * A Solr server was found, but authentication is required.+ *+ * @property url URL of the Solr instance that requires authentication.+ * @property methods The supported authentication methods.+ */+ data class AuthRequired(val url: Url, val methods: List<AuthMethod>) : ConnectResult++ /**+ * The connection could not be established.+ *+ * @property error The error that occurred.+ */+ data class Failure(val error: Throwable) : ConnectResult+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/DefaultConnectUseCase.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/DefaultConnectUseCase.ktnew file mode 100644index 00000000000..890240bd8fc--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/DefaultConnectUseCase.kt@@ -0,0 +1,63 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.start.domain++import io.ktor.http.URLParserException+import io.ktor.http.parseUrl+import kotlin.coroutines.cancellation.CancellationException+import org.apache.solr.ui.components.start.repository.StartRepository+import org.apache.solr.ui.errors.UnauthorizedException+import org.apache.solr.ui.utils.defaultSolrUrl+import org.apache.solr.ui.utils.parseError++internal class DefaultConnectUseCase(+ private val repository: StartRepository,+) : ConnectUseCase {++ override suspend fun invoke(url: String): ConnectResult {+ val urlValue = url.ifBlank { defaultSolrUrl() }+ val solrUrl = parseUrl(urlValue) ?: return ConnectResult.Failure(+ URLParserException(+ urlString = urlValue,+ cause = Error("Invalid URL"),+ ),+ )++ return try {+ repository.connect(solrUrl).fold(+ // Solr server found with no auth active+ onSuccess = { ConnectResult.Connected(solrUrl) },+ onFailure = { error ->+ if (error is UnauthorizedException && error.methods.isNotEmpty()) {+ // Solr server found, but user is unauthorized+ ConnectResult.AuthRequired(url = solrUrl, methods = error.methods)+ } else {+ // Includes Solr servers that responded with an unauthorized error that+ // cannot be processed (supported method or missing information)+ ConnectResult.Failure(error)+ }+ },+ )+ } catch (e: CancellationException) {+ throw e+ } catch (e: Throwable) {+ // error thrown here is platform-specific and needs further parsing+ ConnectResult.Failure(parseError(e))+ }+ }+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/StartEvent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/StartEvent.ktnew file mode 100644index 00000000000..0504486fe1d--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/domain/StartEvent.kt@@ -0,0 +1,44 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.start.domain++import io.ktor.http.Url+import org.apache.solr.ui.domain.AuthMethod++/**+ * Events emitted by the start screen that are meant to be handled by the parent.+ */+sealed interface StartEvent {++ /**+ * Emitted when a connection to a Solr instance has been+ * established and no authentication is required.+ *+ * @property url The URL the connection was established.+ */+ data class Connected(val url: Url) : StartEvent++ /**+ * Emitted when a connection to a Solr instance has been established and authentication+ * is needed.+ *+ * @property url The URL the connection was established but requires authentication.+ * @property methods List of authentication methods that can be used for authenticating.+ */+ data class AuthRequired(val url: Url, val methods: List<AuthMethod>) : StartEvent+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/DefaultStartComponent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/DefaultStartComponent.ktindex a16a91dbf5c..3276a262e4a 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/DefaultStartComponent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/integration/DefaultStartComponent.kt@@ -17,63 +17,38 @@package org.apache.solr.ui.components.start.integration-import com.arkivanov.mvikotlin.core.instancekeeper.getStore-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.labels-import com.arkivanov.mvikotlin.extensions.coroutines.stateFlowimport io.ktor.client.HttpClient-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.flow.launchIn-import kotlinx.coroutines.flow.onEachimport org.apache.solr.ui.components.start.StartComponent-import org.apache.solr.ui.components.start.store.StartStore-import org.apache.solr.ui.components.start.store.StartStore.Intent-import org.apache.solr.ui.components.start.store.StartStoreProvider-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.utils.coroutineScope-import org.apache.solr.ui.utils.map-+import org.apache.solr.ui.components.start.data.HttpStartRepository+import org.apache.solr.ui.components.start.domain.ConnectUseCase+import org.apache.solr.ui.components.start.domain.DefaultConnectUseCase+import org.apache.solr.ui.components.start.repository.StartRepository+import org.apache.solr.ui.components.start.viewmodel.StartViewModel+import org.apache.solr.ui.utils.AppDispatchers+import org.apache.solr.ui.utils.platformDispatchers++/**+ * Default implementation of the [StartComponent].+ *+ * This implementation is using HTTP for establishing connections.+ *+ * @param httpClient The pre-configured HTTP client to use for connection attempts.+ */class DefaultStartComponent(- componentContext: AppComponentContext,- storeFactory: StoreFactory,httpClient: HttpClient,- output: (StartComponent.Output) -> Unit,-) : StartComponent,- AppComponentContext by componentContext {+ private val dispatchers: AppDispatchers = platformDispatchers(),+) : StartComponent {- private val mainScope = coroutineScope(SupervisorJob() + mainContext)- private val ioScope = coroutineScope(SupervisorJob() + ioContext)-- private val store = instanceKeeper.getStore {- StartStoreProvider(- storeFactory = storeFactory,- client = HttpStartStoreClient(httpClient),- mainContext = mainScope.coroutineContext,- ioContext = ioScope.coroutineContext,- ).provide()+ override val startRepository: StartRepository by lazy {+ HttpStartRepository(httpClient)}- @OptIn(ExperimentalCoroutinesApi::class)- override val model = store.stateFlow.map(mainScope, startStateToModel)-- init {- store.labels.onEach { label ->- when (label) {- is StartStore.Label.AuthRequired -> output(- StartComponent.Output.OnAuthRequired(- url = label.url,- methods = label.methods,- ),- )-- is StartStore.Label.Connected ->- output(StartComponent.Output.OnConnected(url = label.url))- }- }.launchIn(mainScope)+ override val connectUseCase: ConnectUseCase by lazy {+ DefaultConnectUseCase(startRepository)}- override fun onSolrUrlChange(url: String) = store.accept(Intent.UpdateSolrUrl(url))-- override fun onConnect() = store.accept(Intent.Connect)+ override fun createStartViewModel(): StartViewModel = StartViewModel(+ connectUseCase = connectUseCase,+ dispatchers = dispatchers,+ )}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/repository/StartRepository.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/repository/StartRepository.ktnew file mode 100644index 00000000000..e23d114ecba--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/repository/StartRepository.kt@@ -0,0 +1,34 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.start.repository++import io.ktor.http.Url++/**+ * Repository interface for establishing connections to Solr instances.+ */+interface StartRepository {++ /**+ * Tries to connect to a Solr instance with the given URL.+ *+ * @param url The Solr URL to connect to.+ * @return Result of whether the connection was established.+ */+ suspend fun connect(url: Url): Result<Unit>+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/store/StartStore.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/store/StartStore.ktdeleted file mode 100644index 3b1e85fd298..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/store/StartStore.kt+++ /dev/null@@ -1,77 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.start.store--import com.arkivanov.mvikotlin.core.store.Store-import io.ktor.http.Url-import org.apache.solr.ui.components.start.store.StartStore.Intent-import org.apache.solr.ui.components.start.store.StartStore.Label-import org.apache.solr.ui.components.start.store.StartStore.State-import org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.utils.defaultSolrUrl--/**- * State store interface of the start screen.- *- * Implementations of this state store manage detailed information of the start screen.- */-internal interface StartStore : Store<Intent, State, Label> {-- /**- * Intent for interacting with the start store.- */- sealed interface Intent {-- /**- * Intent for updating the current Solr URL.- */- data class UpdateSolrUrl(val url: String) : Intent-- /**- * Intent for initiating a new connection to a Solr instance.- */- data object Connect : Intent- }-- sealed interface Label {-- /**- * Label that is published when a connection to a Solr instance has been established- * successful.- *- * @property url URL of the Solr instance.- */- data class Connected(val url: Url) : Label-- /**- * Label that is published when a Solr server was found, but authentication is required.- *- * @property url URL of the Solr instance that requires authentication.- * @property methods The supported authentication methods.- */- data class AuthRequired(val url: Url, val methods: List<AuthMethod>) : Label- }-- /**- * State class that holds the data of the [StartStore].- */- data class State(- val url: String = "",- val error: Throwable? = null,- )-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/store/StartStoreProvider.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/store/StartStoreProvider.ktdeleted file mode 100644index df7ecf70e20..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/store/StartStoreProvider.kt+++ /dev/null@@ -1,169 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.start.store--import com.arkivanov.mvikotlin.core.store.Reducer-import com.arkivanov.mvikotlin.core.store.SimpleBootstrapper-import com.arkivanov.mvikotlin.core.store.Store-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.extensions.coroutines.CoroutineExecutor-import io.ktor.http.URLParserException-import io.ktor.http.Url-import io.ktor.http.parseUrl-import kotlin.coroutines.CoroutineContext-import kotlinx.coroutines.CoroutineExceptionHandler-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import org.apache.solr.ui.components.start.store.StartStore.Intent-import org.apache.solr.ui.components.start.store.StartStore.Label-import org.apache.solr.ui.components.start.store.StartStore.State-import org.apache.solr.ui.errors.UnauthorizedException-import org.apache.solr.ui.utils.defaultSolrUrl-import org.apache.solr.ui.utils.parseError--/**- * Store provider that [provide]s instances of [StartStore].- *- * @property storeFactory Store factory to use for creating the store.- * @property client Client implementation to use for resolving [Intent]s.- * @property ioContext Coroutine context used for IO activity.- */-internal class StartStoreProvider(- private val storeFactory: StoreFactory,- private val client: Client,- private val mainContext: CoroutineContext,- private val ioContext: CoroutineContext,-) {-- fun provide(): StartStore = object :- StartStore,- Store<Intent, State, Label> by storeFactory.create(- name = "StartStore",- initialState = State(),- bootstrapper = SimpleBootstrapper(),- executorFactory = ::ExecutorImpl,- reducer = ReducerImpl,- ) {}-- private sealed interface Message {-- /**- * Message that is dispatched when the stored Solr URL is updated.- *- * @property url The new Solr URL.- */- data class UrlUpdated(val url: String) : Message-- /**- * Message that is dispatch when an unknown error occurs during connection.- *- * @property error Error that was thrown.- */- data class ConnectionFailed(val error: Throwable) : Message- }-- private inner class ExecutorImpl : CoroutineExecutor<Intent, Unit, State, Message, Label>(mainContext) {- override fun executeIntent(intent: Intent) {- when (intent) {- is Intent.UpdateSolrUrl -> dispatch(Message.UrlUpdated(intent.url))-- is Intent.Connect -> {- var urlValue = state().url- if (urlValue.isBlank()) urlValue = defaultSolrUrl()-- try {- val url = parseUrl(urlValue) ?: throw URLParserException(- urlString = urlValue,- cause = Error("Invalid URL"),- )-- scope.launch(- context = CoroutineExceptionHandler { _, throwable ->- // error returned here is platform-specific and needs further parsing- dispatch(Message.ConnectionFailed(error = parseError(throwable)))- },- ) {- withContext(ioContext) {- client.connect(url)- }.onSuccess {- // Solr server found with no auth active- publish(Label.Connected(url))- }.onFailure { error ->- handleConnectionError(error, url)- }- }- } catch (error: Exception) {- dispatch(Message.ConnectionFailed(error))- }- }- }- }-- /**- * Handles any connection error that may occur during a connection establishment.- *- * This function may dispatch [Message]s or publish [Label]s.- *- * @param error Error that occurred.- * @param url The URL that was used for the connection.- */- private fun handleConnectionError(error: Throwable, url: Url) = when (error) {- is UnauthorizedException -> {- if (error.methods.isEmpty()) {- // Solr server found but responded with an unauthorized error- // that cannot be processed (supported method or missing information)- dispatch(Message.ConnectionFailed(error))- } else {- // Solr server found, but user is unauthorized- publish(- Label.AuthRequired(- url = url,- methods = error.methods,- ),- )- }- }-- else -> dispatch(Message.ConnectionFailed(error))- }- }-- /**- * Reducer implementation that consumes [Message]s and updates the store's [State].- */- private object ReducerImpl : Reducer<State, Message> {- override fun State.reduce(msg: Message): State = when (msg) {- is Message.UrlUpdated -> copy(url = msg.url, error = null)- is Message.ConnectionFailed -> copy(error = msg.error)- }- }-- /**- * Client interface for fetching environment information.- */- interface Client {-- /**- * Tries to connect to a Solr instance with the given URL.- *- * @param url The Solr URL to connect to.- * @return Result of whether the connection was established.- */- suspend fun connect(url: Url): Result<Unit>- }-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/viewmodel/StartStateHolder.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/viewmodel/StartStateHolder.ktnew file mode 100644index 00000000000..35ba6b40cbc--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/viewmodel/StartStateHolder.kt@@ -0,0 +1,111 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.start.viewmodel++import io.ktor.client.network.sockets.ConnectTimeoutException+import io.ktor.http.URLParserException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import org.apache.solr.ui.components.start.domain.ConnectResult+import org.apache.solr.ui.components.start.domain.ConnectUseCase+import org.apache.solr.ui.components.start.domain.StartEvent+import org.apache.solr.ui.errors.HostNotFoundException+import org.apache.solr.ui.shared.generated.resources.Res+import org.apache.solr.ui.shared.generated.resources.error_invalid_url+import org.apache.solr.ui.shared.generated.resources.error_solr_host_not_found+import org.apache.solr.ui.shared.generated.resources.error_unknown+import org.apache.solr.ui.utils.AppDispatchers+import org.jetbrains.compose.resources.StringResource++/**+ * State holder of the start screen that manages the Solr URL and connection attempts.+ */+class StartStateHolder(+ private val scope: CoroutineScope,+ private val connectUseCase: ConnectUseCase,+ private val dispatchers: AppDispatchers,+) {++ /**+ * UI state of the start screen.+ */+ val uiState: StateFlow<StartUiState>+ field = MutableStateFlow(StartUiState())++ /**+ * Events emitted by the state holder.+ */+ val events: SharedFlow<StartEvent>+ field = MutableSharedFlow<StartEvent>(extraBufferCapacity = 1)++ /**+ * Updates the Solr URL and resets any error.+ *+ * @param url The new Solr URL value.+ */+ fun changeSolrUrl(url: String) = uiState.update { it.copy(url = url, error = null) }++ /**+ * Connects to the Solr instance with the current [StartUiState.url].+ */+ fun connect() {+ scope.launch {+ val result = withContext(dispatchers.io) {+ connectUseCase(uiState.value.url)+ }++ when (result) {+ is ConnectResult.Connected -> events.emit(StartEvent.Connected(result.url))++ is ConnectResult.AuthRequired -> events.emit(+ StartEvent.AuthRequired(url = result.url, methods = result.methods),+ )++ is ConnectResult.Failure -> uiState.update {+ it.copy(error = result.error.toErrorResource())+ }+ }+ }+ }+}++/**+ * UI state of the start screen.+ *+ * @property url The Solr URL entered by the user.+ * @property isConnecting Whether a connection is currently being established.+ * @property error The error that occurred during the last connection attempt, if any.+ */+data class StartUiState(+ val url: String = "",+ val isConnecting: Boolean = false,+ val error: StringResource? = null,+)++private fun Throwable.toErrorResource(): StringResource = when (this) {+ is URLParserException -> Res.string.error_invalid_url+ is HostNotFoundException -> Res.string.error_solr_host_not_found+ is ConnectTimeoutException -> Res.string.error_solr_host_not_found+ else -> Res.string.error_unknown+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/viewmodel/StartViewModel.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/viewmodel/StartViewModel.ktnew file mode 100644index 00000000000..e0586f760d8--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/components/start/viewmodel/StartViewModel.kt@@ -0,0 +1,57 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.start.viewmodel++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import org.apache.solr.ui.components.start.domain.ConnectUseCase+import org.apache.solr.ui.utils.AppDispatchers++class StartViewModel(+ connectUseCase: ConnectUseCase,+ dispatchers: AppDispatchers,+) : ViewModel() {++ private val startState = StartStateHolder(+ scope = viewModelScope,+ connectUseCase = connectUseCase,+ dispatchers = dispatchers,+ )++ /**+ * UI state of the start screen.+ */+ val uiState = startState.uiState++ /**+ * Events emitted by the start screen.+ */+ val events = startState.events++ /**+ * Updates the Solr URL.+ *+ * @param url The new Solr URL value.+ */+ fun changeSolrUrl(url: String) = startState.changeSolrUrl(url)++ /**+ * Connects to the Solr instance with the current URL.+ */+ fun connect() = startState.connect()+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/CoroutineScopeExt.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/CoroutineScopeExt.ktdeleted file mode 100644index 9296fe90d7b..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/CoroutineScopeExt.kt+++ /dev/null@@ -1,72 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.utils--import com.arkivanov.essenty.lifecycle.Lifecycle-import com.arkivanov.essenty.lifecycle.LifecycleOwner-import com.arkivanov.essenty.lifecycle.doOnDestroy-import kotlin.coroutines.CoroutineContext-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.cancel-import kotlinx.coroutines.flow.SharingStarted-import kotlinx.coroutines.flow.StateFlow-import kotlinx.coroutines.flow.map-import kotlinx.coroutines.flow.stateIn--/**- * Function for creating a coroutine scope for a [lifecycle] that cancels automatically- * when [lifecycle] is destroyed.- *- * @param context The [CoroutineContext] to use for the scope.- * @param lifecycle The lifecycle this coroutine should be aware of.- *- * @return Returns a lifecycle-aware coroutine scope.- */-fun CoroutineScope(context: CoroutineContext, lifecycle: Lifecycle): CoroutineScope {- val scope = CoroutineScope(context)- lifecycle.doOnDestroy(scope::cancel)- return scope-}--/**- * Function for creating a coroutine scope from a lifecycle that cancels automatically- * when lifecycle is destroyed.- *- * @param context The [CoroutineContext] to use for the scope.- *- * @return Returns a lifecycle-aware coroutine scope.- */-fun LifecycleOwner.coroutineScope(context: CoroutineContext): CoroutineScope = CoroutineScope(context, lifecycle)--/**- * StateFlow mapping function that maps one stateflow to another stateflow applying- * [mapper] on the state. [coroutineScope] used for the mapping work.- *- * @param coroutineScope The scope in which the mapping should be executed- * @param mapper The mapper function to use on [T].- * @param T The state to map- * @param M the mapped / resulting state- */-fun <T, M> StateFlow<T>.map(- coroutineScope: CoroutineScope,- mapper: (value: T) -> M,-): StateFlow<M> = map { mapper(it) }.stateIn(- coroutineScope,- SharingStarted.Eagerly,- mapper(value),-)diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/DefaultAppComponentContext.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/DefaultAppComponentContext.ktdeleted file mode 100644index e648bf68045..00000000000--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/utils/DefaultAppComponentContext.kt+++ /dev/null@@ -1,56 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.utils--import com.arkivanov.decompose.ComponentContext-import com.arkivanov.decompose.ComponentContextFactory-import com.arkivanov.essenty.backhandler.BackHandlerOwner-import com.arkivanov.essenty.instancekeeper.InstanceKeeperOwner-import com.arkivanov.essenty.lifecycle.LifecycleOwner-import com.arkivanov.essenty.statekeeper.StateKeeperOwner-import kotlin.coroutines.CoroutineContext--/**- * Default implementation of the [AppComponentContext]. Can be also used in tests with test-specific- * coroutine contexts.- */-class DefaultAppComponentContext(- componentContext: ComponentContext,- override val mainContext: CoroutineContext,- override val ioContext: CoroutineContext,-) : AppComponentContext,- LifecycleOwner by componentContext,- StateKeeperOwner by componentContext,- InstanceKeeperOwner by componentContext,- BackHandlerOwner by componentContext {-- override val componentContextFactory: ComponentContextFactory<AppComponentContext> =- ComponentContextFactory { lifecycle, stateKeeper, instanceKeeper, backHandler ->- val ctx = componentContext.componentContextFactory(- lifecycle = lifecycle,- stateKeeper = stateKeeper,- instanceKeeper = instanceKeeper,- backHandler = backHandler,- )- DefaultAppComponentContext(- componentContext = ctx,- mainContext = mainContext,- ioContext = ioContext,- )- }-}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/BasicAuthContent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/BasicAuthContent.ktindex 8c9cdcae90a..dd1f79c1c55 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/BasicAuthContent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/BasicAuthContent.kt@@ -25,13 +25,11 @@ import androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.text.input.PasswordVisualTransformationimport androidx.compose.ui.unit.dp-import org.apache.solr.ui.components.auth.BasicAuthComponent+import org.apache.solr.ui.components.auth.viewmodel.BasicAuthUiStateimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.action_sign_in_with_credentialsimport org.apache.solr.ui.shared.generated.resources.authenticating@@ -46,24 +44,28 @@ import org.jetbrains.compose.resources.stringResource* The basic auth content is a form where the user can provide credentials to authenticate and* sign in to a Solr instance.*- * @param component The [BasicAuthComponent] that is handling the interactions with this composable.+ * @param uiState The state of the basic auth form to render.+ * @param onChangeUsername Called when the user changes the username.+ * @param onChangePassword Called when the user changes the password.+ * @param onAuthenticate Called when the user wants to authenticate with the credentials.* @param modifier Modifier that is applied to the root of this composable.* @param isAuthenticating Whether the user is currently being authenticated. This disables the inputs* and updates the text shown in the button.*/@Composablefun BasicAuthContent(- component: BasicAuthComponent,+ uiState: BasicAuthUiState,+ onChangeUsername: (String) -> Unit,+ onChangePassword: (String) -> Unit,+ onAuthenticate: () -> Unit,modifier: Modifier = Modifier,isAuthenticating: Boolean = true,) = Column(modifier = modifier,verticalArrangement = Arrangement.spacedBy(16.dp),) {- val model by component.model.collectAsState()-Text(- text = model.realm?.let {+ text = uiState.realm?.let {stringResource(Res.string.desc_sign_in_with_credentials_to_realm, it)} ?: stringResource(Res.string.desc_sign_in_with_credentials),style = MaterialTheme.typography.bodyMedium,@@ -71,29 +73,29 @@ fun BasicAuthContent(OutlinedTextField(modifier = Modifier.fillMaxWidth().testTag(tag = "username_input_field"),- value = model.username,+ value = uiState.username,singleLine = true,- isError = model.hasError,+ isError = uiState.hasError,label = { Text(stringResource(Res.string.label_username)) },- onValueChange = component::onChangeUsername,+ onValueChange = onChangeUsername,enabled = !isAuthenticating,)OutlinedTextField(modifier = Modifier.fillMaxWidth().testTag(tag = "password_input_field"),- value = model.password,+ value = uiState.password,singleLine = true,- isError = model.hasError,+ isError = uiState.hasError,label = { Text(stringResource(Res.string.label_password)) },visualTransformation = PasswordVisualTransformation(),- onValueChange = component::onChangePassword,+ onValueChange = onChangePassword,enabled = !isAuthenticating,)Column {SolrButton(modifier = Modifier.fillMaxWidth().testTag(tag = "sign_in_button"),- onClick = component::onAuthenticate,+ onClick = onAuthenticate,enabled = !isAuthenticating,) {Text(diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/OAuthContent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/OAuthContent.ktindex 14b75bbf6d2..64c912c45e1 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/OAuthContent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/OAuthContent.kt@@ -24,15 +24,10 @@ import androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValueimport androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalUriHandlerimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.unit.dp-import org.apache.solr.ui.components.auth.OAuthComponent-import org.apache.solr.ui.components.auth.store.OAuthStore+import org.apache.solr.ui.components.auth.viewmodel.OAuthUiStateimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.action_sign_in_with_identity_providerimport org.apache.solr.ui.shared.generated.resources.action_sign_in_with_realm@@ -46,7 +41,8 @@ import org.jetbrains.compose.resources.stringResource* The Oauth content is an input button where the user can click to authenticate and sign in to a* Solr instance via an identity provider.*- * @param component The [OAuthComponent] that is handling the interactions with this composable.+ * @param uiState The state of the OAuth authentication to render.+ * @param onAuthenticate Called when the user wants to authenticate via the identity provider.* @param modifier Modifier that is applied to the root of this composable.* @param isAuthenticating Whether the user is currently being authenticated. This disables the inputs* and updates the text shown in the button.@@ -55,7 +51,8 @@ import org.jetbrains.compose.resources.stringResource*/@Composablefun OAuthContent(- component: OAuthComponent,+ uiState: OAuthUiState,+ onAuthenticate: () -> Unit,modifier: Modifier = Modifier,isAuthenticating: Boolean = true,showSupportingText: Boolean = true,@@ -63,11 +60,9 @@ fun OAuthContent(modifier = modifier,verticalArrangement = Arrangement.spacedBy(16.dp),) {- val model by component.model.collectAsState()-if (showSupportingText) {Text(- text = model.realm?.let {+ text = uiState.realm?.let {stringResource(Res.string.desc_sign_in_with_oauth_to_realm, it)} ?: stringResource(Res.string.desc_sign_in_with_oauth),style = MaterialTheme.typography.bodyMedium,@@ -77,14 +72,14 @@ fun OAuthContent(Column {SolrButton(modifier = Modifier.fillMaxWidth().testTag(tag = "oauth_sign_in_button"),- onClick = component::onAuthenticate,+ onClick = onAuthenticate,enabled = !isAuthenticating,) {Text(text = if (isAuthenticating) {stringResource(Res.string.authenticating)} else {- model.realm?.let {+ uiState.realm?.let {stringResource(Res.string.action_sign_in_with_realm, it)} ?: stringResource(Res.string.action_sign_in_with_identity_provider)},@@ -96,15 +91,4 @@ fun OAuthContent()}}-- val uriHandler = LocalUriHandler.current- // Listen for labels once per composition- LaunchedEffect(component) {- component.labels.collect { label ->- when (label) {- is OAuthStore.Label.AuthenticationStarted -> uriHandler.openUri(uri = label.url.toString())- else -> Unit- }- }- }}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/UserAuthenticationContent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/UserAuthenticationContent.ktindex 4fda3172ff5..3bf139b8ad2 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/UserAuthenticationContent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/auth/UserAuthenticationContent.kt@@ -32,15 +32,20 @@ import androidx.compose.material3.Iconimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.scale+import androidx.compose.ui.platform.LocalUriHandlerimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.unit.dp-import com.arkivanov.decompose.extensions.compose.subscribeAsState+import androidx.lifecycle.viewmodel.compose.viewModelimport org.apache.solr.ui.components.auth.AuthenticationComponent+import org.apache.solr.ui.components.auth.domain.AuthenticationEvent+import org.apache.solr.ui.components.auth.viewmodel.AuthenticationUiStateimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.action_go_backimport org.apache.solr.ui.shared.generated.resources.cd_back_navigation@@ -59,20 +64,92 @@ import org.jetbrains.compose.resources.stringResource* The user authentication content is the composable that will check and display* the available authentication options to the user.*- * @param component The authentication component that manages the state of this composable.+ * @param component The authentication component that provides the view model of this composable.+ * @param onEvent Called when the authentication screen emits an event that the parent has to+ * handle, e.g. when the user has been authenticated.* @param modifier Modifier to apply to the root composable.*/@Composablefun UserAuthenticationContent(component: AuthenticationComponent,+ onEvent: (AuthenticationEvent) -> Unit,modifier: Modifier = Modifier,+) {+ val viewModel = viewModel { component.createAuthenticationViewModel() }+ val uiState by viewModel.uiState.collectAsState()+ val currentOnEvent by rememberUpdatedState(onEvent)+ val uriHandler = LocalUriHandler.current++ LaunchedEffect(viewModel) {+ viewModel.events.collect { currentOnEvent(it) }+ }++ LaunchedEffect(viewModel) {+ viewModel.authorizationUrls.collect { uriHandler.openUri(uri = it.toString()) }+ }++ val basicAuth = viewModel.basicAuth+ val oAuth = viewModel.oAuth++ UserAuthenticationContent(+ uiState = uiState,+ onAbort = viewModel::abort,+ modifier = modifier,+ basicAuthContent = basicAuth?.let { holder ->+ @Composable { contentModifier ->+ val basicAuthState by holder.uiState.collectAsState()++ BasicAuthContent(+ uiState = basicAuthState,+ onChangeUsername = holder::changeUsername,+ onChangePassword = holder::changePassword,+ onAuthenticate = holder::authenticate,+ modifier = contentModifier,+ isAuthenticating = uiState.isAuthenticating,+ )+ }+ },+ oAuthContent = oAuth?.let { holder ->+ @Composable { contentModifier, showSupportingText ->+ val oAuthState by holder.uiState.collectAsState()++ OAuthContent(+ uiState = oAuthState,+ onAuthenticate = holder::authenticate,+ modifier = contentModifier,+ isAuthenticating = uiState.isAuthenticating,+ showSupportingText = showSupportingText,+ )+ }+ },+ )+}++/**+ * The user authentication content is the composable that will check and display+ * the available authentication options to the user.+ *+ * @param uiState The state of the authentication screen to render.+ * @param onAbort Called when the user wants to abort the authentication.+ * @param modifier Modifier to apply to the root composable.+ * @param basicAuthContent The content for authenticating with credentials (basic auth), or+ * `null` if the method is not supported.+ * @param oAuthContent The content for authenticating with OAuth, or `null` if the method is not+ * supported. Its second parameter tells whether to show supporting text, which is not the case+ * if multiple authentication options are available.+ */+@Composable+fun UserAuthenticationContent(+ uiState: AuthenticationUiState,+ onAbort: () -> Unit,+ modifier: Modifier = Modifier,+ basicAuthContent: (@Composable (modifier: Modifier) -> Unit)? = null,+ oAuthContent: (@Composable (modifier: Modifier, showSupportingText: Boolean) -> Unit)? = null,) = Row(modifier = modifier,horizontalArrangement = Arrangement.spacedBy(16.dp),verticalAlignment = Alignment.CenterVertically,) {- val model by component.model.collectAsState()-Image(modifier = Modifier.weight(1f).align(Alignment.Bottom)@@ -88,7 +165,7 @@ fun UserAuthenticationContent(modifier = Modifier.weight(1f).padding(16.dp),) {SolrTextButton(- onClick = component::onAbort,+ onClick = onAbort,contentPadding = ButtonDefaults.TextButtonWithIconContentPadding,) {Icon(@@ -111,23 +188,13 @@ fun UserAuthenticationContent()Text(- text = stringResource(Res.string.desc_solr_instance_with_auth, model.url),+ text = stringResource(Res.string.desc_solr_instance_with_auth, uiState.url),style = MaterialTheme.typography.bodyMedium,)- val basicAuthState by component.basicAuthSlot.subscribeAsState()-- basicAuthState.child?.let { basicAuth ->- BasicAuthContent(- modifier = Modifier.testTag("basic_auth_content"),- component = basicAuth.instance,- isAuthenticating = model.isAuthenticating,- )- }+ basicAuthContent?.invoke(Modifier.testTag("basic_auth_content"))- val oauthState by component.oAuthSlot.subscribeAsState()-- val hasMultiAuth = basicAuthState.child != null && oauthState.child != null+ val hasMultiAuth = basicAuthContent != null && oAuthContent != nullif (hasMultiAuth) {Text(modifier = Modifier.testTag("separator_text"),@@ -135,16 +202,9 @@ fun UserAuthenticationContent()}- oauthState.child?.let { oAuth ->- OAuthContent(- modifier = Modifier.testTag("basic_auth_content"),- component = oAuth.instance,- isAuthenticating = model.isAuthenticating,- showSupportingText = !hasMultiAuth,- )- }+ oAuthContent?.invoke(Modifier.testTag("basic_auth_content"), !hasMultiAuth)- model.error?.let { error ->+ uiState.error?.let { error ->Text(modifier = Modifier.testTag("error_text"),text = stringResource(resource = error),diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/cluster/ClusterContent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/cluster/ClusterContent.ktindex 04e52af7335..b77d758f23a 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/cluster/ClusterContent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/cluster/ClusterContent.kt@@ -20,10 +20,13 @@ package org.apache.solr.ui.views.clusterimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.paddingimport androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModelimport org.apache.solr.ui.components.cluster.ClusterComponent-import org.apache.solr.ui.components.cluster.ClusterComponent.ClusterTab+import org.apache.solr.ui.components.cluster.viewmodel.ClusterTabimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.coresimport org.apache.solr.ui.shared.generated.resources.nodes@@ -36,9 +39,13 @@ fun ClusterContent(component: ClusterComponent,modifier: Modifier = Modifier,) = Column(modifier = modifier) {+ val viewModel = viewModel { component.createClusterViewModel() }+ val uiState by viewModel.uiState.collectAsState()+NavigationTabs(- component = component,- entries = ClusterTab.entries,+ tabs = ClusterTab.entries,+ selectedTab = uiState.selectedTab,+ onSelectTab = viewModel::selectTab,mapper = ::clusterTabsMapper,modifier = Modifier.padding(1.dp),)diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/environment/EnvironmentContent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/environment/EnvironmentContent.ktindex 2dc20f808eb..a016302b2cd 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/environment/EnvironmentContent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/environment/EnvironmentContent.kt@@ -27,7 +27,9 @@ import androidx.compose.runtime.getValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModelimport org.apache.solr.ui.components.environment.EnvironmentComponent+import org.apache.solr.ui.components.environment.viewmodel.EnvironmentUiState/*** Composable for loading the environment section.@@ -35,38 +37,56 @@ import org.apache.solr.ui.components.environment.EnvironmentComponent* This composable checks the window size and rearranges the content to achieve a better* representation.*- * @param component The component that holds the state of this composable and handles interactions.+ * @param component The component that provides the view model of this composable.* @param modifier Modifier to apply to the root composable.*/-@OptIn(ExperimentalLayoutApi::class)@Composablefun EnvironmentContent(component: EnvironmentComponent,modifier: Modifier = Modifier,+) {+ val viewModel = viewModel { component.createEnvironmentViewModel() }+ val uiState by viewModel.uiState.collectAsState()++ EnvironmentContent(uiState = uiState, modifier = modifier)+}++/**+ * Composable for rendering the environment section.+ *+ * This composable checks the window size and rearranges the content to achieve a better+ * representation.+ *+ * @param uiState The state of the environment to render.+ * @param modifier Modifier to apply to the root composable.+ */+@OptIn(ExperimentalLayoutApi::class)+@Composable+fun EnvironmentContent(+ uiState: EnvironmentUiState,+ modifier: Modifier = Modifier,) = FlowRow(modifier = modifier,horizontalArrangement = Arrangement.spacedBy(16.dp),verticalArrangement = Arrangement.spacedBy(16.dp),) {- val model by component.model.collectAsState()-val minChildWidth: Dp = 400.dpval maxChildWidth: Dp = 800.dpVersionsCard(modifier = Modifier.weight(1f).widthIn(min = minChildWidth, max = maxChildWidth),- versions = model.versions,- jvm = model.jvm,+ versions = uiState.lucene,+ jvm = uiState.jvm,)CommandLineArgumentsCard(modifier = Modifier.weight(1f).widthIn(min = minChildWidth, max = maxChildWidth),- arguments = model.jvm.jmx.commandLineArgs,+ arguments = uiState.jvm.jmx.commandLineArgs,)JavaPropertiesCard(modifier = Modifier.weight(1f).widthIn(min = minChildWidth, max = maxChildWidth),- properties = model.javaProperties,+ properties = uiState.javaProperties,)}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/main/MainContent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/main/MainContent.ktindex b6f88e3b7ce..bf6438ab68a 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/main/MainContent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/main/MainContent.kt@@ -25,70 +25,98 @@ import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.verticalScrollimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dp-import com.arkivanov.decompose.extensions.compose.stack.Children-import com.arkivanov.decompose.extensions.compose.subscribeAsState+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator+import androidx.navigation3.runtime.entryProvider+import androidx.navigation3.ui.NavDisplayimport org.apache.solr.ui.components.main.MainComponent-import org.apache.solr.ui.components.main.integration.asMainMenu+import org.apache.solr.ui.components.main.domain.MainEvent+import org.apache.solr.ui.components.main.viewmodel.MainScene+import org.apache.solr.ui.components.main.viewmodel.menuItemimport org.apache.solr.ui.views.cluster.ClusterContentimport org.apache.solr.ui.views.configsets.ConfigsetsSceneimport org.apache.solr.ui.views.environment.EnvironmentContentimport org.apache.solr.ui.views.logging.LoggingContentimport org.apache.solr.ui.views.navigation.NavigationSideBar+import org.apache.solr.ui.views.navigation.noPredictiveTransition+import org.apache.solr.ui.views.navigation.noTransition/*** The composable used for users that have already authenticated.*- * @param component Component that manages the state of the composable.+ * @param component Component that provides the view model of the composable.+ * @param onEvent Called when the main screen emits an event that the parent has to handle,+ * e.g. when the user logs out.*/@Composablefun MainContent(component: MainComponent,+ onEvent: (MainEvent) -> Unit,modifier: Modifier = Modifier,) {- val childStack by component.childStack.subscribeAsState()+ val viewModel = viewModel { component.createMainViewModel() }+ val currentOnEvent by rememberUpdatedState(onEvent)val scrollState = rememberScrollState()+ LaunchedEffect(viewModel) {+ viewModel.events.collect { currentOnEvent(it) }+ }+Row(modifier = modifier) {NavigationSideBar(modifier = Modifier.fillMaxHeight().width(224.dp),- selectedItem = childStack.active.instance.asMainMenu,- onNavigate = component::onNavigate,- onLogout = component::onLogout,+ selectedItem = viewModel.backStack.last().menuItem,+ onNavigate = viewModel::navigate,+ onLogout = viewModel::logout,)- Children(- stack = component.childStack,+ NavDisplay(+ backStack = viewModel.backStack,modifier = Modifier.weight(1f),- ) {- when (val child = it.instance) {- is MainComponent.Child.Cluster -> ClusterContent(- component = child.component,- modifier = Modifier.fillMaxWidth()- .verticalScroll(scrollState),- )+ onBack = viewModel::navigateBack,+ entryDecorators = listOf(rememberViewModelStoreNavEntryDecorator()),+ transitionSpec = noTransition(),+ popTransitionSpec = noTransition(),+ predictivePopTransitionSpec = noPredictiveTransition(),+ entryProvider = entryProvider {+ entry<MainScene.Cluster> {+ ClusterContent(+ component = component.clusterComponent,+ modifier = Modifier.fillMaxWidth()+ .verticalScroll(scrollState),+ )+ }- is MainComponent.Child.Configsets -> ConfigsetsScene(- component = child.component,- modifier = Modifier.fillMaxWidth()- .verticalScroll(scrollState),- )+ entry<MainScene.Configsets> {+ ConfigsetsScene(+ component = component.configsetsComponent,+ modifier = Modifier.fillMaxWidth()+ .verticalScroll(scrollState),+ )+ }- is MainComponent.Child.Environment -> EnvironmentContent(- component = child.component,- modifier = Modifier.fillMaxWidth()- .verticalScroll(scrollState)- .padding(16.dp),- )+ entry<MainScene.Environment> {+ EnvironmentContent(+ component = component.environmentComponent,+ modifier = Modifier.fillMaxWidth()+ .verticalScroll(scrollState)+ .padding(16.dp),+ )+ }- is MainComponent.Child.Logging -> LoggingContent(- component = child.component,- modifier = Modifier.fillMaxWidth(),- )- }- }+ entry<MainScene.Logging> {+ LoggingContent(+ component = component.loggingComponent,+ modifier = Modifier.fillMaxWidth(),+ )+ }+ },+ )}}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/navigation/NavTransitions.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/navigation/NavTransitions.ktnew file mode 100644index 00000000000..8157938db1a--- /dev/null+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/navigation/NavTransitions.kt@@ -0,0 +1,40 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.views.navigation++import androidx.compose.animation.AnimatedContentTransitionScope+import androidx.compose.animation.ContentTransform+import androidx.compose.animation.EnterTransition+import androidx.compose.animation.ExitTransition+import androidx.compose.animation.togetherWith+import androidx.navigation3.scene.Scene++/**+ * Transition spec for navigation displays that switches between destinations without animations.+ */+internal fun <T : Any> noTransition(): AnimatedContentTransitionScope<Scene<T>>.() -> ContentTransform = {+ EnterTransition.None togetherWith ExitTransition.None+}++/**+ * Predictive pop transition spec for navigation displays that switches between destinations+ * without animations.+ */+internal fun <T : Any> noPredictiveTransition(): AnimatedContentTransitionScope<Scene<T>>.(Int) -> ContentTransform = {+ EnterTransition.None togetherWith ExitTransition.None+}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/navigation/NavigationTabs.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/navigation/NavigationTabs.ktindex 18ab7a76e49..e457c27df4b 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/navigation/NavigationTabs.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/navigation/NavigationTabs.kt@@ -21,60 +21,23 @@ import androidx.compose.material3.PrimaryScrollableTabRowimport androidx.compose.material3.Tabimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable-import androidx.compose.runtime.getValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp-import com.arkivanov.decompose.extensions.compose.subscribeAsStateimport kotlin.enums.EnumEntries-import org.apache.solr.ui.components.navigation.TabNavigationComponentimport org.jetbrains.compose.resources.StringResourceimport org.jetbrains.compose.resources.stringResource/*** Navigation tabs that can be used for adding basic navigation elements to a section.*- * @param component The tab navigation component that manages the tab navigation.- * @param entries The entries to display in the navigation.- * @param mapper Mapper function that maps the entries to string resources, used to render the tab+ * @param tabs The tabs to display in the navigation.+ * @param selectedTab The currently selected tab.+ * @param onSelectTab Called when the user selects a tab.+ * @param mapper Mapper function that maps the tabs to string resources, used to render the tab* labels.* @param modifier Modifier to apply to the root element.*/-@Composable-fun <T : Enum<T>, C : Any> NavigationTabs(- component: TabNavigationComponent<T, C>,- entries: EnumEntries<T>, // TODO See if we can skip this parameter- mapper: (T) -> StringResource,- modifier: Modifier = Modifier,-) {- val slot by component.tabSlot.subscribeAsState()-- val currentTab = slot.child?.configuration- val currentTabIndex = currentTab?.ordinal ?: 0-- PrimaryScrollableTabRow(- modifier = modifier,- selectedTabIndex = currentTabIndex,- edgePadding = 16.dp,- ) {- entries.forEach { tab ->- val selected = currentTab == tab-- Tab(- selected = selected,- onClick = { component.onNavigate(tab) },- text = {- Text(- text = stringResource(mapper(tab)),- maxLines = 1,- overflow = TextOverflow.Ellipsis,- )- },- )- }- }-}-@Composablefun <T : Enum<T>> NavigationTabs(tabs: EnumEntries<T>,@@ -83,11 +46,9 @@ fun <T : Enum<T>> NavigationTabs(mapper: (T) -> StringResource,modifier: Modifier = Modifier,) {- val currentTabIndex = selectedTab.ordinal ?: 0-PrimaryScrollableTabRow(modifier = modifier,- selectedTabIndex = currentTabIndex,+ selectedTabIndex = selectedTab.ordinal,edgePadding = 16.dp,) {tabs.forEach { tab ->diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/root/RootContent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/root/RootContent.ktindex e75960b36b0..7f28692bde2 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/root/RootContent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/root/RootContent.kt@@ -21,47 +21,72 @@ import androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.runtime.Composable+import androidx.compose.runtime.rememberimport androidx.compose.ui.Modifier-import com.arkivanov.decompose.extensions.compose.stack.Children+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator+import androidx.navigation3.runtime.entryProvider+import androidx.navigation3.ui.NavDisplayimport org.apache.solr.ui.components.root.RootComponent+import org.apache.solr.ui.components.root.viewmodel.RootSceneimport org.apache.solr.ui.views.auth.UserAuthenticationContentimport org.apache.solr.ui.views.main.MainContentimport org.apache.solr.ui.views.navigation.Footer+import org.apache.solr.ui.views.navigation.noPredictiveTransition+import org.apache.solr.ui.views.navigation.noTransitionimport org.apache.solr.ui.views.start.StartContent/*** The root composable of the Compose application. This function is used as the shared entry* point of all targets.*- * @param component Component that manages the state of the root composable.+ * @param component Component that provides the view model of the root composable and the+ * components of the screens.*/@Composablefun RootContent(component: RootComponent,modifier: Modifier = Modifier,) {+ val viewModel = viewModel { component.createRootViewModel() }+Column(modifier = modifier.fillMaxSize()) {- Children(- stack = component.childStack,+ NavDisplay(+ backStack = viewModel.backStack,modifier = Modifier.weight(1f),- ) {- when (val child = it.instance) {- is RootComponent.Child.Start -> StartContent(- component = child.component,- modifier = Modifier.fillMaxSize(),- )+ onBack = viewModel::navigateBack,+ entryDecorators = listOf(rememberViewModelStoreNavEntryDecorator()),+ transitionSpec = noTransition(),+ popTransitionSpec = noTransition(),+ predictivePopTransitionSpec = noPredictiveTransition(),+ entryProvider = entryProvider {+ entry<RootScene.Start> {+ StartContent(+ component = remember { component.createStartComponent() },+ onEvent = viewModel::onStartEvent,+ modifier = Modifier.fillMaxSize(),+ )+ }- is RootComponent.Child.Main -> MainContent(- component = child.component,- modifier = Modifier.fillMaxSize(),- )+ entry<RootScene.Authentication> { scene ->+ UserAuthenticationContent(+ component = remember(scene) {+ component.createAuthenticationComponent(scene.url, scene.methods)+ },+ onEvent = viewModel::onAuthenticationEvent,+ modifier = Modifier.fillMaxSize(),+ )+ }- is RootComponent.Child.Authentication -> UserAuthenticationContent(- component = child.component,- modifier = Modifier.fillMaxSize(),- )- }- }+ entry<RootScene.Main> { scene ->+ MainContent(+ component = remember(scene) { component.createMainComponent(scene.authOption) },+ onEvent = viewModel::onMainEvent,+ modifier = Modifier.fillMaxSize(),+ )+ }+ },+ )Footer(modifier = Modifier.fillMaxWidth())}}diff --git a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/start/StartContent.kt b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/start/StartContent.ktindex 9b2332a79c1..2b96697c1dc 100644--- a/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/start/StartContent.kt+++ b/ui/shared/src/commonMain/kotlin/org/apache/solr/ui/views/start/StartContent.kt@@ -29,14 +29,19 @@ import androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.scaleimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModelimport org.apache.solr.ui.components.start.StartComponent+import org.apache.solr.ui.components.start.domain.StartEvent+import org.apache.solr.ui.components.start.viewmodel.StartUiStateimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.action_connectimport org.apache.solr.ui.shared.generated.resources.cd_solr_logo@@ -55,19 +60,50 @@ import org.jetbrains.compose.resources.stringResource/*** The composable used for users that have already authenticated.*- * @param component Component that manages the state of the composable.+ * @param component Component that provides the view model of the composable.+ * @param onEvent Called when the start screen emits an event that the parent has to handle,+ * e.g. when a connection has been established.*/@Composablefun StartContent(component: StartComponent,+ onEvent: (StartEvent) -> Unit,+ modifier: Modifier = Modifier,+) {+ val viewModel = viewModel { component.createStartViewModel() }+ val uiState by viewModel.uiState.collectAsState()+ val currentOnEvent by rememberUpdatedState(onEvent)++ LaunchedEffect(viewModel) {+ viewModel.events.collect { currentOnEvent(it) }+ }++ StartContent(+ uiState = uiState,+ onSolrUrlChange = viewModel::changeSolrUrl,+ onConnect = viewModel::connect,+ modifier = modifier,+ )+}++/**+ * The composable used for connecting to a Solr instance.+ *+ * @param uiState The state of the start screen to render.+ * @param onSolrUrlChange Called when the user changes the Solr URL.+ * @param onConnect Called when the user wants to connect to the Solr URL.+ */+@Composable+fun StartContent(+ uiState: StartUiState,+ onSolrUrlChange: (String) -> Unit,+ onConnect: () -> Unit,modifier: Modifier = Modifier,) = Row(modifier = modifier,horizontalArrangement = Arrangement.spacedBy(16.dp),verticalAlignment = Alignment.CenterVertically,) {- val model by component.model.collectAsState()-Image(modifier = Modifier.weight(1f).align(Alignment.Bottom)@@ -99,13 +135,13 @@ fun StartContent(SolrOutlinedTextField(modifier = Modifier.fillMaxWidth().testTag("solr_url_input"),- value = model.url,+ value = uiState.url,singleLine = true,- onValueChange = component::onSolrUrlChange,+ onValueChange = onSolrUrlChange,placeholder = { Text(text = defaultSolrUrl()) },- enabled = !model.isConnecting,+ enabled = !uiState.isConnecting,supportingText = {- model.error?.let {+ uiState.error?.let {Text(modifier = Modifier.testTag("input_error"),text = stringResource(it),@@ -119,12 +155,12 @@ fun StartContent(Column {SolrButton(modifier = Modifier.fillMaxWidth().testTag("connect_button"),- enabled = !model.isConnecting,- onClick = component::onConnect,+ enabled = !uiState.isConnecting,+ onClick = onConnect,) {Text(text = stringResource(- if (model.isConnecting) {+ if (uiState.isConnecting) {Res.string.connecting} else {Res.string.action_connect@@ -132,7 +168,7 @@ fun StartContent(),)}- if (model.isConnecting) {+ if (uiState.isConnecting) {SolrLinearProgressIndicator(modifier = Modifier.fillMaxWidth().testTag("loading_indicator"),)diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/TestAppComponentContext.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/TestAppComponentContext.ktdeleted file mode 100644index d78088ee834..00000000000--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/TestAppComponentContext.kt+++ /dev/null@@ -1,61 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui--import com.arkivanov.decompose.ComponentContext-import com.arkivanov.decompose.ComponentContextFactory-import com.arkivanov.decompose.DefaultComponentContext-import com.arkivanov.essenty.backhandler.BackHandlerOwner-import com.arkivanov.essenty.instancekeeper.InstanceKeeperOwner-import com.arkivanov.essenty.lifecycle.LifecycleOwner-import com.arkivanov.essenty.lifecycle.LifecycleRegistry-import com.arkivanov.essenty.statekeeper.StateKeeperOwner-import kotlin.coroutines.CoroutineContext-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.test.StandardTestDispatcher-import kotlinx.coroutines.test.TestCoroutineScheduler-import kotlinx.coroutines.test.UnconfinedTestDispatcher-import org.apache.solr.ui.utils.AppComponentContext--@OptIn(ExperimentalCoroutinesApi::class)-class TestAppComponentContext(- scheduler: TestCoroutineScheduler,- lifecycle: LifecycleRegistry = LifecycleRegistry(),- componentContext: ComponentContext = DefaultComponentContext(lifecycle = lifecycle),- override val mainContext: CoroutineContext = StandardTestDispatcher(scheduler),- override val ioContext: CoroutineContext = UnconfinedTestDispatcher(scheduler),-) : AppComponentContext,- LifecycleOwner by componentContext,- StateKeeperOwner by componentContext,- InstanceKeeperOwner by componentContext,- BackHandlerOwner by componentContext {-- override val componentContextFactory: ComponentContextFactory<AppComponentContext> =- ComponentContextFactory { lifecycle, stateKeeper, instanceKeeper, backHandler ->- val ctx = componentContext.componentContextFactory(- lifecycle = lifecycle,- stateKeeper = stateKeeper,- instanceKeeper = instanceKeeper,- backHandler = backHandler,- )- TestAppComponentContext(- scheduler = scheduler,- componentContext = ctx,- )- }-}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/integration/DefaultAuthenticationComponentIntegrationTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/integration/DefaultAuthenticationComponentIntegrationTest.ktdeleted file mode 100644index 028ee182bf8..00000000000--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/integration/DefaultAuthenticationComponentIntegrationTest.kt+++ /dev/null@@ -1,86 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.auth.integration--import com.arkivanov.decompose.DefaultComponentContext-import com.arkivanov.essenty.lifecycle.LifecycleRegistry-import com.arkivanov.essenty.lifecycle.resume-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.main.store.DefaultStoreFactory-import io.ktor.client.HttpClient-import io.ktor.http.Url-import kotlin.test.Test-import kotlin.test.assertNotNull-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.test.StandardTestDispatcher-import kotlinx.coroutines.test.TestCoroutineScheduler-import kotlinx.coroutines.test.TestScope-import kotlinx.coroutines.test.UnconfinedTestDispatcher-import kotlinx.coroutines.test.advanceUntilIdle-import kotlinx.coroutines.test.runTest-import org.apache.solr.ui.components.auth.AuthenticationComponent-import org.apache.solr.ui.components.auth.AuthenticationComponent.Output-import org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.utils.DefaultAppComponentContext--@OptIn(ExperimentalCoroutinesApi::class)-class DefaultAuthenticationComponentIntegrationTest {-- @Test- fun `GIVEN basic auth method THEN basicAuthSlot populated`() = runTest {- val component = createComponent(methods = listOf(AuthMethod.BasicAuthMethod(realm = "solr")))- advanceUntilIdle()-- assertNotNull(component.basicAuthSlot.value)- }-- /**- * Helper function for creating an instance of the [DefaultAuthenticationComponent].- */- @OptIn(ExperimentalCoroutinesApi::class)- private fun TestScope.createComponent(- lifecycle: LifecycleRegistry = LifecycleRegistry(),- scheduler: TestCoroutineScheduler = testScheduler,- componentContext: AppComponentContext = DefaultAppComponentContext(- componentContext = DefaultComponentContext(lifecycle = lifecycle),- mainContext = StandardTestDispatcher(scheduler),- ioContext = UnconfinedTestDispatcher(scheduler),- ),- storeFactory: StoreFactory = DefaultStoreFactory(),- httpClient: HttpClient = HttpClient(),- urlString: String = "",- methods: List<AuthMethod> = emptyList(),- output: (Output) -> Unit = {},- ): AuthenticationComponent {- val lifecycle = LifecycleRegistry()-- val component =- DefaultAuthenticationComponent(- componentContext = componentContext,- storeFactory = storeFactory,- httpClient = httpClient,- output = output,- url = Url(urlString),- methods = methods,- )-- lifecycle.resume()- return component- }-}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationStateHolderTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationStateHolderTest.ktnew file mode 100644index 00000000000..f7bcc510c66--- /dev/null+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/AuthenticationStateHolderTest.kt@@ -0,0 +1,63 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.auth.viewmodel++import io.ktor.client.HttpClient+import io.ktor.http.Url+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.TestScope+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.advanceUntilIdle+import kotlinx.coroutines.test.runTest+import org.apache.solr.ui.TestDispatchers+import org.apache.solr.ui.components.auth.data.HttpBasicAuthRepository+import org.apache.solr.ui.components.auth.domain.DefaultBasicAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.DefaultCreateOAuthAuthorizationUseCase+import org.apache.solr.ui.components.auth.domain.DefaultOAuthAuthenticateUseCase+import org.apache.solr.ui.domain.AuthMethod++@OptIn(ExperimentalCoroutinesApi::class)+class AuthenticationStateHolderTest {++ @Test+ fun `GIVEN basic auth method THEN basicAuth populated`() = runTest {+ val stateHolder = createStateHolder(methods = listOf(AuthMethod.BasicAuthMethod(realm = "solr")))+ advanceUntilIdle()++ assertNotNull(stateHolder.basicAuth)+ }++ /**+ * Helper function for creating an instance of the [AuthenticationStateHolder].+ */+ private fun TestScope.createStateHolder(+ httpClient: HttpClient = HttpClient(),+ urlString: String = "",+ methods: List<AuthMethod> = emptyList(),+ ) = AuthenticationStateHolder(+ scope = backgroundScope,+ url = Url(urlString),+ methods = methods,+ basicAuthenticateUseCase = DefaultBasicAuthenticateUseCase(HttpBasicAuthRepository(httpClient)),+ createOAuthAuthorizationUseCase = DefaultCreateOAuthAuthorizationUseCase(),+ oAuthAuthenticateUseCase = DefaultOAuthAuthenticateUseCase(FakeOAuthRepository { Result.failure(Exception()) }),+ dispatchers = TestDispatchers(UnconfinedTestDispatcher(scheduler = testScheduler)),+ )+}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/integration/DefaultBasicAuthComponentTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/BasicAuthStateHolderTest.ktsimilarity index 50%rename from ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/integration/DefaultBasicAuthComponentTest.ktrename to ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/BasicAuthStateHolderTest.ktindex c4b07bfacc5..9b4a6cf2e33 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/integration/DefaultBasicAuthComponentTest.kt+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/BasicAuthStateHolderTest.kt@@ -15,13 +15,8 @@* limitations under the License.*/-package org.apache.solr.ui.components.auth.integration+package org.apache.solr.ui.components.auth.viewmodel-import com.arkivanov.decompose.DefaultComponentContext-import com.arkivanov.essenty.lifecycle.LifecycleRegistry-import com.arkivanov.essenty.lifecycle.resume-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.main.store.DefaultStoreFactoryimport io.ktor.client.HttpClientimport io.ktor.client.engine.mock.MockRequestHandleScopeimport io.ktor.client.engine.mock.MockRequestHandler@@ -36,22 +31,21 @@ import kotlin.test.assertContainsimport kotlin.test.assertEqualsimport kotlin.test.assertIsimport kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.test.StandardTestDispatcher-import kotlinx.coroutines.test.TestCoroutineScheduler+import kotlinx.coroutines.launchimport kotlinx.coroutines.test.TestScopeimport kotlinx.coroutines.test.UnconfinedTestDispatcherimport kotlinx.coroutines.test.advanceUntilIdleimport kotlinx.coroutines.test.runTest-import org.apache.solr.ui.components.auth.BasicAuthComponent-import org.apache.solr.ui.components.auth.BasicAuthComponent.Output+import org.apache.solr.ui.TestDispatchers+import org.apache.solr.ui.components.auth.data.HttpBasicAuthRepository+import org.apache.solr.ui.components.auth.domain.BasicAuthEvent+import org.apache.solr.ui.components.auth.domain.DefaultBasicAuthenticateUseCaseimport org.apache.solr.ui.createMockEngineimport org.apache.solr.ui.domain.AuthMethodimport org.apache.solr.ui.errors.InvalidCredentialsException-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.utils.DefaultAppComponentContext@OptIn(ExperimentalCoroutinesApi::class)-class DefaultBasicAuthComponentTest {+class BasicAuthStateHolderTest {/*** A normal basic auth method with the realm "solr".@@ -85,105 +79,87 @@ class DefaultBasicAuthComponentTest {}@Test- fun `GIVEN valid credentials WHEN authenticate THEN Authenticated with BasicAuthMethod outputted`() = runTest {+ fun `GIVEN valid credentials WHEN authenticate THEN Authenticated with BasicAuthMethod emitted`() = runTest {val engine = createMockEngine(authenticationResponseHandler)- val outputs = mutableListOf<Output>()-- val component = createComponent(- httpClient = HttpClient(engine),- output = { outputs.add(it) },- method = method,- )- component.onChangeUsername(validUsername)- component.onChangePassword(validPassword)+ val stateHolder = createStateHolder(httpClient = HttpClient(engine), method = method)+ val events = collectEvents(stateHolder)++ stateHolder.changeUsername(validUsername)+ stateHolder.changePassword(validPassword)advanceUntilIdle()- component.onAuthenticate()+ stateHolder.authenticate()advanceUntilIdle()- assertContains(outputs, Output.Authenticating)- assertContains(outputs, Output.Authenticated(method, validUsername, validPassword))+ assertContains(events, BasicAuthEvent.AuthenticationStarted)+ assertContains(events, BasicAuthEvent.Authenticated(method, validUsername, validPassword))}@Test- fun `GIVEN invalid credentials WHEN authenticate THEN invalid credentials outputted`() = runTest {+ fun `GIVEN invalid credentials WHEN authenticate THEN invalid credentials emitted`() = runTest {val engine = createMockEngine(authenticationResponseHandler)- val outputs = mutableListOf<Output>()-- val component = createComponent(- httpClient = HttpClient(engine),- output = { outputs.add(it) },- )- component.onChangeUsername("invalidUser")- component.onChangePassword("someinvalid-password")+ val stateHolder = createStateHolder(httpClient = HttpClient(engine))+ val events = collectEvents(stateHolder)++ stateHolder.changeUsername("invalidUser")+ stateHolder.changePassword("someinvalid-password")advanceUntilIdle()- component.onAuthenticate()+ stateHolder.authenticate()advanceUntilIdle()- assertEquals(2, outputs.size, "Two outputs expected")- assertContains(outputs, Output.Authenticating)- val outcome = outputs[1]- assertIs<Output.AuthenticationFailed>(outcome)+ assertEquals(2, events.size, "Two events expected")+ assertContains(events, BasicAuthEvent.AuthenticationStarted)+ val outcome = events[1]+ assertIs<BasicAuthEvent.AuthenticationFailed>(outcome)assertIs<InvalidCredentialsException>(outcome.error)}@Test- fun `GIVEN error state WHEN credentials change THEN error reset outputted`() = runTest {+ fun `GIVEN error state WHEN credentials change THEN error reset emitted`() = runTest {val engine = createMockEngine(authenticationResponseHandler)- val outputs = mutableListOf<Output>()-- val component = createComponent(- httpClient = HttpClient(engine),- output = { outputs.add(it) },- )- component.onChangeUsername("invalidUser")- component.onChangePassword("someinvalid-password")+ val stateHolder = createStateHolder(httpClient = HttpClient(engine))+ val events = collectEvents(stateHolder)++ stateHolder.changeUsername("invalidUser")+ stateHolder.changePassword("someinvalid-password")advanceUntilIdle()- component.onAuthenticate()+ stateHolder.authenticate()advanceUntilIdle()- assertContains(outputs, Output.Authenticating)- assertEquals(2, outputs.size, "Two outputs expected")- assertIs<Output.AuthenticationFailed>(outputs[1])+ assertContains(events, BasicAuthEvent.AuthenticationStarted)+ assertEquals(2, events.size, "Two events expected")+ assertIs<BasicAuthEvent.AuthenticationFailed>(events[1])- component.onChangeUsername("newUsername")+ stateHolder.changeUsername("newUsername")advanceUntilIdle()- assertEquals(3, outputs.size, "Three outputs expected")- assertContains(outputs, Output.ErrorReset)+ assertEquals(3, events.size, "Three events expected")+ assertContains(events, BasicAuthEvent.ErrorReset)}/**- * Helper function for creating an instance of the [DefaultAuthenticationComponent].+ * Collects the events emitted by the [stateHolder] into the returned list.*/- @OptIn(ExperimentalCoroutinesApi::class)- private fun TestScope.createComponent(- lifecycle: LifecycleRegistry = LifecycleRegistry(),- scheduler: TestCoroutineScheduler = testScheduler,- componentContext: AppComponentContext = DefaultAppComponentContext(- componentContext = DefaultComponentContext(lifecycle = lifecycle),- mainContext = StandardTestDispatcher(scheduler),- ioContext = UnconfinedTestDispatcher(scheduler),- ),- storeFactory: StoreFactory = DefaultStoreFactory(),+ private fun TestScope.collectEvents(stateHolder: BasicAuthStateHolder): List<BasicAuthEvent> {+ val events = mutableListOf<BasicAuthEvent>()+ backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {+ stateHolder.events.collect { events.add(it) }+ }+ return events+ }++ /**+ * Helper function for creating an instance of the [BasicAuthStateHolder].+ */+ private fun TestScope.createStateHolder(httpClient: HttpClient = HttpClient(),method: AuthMethod.BasicAuthMethod = AuthMethod.BasicAuthMethod(),- output: (Output) -> Unit = {},- ): BasicAuthComponent {- val lifecycle = LifecycleRegistry()-- val component =- DefaultBasicAuthComponent(- componentContext = componentContext,- storeFactory = storeFactory,- httpClient = httpClient,- method = method,- output = output,- )-- lifecycle.resume()- return component- }+ ) = BasicAuthStateHolder(+ scope = this,+ method = method,+ basicAuthenticateUseCase = DefaultBasicAuthenticateUseCase(HttpBasicAuthRepository(httpClient)),+ dispatchers = TestDispatchers(UnconfinedTestDispatcher(scheduler = testScheduler)),+ )}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/store/FakeOAuthClient.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/FakeOAuthRepository.ktsimilarity index 84%rename from ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/store/FakeOAuthClient.ktrename to ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/FakeOAuthRepository.ktindex 8756d9c0429..fef79587b74 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/store/FakeOAuthClient.kt+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/FakeOAuthRepository.kt@@ -15,17 +15,18 @@* limitations under the License.*/-package org.apache.solr.ui.components.auth.store+package org.apache.solr.ui.components.auth.viewmodelimport io.ktor.client.plugins.auth.providers.BearerTokens+import org.apache.solr.ui.components.auth.repository.OAuthRepositoryimport org.apache.solr.ui.domain.OAuthData/**- * OAuth client for mocking the OAuth server responses.+ * OAuth repository for mocking the OAuth server responses.*/-internal class FakeOAuthClient(+internal class FakeOAuthRepository(private val result: suspend () -> Result<BearerTokens>,-) : OAuthStoreProvider.Client {+) : OAuthRepository {var lastState: String? = nullvar lastVerifier: String? = nulldiff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/store/OAuthStoreProviderTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/OAuthStateHolderTest.ktsimilarity index 50%rename from ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/store/OAuthStoreProviderTest.ktrename to ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/OAuthStateHolderTest.ktindex dd61ccb96e9..6435e4d8d37 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/store/OAuthStoreProviderTest.kt+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/auth/viewmodel/OAuthStateHolderTest.kt@@ -15,28 +15,24 @@* limitations under the License.*/-package org.apache.solr.ui.components.auth.store+package org.apache.solr.ui.components.auth.viewmodel-import com.arkivanov.mvikotlin.extensions.coroutines.labels-import com.arkivanov.mvikotlin.main.store.DefaultStoreFactoryimport io.ktor.client.plugins.auth.providers.BearerTokensimport io.ktor.http.Urlimport kotlin.test.Testimport kotlin.test.assertEqualsimport kotlin.test.assertIs-import kotlin.test.assertNotNullimport kotlin.test.assertTrueimport kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.flow.launchIn-import kotlinx.coroutines.flow.onEach-import kotlinx.coroutines.test.StandardTestDispatcher-import kotlinx.coroutines.test.TestCoroutineScheduler+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.TestScopeimport kotlinx.coroutines.test.UnconfinedTestDispatcherimport kotlinx.coroutines.test.advanceUntilIdle-import kotlinx.coroutines.test.runCurrentimport kotlinx.coroutines.test.runTest-import org.apache.solr.ui.components.auth.store.OAuthStore.Intent-import org.apache.solr.ui.components.auth.store.OAuthStore.Label+import org.apache.solr.ui.TestDispatchers+import org.apache.solr.ui.components.auth.domain.DefaultCreateOAuthAuthorizationUseCase+import org.apache.solr.ui.components.auth.domain.DefaultOAuthAuthenticateUseCase+import org.apache.solr.ui.components.auth.domain.OAuthEventimport org.apache.solr.ui.domain.AuthMethodimport org.apache.solr.ui.domain.AuthorizationFlowimport org.apache.solr.ui.domain.OAuthData@@ -44,10 +40,7 @@ import org.apache.solr.ui.errors.InvalidCredentialsExceptionimport org.apache.solr.ui.errors.UnauthorizedException@OptIn(ExperimentalCoroutinesApi::class)-class OAuthStoreProviderTest {-- private lateinit var client: FakeOAuthClient- private lateinit var store: OAuthStore+class OAuthStateHolderTest {private val method = AuthMethod.OAuthMethod(data = OAuthData(@@ -60,41 +53,21 @@ class OAuthStoreProviderTest {),)- private fun createStore(- testScheduler: TestCoroutineScheduler,- result: suspend () -> Result<BearerTokens>,- ) {- client = FakeOAuthClient(result)-- store = OAuthStoreProvider(- storeFactory = DefaultStoreFactory(),- client = client,- mainContext = UnconfinedTestDispatcher(testScheduler),- ioContext = StandardTestDispatcher(testScheduler),- method = method,- ).provide()- store.init()- }-@Test- fun `WHEN authenticate THEN AuthenticationStarted is published`() = runTest {- createStore(testScheduler) {+ fun `WHEN authenticate THEN AuthenticationStarted is emitted`() = runTest {+ val stateHolder = createStateHolder {Result.failure(RuntimeException("noop"))}+ val events = collectEvents(stateHolder)- val labels = mutableListOf<Label>()- store.labels.onEach(labels::add).launchIn(backgroundScope)- runCurrent()-- store.accept(Intent.Authenticate)- runCurrent()+ stateHolder.authenticate()advanceUntilIdle()- val label = assertIs<Label.AuthenticationStarted>(- value = labels.firstOrNull(),- message = "first label emitted should be AuthenticationStarted",+ val event = assertIs<OAuthEvent.AuthenticationStarted>(+ value = events.firstOrNull(),+ message = "first event emitted should be AuthenticationStarted",)- val url = label.url.toString()+ val url = event.url.toString()assertTrue(url.contains("client_id=client-id"))assertTrue(url.contains("response_type=code"))@@ -103,54 +76,43 @@ class OAuthStoreProviderTest {}@Test- fun `WHEN unexpected error during authenticate THEN error state is set and published`() = runTest {- createStore(testScheduler) {+ fun `WHEN unexpected error during authenticate THEN error state is set and emitted`() = runTest {+ val stateHolder = createStateHolder {// Fail immediatelythrow RuntimeException("oops")}+ val events = collectEvents(stateHolder)- val labels = mutableListOf<Label>()- store.labels.onEach(labels::add).launchIn(backgroundScope)- runCurrent()-- store.accept(Intent.Authenticate)- runCurrent()+ stateHolder.authenticate()advanceUntilIdle()- val errorLabel = assertIs<Label.AuthenticationFailed>(- value = labels.filterIsInstance<Label.AuthenticationFailed>().single(),- message = "first label emitted should be AuthenticationStarted",- )+ val errorEvent = events.filterIsInstance<OAuthEvent.AuthenticationFailed>().single()assertIs<RuntimeException>(- value = errorLabel.error,+ value = errorEvent.error,message = "error should be RuntimeException",)- assertNotNull(- actual = store.state.error,+ assertTrue(+ actual = stateHolder.uiState.value.hasError,message = "state should have error",)}@Test- fun `WHEN authentication succeeds THEN Authenticated is published`() = runTest {+ fun `WHEN authentication succeeds THEN Authenticated is emitted`() = runTest {val tokens = BearerTokens(accessToken = "access",refreshToken = "refresh",)- createStore(testScheduler) {+ val stateHolder = createStateHolder {Result.success(tokens)}+ val events = collectEvents(stateHolder)- val labels = mutableListOf<Label>()- store.labels.onEach(labels::add).launchIn(backgroundScope)- runCurrent()-- store.accept(Intent.Authenticate)- runCurrent()+ stateHolder.authenticate()advanceUntilIdle()- val authenticated = labels.filterIsInstance<Label.Authenticated>().single()+ val authenticated = events.filterIsInstance<OAuthEvent.Authenticated>().single()assertEquals("access", authenticated.accessToken)assertEquals("refresh", authenticated.refreshToken)@@ -158,51 +120,64 @@ class OAuthStoreProviderTest {}@Test- fun `WHEN authentication fails THEN AuthenticationFailed is published`() = runTest {+ fun `WHEN authentication fails THEN AuthenticationFailed is emitted`() = runTest {val error = RuntimeException("boom")- createStore(testScheduler) {+ val stateHolder = createStateHolder {Result.failure(error)}+ val events = collectEvents(stateHolder)- val labels = mutableListOf<Label>()- store.labels.onEach(labels::add).launchIn(backgroundScope)- runCurrent()-- store.accept(Intent.Authenticate)- runCurrent()+ stateHolder.authenticate()advanceUntilIdle()- val failedLabel = labels.filterIsInstance<Label.AuthenticationFailed>().single()- assertEquals(error, failedLabel.error)+ val failedEvent = events.filterIsInstance<OAuthEvent.AuthenticationFailed>().single()+ assertEquals(error, failedEvent.error)- assertEquals(error, store.state.error)+ assertTrue(stateHolder.uiState.value.hasError)}@Testfun `WHEN unauthorized THEN error is mapped to InvalidCredentialsException`() = runTest {- createStore(testScheduler) {+ val stateHolder = createStateHolder {Result.failure(exception = UnauthorizedException())}+ val events = collectEvents(stateHolder)- val labels = mutableListOf<Label>()- store.labels.onEach(labels::add).launchIn(backgroundScope)- runCurrent()-- store.accept(Intent.Authenticate)- runCurrent()+ stateHolder.authenticate()advanceUntilIdle()- assertTrue(actual = labels.size > 1, message = "multiple labels should exist")- val failed = labels.filterIsInstance<Label.AuthenticationFailed>().single()+ assertTrue(actual = events.size > 1, message = "multiple events should exist")+ val failed = events.filterIsInstance<OAuthEvent.AuthenticationFailed>().single()assertIs<InvalidCredentialsException>(value = failed.error,message = "error should be InvalidCredentialsException",)- assertIs<InvalidCredentialsException>(- value = store.state.error,- message = "state error should be InvalidCredentialsException",+ assertTrue(+ actual = stateHolder.uiState.value.hasError,+ message = "state should have error",)}++ /**+ * Collects the events emitted by the [stateHolder] into the returned list.+ */+ private fun TestScope.collectEvents(stateHolder: OAuthStateHolder): List<OAuthEvent> {+ val events = mutableListOf<OAuthEvent>()+ backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {+ stateHolder.events.collect { events.add(it) }+ }+ return events+ }++ private fun TestScope.createStateHolder(+ result: suspend () -> Result<BearerTokens>,+ ) = OAuthStateHolder(+ scope = this,+ method = method,+ createOAuthAuthorizationUseCase = DefaultCreateOAuthAuthorizationUseCase(),+ oAuthAuthenticateUseCase = DefaultOAuthAuthenticateUseCase(FakeOAuthRepository(result)),+ dispatchers = TestDispatchers(UnconfinedTestDispatcher(scheduler = testScheduler)),+ )}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStoreProviderTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStoreProviderTest.ktdeleted file mode 100644index 690a7b4546d..00000000000--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/store/EnvironmentStoreProviderTest.kt+++ /dev/null@@ -1,107 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.components.environment.store--import com.arkivanov.mvikotlin.extensions.coroutines.stateFlow-import com.arkivanov.mvikotlin.main.store.DefaultStoreFactory-import kotlin.test.Test-import kotlin.time.Duration.Companion.seconds-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.test.runTest-import org.apache.solr.ui.components.environment.data.SystemData--@OptIn(ExperimentalCoroutinesApi::class)-class EnvironmentStoreProviderTest {-- @Test- fun testFetchInitialSystemDataAction() = runTest(timeout = 2.seconds) {- val expectedJavaProperties = listOf("key" to "value")- val expectedSystemData = SystemData(solrHome = "some/path")- val client = MockedEnvironmentStoreClient(- onGetJavaProperties = { Result.success(expectedJavaProperties) },- onGetSystemData = { Result.success(expectedSystemData) },- )-- // When provide is called, the initial action is already included- val store = EnvironmentStoreProvider(- storeFactory = DefaultStoreFactory(),- client = client,- mainContext = coroutineContext,- ioContext = backgroundScope.coroutineContext,- ).provide()-- // Collect the state updates and wait for the expected state- // If the expected state is never published, test will run into a timeout- store.stateFlow.first { state ->- state.javaProperties == expectedJavaProperties &&- state.system == expectedSystemData.system &&- state.jvm == expectedSystemData.jvm &&- state.solrHome == expectedSystemData.solrHome- }- }-- @Test- fun testFetchSystemDataIntent() = runTest(timeout = 2.seconds) {- var initialRequest1 = true- var initialRequest2 = true- val expectedJavaProperties = listOf("key2" to "value2")- val expectedSystemData = SystemData(solrHome = "some/path2")-- val client = MockedEnvironmentStoreClient(- onGetJavaProperties = {- if (initialRequest1) {- initialRequest1 = false- Result.success(listOf("key" to "value"))- }- // A second request should be sent in this scenario, so we- // respond with different data- else {- Result.success(expectedJavaProperties)- }- },- onGetSystemData = {- if (initialRequest2) {- initialRequest2 = false- Result.success(SystemData(solrHome = "some/path"))- } else {- Result.success(expectedSystemData)- }- },- )-- // When provide is called, the initial action is already included- val store = EnvironmentStoreProvider(- storeFactory = DefaultStoreFactory(),- client = client,- mainContext = coroutineContext,- ioContext = backgroundScope.coroutineContext,- ).provide()-- // Send an intent to re-fetch the data- store.accept(EnvironmentStore.Intent.FetchSystemData)-- // Collect the state updates and wait for the expected state- store.stateFlow.first { state ->- state.javaProperties == expectedJavaProperties &&- state.system == expectedSystemData.system &&- state.jvm == expectedSystemData.jvm &&- state.solrHome == expectedSystemData.solrHome- }- }-}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentStateHolderTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentStateHolderTest.ktnew file mode 100644index 00000000000..897ec46f4db--- /dev/null+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/environment/viewmodel/EnvironmentStateHolderTest.kt@@ -0,0 +1,98 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.ui.components.environment.viewmodel++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.TestScope+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.advanceUntilIdle+import kotlinx.coroutines.test.runTest+import org.apache.solr.ui.TestDispatchers+import org.apache.solr.ui.components.environment.data.JavaProperty+import org.apache.solr.ui.components.environment.data.SystemData+import org.apache.solr.ui.components.environment.domain.LoadJavaPropertiesUseCase+import org.apache.solr.ui.components.environment.domain.LoadSystemDataUseCase++@OptIn(ExperimentalCoroutinesApi::class)+class EnvironmentStateHolderTest {++ @Test+ fun `GIVEN system data and java properties WHEN initialized THEN state contains them`() = runTest {+ val expectedJavaProperties = listOf("key" to "value")+ val expectedSystemData = SystemData(solrHome = "some/path")++ val stateHolder = createStateHolder(+ onLoadSystemData = { Result.success(expectedSystemData) },+ onLoadJavaProperties = { Result.success(expectedJavaProperties) },+ )+ advanceUntilIdle()++ val state = stateHolder.uiState.value+ assertEquals(expectedJavaProperties, state.javaProperties)+ assertEquals(expectedSystemData.system, state.system)+ assertEquals(expectedSystemData.jvm, state.jvm)+ assertEquals(expectedSystemData.solrHome, state.solrHome)+ }++ @Test+ fun `GIVEN loaded state WHEN fetchSystemData THEN state contains new data`() = runTest {+ var isInitialRequest = true+ val expectedJavaProperties = listOf("key2" to "value2")+ val expectedSystemData = SystemData(solrHome = "some/path2")++ val stateHolder = createStateHolder(+ onLoadSystemData = {+ // A second request should be sent in this scenario, so we+ // respond with different data+ if (isInitialRequest) Result.success(SystemData(solrHome = "some/path"))+ else Result.success(expectedSystemData)+ },+ onLoadJavaProperties = {+ if (isInitialRequest) Result.success(listOf("key" to "value"))+ else Result.success(expectedJavaProperties)+ },+ )+ advanceUntilIdle()++ isInitialRequest = false+ stateHolder.fetchSystemData()+ advanceUntilIdle()++ val state = stateHolder.uiState.value+ assertEquals(expectedJavaProperties, state.javaProperties)+ assertEquals(expectedSystemData.system, state.system)+ assertEquals(expectedSystemData.jvm, state.jvm)+ assertEquals(expectedSystemData.solrHome, state.solrHome)+ }++ private fun TestScope.createStateHolder(+ onLoadSystemData: () -> Result<SystemData>,+ onLoadJavaProperties: () -> Result<List<JavaProperty>>,+ ) = EnvironmentStateHolder(+ scope = this,+ loadSystemDataUseCase = object : LoadSystemDataUseCase {+ override suspend fun invoke() = onLoadSystemData()+ },+ loadJavaPropertiesUseCase = object : LoadJavaPropertiesUseCase {+ override suspend fun invoke() = onLoadJavaProperties()+ },+ dispatchers = TestDispatchers(UnconfinedTestDispatcher(scheduler = testScheduler)),+ )+}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/start/integration/DefaultStartComponentIntegrationTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/start/viewmodel/StartStateHolderIntegrationTest.ktsimilarity index 51%rename from ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/start/integration/DefaultStartComponentIntegrationTest.ktrename to ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/start/viewmodel/StartStateHolderIntegrationTest.ktindex 9df174840aa..c687582dc28 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/start/integration/DefaultStartComponentIntegrationTest.kt+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/components/start/viewmodel/StartStateHolderIntegrationTest.kt@@ -15,14 +15,8 @@* limitations under the License.*/-package org.apache.solr.ui.components.start.integration--import com.arkivanov.decompose.DefaultComponentContext-import com.arkivanov.essenty.lifecycle.LifecycleRegistry-import com.arkivanov.essenty.lifecycle.resume-import com.arkivanov.mvikotlin.core.store.StoreFactory-import com.arkivanov.mvikotlin.core.utils.isAssertOnMainThreadEnabled-import com.arkivanov.mvikotlin.main.store.DefaultStoreFactory+package org.apache.solr.ui.components.start.viewmodel+import io.ktor.client.HttpClientimport io.ktor.client.engine.mock.MockRequestHandleScopeimport io.ktor.client.engine.mock.MockRequestHandler@@ -32,31 +26,27 @@ import io.ktor.http.HttpStatusCodeimport io.ktor.http.URLBuilderimport io.ktor.http.fullPathimport io.ktor.http.path-import kotlin.test.AfterTest-import kotlin.test.BeforeTestimport kotlin.test.Testimport kotlin.test.assertEqualsimport kotlin.test.assertIsimport kotlin.test.assertNotNullimport kotlin.test.assertNullimport kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.test.StandardTestDispatcher-import kotlinx.coroutines.test.TestCoroutineScheduler+import kotlinx.coroutines.launchimport kotlinx.coroutines.test.TestScopeimport kotlinx.coroutines.test.UnconfinedTestDispatcherimport kotlinx.coroutines.test.advanceUntilIdleimport kotlinx.coroutines.test.runTest-import org.apache.solr.ui.components.start.StartComponent-import org.apache.solr.ui.components.start.StartComponent.Output+import org.apache.solr.ui.TestDispatchers+import org.apache.solr.ui.components.start.data.HttpStartRepository+import org.apache.solr.ui.components.start.domain.DefaultConnectUseCase+import org.apache.solr.ui.components.start.domain.StartEventimport org.apache.solr.ui.createMockEngineimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.error_invalid_url-import org.apache.solr.ui.utils.AppComponentContext-import org.apache.solr.ui.utils.DEFAULT_SOLR_URL-import org.apache.solr.ui.utils.DefaultAppComponentContext@OptIn(ExperimentalCoroutinesApi::class)-class DefaultStartComponentIntegrationTest {+class StartStateHolderIntegrationTest {/*** Response handler that always responds with HTTP code OK.@@ -65,29 +55,12 @@ class DefaultStartComponentIntegrationTest {scope.respond(content = "Ignore", status = HttpStatusCode.OK)}- /**- * Response handler that always responds with HTTP code Forbidden.- */- private val forbiddenResponseHandler: MockRequestHandler = { scope: MockRequestHandleScope, data: HttpRequestData ->- scope.respond(content = "Forbidden", status = HttpStatusCode.Forbidden)- }-- @BeforeTest- fun beforeTest() {- isAssertOnMainThreadEnabled = false- }-- @AfterTest- fun afterTest() {- isAssertOnMainThreadEnabled = true- }-@Test- fun `GIVEN initial state WHEN onConnect THEN use default Solr URL`() = runTest {+ fun `GIVEN initial state WHEN connect THEN use default Solr URL`() = runTest {val engine = createMockEngine(okResponseHandler)- val component = createComponent(httpClient = HttpClient(engine))+ val stateHolder = createStateHolder(httpClient = HttpClient(engine))- component.onConnect()+ stateHolder.connect()advanceUntilIdle()assertEquals(@@ -105,13 +78,13 @@ class DefaultStartComponentIntegrationTest {}@Test- fun `GIVEN invalid URL WHEN onConnect THEN invalidUrlError`() = runTest {+ fun `GIVEN invalid URL WHEN connect THEN invalidUrlError`() = runTest {val engine = createMockEngine(okResponseHandler)- val component = createComponent(httpClient = HttpClient(engine))+ val stateHolder = createStateHolder(httpClient = HttpClient(engine))- component.onSolrUrlChange("some.-invalid-url")+ stateHolder.changeSolrUrl("some.-invalid-url")- component.onConnect()+ stateHolder.connect()advanceUntilIdle()assertEquals(@@ -122,19 +95,19 @@ class DefaultStartComponentIntegrationTest {assertEquals(expected = Res.string.error_invalid_url,- actual = component.model.value.error,+ actual = stateHolder.uiState.value.error,message = "Expected invalid url error",)}@Test- fun `GIVEN valid Solr URL WHEN onConnect THEN connection request sent`() = runTest {+ fun `GIVEN valid Solr URL WHEN connect THEN connection request sent`() = runTest {val engine = createMockEngine(okResponseHandler)- val component = createComponent(httpClient = HttpClient(engine))+ val stateHolder = createStateHolder(httpClient = HttpClient(engine))val validSolrUrl = "https://my-solr-instance.local/"- component.onSolrUrlChange(validSolrUrl)- component.onConnect()+ stateHolder.changeSolrUrl(validSolrUrl)+ stateHolder.connect()advanceUntilIdle()assertEquals(@@ -152,70 +125,52 @@ class DefaultStartComponentIntegrationTest {}@Test- fun `GIVEN a solr instance with no auth WHEN onConnect THEN output Connected`() = runTest {- val outputStack = mutableListOf<Output>()+ fun `GIVEN a solr instance with no auth WHEN connect THEN event Connected`() = runTest {+ val events = mutableListOf<StartEvent>()val engine = createMockEngine(okResponseHandler)- val component = createComponent(- output = { outputStack.add(it) },- httpClient = HttpClient(engine),- )+ val stateHolder = createStateHolder(httpClient = HttpClient(engine))+ backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {+ stateHolder.events.collect { events.add(it) }+ }- component.onConnect()+ stateHolder.connect()advanceUntilIdle()assertEquals(expected = 1,- actual = outputStack.size,- message = "Expected one output",+ actual = events.size,+ message = "Expected one event",)- assertIs<Output.OnConnected>(- value = outputStack[0],- message = "Expected output to be Connected",+ assertIs<StartEvent.Connected>(+ value = events[0],+ message = "Expected event to be Connected",)}@Testfun `GIVEN input error WHEN input changes THEN error resets`() = runTest {- val component = createComponent()- component.onSolrUrlChange("some.-invalid-url")+ val stateHolder = createStateHolder()+ stateHolder.changeSolrUrl("some.-invalid-url")// Cause an error in state- component.onConnect()+ stateHolder.connect()advanceUntilIdle()- assertNotNull(component.model.value.error)+ assertNotNull(stateHolder.uiState.value.error)- component.onSolrUrlChange("some-other-url")+ stateHolder.changeSolrUrl("some-other-url")advanceUntilIdle()- assertNull(component.model.value.error)+ assertNull(stateHolder.uiState.value.error)}/**- * Helper function for creating an instance of the [DefaultStartComponent].+ * Helper function for creating an instance of the [StartStateHolder].*/- private fun TestScope.createComponent(- lifecycle: LifecycleRegistry = LifecycleRegistry(),- scheduler: TestCoroutineScheduler = testScheduler,- componentContext: AppComponentContext = DefaultAppComponentContext(- componentContext = DefaultComponentContext(lifecycle = lifecycle),- mainContext = StandardTestDispatcher(scheduler),- ioContext = UnconfinedTestDispatcher(scheduler),- ),- storeFactory: StoreFactory = DefaultStoreFactory(),+ private fun TestScope.createStateHolder(httpClient: HttpClient = HttpClient(),- output: (Output) -> Unit = {},- ): StartComponent {- val lifecycle = LifecycleRegistry()-- val component =- DefaultStartComponent(- componentContext = componentContext,- storeFactory = storeFactory,- httpClient = httpClient,- output = output,- )-- lifecycle.resume()- return component- }+ ) = StartStateHolder(+ scope = this,+ connectUseCase = DefaultConnectUseCase(HttpStartRepository(httpClient)),+ dispatchers = TestDispatchers(UnconfinedTestDispatcher(scheduler = testScheduler)),+ )}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/BasicAuthContentTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/BasicAuthContentTest.ktindex e28ee5641c6..abe7b0a6e36 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/BasicAuthContentTest.kt+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/BasicAuthContentTest.kt@@ -17,6 +17,7 @@package org.apache.solr.ui.views.auth+import androidx.compose.runtime.Composableimport androidx.compose.ui.semantics.SemanticsPropertiesimport androidx.compose.ui.test.ExperimentalTestApiimport androidx.compose.ui.test.assert@@ -26,8 +27,7 @@ import androidx.compose.ui.test.onNodeWithTagimport androidx.compose.ui.test.v2.runComposeUiTestimport kotlin.test.Testimport kotlin.test.assertEquals-import org.apache.solr.ui.components.auth.BasicAuthComponent-import org.apache.solr.ui.components.auth.BasicAuthComponent.Model+import org.apache.solr.ui.components.auth.viewmodel.BasicAuthUiStateimport org.apache.solr.ui.isErrorSemantics@OptIn(ExperimentalTestApi::class)@@ -36,7 +36,7 @@ class BasicAuthContentTest {@Testfun `WHEN initialized THEN input is empty`() = runComposeUiTest {setContent {- BasicAuthContent(createComponent())+ TestBasicAuthContent()}assertEquals(@@ -61,7 +61,7 @@ class BasicAuthContentTest {@Testfun `GIVEN isAuthenticating THEN inputs disabled`() = runComposeUiTest {setContent {- BasicAuthContent(component = createComponent(), isAuthenticating = true)+ TestBasicAuthContent(isAuthenticating = true)}onNodeWithTag("username_input_field").assertIsNotEnabled()@@ -72,7 +72,7 @@ class BasicAuthContentTest {@Testfun `GIVEN isAuthenticating THEN loading indicator displayed`() = runComposeUiTest {setContent {- BasicAuthContent(component = createComponent(), isAuthenticating = true)+ TestBasicAuthContent(isAuthenticating = true)}onNodeWithTag("loading_indicator").assertIsDisplayed()@@ -81,12 +81,22 @@ class BasicAuthContentTest {@Testfun `GIVEN has error THEN input fields highlighted as error`() = runComposeUiTest {setContent {- BasicAuthContent(component = createComponent(Model(hasError = true)))+ TestBasicAuthContent(uiState = BasicAuthUiState(hasError = true))}onNodeWithTag("username_input_field").assert(matcher = isErrorSemantics)onNodeWithTag("password_input_field").assert(matcher = isErrorSemantics)}- private fun createComponent(model: Model = Model()): BasicAuthComponent = TestBasicAuthComponent(model = model)+ @Composable+ private fun TestBasicAuthContent(+ uiState: BasicAuthUiState = BasicAuthUiState(),+ isAuthenticating: Boolean = true,+ ) = BasicAuthContent(+ uiState = uiState,+ onChangeUsername = {},+ onChangePassword = {},+ onAuthenticate = {},+ isAuthenticating = isAuthenticating,+ )}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestAuthenticationComponent.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestAuthenticationComponent.ktdeleted file mode 100644index 337c3d9f147..00000000000--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestAuthenticationComponent.kt+++ /dev/null@@ -1,70 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.views.auth--import com.arkivanov.decompose.Child.Created-import com.arkivanov.decompose.router.slot.ChildSlot-import com.arkivanov.decompose.value.MutableValue-import com.arkivanov.decompose.value.Value-import io.ktor.http.Url-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.auth.AuthenticationComponent-import org.apache.solr.ui.components.auth.AuthenticationComponent.BasicAuthConfiguration-import org.apache.solr.ui.components.auth.AuthenticationComponent.Model-import org.apache.solr.ui.components.auth.AuthenticationComponent.OAuthConfiguration-import org.apache.solr.ui.components.auth.BasicAuthComponent-import org.apache.solr.ui.components.auth.OAuthComponent-import org.apache.solr.ui.domain.AuthMethod-import org.apache.solr.ui.domain.AuthorizationFlow-import org.apache.solr.ui.domain.OAuthData--internal class TestAuthenticationComponent(- model: Model = Model(),- basicAuthConfig: BasicAuthConfiguration = BasicAuthConfiguration(),- basicAuthComponent: BasicAuthComponent = TestBasicAuthComponent(),- oAuthConfig: OAuthConfiguration = OAuthConfiguration(- method = AuthMethod.OAuthMethod(data = TestOAuthData),- ),- oAuthComponent: OAuthComponent = TestOAuthComponent(),-) : AuthenticationComponent {- var onAbortClicked = false- override val model: StateFlow<Model> = MutableStateFlow(model)- override val basicAuthSlot: Value<ChildSlot<BasicAuthConfiguration, BasicAuthComponent>> =- MutableValue(- ChildSlot(- child = Created(- configuration = basicAuthConfig,- instance = basicAuthComponent,- ),- ),- )- override val oAuthSlot: Value<ChildSlot<OAuthConfiguration, OAuthComponent>> =- MutableValue(- ChildSlot(- child = Created(- configuration = oAuthConfig,- instance = oAuthComponent,- ),- ),- )-- override fun onAbort() {- onAbortClicked = true- }-}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestBasicAuthComponent.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestBasicAuthComponent.ktdeleted file mode 100644index b7ecae591f0..00000000000--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestBasicAuthComponent.kt+++ /dev/null@@ -1,43 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.views.auth--import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.auth.BasicAuthComponent-import org.apache.solr.ui.components.auth.BasicAuthComponent.Model--internal class TestBasicAuthComponent(model: Model = Model()) : BasicAuthComponent {- var onChangeUsernameClicked = false- var onChangePasswordClicked = false- var onAuthenticateClicked = false-- override val model: StateFlow<Model> = MutableStateFlow(model)-- override fun onChangeUsername(username: String) {- onChangeUsernameClicked = true- }-- override fun onChangePassword(password: String) {- onChangePasswordClicked = true- }-- override fun onAuthenticate() {- onAuthenticateClicked = true- }-}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestOAuthComponent.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestOAuthComponent.ktdeleted file mode 100644index ec9bf437e0c..00000000000--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/TestOAuthComponent.kt+++ /dev/null@@ -1,38 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--package org.apache.solr.ui.views.auth--import kotlinx.coroutines.flow.Flow-import kotlinx.coroutines.flow.MutableSharedFlow-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.auth.OAuthComponent-import org.apache.solr.ui.components.auth.OAuthComponent.Model-import org.apache.solr.ui.components.auth.store.OAuthStore--internal class TestOAuthComponent(- model: Model = Model(),- override val labels: Flow<OAuthStore.Label> = MutableSharedFlow(),-) : OAuthComponent {- var onAuthenticateClicked = false-- override val model: StateFlow<Model> = MutableStateFlow(model)- override fun onAuthenticate() {- onAuthenticateClicked = true- }-}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/UserAuthenticationContentTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/UserAuthenticationContentTest.ktindex afba9e18fec..02999a267fd 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/UserAuthenticationContentTest.kt+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/auth/UserAuthenticationContentTest.kt@@ -23,7 +23,7 @@ import androidx.compose.ui.test.onNodeWithTagimport androidx.compose.ui.test.v2.runComposeUiTestimport kotlin.test.Ignoreimport kotlin.test.Test-import org.apache.solr.ui.components.auth.AuthenticationComponent.Model+import org.apache.solr.ui.components.auth.viewmodel.AuthenticationUiStateimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.error_invalid_credentials@@ -35,11 +35,10 @@ class UserAuthenticationContentTest {fun `GIVEN error THEN error displayed`() = runComposeUiTest {val error = Res.string.error_invalid_credentialssetContent {- UserAuthenticationContent(createComponent(model = Model(error = error)))+ UserAuthenticationContent(uiState = AuthenticationUiState(error = error), onAbort = {})}onNodeWithTag("error_text").assertIsDisplayed()}- private fun createComponent(model: Model = Model()) = TestAuthenticationComponent(model)}diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/environment/EnvironmentContentTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/environment/EnvironmentContentTest.ktindex 71b224a3fa4..2b0b29ccff6 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/environment/EnvironmentContentTest.kt+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/environment/EnvironmentContentTest.kt@@ -15,16 +15,15 @@* limitations under the License.*/+package org.apache.solr.ui.views.environmentimport androidx.compose.ui.test.ExperimentalTestApiimport androidx.compose.ui.test.onNodeWithTextimport androidx.compose.ui.test.v2.runComposeUiTestimport kotlin.test.Test-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.environment.EnvironmentComponentimport org.apache.solr.ui.components.environment.data.Versions+import org.apache.solr.ui.components.environment.viewmodel.EnvironmentUiStateclass EnvironmentContentTest {@@ -32,7 +31,7 @@ class EnvironmentContentTest {@Testfun testEnvironmentContentRendering() = runComposeUiTest {setContent {- EnvironmentContent(TestEnvironmentComponent)+ EnvironmentContent(uiState = testUiState)}// Test if component data is displayed@@ -45,21 +44,17 @@ class EnvironmentContentTest {}}-private object TestEnvironmentComponent : EnvironmentComponent {- override val model: StateFlow<EnvironmentComponent.Model> = MutableStateFlow(- EnvironmentComponent.Model(- versions = Versions(- solrSpecVersion = "solr-spec version",- ),- javaProperties = listOf(- "key 1" to "value 1",- "key 2" to "value 2",- "key 3" to "value 3",- "key 4" to "value 4",- "key 5" to "value 5",- "key 6" to "value 6",- "key 7" to "value 7",- ),- ),- )-}+private val testUiState = EnvironmentUiState(+ lucene = Versions(+ solrSpecVersion = "solr-spec version",+ ),+ javaProperties = listOf(+ "key 1" to "value 1",+ "key 2" to "value 2",+ "key 3" to "value 3",+ "key 4" to "value 4",+ "key 5" to "value 5",+ "key 6" to "value 6",+ "key 7" to "value 7",+ ),+)diff --git a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/start/StartContentTest.kt b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/start/StartContentTest.ktindex e934cf8a78d..3cfdee2b714 100644--- a/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/start/StartContentTest.kt+++ b/ui/shared/src/commonTest/kotlin/org/apache/solr/ui/views/start/StartContentTest.kt@@ -17,6 +17,7 @@package org.apache.solr.ui.views.start+import androidx.compose.runtime.Composableimport androidx.compose.ui.semantics.SemanticsNodeimport androidx.compose.ui.semantics.SemanticsPropertiesimport androidx.compose.ui.test.ExperimentalTestApi@@ -33,7 +34,7 @@ import kotlin.test.Ignoreimport kotlin.test.Testimport kotlin.test.assertEqualsimport kotlin.test.assertTrue-import org.apache.solr.ui.components.start.StartComponent.Model+import org.apache.solr.ui.components.start.viewmodel.StartUiStateimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.error_invalid_urlimport org.jetbrains.compose.resources.stringResource@@ -44,7 +45,7 @@ class StartContentTest {@Testfun `WHEN initialized THEN input is empty`() = runComposeUiTest {setContent {- StartContent(createComponent())+ TestStartContent(uiState = StartUiState())}assertEquals(@@ -61,7 +62,7 @@ class StartContentTest {@Ignore // TODO Currently fails on wasmJsfun `GIVEN input error THEN error text shown`() = runComposeUiTest {setContent {- StartContent(createComponent(Model(error = Res.string.error_invalid_url)))+ TestStartContent(uiState = StartUiState(error = Res.string.error_invalid_url))}onNodeWithTag("input_error").assertIsDisplayed()@@ -69,19 +70,19 @@ class StartContentTest {@Testfun `WHEN on connect clicked THEN onConnect called`() = runComposeUiTest {- val component = createComponent()+ var onConnectClicked = falsesetContent {- StartContent(component)+ TestStartContent(onConnect = { onConnectClicked = true })}onNodeWithTag("connect_button").performClick()- assertTrue(component.onConnectClicked)+ assertTrue(onConnectClicked)}@Testfun `WHEN isConnecting THEN connect inputs disabled`() = runComposeUiTest {setContent {- StartContent(createComponent(Model(isConnecting = true)))+ TestStartContent(uiState = StartUiState(isConnecting = true))}onNodeWithTag("solr_url_input").assertIsNotEnabled()@@ -91,11 +92,19 @@ class StartContentTest {@Testfun `WHEN isConnecting THEN loading indicator displayed`() = runComposeUiTest {setContent {- StartContent(createComponent(Model(isConnecting = true)))+ TestStartContent(uiState = StartUiState(isConnecting = true))}onNodeWithTag("loading_indicator").assertIsDisplayed()}- private fun createComponent(model: Model = Model()) = TestStartComponent(model)+ @Composable+ private fun TestStartContent(+ uiState: StartUiState = StartUiState(),+ onConnect: () -> Unit = {},+ ) = StartContent(+ uiState = uiState,+ onSolrUrlChange = {},+ onConnect = onConnect,+ )}diff --git a/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.kt b/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.ktsimilarity index 96%rename from ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.ktrename to ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.ktindex 03ab5d0d0ed..062bb0e4d25 100644--- a/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.kt+++ b/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.kt@@ -15,7 +15,7 @@* limitations under the License.*/-package org.apache.solr.ui.components.auth.integration+package org.apache.solr.ui.components.auth.dataimport io.ktor.client.HttpClientimport io.ktor.client.call.body@@ -36,7 +36,7 @@ import io.ktor.server.routing.postimport io.ktor.server.routing.routingimport kotlinx.coroutines.CompletableDeferredimport org.apache.solr.ui.components.auth.getRedirectUri-import org.apache.solr.ui.components.auth.store.OAuthStoreProvider+import org.apache.solr.ui.components.auth.repository.OAuthRepositoryimport org.apache.solr.ui.data.AuthorizationResponseimport org.apache.solr.ui.domain.OAuthDataimport org.apache.solr.ui.errors.InvalidResponseException@@ -44,7 +44,7 @@ import org.apache.solr.ui.errors.UnauthorizedExceptionimport org.apache.solr.ui.errors.UnknownResponseException/**- * OAuth store implementation that uses a server instance for handling callbacks.+ * OAuth repository implementation that uses a server instance for handling callbacks.** The flow on desktop looks as follows:* 1. The application launches a server that listens on 127.0.0.1:8088@@ -60,7 +60,7 @@ import org.apache.solr.ui.errors.UnknownResponseException* @property httpClient A preconfigured HTTP client that has the base URL of a Solr instance* already set.*/-actual class PlatformOAuthStoreClient actual constructor(private val httpClient: HttpClient) : OAuthStoreProvider.Client {+actual class PlatformOAuthRepository actual constructor(private val httpClient: HttpClient) : OAuthRepository {actual override suspend fun authenticate(state: String,diff --git a/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/preview/auth/PreviewUserAuthenticationContent.kt b/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/preview/auth/PreviewUserAuthenticationContent.ktindex bd44956b9a8..95ee30ea5ae 100644--- a/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/preview/auth/PreviewUserAuthenticationContent.kt+++ b/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/preview/auth/PreviewUserAuthenticationContent.kt@@ -18,141 +18,97 @@package org.apache.solr.ui.preview.authimport androidx.compose.runtime.Composable+import androidx.compose.ui.Modifierimport androidx.compose.ui.tooling.preview.Preview-import com.arkivanov.decompose.Child-import com.arkivanov.decompose.router.slot.ChildSlot-import com.arkivanov.decompose.value.MutableValue-import com.arkivanov.decompose.value.Valueimport io.ktor.http.Url-import kotlinx.coroutines.flow.Flow-import kotlinx.coroutines.flow.MutableSharedFlow-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.auth.AuthenticationComponent-import org.apache.solr.ui.components.auth.AuthenticationComponent.BasicAuthConfiguration-import org.apache.solr.ui.components.auth.AuthenticationComponent.OAuthConfiguration-import org.apache.solr.ui.components.auth.BasicAuthComponent-import org.apache.solr.ui.components.auth.OAuthComponent-import org.apache.solr.ui.components.auth.store.OAuthStore+import org.apache.solr.ui.components.auth.viewmodel.AuthenticationUiState+import org.apache.solr.ui.components.auth.viewmodel.BasicAuthUiState+import org.apache.solr.ui.components.auth.viewmodel.OAuthUiStateimport org.apache.solr.ui.domain.AuthMethodimport org.apache.solr.ui.domain.AuthorizationFlowimport org.apache.solr.ui.domain.OAuthDataimport org.apache.solr.ui.preview.PreviewContainer+import org.apache.solr.ui.views.auth.BasicAuthContent+import org.apache.solr.ui.views.auth.OAuthContentimport org.apache.solr.ui.views.auth.UserAuthenticationContent@Composable@Previewinternal fun PreviewBasicUserAuthenticationContent() = PreviewContainer {- UserAuthenticationContent(- component = PreviewAuthenticationComponentWithBasicAuth(- withBasicAuth = true,- withOAuth = false,- ),+ PreviewUserAuthenticationContent(+ withBasicAuth = true,+ withOAuth = false,)}@Composable@Previewinternal fun PreviewOAuthUserAuthenticationContent() = PreviewContainer {- UserAuthenticationContent(- component = PreviewAuthenticationComponentWithBasicAuth(- withBasicAuth = false,- withOAuth = true,- ),+ PreviewUserAuthenticationContent(+ withBasicAuth = false,+ withOAuth = true,)}@Composable@Previewinternal fun PreviewMultiUserAuthenticationContent() = PreviewContainer {- UserAuthenticationContent(- component = PreviewAuthenticationComponentWithBasicAuth(- withBasicAuth = true,- withOAuth = true,- ),+ PreviewUserAuthenticationContent(+ withBasicAuth = true,+ withOAuth = true,)}-private class PreviewAuthenticationComponentWithBasicAuth(- private val withBasicAuth: Boolean = false,- private val withOAuth: Boolean = false,- model: AuthenticationComponent.Model = AuthenticationComponent.Model(),-) : AuthenticationComponent {- constructor(- withBasicAuth: Boolean = false,- withOAuth: Boolean = false,- ) : this(- withBasicAuth = withBasicAuth,- withOAuth = withOAuth,- model = AuthenticationComponent.Model(- methods = listOfNotNull(- if (withBasicAuth) AuthMethod.BasicAuthMethod() else null,- if (withOAuth) {- AuthMethod.OAuthMethod(- data = OAuthData(- clientId = "",- authorizationFlow = AuthorizationFlow.CodePKCE,- scope = "",- redirectUris = listOf(Url("http://127.0.0.1")),- authorizationEndpoint = Url("http://127.0.0.1"),- tokenEndpoint = Url("http://127.0.0.1"),- ),- )- } else {- null- },- ),- ),- )-- override val model: StateFlow<AuthenticationComponent.Model> = MutableStateFlow(model)-- override val basicAuthSlot: Value<ChildSlot<BasicAuthConfiguration, BasicAuthComponent>> =- MutableValue(- if (withBasicAuth) {- ChildSlot(- Child.Created(- configuration = BasicAuthConfiguration(),- instance = PreviewBasicAuthComponent,- ),- )- } else {- ChildSlot()- },- )-- override val oAuthSlot: Value<ChildSlot<OAuthConfiguration, OAuthComponent>> =- MutableValue(+@Composable+private fun PreviewUserAuthenticationContent(+ withBasicAuth: Boolean,+ withOAuth: Boolean,+) = UserAuthenticationContent(+ uiState = AuthenticationUiState(+ methods = listOfNotNull(+ if (withBasicAuth) AuthMethod.BasicAuthMethod() else null,if (withOAuth) {- ChildSlot(- Child.Created(- configuration = OAuthConfiguration(- method = model.methods.filterIsInstance<AuthMethod.OAuthMethod>().single(),- ),- instance = PreviewOAuthComponent,+ AuthMethod.OAuthMethod(+ data = OAuthData(+ clientId = "",+ authorizationFlow = AuthorizationFlow.CodePKCE,+ scope = "",+ redirectUris = listOf(Url("http://127.0.0.1")),+ authorizationEndpoint = Url("http://127.0.0.1"),+ tokenEndpoint = Url("http://127.0.0.1"),),)} else {- ChildSlot()+ null},- )-- override fun onAbort() = Unit-}--private object PreviewBasicAuthComponent : BasicAuthComponent {- override val model: StateFlow<BasicAuthComponent.Model> =- MutableStateFlow(BasicAuthComponent.Model())-- override fun onChangeUsername(username: String) = Unit- override fun onChangePassword(password: String) = Unit- override fun onAuthenticate() = Unit-}--private object PreviewOAuthComponent : OAuthComponent {- override val model: StateFlow<OAuthComponent.Model> =- MutableStateFlow(OAuthComponent.Model())- override val labels: Flow<OAuthStore.Label> = MutableSharedFlow()-- override fun onAuthenticate() = Unit-}+ ),+ ),+ onAbort = {},+ basicAuthContent = if (withBasicAuth) {+ { modifier: Modifier ->+ BasicAuthContent(+ uiState = BasicAuthUiState(),+ onChangeUsername = {},+ onChangePassword = {},+ onAuthenticate = {},+ modifier = modifier,+ isAuthenticating = false,+ )+ }+ } else {+ null+ },+ oAuthContent = if (withOAuth) {+ { modifier: Modifier, showSupportingText: Boolean ->+ OAuthContent(+ uiState = OAuthUiState(),+ onAuthenticate = {},+ modifier = modifier,+ isAuthenticating = false,+ showSupportingText = showSupportingText,+ )+ }+ } else {+ null+ },+)diff --git a/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/preview/start/PreviewStartContent.kt b/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/preview/start/PreviewStartContent.ktindex 0a0912bccf2..88b9dccc694 100644--- a/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/preview/start/PreviewStartContent.kt+++ b/ui/shared/src/jvmMain/kotlin/org/apache/solr/ui/preview/start/PreviewStartContent.kt@@ -19,59 +19,41 @@ package org.apache.solr.ui.preview.startimport androidx.compose.runtime.Composableimport androidx.compose.ui.tooling.preview.Preview-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.StateFlow-import org.apache.solr.ui.components.start.StartComponent+import org.apache.solr.ui.components.start.viewmodel.StartUiState+import org.apache.solr.ui.preview.PreviewContainerimport org.apache.solr.ui.shared.generated.resources.Resimport org.apache.solr.ui.shared.generated.resources.error_invalid_url-import org.apache.solr.ui.preview.PreviewContainerimport org.apache.solr.ui.views.start.StartContent@Preview@Composableprivate fun PreviewStartContent() = PreviewContainer {- StartContent(component = PreviewStartComponent)+ StartContent(+ uiState = StartUiState(),+ onSolrUrlChange = {},+ onConnect = {},+ )}@Preview@Composableprivate fun PreviewStartContentWithError() = PreviewContainer {- StartContent(component = PreviewStartComponentWithError)-}--@Preview-@Composable-private fun PreviewStartContentWithConnecting() = PreviewContainer {- StartContent(component = PreviewStartComponentWithConnecting)-}--private object PreviewStartComponent : StartComponent {- override val model: StateFlow<StartComponent.Model> =- MutableStateFlow(StartComponent.Model())-- override fun onSolrUrlChange(url: String) = Unit- override fun onConnect() = Unit-}--private object PreviewStartComponentWithError : StartComponent {- override val model: StateFlow<StartComponent.Model> = MutableStateFlow(- StartComponent.Model(+ StartContent(+ uiState = StartUiState(url = "some-invalid-url!",error = Res.string.error_invalid_url,),+ onSolrUrlChange = {},+ onConnect = {},)-- override fun onSolrUrlChange(url: String) = Unit- override fun onConnect() = Unit}-private object PreviewStartComponentWithConnecting : StartComponent {- override val model: StateFlow<StartComponent.Model> = MutableStateFlow(- StartComponent.Model(- isConnecting = true,- ),+@Preview+@Composable+private fun PreviewStartContentWithConnecting() = PreviewContainer {+ StartContent(+ uiState = StartUiState(isConnecting = true),+ onSolrUrlChange = {},+ onConnect = {},)-- override fun onSolrUrlChange(url: String) = Unit- override fun onConnect() = Unit}diff --git a/ui/shared/src/wasmJsMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.kt b/ui/shared/src/wasmJsMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.ktsimilarity index 95%rename from ui/shared/src/wasmJsMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.ktrename to ui/shared/src/wasmJsMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.ktindex c7e91224c1f..ecc93d85564 100644--- a/ui/shared/src/wasmJsMain/kotlin/org/apache/solr/ui/components/auth/integration/PlatformOAuthStoreClient.kt+++ b/ui/shared/src/wasmJsMain/kotlin/org/apache/solr/ui/components/auth/data/PlatformOAuthRepository.kt@@ -15,7 +15,7 @@* limitations under the License.*/-package org.apache.solr.ui.components.auth.integration+package org.apache.solr.ui.components.auth.dataimport io.github.oshai.kotlinlogging.KotlinLoggingimport io.ktor.client.HttpClient@@ -32,7 +32,7 @@ import kotlin.js.unsafeCastimport kotlinx.browser.windowimport kotlinx.coroutines.suspendCancellableCoroutineimport org.apache.solr.ui.components.auth.getRedirectUri-import org.apache.solr.ui.components.auth.store.OAuthStoreProvider+import org.apache.solr.ui.components.auth.repository.OAuthRepositoryimport org.apache.solr.ui.data.AuthorizationResponseimport org.apache.solr.ui.domain.OAuthDataimport org.apache.solr.ui.errors.InvalidResponseException@@ -43,7 +43,7 @@ import org.w3c.dom.MessageEventprivate val logger = KotlinLogging.logger {}/**- * OAuth store implementation that uses event listener and postMessage for handling callbacks+ * OAuth repository implementation that uses event listener and postMessage for handling callbacks* from the identity provider after authentication / authorization.** The basic flow on web looks as follows:@@ -59,7 +59,7 @@ private val logger = KotlinLogging.logger {}* already set.*/@OptIn(ExperimentalWasmJsInterop::class)-actual class PlatformOAuthStoreClient actual constructor(private val httpClient: HttpClient) : OAuthStoreProvider.Client {+actual class PlatformOAuthRepository actual constructor(private val httpClient: HttpClient) : OAuthRepository {actual override suspend fun authenticate(state: String,diff --git a/ui/webApp/build.gradle.kts b/ui/webApp/build.gradle.ktsindex e857720145b..5bf92b4a4e1 100644--- a/ui/webApp/build.gradle.kts+++ b/ui/webApp/build.gradle.kts@@ -64,9 +64,6 @@ kotlin {implementation(libs.ktor.client.core)implementation(libs.compose.foundation)implementation(libs.compose.material3)- implementation(libs.decompose.decompose)- implementation(libs.mvikotlin.main)- implementation(libs.mvikotlin.mvikotlin)}}}diff --git a/ui/webApp/src/webMain/kotlin/org/apache/solr/ui/Main.kt b/ui/webApp/src/webMain/kotlin/org/apache/solr/ui/Main.ktindex ca3585f1a07..64120f4420e 100644--- a/ui/webApp/src/webMain/kotlin/org/apache/solr/ui/Main.kt+++ b/ui/webApp/src/webMain/kotlin/org/apache/solr/ui/Main.kt@@ -22,17 +22,12 @@ import androidx.compose.material3.Surfaceimport androidx.compose.ui.ExperimentalComposeUiApiimport androidx.compose.ui.Modifierimport androidx.compose.ui.window.ComposeViewport-import com.arkivanov.decompose.DefaultComponentContext-import com.arkivanov.essenty.lifecycle.LifecycleRegistry-import com.arkivanov.mvikotlin.main.store.DefaultStoreFactoryimport io.ktor.http.Urlimport kotlin.js.unsafeCastimport kotlinx.browser.documentimport kotlinx.browser.window-import kotlinx.coroutines.Dispatchersimport org.apache.solr.ui.components.root.RootComponentimport org.apache.solr.ui.components.root.integration.SimpleRootComponent-import org.apache.solr.ui.utils.DefaultAppComponentContextimport org.apache.solr.ui.utils.defaultSolrUrlimport org.apache.solr.ui.utils.getDefaultClientimport org.apache.solr.ui.views.root.RootContent@@ -41,13 +36,6 @@ import org.w3c.dom.Window@OptIn(ExperimentalComposeUiApi::class, ExperimentalWasmJsInterop::class)fun main() {- val lifecycle = LifecycleRegistry()- val componentContext = DefaultAppComponentContext(- componentContext = DefaultComponentContext(lifecycle = lifecycle),- mainContext = Dispatchers.Main,- ioContext = Dispatchers.Default,- )-val url = Url(window.location.href)val destination = url.parameters["dest"]@@ -65,8 +53,6 @@ fun main() {val httpClient = getDefaultClient(url = Url(defaultSolrUrl()))val component: RootComponent = SimpleRootComponent(- componentContext = componentContext,- storeFactory = DefaultStoreFactory(),httpClient = httpClient,destination = destination,)