Add WatchDiv demo

This commit is contained in:
Edwin Jakobs
2020-05-08 11:03:44 +02:00
parent 43edd55d68
commit 2dc7fb1b75
3 changed files with 136 additions and 5 deletions

View File

@@ -5,12 +5,13 @@ import kotlinx.coroutines.yield
import org.openrndr.draw.Drawer
import org.openrndr.launch
class WatchDiv<T : Any>(val watchList: List<T>, val builder: WatchDiv<T>.(T) -> Unit) : Div(), DisposableElement {
class WatchDiv<T : Any>(private val watchList: List<T>, private val builder: WatchDiv<T>.(T) -> Unit) : Div(), DisposableElement {
override var disposed: Boolean = false
var listState = emptyList<T>()
var watchJob : Job? = null
private var listState = emptyList<T>()
private var watchJob: Job? = null
override fun dispose() {
super.dispose()
for (child in children) {
child.parent = null
(child as? DisposableElement)?.dispose()
@@ -18,7 +19,7 @@ class WatchDiv<T : Any>(val watchList: List<T>, val builder: WatchDiv<T>.(T) ->
children.clear()
}
private fun regenerate() {
fun regenerate() {
var regenerate = false
if (listState.size != watchList.size) {
regenerate = true
@@ -45,7 +46,7 @@ class WatchDiv<T : Any>(val watchList: List<T>, val builder: WatchDiv<T>.(T) ->
}
}
override fun draw(drawer: Drawer) {
fun checkJob() {
if (watchJob == null) {
watchJob = (root() as Body).controlManager.program.launch {
while (!disposed) {
@@ -54,6 +55,9 @@ class WatchDiv<T : Any>(val watchList: List<T>, val builder: WatchDiv<T>.(T) ->
}
}
}
}
override fun draw(drawer: Drawer) {
checkJob()
super.draw(drawer)
}
}
@@ -62,4 +66,6 @@ fun <T : Any> Element.watchDiv(vararg classes: String, watchList: List<T>, build
val wd = WatchDiv(watchList, builder)
wd.classes.addAll(classes.map { ElementClass(it) })
this.append(wd)
wd.regenerate()
wd.checkJob()
}