-
Notifications
You must be signed in to change notification settings - Fork 47
/
MonolithicJs.kt
227 lines (196 loc) · 7.66 KB
/
MonolithicJs.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
/* root package */
import kotlinx.browser.document
import org.jetbrains.letsPlot.commons.geometry.DoubleRectangle
import org.jetbrains.letsPlot.commons.geometry.DoubleVector
import org.jetbrains.letsPlot.commons.logging.PortableLogging
import org.jetbrains.letsPlot.core.plot.builder.FigureBuildInfo
import org.jetbrains.letsPlot.core.spec.FailureHandler
import org.jetbrains.letsPlot.core.spec.config.PlotConfig
import org.jetbrains.letsPlot.core.util.MonolithicCommon
import org.jetbrains.letsPlot.core.util.MonolithicCommon.PlotsBuildResult.Error
import org.jetbrains.letsPlot.core.util.MonolithicCommon.PlotsBuildResult.Success
import org.jetbrains.letsPlot.platf.w3c.jsObject.dynamicObjectToMap
import org.w3c.dom.*
import sizing.SizingOption
import sizing.SizingPolicy
private val LOG = PortableLogging.logger("MonolithicJs")
// key for data attibute <body data-lets-plot-preferred-width='700'>
private const val DATALORE_PREFERRED_WIDTH = "letsPlotPreferredWidth"
/**
* The entry point to call in JS
* `raw specs` are plot specs not processed by datalore plot backend
*/
@OptIn(ExperimentalJsExport::class)
@Suppress("unused")
@JsName("buildPlotFromRawSpecs")
@JsExport
fun buildPlotFromRawSpecs(
plotSpecJs: dynamic,
width: Double,
height: Double,
parentElement: HTMLElement,
optionsJs: dynamic = null
): FigureModelJs? {
return try {
val plotSpec = dynamicObjectToMap(plotSpecJs)
PlotConfig.assertFigSpecOrErrorMessage(plotSpec)
val processedSpec = MonolithicCommon.processRawSpecs(plotSpec, frontendOnly = false)
val options: Map<String, Any> = if (optionsJs != null) {
dynamicObjectToMap(optionsJs)
} else {
emptyMap()
}
val persistentDiv = document.createElement("div") as HTMLDivElement
parentElement.appendChild(persistentDiv)
buildPlotFromProcessedSpecsIntern(processedSpec, width, height, persistentDiv, persistentDiv, options)
} catch (e: RuntimeException) {
handleException(e, parentElement)
null
}
}
/**
* The entry point to call in JS
* `processed specs` are plot specs processed by datalore plot backend
*/
@OptIn(ExperimentalJsExport::class)
@Suppress("unused")
@JsName("buildPlotFromProcessedSpecs")
@JsExport
fun buildPlotFromProcessedSpecs(
plotSpecJs: dynamic,
width: Double,
height: Double,
parentElement: HTMLElement,
optionsJs: dynamic = null
): FigureModelJs? {
return try {
val plotSpec = dynamicObjectToMap(plotSpecJs)
// Though the "plotSpec" might contain already "processed" specs,
// we apply "frontend" transforms anyway, just to be sure that
// we are going to use a truly processed specs.
val processedSpec = MonolithicCommon.processRawSpecs(plotSpec, frontendOnly = true)
val options: Map<String, Any> = if (optionsJs != null) {
dynamicObjectToMap(optionsJs)
} else {
emptyMap()
}
val persistentDiv = document.createElement("div") as HTMLDivElement
parentElement.appendChild(persistentDiv)
buildPlotFromProcessedSpecsIntern(processedSpec, width, height, persistentDiv, persistentDiv, options)
} catch (e: RuntimeException) {
handleException(e, parentElement)
null
}
}
internal fun buildPlotFromProcessedSpecsIntern(
plotSpec: Map<String, Any>,
width: Double,
height: Double,
parentElement: HTMLElement,
eventTarget: Element,
options: Map<String, Any>
): FigureModelJs? {
// Fixed plot size (not compatible with reactive sizing).
val plotSizeProvided = if (width > 0 && height > 0) DoubleVector(width, height) else null
// Datalore specific option - not compatible with reactive sizing.
val datalorePreferredWidth: Double? =
parentElement.ownerDocument?.body?.dataset?.get(DATALORE_PREFERRED_WIDTH)?.toDouble()
val sizingPolicy = if (plotSizeProvided != null) {
// Ignore sizing options even if provided
SizingPolicy.fixedBoth(plotSizeProvided)
} else when (val sizingOptions = options[SizingOption.KEY]) {
is Map<*, *> -> SizingPolicy.create(sizingOptions)
else -> SizingPolicy.DEFAULT
}
val (plotSize, plotMaxWidth) = /*if (plotSizeProvided != null) {
SizingPolicyAdapter.SizeAndMaxWidth(plotSizeProvided, null)
} else */if (datalorePreferredWidth != null) {
SizingPolicyAdapter.SizeAndMaxWidth(null, null)
} else {
val sizingPolicyAdapter = SizingPolicyAdapter(sizingPolicy)
sizingPolicyAdapter.monolithicSizingParameters(plotSizeProvided, parentElement)
}
// LOG.error { "plotSize=$plotSize, preferredWidth=$preferredWidth, maxWidth=$maxWidth " }
val buildResult = MonolithicCommon.buildPlotsFromProcessedSpecs(
plotSpec,
plotSize,
plotMaxWidth,
datalorePreferredWidth,
)
if (buildResult.isError) {
val errorMessage = (buildResult as Error).error
showError(errorMessage, parentElement)
return null
}
val success = buildResult as Success
val computationMessages = success.buildInfos.flatMap { it.computationMessages }
computationMessages.forEach {
showInfo(it, parentElement)
}
val figureModel = if (success.buildInfos.size == 1) {
// a single figure
val buildInfo = success.buildInfos[0]
val result = FigureToHtml(buildInfo, parentElement, eventTarget).eval()
FigureModelJs(
plotSpec,
MonolithicParameters(width, height, parentElement, eventTarget, options),
result.toolEventDispatcher,
result.figureRegistration
)
} else {
// a bunch
buildGGBunchComponent(success.buildInfos, parentElement, eventTarget)
null
}
return figureModel
}
fun buildGGBunchComponent(
plotInfos: List<FigureBuildInfo>,
parentElement: HTMLElement,
eventTarget: Element
) {
val bunchBounds = plotInfos.map { it.bounds }
.fold(DoubleRectangle(DoubleVector.ZERO, DoubleVector.ZERO)) { acc, bounds ->
acc.union(bounds)
}
FigureToHtml.setupRootHTMLElement(
parentElement,
bunchBounds.dimension
)
for (plotInfo in plotInfos) {
val origin = plotInfo.bounds.origin
val itemContainerElement = FigureToHtml.createContainerElement(origin)
parentElement.appendChild(itemContainerElement)
FigureToHtml(
buildInfo = plotInfo,
containerElement = itemContainerElement,
eventTarget = eventTarget
).eval()
}
}
private fun handleException(e: RuntimeException, parentElement: HTMLElement) {
val failureInfo = FailureHandler.failureInfo(e)
showError(failureInfo.message, parentElement)
if (failureInfo.isInternalError) {
LOG.error(e) { "Unexpected situation in 'MonolithicJs'" }
}
}
private fun showError(message: String, parentElement: HTMLElement) {
showText(message, "lets-plot-message-error", "color:darkred;", parentElement)
}
private fun showInfo(message: String, parentElement: HTMLElement) {
showText(message, "lets-plot-message-info", "color:darkblue;", parentElement)
}
private fun showText(message: String, className: String, style: String, parentElement: HTMLElement) {
val paragraphElement = parentElement.ownerDocument!!.createElement("p") as HTMLParagraphElement
if (style.isNotBlank()) {
paragraphElement.setAttribute("style", style)
}
paragraphElement.textContent = message
paragraphElement.className = className
parentElement.appendChild(paragraphElement)
}