@@ -70,7 +70,7 @@ kaleido <- function(...) {
70
70
71
71
call_env <- rlang :: caller_env()
72
72
73
- if (! reticulate :: py_available()) {
73
+ if (! reticulate :: py_available(TRUE )) {
74
74
rlang :: abort(c(" `{reticulate}` wasn't able to find a Python environment." ,
75
75
i = " If you have an existing Python installation, use `reticulate::use_python()` to inform `{reticulate}` of it." ,
76
76
i = " To have `{reticulate}` install Python for you, `reticulate::install_python()`."
@@ -97,6 +97,67 @@ kaleido <- function(...) {
97
97
}
98
98
)
99
99
100
+ res <- if (is.null(tryNULL(kaleido $ scopes ))) {
101
+ newKaleidoScope(kaleido )
102
+ } else {
103
+ legacyKaleidoScope(kaleido )
104
+ }
105
+
106
+ class(res ) <- " kaleidoScope"
107
+ res
108
+ }
109
+
110
+ newKaleidoScope <- function (kaleido ) {
111
+ list (
112
+ scopes = NULL ,
113
+ transform = function (p , file , ... , width = NULL , height = NULL , scale = NULL ) {
114
+ # Perform JSON conversion exactly how the R package would do it
115
+ fig <- to_JSON(
116
+ plotly_build(p )$ x [c(" data" , " layout" , " config" )]
117
+ )
118
+
119
+ # Write to JSON file
120
+ tmp_json <- tempfile(fileext = " .json" )
121
+ on.exit(unlink(tmp_json ))
122
+ writeLines(fig , tmp_json )
123
+
124
+ # Import it as a fig (dict)
125
+ load_json <- sprintf(
126
+ " import json; fig = json.load(open('%s'))" ,
127
+ tmp_json
128
+ )
129
+ reticulate :: py_run_string(load_json )
130
+
131
+ # TODO: Pass plotlyMainBundlePath() (and mathjax?)
132
+ # to page level options
133
+ # reticulate::py_run_string(
134
+ # "import kaleido; kaleido.PageGenerator()"
135
+ # )
136
+
137
+ # Gather figure-level options
138
+ opts <- list (
139
+ format = tools :: file_ext(file ),
140
+ width = reticulate :: r_to_py(width ),
141
+ height = reticulate :: r_to_py(height ),
142
+ scale = reticulate :: r_to_py(scale )
143
+ )
144
+
145
+ # TODO: how to bring in Mapbox token?
146
+ # https://github.com/plotly/Kaleido/issues/348
147
+ # mapbox <- Sys.getenv("MAPBOX_TOKEN", NA)
148
+ # if (!is.na(mapbox)) {
149
+ # opts$mapboxAccessToken <- mapbox
150
+ # }
151
+
152
+ # Write the figure to a file using kaleido
153
+ kaleido $ write_fig_sync(reticulate :: py $ fig , file , opts = opts )
154
+ },
155
+ shutdown = function () {}
156
+ )
157
+ }
158
+
159
+
160
+ legacyKaleidoScope <- function (kaleido ) {
100
161
py <- reticulate :: py
101
162
scope_name <- paste0(" scope_" , new_id())
102
163
py [[scope_name ]] <- kaleido $ scopes $ plotly $ PlotlyScope(
@@ -151,7 +212,6 @@ kaleido <- function(...) {
151
212
reticulate :: py_run_string(paste(" del" , scope_name ))
152
213
})
153
214
154
- class(res ) <- " kaleidoScope"
155
215
res
156
216
}
157
217
0 commit comments