Skip to content

Commit

Permalink
improvements in JsNavigatioNode
Browse files Browse the repository at this point in the history
  • Loading branch information
InsanusMokrassar committed Jan 11, 2023
1 parent 3c26108 commit f815b78
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 17 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## 0.0.11

* `JS`:
* `JsNavigationNode` got `htmlElementStateFlow` which is automatically updated when node is in resume state

## 0.0.10

* `Versions`:
Expand Down
35 changes: 18 additions & 17 deletions core/src/jsMain/kotlin/JsNavigationNode.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import kotlinx.browser.document
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import org.w3c.dom.Element
import org.w3c.dom.HTMLElement
import org.w3c.dom.MutationObserver
import org.w3c.dom.MutationObserverInit

abstract class JsNavigationNode<Config : Base, Base : NavigationNodeDefaultConfig>(
override val chain: NavigationChain<Base>,
Expand All @@ -15,37 +18,35 @@ abstract class JsNavigationNode<Config : Base, Base : NavigationNodeDefaultConfi
override val configState: StateFlow<Config> = _configState.asStateFlow()
protected val htmlElementOrThrow
get() = configState.value.htmlElementOrThrow
private val _htmlElementStateFlow = MutableStateFlow<HTMLElement?>(null)
protected val htmlElementStateFlow = _htmlElementStateFlow.asStateFlow()

override var config: Config
get() = _configState.value
set(value) { _configState.value = value }

protected var observer: MutationObserver? = null

override fun onResume() {
runCatching {
htmlElementOrThrow
}.onSuccess {
super.onResume()
}.onFailure {
observer = MutationObserver { _, mutationObserver ->
runCatching {
htmlElementOrThrow
}.onSuccess {
if (state == NavigationNodeState.RESUMED) {
super.onResume()
}
mutationObserver.disconnect()
}
}.apply {
observe(document.body ?: return)
}
super.onResume()
inline fun refresh() {
_htmlElementStateFlow.value = runCatching {
htmlElementOrThrow
}.getOrNull()
}
observer = MutationObserver { _, _ ->
refresh()
}.apply {
observe(document, MutationObserverInit(childList = true, subtree = true, attributes = true))
}
refresh()
}

override fun onPause() {
super.onPause()
observer ?.disconnect()
observer = null
_htmlElementStateFlow.value = null
}

}

0 comments on commit f815b78

Please sign in to comment.