From 51d40b18f85b37d2c88337a2eb8bb6840a2a205b Mon Sep 17 00:00:00 2001 From: rinekri Date: Wed, 7 Oct 2026 14:23:59 +0100 Subject: [PATCH 1/3] Schema extension, lazy regions, focused region host (0.11.0) --- CHANGELOG.md | 82 +++ README.md | 107 +++- gradle.properties | 2 +- .../app/routing/src/google/way/app-flow.dot | 7 + .../sample/compose/app/routing/AppFlowNode.kt | 2 +- .../app/routing/src/huawei/way/app-flow.dot | 10 - .../app/routing/src/main/way/app-flow.dot | 2 - .../app/routing/AppFlowNodeGoogleTest.kt | 6 +- .../kotlin/ru/kode/way/compose/NodeHost.kt | 76 ++- .../ru/kode/way/compose/TransitionSpecs.kt | 73 +++ .../kode/way/compose/FocusedRegionHostTest.kt | 133 +++++ .../ru/kode/way/compose/NodeRetentionTest.kt | 37 ++ .../ru/kode/way/gradle/AdjacencyList.kt | 20 +- .../main/kotlin/ru/kode/way/gradle/Codegen.kt | 6 +- .../kode/way/gradle/FlavorSourceResolution.kt | 14 +- .../ru/kode/way/gradle/GenerateClassesTask.kt | 6 +- .../ru/kode/way/gradle/NodeBuilderCodegen.kt | 40 +- .../main/kotlin/ru/kode/way/gradle/Parser.kt | 92 +++- .../ru/kode/way/gradle/RegionEnumCodegen.kt | 7 +- .../ru/kode/way/gradle/SchemaCodegen.kt | 6 +- .../ru/kode/way/gradle/AdjacencyListTest.kt | 15 + .../ru/kode/way/gradle/SchemaExtensionTest.kt | 162 ++++++ .../ru/kode/way/gradle/SchemaGenerateTest.kt | 9 +- .../src/test/resources/Fi01appNodeBuilder.txt | 12 + .../src/test/resources/Nb01appNodeBuilder.txt | 22 +- .../test/resources/Nbp01mainNodeBuilder.txt | 12 + .../test/resources/Nbp02mainNodeBuilder.txt | 12 + .../test/resources/TargetsTest10Region.txt | 19 + .../test/resources/targets-test10-schema.txt | 45 +- .../kotlin/ru/kode/way/FlowTransition.kt | 3 +- .../kotlin/ru/kode/way/GraphTransitions.kt | 12 +- .../kotlin/ru/kode/way/NavigationService.kt | 470 ++++++++++-------- way/src/commonMain/kotlin/ru/kode/way/Node.kt | 64 +++ .../kotlin/ru/kode/way/NodeBuilder.kt | 10 + .../kotlin/ru/kode/way/NodeExtensionPoint.kt | 12 +- way/src/commonMain/kotlin/ru/kode/way/Path.kt | 7 + .../commonMain/kotlin/ru/kode/way/RegionId.kt | 12 +- .../ru/kode/way/ServiceExtensionPoint.kt | 4 +- .../kotlin/ru/kode/way/TargetResolution.kt | 164 +++++- .../node/hook/BaseParallelFlowNode.kt | 23 + .../way/extension/node/hook/FlowNodeHook.kt | 12 +- .../way/extension/node/hook/ScreenNodeHook.kt | 8 +- .../ru/kode/way/DoubleNestedParallelTest.kt | 445 +++++++++++++++++ .../kotlin/ru/kode/way/InvalidateCacheTest.kt | 27 + .../kotlin/ru/kode/way/LazyRegionTest.kt | 340 +++++++++++++ .../ru/kode/way/NavigationServiceTest.kt | 11 +- .../kotlin/ru/kode/way/ParallelNodeTest.kt | 235 ++++++++- .../commonTest/kotlin/ru/kode/way/PathTest.kt | 6 + .../kode/way/RegionIdResolveAbsoluteTest.kt | 8 + .../kotlin/ru/kode/way/SchemaFanInTest.kt | 179 +++++++ .../ru/kode/way/ScxmlConformanceTest.kt | 1 + way/src/commonTest/way/nav-service16-perm.dot | 1 + .../way/parallel-test-acme-tabs.dot | 3 + .../way/parallel-test-double-nested.dot | 50 ++ 54 files changed, 2780 insertions(+), 363 deletions(-) create mode 100644 sample-compose/app/routing/src/google/way/app-flow.dot delete mode 100644 sample-compose/app/routing/src/huawei/way/app-flow.dot create mode 100644 way-compose/src/main/kotlin/ru/kode/way/compose/TransitionSpecs.kt create mode 100644 way-compose/src/test/kotlin/ru/kode/way/compose/FocusedRegionHostTest.kt create mode 100644 way-compose/src/test/kotlin/ru/kode/way/compose/NodeRetentionTest.kt create mode 100644 way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/SchemaExtensionTest.kt create mode 100644 way-gradle-plugin/src/test/resources/TargetsTest10Region.txt create mode 100644 way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/BaseParallelFlowNode.kt create mode 100644 way/src/commonTest/kotlin/ru/kode/way/DoubleNestedParallelTest.kt create mode 100644 way/src/commonTest/kotlin/ru/kode/way/LazyRegionTest.kt create mode 100644 way/src/commonTest/way/parallel-test-double-nested.dot diff --git a/CHANGELOG.md b/CHANGELOG.md index 1edff30..25f00f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,87 @@ # Changelog +## 0.11.0 - 2026-10-06 + +### Added + +* Gradle plugin: a flavor (or build type) `.dot` file can extend a schema instead of replacing it. A file with the + `mode = "extend"` graph attribute holds only the added nodes and edges; they are added to the schema with the same + graph id, so the schema does not have to be copied into the flavor's source set. A file without the attribute + replaces the lower-priority one as before. See "Flavor-Specific Routing" in the README. +* `Path.endsWith(target: Target)`: `path.endsWith(Target.appFlow.login)` instead of a comparison of the last + segment's name with a string. +* `ParallelFlowNode.initialRegions`: the regions which start together with the node (all of them by default). The + other ones have no nodes until `startRegion(regionId)`, or a `NavigateTo` with a target inside of them, + starts them: tabs which load on the first selection need no placeholder nodes. + `isRegionStarted(regionId)` tells whether a region has nodes. A region of the root parallel which starts later + through `startRegion` gets the payload the service was started with, as the ones started at once do. Back which + is sent with `DispatchBackTo` to a region which is not started is ignored. +* `way-compose`: `FocusedRegionHost(regionId)` renders only one region of a parallel node (the selected tab) and keeps + the saved state of the other ones, `contentModifier` goes to the content of the region; + `collectActiveNode(regionId)` and `collectIsRegionAtRoot(regionId)` take a schema-relative region id. +* `ParallelFlowNode.isRegionAtRoot(regionId)`: the state of a region is readable in `transition()`, so Back can be + sent to an overlay region only when it shows something, without a listener which copies the state into the node. +* `BaseParallelFlowNode`: a parallel flow node with hooks, the counterpart of `BaseFlowNode`. +* `way-compose`: `rememberTransitionSpec()` with `pushTransition()`, `popTransition()`, `fadeTransition()` and + `noTransition()`, a spec which slides forward when the target path continues the source one and back in the + reverse case. + +### Changed + +* `way-compose`: `NodeHost(regionId)`, `collectActiveNode` and `collectIsRegionAtRoot` start from the current state of + the service, not from an empty one for the first frame: a host which enters composition later (a tab, an overlay) + shows its node at once. `NavigationService.currentState()` returns that state. +* The methods of `ServiceExtensionPoint`, `NodeExtensionPoint`, `FlowNodeHook` and `ScreenNodeHook` have empty default + implementations. +* `ParallelFlowNode` has new members `initialRegions`, `startRegion`, `isRegionStarted` and `isRegionAtRoot`: a + subclass which declares a member with one of these names has to rename it. +* The regions of a parallel flow which is declared inside of a region of the root schema start when this parallel + is entered and are removed when it is left. They were started together with the service and never removed. +* `NodeBuilder` has new members `snapshotCache` and `restoreCache` with default implementations, the generated + builders override them. A hand-written builder which caches its child builders should override them too. +* A node which is entered is built once per transition: the node which is asked about its `initial` target or + `initialRegions` is the one which is entered. A child flow node was built twice. + +### Fixed + +* `RegionId.resolveAbsolute` returned a wrong path for a region of a parallel which is declared deeper than the + root of an imported schema, so `DispatchBackTo` with a generated region id of such a parallel fell back to the + deepest region. +* A relative target from a node of a parallel flow into one of its regions changed the region of the parallel + itself, not the target one. +* A flow which has both a nested parallel flow and a screen of its own failed with "path must have at least one + segment" on a relative target to this screen. +* A parallel flow which is left got its `onExit` before the nodes of its regions did. Now the nodes of the regions + exit first, an inner parallel exits before the outer one. +* A parallel flow declared inside of a region of another parallel which is left stayed mounted together with its + regions. +* A schema whose root is a flow with a parallel flow declared under it failed at start with "parallel-flow root + must be a ParallelFlowNode". The root flow is the first region of such a schema now: the generated region ids + get an entry for it, and `ChildFinishRequest` is generated. The region enum keeps the regions of the parallel + only. +* Back was delivered to every region of a parallel flow declared under a flow inside of a region of the root schema, + each of them handled it. Now it goes into one region, chosen by the parallel, as it does for any other parallel. +* The regions of a parallel flow declared deeper inside of an imported parallel schema were started together with + this schema, before their parallel was entered, and never got `onExit`. +* A parallel flow which is entered by a `NavigateTo` with a target inside of it got its `onEntry` before the flows + above it, and before the nodes which the same transition leaves got their `onExit`. +* A transition which fails restores the state first and only then calls `onEntry` of the nodes which had got + `onExit`: such a node saw the half-changed state. +* Gradle plugin: a flow or a parallel flow declared inside of a flow which is not the root of its schema failed with + "illegal path build requested": the node builder of the root asked the outer flow's builder to build it. +* A parallel flow which an initial target has entered was built and entered once more by the first `NavigateTo` + with a target inside of it, and the first node never got its `onExit`. +* A parallel flow declared under a flow got `transition(Event.Back)` twice for one Back. +* A node whose `onEntry` throws gets `onExit` when the failed transition is rolled back, as the nodes entered before + it do. It was left entered half-way. +* A node whose `onPreExit` hook throws before its `onExit` is reached is not entered back when the failed transition + is rolled back. +* An event which a node has sent from `onEntry` or `onExit` while a failed transition was rolled back stayed in the + queue and was handled after the next event. +* A transition which fails restores the child node builders as they were before it. A builder which it had created + for a parameterized schema stayed cached, so the next transition built the nodes of this schema with the argument + of the failed one. + ## 0.10.3 - 2026-10-06 ### Fixed diff --git a/README.md b/README.md index 85df3cd..36edf9e 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ The Compose integration (`:way-compose`) renders active nodes with `NodeHost`. - `:sample` - JVM sample (KMP multi-target support is not yet released). - `:sample-compose:*` - Android sample split into feature modules. - `:sample-compose:main-parallel:*` - tab-bar example using `ParallelFlowNode` (see [Compose Integration](#compose-integration)). - - `:sample-compose:app:routing` - `google`/`huawei` product flavors with per-flavor `.dot` overrides (see [Flavor-Specific Routing](#flavor-specific-routing)). + - `:sample-compose:app:routing` - `google`/`huawei` product flavors with a per-flavor `.dot` extension (see [Flavor-Specific Routing](#flavor-specific-routing)). ## Requirements @@ -88,6 +88,8 @@ digraph App { - `package` - output package for generated code. - `schemaFileName` - override generated schema file/class base name. - `targetsFileName` - override generated targets file/class base name. +- `mode = "extend"` - the file adds nodes and edges to the schema with the same graph id instead of declaring one + (see [Flavor-Specific Routing](#flavor-specific-routing)). ### Supported node attributes @@ -159,26 +161,52 @@ none of them can be a parallel node. ### Flavor-Specific Routing Android product flavors can each get their own `.dot` file for the same schema — e.g. a step only -some flavors need. Resolution works exactly like Android resource merging: a file at -`src//way/.dot` **fully replaces** the file at the same relative path in a -lower-priority source set (never merged). Priority, low to high: +some flavors need. Priority of the source sets, low to high: `main` < flavor < build type < flavor+buildType variant-specific. +A flavor file either **extends** the schema or **replaces** it. + +**Extend.** A file with the `mode = "extend"` graph attribute holds only what the flavor adds. Its nodes and +edges are added to the schema with the same graph id, and the result is validated as a whole: + +``` +src/main/way/app-flow.dot # app -> main +src/google/way/app-flow.dot # extension: app -> login (only google has a login step) ``` -src/main/way/app-flow.dot # base: app -> login -> main -src/huawei/way/app-flow.dot # override: app -> main (huawei skips login) + +```dot +digraph App { + mode = "extend" + + login [type=schema, resultType = "ru.kode.way.sample.compose.login.routing.LoginFlowResult"] + + app -> login +} ``` +- The extended schema is found by the graph id (`digraph App`), so the file may have any name. With the name of + the base file it sits next to it in the flavor's source set, as above. +- An extension is meant to add: it can't remove a node or an edge, declare the type of a node of the schema anew, + or set `package`, `schemaFileName`, `targetsFileName`. Attributes it gives to an untyped node of the schema (a + screen's parameter) do overwrite the schema's ones, as a repeated declaration in one file does. +- Segment ids of the nodes — the added ones too — are built from the path of the base file, so the nodes common + to all flavors have the same ids in every flavor. +- Several extensions of one schema (a flavor's and a build type's) are all applied. + +**Replace.** A file without the attribute at `src//way/.dot` **fully replaces** the file at the +same relative path in a lower-priority source set (together with the extensions at this path), exactly like +Android resource merging. Use it when a flavor has to drop something. + The plugin registers one `generateWayClasses` task per Android variant (`generateGoogleDebugWayClasses`, `generateHuaweiDebugWayClasses`, ...), each writing to -`build/generated/way/code//`. A flavor that doesn't override anything simply reuses +`build/generated/way/code//`. A flavor without files of its own simply reuses `main`'s file as its own input — there is no `generated/way/code/main/`, since `main` is a contributing source set, never a buildable variant on its own. -**The gotcha: hand-written code can't straddle flavors.** `.dot` overrides use full-file -*replacement*; ordinary Kotlin/Java source sets (`src/main/kotlin`, `src/google/kotlin`, +**The gotcha: hand-written code can't straddle flavors.** Whichever way a flavor changes a schema, its generated +code differs, while ordinary Kotlin/Java source sets (`src/main/kotlin`, `src/google/kotlin`, `src/huawei/kotlin`) use plain Gradle *union* — every flavor's compilation always includes -`main/kotlin`. So if one flavor's `.dot` file declares a node another flavor's doesn't, the +`main/kotlin`. So if one flavor's schema has a node another flavor's doesn't, the flavor missing it won't generate the matching class member (e.g. `AppChildFinishRequest.Login`), and hand-written code in `src/main/kotlin` referencing it fails with `Unresolved reference` for that flavor. @@ -186,10 +214,12 @@ that flavor. Rule: anything touching a symbol that isn't in **every** flavor's generated output must live in that flavor's own Kotlin source set (`src/google/kotlin`, `src/huawei/kotlin`, ...), not `src/main/kotlin`. Code that stays in `main` may only reference the intersection of what every -flavor generates. +flavor generates. The node factory is such code: the generated `Factory` interface has a `create…` method +for every node, so a flavor with an added node needs its own factory class (the shared part can stay in `main` +as an abstract class). Worked example: `sample-compose/app/routing` (`google` / `huawei` flavors) — -`src/huawei/way/app-flow.dot` overrides `src/main/way/app-flow.dot` to drop a Google-only login +`src/google/way/app-flow.dot` extends `src/main/way/app-flow.dot` with a Google-only login step, and the hand-written `AppFlow.kt` / `AppFlowNode.kt` / `di/AppFlowComponent.kt` are duplicated per flavor under `src/google/kotlin` / `src/huawei/kotlin` accordingly. `src/test/kotlin/.../AppFlowNodeTest.kt` is a shared test that only touches the symbols common to @@ -432,7 +462,7 @@ class MainTabsNode : ParallelFlowNode(), ComposableNode { } ``` -Pass a `RegionId` from `NavigationState.regions` keys or a generated `.RegionId` constant. A `DispatchBackTo` naming a region that is no longer alive is **not** an error — Back soft-falls-back to the deepest active region, so the back button never crashes. +Pass a `RegionId` from `NavigationState.regions` keys or a generated `.RegionId` constant. A `DispatchBackTo` naming a region that is no longer alive is **not** an error — Back soft-falls-back to the deepest active region, so the back button never crashes. Back to a region which is not started yet (see `initialRegions` below) is ignored. Transitions: - `NavigateTo(targets)` @@ -480,6 +510,55 @@ also drops any intermediate screens. - Supports node/service extension points. - Handles queued events one-by-one after each transition. +### Regions which start later + +All regions of a parallel node start together with it. To start some of them later (a tab which loads on its first +selection), list the ones which start at once in `initialRegions` and start the others with `startRegion`: + +```kotlin +class HomeNode : ParallelFlowNode(), ComposableNode { + private var focused by mutableStateOf(schema.mainTabRegionId) + + override val initialRegions get() = setOf(schema.mainTabRegionId) + + override fun transition(event: Event): FlowTransition = when (event) { + is TabSelected -> { + focused = event.regionId + startRegion(event.regionId) // Stay if the region is already started + } + Event.Back -> DispatchBackTo(focused) + else -> Ignore + } + + @Composable + override fun Content(modifier: Modifier) { + FocusedRegionHost(focused, modifier) + } +} +``` + +A region which is not started has no nodes and receives no events. A `NavigateTo` with a target inside of it +starts it too. A started region lives as long as its parallel node: the regions of a +parallel nested in a flow start when this parallel is entered and are removed when it is left. A region of the root +parallel which `startRegion` starts gets the payload of `service.start(payload)`. +`initialRegions` must name at least one region, and a region whose root is itself a parallel flow cannot be started +later. + +`FocusedRegionHost` (`way-compose`) composes only the given region: the other ones cannot show a dialog or a sheet, +and their saved state is restored when they get focus again. Its `modifier` goes to the container which switches +the regions, `contentModifier` to the content of the shown one. + +Inside of `transition` a parallel node can ask about its regions: `isRegionStarted(regionId)` and +`isRegionAtRoot(regionId)` (the region rests on its first node, nothing is open above it). The second one picks the +region for Back when one of the regions is an overlay: + +```kotlin +Event.Back -> DispatchBackTo(if (isRegionAtRoot(schema.fullScreenRegionId)) focused else schema.fullScreenRegionId) +``` + +A parallel node which needs hooks (for example a coroutine scope hook) extends `BaseParallelFlowNode`, the same way +a flow node extends `BaseFlowNode`. + ## Compose Integration `way-compose` provides: @@ -489,6 +568,8 @@ also drops any intermediate screens. - `NodeHost(service)` composable — auto-starts service, observes root region's active node, renders `ComposableNode.Content()`, applies animated transitions. - `LocalEventSink` — the `EventSink` of the node being rendered, provided by `NodeHost` to every node's `Content()`. Always use it in UI: an event sent from a screen's `Content()` starts at that screen, one sent from a parallel's `Content()` at the active children of its regions; it then reaches every parallel enclosing the node and bubbles up through each parallel's ancestors, like `service.send`, and a tap on a screen which is animating out after Back is dropped instead of being applied to the new screen. Outside any node (but under `LocalNavigationService`) it is the service itself, the root sink. - `NodeHost(regionId)` composable — renders the active screen in a specific sub-region. Call from a parallel node's `Content()` for each sub-region. Requires a parent `NodeHost(service)` to have provided `LocalNavigationService`. +- `FocusedRegionHost(regionId)` composable — renders only the given sub-region and keeps the saved state of the other ones. +- `rememberTransitionSpec()` — a transition spec which slides on push and pop (by comparing the paths) and asks `ambiguousTransitionResolver` for the rest; `pushTransition()`, `popTransition()`, `fadeTransition()`, `noTransition()` are its parts. Sending screen events: diff --git a/gradle.properties b/gradle.properties index 36a0a39..ec0dd6b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,7 +5,7 @@ kotlin.native.ignoreDisabledTargets=true android.useAndroidX=true -versionName=0.10.3 +versionName=0.11.0 pomGroupId=ru.kode pomDescription=Navigation library based on statechart-like node graphs pomUrl=https://github.com/appKODE/way diff --git a/sample-compose/app/routing/src/google/way/app-flow.dot b/sample-compose/app/routing/src/google/way/app-flow.dot new file mode 100644 index 0000000..4c6ff95 --- /dev/null +++ b/sample-compose/app/routing/src/google/way/app-flow.dot @@ -0,0 +1,7 @@ +digraph App { + mode = "extend" + + login [type=schema, resultType = "ru.kode.way.sample.compose.login.routing.LoginFlowResult"] + + app -> login +} diff --git a/sample-compose/app/routing/src/huawei/kotlin/ru/kode/way/sample/compose/app/routing/AppFlowNode.kt b/sample-compose/app/routing/src/huawei/kotlin/ru/kode/way/sample/compose/app/routing/AppFlowNode.kt index 419753c..ce0eaff 100644 --- a/sample-compose/app/routing/src/huawei/kotlin/ru/kode/way/sample/compose/app/routing/AppFlowNode.kt +++ b/sample-compose/app/routing/src/huawei/kotlin/ru/kode/way/sample/compose/app/routing/AppFlowNode.kt @@ -8,7 +8,7 @@ import ru.kode.way.Ignore import ru.kode.way.Target import javax.inject.Inject -// Huawei flavor's app-flow.dot (src/huawei/way/app-flow.dot) drops the Google-only login step, +// The login step is added by the google flavor's schema extension (src/google/way/app-flow.dot), // so this flow starts directly at "main" instead of "login". class AppFlowNode @Inject constructor() : FlowNode { override val initial: Target = Target.app.main diff --git a/sample-compose/app/routing/src/huawei/way/app-flow.dot b/sample-compose/app/routing/src/huawei/way/app-flow.dot deleted file mode 100644 index 3e5d1a7..0000000 --- a/sample-compose/app/routing/src/huawei/way/app-flow.dot +++ /dev/null @@ -1,10 +0,0 @@ -digraph App { - package = "ru.kode.way.sample.compose.app.routing" - - app [type=flow] - main [type=schema, resultType = "ru.kode.way.sample.compose.main.routing.MainFlowResult"] - mainParallel [type=schema] - - app -> main - app -> mainParallel -} diff --git a/sample-compose/app/routing/src/main/way/app-flow.dot b/sample-compose/app/routing/src/main/way/app-flow.dot index e198893..3e5d1a7 100644 --- a/sample-compose/app/routing/src/main/way/app-flow.dot +++ b/sample-compose/app/routing/src/main/way/app-flow.dot @@ -2,11 +2,9 @@ digraph App { package = "ru.kode.way.sample.compose.app.routing" app [type=flow] - login [type=schema, resultType = "ru.kode.way.sample.compose.login.routing.LoginFlowResult"] main [type=schema, resultType = "ru.kode.way.sample.compose.main.routing.MainFlowResult"] mainParallel [type=schema] - app -> login app -> main app -> mainParallel } diff --git a/sample-compose/app/routing/src/testGoogle/kotlin/ru/kode/way/sample/compose/app/routing/AppFlowNodeGoogleTest.kt b/sample-compose/app/routing/src/testGoogle/kotlin/ru/kode/way/sample/compose/app/routing/AppFlowNodeGoogleTest.kt index baf090c..aa8fc2b 100644 --- a/sample-compose/app/routing/src/testGoogle/kotlin/ru/kode/way/sample/compose/app/routing/AppFlowNodeGoogleTest.kt +++ b/sample-compose/app/routing/src/testGoogle/kotlin/ru/kode/way/sample/compose/app/routing/AppFlowNodeGoogleTest.kt @@ -4,9 +4,9 @@ import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe import ru.kode.way.Target -// Target.app.login only exists because google's app-flow.dot (src/main/way) declares a "login" -// node — a huawei test referencing it would fail to compile, which is itself part of the proof -// that flavor dot-file overrides produce genuinely different generated schemas. +// Target.app.login only exists because google's schema extension (src/google/way/app-flow.dot) adds +// a "login" node — a huawei test referencing it would fail to compile, which is itself part of the +// proof that a flavor's dot file produces a genuinely different generated schema. class AppFlowNodeGoogleTest : ShouldSpec({ should("start at login in the google flavor's app flow") { diff --git a/way-compose/src/main/kotlin/ru/kode/way/compose/NodeHost.kt b/way-compose/src/main/kotlin/ru/kode/way/compose/NodeHost.kt index 490507a..3704c64 100644 --- a/way-compose/src/main/kotlin/ru/kode/way/compose/NodeHost.kt +++ b/way-compose/src/main/kotlin/ru/kode/way/compose/NodeHost.kt @@ -23,10 +23,10 @@ import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.SaveableStateHolder +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext @@ -160,8 +160,10 @@ private fun NodeAnimatedContent( // exit animation included) leaves. Snapshot-backed so the cleanup effect re-runs when it changes. val mountedKeys = remember { mutableStateListOf() } // Keys we have handed to the SaveableStateHolder, so the cleanup effect knows what to purge. Plain - // (non-snapshot) set: only read imperatively inside the effect, never during composition. - val trackedKeys = remember { mutableSetOf() } + // (non-snapshot) set: only read imperatively inside the effect, never during composition. Saveable, because the + // holder outlives this host when the host leaves the composition (see FocusedRegionHost): a node which left its + // region meanwhile must not hand its saved state to a new node at the same path. + val trackedKeys = rememberSaveable { mutableSetOf() } val activePath = activeNode?.path val activeKey = activePath?.toSaveableKey() @@ -243,10 +245,10 @@ private fun collectRootNode(service: NavigationService<*>): State } /** - * A [State] reflecting [transform] applied to every [NavigationState] this service emits (and - * `initial` before the first). Registers a transition listener for the composition's lifetime and + * A [State] reflecting [transform] applied to the current [NavigationState] and to every one this service emits + * later (`initial` while the service is not started). Registers a transition listener for the composition's lifetime and * removes it on dispose — the listener lifecycle every collector in this module shares. Extra [keys] - * (beyond the service) re-key the underlying [produceState]. + * (beyond the service) re-key the state. */ @Composable internal fun NavigationService<*>.produceTransitionState( @@ -254,12 +256,16 @@ internal fun NavigationService<*>.produceTransitionState( vararg keys: Any?, transform: (NavigationState) -> T, ): State = key(this, *keys) { - // keyed outside produceState: its value survives a key change, so a new service would start from the old value - produceState(initial) { - val listener = { s: NavigationState -> value = transform(s) } + // starts from the current state: with `initial` the first frame would show a started service as an empty one. + // The first value lives only in the state: a remembered copy of it would keep its node alive after that node exits + val state = remember { mutableStateOf(currentState()?.let(transform) ?: initial) } + DisposableEffect(Unit) { + val listener = { s: NavigationState -> state.value = transform(s) } + // a started service reports its current state right away, so a transition before this effect is not lost addTransitionListener(listener) - awaitDispose { removeTransitionListener(listener) } + onDispose { removeTransitionListener(listener) } } + state } private fun Region.toNodeWithPath(): NodeWithPath = NodeWithPath(active, activeNode) @@ -400,5 +406,55 @@ fun NodeHost( ) } +/** + * Renders only [regionId] out of the regions of a parallel node, e.g. the selected tab. The other regions are not + * composed, so they show no dialogs or sheets, and their saved state is kept and restored when [regionId] points to + * them again. A region which is not started yet (see [ParallelFlowNode.initialRegions]) renders nothing. + * + * Has the same requirements as [NodeHost] with a region id. [regionTransitionSpec] animates the change of [regionId], + * [transitionSpec] animates navigation inside of the region. [modifier] is applied to the host itself, + * [contentModifier] is passed to the content of the nodes, as the modifier of [NodeHost] is. + */ +@ExperimentalAnimationApi +@Composable +fun FocusedRegionHost( + regionId: RegionId, + modifier: Modifier = Modifier, + contentModifier: Modifier = Modifier, + regionTransitionSpec: AnimatedContentTransitionScope.() -> ContentTransform = { + fadeIn() togetherWith + fadeOut() + }, + transitionSpec: AnimatedContentTransitionScope.() -> ContentTransform = defaultTransitionSpec, +) { + val saveableStateHolder = rememberSaveableStateHolder() + AnimatedContent( + targetState = regionId, + modifier = modifier, + transitionSpec = regionTransitionSpec, + label = "FocusedRegionHost", + ) { id -> + saveableStateHolder.SaveableStateProvider(id.path.toSaveableKey()) { + NodeHost(regionId = id, modifier = contentModifier, transitionSpec = transitionSpec) + } + } +} + +/** + * The active node in [regionId] of the parallel node which is being rendered, reactively. Unlike the overload with + * a service, [regionId] may be schema-relative. `null` while the region is not started. + */ +@Composable +fun collectActiveNode(regionId: RegionId): State = + collectActiveNode(LocalNavigationService.current, regionId.resolveAbsolute(LocalNodePath.current)) + +/** + * Whether [regionId] of the parallel node which is being rendered rests on its first node, reactively. Unlike the + * overload with a service, [regionId] may be schema-relative. `false` while the region is not started. + */ +@Composable +fun collectIsRegionAtRoot(regionId: RegionId): State = + collectIsRegionAtRoot(LocalNavigationService.current, regionId.resolveAbsolute(LocalNodePath.current)) + @Immutable data class NodeWithPath(val path: Path, val node: Node) diff --git a/way-compose/src/main/kotlin/ru/kode/way/compose/TransitionSpecs.kt b/way-compose/src/main/kotlin/ru/kode/way/compose/TransitionSpecs.kt new file mode 100644 index 0000000..eedbe2f --- /dev/null +++ b/way-compose/src/main/kotlin/ru/kode/way/compose/TransitionSpecs.kt @@ -0,0 +1,73 @@ +package ru.kode.way.compose + +import androidx.compose.animation.AnimatedContentTransitionScope +import androidx.compose.animation.ContentTransform +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import ru.kode.way.Path +import ru.kode.way.startsWith + +/** + * A transition spec for [NodeHost] which tells a push from a pop by the two paths: a target path which continues + * the source one (`app.login.password` to `app.login.password.otp`) is a push, the reverse is a pop. + * Any other pair of paths is passed to [ambiguousTransitionResolver], which can inspect `initialState` and + * `targetState`. The first content of a host appears with [noTransition]. + * + * If the kind is derived incorrectly for your case, write your own spec instead. + */ +@Composable +fun rememberTransitionSpec( + ambiguousTransitionResolver: AnimatedContentTransitionScope.() -> ContentTransform = { + pushTransition() + }, +): AnimatedContentTransitionScope.() -> ContentTransform { + val resolver by rememberUpdatedState(ambiguousTransitionResolver) + return remember { + { + val fromNode = initialState + val toNode = targetState + when { + fromNode != null && toNode != null -> { + if (toNode.length > fromNode.length && toNode.startsWith(fromNode)) { + pushTransition() + } else if (toNode.length < fromNode.length && fromNode.startsWith(toNode)) { + popTransition() + } else { + resolver() + } + } + + else -> noTransition() + } + } + } +} + +fun AnimatedContentTransitionScope<*>.pushTransition(): ContentTransform = ( + slideIntoContainer(towards = AnimatedContentTransitionScope.SlideDirection.Left) togetherWith + slideOutOfContainer(towards = AnimatedContentTransitionScope.SlideDirection.Left) + ) + .using(sizeTransform = null) + +fun AnimatedContentTransitionScope<*>.popTransition(): ContentTransform = ( + slideIntoContainer(towards = AnimatedContentTransitionScope.SlideDirection.Right) togetherWith + slideOutOfContainer(towards = AnimatedContentTransitionScope.SlideDirection.Right) + ) + .using(sizeTransform = null) + +fun AnimatedContentTransitionScope<*>.fadeTransition(): ContentTransform { + // these timings are taken from AnimatedContent's sources + return (fadeIn(animationSpec = tween(220, delayMillis = 90)) togetherWith fadeOut(animationSpec = tween(90))) + .using(sizeTransform = null) +} + +fun AnimatedContentTransitionScope<*>.noTransition(): ContentTransform = + (EnterTransition.None togetherWith ExitTransition.None).using(sizeTransform = null) diff --git a/way-compose/src/test/kotlin/ru/kode/way/compose/FocusedRegionHostTest.kt b/way-compose/src/test/kotlin/ru/kode/way/compose/FocusedRegionHostTest.kt new file mode 100644 index 0000000..36bc69e --- /dev/null +++ b/way-compose/src/test/kotlin/ru/kode/way/compose/FocusedRegionHostTest.kt @@ -0,0 +1,133 @@ +package ru.kode.way.compose + +import androidx.compose.animation.ExperimentalAnimationApi +import androidx.compose.foundation.clickable +import androidx.compose.foundation.text.BasicText +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import ru.kode.way.Event +import ru.kode.way.FlowTransition +import ru.kode.way.Ignore +import ru.kode.way.NavigationService +import ru.kode.way.Node +import ru.kode.way.ParallelFlowNode +import ru.kode.way.Path +import ru.kode.way.RegionId +import ru.kode.way.Schema +import ru.kode.way.ScreenNode +import ru.kode.way.ScreenTarget +import ru.kode.way.ScreenTransition +import ru.kode.way.Segment + +@OptIn(ExperimentalAnimationApi::class) +@RunWith(RobolectricTestRunner::class) +class FocusedRegionHostTest { + @get:Rule + val rule = createComposeRule() + + private var regionRoots: List = emptyList() + + private val service = NavigationService( + TestNodeBuilder( + TestSchema( + "tabs", + mapOf( + "alpha" to Schema.NodeType.Flow, + "alpha.screen" to Schema.NodeType.Screen, + "beta" to Schema.NodeType.Flow, + "beta.screen" to Schema.NodeType.Screen, + ), + subRegions = listOf("alpha", "beta"), + childSchemas = listOf("alpha", "beta").associate { + Segment(it) to TestSchema(it, mapOf("screen" to Schema.NodeType.Screen)) + }, + ), + ) { path, _ -> + val segments = path.split('.') + when (segments.size) { + 1 -> TabsNode() + 2 -> TestFlowNode(initial = ScreenTarget(Path("screen")), transitions = emptyMap()) + else -> CounterScreen(segments[1]) + } + }, + onFinishRequest = { Ignore }, + ).apply { addTransitionListener { state -> regionRoots = state.regions.keys.map { it.path } } } + + private fun focus(region: String) { + rule.runOnIdle { service.send(TestEvent(region)) } + rule.waitForIdle() + } + + @Test + fun `only the focused region is rendered and a region starts when it gets focus`() { + rule.setContent { NodeHost(service) } + + rule.onNodeWithText("alpha 0").assertExists() + rule.onNodeWithText("beta 0").assertDoesNotExist() + assertEquals(listOf(Path("tabs", "alpha")), regionRoots) + + focus("beta") + + rule.onNodeWithText("beta 0").assertExists() + rule.onNodeWithText("alpha 0").assertDoesNotExist() + assertEquals(listOf(Path("tabs", "alpha"), Path("tabs", "beta")), regionRoots) + } + + @Test + fun `saved state of a region survives losing focus`() { + rule.setContent { NodeHost(service) } + rule.onNodeWithText("alpha 0").performClick() + rule.onNodeWithText("alpha 1").assertExists() + + focus("beta") + focus("alpha") + + rule.onNodeWithText("alpha 1").assertExists() + } + + private class TabsNode : + ParallelFlowNode(), + ComposableNode { + private var focused by mutableStateOf(regionId("alpha")) + override val dismissResult = Unit + override val initialRegions get() = setOf(regionId("alpha")) + + override fun transition(event: Event): FlowTransition { + val regionId = (event as? TestEvent)?.let { regionId(it.name) } ?: return Ignore + focused = regionId + return startRegion(regionId) + } + + @Composable + override fun Content(modifier: Modifier) { + FocusedRegionHost(focused, modifier) + } + + private fun regionId(name: String) = RegionId(Path("tabs", name)) + } + + private class CounterScreen(private val name: String) : + ScreenNode, + ComposableNode { + override fun transition(event: Event): ScreenTransition = Ignore + + @Composable + override fun Content(modifier: Modifier) { + var count by rememberSaveable { mutableIntStateOf(0) } + BasicText("$name $count", modifier.clickable { count++ }) + } + } +} diff --git a/way-compose/src/test/kotlin/ru/kode/way/compose/NodeRetentionTest.kt b/way-compose/src/test/kotlin/ru/kode/way/compose/NodeRetentionTest.kt new file mode 100644 index 0000000..e778216 --- /dev/null +++ b/way-compose/src/test/kotlin/ru/kode/way/compose/NodeRetentionTest.kt @@ -0,0 +1,37 @@ +package ru.kode.way.compose + +import androidx.compose.animation.ExperimentalAnimationApi +import androidx.compose.ui.test.junit4.createComposeRule +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.lang.ref.WeakReference + +@OptIn(ExperimentalAnimationApi::class) +@RunWith(RobolectricTestRunner::class) +class NodeRetentionTest { + @get:Rule + val rule = createComposeRule() + + @Test + fun `node which was active when the host was composed is released after it exits`() { + val fixture = FlowFixture() + fixture.service.start() + fixture.service.send(TestEvent("D")) + rule.setContent { NodeHost(fixture.service) } + val exited = rule.runOnIdle { WeakReference(fixture.screen("details", "a")) } + + rule.runOnIdle { fixture.service.send(TestEvent("R")) } + rule.waitForIdle() + fixture.screens.clear() + + for (attempt in 1..10) { + if (exited.get() == null) break + System.gc() + Thread.sleep(50) + } + assertNull(exited.get()) + } +} diff --git a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/AdjacencyList.kt b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/AdjacencyList.kt index d71ad48..b2888eb 100644 --- a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/AdjacencyList.kt +++ b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/AdjacencyList.kt @@ -127,19 +127,19 @@ internal fun AdjacencyList.parallelParentOf(node: Node): Node.Flow.LocalParallel * Returns the "region roots" — the entry-point flow of every independently-navigable region in this schema. * * A region root is a direct child of any [Node.Flow.LocalParallel] whose immediate parent is NOT itself a - * LocalParallel. For a plain (non-parallel) graph with no such parallel, the single root flow node is the only - * region root. + * LocalParallel. A root flow is a region root too and goes first: for a plain (non-parallel) graph it is the only + * one, for a flow with a parallel declared under it the regions of this parallel follow it. * * This intentionally collects region roots at EVERY nesting depth, not just the top parallel's children. A * parallel reached through a linear [Node.Flow.Local] flow (e.g. * `acmeAppFlow[parallelFlow] -> acmeMainFlow[flow] -> acmeTabsFlow[parallelFlow] -> acmeHomeTab/acmeExploreTab`) * starts a NEW region tier, so `acmeHomeTab`/`acmeExploreTab` surface as region roots alongside the top parallel's * own children `acmeMainFlow`/`acmeAuthFlow` — four flat region roots in total. This is CORRECT and required, NOT - * over-collection: the runtime region model is FLAT. `NavigationService.materializeRegion` iterates - * `schema.regions` once and creates one top-level `Region` per entry, keyed by its full absolute path (region - * depth is encoded in the path, never in map nesting), and `pruneOrphanRegions` pins every `schema.regions` entry - * for the service lifetime. The generated `AcmeAppFlowSchema.regions` must therefore list all four so the runtime - * materialises all four. This is asserted directly by the runtime contract test + * over-collection: the runtime region model is FLAT. `NavigationService.materializeRegion` creates one top-level + * `Region` per `schema.regions` entry, keyed by its full absolute path (region depth is encoded in the path, never + * in map nesting): the regions of the root parallel at start, the deeper ones when their parallel is entered (they + * live as long as it does). The generated `AcmeAppFlowSchema.regions` must therefore list all four so the runtime + * can materialise all four. This is asserted directly by the runtime contract test * "acme-style layout: each region has its own absolute regionId.path anchored at acmeAppFlow" * (`way/src/commonTest/.../ParallelNodeTest.kt`); reducing this * to two would fail that test and break navigation. The same flat set is what `AdjacencyListTest` pins. @@ -159,14 +159,14 @@ internal fun AdjacencyList.parallelParentOf(node: Node): Node.Flow.LocalParallel */ internal fun buildRegionRoots(adjacencyList: AdjacencyList): List { val regionRoots = mutableListOf() + // a root flow is a region itself, the regions of the parallels declared under it come after it + val root = adjacencyList.findRootNode() + if (root !is Node.Flow.LocalParallel) regionRoots.add(root) adjacencyList.forEach { (node, children) -> if (node is Node.Flow.LocalParallel && adjacencyList.findParent(node) !is Node.Flow.LocalParallel) { regionRoots.addAll(children) } } - if (regionRoots.isEmpty()) { - regionRoots.add(adjacencyList.findRootNode()) - } return regionRoots } diff --git a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/Codegen.kt b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/Codegen.kt index 44649a2..c5c8019 100644 --- a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/Codegen.kt +++ b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/Codegen.kt @@ -187,9 +187,9 @@ internal fun buildSpecs( emitParentParallelEntries = false, ) } - // For top-level schemas with more than one region (i.e. parallel-rooted), emit a Region enum - // so consumers can use a typed identifier for each sub-region instead of comparing RegionId - // values directly. Single-region (flow-rooted) schemas have no meaningful enum to emit. + // For top-level schemas with more than one region of a parallel, emit a Region enum so consumers can use + // a typed identifier for each of them instead of comparing RegionId values directly. A schema without + // a parallel has no meaningful enum to emit. val regionEnumSpec = buildRegionEnumFileSpecOrNull(parseResult, config) return SchemaOutputSpecs( schemaFileSpec = buildSchemaFileSpec(parseResult, config, registry), diff --git a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/FlavorSourceResolution.kt b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/FlavorSourceResolution.kt index 99e53df..9b49ece 100644 --- a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/FlavorSourceResolution.kt +++ b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/FlavorSourceResolution.kt @@ -34,7 +34,7 @@ internal fun variantSourceSetNamesInPriorityOrder(identity: ComponentIdentity): } /** - * File-level full-replacement override resolver. + * File-level override resolver. * * [sourceSetDirsInPriorityOrder] holds, for each contributing source set in ascending priority * order (as produced by [variantSourceSetNamesInPriorityOrder]), the list of `way/` directories @@ -42,9 +42,12 @@ internal fun variantSourceSetNamesInPriorityOrder(identity: ComponentIdentity): * path relative to the containing directory; when a higher-priority source set has a `.dot` file * at the same relative path as a lower-priority one, it fully replaces it. Files present in only * one source set pass through unchanged. + * + * A schema extension (see [isSchemaExtensionFile]) replaces nothing: it is returned together with + * the lower-priority files at its relative path. */ internal fun resolveOverriddenDotFiles(sourceSetDirsInPriorityOrder: List>): List { - val fileByRelativePath = LinkedHashMap() + val filesByRelativePath = LinkedHashMap>() sourceSetDirsInPriorityOrder.forEach { dirs -> dirs.forEach { dir -> if (dir.isDirectory) { @@ -52,10 +55,13 @@ internal fun resolveOverriddenDotFiles(sourceSetDirsInPriorityOrder: List candidate.isFile && candidate.extension == "dot" } .forEach { dotFile -> val relativePath = dotFile.relativeTo(dir).path - fileByRelativePath[relativePath] = dotFile + val overridden = filesByRelativePath[relativePath].orEmpty() + // only a file which overrides another one is read: this runs at configuration time + filesByRelativePath[relativePath] = + if (overridden.isNotEmpty() && isSchemaExtensionFile(dotFile)) overridden + dotFile else listOf(dotFile) } } } } - return fileByRelativePath.values.toList() + return filesByRelativePath.values.flatten() } diff --git a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/GenerateClassesTask.kt b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/GenerateClassesTask.kt index 255bd6e..bc78b42 100644 --- a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/GenerateClassesTask.kt +++ b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/GenerateClassesTask.kt @@ -51,10 +51,8 @@ abstract class GenerateClassesTask : SourceTask() { logger.debug("generation started") val files = source.toList() // Parse all files first so we can detect output filename collisions before writing anything. - val parseResults = files.map { file -> - logger.debug("parsing schema file: $file") - parseSchemaDotFile(file, projectDir, warn = logger::warn) - } + logger.debug("parsing schema files: $files") + val parseResults = parseSchemaDotFiles(files, projectDir, warn = logger::warn) validateNoOutputFileCollisions(parseResults, config) // An empty (or whitespace-only) schema file parses to an empty adjacencyList with no // validator errors — SchemaRegistry.from() already skips these silently for registry-matching diff --git a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/NodeBuilderCodegen.kt b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/NodeBuilderCodegen.kt index e7226db..13e27d9 100644 --- a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/NodeBuilderCodegen.kt +++ b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/NodeBuilderCodegen.kt @@ -332,6 +332,32 @@ internal fun buildNodeBuilderTypeSpec( } .build(), ) + .apply { + if (lazyNodeBuilderFactories.isNotEmpty()) { + addFunction( + FunSpec.builder("snapshotCache") + .addModifiers(KModifier.OVERRIDE) + .returns(ANY.copy(nullable = true)) + .addStatement( + "return %L.mapValues·{·(_,·builder)·->·builder·to·builder.snapshotCache()·}", + NODE_BUILDER_CACHE_PROPERTY_NAME, + ) + .build(), + ) + addFunction( + FunSpec.builder("restoreCache") + .addModifiers(KModifier.OVERRIDE) + .addParameter("snapshot", ANY.copy(nullable = true)) + .addStatement("%L.clear()", NODE_BUILDER_CACHE_PROPERTY_NAME) + .beginControlFlow("(snapshot·as·%T<*,·*>).forEach·{·(path,·saved)·->", MAP) + .addStatement("val·(builder,·childSnapshot)·=·saved·as·%T<*,·*>", ClassName("kotlin", "Pair")) + .addStatement("%L[path·as·%T]·=·builder·as·%T", NODE_BUILDER_CACHE_PROPERTY_NAME, PATH, NODE_BUILDER) + .addStatement("builder.restoreCache(childSnapshot)") + .endControlFlow() + .build(), + ) + } + } .addFunction(buildTargetOrErrorFunSpec()) .apply { if (lazyNodeBuilderFactories.keys.any { adjacencyList.isFanIn(it) }) addFunction(buildTargetsOrErrorFunSpec()) @@ -393,10 +419,19 @@ private fun createBuildFunctionBody( .endControlFlow() .beginControlFlow("return when") .apply { + val nodes = mutableListOf() dfsWhile(adjacencyList, flow) { node -> - val shouldDescend = shouldDescendInto(node, flow) // See NOTE_GROUPING_NODES_BY_FLOW_RULE — foreign nodes route through their own flow's NodeBuilder. - if (isForeignToFlowScope(node, flow, isRootNode, adjacencyList)) return@dfsWhile shouldDescend + if (!isForeignToFlowScope(node, flow, isRootNode, adjacencyList)) nodes.add(node) + shouldDescendInto(node, flow) + } + // A flow declared inside of another flow of this schema goes first: the outer one is a prefix of its paths too. + // Only the flows are reordered, each of the other nodes stays where the traversal has put it. + val isNestedFlow = { node: Node -> node is Node.Flow && node != flow } + val nestedFlows = nodes.filter(isNestedFlow) + .sortedByDescending { node -> adjacencyList.parentChains(node).maxOf { it.size } } + .iterator() + nodes.map { node -> if (isNestedFlow(node)) nestedFlows.next() else node }.forEach { node -> when (node) { is Node.Flow -> { if (node == flow) { @@ -501,7 +536,6 @@ private fun createBuildFunctionBody( // History nodes are never built, so they emit no routing branch. is Node.History -> Unit } - shouldDescend } addStatement("else -> error(%P)", "illegal path build requested for \"${flow.id}\" node: \$path") } diff --git a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/Parser.kt b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/Parser.kt index 637c1b0..3ec1991 100644 --- a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/Parser.kt +++ b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/Parser.kt @@ -10,14 +10,72 @@ import java.nio.file.Path import kotlin.io.path.relativeTo internal fun parseSchemaDotFile(file: File, projectDir: File, warn: (String) -> Unit = {}): SchemaParseResult = - file.inputStream().use { input -> - val stream = CommonTokenStream(DotLexer(CharStreams.fromStream(input))) - val parser = DotParser(stream) - val parseTree = parser.graph() + parseSchemaDotFiles(listOf(file), projectDir, warn).single() + +/** + * Parses [files] into one result per schema. A file whose graph has the `mode = "extend"` attribute is not a schema + * of its own: its nodes and edges are added to the schema with the same graph id, which is validated as a whole. + */ +internal fun parseSchemaDotFiles( + files: List, + projectDir: File, + warn: (String) -> Unit = {}, +): List { + val (extensions, schemas) = files.map { it to parseGraph(it) }.partition { (_, graph) -> graph.isSchemaExtension() } + val schemaGraphIds = schemas.map { (_, graph) -> graph.id_()?.asString() } + extensions.forEach { (file, graph) -> + val graphId = graph.id_()?.asString() ?: error("schema extension $file must name the graph it extends") + if (graphId !in schemaGraphIds) { + error("schema extension $file extends \"$graphId\", but there is no schema with this graph id") + } + if (schemaGraphIds.count { it == graphId } > 1) { + error("schema extension $file extends \"$graphId\", but there are several schemas with this graph id") + } + } + return schemas.map { (file, graph) -> val visitor = Visitor() - visitor.visitGraph(parseTree) + visitor.visitGraph(graph) + extensions + .filter { (_, extension) -> extension.id_()?.asString() == graph.id_()?.asString() } + .forEach { (extensionFile, extension) -> visitor.visitExtension(extension, extensionFile) } visitor.buildResult(file.toPath().relativeTo(projectDir.toPath()), warn) } +} + +/** True when [file] extends a schema instead of declaring (or replacing) one, see [parseSchemaDotFiles]. */ +internal fun isSchemaExtensionFile(file: File): Boolean = parseGraph(file).isSchemaExtension() + +private fun parseGraph(file: File): GraphContext = file.inputStream().use { input -> + DotParser(CommonTokenStream(DotLexer(CharStreams.fromStream(input)))).graph() +} + +private fun GraphContext.isSchemaExtension(): Boolean = findGraphAttributeValue(this, MODE_ATTRIBUTE) == MODE_EXTEND + +private const val MODE_ATTRIBUTE = "mode" +private const val MODE_EXTEND = "extend" +private val schemaIdentityAttributes = listOf("schemaFileName", "targetsFileName", "package") + +private fun findGraphAttributeValue(ctx: GraphContext, name: String): String? { + // A genuinely blank/whitespace-only `.dot` file fails ANTLR's grammar check on immediate EOF, + // leaving `ctx.stmt_list()` null. Route that into the same empty-adjacency-list path (and its + // clear "empty navigation graph" error in GenerateClassesTask.generate()) instead of NPEing here. + for (stmt in ctx.stmt_list()?.stmt().orEmpty()) { + // A graph attribute statement is `attrName = attrValue`: id_(0) is the name, id_(1) the value. + val attrName = stmt.id_(0)?.asString() + if (attrName == name) { + return stmt.id_(1)?.asString() ?: error("no value for graph attr '$name'") + } + } + return null +} + +private fun Id_Context.asString(): String = when { + ID() != null -> ID()!!.text + STRING() != null -> STRING()!!.text.removeSurrounding("\"") + HTML_STRING() != null -> HTML_STRING()!!.text.removeSurrounding("<", ">") + NUMBER() != null -> NUMBER()!!.text + else -> error("unrecognized id_ token: ${this.text}") +} private class Visitor : DotBaseVisitor() { private var graphId: String? = null @@ -85,18 +143,14 @@ private class Visitor : DotBaseVisitor() { super.visitGraph(ctx) } - private fun findGraphAttributeValue(ctx: GraphContext, name: String): String? { - // A genuinely blank/whitespace-only `.dot` file fails ANTLR's grammar check on immediate EOF, - // leaving `ctx.stmt_list()` null. Route that into the same empty-adjacency-list path (and its - // clear "empty navigation graph" error in GenerateClassesTask.generate()) instead of NPEing here. - for (stmt in ctx.stmt_list()?.stmt().orEmpty()) { - // A graph attribute statement is `attrName = attrValue`: id_(0) is the name, id_(1) the value. - val attrName = stmt.id_(0)?.asString() - if (attrName == name) { - return stmt.id_(1)?.asString() ?: error("no value for graph attr '$name'") + /** Adds the nodes and edges of [ctx], a `mode = "extend"` graph from [file], to the visited schema. */ + fun visitExtension(ctx: GraphContext, file: File) { + schemaIdentityAttributes.forEach { name -> + if (findGraphAttributeValue(ctx, name) != null) { + error("schema extension $file must not set \"$name\": it is taken from the schema it extends") } } - return null + super.visitGraph(ctx) } override fun visitNode_stmt(ctx: DotParser.Node_stmtContext) { @@ -224,14 +278,6 @@ private class Visitor : DotBaseVisitor() { adjacencyList.getOrPut(to) { mutableSetOf() } adjacencyList[from]?.add(to) } - - private fun Id_Context.asString(): String = when { - ID() != null -> ID()!!.text - STRING() != null -> STRING()!!.text.removeSurrounding("\"") - HTML_STRING() != null -> HTML_STRING()!!.text.removeSurrounding("<", ">") - NUMBER() != null -> NUMBER()!!.text - else -> error("unrecognized id_ token: ${this.text}") - } } internal data class SchemaParseResult( diff --git a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/RegionEnumCodegen.kt b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/RegionEnumCodegen.kt index a1fd675..3da6242 100644 --- a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/RegionEnumCodegen.kt +++ b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/RegionEnumCodegen.kt @@ -16,11 +16,12 @@ import com.squareup.kotlinpoet.TypeSpec * them to compare [ru.kode.way.RegionId] values directly. Each entry carries the segment name * (the portion before `@file.dot`), and a companion `forRegionId` performs the reverse lookup. * - * Returns null when the schema has zero or one region (flow-rooted schemas) — there is no enum - * worth emitting in that case. + * Returns null when the schema has zero or one region of a parallel — there is no enum worth emitting in that + * case. A root flow is a region too, but not one of a parallel: it has no entry. */ internal fun buildRegionEnumFileSpecOrNull(parseResult: SchemaParseResult, config: CodeGenConfig): FileSpec? { - val regionRoots = buildRegionRoots(parseResult.adjacencyList) + val rootNode = parseResult.adjacencyList.findRootNode() + val regionRoots = buildRegionRoots(parseResult.adjacencyList).filter { it != rootNode } if (regionRoots.size <= 1) return null val packageName = parseResult.customPackage ?: config.outputPackageName diff --git a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/SchemaCodegen.kt b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/SchemaCodegen.kt index 2d1f32a..5296e78 100644 --- a/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/SchemaCodegen.kt +++ b/way-gradle-plugin/src/main/kotlin/ru/kode/way/gradle/SchemaCodegen.kt @@ -574,7 +574,9 @@ private fun buildCreateChildFlowFinishEventSpec( endControlFlow() // regions[i] -> { return@forEachIndexed } - dfs(adjacencyList, regionRoot) { node -> + // The same descent as in buildChildFinishEventFileSpecs: a node which owns a virtual sub-schema emits the + // finish events of the flows under it. + dfsWhile(adjacencyList, regionRoot) { node -> when (node) { is Node.Flow -> { // An imported schema reachable from several parents finishes from each of its paths. @@ -605,6 +607,8 @@ private fun buildCreateChildFlowFinishEventSpec( is Node.History, -> Unit } + val ownsVirtualSubSchema = node is Node.Flow.LocalParallel || adjacencyList.isLocalChildOfParallel(node) + node === regionRoot || !ownsVirtualSubSchema } beginControlFlow("else -> {") addStatement("error(%P)", "internal error: failed to build child finish event for path=\$path") diff --git a/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/AdjacencyListTest.kt b/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/AdjacencyListTest.kt index 2a3348f..a9eaccd 100644 --- a/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/AdjacencyListTest.kt +++ b/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/AdjacencyListTest.kt @@ -22,6 +22,21 @@ class AdjacencyListTest : buildRegionRoots(adjacencyList).shouldContainExactlyInAnyOrder(app) } + should("region roots of a flow with a parallel declared under it are the flow and then the parallel's children") { + val app = local("app") + val tabs = parallel("tabs") + val one = local("one") + val two = local("two") + val adjacencyList: AdjacencyList = mapOf( + app to listOf(tabs), + tabs to listOf(one, two), + one to listOf(screen("oneScreen")), + two to listOf(screen("twoScreen")), + ) + + buildRegionRoots(adjacencyList) shouldBe listOf(app, one, two) + } + should("region roots of a parallel-rooted graph are the root parallel's children") { val main = parallel("main") val one = local("one") diff --git a/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/SchemaExtensionTest.kt b/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/SchemaExtensionTest.kt new file mode 100644 index 0000000..bb3b657 --- /dev/null +++ b/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/SchemaExtensionTest.kt @@ -0,0 +1,162 @@ +package ru.kode.way.gradle + +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import java.io.File +import kotlin.io.path.createTempDirectory + +class SchemaExtensionTest : + ShouldSpec({ + + val base = """ + digraph Home { + package = "ru.kode.test.home" + home [type = flow] + home -> placeholder -> profile + } + """.trimIndent() + + val extension = """ + digraph Home { + mode = "extend" + purchase [parameterName = "url", parameterType = "kotlin.String"] + placeholder -> purchase + } + """.trimIndent() + + fun withSourceSets(block: (mainDir: File, flavorDir: File) -> Unit) { + val projectDir = createTempDirectory("way-extension").toFile() + try { + block( + File(projectDir, "src/main/way").apply { + mkdirs() + }, + File(projectDir, "src/rustore/way").apply { mkdirs() }, + ) + } finally { + projectDir.deleteRecursively() + } + } + + fun SchemaParseResult.childIds(nodeId: String): List = + adjacencyList.entries.single { (node, _) -> node.id == nodeId }.value.map { it.id } + + should("add nodes and edges of an extension to the schema with the same graph id") { + withSourceSets { mainDir, flavorDir -> + val baseFile = File(mainDir, "home.dot").apply { writeText(base) } + val extensionFile = File(flavorDir, "home.dot").apply { writeText(extension) } + + val resolved = resolveOverriddenDotFiles(listOf(listOf(mainDir), listOf(flavorDir))) + resolved shouldBe listOf(baseFile, extensionFile) + + val result = parseSchemaDotFiles(resolved, projectDir = mainDir.parentFile.parentFile.parentFile).single() + result.childIds("placeholder") shouldContainExactlyInAnyOrder listOf("profile", "purchase") + result.adjacencyList.keys.single { it.id == "purchase" } shouldBe + Node.Screen("purchase", Parameter("url", "kotlin.String")) + // segment ids are built from the file path: they must not depend on the flavor + result.filePath.toString() shouldBe "src/main/way/home.dot" + result.customPackage shouldBe "ru.kode.test.home" + } + } + + should("find the extended schema by graph id when the files are named differently") { + withSourceSets { mainDir, flavorDir -> + File(mainDir, "home.dot").writeText(base) + File(flavorDir, "home_store.dot").writeText(extension) + + val resolved = resolveOverriddenDotFiles(listOf(listOf(mainDir), listOf(flavorDir))) + + parseSchemaDotFiles(resolved, projectDir = mainDir.parentFile.parentFile.parentFile).single() + .childIds("placeholder") shouldContainExactlyInAnyOrder listOf("profile", "purchase") + } + } + + should("replace the schema together with its extensions by a higher-priority file without the mode") { + withSourceSets { mainDir, flavorDir -> + val variantDir = File(mainDir.parentFile.parentFile, "rustoreDebug/way").apply { mkdirs() } + File(mainDir, "home.dot").writeText(base) + File(flavorDir, "home.dot").writeText(extension) + val replacement = File(variantDir, "home.dot").apply { writeText(base) } + + resolveOverriddenDotFiles(listOf(listOf(mainDir), listOf(flavorDir), listOf(variantDir))) shouldBe + listOf(replacement) + } + } + + should("validate the extended schema as a whole") { + withSourceSets { mainDir, flavorDir -> + val files = listOf( + File(mainDir, "home.dot").apply { writeText(base) }, + File(flavorDir, "home.dot").apply { + writeText("digraph Home {\n mode = \"extend\"\n profile -> placeholder\n}") + }, + ) + + shouldThrow { + parseSchemaDotFiles(files, projectDir = mainDir.parentFile.parentFile.parentFile) + } + .message!! shouldContain "cycle" + } + } + + should("reject an extension which declares the type of a node of the extended schema anew") { + withSourceSets { mainDir, flavorDir -> + val files = listOf( + File(mainDir, "home.dot").apply { writeText(base) }, + File(flavorDir, "home.dot").apply { + writeText("digraph Home {\n mode = \"extend\"\n home [type = flow]\n}") + }, + ) + + shouldThrow { + parseSchemaDotFiles(files, projectDir = mainDir.parentFile.parentFile.parentFile) + } + .message!! shouldContain "duplicate node definition" + } + } + + should("reject an extension without a schema to extend") { + withSourceSets { _, flavorDir -> + val file = File(flavorDir, "home.dot").apply { writeText(extension) } + + shouldThrow { parseSchemaDotFiles(listOf(file), projectDir = flavorDir) } + .message!! shouldContain "there is no schema with this graph id" + } + } + + should("reject an extension when several schemas have its graph id") { + withSourceSets { mainDir, flavorDir -> + val files = listOf( + File(mainDir, "home.dot").apply { writeText(base) }, + File(mainDir, "home2.dot").apply { writeText(base) }, + File(flavorDir, "home.dot").apply { writeText(extension) }, + ) + + shouldThrow { + parseSchemaDotFiles(files, projectDir = mainDir.parentFile.parentFile.parentFile) + } + .message!! shouldContain "several schemas with this graph id" + } + } + + should("reject an extension which sets the package or the generated file names") { + withSourceSets { mainDir, flavorDir -> + val files = listOf( + File(mainDir, "home.dot").apply { writeText(base) }, + File(flavorDir, "home.dot").apply { + writeText( + "digraph Home {\n mode = \"extend\"\n package = \"ru.kode.other\"\n placeholder -> purchase\n}", + ) + }, + ) + + shouldThrow { + parseSchemaDotFiles(files, projectDir = mainDir.parentFile.parentFile.parentFile) + } + .message!! shouldContain "must not set \"package\"" + } + } + }) diff --git a/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/SchemaGenerateTest.kt b/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/SchemaGenerateTest.kt index eb90f14..6346fda 100644 --- a/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/SchemaGenerateTest.kt +++ b/way-gradle-plugin/src/test/kotlin/ru/kode/way/gradle/SchemaGenerateTest.kt @@ -82,7 +82,14 @@ class SchemaGenerateTest : ), TestCase( schemaFile = "targets-test10.dot", - expectedOutputFiles = listOf("targets-test10-schema.txt", "TabsSchema.txt", "TabASchema.txt", "TabBSchema.txt"), + expectedOutputFiles = listOf( + "targets-test10-schema.txt", + // the root flow is a region, but it has no entry in the enum of the regions + "TargetsTest10Region.txt", + "TabsSchema.txt", + "TabASchema.txt", + "TabBSchema.txt", + ), testName = "isParameterized inside a parallel schema and its sub-schemas", ), TestCase( diff --git a/way-gradle-plugin/src/test/resources/Fi01appNodeBuilder.txt b/way-gradle-plugin/src/test/resources/Fi01appNodeBuilder.txt index 6b93ec8..45fb931 100644 --- a/way-gradle-plugin/src/test/resources/Fi01appNodeBuilder.txt +++ b/way-gradle-plugin/src/test/resources/Fi01appNodeBuilder.txt @@ -2,6 +2,7 @@ package ru.kode.test.app.schema import kotlin.Any import kotlin.Int +import kotlin.Pair import kotlin.String import kotlin.Suppress import kotlin.collections.HashMap @@ -63,6 +64,17 @@ public class Fi01appNodeBuilder( } } + override fun snapshotCache(): Any? = nodeBuilders.mapValues { (_, builder) -> builder to builder.snapshotCache() } + + override fun restoreCache(snapshot: Any?) { + nodeBuilders.clear() + (snapshot as Map<*, *>).forEach { (path, saved) -> + val (builder, childSnapshot) = saved as Pair<*, *> + nodeBuilders[path as Path] = builder as NodeBuilder + builder.restoreCache(childSnapshot) + } + } + public fun targetOrError(segment: Segment, rootSegmentAlias: Segment?): Path = schema.regions.firstNotNullOfOrNull { schema.target(it, segment, rootSegmentAlias) } ?: error("""internal error: no target generated for segment "${segment.id}"""") public fun targetsOrError(segment: Segment, rootSegmentAlias: Segment?): List = schema.regions.firstNotNullOfOrNull { schema.targets(it, segment, rootSegmentAlias).ifEmpty { null } } ?: error("""internal error: no target generated for segment "${segment.id}"""") diff --git a/way-gradle-plugin/src/test/resources/Nb01appNodeBuilder.txt b/way-gradle-plugin/src/test/resources/Nb01appNodeBuilder.txt index 451667f..a827f0c 100644 --- a/way-gradle-plugin/src/test/resources/Nb01appNodeBuilder.txt +++ b/way-gradle-plugin/src/test/resources/Nb01appNodeBuilder.txt @@ -1,6 +1,7 @@ package ru.kode.test.app.schema import kotlin.Any +import kotlin.Pair import kotlin.Suppress import kotlin.collections.HashMap import kotlin.collections.Map @@ -43,16 +44,16 @@ public class Nb01appNodeBuilder( } return when { path == rootPath -> nodeFactory.createRootNode() - path.startsWith(targetOrError(Segment("nb01login@NodeBuildersTest01:src/test/resources/node-builders-multiple-flows.dot"), rootSegmentAlias)) -> { - val targetPath = targetOrError(Segment("nb01login@NodeBuildersTest01:src/test/resources/node-builders-multiple-flows.dot"), rootSegmentAlias) - val nodeBuilder = nb01loginNodeBuilder(rootSegmentAlias) - nodeBuilder.build(path.drop(targetPath.length - 1), payloads = payloads.filterKeys { it.length > targetPath.length - 1 }.mapKeys { it.key.drop(targetPath.length - 1) }, rootSegmentAlias = targetPath.lastSegment()) - } path.startsWith(targetOrError(Segment("nb01onboarding@NodeBuildersTest01:src/test/resources/node-builders-multiple-flows.dot"), rootSegmentAlias)) -> { val targetPath = targetOrError(Segment("nb01onboarding@NodeBuildersTest01:src/test/resources/node-builders-multiple-flows.dot"), rootSegmentAlias) val nodeBuilder = nb01onboardingNodeBuilder(rootSegmentAlias) nodeBuilder.build(path.drop(targetPath.length - 1), payloads = payloads.filterKeys { it.length > targetPath.length - 1 }.mapKeys { it.key.drop(targetPath.length - 1) }, rootSegmentAlias = targetPath.lastSegment()) } + path.startsWith(targetOrError(Segment("nb01login@NodeBuildersTest01:src/test/resources/node-builders-multiple-flows.dot"), rootSegmentAlias)) -> { + val targetPath = targetOrError(Segment("nb01login@NodeBuildersTest01:src/test/resources/node-builders-multiple-flows.dot"), rootSegmentAlias) + val nodeBuilder = nb01loginNodeBuilder(rootSegmentAlias) + nodeBuilder.build(path.drop(targetPath.length - 1), payloads = payloads.filterKeys { it.length > targetPath.length - 1 }.mapKeys { it.key.drop(targetPath.length - 1) }, rootSegmentAlias = targetPath.lastSegment()) + } else -> error("""illegal path build requested for "nb01app" node: $path""") } } @@ -66,6 +67,17 @@ public class Nb01appNodeBuilder( } } + override fun snapshotCache(): Any? = nodeBuilders.mapValues { (_, builder) -> builder to builder.snapshotCache() } + + override fun restoreCache(snapshot: Any?) { + nodeBuilders.clear() + (snapshot as Map<*, *>).forEach { (path, saved) -> + val (builder, childSnapshot) = saved as Pair<*, *> + nodeBuilders[path as Path] = builder as NodeBuilder + builder.restoreCache(childSnapshot) + } + } + public fun targetOrError(segment: Segment, rootSegmentAlias: Segment?): Path = schema.regions.firstNotNullOfOrNull { schema.target(it, segment, rootSegmentAlias) } ?: error("""internal error: no target generated for segment "${segment.id}"""") @Suppress("UNCHECKED_CAST") diff --git a/way-gradle-plugin/src/test/resources/Nbp01mainNodeBuilder.txt b/way-gradle-plugin/src/test/resources/Nbp01mainNodeBuilder.txt index f941b1f..6e11e0e 100644 --- a/way-gradle-plugin/src/test/resources/Nbp01mainNodeBuilder.txt +++ b/way-gradle-plugin/src/test/resources/Nbp01mainNodeBuilder.txt @@ -1,6 +1,7 @@ package ru.kode.test.app.schema import kotlin.Any +import kotlin.Pair import kotlin.Suppress import kotlin.collections.HashMap import kotlin.collections.Map @@ -73,6 +74,17 @@ public class Nbp01mainNodeBuilder( } } + override fun snapshotCache(): Any? = nodeBuilders.mapValues { (_, builder) -> builder to builder.snapshotCache() } + + override fun restoreCache(snapshot: Any?) { + nodeBuilders.clear() + (snapshot as Map<*, *>).forEach { (path, saved) -> + val (builder, childSnapshot) = saved as Pair<*, *> + nodeBuilders[path as Path] = builder as NodeBuilder + builder.restoreCache(childSnapshot) + } + } + public fun targetOrError(segment: Segment, rootSegmentAlias: Segment?): Path = schema.regions.firstNotNullOfOrNull { schema.target(it, segment, rootSegmentAlias) } ?: error("""internal error: no target generated for segment "${segment.id}"""") @Suppress("UNCHECKED_CAST") diff --git a/way-gradle-plugin/src/test/resources/Nbp02mainNodeBuilder.txt b/way-gradle-plugin/src/test/resources/Nbp02mainNodeBuilder.txt index 3448309..e418df0 100644 --- a/way-gradle-plugin/src/test/resources/Nbp02mainNodeBuilder.txt +++ b/way-gradle-plugin/src/test/resources/Nbp02mainNodeBuilder.txt @@ -1,6 +1,7 @@ package ru.kode.test.app.schema import kotlin.Any +import kotlin.Pair import kotlin.Suppress import kotlin.collections.HashMap import kotlin.collections.Map @@ -73,6 +74,17 @@ public class Nbp02mainNodeBuilder( } } + override fun snapshotCache(): Any? = nodeBuilders.mapValues { (_, builder) -> builder to builder.snapshotCache() } + + override fun restoreCache(snapshot: Any?) { + nodeBuilders.clear() + (snapshot as Map<*, *>).forEach { (path, saved) -> + val (builder, childSnapshot) = saved as Pair<*, *> + nodeBuilders[path as Path] = builder as NodeBuilder + builder.restoreCache(childSnapshot) + } + } + public fun targetOrError(segment: Segment, rootSegmentAlias: Segment?): Path = schema.regions.firstNotNullOfOrNull { schema.target(it, segment, rootSegmentAlias) } ?: error("""internal error: no target generated for segment "${segment.id}"""") @Suppress("UNCHECKED_CAST") diff --git a/way-gradle-plugin/src/test/resources/TargetsTest10Region.txt b/way-gradle-plugin/src/test/resources/TargetsTest10Region.txt new file mode 100644 index 0000000..9ddae09 --- /dev/null +++ b/way-gradle-plugin/src/test/resources/TargetsTest10Region.txt @@ -0,0 +1,19 @@ +package ru.kode.test.app.schema + +import kotlin.String +import ru.kode.way.RegionId + +public enum class TargetsTest10Region( + public val segmentName: String, +) { + TabA("tabA"), + TabB("tabB"), + ; + + public companion object { + public fun forRegionId(regionId: RegionId): TargetsTest10Region? { + val name = regionId.path.segments.last().id.substringBefore('@') + return entries.firstOrNull { it.segmentName == name } + } + } +} diff --git a/way-gradle-plugin/src/test/resources/targets-test10-schema.txt b/way-gradle-plugin/src/test/resources/targets-test10-schema.txt index 89e4e22..2ec53f5 100644 --- a/way-gradle-plugin/src/test/resources/targets-test10-schema.txt +++ b/way-gradle-plugin/src/test/resources/targets-test10-schema.txt @@ -18,14 +18,17 @@ public class TargetsTest10Schema : Schema { mapOf(Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot") to TabsSchema(), Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot") to TabASchema(), Segment("tabB@TargetsTest10:src/test/resources/targets-test10.dot") to TabBSchema()) override val regions: List = - listOf(RegionId(Path(listOf(Segment("app@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot")))), RegionId(Path(listOf(Segment("app@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabB@TargetsTest10:src/test/resources/targets-test10.dot"))))) + listOf(RegionId(Path(listOf(Segment("app@TargetsTest10:src/test/resources/targets-test10.dot")))), RegionId(Path(listOf(Segment("app@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot")))), RegionId(Path(listOf(Segment("app@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabB@TargetsTest10:src/test/resources/targets-test10.dot"))))) - public val tabARegionId: RegionId + public val appRegionId: RegionId get() = regions[0] - public val tabBRegionId: RegionId + public val tabARegionId: RegionId get() = regions[1] + public val tabBRegionId: RegionId + get() = regions[2] + override fun target( regionId: RegionId, segment: Segment, @@ -55,6 +58,18 @@ public class TargetsTest10Schema : Schema { else -> null } } + regions[2] -> { + val rootSegment = rootSegmentAlias ?: Segment("app@TargetsTest10:src/test/resources/targets-test10.dot") + when(segment.id) { + "app@TargetsTest10:src/test/resources/targets-test10.dot" -> Path(rootSegment) + "tabs@TargetsTest10:src/test/resources/targets-test10.dot" -> Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"))) + "tabB@TargetsTest10:src/test/resources/targets-test10.dot" -> Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabB@TargetsTest10:src/test/resources/targets-test10.dot"))) + "screenB@TargetsTest10:src/test/resources/targets-test10.dot" -> Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabB@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("screenB@TargetsTest10:src/test/resources/targets-test10.dot"))) + "tabA@TargetsTest10:src/test/resources/targets-test10.dot" -> Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot"))) + "screenA@TargetsTest10:src/test/resources/targets-test10.dot" -> Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("screenA@TargetsTest10:src/test/resources/targets-test10.dot"))) + else -> null + } + } else -> { error("""unknown regionId=$regionId""") } @@ -93,6 +108,20 @@ public class TargetsTest10Schema : Schema { } } } + regions[2] -> { + val rootSegment = rootSegmentAlias ?: Segment("app@TargetsTest10:src/test/resources/targets-test10.dot") + when { + path == Path(rootSegment) -> Schema.NodeType.Flow + path == Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"))) -> Schema.NodeType.ParallelFlow + path == Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabB@TargetsTest10:src/test/resources/targets-test10.dot"))) -> Schema.NodeType.Flow + path == Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabB@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("screenB@TargetsTest10:src/test/resources/targets-test10.dot"))) -> Schema.NodeType.Screen + path == Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot"))) -> Schema.NodeType.Flow + path == Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot"), Segment("screenA@TargetsTest10:src/test/resources/targets-test10.dot"))) -> Schema.NodeType.Screen + else -> { + error("""internal error: no nodeType for path=$path""") + } + } + } else -> { error("""unknown regionId=$regionId""") } @@ -119,13 +148,21 @@ public class TargetsTest10Schema : Schema { ): Event = when (regionId) { regions[0] -> { when(path) { - Path(Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot")) -> TabsChildFinishRequest.TabA + Path(listOf(rootSegment, Segment("tabs@TargetsTest10:src/test/resources/targets-test10.dot"))) -> AppChildFinishRequest.Tabs else -> { error("""internal error: failed to build child finish event for path=$path""") } } } regions[1] -> { + when(path) { + Path(Segment("tabA@TargetsTest10:src/test/resources/targets-test10.dot")) -> TabsChildFinishRequest.TabA + else -> { + error("""internal error: failed to build child finish event for path=$path""") + } + } + } + regions[2] -> { when(path) { Path(Segment("tabB@TargetsTest10:src/test/resources/targets-test10.dot")) -> TabsChildFinishRequest.TabB else -> { diff --git a/way/src/commonMain/kotlin/ru/kode/way/FlowTransition.kt b/way/src/commonMain/kotlin/ru/kode/way/FlowTransition.kt index 91eba15..511b2a2 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/FlowTransition.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/FlowTransition.kt @@ -121,7 +121,8 @@ infix fun NavigateAndEnqueue.thenEnqueue(event: Event): NavigateAndEnqueue = cop * [regionId] may be either an absolute key from `NavigationState.regions` or a schema-local id * (such as `MyParallelFlowSchema.exploreFlowRegionId`); the runtime suffix-matches schema-local ids * against the parallel's active sub-regions. A stale or unresolved id never crashes Back — it - * soft-falls-back to the deepest active sub-region. + * soft-falls-back to the deepest active sub-region. Back to a region of this parallel which is not started + * (see [ParallelFlowNode.initialRegions]) is ignored. * * This is a parallel-only transition (declared `FlowTransition`). Returning it from a plain * [FlowNode] or [ScreenNode] is a misuse and is rejected at resolution time. diff --git a/way/src/commonMain/kotlin/ru/kode/way/GraphTransitions.kt b/way/src/commonMain/kotlin/ru/kode/way/GraphTransitions.kt index 26a6145..85aa142 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/GraphTransitions.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/GraphTransitions.kt @@ -54,9 +54,17 @@ internal fun calculateAliveNodes( internal fun computeConfiguration(state: NavigationState): Set = state._regions.values.flatMapTo(mutableSetOf()) { it.alive } +/** + * Whether [regionId] is a region of the root node of this schema: the region of a root flow itself or a region of + * a root parallel. Such a region lives as long as the service does; a region of a parallel which is declared deeper + * lives as long as that parallel. + */ +internal fun Schema.isRootRegion(regionId: RegionId): Boolean = + regionId in regions && (regionId.path.length == 1 || regionId.path.dropLast(1) == Path(rootSegment)) + /** * Removes from [state]._regions every sub-region whose parent parallel is no longer reachable, keeping: - * - schema-declared top-level regions (always retained), and + * - the regions of the root parallel (always retained), and * - sub-regions whose parent parallel is still alive — either (a) a runtime node alive in a sibling * region (sub-regions lazily mounted by NavigateTo) or (b) an intermediate parallel root * (parallel-rooted schema mounted as a sub-region of another parallel-rooted schema) that lives in @@ -69,7 +77,7 @@ internal fun computeConfiguration(state: NavigationState): Set = */ internal fun pruneOrphanRegions(state: NavigationState, schema: Schema) { state._regions.keys.retainAll { regionId -> - if (schema.regions.contains(regionId)) return@retainAll true + if (schema.isRootRegion(regionId)) return@retainAll true val parallelParentPath = regionId.path.dropLast(1) if (parallelParentPath in state._intermediateParallels.keys) return@retainAll true val parentAliveInSibling = state._regions.entries.any { (otherId, otherRegion) -> diff --git a/way/src/commonMain/kotlin/ru/kode/way/NavigationService.kt b/way/src/commonMain/kotlin/ru/kode/way/NavigationService.kt index d167c5e..819a285 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/NavigationService.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/NavigationService.kt @@ -11,10 +11,9 @@ import ru.kode.way.extension.node.hook.BaseScreenNode * The reentrancy guard ([isDispatching]) only protects against single-threaded re-entry from * within listener callbacks, not concurrent access from multiple threads. */ -class NavigationService( - private val nodeBuilder: NodeBuilder, - private val onFinishRequest: (R) -> FlowTransition, -) : EventSink { +class NavigationService(nodeBuilder: NodeBuilder, private val onFinishRequest: (R) -> FlowTransition) : + EventSink { + private val nodeBuilder = TransitionNodeBuilder(nodeBuilder) private var state: NavigationState = NavigationState( _regions = mutableMapOf(), _nodeExtensionPoints = mutableListOf(), @@ -72,6 +71,9 @@ class NavigationService( fun isStarted(): Boolean = state.isInitialized() + /** A copy of the current state, `null` before the service is started. */ + fun currentState(): NavigationState? = if (state.isInitialized()) state.copy() else null + /** * Registers a listener that receives the [NavigationState] after every transition. * @@ -225,11 +227,15 @@ class NavigationService( private val rootNodePath: Path? = state.rootNodePath private val rootFinishTransitionBuilder: ((Any) -> Transition)? = state._rootFinishTransitionBuilder + fun restoreEnqueuedEvents(state: NavigationState) { + state._enqueuedEvents.clear() + state._enqueuedEvents.addAll(enqueuedEvents) + } + fun restore(state: NavigationState) { state._regions.clear() state._regions.putAll(regions) - state._enqueuedEvents.clear() - state._enqueuedEvents.addAll(enqueuedEvents) + restoreEnqueuedEvents(state) state._payloads.clear() state._payloads.putAll(payloads) state._intermediateParallels.clear() @@ -248,6 +254,26 @@ class NavigationService( check(event is InitEvent || state.isInitialized()) { "send() was called before start(); call NavigationService.start() first" } + // a child NodeBuilder which a failed transition has created or dropped is not kept: it may have been created + // with the argument of a target which was never reached + val nodeBuilderCache = nodeBuilder.snapshotCache() + return try { + val navigationState = try { + runTransition(state, event, source) + } catch (e: Throwable) { + nodeBuilder.restoreCache(nodeBuilderCache) + throw e + } + // Called after the transition is fully committed. Exceptions here propagate to the caller + // but do not roll back navigation state — the transition has already completed. + serviceExtensionPoints.toList().forEach { it.onPostTransition(this, event, navigationState.copy()) } + navigationState + } finally { + nodeBuilder.endTransition() + } + } + + private fun runTransition(state: NavigationState, event: Event, source: Path?): NavigationState { // Snapshot every mutable slot before any mutation so a throw anywhere below restores the exact // pre-transition state (all-or-nothing). Taken before InitEvent populates regions, so a failed // start() restores to empty and is retryable. @@ -258,42 +284,50 @@ class NavigationService( serviceExtensionPoints.toList().forEach { it.onPreTransition(this, event, state.copy()) } - // Root flow nodes entered by the InitEvent block, tracked so the catch can compensate their - // onEntry. applyResolvedTransition tracks its own entered/exited separately. - val initEnteredRoots = mutableListOf>() - val navigationState = try { - applyResolvedTransition(state, event, source, resolvedTransition, initEnteredRoots) + // Every node which got its onEntry or onExit during this transition, in the order of the calls. + val entered = mutableListOf>() + val exited = mutableListOf>() + return try { + applyResolvedTransition(state, event, source, resolvedTransition, entered, exited) } catch (e: Throwable) { - // Compensate onEntry for root flow nodes entered in the InitEvent block (applyResolvedTransition - // compensates its own nodes); then restore the snapshot so the whole dispatch is all-or-nothing. - compensateLifecycle(initEnteredRoots, exited = emptyList(), event, state._nodeExtensionPoints) + // All-or-nothing: the state is restored first, so a node which is entered back sees the regions it had, + // then every lifecycle call made so far is reversed. snapshot.restore(state) + compensateLifecycle(entered, exited, event, state._nodeExtensionPoints) + // an event which a node has sent while it was entered back belongs to the transition which has failed + snapshot.restoreEnqueuedEvents(state) throw e } - // Called after the transition is fully committed. Exceptions here propagate to the caller - // but do not roll back navigation state — the transition has already completed. - serviceExtensionPoints.toList().forEach { it.onPostTransition(this, event, navigationState.copy()) } - return navigationState } /** * Runs the committed body of a [transition]: materializes regions on InitEvent, resolves the event * to target paths, recomputes the alive set, then synchronizes node lifecycles. Mutates [state] in - * place and returns the same instance. Appends InitEvent-entered roots to [initEnteredRoots] so the - * caller's catch can compensate them; its own inner lifecycle calls are compensated here on a throw. - * The caller ([transition]) owns the snapshot/restore for all-or-nothing rollback. + * place and returns the same instance. Appends every node which got its `onEntry` to [entered] and + * every node which got its `onExit` to [exited]: the caller ([transition]) owns the snapshot/restore and the + * compensation of these calls for all-or-nothing rollback. */ private fun applyResolvedTransition( state: NavigationState, event: Event, source: Path?, preResolvedTransition: ResolvedTransition?, - initEnteredRoots: MutableList>, + entered: MutableList>, + exited: MutableList>, ): NavigationState { if (event is InitEvent) { - enterRootParallelIfNeeded(state, event, initEnteredRoots) - nodeBuilder.schema.regions.forEach { regionId -> - materializeRegion(regionId, event, initEnteredRoots) + enterRootParallelIfNeeded(state, event, entered) + val rootParallel = state.rootNode as? ParallelFlowNode<*> + val rootParallelPath = state.rootNodePath + // regions of a parallel declared deeper start when that parallel is entered + val rootRegions = nodeBuilder.schema.regions.filter(nodeBuilder.schema::isRootRegion) + if (rootParallel != null && rootParallelPath != null) { + rootParallel.checkInitialRegions(rootParallelPath, rootRegions.map { it.path }) + } + rootRegions.forEach { regionId -> + val starts = rootParallel == null || rootParallelPath == null || + rootParallel.startsRegion(rootParallelPath, regionId.path) + if (starts) materializeRegion(regionId, event, entered) } } val resolvedTransition = preResolvedTransition ?: resolveCheckedTransition(state, event, source) @@ -311,16 +345,11 @@ class NavigationService( state._payloads.putAll(resolvedTransition.payloads) val previousAlive = state._regions.mapValues { it.value.alive.toList() } val previousNodes = state._regions.mapValues { it.value.nodes.toMap() } - // Hoisted out of synchronizeNodes so the runtime pre-mount and pre-unmount of intermediate - // parallels can append to the same compensation lists — the inner catch below replays - // every phase's enter/exit in lockstep regardless of which one threw. - val syncEntered = mutableListOf>() - val syncExited = mutableListOf>() - premountIntermediates(state, event, resolvedTransition, syncEntered) + val premounted = premountIntermediates(state, event, resolvedTransition) val unmountedIntermediates = mutableSetOf() // calculateAliveNodes mutates and returns the SAME state instance; mutatedState === state. val mutatedState = calculateAliveNodes(state, resolvedTransition.targetPaths, nodeBuilder.schema) - unmountOrphanedIntermediates(state, event, syncExited, unmountedIntermediates) + exitOrphanedParallels(state, event, previousAlive, previousNodes, exited, unmountedIntermediates, premounted) // An intermediate parallel below a re-targeted node is kept, only region nodes are rebuilt val recreated = computeConfiguration(mutatedState).filterTo(mutableSetOf()) { path -> path !in mutatedState._intermediateParallels && retargeted.any { path.startsWith(it) } @@ -334,19 +363,14 @@ class NavigationService( event, mutatedState._payloads, previousAlive, - previousNodes, - syncEntered, - syncExited, + entered, + exited, unmountedIntermediates, recreated, + premounted, ) - try { - if (validateSchema) checkSchemaValidity(nodeBuilder.schema, mutatedState) - mutatedState._enqueuedEvents.addAll(resolvedTransition.enqueuedEvents.orEmpty()) - } catch (e: Throwable) { - compensateLifecycle(syncEntered, syncExited, event, mutatedState._nodeExtensionPoints) - throw e - } + if (validateSchema) checkSchemaValidity(nodeBuilder.schema, mutatedState) + mutatedState._enqueuedEvents.addAll(resolvedTransition.enqueuedEvents.orEmpty()) return mutatedState } @@ -417,15 +441,31 @@ class NavigationService( * Only forward entries go through here. The re-entry in [compensateLifecycle] after a rollback intentionally does * not re-attach: the node keeps the sink of its original entry, which is live again because [TransactionSnapshot] * restores `_generations`. + * + * The node is added to [entered] right before its `onEntry`: a node which is there gets `onExit` on a rollback. */ - private fun enter(state: NavigationState, node: Node, path: Path, event: Event) { + private fun enter( + state: NavigationState, + node: Node, + path: Path, + event: Event, + entered: MutableList>, + ) { when (node) { is BaseFlowNode<*> -> node.attachEventSink(eventSink(path, state)) + is BaseScreenNode -> node.attachEventSink(eventSink(path, state)) - is ParallelFlowNode<*> -> node.attachEventSink(eventSink(path, state)) + + is ParallelFlowNode<*> -> { + node.attachEventSink(eventSink(path, state)) + // the root parallel gives the start payload to its regions which start later + val startPayload = (event as? InitEvent)?.payload.takeIf { path.length == 1 } + node.attachRegions(path, startPayload) { state._regions } + } + else -> Unit } - callOnEntry(node, path, event, state._nodeExtensionPoints) + callOnEntry(node, path, event, state._nodeExtensionPoints) { entered.add(node to path) } } /** @@ -439,7 +479,7 @@ class NavigationService( * its sub-regions) so its `onEntry` fires and its `ComposableNode.Content` can render. * The parallel-flow lives at the schema's `rootSegment` path — one segment shorter than each * sub-region path — and is NOT iterated by `schema.regions`, so without this step it would never - * be constructed. No-op for the common flow-rooted schema. Appends the entered root to + * be constructed. No-op for a flow-rooted schema: its root flow is the first region. Appends the entered root to * [initEnteredRoots] so the caller's catch can compensate its `onEntry` on a later failure. */ private fun enterRootParallelIfNeeded( @@ -468,8 +508,7 @@ class NavigationService( } // Entered before syncGenerations runs: give it its generation now so a sink obtained in onEntry is live. state._generations.getOrPut(rootSegmentPath) { nextGeneration++ } - enter(state, rootNode, rootSegmentPath, event) - initEnteredRoots.add(rootNode to rootSegmentPath) + enter(state, rootNode, rootSegmentPath, event, initEnteredRoots) state.rootNode = rootNode state.rootNodePath = rootSegmentPath state._rootFinishTransitionBuilder = erasedFinishRequest @@ -479,16 +518,17 @@ class NavigationService( * Pre-mount step (runtime NavigateTo only): BEFORE [calculateAliveNodes]' prune runs, mount any * intermediate parallel a target path passes through that isn't yet in `_intermediateParallels`. * Without this, [calculateAliveNodes] prunes the freshly-activated sub-region because its parent - * intermediate isn't yet registered. Shallowest-first so `onEntry` fires parent-before-child; - * mounts are appended to [syncEntered] for compensation on a downstream throw. + * intermediate isn't yet registered. The mounted parallels are built and registered only, their paths are + * returned: [synchronizeNodes] enters them together with the nodes of the regions, after the nodes which are left + * got their `onExit` and after the flows they are declared in got their `onEntry`. */ private fun premountIntermediates( state: NavigationState, event: Event, resolvedTransition: ResolvedTransition, - syncEntered: MutableList>, - ) { - if (event is InitEvent) return + ): MutableSet { + val premounted = mutableSetOf() + if (event is InitEvent) return premounted // intermediateParallelAncestors returns shallowest-first; LinkedHashSet keeps that ordering // across multiple targets while de-duplicating. val premountOrdered = LinkedHashSet() @@ -496,47 +536,67 @@ class NavigationService( premountOrdered.addAll(intermediateParallelAncestors(targetPath, nodeBuilder.schema)) } premountOrdered.forEach { intermediatePath -> - if (intermediatePath !in state._intermediateParallels) { - mountIntermediateParallel(intermediatePath, event, state._payloads, syncEntered) + if (intermediatePath in state._intermediateParallels) return@forEach + // a parallel which an initial target has entered is alive as a node of the calling region only + val alive = state._regions.values.firstNotNullOfOrNull { it._nodes[intermediatePath] as? ParallelFlowNode<*> } + if (alive != null) { + state._intermediateParallels[intermediatePath] = + IntermediateParallel(node = alive, finishBuilder = finishBuilderFor(intermediatePath), initMounted = false) + } else { + mountIntermediateParallel(intermediatePath, event, state._payloads, entered = null) + // the root parallel is not an intermediate one, it is entered at start + if (intermediatePath in state._intermediateParallels) premounted.add(intermediatePath) } } + return premounted } /** - * Post-update unmount step (runtime NavigateTo only): now that each region's `alive` reflects this - * transition, a class-1 (runtime-mounted) intermediate is orphaned iff its path no longer appears - * in any region's `alive` (the path was placed there by `initParallelAndRouteAbsolute` on the way - * IN, and removed by [calculateAliveNodes] when the new target doesn't pass through it). Class-2 - * (initMounted) intermediates are pinned for the service's lifetime and torn down only via - * [cleanDispose]. Unmounts deepest-first (matching the [cleanDispose] contract: an outer - * intermediate exits only AFTER its inner ones), recording exits in [syncExited] / - * [unmountedIntermediates]. If anything was unmounted, re-runs [pruneOrphanRegions] so sub-regions - * kept only by the "parent in _intermediateParallels" escape hatch are removed before - * [synchronizeNodes] runs. + * Leaves the parallels which the new configuration does not pass through any more: runtime-mounted intermediate + * parallels (the ones mounted at InitEvent live as long as the service does) and the regions which lived only + * because of them. Leaving a parallel can orphan a parallel declared inside of one of its regions, so the sweep + * repeats until nothing is left to drop. + * + * The structure is settled first, `onExit` is called after that, deepest path first: the nodes of a region exit + * before the parallel which owns the region, an inner parallel before the outer one. Every node gets its `onExit` + * even if an earlier one throws; the throws are rethrown together. */ - private fun unmountOrphanedIntermediates( + private fun exitOrphanedParallels( state: NavigationState, event: Event, - syncExited: MutableList>, + previousAlive: Map>, + previousNodes: Map>, + exited: MutableList>, unmountedIntermediates: MutableSet, + premounted: MutableSet, ) { if (event is InitEvent) return - val configuration = computeConfiguration(state) - val toUnmount = state._intermediateParallels.entries - .asSequence() - .filter { (_, intermediate) -> !intermediate.initMounted } - .map { it.key } - .filter { path -> path !in configuration } - .toList() - toUnmount.sortedByDescending { it.length }.forEach { intermediatePath -> - val intermediate = state._intermediateParallels.remove(intermediatePath)!! - callOnExit(intermediate.node, intermediatePath, event, state._nodeExtensionPoints) - syncExited.add(intermediate.node to intermediatePath) - unmountedIntermediates.add(intermediatePath) - } - if (toUnmount.isNotEmpty()) { + val leaving = mutableMapOf() + do { + val configuration = computeConfiguration(state) + val orphaned = state._intermediateParallels.filter { (path, intermediate) -> + !intermediate.initMounted && path !in configuration + } + orphaned.forEach { (path, intermediate) -> + state._intermediateParallels.remove(path) + unmountedIntermediates.add(path) + // a parallel which this transition has mounted is not entered yet + if (!premounted.remove(path)) leaving[path] = intermediate.node + } pruneOrphanRegions(state, nodeBuilder.schema) + } while (orphaned.isNotEmpty()) + previousAlive.forEach { (regionId, paths) -> + if (regionId !in state._regions) { + // a region above a parallel carries the path of that parallel as well, the node is the same one + paths.forEach { path -> previousNodes[regionId]?.get(path)?.let { leaving.getOrPut(path) { it } } } + } + } + val onExitThrows = mutableListOf() + leaving.entries.sortedByDescending { it.key.length }.forEach { (path, node) -> + runCatching { callOnExit(node, path, event, state._nodeExtensionPoints) { exited.add(node to path) } } + .onFailure { onExitThrows.add(it) } } + onExitThrows.rethrowAsAggregate() } /** @@ -573,8 +633,7 @@ class NavigationService( when (regionRoot) { is FlowNode<*> -> { state._generations.getOrPut(regionRootPath) { nextGeneration++ } - enter(state, regionRoot, regionRootPath, event) - initEnteredRoots.add(regionRoot to regionRootPath) + enter(state, regionRoot, regionRootPath, event, initEnteredRoots) val rootFinishBuilder = finishBuilderFor(regionRootPath) state._regions[regionId] = Region( _nodes = mutableMapOf(regionRootPath to regionRoot), @@ -604,10 +663,13 @@ class NavigationService( regionRootPath, inclusive = true, ) - innerSchema.regions.forEach { innerRelRegion -> - val innerAbsPath = absoluteRegionRoot(innerSchemaPath, innerRelRegion) - val innerAbsRegionId = RegionId(innerAbsPath) - materializeRegion(innerAbsRegionId, event, initEnteredRoots) + // only the regions of this parallel: the ones of a parallel declared deeper start when it is entered + val innerRegionRoots = regionRootsOf(innerSchema, innerSchemaPath, regionRootPath) + regionRoot.checkInitialRegions(regionRootPath, innerRegionRoots) + innerRegionRoots.forEach { innerAbsPath -> + if (regionRoot.startsRegion(regionRootPath, innerAbsPath)) { + materializeRegion(RegionId(innerAbsPath), event, initEnteredRoots) + } } } @@ -624,9 +686,9 @@ class NavigationService( * [entered] so the caller's compensation sweep can reverse the mount on a downstream throw. * * Used both by [materializeRegion] (InitEvent path, passes the already-built [preBuiltNode]) - * and by the pre-mount step in [transition] (runtime NavigateTo path that lands on a sub-region - * under a not-yet-mounted intermediate; passes `preBuiltNode = null` so this helper builds the - * node itself). + * and by [premountIntermediates] (runtime NavigateTo path that lands on a sub-region under a + * not-yet-mounted intermediate; passes `preBuiltNode = null` so this helper builds the node itself, and + * `entered = null` because such a parallel is entered later, after the flows above it). * * No-op if [parallelPath] is already in [NavigationState._intermediateParallels] OR equals * the service's [NavigationState.rootNodePath] (the root parallel is handled directly by the @@ -636,7 +698,7 @@ class NavigationService( parallelPath: Path, event: Event, payloads: Map, - entered: MutableList>, + entered: MutableList>?, preBuiltNode: Node? = null, initMounted: Boolean = false, ) { @@ -655,8 +717,10 @@ class NavigationService( "expected ParallelFlowNode at $parallelPath, but builder returned ${node::class.simpleName}" } state._generations.getOrPut(parallelPath) { nextGeneration++ } - enter(state, node, parallelPath, event) - entered.add(node to parallelPath) + // without [entered] the caller enters the node itself + if (entered != null) { + enter(state, node, parallelPath, event, entered) + } val finishBuilder = finishBuilderFor(parallelPath) state._intermediateParallels[parallelPath] = IntermediateParallel( node = node, @@ -701,124 +765,93 @@ class NavigationService( event: Event, payloads: Map, previousAlive: Map>, - previousNodes: Map>, entered: MutableList>, exited: MutableList>, unmountedIntermediates: Set, recreated: Set, + premounted: Set, ) { // Record SCXML history for every compound flow/region that just left the alive set, keyed by // its path → the atomic leaf that was active under it. Done here — after calculateAliveNodes // recomputed each region's alive chain but before onExit/prune below — so the read of the // now-current alive set is accurate. Rolled back by the transaction snapshot on any later throw. recordHistoryOnExit(state, previousAlive) - // Track lifecycle calls so we can compensate if an exception occurs mid-synchronization. - // The snapshot rollback in transition() restores structural state; this tracking ensures - // onEntry/onExit calls remain balanced even when the rollback path is taken. - // - // [entered] and [exited] are owned by the caller (transition()) so the runtime pre-mount - // and pre-unmount steps' entries are folded into the same compensation lists this catch - // walks. A throw mid-synchronization then exits BOTH pre-mounted intermediates and - // per-region nodes in the same reversed sweep. - try { - // each callOnExit in the two prune loops below is wrapped in runCatching so that one - // consumer's throwing onExit doesn't skip sibling nodes' onExit calls. Mirrors the - // cleanDispose pattern (every step runCatching'd, every node gets a chance to clean up - // its DI scope / coroutine scope / etc). Throws are collected and rethrown — the first - // throw is the primary, the rest are attached via addSuppressed — after both loops - // complete. The inner catch below still runs because the rethrow happens before - // synchronizeNodes returns: it compensates `exited` via callOnEntry (re-enter the - // partially-exited nodes) and the outer transition catch then snapshot-restores state. - // `exited.add` always runs even when callOnExit throws, so the compensation re-enters - // every node we attempted to exit — keeping entry/exit balanced. - val onExitThrows = mutableListOf() - // Call onExit for nodes in regions that were pruned - previousAlive.forEach { (regionId, prevPaths) -> - if (!state._regions.containsKey(regionId)) { - val nodes = previousNodes[regionId] ?: emptyMap() - prevPaths.reversed().forEach { path -> - nodes[path]?.also { - runCatching { callOnExit(it, path, event, state._nodeExtensionPoints) } - .onFailure { onExitThrows.add(it) } - exited.add(it to path) - } + // Every onExit below runs even if an earlier one throws, so one failing node does not skip the others; the + // throws are rethrown together. [entered] and [exited] are compensated by the caller after it restores the state. + val onExitThrows = mutableListOf() + // Per-region synchronization + state._regions.forEach { (regionId, region) -> + previousAlive[regionId].orEmpty().reversed().forEach { path -> + if (!region.alive.contains(path) || path in recreated) { + // Skip intermediate parallels: their onExit was already fired by the pre-unmount + // step in transition(). They were carried in this region's previousAlive as a + // path-coverage placeholder (placed by initParallelAndRouteAbsolute's + // `resolved[callingRegionId] = parallelPath` on the way IN); the pre-unmount + // sweep handled the actual lifecycle teardown — emitting onExit again here would + // double-exit. + if (path in unmountedIntermediates) { + return@forEach } + val node = region._nodes[path] ?: error("state doesn't contain node at \"$path\"") + runCatching { callOnExit(node, path, event, state._nodeExtensionPoints) { exited.add(node to path) } } + .onFailure { onExitThrows.add(it) } } } - // Per-region synchronization - state._regions.forEach { (regionId, region) -> - previousAlive[regionId].orEmpty().reversed().forEach { path -> - if (!region.alive.contains(path) || path in recreated) { - // Skip intermediate parallels: their onExit was already fired by the pre-unmount - // step in transition(). They were carried in this region's previousAlive as a - // path-coverage placeholder (placed by initParallelAndRouteAbsolute's - // `resolved[callingRegionId] = parallelPath` on the way IN); the pre-unmount - // sweep handled the actual lifecycle teardown — emitting onExit again here would - // double-exit. - if (path in unmountedIntermediates) { - return@forEach - } - val node = region._nodes[path] ?: error("state doesn't contain node at \"$path\"") - runCatching { callOnExit(node, path, event, state._nodeExtensionPoints) } - .onFailure { onExitThrows.add(it) } - exited.add(node to path) - } - } - region._nodes.keys.retainAll(region.alive.toSet() - recreated) + region._nodes.keys.retainAll(region.alive.toSet() - recreated) + } + onExitThrows.rethrowAsAggregate() + // A cached child NodeBuilder of a recreated node was created with the previous argument. + if (recreated.isNotEmpty()) nodeBuilder.invalidateCache(computeConfiguration(state) - recreated) + // Entries: the parallels mounted by this transition and the nodes newly added to the regions by + // calculateAliveNodes. A node is entered after every node above it, in whichever region that one lives. + val pendingEntries = LinkedHashMap Unit>() + premounted.forEach { path -> + val node = state._intermediateParallels.getValue(path).node + pendingEntries[path] = { + enter(state, node, path, event, entered) } - onExitThrows.rethrowAsAggregate() - // A cached child NodeBuilder of a recreated node was created with the previous argument. - if (recreated.isNotEmpty()) nodeBuilder.invalidateCache(computeConfiguration(state) - recreated) - // Per-region build loop — entries newly added by calculateAliveNodes get their nodes - // built and onEntry fired. - state._regions.forEach { (_, region) -> - region.alive.forEach { path -> - if (!region._nodes.containsKey(path)) { - // Intermediate parallel paths are already built and entered by the pre-mount step - // (or by materializeRegion during InitEvent). Their node lives in - // _intermediateParallels and conceptually does NOT belong to any region — but a - // calling region whose NavigateTo lands beyond the intermediate carries the - // intermediate's path in its `alive` list (via initParallelAndRouteAbsolute's - // `resolved[callingRegionId] = parallelPath`). To keep runValidityChecks's - // alive==nodes invariant satisfied without re-building or re-entering, hand the - // same ParallelFlowNode instance to the region too. - val intermediate = state._intermediateParallels[path] - if (intermediate != null) { - region._nodes[path] = intermediate.node - return@forEach - } - val pathPayloads = payloads.onBuildPath(path) - region._nodes[path] = - nodeBuilder.build(path, pathPayloads, rootSegmentAlias = nodeBuilder.schema.rootSegment) - .also { - enter(state, it, path, event) - entered.add(it to path) - } + } + state._regions.forEach { (_, region) -> + region.alive.forEach { path -> + if (!region._nodes.containsKey(path)) { + // An intermediate parallel lives in _intermediateParallels and belongs to no region, but a calling + // region whose NavigateTo lands beyond it carries its path in the `alive` list (via + // initParallelAndRouteAbsolute's `resolved[callingRegionId] = parallelPath`). The region gets the same + // node instance, so that alive == nodes holds without building or entering it once more. + val intermediate = state._intermediateParallels[path] + if (intermediate != null) { + region._nodes[path] = intermediate.node + return@forEach + } + pendingEntries[path] = { + val node = nodeBuilder.build(path, payloads.onBuildPath(path), nodeBuilder.schema.rootSegment) + region._nodes[path] = node + enter(state, node, path, event, entered) } } } - // Prune the persistent payload store: drop entries whose key is not a prefix of any - // alive path across all regions. Mirrors `region._nodes.keys.retainAll(region.alive)` - // and the lazy-NodeBuilder cache invalidation below. Without pruning the map would - // grow unboundedly and keep references to payload instances after the owning flow - // has been disposed. - val aliveAcrossRegions = computeConfiguration(state) - state._payloads.keys.retainAll { payloadKey -> - aliveAcrossRegions.any { alivePath -> alivePath.startsWith(payloadKey) } - } - // Invalidate the lazy-NodeBuilder cache ONCE with the union of every region's alive - // paths. A per-region call would evict children alive only in sibling parallel regions - // (e.g. invalidating with the profile region's active path drops the cached explore - // NodeBuilder, even though explore is still active in another region — and recreating - // it on next access constructs a fresh DI subcomponent, losing every scope-singleton - // state held inside). - nodeBuilder.invalidateCache(aliveAcrossRegions) - } catch (e: Throwable) { - // Exit nodes that received onEntry and re-enter nodes that received onExit — both will be - // reconciled by the caller's snapshot restore; this keeps entry/exit balanced meanwhile. - compensateLifecycle(entered, exited, event, state._nodeExtensionPoints) - throw e } + while (pendingEntries.isNotEmpty()) { + val path = pendingEntries.keys.first() + val above = pendingEntries.keys.filter { it != path && path.startsWith(it) }.sortedBy { it.length } + (above + path).forEach { pendingEntries.remove(it)?.invoke() } + } + // Prune the persistent payload store: drop entries whose key is not a prefix of any + // alive path across all regions. Mirrors `region._nodes.keys.retainAll(region.alive)` + // and the lazy-NodeBuilder cache invalidation below. Without pruning the map would + // grow unboundedly and keep references to payload instances after the owning flow + // has been disposed. + val aliveAcrossRegions = computeConfiguration(state) + state._payloads.keys.retainAll { payloadKey -> + aliveAcrossRegions.any { alivePath -> alivePath.startsWith(payloadKey) } + } + // Invalidate the lazy-NodeBuilder cache ONCE with the union of every region's alive + // paths. A per-region call would evict children alive only in sibling parallel regions + // (e.g. invalidating with the profile region's active path drops the cached explore + // NodeBuilder, even though explore is still active in another region — and recreating + // it on next access constructs a fresh DI subcomponent, losing every scope-singleton + // state held inside). + nodeBuilder.invalidateCache(aliveAcrossRegions) } /** @@ -1014,18 +1047,32 @@ private fun List.rethrowAsAggregate() { private fun Map.onBuildPath(path: Path): Map = filterKeys { it.startsWith(path) || path.startsWith(it) } -private fun callOnEntry(node: Node, path: Path, event: Event, extensionPoints: List) { +private fun callOnEntry( + node: Node, + path: Path, + event: Event, + extensionPoints: List, + onEntering: () -> Unit = {}, +) { val snapshot = extensionPoints.toList() snapshot.forEach { it.onPreEntry(node, path) } + onEntering() // Pass [path] to the new overload; default impl in [Node] delegates to the legacy // (event-only) variant for backward compatibility. node.onEntry(event, path) snapshot.forEach { it.onPostEntry(node, path) } } -private fun callOnExit(node: Node, path: Path, event: Event, extensionPoints: List) { +private fun callOnExit( + node: Node, + path: Path, + event: Event, + extensionPoints: List, + onExiting: () -> Unit = {}, +) { val snapshot = extensionPoints.toList() snapshot.forEach { it.onPreExit(node, path) } + onExiting() node.onExit(event, path) snapshot.forEach { it.onPostExit(node, path) } } @@ -1036,3 +1083,36 @@ private fun callOnDispose(node: Node, path: Path, extensionPoints: List() + + /** [payloads] are the ones a build of [path] reads: its own one and those of its ancestors. */ + private data class Key(val path: Path, val payloads: Map, val rootSegmentAlias: Segment?) + + override val schema: Schema get() = delegate.schema + + override fun build(path: Path, payloads: Map, rootSegmentAlias: Segment?): Node = + built.getOrPut(Key(path, payloads.filterKeys(path::startsWith), rootSegmentAlias)) { + delegate.build(path, payloads, rootSegmentAlias) + } + + override fun invalidateCache(alivePaths: Set) { + // a child of a recreated node was built by the child NodeBuilder which is dropped here + built.keys.retainAll { it.path in alivePaths } + delegate.invalidateCache(alivePaths) + } + + override fun snapshotCache(): Any? = delegate.snapshotCache() + + override fun restoreCache(snapshot: Any?) = delegate.restoreCache(snapshot) + + fun endTransition() { + built.clear() + } +} diff --git a/way/src/commonMain/kotlin/ru/kode/way/Node.kt b/way/src/commonMain/kotlin/ru/kode/way/Node.kt index 6406871..1d4ec4b 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/Node.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/Node.kt @@ -134,4 +134,68 @@ abstract class ParallelFlowNode : Node { internal fun attachEventSink(sink: EventSink) { _eventSink = sink } + + /** + * Regions which start together with this node, as declared in its schema (`schema.RegionId`). `null` + * (default) starts all of them. A region which is not listed has no nodes until [startRegion], or a + * [NavigateTo] with a target inside of it, starts it; then it lives as long as this node does. Must name at least one region of this node. Read on every entry. + */ + open val initialRegions: Set? get() = null + + private var regionsPath: Path? = null + private var regions: () -> Map = { emptyMap() } + private var startPayload: Any? = null + + /** + * A transition which starts [regionId] from its initial node, or [Stay] if the region is already started. + * Available from the first entry of this node. + */ + fun startRegion(regionId: RegionId): FlowTransition = if (isRegionStarted(regionId)) { + Stay + } else { + val root = absoluteRegionId(regionId).path + NavigateTo(AbsoluteTarget(root, payloads = startPayload?.let { mapOf(root to it) } ?: emptyMap())) + } + + /** Whether [regionId] has nodes: it is one of [initialRegions] or has been started later. */ + fun isRegionStarted(regionId: RegionId): Boolean { + val root = absoluteRegionId(regionId).path + // a region whose root is a parallel flow is known only by the regions of that parallel + return regions().keys.any { it.path.startsWith(root) } + } + + /** + * Whether [regionId] is started and rests on the node it has started with. Lets [transition] decide by the state + * of a region, for example send Back to an overlay region only when it shows something. + */ + fun isRegionAtRoot(regionId: RegionId): Boolean = + regions()[absoluteRegionId(regionId)]?.let { it.active == it.rootPath } ?: false + + private fun absoluteRegionId(regionId: RegionId): RegionId { + val path = checkNotNull(regionsPath) { "regions are not available before the runtime calls onEntry on this node" } + return regionId.resolveAbsolute(path) + } + + internal fun attachRegions(path: Path, startPayload: Any?, regions: () -> Map) { + regionsPath = path + this.startPayload = startPayload + this.regions = regions + } +} + +/** Whether the region with the root at [regionRoot] starts together with this node at [parallelPath]. */ +internal fun ParallelFlowNode<*>.startsRegion(parallelPath: Path, regionRoot: Path): Boolean { + val initial = initialRegions ?: return true + return initial.any { it.resolveAbsolute(parallelPath).path == regionRoot } +} + +/** Fails if [ParallelFlowNode.initialRegions] of this node at [parallelPath] names no region out of [regionRoots]. */ +internal fun ParallelFlowNode<*>.checkInitialRegions(parallelPath: Path, regionRoots: List) { + val initial = initialRegions?.map { it.resolveAbsolute(parallelPath).path } ?: return + check(initial.isNotEmpty()) { + "initialRegions of the parallel flow at \"$parallelPath\" must name at least one region" + } + check(regionRoots.containsAll(initial)) { + "initialRegions of the parallel flow at \"$parallelPath\" must name its own regions $regionRoots, but were $initial" + } } diff --git a/way/src/commonMain/kotlin/ru/kode/way/NodeBuilder.kt b/way/src/commonMain/kotlin/ru/kode/way/NodeBuilder.kt index 38c919c..05a1123 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/NodeBuilder.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/NodeBuilder.kt @@ -50,5 +50,15 @@ interface NodeBuilder { */ fun invalidateCache(alivePaths: Set) + /** + * The cached child NodeBuilders of this one and of every NodeBuilder below it, for [restoreCache]. A transition + * which fails gives the ones it has dropped back with it, so the nodes which stay alive keep their builders (and + * the DI scopes these hold). A NodeBuilder without a cache has nothing to return. + */ + fun snapshotCache(): Any? = null + + /** Puts back the child NodeBuilders taken by [snapshotCache]. */ + fun restoreCache(snapshot: Any?) {} + val schema: Schema } diff --git a/way/src/commonMain/kotlin/ru/kode/way/NodeExtensionPoint.kt b/way/src/commonMain/kotlin/ru/kode/way/NodeExtensionPoint.kt index f558ff1..066ec04 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/NodeExtensionPoint.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/NodeExtensionPoint.kt @@ -1,13 +1,13 @@ package ru.kode.way interface NodeExtensionPoint { - fun onPreEntry(node: Node, path: Path) - fun onPostEntry(node: Node, path: Path) - fun onPreExit(node: Node, path: Path) - fun onPostExit(node: Node, path: Path) + fun onPreEntry(node: Node, path: Path) = Unit + fun onPostEntry(node: Node, path: Path) = Unit + fun onPreExit(node: Node, path: Path) = Unit + fun onPostExit(node: Node, path: Path) = Unit fun onPreDispose(node: Node, path: Path) = Unit fun onPostDispose(node: Node, path: Path) = Unit - fun onPreTransition(node: Node, path: Path, event: Event) - fun onPostTransition(node: Node, path: Path, event: Event, transition: Transition) + fun onPreTransition(node: Node, path: Path, event: Event) = Unit + fun onPostTransition(node: Node, path: Path, event: Event, transition: Transition) = Unit } diff --git a/way/src/commonMain/kotlin/ru/kode/way/Path.kt b/way/src/commonMain/kotlin/ru/kode/way/Path.kt index 81e7ac3..77811f9 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/Path.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/Path.kt @@ -112,6 +112,13 @@ fun Path.endsWith(other: Path): Boolean { return true } +/** + * True when the node at this path is the one [target] points to: `path.endsWith(Target.appFlow.login)`. + * A generated target of a screen or a flow and a live path have the same segment ids, so this replaces a comparison + * of node names. A [HistoryTarget] has the path of its parent flow, so it matches the flow. + */ +fun Path.endsWith(target: Target): Boolean = endsWith(target.path) + /** * Like [endsWith], but the FIRST segment of [other] is compared by [Segment.name] only — the * `@:` disambiguator on that one segment may differ across a schema mount that diff --git a/way/src/commonMain/kotlin/ru/kode/way/RegionId.kt b/way/src/commonMain/kotlin/ru/kode/way/RegionId.kt index 62daae5..c58a8fb 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/RegionId.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/RegionId.kt @@ -24,6 +24,14 @@ value class RegionId(val path: Path) { */ fun RegionId.resolveAbsolute(parentPath: Path?): RegionId { if (parentPath == null || path.startsWith(parentPath)) return this - val tail = if (path.length > 1) path.drop(1) else null - return RegionId(if (tail != null) parentPath.append(tail) else parentPath) + // The id is relative to the schema which declares the region, and [parentPath] ends with the part of the id which + // leads from that schema to the parallel node: nothing for the root of the schema, more for a parallel node inside + // of it. The first segment is not compared, a schema is mounted under the name its parent gives it. + val segments = path.segments + val parentSegments = parentPath.segments + val overlap = (segments.size - 2 downTo 1).firstOrNull { count -> + count <= parentSegments.size && parentSegments.takeLast(count) == segments.subList(1, 1 + count) + } ?: 0 + val tail = segments.drop(1 + overlap) + return RegionId(if (tail.isEmpty()) parentPath else parentPath.append(Path(tail))) } diff --git a/way/src/commonMain/kotlin/ru/kode/way/ServiceExtensionPoint.kt b/way/src/commonMain/kotlin/ru/kode/way/ServiceExtensionPoint.kt index 423e1ec..a55145d 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/ServiceExtensionPoint.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/ServiceExtensionPoint.kt @@ -10,7 +10,7 @@ interface ServiceExtensionPoint { * @param event event which is about to trigger a transition * @param state current navigation state */ - fun onPreTransition(service: NavigationService, event: Event, state: NavigationState) + fun onPreTransition(service: NavigationService, event: Event, state: NavigationState) {} /** * Called after service processed an event, built and executed a transition. @@ -25,7 +25,7 @@ interface ServiceExtensionPoint { * @param event event which has triggered the transition * @param state a new navigation state after transition */ - fun onPostTransition(service: NavigationService, event: Event, state: NavigationState) + fun onPostTransition(service: NavigationService, event: Event, state: NavigationState) {} /** * Called when service drops [event] instead of applying its transition, after the state has been rolled diff --git a/way/src/commonMain/kotlin/ru/kode/way/TargetResolution.kt b/way/src/commonMain/kotlin/ru/kode/way/TargetResolution.kt index 444f167..954d9ea 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/TargetResolution.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/TargetResolution.kt @@ -56,7 +56,7 @@ internal fun resolveTransition( val isRootParallelSubRegion = rootNode is ParallelFlowNode<*> && rootNodePath != null && regionId.path != rootNodePath && regionId.path.startsWith(rootNodePath) // A sink under the parallel (not the parallel itself) keeps Back in its own sub-region. - val isSubRegion = !nodeBuilder.schema.regions.contains(regionId) || isRootParallelSubRegion + val isSubRegion = !nodeBuilder.schema.isRootRegion(regionId) || isRootParallelSubRegion if (isSubRegion && inScope(regionId.path.dropLast(1))) { return@fold acc } @@ -85,6 +85,7 @@ internal fun resolveTransition( allRegions = regions, history = history, consulted = consulted, + activeAsked = start == region.active && event !is RootFinishRequestEvent, ) acc + resolved } @@ -350,6 +351,8 @@ private fun resolveTransitionInRegion( allRegions: Map, history: Map = emptyMap(), consulted: MutableSet? = null, + // the walk has started at [activePath]: every node from it up to [path] was asked about [event] already + activeAsked: Boolean = false, ): ResolvedTransition = when (transition) { is EnqueueEvent -> ResolvedTransition( targetPaths = mapOf(regionId to activePath), @@ -377,8 +380,12 @@ private fun resolveTransitionInRegion( check(subRegions.isNotEmpty()) { "DispatchBackTo must be returned from a ParallelFlowNode's transition(Event.Back) (path=$path)" } - val chosen = chooseBackRegion(transition.regionId, subRegions) - dispatchBackIntoRegion(chosen, subRegions, allRegions, nodeBuilder, event, extensionPoints, history) + if (isUnstartedRegion(transition.regionId, path, allRegions, nodeBuilder.schema)) { + ResolvedTransition.EMPTY + } else { + val chosen = chooseBackRegion(transition.regionId, subRegions) + dispatchBackIntoRegion(chosen, subRegions, allRegions, nodeBuilder, event, extensionPoints, history) + } } is NavigateTo -> { @@ -406,7 +413,20 @@ private fun resolveTransitionInRegion( is FlowTarget, is ScreenTarget -> { val targetPathAbs = resolveAbsoluteTargetPath(schema, path, target.path) recordTargetPayloads(target, targetPathAbs, regionId, nodes, payloads) - maybeResolveInitial(target, targetPathAbs, nodeBuilder, nodes, schema, payloads, regionId) + val owningRegionId = unstartedRegionId(targetPathAbs, allRegions.keys, schema) + ?: owningRegionId(targetPathAbs, allRegions.keys, fallback = regionId) + if (owningRegionId != regionId || + findParallelOnPath(targetPathAbs, owningRegionId, initializedPaths, schema) != null + ) { + // the target is inside of a region of a parallel below this node: that region takes it, and + // a parallel which is not entered yet is entered and starts its regions + resolveAbsoluteLeaves( + listOf(targetPathAbs), regionId, nodes, allRegions, nodeBuilder, schema, payloads, initializedPaths, + alreadyChosenBase = targetPaths, + ) + } else { + maybeResolveInitial(target, targetPathAbs, nodeBuilder, nodes, schema, payloads, regionId) + } } is HistoryTarget -> resolveHistoryTarget( @@ -465,6 +485,7 @@ private fun resolveTransitionInRegion( extensionPoints, allRegions, history, + activeAsked, ) if (resolved == null) { ResolvedTransition( @@ -490,6 +511,7 @@ private fun resolveTransitionInRegion( allRegions, history, consulted, + activeAsked, ) } } @@ -518,7 +540,8 @@ private fun resolveAbsoluteTarget( val absolutePath = target.path require(!isParallelFlowAt(schema, absolutePath)) { "NavigateTo(AbsoluteTarget(\"$absolutePath\")) targets a ParallelFlowNode path. " + - "Use an AbsoluteTarget pointing at a path inside one of its sub-regions." + "Use an AbsoluteTarget pointing at a path inside one of its sub-regions " + + "(a region whose root is a parallel flow cannot be started by startRegion)." } return resolveAbsoluteLeaves( candidates = listOf(absolutePath), @@ -558,7 +581,8 @@ private fun resolveHistoryTarget( alreadyChosen: Map, ): Map { val flowPath = target.path - val targetRegionId = owningRegionId(flowPath, allRegions.keys, fallback = callingRegionId) + val targetRegionId = unstartedRegionId(flowPath, allRegions.keys, schema) + ?: owningRegionId(flowPath, allRegions.keys, fallback = callingRegionId) val existingNodes = allRegions[targetRegionId]?.nodes ?: nodes target.payload?.also { payloads[flowPath] = it } val record = history[flowPath] @@ -623,9 +647,24 @@ private fun resolveAbsoluteTargetPath(schema: Schema, activePath: Path, targetPa // drop exactly the same number of leading segments from the resolved relative path before // appending. Dropping fewer would double-stack the regionRoot (`...par05Alpha.par05Alpha...`); // dropping more would skip a real intermediate segment. + if (!activePath.startsWith(absoluteRegionRoot(activeSchemaPath, regionId))) { + // the active node is a flow above the regions which its schema declares (they belong to a parallel nested + // in it), [regionId] is only a fallback here: the target is relative to the root of the schema + return if (relativeResolvedPath.length <= + 1 + ) { + activeSchemaPath + } else { + activeSchemaPath.append(relativeResolvedPath.drop(1)) + } + } return absoluteRegionRoot(activeSchemaPath, regionId).append(relativeResolvedPath.drop(regionId.path.length)) } +/** The roots of the regions of the parallel at [parallelPath]; its schema may declare other parallels as well. */ +internal fun regionRootsOf(parallelSchema: Schema, schemaPath: Path, parallelPath: Path): List = + parallelSchema.regions.map { absoluteRegionRoot(schemaPath, it) }.filter { it.dropLast(1) == parallelPath } + internal fun absoluteRegionRoot(schemaPath: Path, relativeRegionId: RegionId): Path = if (relativeRegionId.path.length <= 1) { schemaPath @@ -702,6 +741,8 @@ private fun maybeResolveBackEvent( extensionPoints: List, allRegions: Map, history: Map = emptyMap(), + // the nodes from [activePath] up to the root of the region have answered Ignore to this Back + activeAsked: Boolean = false, ): ResolvedTransition? { if (event != Event.Back || activePath.segments.size <= 1) return null @@ -727,6 +768,8 @@ private fun maybeResolveBackEvent( ownerRegionId = regionId, ownerNodes = nodes, history = history, + // asked on the way up already, it is not asked about the same Back once more + knownTransition = if (activeAsked && candidatePath.startsWith(regionId.path)) Ignore else null, ) } @@ -783,18 +826,23 @@ private fun dispatchBackThroughParallel( ownerRegionId: RegionId? = null, ownerNodes: Map? = null, history: Map = emptyMap(), + knownTransition: Transition? = null, ): ResolvedTransition { - val parallelBackTransition = buildTransition(event, parallelNode, parallelNodePath, extensionPoints) + val parallelBackTransition = knownTransition + ?: buildTransition(event, parallelNode, parallelNodePath, extensionPoints) val chosenRegionId = when (parallelBackTransition) { - is DispatchBackTo -> chooseBackRegion(parallelBackTransition.regionId, subRegionActivePaths) + is DispatchBackTo -> { + val regionId = parallelBackTransition.regionId + if (isUnstartedRegion(regionId, parallelNodePath, allRegions, nodeBuilder.schema)) return ResolvedTransition.EMPTY + chooseBackRegion(regionId, subRegionActivePaths) + } is Ignore -> deepestRegion(subRegionActivePaths) // A flow-nested parallel is not a sub-region root, so its own transition must be resolved exactly // as the region fold would: resolveTransitionInRegion derives the schema-based child/root finish - // for a Finish (no finishTransitionBuilder involved). In practice a pure transition() only reaches - // this arm as Ignore (handled above); this keeps Finish/NavigateTo/… correct-by-construction for a - // stateful transition() that returns something else on re-consultation. + // for a Finish (no finishTransitionBuilder involved). A parallel which was asked on the way up of the + // region fold already comes here with that answer (Ignore, handled above) and is not asked again. else -> return if (ownerRegionId != null && ownerNodes != null) { resolveTransitionInRegion( regionId = ownerRegionId, @@ -885,6 +933,22 @@ private fun dispatchBackIntoRegion( ) } +/** + * Whether [regionId] names a region of the parallel at [parallelPath] which is not started: it has nothing to go + * back from, so Back which is dispatched to it is ignored. + */ +private fun isUnstartedRegion( + regionId: RegionId, + parallelPath: Path, + allRegions: Map, + schema: Schema, +): Boolean { + val regionRoot = regionId.resolveAbsolute(parallelPath).path + return regionRoot.length == parallelPath.length + 1 && + allRegions.keys.none { it.path.startsWith(regionRoot) } && + nodeTypeOrNull(schema, regionRoot) != null +} + private fun subRegionActivePaths(parentPath: Path, allRegions: Map): Map = allRegions .filterKeys { it.path.length == parentPath.length + 1 && it.path.startsWith(parentPath) } .mapValues { it.value.active } @@ -1025,16 +1089,31 @@ private fun maybeResolveInitial( is FlowNode<*> -> { val nextTargetPathAbs = targetPathAbs.append(targetNode.initial.path) recordTargetPayloads(targetNode.initial, nextTargetPathAbs, callingRegionId, nodes, payloads) - maybeResolveInitial( - targetNode.initial, - nextTargetPathAbs, - nodeBuilder, - nodes, - schema, - payloads, - callingRegionId, - visitedPaths, - ) + // an initial target inside of a parallel declared below this flow enters that parallel + val parallelOnPath = findParallelOnPath(nextTargetPathAbs, RegionId(targetPathAbs), emptySet(), schema) + if (parallelOnPath != null) { + initParallelAndRouteAbsolute( + nextTargetPathAbs, + parallelOnPath, + callingRegionId, + nodeBuilder, + nodes, + schema, + payloads, + emptySet(), + ) + } else { + maybeResolveInitial( + targetNode.initial, + nextTargetPathAbs, + nodeBuilder, + nodes, + schema, + payloads, + callingRegionId, + visitedPaths, + ) + } } is ParallelFlowNode<*> -> { @@ -1046,8 +1125,10 @@ private fun maybeResolveInitial( if (targetPathAbs.startsWith(callingRegionId.path)) { resolved[callingRegionId] = targetPathAbs } - parallelSchema.regions.forEach { relativeRegionId -> - val regionRootAbs = absoluteRegionRoot(schemaPath, relativeRegionId) + val regionRoots = regionRootsOf(parallelSchema, schemaPath, targetPathAbs) + targetNode.checkInitialRegions(targetPathAbs, regionRoots) + regionRoots.forEach { regionRootAbs -> + if (!targetNode.startsRegion(targetPathAbs, regionRootAbs)) return@forEach val absoluteRegionId = RegionId(regionRootAbs) resolved.putAll( maybeResolveInitial(regionRootAbs, absoluteRegionId, nodeBuilder, nodes, schema, payloads, mutableSetOf()), @@ -1070,6 +1151,24 @@ private fun maybeResolveInitial( internal fun owningRegionId(path: Path, regions: Collection, fallback: RegionId): RegionId = regions.filter { path.startsWith(it.path) }.maxByOrNull { it.path.length } ?: fallback +/** + * The region of an alive parallel which owns [path] and is not started yet (see [ParallelFlowNode.initialRegions]), + * or `null` if [path] belongs to a started region or to a parallel which is not alive. A parallel is alive exactly + * when one of its regions is started. + */ +private fun unstartedRegionId(path: Path, regions: Collection, schema: Schema): RegionId? { + val ownerLength = regions.filter { path.startsWith(it.path) }.maxOfOrNull { it.path.length } ?: 0 + for (length in maxOf(ownerLength + 1, 2)..path.length) { + val regionRoot = path.take(length) + val parallelPath = regionRoot.dropLast(1) + if (isParallelFlowAt(schema, parallelPath)) { + val isAlive = regions.any { it.path.length == length && it.path.startsWith(parallelPath) } + return if (isAlive && !isParallelFlowAt(schema, regionRoot)) RegionId(regionRoot) else null + } + } + return null +} + /** The node type at [path], or `null` if the schema can't resolve it. Defensive against traversal errors. */ private fun nodeTypeOrNull(schema: Schema, path: Path): Schema.NodeType? = runCatching { findNodeType(schema, path) }.getOrNull() @@ -1104,7 +1203,8 @@ private fun resolveAbsoluteLeaves( ): Map { val resolvedLeaves = mutableMapOf() candidates.forEach { candidate -> - val candidateRegionId = owningRegionId(candidate, allRegions.keys, fallback = defaultRegionId) + val candidateRegionId = unstartedRegionId(candidate, allRegions.keys, schema) + ?: owningRegionId(candidate, allRegions.keys, fallback = defaultRegionId) val candidateNodes = allRegions[candidateRegionId]?.nodes ?: fallbackNodes val parallelOnPath = findParallelOnPath(candidate, candidateRegionId, initializedPaths, schema) val resolved = if (parallelOnPath != null) { @@ -1192,8 +1292,18 @@ private fun initParallelAndRouteAbsolute( if (parallelPath.startsWith(callingRegionId.path)) { resolved[callingRegionId] = parallelPath } - parallelSchema.regions.forEach { relativeRegionId -> - val regionRootAbs = absoluteRegionRoot(schemaPath, relativeRegionId) + val regionRoots = regionRootsOf(parallelSchema, schemaPath, parallelPath) + // Built only to read initialRegions, and only if there is a sibling region to decide on. A node which cannot be + // built here (a payload is missing) starts all its regions, the transition is then dropped as MissingPayload. + val parallelNode by lazy { + val node = nodes[parallelPath] ?: runCatching { + nodeBuilder.build(parallelPath, payloads = payloads, rootSegmentAlias = nodeBuilder.schema.rootSegment) + }.getOrNull() + (node as? ParallelFlowNode<*>)?.also { + it.checkInitialRegions(parallelPath, regionRoots) + } + } + regionRoots.forEach { regionRootAbs -> val absoluteRegionId = RegionId(regionRootAbs) if (absolutePath.startsWith(regionRootAbs)) { // This sub-region owns absolutePath — check for deeper nested uninitialized parallels @@ -1212,6 +1322,8 @@ private fun initParallelAndRouteAbsolute( // Other sub-regions — preserve any active path a previous target in the same NavigateTo // chose for this region; otherwise initialize to the default initial state. if (absoluteRegionId in alreadyChosen) return@forEach + val startsRegion = parallelNode?.startsRegion(parallelPath, regionRootAbs) ?: true + if (!startsRegion) return@forEach resolved.putAll( maybeResolveInitial(regionRootAbs, absoluteRegionId, nodeBuilder, nodes, schema, payloads, mutableSetOf()), ) diff --git a/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/BaseParallelFlowNode.kt b/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/BaseParallelFlowNode.kt new file mode 100644 index 0000000..27fbbd4 --- /dev/null +++ b/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/BaseParallelFlowNode.kt @@ -0,0 +1,23 @@ +package ru.kode.way.extension.node.hook + +import ru.kode.way.ParallelFlowNode + +/** + * A parallel flow node with hooks support, the counterpart of [BaseFlowNode]. + * + * Requires [NodeHooksSupportExtensionPoint] to be added to [ru.kode.way.NavigationService] to work. + */ +abstract class BaseParallelFlowNode : + ParallelFlowNode(), + HasFlowNodeHooks { + private val _hooks = mutableListOf>() + override val hooks: List> = _hooks + + override fun addHook(hook: FlowNodeHook) { + _hooks.add(hook) + } + + override fun removeHook(hook: FlowNodeHook) { + _hooks.remove(hook) + } +} diff --git a/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/FlowNodeHook.kt b/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/FlowNodeHook.kt index 12a7084..2186adc 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/FlowNodeHook.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/FlowNodeHook.kt @@ -4,12 +4,12 @@ import ru.kode.way.Event import ru.kode.way.FlowTransition interface FlowNodeHook { - fun onPreEntry() - fun onPostEntry() - fun onPreTransition(event: Event) - fun onPostTransition(event: Event, transition: FlowTransition) - fun onPreExit() - fun onPostExit() + fun onPreEntry() {} + fun onPostEntry() {} + fun onPreTransition(event: Event) {} + fun onPostTransition(event: Event, transition: FlowTransition) {} + fun onPreExit() {} + fun onPostExit() {} fun onPreDispose() {} fun onPostDispose() {} } diff --git a/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/ScreenNodeHook.kt b/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/ScreenNodeHook.kt index 7f07cb9..ed1c8b4 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/ScreenNodeHook.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/extension/node/hook/ScreenNodeHook.kt @@ -19,10 +19,10 @@ package ru.kode.way.extension.node.hook * [ru.kode.way.NavigationService] and the screen node to implement [HasScreenNodeHooks]. */ interface ScreenNodeHook { - fun onPreEntry() - fun onPostEntry() - fun onPreExit() - fun onPostExit() + fun onPreEntry() {} + fun onPostEntry() {} + fun onPreExit() {} + fun onPostExit() {} fun onPreDispose() {} fun onPostDispose() {} } diff --git a/way/src/commonTest/kotlin/ru/kode/way/DoubleNestedParallelTest.kt b/way/src/commonTest/kotlin/ru/kode/way/DoubleNestedParallelTest.kt new file mode 100644 index 0000000..8f9e094 --- /dev/null +++ b/way/src/commonTest/kotlin/ru/kode/way/DoubleNestedParallelTest.kt @@ -0,0 +1,445 @@ +package ru.kode.way + +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.collections.shouldBeEmpty +import io.kotest.matchers.collections.shouldContainExactly +import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder +import io.kotest.matchers.comparables.shouldBeLessThan +import io.kotest.matchers.shouldBe +import ru.kode.way.doublenested.DnANodeBuilder +import ru.kode.way.doublenested.DnASchema +import ru.kode.way.doublenested.DnAppNodeBuilder +import ru.kode.way.doublenested.DnBNodeBuilder +import ru.kode.way.doublenested.DnBSchema +import ru.kode.way.doublenested.DnInnerNodeBuilder +import ru.kode.way.doublenested.DnInnerSchema +import ru.kode.way.doublenested.DnLeftNodeBuilder +import ru.kode.way.doublenested.DnLeftSchema +import ru.kode.way.doublenested.DnMainNodeBuilder +import ru.kode.way.doublenested.DnMainSchema +import ru.kode.way.doublenested.DnOuterNodeBuilder +import ru.kode.way.doublenested.DnOuterSchema +import ru.kode.way.doublenested.DnRightNodeBuilder +import ru.kode.way.doublenested.DnRightSchema +import ru.kode.way.doublenested.DnSideNodeBuilder +import ru.kode.way.doublenested.DnSideSchema +import ru.kode.way.doublenested.DnWrapNodeBuilder +import ru.kode.way.doublenested.ParallelTestDoubleNestedSchema +import ru.kode.way.doublenested.dnA +import ru.kode.way.doublenested.dnB +import ru.kode.way.doublenested.dnLeft +import ru.kode.way.doublenested.dnMain +import ru.kode.way.doublenested.dnRight +import ru.kode.way.doublenested.dnSide +import ru.kode.way.doublenested.dnWrap + +/** A parallel declared inside of a region of another parallel, see `parallel-test-double-nested.dot`. */ +class DoubleNestedParallelTest : ShouldSpec() { + init { + should("start the regions of each parallel when it is entered") { + val log = mutableListOf() + val states = mutableListOf() + val sut = buildService(log) + sut.addTransitionListener { states.add(it) } + sut.start() + log.shouldBeEmpty() + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnSide") + + sut.send(TestEvent("openOuter")) + log.shouldContainExactly("enter wrap", "enter outer", "enter left", "enter right") + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnSide", "dnLeft", "dnRight") + + log.clear() + sut.send(TestEvent("openInner")) + log.shouldContainExactlyInAnyOrder("enter inner", "enter a", "enter b") + log.indexOf("enter inner") shouldBeLessThan log.indexOf("enter a") + log.indexOf("enter inner") shouldBeLessThan log.indexOf("enter b") + states.last().regionNames() + .shouldContainExactlyInAnyOrder("dnMain", "dnSide", "dnLeft", "dnRight", "dnA", "dnB") + } + + should("exit the inner parallel and its regions when only it is left") { + val log = mutableListOf() + val states = mutableListOf() + val sut = buildService(log) + sut.addTransitionListener { states.add(it) } + sut.start() + sut.send(TestEvent("openOuter")) + sut.send(TestEvent("openInner")) + + log.clear() + sut.send(TestEvent("closeInner")) + log.shouldContainExactlyInAnyOrder("exit a", "exit b", "exit inner") + log.last() shouldBe "exit inner" + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnSide", "dnLeft", "dnRight") + } + + should("exit both parallels from the deepest node up when the outer one is left") { + val log = mutableListOf() + val states = mutableListOf() + val sut = buildService(log) + sut.addTransitionListener { states.add(it) } + sut.start() + sut.send(TestEvent("openOuter")) + sut.send(TestEvent("openInner")) + + log.clear() + sut.send(TestEvent("openIntro")) + log.shouldContainExactlyInAnyOrder( + "exit a", + "exit b", + "exit inner", + "exit left", + "exit right", + "exit outer", + "exit wrap", + ) + // a flow between the region and the parallel is above the parallel, so it is exited after it + log.last() shouldBe "exit wrap" + log.indexOf("exit a") shouldBeLessThan log.indexOf("exit inner") + log.indexOf("exit b") shouldBeLessThan log.indexOf("exit inner") + log.indexOf("exit inner") shouldBeLessThan log.indexOf("exit left") + log.indexOf("exit left") shouldBeLessThan log.indexOf("exit outer") + log.indexOf("exit right") shouldBeLessThan log.indexOf("exit outer") + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnSide") + + // nothing of the left parallels is kept: they are entered anew, the inner one only when asked for + log.clear() + sut.send(TestEvent("openOuter")) + log.shouldContainExactly("enter wrap", "enter outer", "enter left", "enter right") + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnSide", "dnLeft", "dnRight") + } + + listOf("a", "inner", "left", "outer", "wrap").forEach { failing -> + should("keep both parallels when the onExit of \"$failing\" throws on leaving the outer one") { + val all = listOf("a", "b", "inner", "left", "right", "outer", "wrap") + val log = mutableListOf() + val states = mutableListOf() + val sut = buildService(log, failingOnExit = mutableSetOf(failing)) + sut.addTransitionListener { states.add(it) } + sut.start() + sut.send(TestEvent("openOuter")) + sut.send(TestEvent("openInner")) + val statesBefore = states.size + + log.clear() + shouldThrow { sut.send(TestEvent("openIntro")) } + // every node which was exited is entered back, no node twice + val exited = log.filter { it.startsWith("exit") }.map { it.removePrefix("exit ") } + exited.shouldContainExactlyInAnyOrder(exited.distinct()) + log.filter { it.startsWith("enter") }.map { it.removePrefix("enter ") }.shouldContainExactlyInAnyOrder(exited) + states.size shouldBe statesBefore + + // the transition was rolled back: nothing is lost and the same leave works afterwards + log.clear() + sut.send(TestEvent("openIntro")) + log.shouldContainExactlyInAnyOrder(all.map { "exit $it" }) + log.indexOf("exit inner") shouldBeLessThan log.indexOf("exit left") + log.indexOf("exit left") shouldBeLessThan log.indexOf("exit outer") + log.last() shouldBe "exit wrap" + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnSide") + } + } + + should("enter back a parallel which was left by a failed transition with its regions in place") { + val log = mutableListOf() + val leftStartedOnEntry = mutableListOf() + val sut = buildService( + log, + failingOnExit = mutableSetOf("wrap"), + onOuterEntry = { leftStartedOnEntry += it.isRegionStarted(DnOuterSchema().dnLeftRegionId) }, + ) + sut.start() + sut.send(TestEvent("openOuter")) + + leftStartedOnEntry.clear() + shouldThrow { sut.send(TestEvent("openIntro")) } + leftStartedOnEntry.shouldContainExactly(true) + } + + should("enter every node after the nodes above it when a target is deep inside of both parallels") { + val log = mutableListOf() + val sut = buildService(log) + sut.start() + + sut.send(TestEvent("openDeep")) + log.shouldContainExactlyInAnyOrder( + "enter wrap", + "enter outer", + "enter left", + "enter right", + "enter inner", + "enter a", + "enter b", + ) + listOf( + "wrap" to "outer", + "outer" to "left", + "outer" to "right", + "left" to "inner", + "inner" to "a", + "inner" to "b", + ) + .forEach { (above, below) -> log.indexOf("enter $above") shouldBeLessThan log.indexOf("enter $below") } + } + + should("start a schema whose root is a flow with a parallel declared under it") { + val log = mutableListOf() + val states = mutableListOf() + val sut = buildService(log, flowRooted = true) + sut.addTransitionListener { states.add(it) } + sut.start() + log.shouldBeEmpty() + states.last().regionNames().shouldContainExactly("dnMain") + + sut.send(TestEvent("openOuter")) + log.shouldContainExactly("enter wrap", "enter outer", "enter left", "enter right") + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnLeft", "dnRight") + + sut.send(TestEvent("openInner")) + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnLeft", "dnRight", "dnA", "dnB") + + log.clear() + sut.send(TestEvent("openIntro")) + log.last() shouldBe "exit wrap" + log.size shouldBe 7 + states.last().regionNames().shouldContainExactly("dnMain") + } + + should("ask a parallel declared under a flow about Back once") { + fun eventsOfOuterOnBack(flowRooted: Boolean): List { + val outerEvents = mutableListOf() + val sut = buildService(mutableListOf(), flowRooted = flowRooted, onOuterEvent = { outerEvents.add(it) }) + sut.start() + sut.send(TestEvent("openOuter")) + outerEvents.clear() + sut.send(Event.Back) + return outerEvents.map { it.toString() } + } + + // Back goes into one region, chosen by the parallel: its regions are not asked each on their own + val events = eventsOfOuterOnBack(flowRooted = true) + events.count { it == Event.Back.toString() } shouldBe 1 + events.size shouldBe 2 + eventsOfOuterOnBack(flowRooted = false) shouldBe events + } + + should("exit a node whose onEntry has thrown along with the nodes entered before it") { + val log = mutableListOf() + val states = mutableListOf() + val sut = buildService(log, failingOnEntry = mutableSetOf("left")) + sut.addTransitionListener { states.add(it) } + sut.start() + + shouldThrow { sut.send(TestEvent("openOuter")) } + log.shouldContainExactly("enter wrap", "enter outer", "enter left", "exit left", "exit outer", "exit wrap") + states.last().regionNames().shouldContainExactlyInAnyOrder("dnMain", "dnSide") + + log.clear() + sut.send(TestEvent("openOuter")) + log.shouldContainExactly("enter wrap", "enter outer", "enter left", "enter right") + } + + should("not exit a node whose onEntry was not reached because a hook has thrown before it") { + val log = mutableListOf() + val sut = buildService(log) + var failing = true + sut.addNodeExtensionPoint( + TestNodeExtensionPoint( + preEntry = { _, path -> if (failing && "$path".endsWith("dnLeft")) error("hook failed") }, + ), + ) + sut.start() + + shouldThrow { sut.send(TestEvent("openOuter")) } + log.shouldContainExactly("enter wrap", "enter outer", "exit outer", "exit wrap") + + failing = false + log.clear() + sut.send(TestEvent("openOuter")) + log.shouldContainExactly("enter wrap", "enter outer", "enter left", "enter right") + } + + should("not enter back a node whose onExit was not reached because a hook has thrown before it") { + val log = mutableListOf() + val sut = buildService(log) + var failing = false + sut.addNodeExtensionPoint( + TestNodeExtensionPoint( + preExit = { _, path -> if (failing && "$path".endsWith("dnLeft")) error("hook failed") }, + ), + ) + sut.start() + sut.send(TestEvent("openOuter")) + + failing = true + log.clear() + shouldThrow { sut.send(TestEvent("openIntro")) } + log.filter { it.endsWith(" left") }.shouldBeEmpty() + log.filter { it.startsWith("exit") }.map { it.removePrefix("exit") }.sorted() shouldBe + log.filter { it.startsWith("enter") }.map { it.removePrefix("enter") }.sorted() + + failing = false + log.clear() + sut.send(TestEvent("openIntro")) + log.filter { it.endsWith(" left") }.shouldContainExactly("exit left") + } + + should("drop an event which a node has sent while it was entered back by a failed transition") { + val log = mutableListOf() + lateinit var sut: NavigationService + var sendOnEntry = false + sut = buildService( + log, + failingOnExit = mutableSetOf("wrap"), + onOuterEntry = { if (sendOnEntry) sut.send(TestEvent("openIntro")) }, + ) + sut.start() + sut.send(TestEvent("openOuter")) + + sendOnEntry = true + shouldThrow { sut.send(TestEvent("openIntro")) } + sendOnEntry = false + log.clear() + sut.send(TestEvent("unknown")) + log.shouldBeEmpty() + } + } +} + +private fun NavigationState.regionNames(): List = regions.keys.map { it.path.lastSegment().name } + +private fun buildService( + log: MutableList, + failingOnExit: MutableSet = mutableSetOf(), + failingOnEntry: MutableSet = mutableSetOf(), + flowRooted: Boolean = false, + onOuterEntry: (ParallelFlowNode<*>) -> Unit = {}, + onOuterEvent: (Event) -> Unit = {}, +): NavigationService { + fun onExit(name: String) { + log += "exit $name" + if (failingOnExit.remove(name)) error("exit of $name failed") + } + + fun onEntry(name: String) { + log += "enter $name" + if (failingOnEntry.remove(name)) error("entry of $name failed") + } + + fun flow(name: String, initialTarget: Target, transitions: List = emptyList()) = TestFlowNode( + initialTarget = initialTarget, + transitions = transitions, + onEntryImpl = { onEntry(name) }, + onExitImpl = { onExit(name) }, + ) + + fun parallel(name: String) = TestParallelNode(onEntryImpl = { onEntry(name) }, onExitImpl = { onExit(name) }) + + val aNodeBuilder = DnANodeBuilder( + nodeFactory = object : DnANodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = flow("a", Target.dnA.dnAScreen) + override fun createDnAScreenNode(): ScreenNode = TestScreenNode() + }, + schema = DnASchema(), + ) + val bNodeBuilder = DnBNodeBuilder( + nodeFactory = object : DnBNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = flow("b", Target.dnB.dnBScreen) + override fun createDnBScreenNode(): ScreenNode = TestScreenNode() + }, + schema = DnBSchema(), + ) + val innerNodeBuilder = DnInnerNodeBuilder( + nodeFactory = object : DnInnerNodeBuilder.Factory { + override fun createRootNode(): ParallelFlowNode<*> = parallel("inner") + override fun createDnANodeBuilder(): NodeBuilder = aNodeBuilder + override fun createDnBNodeBuilder(): NodeBuilder = bNodeBuilder + }, + schema = DnInnerSchema(), + ) + val leftNodeBuilder = DnLeftNodeBuilder( + nodeFactory = object : DnLeftNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = flow( + "left", + Target.dnLeft.dnLeftScreen, + listOf(tr("openInner", Target.dnA.dnAScreen), tr("closeInner", Target.dnLeft.dnLeftScreen)), + ) + override fun createDnLeftScreenNode(): ScreenNode = TestScreenNode() + override fun createDnInnerNodeBuilder(): NodeBuilder = innerNodeBuilder + }, + schema = DnLeftSchema(), + ) + val rightNodeBuilder = DnRightNodeBuilder( + nodeFactory = object : DnRightNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = flow("right", Target.dnRight.dnRightScreen) + override fun createDnRightScreenNode(): ScreenNode = TestScreenNode() + }, + schema = DnRightSchema(), + ) + val outerNodeBuilder = DnOuterNodeBuilder( + nodeFactory = object : DnOuterNodeBuilder.Factory { + override fun createRootNode(): ParallelFlowNode<*> { + lateinit var node: ParallelFlowNode<*> + node = TestParallelNode( + onEntryImpl = { + log += "enter outer" + onOuterEntry(node) + }, + onExitImpl = { onExit("outer") }, + onTransitionCallback = onOuterEvent, + ) + return node + } + override fun createDnLeftNodeBuilder(): NodeBuilder = leftNodeBuilder + override fun createDnRightNodeBuilder(): NodeBuilder = rightNodeBuilder + override fun createDnInnerNodeBuilder(): NodeBuilder = innerNodeBuilder + }, + schema = DnOuterSchema(), + ) + val wrapNodeBuilder = DnWrapNodeBuilder( + nodeFactory = object : DnWrapNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = flow("wrap", Target.dnWrap.dnWrapScreen) + override fun createDnWrapScreenNode(): ScreenNode = TestScreenNode() + }, + schema = DnMainSchema(), + ) + val mainNodeBuilder = DnMainNodeBuilder( + nodeFactory = object : DnMainNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = TestFlowNode( + initialTarget = Target.dnMain.dnIntroScreen, + transitions = listOf( + tr("openOuter", Target.dnLeft.dnLeftScreen), + tr("openIntro", Target.dnMain.dnIntroScreen), + tr("openDeep", Target.dnA.dnAScreen), + ), + ) + override fun createDnIntroScreenNode(): ScreenNode = TestScreenNode() + override fun createDnWrapNodeBuilder(): NodeBuilder = wrapNodeBuilder + override fun createDnOuterNodeBuilder(): NodeBuilder = outerNodeBuilder + }, + schema = DnMainSchema(), + ) + val sideNodeBuilder = DnSideNodeBuilder( + nodeFactory = object : DnSideNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = TestFlowNode(initialTarget = Target.dnSide.dnSideScreen) + override fun createDnSideScreenNode(): ScreenNode = TestScreenNode() + }, + schema = DnSideSchema(), + ) + if (flowRooted) return NavigationService(nodeBuilder = mainNodeBuilder, onFinishRequest = { Ignore }) + return NavigationService( + nodeBuilder = DnAppNodeBuilder( + nodeFactory = object : DnAppNodeBuilder.Factory { + override fun createRootNode(): ParallelFlowNode<*> = TestParallelNode() + override fun createDnMainNodeBuilder(): NodeBuilder = mainNodeBuilder + override fun createDnSideNodeBuilder(): NodeBuilder = sideNodeBuilder + override fun createDnWrapNodeBuilder(): NodeBuilder = wrapNodeBuilder + override fun createDnOuterNodeBuilder(): NodeBuilder = outerNodeBuilder + }, + schema = ParallelTestDoubleNestedSchema(), + ), + onFinishRequest = { Ignore }, + ) +} diff --git a/way/src/commonTest/kotlin/ru/kode/way/InvalidateCacheTest.kt b/way/src/commonTest/kotlin/ru/kode/way/InvalidateCacheTest.kt index 99551c9..d93203b 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/InvalidateCacheTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/InvalidateCacheTest.kt @@ -127,6 +127,33 @@ class InvalidateCacheTest : ShouldSpec() { betaCreates shouldBe 2 } + should("restoreCache brings back the child NodeBuilders which invalidateCache has evicted") { + var alphaCreates = 0 + val alphaBuilder = makeAlphaNodeBuilder() + val betaBuilder = makeBetaNodeBuilder() + val mainBuilder = Par02MainNodeBuilder( + nodeFactory = object : Par02MainNodeBuilder.Factory { + override fun createRootNode(): ParallelFlowNode = TestParallelNode() + override fun createPar02AlphaNodeBuilder(): NodeBuilder { + alphaCreates++ + return alphaBuilder + } + override fun createPar02BetaNodeBuilder(): NodeBuilder = betaBuilder + }, + schema = Parallel02MainSchema(Parallel02AlphaSchema(), Parallel02BetaSchema()), + ) + val mainRoot = Segment("par02Main@Parallel02Main:src/commonTest/way/parallel-test02-main.dot") + val alphaSeg = Segment("par02Alpha@Parallel02Alpha:src/commonTest/way/parallel-test02-alpha.dot") + mainBuilder.build(Path(listOf(mainRoot, alphaSeg)), payloads = emptyMap(), rootSegmentAlias = mainRoot) + + val snapshot = mainBuilder.snapshotCache() + mainBuilder.invalidateCache(emptySet()) + mainBuilder.restoreCache(snapshot) + + mainBuilder.build(Path(listOf(mainRoot, alphaSeg)), payloads = emptyMap(), rootSegmentAlias = mainRoot) + alphaCreates shouldBe 1 + } + // Short-form regression guard for Way, written directly against the new // `Set` signature of [NodeBuilder.invalidateCache] (the long-form lives in // `ParallelNodeTest.kt` at "invalidateCache does not evict NodeBuilders that are alive diff --git a/way/src/commonTest/kotlin/ru/kode/way/LazyRegionTest.kt b/way/src/commonTest/kotlin/ru/kode/way/LazyRegionTest.kt new file mode 100644 index 0000000..d007831 --- /dev/null +++ b/way/src/commonTest/kotlin/ru/kode/way/LazyRegionTest.kt @@ -0,0 +1,340 @@ +package ru.kode.way + +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.collections.shouldContainOnly +import io.kotest.matchers.shouldBe +import ru.kode.way.extension.node.hook.BaseParallelFlowNode +import ru.kode.way.extension.node.hook.FlowNodeHook +import ru.kode.way.extension.node.hook.NodeHooksSupportExtensionPoint +import ru.kode.way.par03.Par03AppNodeBuilder +import ru.kode.way.par03.Parallel03Schema +import ru.kode.way.par03.alpha.Par03AlphaNodeBuilder +import ru.kode.way.par03.alpha.Parallel03AlphaSchema +import ru.kode.way.par03.alpha.par03Alpha +import ru.kode.way.par03.beta.Par03BetaNodeBuilder +import ru.kode.way.par03.beta.Parallel03BetaSchema +import ru.kode.way.par03.beta.par03Beta +import ru.kode.way.par03.main.Par03MainNodeBuilder +import ru.kode.way.par03.main.Parallel03MainSchema +import ru.kode.way.par03.par03App +import ru.kode.way.partoproot.AlphaNodeBuilder +import ru.kode.way.partoproot.AlphaSchema +import ru.kode.way.partoproot.BetaNodeBuilder +import ru.kode.way.partoproot.BetaSchema +import ru.kode.way.partoproot.ParallelTestTopRootSchema +import ru.kode.way.partoproot.TopRootNodeBuilder +import ru.kode.way.partoproot.alpha +import ru.kode.way.partoproot.beta + +class LazyRegionTest : ShouldSpec() { + init { + should("start only the initial regions of a root parallel") { + val fixture = TopRootFixture(initial = { setOf(it.alphaRegionId) }) + fixture.service.start() + + fixture.regionLeaves() shouldBe mapOf("alpha" to "alphaScreen") + fixture.betaRootsCreated shouldBe 0 + fixture.root.isRegionStarted(fixture.schema.alphaRegionId) shouldBe true + fixture.root.isRegionStarted(fixture.schema.betaRegionId) shouldBe false + } + + should("start a region of a root parallel once and keep the started ones") { + val fixture = TopRootFixture(initial = { setOf(it.alphaRegionId) }) + fixture.service.start() + + fixture.service.send(TestEvent("startBeta")) + + fixture.regionLeaves() shouldBe mapOf("alpha" to "alphaScreen", "beta" to "betaScreen") + fixture.alphaRootEntries shouldBe 1 + fixture.betaRootEntries shouldBe 1 + fixture.root.isRegionStarted(fixture.schema.betaRegionId) shouldBe true + + fixture.service.send(TestEvent("startBeta")) + fixture.betaRootEntries shouldBe 1 + } + + should("deliver events and Back while a region is not started") { + val fixture = TopRootFixture(initial = { setOf(it.alphaRegionId) }) + fixture.service.start() + + fixture.service.send(TestEvent("unknown")) + fixture.service.send(Event.Back) + + fixture.betaRootsCreated shouldBe 0 + } + + should("tell whether a region rests on its first node") { + val fixture = Par03Fixture(initial = { setOf(it.par03BetaRegionId) }) + fixture.service.start() + val main = fixture.main + val alpha = fixture.mainSchema.par03AlphaRegionId + + main.isRegionAtRoot(alpha) shouldBe false + fixture.service.send(TestEvent("startAlpha")) + main.isRegionAtRoot(alpha) shouldBe true + fixture.service.send(TestEvent("goToScreen2")) + main.isRegionAtRoot(alpha) shouldBe false + fixture.service.send(Event.Back) + main.isRegionAtRoot(alpha) shouldBe true + } + + should("call hooks of a parallel flow node") { + val calls = mutableListOf() + val fixture = Par03Fixture(initial = { setOf(it.par03BetaRegionId) }) + fixture.main.addHook(object : FlowNodeHook { + override fun onPostEntry() { + calls += "entry" + } + override fun onPostExit() { + calls += "exit" + } + }) + fixture.service.start() + fixture.service.send(TestEvent("PAGE")) + + calls shouldBe listOf("entry", "exit") + } + + should("reject empty initial regions") { + val fixture = TopRootFixture(initial = { emptySet() }) + shouldThrow { fixture.service.start() } + } + + should("start only the initial regions when a parallel is entered by navigation") { + val fixture = Par03Fixture(initial = { setOf(it.par03BetaRegionId) }) + fixture.service.start() + + fixture.regionLeaves() shouldBe mapOf("par03App" to "par03Main", "par03Beta" to "par03BetaScreen") + + fixture.service.send(TestEvent("PAGE")) + fixture.service.send(TestEvent("MAIN")) + fixture.regionLeaves() shouldBe mapOf("par03App" to "par03Main", "par03Beta" to "par03BetaScreen") + } + + should("not restart a started region of a nested parallel") { + val fixture = Par03Fixture(initial = { setOf(it.par03BetaRegionId) }) + fixture.service.start() + + fixture.service.send(TestEvent("startAlpha")) + fixture.regionLeaves()["par03Alpha"] shouldBe "par03AlphaScreen" + fixture.betaRootEntries shouldBe 1 + + fixture.service.send(TestEvent("goToScreen2")) + fixture.service.send(TestEvent("startAlpha")) + fixture.regionLeaves()["par03Alpha"] shouldBe "par03AlphaScreen2" + fixture.betaRootEntries shouldBe 1 + } + + should("start a region by an absolute target without restarting its siblings") { + val fixture = Par03Fixture(initial = { setOf(it.par03BetaRegionId) }) + fixture.service.start() + + fixture.service.send(TestEvent("deeplinkAlpha")) + + fixture.regionLeaves() shouldBe mapOf( + "par03App" to "par03Main", + "par03Alpha" to "par03AlphaScreen2", + "par03Beta" to "par03BetaScreen", + ) + fixture.betaRootEntries shouldBe 1 + } + + should("start a region by a history target") { + val fixture = Par03Fixture(initial = { setOf(it.par03BetaRegionId) }) + fixture.service.start() + + fixture.service.send(TestEvent("historyAlpha")) + + fixture.regionLeaves() shouldBe mapOf( + "par03App" to "par03Main", + "par03Alpha" to "par03AlphaScreen", + "par03Beta" to "par03BetaScreen", + ) + fixture.main.isRegionStarted(fixture.mainSchema.par03AlphaRegionId) shouldBe true + fixture.betaRootEntries shouldBe 1 + } + + should("ignore Back which is dispatched to a region which is not started") { + val fixture = Par03Fixture(initial = { setOf(it.par03AlphaRegionId) }, backRegion = { it.par03BetaRegionId }) + fixture.service.start() + fixture.service.send(TestEvent("goToScreen2")) + + fixture.service.send(Event.Back) + + fixture.regionLeaves() shouldBe mapOf("par03App" to "par03Main", "par03Alpha" to "par03AlphaScreen2") + } + + should("reject initial regions of another parallel") { + val fixture = + TopRootFixture(initial = { + setOf(Parallel03MainSchema(Parallel03AlphaSchema(), Parallel03BetaSchema()).par03AlphaRegionId) + }) + shouldThrow { fixture.service.start() } + } + + should("start the initial regions and the target one when an absolute target enters a parallel") { + val fixture = Par03Fixture(initial = { setOf(it.par03BetaRegionId) }) + fixture.service.start() + fixture.service.send(TestEvent("PAGE")) + fixture.regionLeaves().keys.shouldContainOnly("par03App") + + fixture.service.send(TestEvent("deeplinkBeta")) + fixture.regionLeaves() shouldBe mapOf("par03App" to "par03Main", "par03Beta" to "par03BetaScreen") + + fixture.service.send(TestEvent("PAGE")) + fixture.service.send(TestEvent("deeplinkAlpha")) + fixture.regionLeaves() shouldBe mapOf( + "par03App" to "par03Main", + "par03Alpha" to "par03AlphaScreen2", + "par03Beta" to "par03BetaScreen", + ) + } + } +} + +internal class LazyParallelNode( + private val initial: Set, + private val startEvents: Map, + private val backRegion: RegionId? = null, +) : BaseParallelFlowNode() { + override val dismissResult = Unit + override val initialRegions: Set get() = initial + + override fun transition(event: Event): FlowTransition { + if (event == Event.Back && backRegion != null) return DispatchBackTo(backRegion) + val regionId = (event as? TestEvent)?.let { startEvents[it.name] } + return if (regionId != null) startRegion(regionId) else Ignore + } +} + +private fun NavigationState.leaves(): Map = + regions.entries.associate { it.key.path.lastSegment().name to it.value.active.lastSegment().name } + +private class TopRootFixture(initial: (ParallelTestTopRootSchema) -> Set) { + val schema = ParallelTestTopRootSchema() + val root = LazyParallelNode(initial(schema), mapOf("startBeta" to schema.betaRegionId)) + var alphaRootEntries = 0 + var betaRootEntries = 0 + var betaRootsCreated = 0 + private val states = mutableListOf() + + val service: NavigationService = NavigationService( + nodeBuilder = TopRootNodeBuilder( + nodeFactory = object : TopRootNodeBuilder.Factory { + override fun createRootNode(): ParallelFlowNode = root + override fun createAlphaNodeBuilder(): NodeBuilder = AlphaNodeBuilder( + nodeFactory = object : AlphaNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = + TestFlowNode(initialTarget = Target.alpha.alphaScreen, onEntryImpl = { alphaRootEntries++ }) + override fun createAlphaScreenNode(): ScreenNode = TestScreenNode() + }, + schema = AlphaSchema(), + ) + override fun createBetaNodeBuilder(): NodeBuilder = BetaNodeBuilder( + nodeFactory = object : BetaNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> { + betaRootsCreated++ + return TestFlowNode(initialTarget = Target.beta.betaScreen, onEntryImpl = { betaRootEntries++ }) + } + override fun createBetaScreenNode(): ScreenNode = TestScreenNode() + }, + schema = BetaSchema(), + ) + }, + schema = schema, + ), + onFinishRequest = { Ignore }, + ).also { service -> service.addTransitionListener { states.add(it) } } + + fun regionLeaves(): Map = states.last().leaves() +} + +private class Par03Fixture( + initial: (Parallel03MainSchema) -> Set, + backRegion: (Parallel03MainSchema) -> RegionId? = { null }, +) { + val mainSchema = Parallel03MainSchema(Parallel03AlphaSchema(), Parallel03BetaSchema()) + private val appSchema = Parallel03Schema(par03MainSchema = mainSchema) + var betaRootEntries = 0 + private val states = mutableListOf() + + val main = LazyParallelNode( + initial(mainSchema), + mapOf("startAlpha" to mainSchema.par03AlphaRegionId), + backRegion(mainSchema), + ) + + private val alphaNodeBuilder = Par03AlphaNodeBuilder( + nodeFactory = object : Par03AlphaNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = TestFlowNode( + initialTarget = Target.par03Alpha.par03AlphaScreen, + transitions = listOf(tr("goToScreen2", Target.par03Alpha.par03AlphaScreen2)), + ) + override fun createPar03AlphaScreenNode(): ScreenNode = TestScreenNode() + override fun createPar03AlphaScreen2Node(): ScreenNode = TestScreenNode() + }, + schema = Parallel03AlphaSchema(), + ) + private val betaNodeBuilder = Par03BetaNodeBuilder( + nodeFactory = object : Par03BetaNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = + TestFlowNode(initialTarget = Target.par03Beta.par03BetaScreen, onEntryImpl = { betaRootEntries++ }) + override fun createPar03BetaScreenNode(): ScreenNode = TestScreenNode() + }, + schema = Parallel03BetaSchema(), + ) + private val mainNodeBuilder = Par03MainNodeBuilder( + nodeFactory = object : Par03MainNodeBuilder.Factory { + override fun createRootNode(): ParallelFlowNode = main + override fun createPar03AlphaNodeBuilder(): NodeBuilder = alphaNodeBuilder + override fun createPar03BetaNodeBuilder(): NodeBuilder = betaNodeBuilder + }, + schema = mainSchema, + ) + + private val mainPath = Target.par03App.par03Main.path.let { Path(appSchema.rootSegment).append(it) } + + val service: NavigationService = NavigationService( + nodeBuilder = Par03AppNodeBuilder( + nodeFactory = object : Par03AppNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = object : FlowNode { + override val initial: Target = Target.par03App.par03Main + override val dismissResult = Unit + override fun transition(event: Event): FlowTransition = when ((event as? TestEvent)?.name) { + "PAGE" -> NavigateTo(Target.par03App.par03Page) + + "MAIN" -> NavigateTo(Target.par03App.par03Main) + + "deeplinkAlpha" -> NavigateTo( + AbsoluteTarget( + mainSchema.par03AlphaRegionId.resolveAbsolute(mainPath).path + .append(Target.par03Alpha.par03AlphaScreen2.path), + ), + ) + + "historyAlpha" -> NavigateTo(HistoryTarget(mainSchema.par03AlphaRegionId.resolveAbsolute(mainPath).path)) + + "deeplinkBeta" -> NavigateTo( + AbsoluteTarget( + mainSchema.par03BetaRegionId.resolveAbsolute(mainPath).path + .append(Target.par03Beta.par03BetaScreen.path), + ), + ) + + else -> Ignore + } + } + override fun createPar03MainNodeBuilder(): NodeBuilder = mainNodeBuilder + override fun createPar03PageNode(): ScreenNode = TestScreenNode() + }, + schema = appSchema, + ), + onFinishRequest = { Ignore }, + ).also { service -> + service.addNodeExtensionPoint(NodeHooksSupportExtensionPoint()) + service.addTransitionListener { states.add(it) } + } + + fun regionLeaves(): Map = states.last().leaves() +} diff --git a/way/src/commonTest/kotlin/ru/kode/way/NavigationServiceTest.kt b/way/src/commonTest/kotlin/ru/kode/way/NavigationServiceTest.kt index 13feade..0772018 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/NavigationServiceTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/NavigationServiceTest.kt @@ -1318,12 +1318,8 @@ class NavigationServiceTest : } } - // NOTE: For now this is an expected behavior: flow nodes can be built several times prior to being used - // in transitions (for example during initial node resolution). Users are expected to use onEntry/onExit instead of - // node constructors to initialize node-tree dependent data. - // NOTE: In case the above restriction will be lifted and node construction will be guaranteed to happen once, - // this test should be adjusted to test for exactly this case and this comment should be removed. - should("call child flow builder twice ") { + // The node which is asked about its initial target while a transition is resolved is the one which is entered. + should("build a child flow node once") { var createChildNodeCallCount = 0 val sut = NavigationService( ru.kode.way.nav09.AppNodeBuilder( @@ -1355,8 +1351,7 @@ class NavigationServiceTest : awaitItem().apply { active shouldBe "app.page1.permissions.intro" } - // See NOTEs above - createChildNodeCallCount shouldBe 2 + createChildNodeCallCount shouldBe 1 } } diff --git a/way/src/commonTest/kotlin/ru/kode/way/ParallelNodeTest.kt b/way/src/commonTest/kotlin/ru/kode/way/ParallelNodeTest.kt index 0695487..195673d 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/ParallelNodeTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/ParallelNodeTest.kt @@ -48,6 +48,7 @@ import ru.kode.way.acmetabs.ParallelTestAcmeTabsSchema import ru.kode.way.acmetabs.acmeAuthFlow import ru.kode.way.acmetabs.acmeExploreTab import ru.kode.way.acmetabs.acmeHomeTab +import ru.kode.way.acmetabs.acmeMainFlow import ru.kode.way.nullroot.NullAppRootNodeBuilder import ru.kode.way.nullroot.ParallelTestNullrootSchema import ru.kode.way.nullroot.main.NullMainImportNodeBuilder @@ -2636,6 +2637,213 @@ class ParallelNodeTest : ShouldSpec() { } } + should("start only the initial regions of a parallel declared inside of a region of the root schema") { + val schema = ParallelTestAcmeTabsSchema() + val states = mutableListOf() + var tabsNodesCreated = 0 + val sut = buildAcmeTabsService( + createTabsFlowNode = { + tabsNodesCreated++ + LazyParallelNode(setOf(schema.acmeHomeTabRegionId), mapOf("startExplore" to schema.acmeExploreTabRegionId)) + }, + ) + sut.addTransitionListener { states.add(it) } + sut.start() + + states.last().regions.keys.map { it.path.lastSegment().name } + .shouldContainOnly("acmeMainFlow", "acmeAuthFlow", "acmeHomeTab") + // the node which is asked about its initial regions is the one which lives in the region + tabsNodesCreated shouldBe 1 + + sut.send(TestEvent("startExplore")) + states.last().acmeActiveLeaf("acmeExploreTab") shouldBe "acmeExploreScreen" + } + + should( + "start the regions of a parallel declared inside of a region when it is entered, drop them when it is left", + ) { + val states = mutableListOf() + var tabsNodesCreated = 0 + val sut = buildAcmeTabsService( + createTabsFlowNode = { + tabsNodesCreated++ + TestParallelNode() + }, + mainInitialTarget = Target.acmeMainFlow.acmeIntroScreen, + mainTransitions = listOf( + TestFlowTransitionSpec( + eventMatcher = { it is TestEvent && it.name == "openTabs" }, + transition = NavigateTo(Target.acmeExploreTab.acmeExploreDetailScreen), + ), + TestFlowTransitionSpec( + eventMatcher = { it is TestEvent && it.name == "openIntro" }, + transition = NavigateTo(Target.acmeMainFlow.acmeIntroScreen), + ), + ), + ) + sut.addTransitionListener { states.add(it) } + sut.start() + + states.last().regions.keys.map { it.path.lastSegment().name }.shouldContainOnly("acmeMainFlow", "acmeAuthFlow") + tabsNodesCreated shouldBe 0 + + sut.send(TestEvent("openTabs")) + states.last().regions.keys.map { it.path.lastSegment().name } + .shouldContainOnly("acmeMainFlow", "acmeAuthFlow", "acmeHomeTab", "acmeExploreTab") + states.last().acmeActiveLeaf("acmeExploreTab") shouldBe "acmeExploreDetailScreen" + states.last().acmeActiveLeaf("acmeHomeTab") shouldBe "acmeHomeScreen" + tabsNodesCreated shouldBe 1 + + sut.send(TestEvent("openIntro")) + states.last().regions.keys.map { it.path.lastSegment().name }.shouldContainOnly("acmeMainFlow", "acmeAuthFlow") + + sut.send(TestEvent("openTabs")) + tabsNodesCreated shouldBe 2 + } + + should("enter a parallel declared inside of a region before its regions and exit it after them") { + val log = mutableListOf() + val sut = buildAcmeTabsService( + createTabsFlowNode = { + TestParallelNode(onEntryImpl = { log += "enter tabs" }, onExitImpl = { log += "exit tabs" }) + }, + mainInitialTarget = Target.acmeMainFlow.acmeIntroScreen, + mainTransitions = listOf( + tr("openTabs", Target.acmeHomeTab.acmeHomeScreen), + tr("openIntro", Target.acmeMainFlow.acmeIntroScreen), + ), + lifecycleLog = log, + ) + sut.start() + log.shouldBeEmpty() + + sut.send(TestEvent("openTabs")) + log.first() shouldBe "enter tabs" + log.shouldContainExactlyInAnyOrder("enter tabs", "enter home", "enter explore") + + log.clear() + sut.send(TestEvent("openIntro")) + log.last() shouldBe "exit tabs" + log.shouldContainExactlyInAnyOrder("exit home", "exit explore", "exit tabs") + } + + should("keep a parallel declared inside of a region and its regions when an onExit throws on leaving it") { + val log = mutableListOf() + var failures = 1 + val sut = buildAcmeTabsService( + createTabsFlowNode = { + TestParallelNode( + onEntryImpl = { log += "enter tabs" }, + onExitImpl = { + log += "exit tabs" + if (failures-- > 0) error("exit failed") + }, + ) + }, + mainInitialTarget = Target.acmeMainFlow.acmeIntroScreen, + mainTransitions = listOf( + tr("openTabs", Target.acmeHomeTab.acmeHomeScreen), + tr("openIntro", Target.acmeMainFlow.acmeIntroScreen), + ), + lifecycleLog = log, + ) + sut.start() + sut.send(TestEvent("openTabs")) + + log.clear() + shouldThrow { sut.send(TestEvent("openIntro")) } + // every node which was exited is entered back + log.filter { it.startsWith("exit") }.shouldContainExactlyInAnyOrder("exit home", "exit explore", "exit tabs") + log.filter { it.startsWith("enter") }.shouldContainExactlyInAnyOrder("enter home", "enter explore", "enter tabs") + + // the transition was rolled back: the parallel is still there and is left as usual + log.clear() + sut.send(TestEvent("openIntro")) + log.shouldContainExactlyInAnyOrder("exit home", "exit explore", "exit tabs") + log.last() shouldBe "exit tabs" + } + + should("keep the node of a parallel entered at start when a later event targets a node inside of it") { + val log = mutableListOf() + val sut = buildAcmeTabsService( + homeTabTransitions = listOf(tr("topUp", Target.acmeHomeTab.acmeTopUpScreen)), + createTabsFlowNode = { + TestParallelNode(onEntryImpl = { log += "enter tabs" }, onExitImpl = { log += "exit tabs" }) + }, + mainTransitions = listOf(tr("openIntro", Target.acmeMainFlow.acmeIntroScreen)), + lifecycleLog = log, + ) + sut.start() + sut.send(TestEvent("topUp")) + log.shouldContainExactlyInAnyOrder("enter tabs", "enter home", "enter explore") + + log.clear() + sut.send(TestEvent("openIntro")) + log.shouldContainExactlyInAnyOrder("exit home", "exit explore", "exit tabs") + log.last() shouldBe "exit tabs" + } + + should("restore the regions of a left parallel declared inside of a region by a HistoryTarget") { + val states = mutableListOf() + val tabsPath = ParallelTestAcmeTabsSchema().acmeHomeTabRegionId.path.dropLast(1) + val sut = buildAcmeTabsService( + mainInitialTarget = Target.acmeMainFlow.acmeIntroScreen, + mainTransitions = listOf( + tr("openTabs", Target.acmeExploreTab.acmeExploreDetailScreen), + tr("openIntro", Target.acmeMainFlow.acmeIntroScreen), + tr("deep", HistoryTarget(tabsPath, deep = true)), + tr("shallow", HistoryTarget(tabsPath, deep = false)), + ), + ) + sut.addTransitionListener { states.add(it) } + sut.start() + + // no history yet: the same as a target to the parallel itself + sut.send(TestEvent("deep")) + states.last().acmeActiveLeaf("acmeHomeTab") shouldBe "acmeHomeScreen" + states.last().acmeActiveLeaf("acmeExploreTab") shouldBe "acmeExploreScreen" + + sut.send(TestEvent("openTabs")) + sut.send(TestEvent("openIntro")) + states.last().regions.keys.map { it.path.lastSegment().name }.shouldContainOnly("acmeMainFlow", "acmeAuthFlow") + + sut.send(TestEvent("deep")) + states.last().acmeActiveLeaf("acmeHomeTab") shouldBe "acmeHomeScreen" + states.last().acmeActiveLeaf("acmeExploreTab") shouldBe "acmeExploreDetailScreen" + + sut.send(TestEvent("openIntro")) + sut.send(TestEvent("shallow")) + states.last().regions.keys.map { it.path.lastSegment().name } + .shouldContainOnly("acmeMainFlow", "acmeAuthFlow", "acmeHomeTab", "acmeExploreTab") + } + + should("give the start payload to a region of the root parallel which starts later") { + val schema = ParallelTestParamswSchema( + paramMainImportSchema = ParallelTestParamswMainSchema( + paramHomeImportSchema = ParallelTestParamswHomeSchema( + paramTabASchema = ParallelTestParamswTabASchema(), + paramTabBSchema = ParallelTestParamswTabBSchema(), + ), + ), + paramSheetImportSchema = ParallelTestParamswSheetSchema(), + ) + val mainReceived = mutableListOf() + val sut = buildParamswService( + createParamAppRoot = { + LazyParallelNode(setOf(schema.paramSheetImportRegionId), mapOf("startMain" to schema.paramMainImportRegionId)) + }, + createParamMainImport = { deeplink -> + mainReceived.add(deeplink) + TestFlowNode(initialTarget = Target.paramMainImport.paramMainScreen) + }, + ) + sut.start("acme://deeplink") + mainReceived.shouldBeEmpty() + + sut.send(TestEvent("startMain")) + mainReceived.distinct() shouldBe listOf("acme://deeplink") + } + // ── A1. Parallel-root detection (NavigationService.kt:169-196) ──────────────────────────────── // Regression — a real-world shape (`appFlow(parallel) → mainFlow → homeFlow(parallel)`) requires // the parallel-root init branch to fire correctly even when a parallel-rooted schema is mounted @@ -3885,16 +4093,13 @@ class ParallelNodeTest : ShouldSpec() { onFinishCalled shouldBe true } - should("flow-nested parallel Finish on the dispatchBackThroughParallel re-consultation still finishes") { - // Hardening for the re-consultation path: on Back a flow-nested parallel's transition(Back) is - // consulted twice — once in the region fold, once inside dispatchBackThroughParallel. If the - // first returns Ignore (bubbles to maybeResolveBackEvent) and the re-consultation returns Finish, - // dispatchBackThroughParallel's else branch must route it through resolveTransitionInRegion (the - // schema-based finish), NOT drop it via a null finishTransitionBuilder. Drives exactly that - // sequence and asserts the root flow's onFinishRequest fires. + should("flow-nested parallel is asked about Back once") { + // The parallel answers Ignore in the region fold; dispatchBackThroughParallel reuses this answer and does + // not ask the node again, so its second answer stays in the queue. + val backTransitions = mutableListOf>(Ignore, Finish(Unit)) var onFinishCalled = false val sut = buildPar01Service( - mainBackTransitionQueue = mutableListOf(Ignore, Finish(Unit)), + mainBackTransitionQueue = backTransitions, onFinishRequest = { onFinishCalled = true Ignore @@ -3905,7 +4110,8 @@ class ParallelNodeTest : ShouldSpec() { sut.send(Event.Back) cancelAndIgnoreRemainingEvents() } - onFinishCalled shouldBe true + backTransitions.size shouldBe 1 + onFinishCalled shouldBe false } should("transition(Event.Back)=Ignore routes Back into the deepest active sub-region") { @@ -4970,12 +5176,17 @@ private fun buildAcmeTabsService( homeTabTransitions: List = emptyList(), exploreTabTransitions: List = emptyList(), createTabsFlowNode: () -> ParallelFlowNode = { TestParallelNode() }, + mainInitialTarget: Target = Target.acmeHomeTab.acmeHomeScreen, + mainTransitions: List = emptyList(), + lifecycleLog: MutableList = mutableListOf(), ): NavigationService { val homeTabNodeBuilder = AcmeHomeTabNodeBuilder( nodeFactory = object : AcmeHomeTabNodeBuilder.Factory { override fun createRootNode(): FlowNode<*> = TestFlowNode( initialTarget = Target.acmeHomeTab.acmeHomeScreen, transitions = homeTabTransitions, + onEntryImpl = { lifecycleLog += "enter home" }, + onExitImpl = { lifecycleLog += "exit home" }, ) override fun createAcmeHomeScreenNode(): ScreenNode = TestScreenNode() override fun createAcmeTopUpScreenNode(): ScreenNode = TestScreenNode() @@ -4987,6 +5198,8 @@ private fun buildAcmeTabsService( override fun createRootNode(): FlowNode<*> = TestFlowNode( initialTarget = Target.acmeExploreTab.acmeExploreScreen, transitions = exploreTabTransitions, + onEntryImpl = { lifecycleLog += "enter explore" }, + onExitImpl = { lifecycleLog += "exit explore" }, ) override fun createAcmeExploreScreenNode(): ScreenNode = TestScreenNode() override fun createAcmeExploreDetailScreenNode(): ScreenNode = TestScreenNode() @@ -5007,7 +5220,9 @@ private fun buildAcmeTabsService( // when entering the parallel on the way to that screen. val mainFlowNodeBuilder = AcmeMainFlowNodeBuilder( nodeFactory = object : AcmeMainFlowNodeBuilder.Factory { - override fun createRootNode(): FlowNode<*> = TestFlowNode(initialTarget = Target.acmeHomeTab.acmeHomeScreen) + override fun createRootNode(): FlowNode<*> = + TestFlowNode(initialTarget = mainInitialTarget, transitions = mainTransitions) + override fun createAcmeIntroScreenNode(): ScreenNode = TestScreenNode() override fun createAcmeTabsFlowNodeBuilder(): NodeBuilder = tabsFlowNodeBuilder }, schema = AcmeMainFlowSchema(), diff --git a/way/src/commonTest/kotlin/ru/kode/way/PathTest.kt b/way/src/commonTest/kotlin/ru/kode/way/PathTest.kt index 3f5d05c..c784ef7 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/PathTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/PathTest.kt @@ -31,6 +31,12 @@ class PathTest : ShouldSpec() { } } + should("end with a target of its last nodes only") { + val path = Path("app", "home", "profile") + path.endsWith(ScreenTarget(Path("home", "profile"))).shouldBeTrue() + path.endsWith(FlowTarget(Path("home"))).shouldBeFalse() + } + should("ends with itself") { checkAll(Arb.path()) { path: Path -> path.endsWith(path).shouldBeTrue() diff --git a/way/src/commonTest/kotlin/ru/kode/way/RegionIdResolveAbsoluteTest.kt b/way/src/commonTest/kotlin/ru/kode/way/RegionIdResolveAbsoluteTest.kt index 7c90170..c759733 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/RegionIdResolveAbsoluteTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/RegionIdResolveAbsoluteTest.kt @@ -23,6 +23,14 @@ class RegionIdResolveAbsoluteTest : ShouldSpec() { regionId.resolveAbsolute(parentPath) shouldBe RegionId(Path("appFlow", "mainFlow", "homeFlow", "exploreFlow")) } + should("resolve a regionId of a parallel which is declared deeper in its schema") { + // homeFlow is a schema mounted as "home"; its region tabA belongs to the parallel tabs inside of its flow main + val regionId = RegionId(Path("homeFlow", "main", "tabs", "tabA")) + val absolute = RegionId(Path("appFlow", "home", "main", "tabs", "tabA")) + regionId.resolveAbsolute(Path("appFlow", "home", "main", "tabs")) shouldBe absolute + regionId.resolveAbsolute(Path("appFlow", "home")) shouldBe absolute + } + should("resolve a length-1 schema-relative regionId to parentPath itself") { val parentPath = Path("appFlow", "mainFlow", "homeFlow") // A length-1 relative id (e.g. an imported non-parallel schema) has no tail to append. diff --git a/way/src/commonTest/kotlin/ru/kode/way/SchemaFanInTest.kt b/way/src/commonTest/kotlin/ru/kode/way/SchemaFanInTest.kt index 1fd9602..45e0120 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/SchemaFanInTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/SchemaFanInTest.kt @@ -1,6 +1,7 @@ package ru.kode.way import app.cash.turbine.test +import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe import ru.kode.way.nav16.AppChildFinishRequest @@ -13,6 +14,183 @@ import ru.kode.way.nav16.perm class SchemaFanInTest : ShouldSpec({ + should("keep the node builder of a parameterized schema when a transition which re-targets it fails") { + val failingReasons = mutableSetOf("r-2") + val sut = NavigationService( + AppNodeBuilder( + object : AppNodeBuilder.Factory { + override fun createRootNode() = TestFlowNode( + initialTarget = Target.app.a(aId = 1), + transitions = listOf( + tr("First", Target.app.permViaA(reason = "r-1")), + tr("Second", Target.app.permViaA(reason = "r-2")), + ), + ) + override fun createANode(aId: Int) = TestScreenNode(payload = aId) + override fun createBNode(bId: String) = TestScreenNode(payload = bId) + override fun createPermNodeBuilder(reason: String): NodeBuilder = PermNodeBuilder( + object : PermNodeBuilder.Factory { + override fun createRootNode(reason: String): FlowNode<*> = TestFlowNodeWithResult( + initialTarget = Target.perm.permIntro, + dismissResult = "", + transitions = listOf(tr("Details", Target.perm.permDetails)), + onEntryImpl = { if (failingReasons.remove(reason)) error("entry of $reason failed") }, + ) + override fun createPermIntroNode() = TestScreenNode(payload = reason) + override fun createPermDetailsNode() = TestScreenNode(payload = reason) + }, + NavService16PermSchema(), + ) + }, + NavService16Schema(NavService16PermSchema()), + ), + onFinishRequest = { _: Unit -> Stay }, + ) + + sut.collectTransitions().test { + awaitItem() + sut.send(TestEvent("First")) + awaitItem().active shouldBe "app.a.perm.permIntro" + + shouldThrow { sut.send(TestEvent("Second")) } + + // the schema is alive with its first argument still, so is its node builder + sut.send(TestEvent("Details")) + (awaitItem().aliveNodes["app.a.perm.permDetails"] as TestScreenNode).payload shouldBe "r-1" + } + } + + should("drop the node builder of a parameterized schema which a failed transition has created") { + val failingReasons = mutableSetOf("r-2") + val sut = NavigationService( + AppNodeBuilder( + object : AppNodeBuilder.Factory { + override fun createRootNode() = TestFlowNode( + initialTarget = Target.app.a(aId = 1), + transitions = listOf( + tr("First", Target.app.permViaA(reason = "r-1")), + tr("Second", Target.app.permViaA(reason = "r-2")), + ), + ) + override fun createANode(aId: Int) = TestScreenNode(payload = aId) + override fun createBNode(bId: String) = TestScreenNode(payload = bId) + override fun createPermNodeBuilder(reason: String): NodeBuilder = PermNodeBuilder( + object : PermNodeBuilder.Factory { + override fun createRootNode(reason: String): FlowNode<*> = TestFlowNodeWithResult( + initialTarget = Target.perm.permIntro, + dismissResult = "", + transitions = listOf(tr("Details", Target.perm.permDetails)), + onEntryImpl = { if (failingReasons.remove(reason)) error("entry of $reason failed") }, + ) + override fun createPermIntroNode() = TestScreenNode(payload = reason) + override fun createPermDetailsNode() = TestScreenNode(payload = reason) + }, + NavService16PermSchema(), + ) + }, + NavService16Schema(NavService16PermSchema()), + ), + onFinishRequest = { _: Unit -> Stay }, + ) + + sut.collectTransitions().test { + awaitItem() + shouldThrow { sut.send(TestEvent("Second")) } + + sut.send(TestEvent("First")) + (awaitItem().aliveNodes["app.a.perm.permIntro"] as TestScreenNode).payload shouldBe "r-1" + } + } + + should("keep the node builder which a transition has created when a hook throws after that transition") { + var builders = 0 + val sut = NavigationService( + AppNodeBuilder( + object : AppNodeBuilder.Factory { + override fun createRootNode() = TestFlowNode( + initialTarget = Target.app.a(aId = 1), + transitions = listOf(tr("First", Target.app.permViaA(reason = "r-1"))), + ) + override fun createANode(aId: Int) = TestScreenNode(payload = aId) + override fun createBNode(bId: String) = TestScreenNode(payload = bId) + override fun createPermNodeBuilder(reason: String): NodeBuilder = PermNodeBuilder( + object : PermNodeBuilder.Factory { + override fun createRootNode(reason: String): FlowNode<*> = TestFlowNodeWithResult( + initialTarget = Target.perm.permIntro, + dismissResult = "", + transitions = listOf(tr("Details", Target.perm.permDetails)), + ) + override fun createPermIntroNode() = TestScreenNode() + override fun createPermDetailsNode() = TestScreenNode() + }, + NavService16PermSchema(), + ).also { builders++ } + }, + NavService16Schema(NavService16PermSchema()), + ), + onFinishRequest = { _: Unit -> Stay }, + ) + sut.addServiceExtensionPoint(object : ServiceExtensionPoint { + override fun onPostTransition(service: NavigationService, event: Event, state: NavigationState) { + if (event == TestEvent("First")) error("hook failed") + } + }) + sut.start() + + // the transition is committed, the nodes of the schema are alive: they keep the builder which has made them + shouldThrow { sut.send(TestEvent("First")) } + sut.send(TestEvent("Details")) + builders shouldBe 1 + } + + should("build the initial node of a re-targeted parameterized schema with its new argument") { + val sut = NavigationService( + AppNodeBuilder( + object : AppNodeBuilder.Factory { + override fun createRootNode() = TestFlowNode( + initialTarget = Target.app.a(aId = 1), + transitions = listOf( + tr("First", Target.app.permViaA(reason = "r-1")), + tr("Second", Target.app.permViaA(reason = "r-2")), + ), + ) + override fun createANode(aId: Int) = TestScreenNode(payload = aId) + override fun createBNode(bId: String) = TestScreenNode(payload = bId) + override fun createPermNodeBuilder(reason: String): NodeBuilder = PermNodeBuilder( + object : PermNodeBuilder.Factory { + override fun createRootNode(reason: String): FlowNode<*> = TestFlowNodeWithResult( + initialTarget = Target.perm.permIntro, + dismissResult = "", + transitions = listOf(tr("Details", Target.perm.permDetails)), + ) + override fun createPermIntroNode() = TestScreenNode(payload = reason) + override fun createPermDetailsNode() = TestScreenNode() + }, + NavService16PermSchema(), + ) + }, + NavService16Schema(NavService16PermSchema()), + ), + onFinishRequest = { _: Unit -> Stay }, + ) + + sut.collectTransitions().test { + awaitItem() + sut.send(TestEvent("First")) + (awaitItem().aliveNodes["app.a.perm.permIntro"] as TestScreenNode).payload shouldBe "r-1" + + // the initial node is not alive when the schema is re-targeted + sut.send(TestEvent("Details")) + awaitItem().active shouldBe "app.a.perm.permDetails" + + sut.send(TestEvent("Second")) + awaitItem().apply { + active shouldBe "app.a.perm.permIntro" + (aliveNodes["app.a.perm.permIntro"] as TestScreenNode).payload shouldBe "r-2" + } + } + } + should("enter an imported schema through each of its parents with that path's payloads and finish to it") { val permReasons = mutableMapOf() val finishedIn = mutableListOf() @@ -23,6 +201,7 @@ class SchemaFanInTest : transitions = listOf(tr("Done", Finish("done-$reason"))), ).also { permReasons[it] = reason } override fun createPermIntroNode() = TestScreenNode() + override fun createPermDetailsNode() = TestScreenNode() } fun parentScreen(id: String, payload: Any, back: Target) = TestScreenNode( payload = payload, diff --git a/way/src/commonTest/kotlin/ru/kode/way/ScxmlConformanceTest.kt b/way/src/commonTest/kotlin/ru/kode/way/ScxmlConformanceTest.kt index 9d7b12e..7bfc07a 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/ScxmlConformanceTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/ScxmlConformanceTest.kt @@ -393,6 +393,7 @@ private fun buildAcmeConformanceService( val mainFlowNodeBuilder = AcmeMainFlowNodeBuilder( nodeFactory = object : AcmeMainFlowNodeBuilder.Factory { override fun createRootNode(): FlowNode<*> = TestFlowNode(initialTarget = Target.acmeHomeTab.acmeHomeScreen) + override fun createAcmeIntroScreenNode(): ScreenNode = TestScreenNode() override fun createAcmeTabsFlowNodeBuilder(): NodeBuilder = tabsFlowNodeBuilder }, schema = AcmeMainFlowSchema(), diff --git a/way/src/commonTest/way/nav-service16-perm.dot b/way/src/commonTest/way/nav-service16-perm.dot index edb5cd7..836c3af 100644 --- a/way/src/commonTest/way/nav-service16-perm.dot +++ b/way/src/commonTest/way/nav-service16-perm.dot @@ -4,4 +4,5 @@ digraph NavService16Perm { perm [type = flow, parameterName = reason, parameterType = "kotlin.String", resultType = "kotlin.String"] perm -> permIntro + perm -> permDetails } diff --git a/way/src/commonTest/way/parallel-test-acme-tabs.dot b/way/src/commonTest/way/parallel-test-acme-tabs.dot index fdc0384..416e05e 100644 --- a/way/src/commonTest/way/parallel-test-acme-tabs.dot +++ b/way/src/commonTest/way/parallel-test-acme-tabs.dot @@ -27,10 +27,13 @@ digraph ParallelTestAcmeTabs { // is a concrete Explore destination the Back-side "switch focus + navigate" step lands on. acmeTopUpScreen [type = "screen"] acmeExploreDetailScreen [type = "screen"] + // a screen of acmeMainFlow outside of the nested parallel: while it is active, the tabs do not exist + acmeIntroScreen [type = "screen"] acmeAppFlow -> acmeMainFlow acmeAppFlow -> acmeAuthFlow acmeMainFlow -> acmeTabsFlow + acmeMainFlow -> acmeIntroScreen acmeTabsFlow -> acmeHomeTab acmeTabsFlow -> acmeExploreTab acmeHomeTab -> acmeHomeScreen diff --git a/way/src/commonTest/way/parallel-test-double-nested.dot b/way/src/commonTest/way/parallel-test-double-nested.dot new file mode 100644 index 0000000..a54c061 --- /dev/null +++ b/way/src/commonTest/way/parallel-test-double-nested.dot @@ -0,0 +1,50 @@ +digraph ParallelTestDoubleNested { + package = "ru.kode.way.doublenested" + + // A parallel declared inside of a region of another parallel, both of them local: + // + // dnApp [parallelFlow] <-- schema root + // +-- dnMain [flow] -> dnIntroScreen + // | \-- dnWrap [flow] -> dnWrapScreen + // | \-- dnOuter [parallelFlow] + // | +-- dnLeft [flow] -> dnLeftScreen + // | | \-- dnInner [parallelFlow] + // | | +-- dnA [flow] -> dnAScreen + // | | \-- dnB [flow] -> dnBScreen + // | \-- dnRight [flow] -> dnRightScreen + // \-- dnSide [flow] -> dnSideScreen + dnApp [type = "parallelFlow"] + dnMain [type = "flow"] + dnSide [type = "flow"] + dnWrap [type = "flow"] + dnOuter [type = "parallelFlow"] + dnLeft [type = "flow"] + dnRight [type = "flow"] + dnInner [type = "parallelFlow"] + dnA [type = "flow"] + dnB [type = "flow"] + dnIntroScreen [type = "screen"] + dnSideScreen [type = "screen"] + dnWrapScreen [type = "screen"] + dnLeftScreen [type = "screen"] + dnRightScreen [type = "screen"] + dnAScreen [type = "screen"] + dnBScreen [type = "screen"] + + dnApp -> dnMain + dnApp -> dnSide + dnMain -> dnIntroScreen + dnMain -> dnWrap + dnWrap -> dnWrapScreen + dnWrap -> dnOuter + dnOuter -> dnLeft + dnOuter -> dnRight + dnLeft -> dnLeftScreen + dnLeft -> dnInner + dnRight -> dnRightScreen + dnInner -> dnA + dnInner -> dnB + dnA -> dnAScreen + dnB -> dnBScreen + dnSide -> dnSideScreen +} From f8d5779900e979277c8c34f48a7238f1d184cffd Mon Sep 17 00:00:00 2001 From: rinekri Date: Wed, 7 Oct 2026 14:37:00 +0100 Subject: [PATCH 2/3] Cover queued events, nested builder cache and exit animation in rollback and retention tests --- .../ru/kode/way/compose/NodeRetentionTest.kt | 27 ++++++++ .../kotlin/ru/kode/way/EventDroppingTest.kt | 36 +++++++++++ .../kotlin/ru/kode/way/SchemaFanInTest.kt | 62 +++++++++++++++++++ 3 files changed, 125 insertions(+) diff --git a/way-compose/src/test/kotlin/ru/kode/way/compose/NodeRetentionTest.kt b/way-compose/src/test/kotlin/ru/kode/way/compose/NodeRetentionTest.kt index e778216..12916b1 100644 --- a/way-compose/src/test/kotlin/ru/kode/way/compose/NodeRetentionTest.kt +++ b/way-compose/src/test/kotlin/ru/kode/way/compose/NodeRetentionTest.kt @@ -2,6 +2,7 @@ package ru.kode.way.compose import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText import org.junit.Assert.assertNull import org.junit.Rule import org.junit.Test @@ -34,4 +35,30 @@ class NodeRetentionTest { } assertNull(exited.get()) } + + @Test + fun `node which was active when the host was composed is released after its exit animation ends`() { + val fixture = FlowFixture() + fixture.service.start() + fixture.service.send(TestEvent("D")) + rule.setContent { NodeHost(fixture.service) } + val exited = rule.runOnIdle { WeakReference(fixture.screen("details", "a")) } + + // "M" goes to another path: details stays composed until its exit animation ends + rule.mainClock.autoAdvance = false + rule.runOnIdle { fixture.service.send(TestEvent("M")) } + rule.mainClock.advanceTimeByFrame() + rule.onNodeWithText("details a 0").assertExists() + rule.mainClock.autoAdvance = true + rule.waitForIdle() + rule.onNodeWithText("details a 0").assertDoesNotExist() + fixture.screens.clear() + + for (attempt in 1..10) { + if (exited.get() == null) break + System.gc() + Thread.sleep(50) + } + assertNull(exited.get()) + } } diff --git a/way/src/commonTest/kotlin/ru/kode/way/EventDroppingTest.kt b/way/src/commonTest/kotlin/ru/kode/way/EventDroppingTest.kt index f01b8fb..764c180 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/EventDroppingTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/EventDroppingTest.kt @@ -413,6 +413,42 @@ class EventDroppingTest : recorder.dropped.last().second shouldBe DropReason.StaleSource(detailsPath!!) } + should("deliver the events which were queued before a transition is rolled back, once and in their order") { + val sut = createService(hideParameters = true) + val recorder = Recorder(sut) + // only the first entry of details sends "X": the one which is rolled back + var sendOnEntry = true + sut.addNodeExtensionPoint( + TestNodeExtensionPoint(postEntry = { _, path -> + if (sendOnEntry && path.toString() == "app.main.details") { + sendOnEntry = false + sut.send(TestEvent("X")) + } + }), + ) + sut.start() + recorder.clear() + // armed only for the dispatch of "M": addTransitionListener also calls the listener with the current state + var armed = false + sut.addTransitionListener { + if (armed) { + armed = false + sut.send(TestEvent("N")) + sut.send(TestEvent("D")) + sut.send(TestEvent("R")) + } + } + + armed = true + sut.send(TestEvent("M")) + + // "D" and "R" were queued behind "N" when it was rolled back: they stay, "X" which "N" has sent does not + recorder.dropped.single().first shouldBe TestEvent("N") + recorder.states.map { it.active } shouldBe listOf("app.main", "app.main.details", "app.main.details") + recorder.states.drop(1).map { (it.aliveNodes["app.main.details"] as TestScreenNode).payload } shouldBe + listOf("d1", "d9") + } + // sends "M" and enqueues "T" (dropped: details is not alive) and "D" while "M" is dispatched fun NavigationService.sendMainEnqueuingDropAndDetails() { // armed only for the dispatch of "M": addTransitionListener also calls the listener with the current state diff --git a/way/src/commonTest/kotlin/ru/kode/way/SchemaFanInTest.kt b/way/src/commonTest/kotlin/ru/kode/way/SchemaFanInTest.kt index 45e0120..e7ffe09 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/SchemaFanInTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/SchemaFanInTest.kt @@ -4,6 +4,15 @@ import app.cash.turbine.test import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe +import ru.kode.way.mc01.AppFlowNodeBuilder +import ru.kode.way.mc01.LoginFlowNodeBuilder +import ru.kode.way.mc01.MCAppFlowSchema +import ru.kode.way.mc01.MCLoginFlowSchema +import ru.kode.way.mc01.MCMainFlowSchema +import ru.kode.way.mc01.MainFlowNodeBuilder +import ru.kode.way.mc01.appFlow +import ru.kode.way.mc01.loginFlow +import ru.kode.way.mc01.mainFlow import ru.kode.way.nav16.AppChildFinishRequest import ru.kode.way.nav16.AppNodeBuilder import ru.kode.way.nav16.NavService16PermSchema @@ -102,6 +111,59 @@ class SchemaFanInTest : } } + should("drop the node builder of a parameterized schema two imported schemas below the root") { + val failingSections = mutableSetOf(2) + val sut = NavigationService( + AppFlowNodeBuilder( + object : AppFlowNodeBuilder.Factory { + override fun createRootNode() = TestFlowNode(initialTarget = Target.appFlow.mainFlow) + override fun createLoginFlowNodeBuilder(section: Int): NodeBuilder = error("not reached") + override fun createMainFlowNodeBuilder(): NodeBuilder = MainFlowNodeBuilder( + object : MainFlowNodeBuilder.Factory { + override fun createRootNode() = TestFlowNode( + initialTarget = Target.mainFlow.main(count = 1), + transitions = listOf( + tr("First", Target.mainFlow.loginFlow(section = 1)), + tr("Second", Target.mainFlow.loginFlow(section = 2)), + ), + ) + override fun createMainNode(count: Int) = TestScreenNode(payload = count) + override fun createLoginFlowNodeBuilder(section: Int): NodeBuilder = LoginFlowNodeBuilder( + object : LoginFlowNodeBuilder.Factory { + override fun createRootNode(section: Int): FlowNode<*> = TestFlowNode( + initialTarget = Target.loginFlow.credentials, + onEntryImpl = { if (failingSections.remove(section)) error("entry of $section failed") }, + ) + override fun createCredentialsNode() = TestScreenNode(payload = section) + override fun createOtpNode() = TestScreenNode(payload = section) + }, + MCLoginFlowSchema(), + ) + }, + MCMainFlowSchema(MCLoginFlowSchema()), + ) + }, + MCAppFlowSchema( + loginFlowSchema = MCLoginFlowSchema(), + mainFlowSchema = MCMainFlowSchema(MCLoginFlowSchema()), + ), + ), + onFinishRequest = { _: Unit -> Stay }, + ) + + sut.collectTransitions().test { + awaitItem().active shouldBe "appFlow.mainFlow.main" + // the node builder of mainFlow is kept, the one of loginFlow which it has created is not + shouldThrow { sut.send(TestEvent("Second")) } + + sut.send(TestEvent("First")) + awaitItem().apply { + active shouldBe "appFlow.mainFlow.main.loginFlow.credentials" + (aliveNodes["appFlow.mainFlow.main.loginFlow.credentials"] as TestScreenNode).payload shouldBe 1 + } + } + } + should("keep the node builder which a transition has created when a hook throws after that transition") { var builders = 0 val sut = NavigationService( From 9252ff640e3e4f6828de82e53779e8733940d5f0 Mon Sep 17 00:00:00 2001 From: rinekri Date: Wed, 7 Oct 2026 14:59:23 +0100 Subject: [PATCH 3/3] Dispose a parallel entered by NavigateTo once in cleanDispose --- CHANGELOG.md | 2 + .../kotlin/ru/kode/way/NavigationService.kt | 14 ++++- .../ru/kode/way/CrossRegionEventTest.kt | 57 +++++++++++++++++++ 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25f00f4..105b815 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,8 @@ ### Fixed +* `cleanDispose()` called `onDispose` twice on a parallel flow which was entered by `NavigateTo`: such a node + is alive both as a node of the calling region and as an intermediate parallel. * `RegionId.resolveAbsolute` returned a wrong path for a region of a parallel which is declared deeper than the root of an imported schema, so `DispatchBackTo` with a generated region id of such a parallel fell back to the deepest region. diff --git a/way/src/commonMain/kotlin/ru/kode/way/NavigationService.kt b/way/src/commonMain/kotlin/ru/kode/way/NavigationService.kt index 819a285..ce6d773 100644 --- a/way/src/commonMain/kotlin/ru/kode/way/NavigationService.kt +++ b/way/src/commonMain/kotlin/ru/kode/way/NavigationService.kt @@ -178,12 +178,20 @@ class NavigationService(nodeBuilder: NodeBuilder, private val onFinishR "listener or extension point). Call it after send() returns." } if (state.isInitialized()) { + // a parallel entered by NavigateTo is both a node of the calling region and an intermediate parallel + val disposed = mutableListOf() + val disposeOnce = { node: Node, path: Path -> + if (disposed.none { it === node }) { + disposed.add(node) + callOnDispose(node, path, state._nodeExtensionPoints) + } + } state._regions.entries .sortedByDescending { it.key.path.length } .forEach { (_, region) -> region.alive.reversed().forEach { path -> val node = region.nodes[path] ?: return@forEach - callOnDispose(node, path, state._nodeExtensionPoints) + disposeOnce(node, path) } } // Dispose intermediate parallel roots (parallel-rooted sub-region roots wrapping another @@ -192,7 +200,7 @@ class NavigationService(nodeBuilder: NodeBuilder, private val onFinishR state._intermediateParallels.entries .sortedByDescending { it.key.length } .forEach { (path, intermediate) -> - callOnDispose(intermediate.node, path, state._nodeExtensionPoints) + disposeOnce(intermediate.node, path) } // For a parallel-flow-ROOTED schema the root ParallelFlowNode lives in `state.rootNode` // (set at InitEvent), NOT in any region's `_nodes` map nor in `_intermediateParallels` @@ -203,7 +211,7 @@ class NavigationService(nodeBuilder: NodeBuilder, private val onFinishR val rootNode = state.rootNode val rootNodePath = state.rootNodePath if (rootNode != null && rootNodePath != null) { - callOnDispose(rootNode, rootNodePath, state._nodeExtensionPoints) + disposeOnce(rootNode, rootNodePath) } } dispose() diff --git a/way/src/commonTest/kotlin/ru/kode/way/CrossRegionEventTest.kt b/way/src/commonTest/kotlin/ru/kode/way/CrossRegionEventTest.kt index 011b052..ce89a21 100644 --- a/way/src/commonTest/kotlin/ru/kode/way/CrossRegionEventTest.kt +++ b/way/src/commonTest/kotlin/ru/kode/way/CrossRegionEventTest.kt @@ -184,6 +184,63 @@ class CrossRegionEventTest : parallelInvocations.shouldContainExactly(CrossRegionTestEvent("ping")) } + should("dispose a parallel entered by NavigateTo exactly once") { + var disposed = 0 + val go = TestEvent("go") + val mainParallel = TestParallelNode(onDisposeImpl = { disposed++ }) + val alphaNodeBuilder = Par03AlphaNodeBuilder( + nodeFactory = object : Par03AlphaNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = TestFlowNode(initialTarget = Target.par03Alpha.par03AlphaScreen) + override fun createPar03AlphaScreenNode(): ScreenNode = TestScreenNode() + override fun createPar03AlphaScreen2Node(): ScreenNode = TestScreenNode() + }, + schema = Parallel03AlphaSchema(), + ) + val betaNodeBuilder = Par03BetaNodeBuilder( + nodeFactory = object : Par03BetaNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = TestFlowNode(initialTarget = Target.par03Beta.par03BetaScreen) + override fun createPar03BetaScreenNode(): ScreenNode = TestScreenNode() + }, + schema = Parallel03BetaSchema(), + ) + val mainNodeBuilder = Par03MainNodeBuilder( + nodeFactory = object : Par03MainNodeBuilder.Factory { + override fun createRootNode(): ParallelFlowNode = mainParallel + override fun createPar03AlphaNodeBuilder(): NodeBuilder = alphaNodeBuilder + override fun createPar03BetaNodeBuilder(): NodeBuilder = betaNodeBuilder + }, + schema = Parallel03MainSchema(Parallel03AlphaSchema(), Parallel03BetaSchema()), + ) + val appNodeBuilder = Par03AppNodeBuilder( + nodeFactory = object : Par03AppNodeBuilder.Factory { + override fun createRootNode(): FlowNode<*> = object : FlowNode { + override val initial: Target = Target.par03App.par03Page + override val dismissResult: Unit = Unit + override fun transition(event: Event): FlowTransition = + if (event == go) NavigateTo(Target.par03App.par03Main) else Ignore + } + override fun createPar03MainNodeBuilder(): NodeBuilder = mainNodeBuilder + override fun createPar03PageNode(): ScreenNode = TestScreenNode() + }, + schema = Parallel03Schema( + par03MainSchema = Parallel03MainSchema( + par03AlphaSchema = Parallel03AlphaSchema(), + par03BetaSchema = Parallel03BetaSchema(), + ), + ), + ) + val sut = NavigationService( + nodeBuilder = appNodeBuilder, + onFinishRequest = { _: Unit -> Stay }, + ) + + sut.start() + sut.send(go) + sut.cleanDispose() + + disposed shouldBe 1 + } + // Production code: NavigationService.send (NavigationService.kt:423-449) calls // `transition(state, current)` FIRST (line 433) — which invokes every node's // `transition()` via `resolveTransition` — and only THEN notifies listeners