@@ -70,7 +70,7 @@ kaleido <- function(...) {
7070
7171 call_env <- rlang :: caller_env()
7272
73- if (! reticulate :: py_available()) {
73+ if (! reticulate :: py_available(TRUE )) {
7474 rlang :: abort(c(" `{reticulate}` wasn't able to find a Python environment." ,
7575 i = " If you have an existing Python installation, use `reticulate::use_python()` to inform `{reticulate}` of it." ,
7676 i = " To have `{reticulate}` install Python for you, `reticulate::install_python()`."
@@ -97,6 +97,67 @@ kaleido <- function(...) {
9797 }
9898 )
9999
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 ) {
100161 py <- reticulate :: py
101162 scope_name <- paste0(" scope_" , new_id())
102163 py [[scope_name ]] <- kaleido $ scopes $ plotly $ PlotlyScope(
@@ -151,7 +212,6 @@ kaleido <- function(...) {
151212 reticulate :: py_run_string(paste(" del" , scope_name ))
152213 })
153214
154- class(res ) <- " kaleidoScope"
155215 res
156216}
157217
0 commit comments