diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3c3c2d7..5feb4f0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -49,6 +49,7 @@ jobs:
:way-gradle-plugin:assemble \
:way-gradle-plugin:test \
:way:jvmTest \
+ :way-dsl:jvmTest \
:sample-compose:core:ui:assembleDebug \
:sample-compose:core:routing:assembleDebug \
:sample-compose:main:ui:assembleDebug \
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 4d355d2..43aef14 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -44,7 +44,8 @@ jobs:
run: |
./gradlew --no-daemon --stacktrace \
:way-gradle-plugin:test \
- :way:jvmTest
+ :way:jvmTest \
+ :way-dsl:jvmTest
- name: Validate tag matches version
run: |
@@ -97,7 +98,8 @@ jobs:
run: |
./gradlew --no-daemon --stacktrace \
:way:publishAndReleaseToMavenCentral \
- :way-compose:publishAndReleaseToMavenCentral
+ :way-compose:publishAndReleaseToMavenCentral \
+ :way-dsl:publishAndReleaseToMavenCentral
gh-release:
needs: publish-libraries
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a5b2c28..814bca0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,20 @@
# Changelog
+## Unreleased
+
+### Added
+
+* New artifact `ru.kode:way-dsl`: `ru.kode.way.dsl.Graph` declares a navigation graph in Kotlin, without `.dot`
+ files and code generation. It gives the runtime the same `Schema` and `NodeBuilder` as generated code, on all
+ platforms of `way`. See "Kotlin DSL" in the README.
+ * Typed parameters: `parameterizedFlow
`, `parameterizedParallel
` and `parameterizedScreen
` take a
+ payload of type `P` in their targets and pass it to their factories; an included graph has the parameter and the
+ result of its root. A nullable root is built with `null` when it is started without a payload.
+ * History nodes: `history(id)` and `deepHistory(id)`, with a `HistoryTarget`.
+ * Parallel flows anywhere a `.dot` file allows them, regions may be local flows and parallel flows.
+ * An included graph may have several parents in one region, `target(payload, via = parent)` picks the one to
+ enter it from.
+
## 0.12.0 - 2026-11-08
### Added
diff --git a/README.md b/README.md
index f0c1ea8..ed4601c 100644
--- a/README.md
+++ b/README.md
@@ -10,12 +10,15 @@ A graph is defined in `.dot` files, and the `ru.kode.way` Gradle plugin generate
- node builders
- child flow finish request events
+A graph can also be declared in Kotlin, without the plugin, see [Kotlin DSL](#kotlin-dsl-no-code-generation).
+
The runtime (`:way`) executes transitions, keeps navigation state, and supports extension points.
The Compose integration (`:way-compose`) renders active nodes with `NodeHost`.
## Modules
- `:way` - Kotlin Multiplatform runtime library: JVM, Android, iOS (`iosArm64`, `iosSimulatorArm64`, `iosX64`).
+- `:way-dsl` - Kotlin DSL for declaring graphs without code generation, same platforms as `:way`.
- `:way-compose` - Compose integration for `NavigationService`: Android (androidx Compose) and iOS (Compose Multiplatform).
- `:way-gradle-plugin` - Gradle plugin (`id("ru.kode.way")`) that generates code from `.dot` schemas.
- `:sample` - JVM sample.
@@ -42,6 +45,7 @@ Notes:
dependencies {
implementation("ru.kode:way:")
implementation("ru.kode:way-compose:") // optional, for Compose host
+ implementation("ru.kode:way-dsl:") // optional, for the Kotlin DSL
}
```
@@ -225,6 +229,127 @@ duplicated per flavor under `src/google/kotlin` / `src/huawei/kotlin` accordingl
`src/test/kotlin/.../AppFlowNodeTest.kt` is a shared test that only touches the symbols common to
both flavors, compiled once per flavor to prove both generate usable code.
+## Kotlin DSL (no code generation)
+
+`ru.kode.way.dsl.Graph` declares a graph in Kotlin instead of a `.dot` file. It ships as a separate artifact, needs no
+Gradle plugin and runs on every platform of `:way`:
+
+```kotlin
+dependencies {
+ implementation("ru.kode:way-dsl:") // brings ru.kode:way as an api dependency
+}
+```
+
+A `Graph` gives the runtime a `Schema` and a `NodeBuilder` as generated code does, so `NavigationService`, extension
+points and `:way-compose` work the same with both, and both kinds of graph can include each other's schemas.
+
+Nodes are properties of a subclass, edges are declared with `to` in its `init` block. The node without a parent is the
+root. A flow declares the type of its result, a parameterized node the type of its payload:
+
+```kotlin
+object LoginGraph : Graph("Login") {
+ val login = parameterizedFlow("login") // built with a String, Finish(result: Int)
+ val credentials = screen("credentials")
+ val otp = parameterizedScreen("otp")
+
+ init {
+ login to credentials to otp
+ }
+}
+
+object AppGraph : Graph("App") {
+ val app = flow("app")
+ val intro = screen("intro")
+ val login = include("login", LoginGraph.login) // a `type = schema` node, with the payload and result of the root
+
+ init {
+ app to intro
+ app to login
+ }
+}
+```
+
+Targets come from the nodes and take a payload of the declared type, as a generated target does:
+
+```kotlin
+NavigateTo(AppGraph.login.target("alice"))
+NavigateTo(LoginGraph.otp.target("+7 900 000-00-00"))
+```
+
+A flow with a nullable parameter (`parameterizedFlow`) takes `null` in its target; as the root of a
+graph it is built with `null` when it is started without a payload.
+
+A finished child flow is reported to its parent with a `ChildFlowFinishedEvent`, read its typed result with
+`childFlowResult`:
+
+```kotlin
+override fun transition(event: Event): FlowTransition {
+ val userId: Int = event.childFlowResult(AppGraph.login) ?: return Ignore
+ return NavigateTo(AppGraph.intro.target())
+}
+```
+
+`nodeBuilder` registers a factory for every node, a parameterized node gets its typed payload (`Unit` for a flow
+without a parameter). An included graph gets a factory of its own `NodeBuilder`, which makes it the place for a
+separate DI scope:
+
+```kotlin
+val service = NavigationService(
+ AppGraph.nodeBuilder {
+ flow(AppGraph.app) { AppFlowNode() }
+ screen(AppGraph.intro) { IntroScreen() }
+ include(AppGraph.login) { userName: String ->
+ LoginGraph.nodeBuilder {
+ flow(LoginGraph.login) { LoginFlowNode(it) }
+ screen(LoginGraph.credentials) { CredentialsScreen() }
+ screen(LoginGraph.otp) { phone -> OtpScreen(phone) }
+ }
+ }
+ },
+ onFinishRequest = { Finish(Unit) },
+)
+```
+
+`parallel(...)` (`parameterizedParallel(...)`) declares a parallel flow. It can be the root or sit under a
+flow, a screen or another parallel flow; its children (the regions) are flows, parallel flows or included graphs.
+
+`history(...)` and `deepHistory(...)` declare history nodes. A history node is a leaf under a flow, or under a parallel
+flow with a flow above it; its target re-enters the parent with the nodes which were active when it was left. History
+nodes need no factory:
+
+```kotlin
+object ShopGraph : Graph("Shop") {
+ val shop = flow("shop")
+ val cart = screen("cart")
+ val checkout = screen("checkout")
+ val lastStep = deepHistory("lastStep")
+
+ init {
+ shop to cart to checkout
+ shop to lastStep
+ }
+}
+
+NavigateTo(ShopGraph.lastStep.target()) // back to checkout if the shop was left from there
+```
+
+An included graph can have several parents, which are not parallel flows and are in the same region. Its target then
+needs the parent it is entered from, the counterpart of a generated `Via` target:
+
+```kotlin
+NavigateTo(SettingsGraph.permission.target("camera", via = SettingsGraph.profile))
+```
+
+The graph is checked when its `schema` or `nodeBuilder` is first used, with the rules of a `.dot` file: one root which
+is a flow or a parallel flow, no cycles, children under a root flow and under every parallel flow, several parents
+only for an included graph, no children under an included graph, history nodes in place, a factory for every node
+but a history one. Segments are `@`, so graph ids have to be unique among the graphs of a service.
+
+Not supported, unlike `.dot` files: screens as regions of a parallel flow (wrap them in a flow), full targets (with
+the payloads of ancestors, use `AbsoluteTarget`), typed region accessors (use `Schema.regionByName`) and a separate node
+builder per local flow (include a graph instead). The target of a node under a parallel flow starts at its closest
+flow, not at the flow above the parallel one as in generated code; both resolve to the same node.
+
## Runtime Model
Core runtime types in `:way`:
diff --git a/settings.gradle.kts b/settings.gradle.kts
index f546323..121b31d 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -19,6 +19,7 @@ rootProject.name = "way"
include(":way")
include(":way-compose")
+include(":way-dsl")
include(":sample")
include(":sample-compose:core:routing")
include(":sample-compose:core:ui")
diff --git a/way-dsl/build.gradle.kts b/way-dsl/build.gradle.kts
new file mode 100644
index 0000000..880ff51
--- /dev/null
+++ b/way-dsl/build.gradle.kts
@@ -0,0 +1,113 @@
+@Suppress("DSL_SCOPE_VIOLATION")
+plugins {
+ id(libs.plugins.kotlinMultiplatform.get().pluginId)
+ id(libs.plugins.androidKmpLibrary.get().pluginId)
+ // KSP before Kotest: the Kotest plugin needs it to run specs on native
+ id(libs.plugins.ksp.get().pluginId)
+ id(libs.plugins.kotest.get().pluginId)
+ alias(libs.plugins.way)
+ alias(libs.plugins.vanniktech.maven.publish)
+}
+
+group = providers.gradleProperty("pomGroupId").get()
+version = providers.gradleProperty("versionName").get()
+
+kotlin {
+ jvmToolchain(11)
+
+ jvm {
+ compilerOptions {
+ moduleName.set("way-dsl")
+ }
+ }
+
+ androidLibrary {
+ namespace = "ru.kode.way.dsl"
+ compileSdk = libs.versions.compileSdk.get().toInt()
+ minSdk = 21
+ }
+
+ iosArm64()
+ iosSimulatorArm64()
+ iosX64()
+
+ sourceSets {
+ val commonMain by getting {
+ dependencies {
+ api(project(":way"))
+ }
+ }
+ val commonTest by getting {
+ dependencies {
+ implementation(libs.bundles.koTestCommon)
+ }
+ }
+ val jvmTest by getting {
+ dependencies {
+ implementation(libs.bundles.koTestJvm)
+ }
+ }
+ }
+}
+
+mavenPublishing {
+ coordinates(artifactId = "way-dsl")
+
+ publishToMavenCentral()
+ signAllPublications()
+
+ pom {
+ val pomName: String by project
+ val pomDescription: String by project
+ val pomUrl: String by project
+ val pomScmUrl: String by project
+ val pomScmConnection: String by project
+ val pomScmDevConnection: String by project
+ val pomLicenseName: String by project
+ val pomLicenseUrl: String by project
+ val pomLicenseDist: String by project
+ val pomDeveloperId: String by project
+ val pomDeveloperName: String by project
+
+ name.set(pomName)
+ description.set(pomDescription)
+ url.set(pomUrl)
+
+ scm {
+ url.set(pomScmUrl)
+ connection.set(pomScmConnection)
+ developerConnection.set(pomScmDevConnection)
+ }
+
+ licenses {
+ license {
+ name.set(pomLicenseName)
+ url.set(pomLicenseUrl)
+ distribution.set(pomLicenseDist)
+ }
+ }
+
+ developers {
+ developer {
+ id.set(pomDeveloperId)
+ name.set(pomDeveloperName)
+ }
+ }
+ }
+}
+
+tasks.named("jvmTest") {
+ useJUnitPlatform()
+ testLogging {
+ showExceptions = true
+ showStandardStreams = true
+ events = setOf(
+ org.gradle.api.tasks.testing.logging.TestLogEvent.STANDARD_OUT,
+ org.gradle.api.tasks.testing.logging.TestLogEvent.STARTED,
+ org.gradle.api.tasks.testing.logging.TestLogEvent.SKIPPED,
+ org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED,
+ org.gradle.api.tasks.testing.logging.TestLogEvent.PASSED,
+ )
+ exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
+ }
+}
diff --git a/way-dsl/gradle.properties b/way-dsl/gradle.properties
new file mode 100644
index 0000000..15e43c5
--- /dev/null
+++ b/way-dsl/gradle.properties
@@ -0,0 +1 @@
+pomName=Way Kotlin DSL
diff --git a/way-dsl/src/commonMain/kotlin/ru/kode/way/dsl/Graph.kt b/way-dsl/src/commonMain/kotlin/ru/kode/way/dsl/Graph.kt
new file mode 100644
index 0000000..675af11
--- /dev/null
+++ b/way-dsl/src/commonMain/kotlin/ru/kode/way/dsl/Graph.kt
@@ -0,0 +1,329 @@
+package ru.kode.way.dsl
+
+import ru.kode.way.Event
+import ru.kode.way.FlowTarget
+import ru.kode.way.HistoryTarget
+import ru.kode.way.NodeBuilder
+import ru.kode.way.NullPayload
+import ru.kode.way.Path
+import ru.kode.way.Schema
+import ru.kode.way.ScreenTarget
+import ru.kode.way.Segment
+import ru.kode.way.append
+
+/**
+ * A navigation graph declared in Kotlin, the counterpart of a `.dot` file which needs no Gradle plugin. Nodes are
+ * properties of a subclass, edges are declared with [to] in its `init` block:
+ *
+ * ```kotlin
+ * object LoginGraph : Graph("Login") {
+ * val login = parameterizedFlow("login")
+ * val credentials = screen("credentials")
+ * val otp = parameterizedScreen("otp")
+ *
+ * init {
+ * login to credentials to otp
+ * }
+ * }
+ * ```
+ *
+ * The node without a parent is the root, it is a flow or a parallel flow. The rules are the ones of a `.dot` file:
+ * - the children of a parallel flow (its regions) are flows, parallel flows or [include]d graphs;
+ * - a [history] node is a leaf under a flow, or under a parallel flow which has a flow above it;
+ * - only an [include]d graph may have several parents, which are not parallel flows and are in the same region.
+ *
+ * Nodes are identified by `id@graphId`, so [id] has to be unique among the graphs of a
+ * [ru.kode.way.NavigationService]. The graph is checked and frozen on the first access to [schema] or [nodeBuilder].
+ */
+abstract class Graph(val id: String) {
+ private val nodes = LinkedHashMap()
+ private val parents = HashMap>()
+ private val children = HashMap>()
+ private var frozen = false
+
+ /** The [Schema] of this graph, used by the runtime in the same way as a generated one. */
+ val schema: Schema by lazy {
+ validate()
+ frozen = true
+ GraphSchema(this, rootNode)
+ }
+
+ internal val rootNode: NodeRef by lazy { nodes.values.single { it !in parents } }
+
+ /** A flow without a parameter which finishes with a result of type [R]. */
+ protected fun flow(id: String): FlowRef =
+ add(FlowRef(this, id, parameterized = false, nullable = false, included = null))
+
+ /** A flow with a parameter of type [P], a nullable [P] is `null` when the flow is started without a payload. */
+ protected inline fun parameterizedFlow(id: String): FlowRef =
+ addFlow(id, nullable = null is P)
+
+ protected fun parallel(id: String): ParallelRef =
+ add(ParallelRef(this, id, parameterized = false, nullable = false))
+
+ /** A parallel flow with a parameter of type [P], see [parameterizedFlow]. */
+ protected inline fun parameterizedParallel(id: String): ParallelRef =
+ addParallel(id, nullable = null is P)
+
+ protected fun screen(id: String): ScreenRef = add(ScreenRef(this, id))
+
+ protected fun
parameterizedScreen(id: String): ParameterizedScreenRef
= add(ParameterizedScreenRef(this, id))
+
+ /** A shallow history node, the counterpart of a `type = history` node of a `.dot` file. */
+ protected fun history(id: String): HistoryRef = add(HistoryRef(this, id, deep = false))
+
+ /** A deep history node, the counterpart of a `type = deepHistory` node of a `.dot` file. */
+ protected fun deepHistory(id: String): HistoryRef = add(HistoryRef(this, id, deep = true))
+
+ /**
+ * A node which is the graph whose root is [root], the counterpart of a `type = schema` node of a `.dot` file. It has
+ * the parameter and the result of [root].
+ */
+ protected fun
include(id: String, root: FlowNodeRef
): FlowRef
{
+ root.graph.schema // freezes the included graph
+ require(root.graph.rootNode === root) { "'${root.id}' is not the root of graph '${root.graph.id}'" }
+ return add(FlowRef(this, id, root.parameterized, root.nullable, included = root.graph))
+ }
+
+ @PublishedApi
+ internal fun
addFlow(id: String, nullable: Boolean): FlowRef
=
+ add(FlowRef(this, id, parameterized = true, nullable = nullable, included = null))
+
+ @PublishedApi
+ internal fun
addParallel(id: String, nullable: Boolean): ParallelRef
=
+ add(ParallelRef(this, id, parameterized = true, nullable = nullable))
+
+ /** Declares an edge from this node to [child] and returns [child], so `a to b to c` reads as `a -> b -> c`. */
+ protected infix fun NodeRef.to(child: T): T {
+ check(!frozen) { "graph '${this@Graph.id}' is frozen, edges are declared in its init block" }
+ require(graph === this@Graph && child.graph === this@Graph) {
+ "edge '${this.id}' -> '${child.id}' uses a node of another graph than '${this@Graph.id}'"
+ }
+ val childParents = parents.getOrPut(child) { mutableListOf() }
+ require(this !in childParents) { "edge '${this.id}' -> '${child.id}' is declared twice" }
+ childParents.add(this)
+ children.getOrPut(this) { mutableListOf() }.add(child)
+ return child
+ }
+
+ /**
+ * A [NodeBuilder] which creates the nodes of this graph with the factories registered in [configure]. Every node
+ * but a history one needs a factory.
+ */
+ fun nodeBuilder(configure: NodeFactories.() -> Unit): NodeBuilder {
+ schema // freezes the graph
+ val factories = NodeFactories(this).apply(configure).factories
+ val missing = nodes.values.filter { it !in factories && it !is HistoryRef }
+ require(missing.isEmpty()) { "graph '$id' has no factories for nodes: ${missing.joinToString { it.id }}" }
+ return GraphNodeBuilder(this, factories)
+ }
+
+ internal fun childrenOf(node: NodeRef): List = children[node].orEmpty()
+
+ internal fun parentsOf(node: NodeRef): List = parents[node].orEmpty()
+
+ internal fun parentOf(node: NodeRef): NodeRef? = parents[node]?.first()
+
+ internal fun nodeBySegment(segment: Segment): NodeRef? =
+ nodes[segment.id.substringBefore('@')]?.takeIf { it.segment == segment }
+
+ /**
+ * `true` for a node which is the root of a schema of its own, as a virtual sub-schema of a `.dot` file: a parallel
+ * flow which is not the root and a flow which is a region of a parallel flow.
+ */
+ internal fun ownsSchema(node: NodeRef): Boolean = (node is ParallelRef<*, *> && node in parents) ||
+ (node is FlowRef<*, *> && node.included == null && parentOf(node) is ParallelRef<*, *>)
+
+ /** [node] followed by its ancestors, up to the root (through the first parent of a node with several parents). */
+ private fun ancestry(node: NodeRef): Sequence = generateSequence(node, ::parentOf)
+
+ private fun add(node: T): T {
+ check(!frozen) { "graph '$id' is frozen, nodes are declared as its properties" }
+ require(node.id.isNotBlank() && '@' !in node.id) { "illegal node id '${node.id}' in graph '$id'" }
+ require(nodes.put(node.id, node) == null) { "node '${node.id}' is declared twice in graph '$id'" }
+ return node
+ }
+
+ private fun validate() {
+ nodes.values.filterIsInstance().forEach { history ->
+ require(history in parents) {
+ "history node '${history.id}' of graph '$id' has no parent flow, declare it under one flow with an edge"
+ }
+ }
+ val roots = nodes.values.filter { it !in parents }
+ require(roots.size == 1) { "graph '$id' must have one root node (without a parent), has: ${roots.map { it.id }}" }
+ val root = roots.single()
+ val reachable = generateSequence(listOf(root)) { level -> level.flatMap(::childrenOf).ifEmpty { null } }
+ .flatten().toSet()
+ require(reachable.size == nodes.size) {
+ "graph '$id' has nodes in a cycle: ${nodes.values.filter { it !in reachable }.map { it.id }}"
+ }
+ require((root is FlowRef<*, *> && root.included == null) || root is ParallelRef<*, *>) {
+ "the root '${root.id}' of graph '$id' must be a flow or a parallel flow"
+ }
+ require(root is ParallelRef<*, *> || childrenOf(root).isNotEmpty()) {
+ "flow '${root.id}' of graph '$id' has no children, a flow must have at least one child screen or flow"
+ }
+ val fanIn = nodes.values.filter { parentsOf(it).size > 1 && (it !is FlowRef<*, *> || it.included == null) }
+ require(fanIn.isEmpty()) {
+ "nodes of graph '$id' have several parents (fan-in): ${fanIn.joinToString { it.id }}, only an included " +
+ "graph can have several parents"
+ }
+ nodes.values.forEach { node ->
+ when (node) {
+ is ParallelRef<*, *> -> validateParallel(node)
+ is FlowRef<*, *> -> if (node.included != null) validateInclude(node)
+ is HistoryRef -> validateHistory(node)
+ is ScreenRef, is ParameterizedScreenRef<*> -> Unit
+ }
+ }
+ }
+
+ private fun validateParallel(parallel: ParallelRef<*, *>) {
+ val regions = childrenOf(parallel).filter { it !is HistoryRef }
+ require(regions.isNotEmpty()) {
+ "parallel '${parallel.id}' of graph '$id' has no children, a parallel flow must have at least one child flow"
+ }
+ require(regions.none { it is ScreenRef || it is ParameterizedScreenRef<*> }) {
+ "the children of parallel '${parallel.id}' in graph '$id' must be flows, parallel flows or included graphs"
+ }
+ }
+
+ private fun validateInclude(include: FlowRef<*, *>) {
+ require(childrenOf(include).isEmpty()) { "included graph '${include.id}' in graph '$id' can't have children" }
+ val includeParents = parentsOf(include)
+ if (includeParents.size < 2) return
+ includeParents.firstOrNull { it is ParallelRef<*, *> }?.let { parallel ->
+ throw IllegalArgumentException(
+ "included graph '${include.id}' in graph '$id' has several parents, one of which is the parallel " +
+ "'${parallel.id}'; enter it through a flow or a screen instead",
+ )
+ }
+ val owners = includeParents.map { parent -> ancestry(parent).firstOrNull(::ownsSchema) }
+ require(owners.distinct().size == 1) {
+ "included graph '${include.id}' in graph '$id' has parents in different parallel regions " +
+ "(${includeParents.joinToString { it.id }}); move the parents into one region"
+ }
+ }
+
+ private fun validateHistory(history: HistoryRef) {
+ require(childrenOf(history).isEmpty()) {
+ "history node '${history.id}' of graph '$id' must be a leaf, but has children: " +
+ childrenOf(history).joinToString { it.id }
+ }
+ val parent = parentOf(history)
+ when {
+ parent is FlowRef<*, *> && parent.included == null -> Unit
+
+ parent is ParallelRef<*, *> -> require(ancestry(parent).drop(1).any { it is FlowRef<*, *> }) {
+ "history node '${history.id}' of graph '$id' is under the parallel '${parent.id}' with no flow above it to " +
+ "host its target; nest the parallel under a flow"
+ }
+
+ else -> throw IllegalArgumentException(
+ "history node '${history.id}' of graph '$id' must be a child of a flow or a parallel flow, but its parent " +
+ "'${parent?.id}' is not; history under an included graph or a screen is not supported",
+ )
+ }
+ }
+}
+
+sealed class NodeRef(
+ internal val graph: Graph,
+ val id: String,
+ internal val parameterized: Boolean,
+ internal val nullable: Boolean = false,
+) {
+ val segment: Segment = Segment("$id@${graph.id}")
+
+ override fun toString(): String = segment.id
+
+ /**
+ * The path from the closest flow above this node, as in a generated target. A node with several parents needs
+ * [via], the parent it is entered from.
+ */
+ internal fun targetPath(via: NodeRef? = null): Path {
+ val parents = graph.parentsOf(this)
+ val parent = when {
+ via != null -> via.also { require(it in parents) { "'${it.id}' is not a parent of '$id'" } }
+
+ parents.size > 1 -> throw IllegalArgumentException(
+ "'$id' has several parents (${parents.joinToString { it.id }}), pass the one to enter it from as `via`",
+ )
+
+ else -> parents.firstOrNull()
+ }
+ val segments = ArrayDeque(listOf(segment))
+ var screen = parent
+ while (screen is ScreenRef || screen is ParameterizedScreenRef<*>) {
+ segments.addFirst(screen.segment)
+ screen = graph.parentOf(screen)
+ }
+ return Path(segments)
+ }
+}
+
+/** A flow or a parallel flow with a parameter of type [P] (`Unit` for none) and a result of type [R]. */
+sealed class FlowNodeRef(graph: Graph, id: String, parameterized: Boolean, nullable: Boolean) :
+ NodeRef(graph, id, parameterized, nullable) {
+ /**
+ * A target which starts this flow with [payload]. An included graph with several parents needs [via], the parent
+ * it is entered from (a generated `Via` target).
+ */
+ fun target(payload: P, via: NodeRef? = null): FlowTarget =
+ FlowTarget(targetPath(via), if (parameterized) payload ?: NullPayload else null)
+}
+
+/** A target of a flow without a parameter, see [FlowNodeRef.target]. */
+fun FlowNodeRef.target(via: NodeRef? = null): FlowTarget = target(Unit, via)
+
+class FlowRef internal constructor(
+ graph: Graph,
+ id: String,
+ parameterized: Boolean,
+ nullable: Boolean,
+ internal val included: Graph?,
+) : FlowNodeRef
(graph, id, parameterized, nullable)
+
+class ParallelRef
internal constructor(
+ graph: Graph,
+ id: String,
+ parameterized: Boolean,
+ nullable: Boolean,
+) : FlowNodeRef
(graph, id, parameterized, nullable)
+
+class ScreenRef internal constructor(graph: Graph, id: String) : NodeRef(graph, id, parameterized = false) {
+ fun target(): ScreenTarget = ScreenTarget(targetPath())
+}
+
+class ParameterizedScreenRef
internal constructor(graph: Graph, id: String) :
+ NodeRef(graph, id, parameterized = true) {
+ fun target(payload: P): ScreenTarget = ScreenTarget(targetPath(), payload ?: NullPayload)
+}
+
+/**
+ * A history node: [target] re-enters its parent with the nodes which were active when the parent was left (only the
+ * direct child of the parent for a shallow history, every node below it for a [deep] one).
+ */
+class HistoryRef internal constructor(graph: Graph, id: String, val deep: Boolean) :
+ NodeRef(graph, id, parameterized = false) {
+ /**
+ * The target of the parent of this node. Its path starts at the root of the graph and comes after [prefix] (the
+ * absolute path above the graph, if any), as the generated history target does.
+ */
+ fun target(prefix: Path? = null): HistoryTarget {
+ val path = Path(generateSequence(graph.parentOf(this), graph::parentOf).map { it.segment }.toList().asReversed())
+ return HistoryTarget(prefix?.append(path) ?: path, deep)
+ }
+}
+
+/**
+ * Sent to the parent of a flow (or of a region of a parallel flow) declared by a [Graph] when it finishes, the
+ * counterpart of a generated `ChildFinishRequest`. Read its result with [childFlowResult].
+ */
+data class ChildFlowFinishedEvent(val child: Segment, val result: Any) : Event
+
+/** The result of [child] if this event reports that [child] has finished, `null` otherwise. */
+@Suppress("UNCHECKED_CAST")
+fun Event.childFlowResult(child: FlowNodeRef<*, C>): C? =
+ if (this is ChildFlowFinishedEvent && this.child == child.segment) result as C else null
diff --git a/way-dsl/src/commonMain/kotlin/ru/kode/way/dsl/GraphNodeBuilder.kt b/way-dsl/src/commonMain/kotlin/ru/kode/way/dsl/GraphNodeBuilder.kt
new file mode 100644
index 0000000..de7b0b1
--- /dev/null
+++ b/way-dsl/src/commonMain/kotlin/ru/kode/way/dsl/GraphNodeBuilder.kt
@@ -0,0 +1,185 @@
+package ru.kode.way.dsl
+
+import ru.kode.way.Event
+import ru.kode.way.FlowNode
+import ru.kode.way.MissingPayloadException
+import ru.kode.way.Node
+import ru.kode.way.NodeBuilder
+import ru.kode.way.NullPayload
+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.Segment
+import ru.kode.way.drop
+import ru.kode.way.firstSegment
+import ru.kode.way.lastSegment
+import ru.kode.way.startsWith
+import ru.kode.way.take
+
+/** Registers a factory for every node of a [Graph], see [Graph.nodeBuilder]. */
+class NodeFactories internal constructor(private val graph: Graph) {
+ internal val factories = HashMap Any>()
+
+ /** [factory] gets the payload of the flow, `Unit` for a flow without a parameter. */
+ fun flow(ref: FlowRef
, factory: (payload: P) -> FlowNode) {
+ require(ref.included == null) { "'${ref.id}' is an included graph, register it with include()" }
+ put(ref, factory)
+ }
+
+ /** [factory] gets the payload of the parallel flow, `Unit` for a parallel flow without a parameter. */
+ fun parallel(ref: ParallelRef
, factory: (payload: P) -> ParallelFlowNode) = put(ref, factory)
+
+ fun screen(ref: ScreenRef, factory: () -> ScreenNode) = put(ref) { _: Any? -> factory() }
+
+ fun screen(ref: ParameterizedScreenRef
, factory: (payload: P) -> ScreenNode) = put(ref, factory)
+
+ /** [factory] creates the [NodeBuilder] of the included graph, it gets the payload of the graph's root. */
+ fun
include(ref: FlowRef
, factory: (payload: P) -> NodeBuilder) {
+ require(ref.included != null) { "'${ref.id}' is not an included graph, register it with flow()" }
+ put(ref, factory)
+ }
+
+ @Suppress("UNCHECKED_CAST")
+ private fun
put(ref: NodeRef, factory: (P) -> Any) {
+ require(ref.graph === graph) { "node '$ref' does not belong to graph '${graph.id}'" }
+ factories[ref] = { payload -> factory(payload as P) }
+ }
+}
+
+/**
+ * The schema of the part of a [Graph] under [root], the graph's root or a node which owns a schema (see
+ * [Graph.ownsSchema]), as a generated schema or virtual sub-schema is. History nodes are not part of it: they are never
+ * built, their target is the one of their parent.
+ */
+internal class GraphSchema(private val graph: Graph, private val root: NodeRef) : Schema {
+ private val nodes: Set = LinkedHashSet().also { collect(root, it) }
+
+ override val rootSegment: Segment = root.segment
+
+ override val childSchemas: Map = nodes.filter { it !== root }.mapNotNull { node ->
+ val included = (node as? FlowRef<*, *>)?.included
+ when {
+ included != null -> node.segment to included.schema
+ graph.ownsSchema(node) -> node.segment to GraphSchema(graph, node)
+ else -> null
+ }
+ }.toMap()
+
+ /**
+ * The root unless it is a parallel flow, then the children of every parallel flow which is not a child of another
+ * one (the regions of that one), as in a generated schema.
+ */
+ override val regions: List = buildList {
+ if (root !is ParallelRef<*, *>) add(root)
+ nodes.filter { it is ParallelRef<*, *> && (it === root || graph.parentOf(it) !is ParallelRef<*, *>) }
+ .forEach { parallel -> addAll(graph.childrenOf(parallel).filter { it in nodes }) }
+ }.map { RegionId(pathsOf(it, rootSegmentAlias = null).single()) }
+
+ override fun target(regionId: RegionId, segment: Segment, rootSegmentAlias: Segment?): Path? =
+ targets(regionId, segment, rootSegmentAlias).firstOrNull()
+
+ override fun targets(regionId: RegionId, segment: Segment, rootSegmentAlias: Segment?): List {
+ checkRegion(regionId)
+ return graph.nodeBySegment(segment)?.takeIf { it in nodes }?.let { pathsOf(it, rootSegmentAlias) }.orEmpty()
+ }
+
+ override fun nodeType(regionId: RegionId, path: Path, rootSegmentAlias: Segment?): Schema.NodeType =
+ when (nodeAt(regionId, path, rootSegmentAlias)) {
+ is FlowRef<*, *> -> Schema.NodeType.Flow
+ is ParallelRef<*, *> -> Schema.NodeType.ParallelFlow
+ is ScreenRef, is ParameterizedScreenRef<*> -> Schema.NodeType.Screen
+ is HistoryRef -> error("internal error: history node at path=$path")
+ }
+
+ /** A nullable root is built with `null` when it has no payload, so it never misses one. */
+ override fun isParameterized(regionId: RegionId, path: Path, rootSegmentAlias: Segment?): Boolean {
+ val node = nodeAt(regionId, path, rootSegmentAlias)
+ return node.parameterized && !(node === root && node.nullable)
+ }
+
+ override fun createChildFlowFinishRequestEvent(regionId: RegionId, path: Path, result: Any): Event {
+ checkRegion(regionId)
+ return ChildFlowFinishedEvent(path.lastSegment(), result)
+ }
+
+ /** The paths of [node] from [root], one per parent, the root is replaced with [rootSegmentAlias]. */
+ private fun pathsOf(node: NodeRef, rootSegmentAlias: Segment?): List = if (node === root) {
+ listOf(Path(rootSegmentAlias ?: rootSegment))
+ } else {
+ graph.parentsOf(node).flatMap { pathsOf(it, rootSegmentAlias) }.map { Path(it.segments + node.segment) }
+ }
+
+ private fun nodeAt(regionId: RegionId, path: Path, rootSegmentAlias: Segment?): NodeRef {
+ checkRegion(regionId)
+ val node = if (path.length == 1) root else graph.nodeBySegment(path.lastSegment())?.takeIf { it in nodes }
+ return node?.takeIf { path in pathsOf(it, rootSegmentAlias) } ?: error("internal error: no node for path=$path")
+ }
+
+ private fun checkRegion(regionId: RegionId) = check(regionId in regions) { "unknown regionId=$regionId" }
+
+ private fun collect(node: NodeRef, into: MutableSet) {
+ if (node !is HistoryRef && into.add(node)) graph.childrenOf(node).forEach { collect(it, into) }
+ }
+}
+
+/**
+ * Builds the nodes of a [Graph] as a generated node builder does: a node is created on every request (the runtime
+ * keeps alive nodes), the node builders of included graphs are cached while some alive node is inside of them.
+ */
+internal class GraphNodeBuilder(private val graph: Graph, private val factories: Map Any>) :
+ NodeBuilder {
+ override val schema: GraphSchema = graph.schema as GraphSchema
+
+ private val nodeBuilders = HashMap()
+
+ override fun build(path: Path, payloads: Map, rootSegmentAlias: Segment?): Node {
+ val rootSegment = rootSegmentAlias ?: schema.rootSegment
+ check(path.firstSegment() == rootSegment) { "illegal path build requested for graph '${graph.id}': $path" }
+ var node = graph.rootNode
+ for (index in 1 until path.length) {
+ node = graph.childrenOf(node).find { it.segment == path.segments[index] }
+ ?: error("illegal path build requested for graph '${graph.id}': $path")
+ if (node is FlowRef<*, *> && node.included != null) {
+ val includePath = path.take(index + 1)
+ val included = node
+ val nodeBuilder = nodeBuilders.getOrPut(includePath) {
+ factories.getValue(included)(payload(included, includePath, payloads)) as NodeBuilder
+ }
+ return nodeBuilder.build(
+ path.drop(index),
+ payloads.filterKeys { it.length > index }.mapKeys { it.key.drop(index) },
+ rootSegmentAlias = path.segments[index],
+ )
+ }
+ }
+ return factories.getValue(node)(payload(node, path, payloads)) as Node
+ }
+
+ override fun invalidateCache(alivePaths: Set) {
+ nodeBuilders.keys.retainAll { key -> alivePaths.any { it.startsWith(key) } }
+ nodeBuilders.forEach { (builderPath, builder) ->
+ val drop = builderPath.length - 1
+ builder.invalidateCache(alivePaths.filter { it.startsWith(builderPath) }.map { it.drop(drop) }.toSet())
+ }
+ }
+
+ 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)
+ }
+ }
+
+ /** `Unit` for a node without a parameter, `null` for a missing payload of a nullable flow (see [GraphSchema]). */
+ private fun payload(node: NodeRef, path: Path, payloads: Map): Any? {
+ if (!node.parameterized) return Unit
+ val payload = payloads[path] ?: if (node.nullable) return null else throw MissingPayloadException(path)
+ return payload.takeUnless { it === NullPayload }
+ }
+}
diff --git a/way-dsl/src/commonTest/kotlin/ru/kode/way/TestEvent.kt b/way-dsl/src/commonTest/kotlin/ru/kode/way/TestEvent.kt
new file mode 100644
index 0000000..29f43f9
--- /dev/null
+++ b/way-dsl/src/commonTest/kotlin/ru/kode/way/TestEvent.kt
@@ -0,0 +1,3 @@
+package ru.kode.way
+
+data class TestEvent(val name: String) : Event
diff --git a/way-dsl/src/commonTest/kotlin/ru/kode/way/TestFlowNode.kt b/way-dsl/src/commonTest/kotlin/ru/kode/way/TestFlowNode.kt
new file mode 100644
index 0000000..4456619
--- /dev/null
+++ b/way-dsl/src/commonTest/kotlin/ru/kode/way/TestFlowNode.kt
@@ -0,0 +1,134 @@
+package ru.kode.way
+
+class TestFlowNode(
+ initialTarget: Target,
+ onEntryImpl: () -> Unit = {},
+ onExitImpl: () -> Unit = {},
+ onDisposeImpl: () -> Unit = {},
+ transitions: List = emptyList(),
+ val payload: Any? = null,
+) : GenericTestFlowNode(initialTarget, Unit, onEntryImpl, onExitImpl, onDisposeImpl, transitions)
+
+class TestFlowNodeWithResult(
+ initialTarget: Target,
+ override val dismissResult: R,
+ onEntryImpl: () -> Unit = {},
+ onExitImpl: () -> Unit = {},
+ onDisposeImpl: () -> Unit = {},
+ transitions: List = emptyList(),
+ val payload: Any? = null,
+) : GenericTestFlowNode(initialTarget, dismissResult, onEntryImpl, onExitImpl, onDisposeImpl, transitions)
+
+open class GenericTestFlowNode(
+ initialTarget: Target,
+ override val dismissResult: R,
+ private val onEntryImpl: () -> Unit = {},
+ private val onExitImpl: () -> Unit = {},
+ private val onDisposeImpl: () -> Unit = {},
+ private val transitions: List = emptyList(),
+) : FlowNode {
+
+ override val initial: Target = initialTarget
+
+ override fun transition(event: Event): FlowTransition = if (transitions.isEmpty()) {
+ Ignore
+ } else {
+ transitions.find { it.eventMatcher(event) }?.transition as FlowTransition? ?: Ignore
+ }
+
+ override fun onEntry(event: Event) {
+ super.onEntry(event)
+ onEntryImpl()
+ }
+
+ override fun onExit(event: Event) {
+ super.onExit(event)
+ onExitImpl()
+ }
+
+ override fun onDispose() {
+ super.onDispose()
+ onDisposeImpl()
+ }
+}
+
+class TestScreenNode(
+ val payload: Any? = null,
+ private val transitions: List = emptyList(),
+ private val onEntryImpl: () -> Unit = {},
+ private val onExitImpl: () -> Unit = {},
+ private val onDisposeImpl: () -> Unit = {},
+) : ScreenNode {
+ override fun transition(event: Event): ScreenTransition = if (transitions.isEmpty()) {
+ Ignore
+ } else {
+ transitions.find { it.eventMatcher(event) }?.transition ?: Ignore
+ }
+
+ override fun onEntry(event: Event) {
+ super.onEntry(event)
+ onEntryImpl()
+ }
+
+ override fun onExit(event: Event) {
+ super.onExit(event)
+ onExitImpl()
+ }
+
+ override fun onDispose() {
+ super.onDispose()
+ onDisposeImpl()
+ }
+}
+
+class TestParallelNode(
+ val payload: Any? = null,
+ private val transitions: List = emptyList(),
+ private val parallelTransitions: List = emptyList(),
+ private val onEntryImpl: () -> Unit = {},
+ private val onExitImpl: () -> Unit = {},
+ private val onDisposeImpl: () -> Unit = {},
+ private val onTransitionCallback: ((Event) -> Unit)? = null,
+ // Stateful override for Back: each Back event pops the next transition off this queue. Lets a test
+ // drive an Ignore-then-Finish sequence to exercise the re-consultation inside dispatchBackThroughParallel.
+ private val backTransitionQueue: MutableList>? = null,
+) : ParallelFlowNode() {
+ override val dismissResult = Unit
+
+ override fun transition(event: Event): FlowTransition {
+ onTransitionCallback?.invoke(event)
+ if (event is BackEvent && backTransitionQueue != null && backTransitionQueue.isNotEmpty()) {
+ return backTransitionQueue.removeAt(0)
+ }
+ parallelTransitions.find { it.eventMatcher(event) }?.transition?.also { return it }
+ return if (event is TestEvent) {
+ if (transitions.isEmpty()) {
+ Ignore
+ } else {
+ transitions.find { it.eventMatcher(event) }?.transition as FlowTransition? ?: Ignore
+ }
+ } else {
+ Ignore
+ }
+ }
+
+ override fun onEntry(event: Event) {
+ super.onEntry(event)
+ onEntryImpl()
+ }
+
+ override fun onExit(event: Event) {
+ super.onExit(event)
+ onExitImpl()
+ }
+
+ override fun onDispose() {
+ super.onDispose()
+ onDisposeImpl()
+ }
+}
+
+data class TestParallelTransitionSpec(val eventMatcher: (Event) -> Boolean, val transition: FlowTransition)
+
+inline fun trp(transition: FlowTransition): TestParallelTransitionSpec =
+ TestParallelTransitionSpec(eventMatcher = { it is E }, transition)
diff --git a/way-dsl/src/commonTest/kotlin/ru/kode/way/TestNodeBuilder.kt b/way-dsl/src/commonTest/kotlin/ru/kode/way/TestNodeBuilder.kt
new file mode 100644
index 0000000..512ab4d
--- /dev/null
+++ b/way-dsl/src/commonTest/kotlin/ru/kode/way/TestNodeBuilder.kt
@@ -0,0 +1,20 @@
+package ru.kode.way
+
+class TestNodeBuilder(
+ override val schema: Schema,
+ private val mapping: Map,
+ private val throwAtBuild: Path? = null,
+ private val throwAtBuildMessage: String = "TestNodeBuilder.build injected throw",
+ private val throwOnInvalidateCache: Boolean = false,
+ private val throwOnInvalidateCacheMessage: String = "TestNodeBuilder.invalidateCache injected throw",
+) : NodeBuilder {
+ override fun build(path: Path, payloads: Map, rootSegmentAlias: Segment?): Node {
+ if (path == throwAtBuild) error(throwAtBuildMessage)
+ return mapping[path.segments.joinToString(".") { it.name }]
+ ?: error("no test node mapping for path $path. Existing keys: ${mapping.keys}")
+ }
+
+ override fun invalidateCache(alivePaths: Set) {
+ if (throwOnInvalidateCache) error(throwOnInvalidateCacheMessage)
+ }
+}
diff --git a/way-dsl/src/commonTest/kotlin/ru/kode/way/TestTransitionSpec.kt b/way-dsl/src/commonTest/kotlin/ru/kode/way/TestTransitionSpec.kt
new file mode 100644
index 0000000..ce0e799
--- /dev/null
+++ b/way-dsl/src/commonTest/kotlin/ru/kode/way/TestTransitionSpec.kt
@@ -0,0 +1,39 @@
+package ru.kode.way
+
+data class TestFlowTransitionSpec(val eventMatcher: (Event) -> Boolean, val transition: FlowTransition<*>)
+
+data class TestScreenTransitionSpec(val eventMatcher: (Event) -> Boolean, val transition: ScreenTransition)
+
+fun tr(on: String, target: Target): TestFlowTransitionSpec = TestFlowTransitionSpec(eventMatcher = {
+ it is TestEvent && it.name == on
+}, NavigateTo(target))
+
+fun tr(on: String, transition: FlowTransition<*>): TestFlowTransitionSpec = TestFlowTransitionSpec(eventMatcher = {
+ it is TestEvent && it.name == on
+}, transition)
+
+inline fun tr(target: Target): TestFlowTransitionSpec = TestFlowTransitionSpec(eventMatcher = {
+ it is E
+}, NavigateTo(target))
+
+inline fun tr(transition: FlowTransition<*>): TestFlowTransitionSpec =
+ TestFlowTransitionSpec(eventMatcher = {
+ it is E
+ }, transition)
+
+fun trs(on: String, target: Target): TestScreenTransitionSpec = TestScreenTransitionSpec(eventMatcher = {
+ it is TestEvent && it.name == on
+}, NavigateTo(target))
+
+fun trs(on: String, transition: ScreenTransition): TestScreenTransitionSpec = TestScreenTransitionSpec(eventMatcher = {
+ it is TestEvent && it.name == on
+}, transition)
+
+inline fun trs(target: Target): TestScreenTransitionSpec = TestScreenTransitionSpec(eventMatcher = {
+ it is E
+}, NavigateTo(target))
+
+inline fun trs(transition: ScreenTransition): TestScreenTransitionSpec =
+ TestScreenTransitionSpec(eventMatcher = {
+ it is E
+ }, transition)
diff --git a/way-dsl/src/commonTest/kotlin/ru/kode/way/dsl/DslParityTest.kt b/way-dsl/src/commonTest/kotlin/ru/kode/way/dsl/DslParityTest.kt
new file mode 100644
index 0000000..a8673d3
--- /dev/null
+++ b/way-dsl/src/commonTest/kotlin/ru/kode/way/dsl/DslParityTest.kt
@@ -0,0 +1,834 @@
+package ru.kode.way.dsl
+
+import io.kotest.core.spec.style.ShouldSpec
+import io.kotest.matchers.collections.shouldContainExactly
+import io.kotest.matchers.shouldBe
+import io.kotest.matchers.string.shouldContain
+import io.kotest.matchers.string.shouldStartWith
+import ru.kode.way.Event
+import ru.kode.way.Finish
+import ru.kode.way.Ignore
+import ru.kode.way.NavigateTo
+import ru.kode.way.NavigationService
+import ru.kode.way.NavigationState
+import ru.kode.way.NodeBuilder
+import ru.kode.way.Target
+import ru.kode.way.TestEvent
+import ru.kode.way.TestFlowNode
+import ru.kode.way.TestFlowNodeWithResult
+import ru.kode.way.TestFlowTransitionSpec
+import ru.kode.way.TestNodeBuilder
+import ru.kode.way.TestParallelNode
+import ru.kode.way.TestParallelTransitionSpec
+import ru.kode.way.TestScreenNode
+import ru.kode.way.dslparity.AppChildFinishRequest
+import ru.kode.way.dslparity.AppNodeBuilder
+import ru.kode.way.dslparity.DslParityAppSchema
+import ru.kode.way.dslparity.app
+import ru.kode.way.dslparity.counter.CounterNodeBuilder
+import ru.kode.way.dslparity.counter.DslParityCounterSchema
+import ru.kode.way.dslparity.counter.counter
+import ru.kode.way.dslparity.fanin.DslParityFanInSchema
+import ru.kode.way.dslparity.fanin.SharedChildFinishRequest
+import ru.kode.way.dslparity.fanin.SharedNodeBuilder
+import ru.kode.way.dslparity.fanin.shared
+import ru.kode.way.dslparity.feed.DslParityFeedSchema
+import ru.kode.way.dslparity.feed.FeedNodeBuilder
+import ru.kode.way.dslparity.feed.feed
+import ru.kode.way.dslparity.history.DslParityHistorySchema
+import ru.kode.way.dslparity.history.HistNodeBuilder
+import ru.kode.way.dslparity.history.hist
+import ru.kode.way.dslparity.history.shop
+import ru.kode.way.dslparity.home.DslParityHomeSchema
+import ru.kode.way.dslparity.home.HomeNodeBuilder
+import ru.kode.way.dslparity.home.home
+import ru.kode.way.dslparity.login.DslParityLoginSchema
+import ru.kode.way.dslparity.login.LoginNodeBuilder
+import ru.kode.way.dslparity.login.login
+import ru.kode.way.dslparity.nested.DslParityNestedSchema
+import ru.kode.way.dslparity.nested.InnerNodeBuilder
+import ru.kode.way.dslparity.nested.InnerSchema
+import ru.kode.way.dslparity.nested.LeftNodeBuilder
+import ru.kode.way.dslparity.nested.LeftSchema
+import ru.kode.way.dslparity.nested.MainNodeBuilder
+import ru.kode.way.dslparity.nested.RightNodeBuilder
+import ru.kode.way.dslparity.nested.RightSchema
+import ru.kode.way.dslparity.nested.TabsSchema
+import ru.kode.way.dslparity.nested.left
+import ru.kode.way.dslparity.nested.main
+import ru.kode.way.dslparity.nested.right
+import ru.kode.way.dslparity.params.DslParityParamsSchema
+import ru.kode.way.dslparity.params.ParamsChildFinishRequest
+import ru.kode.way.dslparity.params.ParamsNodeBuilder
+import ru.kode.way.dslparity.params.params
+import ru.kode.way.dslparity.perm.DslParityPermSchema
+import ru.kode.way.dslparity.perm.PermNodeBuilder
+import ru.kode.way.dslparity.perm.perm
+import ru.kode.way.dslparity.settings
+import ru.kode.way.dslparity.tabs.DslParityTabsSchema
+import ru.kode.way.dslparity.tabs.TabsChildFinishRequest
+import ru.kode.way.dslparity.tabs.TabsNodeBuilder
+import ru.kode.way.tr
+import ru.kode.way.dslparity.nested.TabsNodeBuilder as NestedTabsNodeBuilder
+
+/** The DSL counterparts of `dsl-parity-*.dot`. */
+private object LoginGraph : Graph("DslLogin") {
+ val login = parameterizedFlow("login")
+ val credentials = screen("credentials")
+ val otp = parameterizedScreen("otp")
+
+ init {
+ login to credentials to otp
+ }
+}
+
+private object AppGraph : Graph("DslApp") {
+ val app = parameterizedFlow("app")
+ val intro = screen("intro")
+ val details = parameterizedScreen("details")
+ val settings = flow("settings")
+ val general = screen("general")
+ val login = include("login", LoginGraph.login)
+
+ init {
+ app to intro to details
+ app to settings to general
+ app to login
+ }
+}
+
+private object HomeGraph : Graph("DslHome") {
+ val home = flow("home")
+ val homeScreen = screen("homeScreen")
+ val homeDetails = screen("homeDetails")
+
+ init {
+ home to homeScreen to homeDetails
+ }
+}
+
+private object FeedGraph : Graph("DslFeed") {
+ val feed = flow("feed")
+ val feedScreen = screen("feedScreen")
+
+ init {
+ feed to feedScreen
+ }
+}
+
+private object TabsGraph : Graph("DslTabs") {
+ val tabs = parallel("tabs")
+ val home = include("home", HomeGraph.home)
+ val feed = include("feed", FeedGraph.feed)
+
+ init {
+ tabs to home
+ tabs to feed
+ }
+}
+
+private object CounterGraph : Graph("DslCounter") {
+ val counter = parameterizedFlow("counter")
+ val counterScreen = screen("counterScreen")
+
+ init {
+ counter to counterScreen
+ }
+}
+
+private object ParamsGraph : Graph("DslParams") {
+ val params = parameterizedFlow("params")
+ val paramsScreen = screen("paramsScreen")
+ val counter = include("counter", CounterGraph.counter)
+
+ init {
+ params to paramsScreen to counter
+ }
+}
+
+private object HistoryGraph : Graph("DslHistory") {
+ val hist = flow("hist")
+ val home = screen("home")
+ val shop = flow("shop")
+ val cart = screen("cart")
+ val checkout = screen("checkout")
+ val cartHistory = history("cartHistory")
+ val cartDeepHistory = deepHistory("cartDeepHistory")
+
+ init {
+ hist to home
+ hist to shop to cart to checkout
+ shop to cartHistory
+ shop to cartDeepHistory
+ }
+}
+
+private object NestedGraph : Graph("DslNested") {
+ val main = flow("main")
+ val start = screen("start")
+ val tabs = parallel("tabs")
+ val left = flow("left")
+ val leftScreen = screen("leftScreen")
+ val leftDetails = screen("leftDetails")
+ val inner = parallel("inner")
+ val right = flow("right")
+ val rightScreen = screen("rightScreen")
+ val feed = include("feed", FeedGraph.feed)
+ val tabsHistory = deepHistory("tabsHistory")
+
+ init {
+ main to start
+ main to tabs
+ tabs to left to leftScreen to leftDetails
+ left to inner
+ inner to right to rightScreen
+ inner to feed
+ tabs to tabsHistory
+ }
+}
+
+private object PermGraph : Graph("DslPerm") {
+ val perm = parameterizedFlow("perm")
+ val permIntro = screen("permIntro")
+ val permDetails = screen("permDetails")
+
+ init {
+ perm to permIntro to permDetails
+ }
+}
+
+private object FanInGraph : Graph("DslFanIn") {
+ val shared = flow("shared")
+ val a = parameterizedScreen("a")
+ val b = parameterizedScreen("b")
+ val perm = include("perm", PermGraph.perm)
+
+ init {
+ shared to a to perm
+ shared to b to perm
+ }
+}
+
+/** The targets and events which differ between a generated and a DSL graph. */
+private class AppSpec(
+ val intro: Target,
+ val details: (String?) -> Target,
+ val settings: Target,
+ val general: Target,
+ val login: (String) -> Target,
+ val credentials: Target,
+ val otp: (Int) -> Target,
+ val isSettingsFinished: (Event) -> Boolean,
+ val isLoginFinished: (Event) -> Boolean,
+)
+
+private fun appRootNode(spec: AppSpec, payload: Any?) = TestFlowNode(
+ initialTarget = spec.intro,
+ payload = payload,
+ transitions = listOf(
+ tr("D", spec.details(null)),
+ tr("S", spec.settings),
+ tr("L", spec.login("alice")),
+ TestFlowTransitionSpec(spec.isSettingsFinished, NavigateTo(spec.details("from-settings"))),
+ TestFlowTransitionSpec(spec.isLoginFinished, NavigateTo(spec.intro)),
+ ),
+)
+
+private fun settingsNode(spec: AppSpec) = TestFlowNodeWithResult(
+ initialTarget = spec.general,
+ dismissResult = "dismissed",
+ transitions = listOf(tr("F", Finish("done"))),
+)
+
+private fun loginNode(spec: AppSpec, payload: Any?) = TestFlowNodeWithResult(
+ initialTarget = spec.credentials,
+ dismissResult = 0,
+ payload = payload,
+ transitions = listOf(tr("O", spec.otp(7)), tr("F", Finish(5))),
+)
+
+private fun generatedAppBuilder(): NodeBuilder {
+ val spec = AppSpec(
+ intro = Target.app.intro,
+ details = { Target.app.details(it) },
+ settings = Target.app.settings,
+ general = Target.settings.general,
+ login = { Target.app.login(it) },
+ credentials = Target.login.credentials,
+ otp = { Target.login.otp(it) },
+ isSettingsFinished = { it is AppChildFinishRequest.Settings && it.result == "done" },
+ isLoginFinished = { it is AppChildFinishRequest.Login && it.result == 5 },
+ )
+ val schema = DslParityAppSchema(DslParityLoginSchema())
+ return AppNodeBuilder(
+ object : AppNodeBuilder.Factory {
+ override fun createRootNode(timeout: Int) = appRootNode(spec, timeout)
+ override fun createIntroNode() = TestScreenNode()
+ override fun createDetailsNode(id: String?) = TestScreenNode(payload = id)
+
+ // the generated SettingsNodeBuilder resolves "general" to app.settings.general under the "settings" alias and
+ // fails to build it, so the local flow is built by hand
+ override fun createSettingsNodeBuilder(): NodeBuilder =
+ TestNodeBuilder(schema, mapOf("settings" to settingsNode(spec), "settings.general" to TestScreenNode()))
+
+ override fun createLoginNodeBuilder(userName: String): NodeBuilder = LoginNodeBuilder(
+ object : LoginNodeBuilder.Factory {
+ override fun createRootNode(userName: String) = loginNode(spec, userName)
+ override fun createCredentialsNode() = TestScreenNode()
+ override fun createOtpNode(code: Int) = TestScreenNode(payload = code)
+ },
+ DslParityLoginSchema(),
+ )
+ },
+ schema,
+ )
+}
+
+private fun dslAppBuilder(): NodeBuilder {
+ val spec = AppSpec(
+ intro = AppGraph.intro.target(),
+ details = { AppGraph.details.target(it) },
+ settings = AppGraph.settings.target(),
+ general = AppGraph.general.target(),
+ login = { AppGraph.login.target(it) },
+ credentials = LoginGraph.credentials.target(),
+ otp = { LoginGraph.otp.target(it) },
+ isSettingsFinished = { it.childFlowResult(AppGraph.settings) == "done" },
+ isLoginFinished = { it.childFlowResult(AppGraph.login) == 5 },
+ )
+ return AppGraph.nodeBuilder {
+ flow(AppGraph.app) { appRootNode(spec, it) }
+ screen(AppGraph.intro) { TestScreenNode() }
+ screen(AppGraph.details) { TestScreenNode(payload = it) }
+ flow(AppGraph.settings) { settingsNode(spec) }
+ screen(AppGraph.general) { TestScreenNode() }
+ include(AppGraph.login) {
+ LoginGraph.nodeBuilder {
+ flow(LoginGraph.login) { loginNode(spec, it) }
+ screen(LoginGraph.credentials) { TestScreenNode() }
+ screen(LoginGraph.otp) { TestScreenNode(payload = it) }
+ }
+ }
+ }
+}
+
+private fun tabsRootNode(isChildFinished: (Event) -> Boolean) = TestParallelNode(
+ parallelTransitions = listOf(TestParallelTransitionSpec(isChildFinished, Finish(Unit))),
+)
+
+private fun homeNode(homeDetails: Target, homeScreen: Target) = TestFlowNode(
+ initialTarget = homeScreen,
+ transitions = listOf(tr("HD", homeDetails), tr("HF", Finish(Unit))),
+)
+
+private fun generatedTabsBuilder(): NodeBuilder = TabsNodeBuilder(
+ object : TabsNodeBuilder.Factory {
+ override fun createRootNode() = tabsRootNode { it == TabsChildFinishRequest.Home }
+ override fun createHomeNodeBuilder(): NodeBuilder = HomeNodeBuilder(
+ object : HomeNodeBuilder.Factory {
+ override fun createRootNode() = homeNode(Target.home.homeDetails, Target.home.homeScreen)
+ override fun createHomeScreenNode() = TestScreenNode()
+ override fun createHomeDetailsNode() = TestScreenNode()
+ },
+ DslParityHomeSchema(),
+ )
+
+ override fun createFeedNodeBuilder(): NodeBuilder = FeedNodeBuilder(
+ object : FeedNodeBuilder.Factory {
+ override fun createRootNode() = TestFlowNode(initialTarget = Target.feed.feedScreen)
+ override fun createFeedScreenNode() = TestScreenNode()
+ },
+ DslParityFeedSchema(),
+ )
+ },
+ DslParityTabsSchema(DslParityHomeSchema(), DslParityFeedSchema()),
+)
+
+private fun dslTabsBuilder(): NodeBuilder = TabsGraph.nodeBuilder {
+ parallel(TabsGraph.tabs) { tabsRootNode { it.childFlowResult(TabsGraph.home) != null } }
+ include(TabsGraph.home) {
+ HomeGraph.nodeBuilder {
+ flow(HomeGraph.home) { homeNode(HomeGraph.homeDetails.target(), HomeGraph.homeScreen.target()) }
+ screen(HomeGraph.homeScreen) { TestScreenNode() }
+ screen(HomeGraph.homeDetails) { TestScreenNode() }
+ }
+ }
+ include(TabsGraph.feed) {
+ FeedGraph.nodeBuilder {
+ flow(FeedGraph.feed) { TestFlowNode(initialTarget = FeedGraph.feedScreen.target()) }
+ screen(FeedGraph.feedScreen) { TestScreenNode() }
+ }
+ }
+}
+
+private class ParamsSpec(
+ val paramsScreen: Target,
+ val counter: (Int?) -> Target,
+ val counterScreen: Target,
+ val isCounterFinished: (Event) -> Boolean,
+)
+
+private fun paramsRootNode(spec: ParamsSpec, payload: String?) = TestFlowNode(
+ initialTarget = spec.paramsScreen,
+ payload = payload,
+ transitions = listOf(
+ tr("C", spec.counter(null)),
+ tr("C7", spec.counter(7)),
+ TestFlowTransitionSpec(spec.isCounterFinished, NavigateTo(spec.paramsScreen)),
+ ),
+)
+
+private fun counterNode(spec: ParamsSpec, payload: Int?) = TestFlowNode(
+ initialTarget = spec.counterScreen,
+ payload = payload,
+ transitions = listOf(tr("F", Finish(Unit))),
+)
+
+private fun generatedParamsBuilder(): NodeBuilder {
+ val spec = ParamsSpec(
+ paramsScreen = Target.params.paramsScreen,
+ counter = { Target.params.counter(it) },
+ counterScreen = Target.counter.counterScreen,
+ isCounterFinished = { it == ParamsChildFinishRequest.Counter },
+ )
+ return ParamsNodeBuilder(
+ object : ParamsNodeBuilder.Factory {
+ override fun createRootNode(name: String?) = paramsRootNode(spec, name)
+ override fun createParamsScreenNode() = TestScreenNode()
+ override fun createCounterNodeBuilder(start: Int?): NodeBuilder = CounterNodeBuilder(
+ object : CounterNodeBuilder.Factory {
+ override fun createRootNode(start: Int?) = counterNode(spec, start)
+ override fun createCounterScreenNode() = TestScreenNode()
+ },
+ DslParityCounterSchema(),
+ )
+ },
+ DslParityParamsSchema(DslParityCounterSchema()),
+ )
+}
+
+private fun dslParamsBuilder(): NodeBuilder {
+ val spec = ParamsSpec(
+ paramsScreen = ParamsGraph.paramsScreen.target(),
+ counter = { ParamsGraph.counter.target(it) },
+ counterScreen = CounterGraph.counterScreen.target(),
+ isCounterFinished = { it.childFlowResult(ParamsGraph.counter) != null },
+ )
+ return ParamsGraph.nodeBuilder {
+ flow(ParamsGraph.params) { paramsRootNode(spec, it) }
+ screen(ParamsGraph.paramsScreen) { TestScreenNode() }
+ include(ParamsGraph.counter) {
+ CounterGraph.nodeBuilder {
+ flow(CounterGraph.counter) { counterNode(spec, it) }
+ screen(CounterGraph.counterScreen) { TestScreenNode() }
+ }
+ }
+ }
+}
+
+private class HistorySpec(
+ val home: Target,
+ val shop: Target,
+ val cart: Target,
+ val checkout: Target,
+ val cartHistory: Target,
+ val cartDeepHistory: Target,
+)
+
+private fun histRootNode(spec: HistorySpec) = TestFlowNode(
+ initialTarget = spec.home,
+ transitions = listOf(
+ tr("S", spec.shop),
+ tr("H", spec.home),
+ tr("R", spec.cartHistory),
+ tr("D", spec.cartDeepHistory),
+ ),
+)
+
+private fun shopNode(spec: HistorySpec) = TestFlowNode(
+ initialTarget = spec.cart,
+ transitions = listOf(tr("C", spec.checkout)),
+)
+
+private fun generatedHistoryBuilder(): NodeBuilder {
+ val spec = HistorySpec(
+ home = Target.hist.home,
+ shop = Target.hist.shop,
+ cart = Target.shop.cart,
+ checkout = Target.shop.checkout,
+ cartHistory = Target.shop.cartHistory,
+ cartDeepHistory = Target.shop.cartDeepHistory,
+ )
+ val schema = DslParityHistorySchema()
+ return HistNodeBuilder(
+ object : HistNodeBuilder.Factory {
+ override fun createRootNode() = histRootNode(spec)
+ override fun createHomeNode() = TestScreenNode()
+
+ // way#19: the generated ShopNodeBuilder duplicates the root segment of the nested flow, built by hand
+ override fun createShopNodeBuilder(): NodeBuilder = TestNodeBuilder(
+ schema,
+ mapOf("shop" to shopNode(spec), "shop.cart" to TestScreenNode(), "shop.cart.checkout" to TestScreenNode()),
+ )
+ },
+ schema,
+ )
+}
+
+private fun dslHistoryBuilder(): NodeBuilder {
+ val spec = HistorySpec(
+ home = HistoryGraph.home.target(),
+ shop = HistoryGraph.shop.target(),
+ cart = HistoryGraph.cart.target(),
+ checkout = HistoryGraph.checkout.target(),
+ cartHistory = HistoryGraph.cartHistory.target(),
+ cartDeepHistory = HistoryGraph.cartDeepHistory.target(),
+ )
+ return HistoryGraph.nodeBuilder {
+ flow(HistoryGraph.hist) { histRootNode(spec) }
+ screen(HistoryGraph.home) { TestScreenNode() }
+ flow(HistoryGraph.shop) { shopNode(spec) }
+ screen(HistoryGraph.cart) { TestScreenNode() }
+ screen(HistoryGraph.checkout) { TestScreenNode() }
+ }
+}
+
+private class NestedSpec(
+ val start: Target,
+ val tabs: Target,
+ /** Only in the DSL graph: the generated one can't enter a parallel flow with a history child. */
+ val tabsHistory: Target?,
+ val leftScreen: Target,
+ val leftDetails: Target,
+ val inner: Target,
+ val rightScreen: Target,
+ val feedScreen: Target,
+)
+
+private fun mainRootNode(spec: NestedSpec) = TestFlowNode(
+ initialTarget = spec.start,
+ transitions = listOfNotNull(tr("T", spec.tabs), tr("B", spec.start), spec.tabsHistory?.let { tr("TH", it) }),
+)
+
+private fun leftNode(spec: NestedSpec) = TestFlowNode(
+ initialTarget = spec.leftScreen,
+ transitions = listOf(tr("LD", spec.leftDetails), tr("I", spec.inner)),
+)
+
+private fun feedBuilder(feedScreen: Target): NodeBuilder = FeedNodeBuilder(
+ object : FeedNodeBuilder.Factory {
+ override fun createRootNode() = TestFlowNode(initialTarget = feedScreen)
+ override fun createFeedScreenNode() = TestScreenNode()
+ },
+ DslParityFeedSchema(),
+)
+
+private fun generatedNestedBuilder(): NodeBuilder {
+ val spec = NestedSpec(
+ start = Target.main.start,
+ tabs = Target.main.tabs,
+ tabsHistory = null,
+ leftScreen = Target.left.leftScreen,
+ leftDetails = Target.left.leftDetails,
+ inner = Target.main.inner,
+ rightScreen = Target.right.rightScreen,
+ feedScreen = Target.feed.feedScreen,
+ )
+ val innerBuilder = {
+ InnerNodeBuilder(
+ object : InnerNodeBuilder.Factory {
+ override fun createRootNode() = TestParallelNode()
+ override fun createFeedNodeBuilder() = feedBuilder(spec.feedScreen)
+ override fun createRightNodeBuilder(): NodeBuilder = RightNodeBuilder(
+ object : RightNodeBuilder.Factory {
+ override fun createRootNode() = TestFlowNode(initialTarget = spec.rightScreen)
+ override fun createRightScreenNode() = TestScreenNode()
+ },
+ RightSchema(),
+ )
+ },
+ InnerSchema(DslParityFeedSchema()),
+ )
+ }
+ return MainNodeBuilder(
+ object : MainNodeBuilder.Factory {
+ override fun createRootNode() = mainRootNode(spec)
+ override fun createStartNode() = TestScreenNode()
+ override fun createTabsNodeBuilder(): NodeBuilder = NestedTabsNodeBuilder(
+ object : NestedTabsNodeBuilder.Factory {
+ override fun createRootNode() = TestParallelNode()
+ override fun createInnerNodeBuilder(): NodeBuilder = innerBuilder()
+ override fun createLeftNodeBuilder(): NodeBuilder = LeftNodeBuilder(
+ object : LeftNodeBuilder.Factory {
+ override fun createRootNode() = leftNode(spec)
+ override fun createInnerNodeBuilder(): NodeBuilder = innerBuilder()
+ override fun createLeftScreenNode() = TestScreenNode()
+ override fun createLeftDetailsNode() = TestScreenNode()
+ },
+ LeftSchema(DslParityFeedSchema()),
+ )
+ },
+ TabsSchema(DslParityFeedSchema()),
+ )
+ },
+ DslParityNestedSchema(DslParityFeedSchema()),
+ )
+}
+
+private fun dslNestedBuilder(): NodeBuilder {
+ val spec = NestedSpec(
+ start = NestedGraph.start.target(),
+ tabs = NestedGraph.tabs.target(),
+ tabsHistory = NestedGraph.tabsHistory.target(),
+ leftScreen = NestedGraph.leftScreen.target(),
+ leftDetails = NestedGraph.leftDetails.target(),
+ inner = NestedGraph.inner.target(),
+ rightScreen = NestedGraph.rightScreen.target(),
+ feedScreen = FeedGraph.feedScreen.target(),
+ )
+ return NestedGraph.nodeBuilder {
+ flow(NestedGraph.main) { mainRootNode(spec) }
+ screen(NestedGraph.start) { TestScreenNode() }
+ parallel(NestedGraph.tabs) { TestParallelNode() }
+ flow(NestedGraph.left) { leftNode(spec) }
+ screen(NestedGraph.leftScreen) { TestScreenNode() }
+ screen(NestedGraph.leftDetails) { TestScreenNode() }
+ parallel(NestedGraph.inner) { TestParallelNode() }
+ flow(NestedGraph.right) { TestFlowNode(initialTarget = spec.rightScreen) }
+ screen(NestedGraph.rightScreen) { TestScreenNode() }
+ include(NestedGraph.feed) {
+ FeedGraph.nodeBuilder {
+ flow(FeedGraph.feed) { TestFlowNode(initialTarget = spec.feedScreen) }
+ screen(FeedGraph.feedScreen) { TestScreenNode() }
+ }
+ }
+ }
+}
+
+private class FanInSpec(
+ val a: (Int) -> Target,
+ val b: (String) -> Target,
+ val permViaA: (String) -> Target,
+ val permViaB: (String) -> Target,
+ val permDetails: Target,
+ val permIntro: Target,
+ val permResult: (Event) -> String?,
+)
+
+private fun sharedRootNode(spec: FanInSpec) = TestFlowNode(
+ initialTarget = spec.a(1),
+ transitions = listOf(
+ tr("PA", spec.permViaA("x")),
+ tr("PB", spec.permViaB("y")),
+ TestFlowTransitionSpec({ spec.permResult(it) != null }, NavigateTo(spec.b("after"))),
+ ),
+)
+
+private fun permNode(spec: FanInSpec, reason: String) = TestFlowNodeWithResult(
+ initialTarget = spec.permIntro,
+ dismissResult = "dismissed",
+ payload = reason,
+ transitions = listOf(tr("PD", spec.permDetails), tr("F", Finish("granted"))),
+)
+
+private fun generatedFanInBuilder(): NodeBuilder {
+ val spec = FanInSpec(
+ a = { Target.shared.a(it) },
+ b = { Target.shared.b(it) },
+ permViaA = { Target.shared.permViaA(it) },
+ permViaB = { Target.shared.permViaB(it) },
+ permIntro = Target.perm.permIntro,
+ permDetails = Target.perm.permDetails,
+ permResult = { (it as? SharedChildFinishRequest.Perm)?.result },
+ )
+ return SharedNodeBuilder(
+ object : SharedNodeBuilder.Factory {
+ override fun createRootNode() = sharedRootNode(spec)
+ 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) = permNode(spec, reason)
+ override fun createPermIntroNode() = TestScreenNode()
+ override fun createPermDetailsNode() = TestScreenNode()
+ },
+ DslParityPermSchema(),
+ )
+ },
+ DslParityFanInSchema(DslParityPermSchema()),
+ )
+}
+
+private fun dslFanInBuilder(): NodeBuilder {
+ val spec = FanInSpec(
+ a = { FanInGraph.a.target(it) },
+ b = { FanInGraph.b.target(it) },
+ permViaA = { FanInGraph.perm.target(it, via = FanInGraph.a) },
+ permViaB = { FanInGraph.perm.target(it, via = FanInGraph.b) },
+ permIntro = PermGraph.permIntro.target(),
+ permDetails = PermGraph.permDetails.target(),
+ permResult = { it.childFlowResult(FanInGraph.perm) },
+ )
+ return FanInGraph.nodeBuilder {
+ flow(FanInGraph.shared) { sharedRootNode(spec) }
+ screen(FanInGraph.a) { TestScreenNode(payload = it) }
+ screen(FanInGraph.b) { TestScreenNode(payload = it) }
+ include(FanInGraph.perm) {
+ PermGraph.nodeBuilder {
+ flow(PermGraph.perm) { permNode(spec, it) }
+ screen(PermGraph.permIntro) { TestScreenNode() }
+ screen(PermGraph.permDetails) { TestScreenNode() }
+ }
+ }
+ }
+}
+
+/** Everything a test can observe after each step: per region the active path, the alive paths and their payloads. */
+private fun NavigationState.describe(): List = regions.values.map { region ->
+ val payloads = region.alive.joinToString { path ->
+ val payload = when (val node = region.nodes[path]) {
+ is TestFlowNode -> node.payload
+ is TestFlowNodeWithResult<*> -> node.payload
+ is TestScreenNode -> node.payload
+ else -> null
+ }
+ "$path=$payload"
+ }
+ "${region.active} [$payloads]"
+}
+
+/** Runs [events] on a service built by [nodeBuilder], returns the states after the start and after every event. */
+private fun run(nodeBuilder: NodeBuilder, rootPayload: Any?, events: List): Pair>, Boolean> {
+ var finished = false
+ val service = NavigationService(nodeBuilder, onFinishRequest = {
+ finished = true
+ Ignore
+ })
+ service.strictEventDropping = true
+ val states = mutableListOf>()
+ service.addTransitionListener { states.add(it.describe()) }
+ service.start(rootPayload)
+ events.forEach { service.send(TestEvent(it)) }
+ return states to finished
+}
+
+class DslParityTest :
+ ShouldSpec({
+ should("navigate a flow with an included graph as its generated counterpart does") {
+ val events = listOf("D", "S", "F", "L", "O", "F")
+
+ val (generated, _) = run(generatedAppBuilder(), rootPayload = 42, events)
+ val (dsl, _) = run(dslAppBuilder(), rootPayload = 42, events)
+
+ dsl shouldBe generated
+ // as in the generated graph, finishing a flow emits two states
+ dsl.map { it.single().substringBefore(' ') } shouldContainExactly listOf(
+ "app.intro",
+ "app.intro.details",
+ "app.settings.general",
+ "app.settings.general",
+ "app.intro.details",
+ "app.login.credentials",
+ "app.login.credentials.otp",
+ "app.login.credentials.otp",
+ "app.intro",
+ )
+ dsl[4].single() shouldBe "app.intro.details [app=42, app.intro=null, app.intro.details=from-settings]"
+ dsl[6].single() shouldBe
+ "app.login.credentials.otp [app=42, app.login=alice, app.login.credentials=null, app.login.credentials.otp=7]"
+ }
+
+ should("navigate a parallel flow with included regions as its generated counterpart does") {
+ val events = listOf("HD", "HF")
+
+ val (generated, generatedFinished) = run(generatedTabsBuilder(), rootPayload = null, events)
+ val (dsl, dslFinished) = run(dslTabsBuilder(), rootPayload = null, events)
+
+ dsl shouldBe generated
+ dsl.first().map { it.substringBefore(' ') } shouldContainExactly
+ listOf("tabs.home.homeScreen", "tabs.feed.feedScreen")
+ dsl[1].map { it.substringBefore(' ') } shouldContainExactly
+ listOf("tabs.home.homeScreen.homeDetails", "tabs.feed.feedScreen")
+ dslFinished shouldBe true
+ generatedFinished shouldBe true
+ }
+ should("pass typed and nullable payloads as the generated graph does") {
+ val events = listOf("C", "F", "C7", "F")
+ for (rootPayload in listOf(null, "bob")) {
+ val (generated, _) = run(generatedParamsBuilder(), rootPayload, events)
+ val (dsl, _) = run(dslParamsBuilder(), rootPayload, events)
+
+ dsl shouldBe generated
+ dsl.map { it.single().substringBefore(' ') } shouldContainExactly listOf(
+ "params.paramsScreen",
+ "params.paramsScreen.counter.counterScreen",
+ "params.paramsScreen.counter.counterScreen",
+ "params.paramsScreen",
+ "params.paramsScreen.counter.counterScreen",
+ "params.paramsScreen.counter.counterScreen",
+ "params.paramsScreen",
+ )
+ dsl[1].single() shouldContain "params=$rootPayload, params.paramsScreen=null, params.paramsScreen.counter=null,"
+ dsl[4].single() shouldContain "params.paramsScreen.counter=7,"
+ }
+ }
+
+ should("navigate to history nodes as the generated graph does") {
+ val events = listOf("S", "C", "H", "D", "H", "R")
+
+ val (generated, _) = run(generatedHistoryBuilder(), rootPayload = null, events)
+ val (dsl, _) = run(dslHistoryBuilder(), rootPayload = null, events)
+
+ dsl shouldBe generated
+ // the deep history restores checkout, the shallow one only the direct child of shop
+ dsl.map { it.single().substringBefore(' ') } shouldContainExactly listOf(
+ "hist.home",
+ "hist.shop.cart",
+ "hist.shop.cart.checkout",
+ "hist.home",
+ "hist.shop.cart.checkout",
+ "hist.home",
+ "hist.shop.cart",
+ )
+ }
+
+ should("navigate nested parallel flows as the generated graph does") {
+ val events = listOf("T", "LD", "I", "B")
+
+ val (generated, _) = run(generatedNestedBuilder(), rootPayload = null, events)
+ val (dsl, _) = run(dslNestedBuilder(), rootPayload = null, events)
+
+ dsl shouldBe generated
+ dsl[3].map { it.substringBefore(' ') } shouldContainExactly listOf(
+ "main.tabs",
+ "main.tabs.left.inner",
+ "main.tabs.left.inner.right.rightScreen",
+ "main.tabs.left.inner.feed.feedScreen",
+ )
+ dsl[4].single() shouldStartWith "main.start "
+ // the deep history of the outer parallel flow restores its regions, the nested ones included
+ val (withHistory, _) = run(dslNestedBuilder(), rootPayload = null, events + "TH")
+ withHistory.last() shouldBe dsl[3]
+ }
+
+ should("enter an included graph from each of its parents as the generated graph does") {
+ val events = listOf("PA", "PD", "F", "PB", "F")
+
+ val (generated, _) = run(generatedFanInBuilder(), rootPayload = null, events)
+ val (dsl, _) = run(dslFanInBuilder(), rootPayload = null, events)
+
+ dsl shouldBe generated
+ dsl.map { it.single().substringBefore(' ') } shouldContainExactly listOf(
+ "shared.a",
+ "shared.a.perm.permIntro",
+ "shared.a.perm.permIntro.permDetails",
+ "shared.a.perm.permIntro.permDetails",
+ "shared.b",
+ "shared.b.perm.permIntro",
+ "shared.b.perm.permIntro",
+ "shared.b",
+ )
+ dsl[1].single() shouldContain "shared.a.perm=x,"
+ dsl[5].single() shouldContain "shared.b=after, shared.b.perm=y,"
+ }
+ })
diff --git a/way-dsl/src/commonTest/kotlin/ru/kode/way/dsl/GraphTest.kt b/way-dsl/src/commonTest/kotlin/ru/kode/way/dsl/GraphTest.kt
new file mode 100644
index 0000000..17cebf1
--- /dev/null
+++ b/way-dsl/src/commonTest/kotlin/ru/kode/way/dsl/GraphTest.kt
@@ -0,0 +1,522 @@
+package ru.kode.way.dsl
+
+import io.kotest.assertions.throwables.shouldThrow
+import io.kotest.core.spec.style.ShouldSpec
+import io.kotest.matchers.collections.shouldContainExactly
+import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder
+import io.kotest.matchers.nulls.shouldBeNull
+import io.kotest.matchers.shouldBe
+import io.kotest.matchers.string.shouldContain
+import ru.kode.way.FlowTarget
+import ru.kode.way.HistoryTarget
+import ru.kode.way.MissingPayloadException
+import ru.kode.way.NullPayload
+import ru.kode.way.Path
+import ru.kode.way.Schema
+import ru.kode.way.ScreenTarget
+import ru.kode.way.Segment
+import ru.kode.way.TestEvent
+import ru.kode.way.TestFlowNode
+import ru.kode.way.TestFlowNodeWithResult
+import ru.kode.way.TestScreenNode
+import ru.kode.way.name
+
+private class FlowGraph : Graph("DslFlow") {
+ val root = flow("root")
+ val list = screen("list")
+ val item = parameterizedScreen("item")
+ val edit = parameterizedFlow("edit")
+ val form = screen("form")
+
+ init {
+ root to list to item
+ item to edit to form
+ }
+}
+
+private class PermissionGraph : Graph("DslPermission") {
+ val permission = parameterizedFlow("permission")
+ val rationale = screen("rationale")
+
+ init {
+ permission to rationale
+ }
+}
+
+private class MultiParentGraph : Graph("DslFanIn") {
+ val root = flow("root")
+ val a = screen("a")
+ val b = parameterizedScreen("b")
+ val permission = include("permission", PermissionGraph().permission)
+
+ init {
+ root to a to permission
+ root to b to permission
+ }
+}
+
+private class HistGraph : Graph("DslHist") {
+ val root = flow("root")
+ val home = screen("home")
+ val shop = flow("shop")
+ val cart = screen("cart")
+ val shopHistory = history("shopHistory")
+ val shopDeepHistory = deepHistory("shopDeepHistory")
+
+ init {
+ root to home
+ root to shop to cart
+ shop to shopHistory
+ shop to shopDeepHistory
+ }
+}
+
+private class NestedParallelGraph : Graph("DslNest") {
+ val main = flow("main")
+ val start = screen("start")
+ val tabs = parallel("tabs")
+ val left = flow("left")
+ val leftScreen = screen("leftScreen")
+ val inner = parameterizedParallel("inner")
+ val right = flow("right")
+ val rightScreen = screen("rightScreen")
+ val feed = include("feed", FlowGraph().root)
+ val tabsHistory = deepHistory("tabsHistory")
+
+ init {
+ main to start
+ main to tabs
+ tabs to left to leftScreen
+ left to inner
+ inner to right to rightScreen
+ inner to feed
+ tabs to tabsHistory
+ }
+}
+
+class GraphTest :
+ ShouldSpec({
+ should("build a schema with targets relative to the closest flow") {
+ val graph = FlowGraph()
+ val schema = graph.schema
+ val region = schema.regions.single()
+
+ schema.rootSegment shouldBe graph.root.segment
+ graph.item.target(3) shouldBe ScreenTarget(Path(listOf(graph.list.segment, graph.item.segment)), 3)
+ graph.item.target(null) shouldBe ScreenTarget(Path(listOf(graph.list.segment, graph.item.segment)), NullPayload)
+ graph.edit.target("a") shouldBe
+ FlowTarget(Path(listOf(graph.list.segment, graph.item.segment, graph.edit.segment)), "a")
+ graph.form.target() shouldBe ScreenTarget(Path(graph.form.segment))
+
+ val formPath = schema.target(region, graph.form.segment, rootSegmentAlias = null)!!
+ formPath.toString() shouldBe "root.list.item.edit.form"
+ schema.nodeType(region, formPath, null) shouldBe Schema.NodeType.Screen
+ schema.isParameterized(region, formPath, null) shouldBe false
+ val editPath = schema.target(region, graph.edit.segment, null)!!
+ schema.nodeType(region, editPath, null) shouldBe Schema.NodeType.Flow
+ schema.isParameterized(region, editPath, null) shouldBe true
+ schema.target(region, Segment("form@Other"), null).shouldBeNull()
+ }
+
+ should("report the result of a finished child flow") {
+ val graph = FlowGraph()
+ val region = graph.schema.regions.single()
+ val editPath = graph.schema.target(region, graph.edit.segment, null)!!
+ val event = graph.schema.createChildFlowFinishRequestEvent(region, editPath, "saved")
+
+ event.childFlowResult(graph.edit) shouldBe "saved"
+ TestEvent("x").childFlowResult(graph.edit).shouldBeNull()
+ }
+
+ should("pass payloads to the factories and throw for a missing one") {
+ val graph = FlowGraph()
+ val payloads = mutableListOf()
+ val nodeBuilder = graph.nodeBuilder {
+ flow(graph.root) { TestFlowNode(graph.list.target()) }
+ screen(graph.list) { TestScreenNode() }
+ screen(graph.item) { TestScreenNode(payload = it).also { _ -> payloads.add(it) } }
+ flow(graph.edit) { TestFlowNodeWithResult(graph.form.target(), dismissResult = "", payload = it) }
+ screen(graph.form) { TestScreenNode() }
+ }
+ val region = graph.schema.regions.single()
+ val itemPath = graph.schema.target(region, graph.item.segment, null)!!
+ val editPath = graph.schema.target(region, graph.edit.segment, null)!!
+
+ nodeBuilder.build(itemPath, mapOf(itemPath to NullPayload), null)
+ nodeBuilder.build(itemPath, mapOf(itemPath to 5), null)
+ (nodeBuilder.build(editPath, mapOf(editPath to "e"), null) as TestFlowNodeWithResult<*>).payload shouldBe "e"
+ payloads shouldBe listOf(null, 5)
+ shouldThrow { nodeBuilder.build(editPath, emptyMap(), null) }.path shouldBe editPath
+ }
+
+ should("require a factory for every node") {
+ val graph = FlowGraph()
+
+ shouldThrow {
+ graph.nodeBuilder { flow(graph.root) { TestFlowNode(graph.list.target()) } }
+ }.message shouldContain "list, item, edit, form"
+ shouldThrow {
+ graph.nodeBuilder { screen(FlowGraph().list) { TestScreenNode() } }
+ }.message shouldContain "does not belong"
+ }
+
+ should("reject an invalid graph") {
+ fun invalid(build: () -> Graph) = shouldThrow { build().schema }.message!!
+
+ invalid {
+ object : Graph("G") {
+ val a = flow("a")
+ val b = flow("b")
+ }
+ } shouldContain "must have one root"
+ invalid {
+ object : Graph("G") {
+ val a = screen("a")
+ val b = screen("b")
+
+ init {
+ a to b
+ }
+ }
+ } shouldContain "must be a flow"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val a = screen("a")
+ val b = screen("b")
+
+ init {
+ a to b
+ b to a
+ }
+ }
+ } shouldContain "cycle"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ }
+ } shouldContain "a flow must have at least one child"
+ invalid {
+ object : Graph("G") {
+ val p = parallel("p")
+ val s = screen("s")
+
+ init {
+ p to s
+ }
+ }
+ } shouldContain "must be flows, parallel flows or included graphs"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val i = include("i", FlowGraph().root)
+ val s = screen("s")
+
+ init {
+ r to i to s
+ }
+ }
+ } shouldContain "can't have children"
+ shouldThrow {
+ object : Graph("G") {
+ val a = flow("a")
+ val b = screen("a")
+ }
+ }.message shouldContain "declared twice"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val a = screen("a")
+ val b = screen("b")
+
+ init {
+ r to a
+ r to b to a
+ }
+ }
+ } shouldContain "several parents (fan-in): a, only an included graph can have several parents"
+ shouldThrow {
+ object : Graph("G") {
+ val r = flow("r")
+ val a = screen("a")
+
+ init {
+ r to a
+ r to a
+ }
+ }
+ }.message shouldContain "is declared twice"
+ shouldThrow {
+ object : Graph("G") {
+ val i = include("i", FlowGraph().edit)
+ }
+ }.message shouldContain "'edit' is not the root of graph 'DslFlow'"
+ }
+ should("pass typed payloads to the factories, null for a missing payload of a nullable root") {
+ val graph = object : Graph("Nullable") {
+ val root = parameterizedFlow("root")
+ val list = screen("list")
+
+ init {
+ root to list
+ }
+ }
+ val payloads = mutableListOf()
+ val nodeBuilder = graph.nodeBuilder {
+ flow(graph.root) { payload: String? ->
+ TestFlowNode(graph.list.target(), payload = payload.also(payloads::add))
+ }
+ screen(graph.list) { TestScreenNode() }
+ }
+ val region = graph.schema.regions.single()
+ val rootPath = Path(graph.root.segment)
+
+ graph.schema.isParameterized(region, rootPath, null) shouldBe false
+ nodeBuilder.build(rootPath, emptyMap(), null)
+ nodeBuilder.build(rootPath, mapOf(rootPath to NullPayload), null)
+ nodeBuilder.build(rootPath, mapOf(rootPath to "a"), null)
+ payloads shouldBe listOf(null, null, "a")
+ graph.root.target(null) shouldBe FlowTarget(rootPath, NullPayload)
+ FlowGraph().let { it.root.target() shouldBe FlowTarget(Path(it.root.segment)) }
+ }
+
+ should("pass the payload of an included graph to its factory and throw for a missing one") {
+ val graph = MultiParentGraph()
+ val included = mutableListOf()
+ val nodeBuilder = graph.nodeBuilder {
+ flow(graph.root) { TestFlowNode(graph.a.target()) }
+ screen(graph.a) { TestScreenNode() }
+ screen(graph.b) { id: Int -> TestScreenNode(payload = id) }
+ include(graph.permission) { reason: String ->
+ included.add(reason)
+ val permission = graph.permission.included as PermissionGraph
+ permission.nodeBuilder {
+ flow(permission.permission) { TestFlowNodeWithResult(permission.rationale.target(), false, payload = it) }
+ screen(permission.rationale) { TestScreenNode() }
+ }
+ }
+ }
+ val path = Path(listOf(graph.root.segment, graph.a.segment, graph.permission.segment))
+
+ val node = nodeBuilder.build(path, mapOf(path to "camera"), null) as TestFlowNodeWithResult<*>
+ node.payload shouldBe "camera"
+ included shouldBe listOf("camera")
+ val otherPath = Path(listOf(graph.root.segment, graph.b.segment, graph.permission.segment))
+ shouldThrow { nodeBuilder.build(otherPath, emptyMap(), null) }.path shouldBe otherPath
+ }
+
+ should("target the parent of a history node and leave it out of the schema") {
+ val graph = HistGraph()
+ val schema = graph.schema
+ val region = schema.regions.single()
+ val shopPath = Path(listOf(graph.root.segment, graph.shop.segment))
+
+ graph.shopHistory.deep shouldBe false
+ graph.shopHistory.target() shouldBe HistoryTarget(shopPath, deep = false)
+ graph.shopDeepHistory.target() shouldBe HistoryTarget(shopPath, deep = true)
+ graph.shopHistory.target(prefix = Path("app")) shouldBe
+ HistoryTarget(Path(listOf(Segment("app"), graph.root.segment, graph.shop.segment)), deep = false)
+ schema.target(region, graph.shopHistory.segment, null).shouldBeNull()
+ schema.target(region, graph.cart.segment, null).toString() shouldBe "root.shop.cart"
+ // history nodes are never built, so they need no factory
+ graph.nodeBuilder {
+ flow(graph.root) { TestFlowNode(graph.home.target()) }
+ screen(graph.home) { TestScreenNode() }
+ flow(graph.shop) { TestFlowNode(graph.cart.target()) }
+ screen(graph.cart) { TestScreenNode() }
+ }
+ }
+
+ should("reject a history node out of place") {
+ fun invalid(build: () -> Graph) = shouldThrow { build().schema }.message!!
+
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val s = screen("s")
+ val h = history("h")
+
+ init {
+ r to s
+ }
+ }
+ } shouldContain "history node 'h' of graph 'G' has no parent flow"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val h = history("h")
+ val s = screen("s")
+
+ init {
+ r to h to s
+ }
+ }
+ } shouldContain "must be a leaf, but has children: s"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val s = screen("s")
+ val h = history("h")
+
+ init {
+ r to s to h
+ }
+ }
+ } shouldContain "its parent 's' is not"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val h = history("h")
+ val i = include("i", FlowGraph().root)
+
+ init {
+ r to i to h
+ }
+ }
+ } shouldContain "history under an included graph or a screen is not supported"
+ invalid {
+ object : Graph("G") {
+ val p = parallel("p")
+ val f = flow("f")
+ val s = screen("s")
+ val h = history("h")
+
+ init {
+ p to f to s
+ p to h
+ }
+ }
+ } shouldContain "is under the parallel 'p' with no flow above it"
+ }
+
+ should("build regions and sub-schemas of nested parallel flows") {
+ val graph = NestedParallelGraph()
+ val schema = graph.schema
+
+ schema.regions.map { it.path.toString() } shouldContainExactly
+ listOf("main", "main.tabs.left", "main.tabs.left.inner.right", "main.tabs.left.inner.feed")
+ schema.childSchemas.keys.map { it.name } shouldContainExactlyInAnyOrder
+ listOf("tabs", "left", "inner", "right", "feed")
+ schema.childSchemas.getValue(graph.tabs.segment).regions.map { it.path.toString() } shouldContainExactly
+ listOf("tabs.left", "tabs.left.inner.right", "tabs.left.inner.feed")
+ schema.childSchemas.getValue(graph.inner.segment).regions.map { it.path.toString() } shouldContainExactly
+ listOf("inner.right", "inner.feed")
+
+ val region = schema.regions.first()
+ val innerPath = schema.target(region, graph.inner.segment, null)!!
+ innerPath.toString() shouldBe "main.tabs.left.inner"
+ schema.nodeType(region, innerPath, null) shouldBe Schema.NodeType.ParallelFlow
+ schema.isParameterized(region, innerPath, null) shouldBe true
+ graph.inner.target(3) shouldBe FlowTarget(Path(graph.inner.segment), 3)
+ graph.tabsHistory.target() shouldBe
+ HistoryTarget(Path(listOf(graph.main.segment, graph.tabs.segment)), deep = true)
+ }
+
+ should("reject a parallel flow without children") {
+ fun invalid(build: () -> Graph) = shouldThrow { build().schema }.message!!
+
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val p = parallel("p")
+
+ init {
+ r to p
+ }
+ }
+ } shouldContain "parallel 'p' of graph 'G' has no children"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val p = parallel("p")
+ val h = history("h")
+
+ init {
+ r to p to h
+ }
+ }
+ } shouldContain "parallel 'p' of graph 'G' has no children"
+ }
+
+ should("give every path of an included graph with several parents") {
+ val graph = MultiParentGraph()
+ val schema = graph.schema
+ val region = schema.regions.single()
+
+ schema.targets(region, graph.permission.segment, null).map { it.toString() } shouldContainExactly
+ listOf("root.a.permission", "root.b.permission")
+ graph.permission.target("camera", via = graph.a) shouldBe
+ FlowTarget(Path(listOf(graph.a.segment, graph.permission.segment)), "camera")
+ graph.permission.target("camera", via = graph.b) shouldBe
+ FlowTarget(Path(listOf(graph.b.segment, graph.permission.segment)), "camera")
+ shouldThrow { graph.permission.target("camera") }.message shouldContain
+ "pass the one to enter it from as `via`"
+ shouldThrow {
+ graph.permission.target("camera", via = graph.root)
+ }.message shouldContain
+ "'root' is not a parent of 'permission'"
+ }
+
+ should("reject several parents out of place") {
+ fun invalid(build: () -> Graph) = shouldThrow { build().schema }.message!!
+
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val a = screen("a")
+ val b = screen("b")
+ val f = flow("f")
+ val s = screen("s")
+
+ init {
+ r to a to f to s
+ r to b to f
+ }
+ }
+ } shouldContain "only an included graph can have several parents"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val p = parallel("p")
+ val f = flow("f")
+ val s = screen("s")
+ val i = include("i", FlowGraph().root)
+
+ init {
+ r to p to f to s to i
+ p to i
+ }
+ }
+ } shouldContain "has several parents, one of which is the parallel 'p'"
+ invalid {
+ object : Graph("G") {
+ val r = flow("r")
+ val p = parallel("p")
+ val f1 = flow("f1")
+ val s1 = screen("s1")
+ val f2 = flow("f2")
+ val s2 = screen("s2")
+ val i = include("i", FlowGraph().root)
+
+ init {
+ r to p to f1 to s1 to i
+ p to f2 to s2 to i
+ }
+ }
+ } shouldContain "has parents in different parallel regions (s1, s2)"
+ // parents in one region of a parallel flow are fine
+ object : Graph("G") {
+ val r = flow("r")
+ val p = parallel("p")
+ val f = flow("f")
+ val s1 = screen("s1")
+ val s2 = screen("s2")
+ val i = include("i", FlowGraph().root)
+
+ init {
+ r to p to f to s1 to i
+ f to s2 to i
+ }
+ }.schema.regions.map { it.path.toString() } shouldContainExactly listOf("r", "r.p.f")
+ }
+ })
diff --git a/way-dsl/src/commonTest/way/dsl-parity-app.dot b/way-dsl/src/commonTest/way/dsl-parity-app.dot
new file mode 100644
index 0000000..ae14ba0
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-app.dot
@@ -0,0 +1,13 @@
+digraph DslParityApp {
+ package = "ru.kode.way.dslparity"
+
+ // Mirrored by DslParityGraphs.kt: the same navigation has to happen with the generated and the DSL graph.
+ app [type = flow, parameterName = timeout, parameterType = "kotlin.Int"]
+ details [parameterName = id, parameterType = "kotlin.String?"]
+ settings [type = flow, resultType = "kotlin.String"]
+ login [type = schema, parameterName = userName, parameterType = "kotlin.String", resultType = "kotlin.Int"]
+
+ app -> intro -> details
+ app -> settings -> general
+ app -> login
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-counter.dot b/way-dsl/src/commonTest/way/dsl-parity-counter.dot
new file mode 100644
index 0000000..16ed79f
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-counter.dot
@@ -0,0 +1,7 @@
+digraph DslParityCounter {
+ package = "ru.kode.way.dslparity.counter"
+
+ counter [type = flow, parameterName = start, parameterType = "kotlin.Int?"]
+
+ counter -> counterScreen
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-fanin.dot b/way-dsl/src/commonTest/way/dsl-parity-fanin.dot
new file mode 100644
index 0000000..fe601e4
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-fanin.dot
@@ -0,0 +1,12 @@
+digraph DslParityFanIn {
+ package = "ru.kode.way.dslparity.fanin"
+
+ // Mirrored by DslParityTest.kt: an imported schema entered from two parents.
+ shared [type = flow]
+ a [parameterName = aId, parameterType = "kotlin.Int"]
+ b [parameterName = bId, parameterType = "kotlin.String"]
+ perm [type = schema, parameterName = reason, parameterType = "kotlin.String", resultType = "kotlin.String"]
+
+ shared -> a -> perm
+ shared -> b -> perm
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-feed.dot b/way-dsl/src/commonTest/way/dsl-parity-feed.dot
new file mode 100644
index 0000000..2afc7c4
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-feed.dot
@@ -0,0 +1,7 @@
+digraph DslParityFeed {
+ package = "ru.kode.way.dslparity.feed"
+
+ feed [type = flow]
+
+ feed -> feedScreen
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-history.dot b/way-dsl/src/commonTest/way/dsl-parity-history.dot
new file mode 100644
index 0000000..413a834
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-history.dot
@@ -0,0 +1,14 @@
+digraph DslParityHistory {
+ package = "ru.kode.way.dslparity.history"
+
+ // Mirrored by DslParityTest.kt: a shallow and a deep history of a nested flow.
+ hist [type = flow]
+ shop [type = flow]
+ cartHistory [type = history]
+ cartDeepHistory [type = deepHistory]
+
+ hist -> home
+ hist -> shop -> cart -> checkout
+ shop -> cartHistory
+ shop -> cartDeepHistory
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-home.dot b/way-dsl/src/commonTest/way/dsl-parity-home.dot
new file mode 100644
index 0000000..737cf37
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-home.dot
@@ -0,0 +1,7 @@
+digraph DslParityHome {
+ package = "ru.kode.way.dslparity.home"
+
+ home [type = flow]
+
+ home -> homeScreen -> homeDetails
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-login.dot b/way-dsl/src/commonTest/way/dsl-parity-login.dot
new file mode 100644
index 0000000..2790758
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-login.dot
@@ -0,0 +1,8 @@
+digraph DslParityLogin {
+ package = "ru.kode.way.dslparity.login"
+
+ login [type = flow, parameterName = userName, parameterType = "kotlin.String", resultType = "kotlin.Int"]
+ otp [parameterName = code, parameterType = "kotlin.Int"]
+
+ login -> credentials -> otp
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-nested.dot b/way-dsl/src/commonTest/way/dsl-parity-nested.dot
new file mode 100644
index 0000000..0597d06
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-nested.dot
@@ -0,0 +1,19 @@
+digraph DslParityNested {
+ package = "ru.kode.way.dslparity.nested"
+
+ // Mirrored by DslParityTest.kt: a parallel under a flow whose region holds another parallel. The DSL graph also has a
+ // history of the outer parallel, which codegen lists as a region and fails to build.
+ main [type = flow]
+ tabs [type = parallelFlow]
+ left [type = flow]
+ inner [type = parallelFlow]
+ right [type = flow]
+ feed [type = schema]
+
+ main -> start
+ main -> tabs
+ tabs -> left -> leftScreen -> leftDetails
+ left -> inner
+ inner -> right -> rightScreen
+ inner -> feed
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-params.dot b/way-dsl/src/commonTest/way/dsl-parity-params.dot
new file mode 100644
index 0000000..8abfdb8
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-params.dot
@@ -0,0 +1,9 @@
+digraph DslParityParams {
+ package = "ru.kode.way.dslparity.params"
+
+ // Mirrored by DslParityTest.kt: a nullable root parameter and an imported schema with a nullable parameter.
+ params [type = flow, parameterName = name, parameterType = "kotlin.String?"]
+ counter [type = schema, parameterName = start, parameterType = "kotlin.Int?"]
+
+ params -> paramsScreen -> counter
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-perm.dot b/way-dsl/src/commonTest/way/dsl-parity-perm.dot
new file mode 100644
index 0000000..60a51e0
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-perm.dot
@@ -0,0 +1,7 @@
+digraph DslParityPerm {
+ package = "ru.kode.way.dslparity.perm"
+
+ perm [type = flow, parameterName = reason, parameterType = "kotlin.String", resultType = "kotlin.String"]
+
+ perm -> permIntro -> permDetails
+}
diff --git a/way-dsl/src/commonTest/way/dsl-parity-tabs.dot b/way-dsl/src/commonTest/way/dsl-parity-tabs.dot
new file mode 100644
index 0000000..c59ab30
--- /dev/null
+++ b/way-dsl/src/commonTest/way/dsl-parity-tabs.dot
@@ -0,0 +1,11 @@
+digraph DslParityTabs {
+ package = "ru.kode.way.dslparity.tabs"
+
+ // Mirrored by DslParityGraphs.kt: a parallel root whose regions are imported schemas.
+ tabs [type = parallelFlow]
+ home [type = schema]
+ feed [type = schema]
+
+ tabs -> home
+ tabs -> feed
+}