11package space.kscience.plotly
22
3+ import kotlinx.coroutines.CoroutineScope
34import kotlinx.coroutines.DelicateCoroutinesApi
45import kotlinx.coroutines.GlobalScope
56import kotlinx.coroutines.flow.filterIsInstance
@@ -32,7 +33,11 @@ private fun List<MetaRepr>.toDynamic(): Array<dynamic> = map { it.toDynamic() }.
3233 * Attach a plot to this element or update the existing plot
3334 */
3435@OptIn(DelicateCoroutinesApi ::class )
35- public fun Element.plot (plotlyConfig : PlotlyConfig = PlotlyConfig (), plot : Plot ) {
36+ public fun Element.plot (
37+ plotlyConfig : PlotlyConfig ,
38+ plot : Plot ,
39+ scope : CoroutineScope = plot.manager?.context ? : GlobalScope
40+ ) {
3641
3742// console.info("""
3843// Plotly.react(
@@ -51,7 +56,7 @@ public fun Element.plot(plotlyConfig: PlotlyConfig = PlotlyConfig(), plot: Plot)
5156 )
5257
5358 // start updates
54- val listenJob = (plot.manager?.context ? : GlobalScope ) .launch {
59+ val listenJob = scope .launch {
5560 plot.data.forEachIndexed { index, trace ->
5661 trace.eventFlow.filterIsInstance<VisionPropertyChangedEvent >().onEach { event ->
5762 val traceData = trace.toDynamic()
@@ -92,27 +97,34 @@ public fun Element.plot(plot: Plot, plotlyConfig: PlotlyConfig = PlotlyConfig())
9297/* *
9398 * Create a plot in this element
9499 */
95- public inline fun Element.plot (plotlyConfig : PlotlyConfig = PlotlyConfig (), plotBuilder : Plot .() -> Unit ) {
96- plot(plotlyConfig, Plot ().apply (plotBuilder))
100+ public inline fun Element.plot (
101+ scope : CoroutineScope ,
102+ plotlyConfig : PlotlyConfig = PlotlyConfig (),
103+ plotBuilder : Plot .() -> Unit
104+ ) {
105+ plot(plotlyConfig, Plot ().apply (plotBuilder), scope)
97106}
98107
99108public class PlotlyElement (public val div : HTMLElement )
100109
101110/* *
102- * Create a div element and render plot in it
111+ * Create a div element and render the plot in it
103112 */
113+ @OptIn(DelicateCoroutinesApi ::class )
104114public fun TagConsumer<HTMLElement>.plotDiv (
105- plotlyConfig : PlotlyConfig = PlotlyConfig () ,
115+ plotlyConfig : PlotlyConfig ,
106116 plot : Plot ,
117+ scope : CoroutineScope = plot.manager?.context ? : GlobalScope ,
107118): PlotlyElement = PlotlyElement (div(" plotly-kt-plot" ).apply { plot(plotlyConfig, plot) })
108119
109120/* *
110121 * Render plot in the HTML element using direct plotly API.
111122 */
112123public inline fun TagConsumer<HTMLElement>.plotDiv (
124+ scope : CoroutineScope ,
113125 plotlyConfig : PlotlyConfig = PlotlyConfig (),
114126 plotBuilder : Plot .() -> Unit ,
115- ): PlotlyElement = PlotlyElement (div(" plotly-kt-plot" ).apply { plot(plotlyConfig, plotBuilder) })
127+ ): PlotlyElement = PlotlyElement (div(" plotly-kt-plot" ).apply { plot(scope, plotlyConfig, plotBuilder) })
116128
117129@OptIn(ExperimentalSerializationApi ::class )
118130public fun PlotlyElement.on (eventType : PlotlyEventListenerType , block : MouseEvent .(PlotlyEvent ) -> Unit ) {
0 commit comments