| 1 |
|
| 2 |
# Create a shiny app object from an Rmd w/ runtime: shiny_prerendered |
| 3 |
shiny_prerendered_app <- function(input_rmd, render_args) { |
| 4 |
|
| 5 |
# get rendered html and capture dependencies |
| 6 |
html <- shiny_prerendered_html(input_rmd, render_args) |
| 7 |
deps <- htmltools::htmlDependencies(html) |
| 8 |
|
| 9 |
# create the server environment |
| 10 |
server_envir = new.env(parent = globalenv()) |
| 11 |
|
| 12 |
# read the html |
| 13 |
html_lines <- strsplit(html, "\n", fixed = TRUE)[[1]] |
| 14 |
|
| 15 |
# read and remove server-extras (used for both embedded and server.R use cases) |
| 16 |
server_extras <- shiny_prerendered_extract_context(html_lines, "server-extras") |
| 17 |
if (length(server_extras) > 0) { |
| 18 |
html_lines <- shiny_prerendered_remove_contexts(html_lines, "server-extras") |
| 19 |
} |
| 20 |
|
| 21 |
# extract the server-start context |
| 22 |
server_start_context <- shiny_prerendered_extract_context(html_lines, |
| 23 |
"server-start") |
| 24 |
|
| 25 |
# extract the code used for server startup (this encompasses both the |
| 26 |
# context="server-start" code and the context="data" code). This can be |
| 27 |
# retrieved later via the shiny_prerendered_server_start_code function. The |
| 28 |
# purpose of this is for appliations which want to run user in other |
| 29 |
# processes while still duplicating the setup context (e.g. tutorials). |
| 30 |
server_start_code <- one_string(c(server_start_context, |
| 31 |
shiny_prerendered_extract_context(html_lines, "data"))) |
| 32 |
|
| 33 |
onStart <- function() { |
| 34 |
|
| 35 |
# save the server_start_code |
| 36 |
assign(".shiny_prerendered_server_start_code", server_start_code, envir = server_envir) |
| 37 |
|
| 38 |
# execute the startup code (server_start_context + context="data" loading) |
| 39 |
eval(xfun::parse_only(server_start_context), envir = server_envir) |
| 40 |
shiny_prerendered_data_load(input_rmd, server_envir) |
| 41 |
|
| 42 |
# lock the environment to prevent inadvertent assignments |
| 43 |
lockEnvironment(server_envir) |
| 44 |
} |
| 45 |
|
| 46 |
# extract the server context |
| 47 |
.server_context <- c(server_extras, |
| 48 |
shiny_prerendered_extract_context(html_lines, "server")) |
| 49 |
server_envir$.server_context <- .server_context |
| 50 |
server <- function(input, output, session) { |
| 51 |
eval(xfun::parse_only(.server_context)) |
| 52 |
} |
| 53 |
environment(server) <- new.env(parent = server_envir) |
| 54 |
|
| 55 |
# remove server code before serving |
| 56 |
server_contexts <- c("server-start", "data", "server") |
| 57 |
redacted_html_lines <- shiny_prerendered_remove_contexts(html_lines, server_contexts) |
| 58 |
|
| 59 |
# if there were server contexts then update html w/ removed contexts |
| 60 |
if (length(redacted_html_lines) < length(html_lines)) { |
| 61 |
html <- HTML(one_string(redacted_html_lines)) |
| 62 |
} |
| 63 |
# if there were not server contexts then this may be a ui-only rmd, |
| 64 |
# check for a server.R |
| 65 |
else if (file.exists(file.path(dirname(input_rmd), "server.R"))) { |
| 66 |
# source global.R onStart |
| 67 |
onStart <- function() { |
| 68 |
global_r <- file.path.ci(dirname(input_rmd), "global.R") |
| 69 |
if (file.exists(global_r)) { |
| 70 |
source(global_r, local = FALSE) |
| 71 |
} |
| 72 |
} |
| 73 |
# server function from server.R |
| 74 |
server_r <- file.path(dirname(input_rmd), "server.R") |
| 75 |
server_r_env = new.env(parent = globalenv()) |
| 76 |
if (length(server_extras) > 0) { |
| 77 |
eval(xfun::parse_only(server_extras), envir = server_r_env) |
| 78 |
} |
| 79 |
server <- source(server_r, local = server_r_env)$value |
| 80 |
} else { |
| 81 |
stop("No server contexts or server.R available for ", input_rmd) |
| 82 |
} |
| 83 |
|
| 84 |
html_ui <- shiny_prerendered_ui(html, deps) |
| 85 |
|
| 86 |
# create shiny app |
| 87 |
shiny::shinyApp( |
| 88 |
ui = function(req) html_ui, |
| 89 |
server = server, |
| 90 |
onStart = onStart, |
| 91 |
uiPattern = "^/$|^(/.*\\.[Rrq][Mm][Dd])$" |
| 92 |
) |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
# Generate the html for a runtime: shiny_prerendered Rmd (attempts to use |
| 97 |
# an existing rendering of the html if it's still valid) |
| 98 |
shiny_prerendered_html <- function(input_rmd, render_args) { |
| 99 |
|
| 100 |
# determine the path to the rendered_html |
| 101 |
output_file <- render_args$output_file |
| 102 |
if (is.null(output_file)) |
| 103 |
output_file <- file_with_ext(basename(input_rmd), "html") |
| 104 |
output_dir <- render_args$output_dir |
| 105 |
if (is.null(output_dir)) |
| 106 |
output_dir <- dirname(input_rmd) |
| 107 |
rendered_html <- file.path(output_dir, output_file) |
| 108 |
|
| 109 |
# determine whether we need to render the Rmd in advance |
| 110 |
prerender_option <- tolower(Sys.getenv("RMARKDOWN_RUN_PRERENDER", "1")) |
| 111 |
prerender <- shiny_prerendered_prerender( |
| 112 |
input_rmd, |
| 113 |
rendered_html, |
| 114 |
output_dir, |
| 115 |
prerender_option |
| 116 |
) |
| 117 |
|
| 118 |
# prerender if necessary |
| 119 |
if (prerender) { |
| 120 |
args <- merge_lists(list(input = input_rmd), render_args) |
| 121 |
# force prerender to execute in separate environment to ensure that |
| 122 |
# running w/ prerender step is equivalent to running the prerendered app |
| 123 |
args$envir <- new.env(parent = args$envir %||% globalenv()) |
| 124 |
|
| 125 |
# execute the render |
| 126 |
rendered_html <- do.call(render, args) |
| 127 |
} |
| 128 |
|
| 129 |
if (!file.exists(rendered_html)) { |
| 130 |
stop("Prerendered HTML file not found at ", rendered_html) |
| 131 |
} |
| 132 |
|
| 133 |
# normalize paths |
| 134 |
rendered_html <- normalize_path(rendered_html) |
| 135 |
output_dir <- dirname(rendered_html) |
| 136 |
|
| 137 |
add_resource_path <- function(path, prefix = basename(path), temporary = TRUE) { |
| 138 |
if (dir_exists(path)) { |
| 139 |
shiny::addResourcePath(prefix, path) |
| 140 |
# Remove resource paths so they don't clash with 'down-stream' resources |
| 141 |
removeResourcePath <- if (temporary) |
| 142 |
try(getFromNamespace("removeResourcePath", "shiny"), silent = TRUE) |
| 143 |
if (is.function(removeResourcePath)) { |
| 144 |
shiny::onStop(function() { removeResourcePath(prefix) }, NULL) |
| 145 |
} |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
files_dir <- knitr_files_dir(rendered_html) |
| 150 |
add_resource_path(files_dir) |
| 151 |
add_resource_path(file.path(output_dir,"css")) |
| 152 |
add_resource_path(file.path(output_dir,"js")) |
| 153 |
add_resource_path(file.path(output_dir,"images")) |
| 154 |
add_resource_path(file.path(output_dir,"www")) |
| 155 |
|
| 156 |
# extract dependencies from html |
| 157 |
html_lines <- read_utf8(rendered_html) |
| 158 |
dependencies <- shiny_prerendered_extract_context_serialized(html_lines, "dependencies") |
| 159 |
|
| 160 |
# resolve package paths (this will happen automatically for the |
| 161 |
# development version of htmltools but this isn't on CRAN yet) |
| 162 |
dependencies <- lapply(dependencies, function(dependency) { |
| 163 |
if (!is.null(dependency$package) && !is.null(dependency$src$file)) { |
| 164 |
dependency$src$file <- system.file(dependency$src$file, |
| 165 |
package = dependency$package) |
| 166 |
dependency$package <- NULL |
| 167 |
} |
| 168 |
dependency |
| 169 |
}) |
| 170 |
|
| 171 |
# attach rstudio rsiframe script if we are in rstudio |
| 172 |
if (nzchar(Sys.getenv("RSTUDIO"))) |
| 173 |
dependencies <- append(dependencies, list(html_dependency_rsiframe())) |
| 174 |
|
| 175 |
# return html w/ dependencies |
| 176 |
html_with_deps <- shinyHTML_with_deps(rendered_html, dependencies) |
| 177 |
|
| 178 |
# The html template used to render the UI should contain the placeholder |
| 179 |
# expected by shiny in `shiny:::renderPage()` which uses `htmltools::renderDocument`. |
| 180 |
# This should be included during render() as a header include file. As a safety measure, |
| 181 |
# if it is not present in the template, we add this placeholder at the end of |
| 182 |
# the <head> element. This should not happen really. |
| 183 |
# Context: https://github.com/rstudio/rmarkdown/pull/2249 |
| 184 |
if (!any(grepl(headContent <- "<!-- HEAD_CONTENT -->", html_with_deps, fixed = TRUE))) { |
| 185 |
html_with_deps <- sub( |
| 186 |
'</head>', |
| 187 |
paste0('\n', headContent, '\n</head>'), |
| 188 |
html_with_deps, |
| 189 |
fixed = TRUE, |
| 190 |
useBytes = TRUE) |
| 191 |
Encoding(html_with_deps) <- "UTF-8" |
| 192 |
} |
| 193 |
html_with_deps |
| 194 |
} |
| 195 |
|
| 196 |
shiny_prerendered_ui <- function(html, deps) { |
| 197 |
# prerendered html is a full document that should not be expanded in shiny::renderPage() |
| 198 |
# so make shiny aware of that with the attributes 'html_document' to mimic the result of |
| 199 |
# htmltools::htmlTemplate(document_ = TRUE). |
| 200 |
# https://github.com/rstudio/rmarkdown/issues/1912 |
| 201 |
html_doc <- htmltools::tagList(html) |
| 202 |
class(html_doc) <- c("html_document", class(html_doc)) |
| 203 |
# attach dependencies to final html |
| 204 |
htmltools::attachDependencies(html_doc, deps) |
| 205 |
} |
| 206 |
|
| 207 |
shiny_prerendered_prerender <- function( |
| 208 |
input_rmd, |
| 209 |
rendered_html, |
| 210 |
output_dir, |
| 211 |
prerender_option |
| 212 |
) { |
| 213 |
if (file.access(output_dir, 2) != 0) { |
| 214 |
if (!file.exists(rendered_html)) |
| 215 |
stop("Unable to write prerendered HTML file to ", rendered_html) |
| 216 |
return(FALSE) |
| 217 |
} |
| 218 |
|
| 219 |
if (identical(prerender_option, "0")) { |
| 220 |
return(FALSE) |
| 221 |
} |
| 222 |
if (!identical(prerender_option, "1")) { |
| 223 |
stop("Invalid value '", prerender_option, "' for RMARKDOWN_RUN_PRERENDER") |
| 224 |
} |
| 225 |
|
| 226 |
# determine the last modified time of the output file |
| 227 |
if (file.exists(rendered_html)) { |
| 228 |
output_last_modified <- as.integer(file.info(rendered_html)$mtime) |
| 229 |
} else { |
| 230 |
output_last_modified <- 0L |
| 231 |
} |
| 232 |
|
| 233 |
# short circuit for Rmd modified. if it hasn't been modified since the |
| 234 |
# html was generated look at external resources |
| 235 |
input_last_modified <- as.integer(file.info(input_rmd)$mtime) |
| 236 |
if (input_last_modified > output_last_modified) { |
| 237 |
return(TRUE) |
| 238 |
} |
| 239 |
|
| 240 |
# find external resources referenced by the file |
| 241 |
external_resources <- find_external_resources(input_rmd) |
| 242 |
|
| 243 |
# get paths to external resources |
| 244 |
input_files <- c(input_rmd, file.path(output_dir, external_resources$path)) |
| 245 |
|
| 246 |
# what's the maximum last_modified time of an input file |
| 247 |
input_last_modified <- max(as.integer(file.info(input_files)$mtime), na.rm = TRUE) |
| 248 |
|
| 249 |
# render if an input file was modified after the output file |
| 250 |
if (input_last_modified > output_last_modified) { |
| 251 |
return(TRUE) |
| 252 |
} |
| 253 |
|
| 254 |
html_lines <- read_utf8(rendered_html) |
| 255 |
|
| 256 |
# check that all html dependencies exist |
| 257 |
dependencies <- tryCatch( |
| 258 |
shiny_prerendered_extract_context_serialized(html_lines, "dependencies"), |
| 259 |
error = function(...) NULL |
| 260 |
) |
| 261 |
if (is.null(dependencies)) { |
| 262 |
# Pre-render needed: failed to parse deps from pre-rendered HTML |
| 263 |
return(TRUE) |
| 264 |
} |
| 265 |
|
| 266 |
pkgsSeen <- list() |
| 267 |
for (dep in dependencies) { |
| 268 |
if (is.null(dep$package)) { |
| 269 |
src_file <- dep$src$file |
| 270 |
if (!is.null(src_file)) { |
| 271 |
if (!file.exists(src_file)) { |
| 272 |
# might create a missing file compile-time error, |
| 273 |
# but that's better than a missing file prerendered error |
| 274 |
return(TRUE) |
| 275 |
} |
| 276 |
} |
| 277 |
# if there is a dep$src$href but no dep$package, |
| 278 |
# then we can't determine where the file came from. |
| 279 |
# Ignore checking for the href files for now, as pkg versions are checked below |
| 280 |
} else { |
| 281 |
depPkg <- dep$package |
| 282 |
depVer <- dep$pkgVersion |
| 283 |
if (is.null(pkgsSeen[[depPkg]])) { |
| 284 |
# has not seen pkg |
| 285 |
|
| 286 |
# depVer could be NULL, producing a logical(0) |
| 287 |
# means old prerender version, render again |
| 288 |
if (!isTRUE(get_package_version_string(depPkg) == depVer)) { |
| 289 |
# was not rendered with the same R package. must render again |
| 290 |
return(TRUE) |
| 291 |
} |
| 292 |
pkgsSeen[[depPkg]] <- depVer |
| 293 |
} |
| 294 |
} |
| 295 |
} |
| 296 |
# all html dependencies are accounted for |
| 297 |
|
| 298 |
# check for execution package version differences |
| 299 |
execution_info <- tryCatch( |
| 300 |
shiny_prerendered_extract_context_serialized(html_lines, "execution_dependencies"), |
| 301 |
error = function(...) NULL |
| 302 |
) |
| 303 |
if (is.null(execution_info)) { |
| 304 |
# Pre-render needed: failed to parse execution deps from pre-rendered HTML |
| 305 |
return(TRUE) |
| 306 |
} |
| 307 |
execution_pkg_names <- execution_info$packages$packages |
| 308 |
execution_pkg_versions <- execution_info$packages$version |
| 309 |
for (i in seq_along(execution_pkg_names)) { |
| 310 |
if (!identical( |
| 311 |
get_package_version_string(execution_pkg_names[i]), |
| 312 |
execution_pkg_versions[i] |
| 313 |
)) { |
| 314 |
return(TRUE) |
| 315 |
} |
| 316 |
} |
| 317 |
# all execution packages match |
| 318 |
|
| 319 |
return(FALSE) |
| 320 |
} |
| 321 |
|
| 322 |
|
| 323 |
# Write the dependencies for a shiny_prerendered document. |
| 324 |
shiny_prerendered_append_dependencies <- function(input, # always UTF-8 |
| 325 |
shiny_prerendered_dependencies, |
| 326 |
files_dir, |
| 327 |
output_dir) { |
| 328 |
|
| 329 |
# transform dependencies (if we aren't in debug mode) |
| 330 |
dependencies <- lapply(shiny_prerendered_dependencies$deps, function(dependency) { |
| 331 |
|
| 332 |
# no transformation in dev mode (so browser dev tools can map directly |
| 333 |
# to the locations of CSS and JS files in their pkg src directory) |
| 334 |
if (nzchar(Sys.getenv("RMARKDOWN_SHINY_PRERENDERED_DEVMODE"))) |
| 335 |
return(dependency) |
| 336 |
|
| 337 |
# see if we can convert absolute paths into package-aliased ones |
| 338 |
if (is.null(dependency$package) && is.character(dependency$src$file)) { |
| 339 |
|
| 340 |
# check for a package directory parent |
| 341 |
package_dir <- proj_root(dependency$src$file) |
| 342 |
# if we have one then populate the package field and make the |
| 343 |
# src$file relative to the package |
| 344 |
if (!is.null(package_dir)) { |
| 345 |
package_desc <- read.dcf(file.path(package_dir, "DESCRIPTION"), |
| 346 |
all = TRUE) |
| 347 |
dependency$package <- package_desc$Package |
| 348 |
# named to something that doesn't start with 'package' to deter lazy name matching |
| 349 |
dependency$pkgVersion <- package_desc$Version |
| 350 |
dependency$src$file <- normalized_relative_to(package_dir, |
| 351 |
dependency$src$file) |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
# if we couldn't resolve the src to a package then copy the files |
| 356 |
if (is.null(dependency$package) && !is.null(dependency$src$file)) { |
| 357 |
dependency <- copyDependencyToDir(dependency, files_dir) |
| 358 |
dependency <- makeDependencyRelative(dependency, output_dir) |
| 359 |
dependency$src = list(href = unname(dependency$src)) |
| 360 |
} |
| 361 |
|
| 362 |
if (!is.null(dependency$package)) { |
| 363 |
dependency$pkgVersion <- get_package_version_string(dependency$package) |
| 364 |
} |
| 365 |
|
| 366 |
# return dependency |
| 367 |
dependency |
| 368 |
}) |
| 369 |
|
| 370 |
# remove NULLs (excluded dependencies) |
| 371 |
dependencies <- dependencies[!sapply(dependencies, is.null)] |
| 372 |
|
| 373 |
# append them to the file (guaranteed to be UTF-8) |
| 374 |
con <- file(input, open = "at", encoding = "UTF-8") |
| 375 |
on.exit(close(con), add = TRUE) |
| 376 |
|
| 377 |
# Add newline before adding any raw html dependency script |
| 378 |
# https://github.com/rstudio/rmarkdown/issues/2336 |
| 379 |
writeLines("", con = con) |
| 380 |
|
| 381 |
# write deps to connection |
| 382 |
dependencies_json <- jsonlite::serializeJSON(dependencies, pretty = FALSE) |
| 383 |
shiny_prerendered_append_context(con, "dependencies", dependencies_json) |
| 384 |
|
| 385 |
# write r major version and execution package dependencies |
| 386 |
execution_json <- jsonlite::serializeJSON( |
| 387 |
# visibly display what is being stored |
| 388 |
shiny_prerendered_dependencies["packages"], |
| 389 |
pretty = FALSE |
| 390 |
) |
| 391 |
shiny_prerendered_append_context(con, "execution_dependencies", execution_json) |
| 392 |
} |
| 393 |
|
| 394 |
shiny_prerendered_extract_context_serialized <- function(html_lines, context = "dependencies") { |
| 395 |
json_str <- shiny_prerendered_extract_context(html_lines, context) |
| 396 |
json_str <- unique(json_str) |
| 397 |
if (length(json_str) > 1) { |
| 398 |
warning("Multiple ", context, " contexts found in prerendered HTML, using last.") |
| 399 |
json_str <- json_str[length(json_str)] |
| 400 |
} |
| 401 |
jsonlite::unserializeJSON(json_str) |
| 402 |
} |
| 403 |
|
| 404 |
|
| 405 |
#' Clean prerendered content for the specified Rmd input file |
| 406 |
#' |
| 407 |
#' Remove the associated html file and supporting _files directory |
| 408 |
#' for a shiny_prerendered documet. |
| 409 |
#' |
| 410 |
#' @param input Rmd input file to clean content for |
| 411 |
#' |
| 412 |
#' @export |
| 413 |
shiny_prerendered_clean <- function(input) { |
| 414 |
|
| 415 |
# html file |
| 416 |
html_file <- file_with_ext(input, "html") |
| 417 |
if (file.exists(html_file)) |
| 418 |
file.remove(html_file) |
| 419 |
|
| 420 |
# cache dir |
| 421 |
cache_dir <- knitr_root_cache_dir(input) |
| 422 |
if (dir_exists(cache_dir)) |
| 423 |
unlink(cache_dir, recursive = TRUE) |
| 424 |
|
| 425 |
# files dir |
| 426 |
files_dir <- knitr_files_dir(input) |
| 427 |
if (dir_exists(files_dir)) |
| 428 |
unlink(files_dir, recursive = TRUE) |
| 429 |
|
| 430 |
# data dir |
| 431 |
data_dir <- shiny_prerendered_data_dir(input) |
| 432 |
if (dir_exists(data_dir)) |
| 433 |
unlink(data_dir, recursive = TRUE) |
| 434 |
} |
| 435 |
|
| 436 |
|
| 437 |
#' Add code to a shiny_prerendered context |
| 438 |
#' |
| 439 |
#' Programmatic equivalent to including a code chunk with a |
| 440 |
#' context in a runtime: shiny_prerendered document. |
| 441 |
#' |
| 442 |
#' @param context Context name (e.g. "server", "server-start") |
| 443 |
#' @param code Character vector with code |
| 444 |
#' @param singleton Collapse multiple identical versions of this |
| 445 |
#' chunk into a single chunk. |
| 446 |
#' |
| 447 |
#' @export |
| 448 |
shiny_prerendered_chunk <- function(context, code, singleton = FALSE) { |
| 449 |
|
| 450 |
# verify we are in runtime: shiny_prerendered |
| 451 |
if (!is_shiny_prerendered(knitr::opts_knit$get("rmarkdown.runtime"))) |
| 452 |
stop2("The shiny_prerendered_chunk function can only be called from ", |
| 453 |
"within a shiny server compatible document" |
| 454 |
) |
| 455 |
|
| 456 |
# add the prerendered chunk to knit_meta |
| 457 |
knitr::knit_meta_add(list( |
| 458 |
structure(class = "shiny_prerendered", list( |
| 459 |
name = context, |
| 460 |
code = code, |
| 461 |
singleton = singleton |
| 462 |
)) |
| 463 |
)) |
| 464 |
|
| 465 |
# return NULL invisibly |
| 466 |
invisible(NULL) |
| 467 |
} |
| 468 |
|
| 469 |
|
| 470 |
#' Get the server startup code for a shiny_prerendered server instance |
| 471 |
#' |
| 472 |
#' @param server_envir Shiny server environment to get code for |
| 473 |
#' |
| 474 |
#' @keywords internal |
| 475 |
#' @export |
| 476 |
shiny_prerendered_server_start_code <- function(server_envir) { |
| 477 |
if (exists(".shiny_prerendered_server_start_code", envir = server_envir)) |
| 478 |
get(".shiny_prerendered_server_start_code", envir = server_envir) |
| 479 |
else |
| 480 |
"" |
| 481 |
} |
| 482 |
|
| 483 |
|
| 484 |
# Record which context="data" chunks are actually executed during |
| 485 |
# the current render as well as the file names they are saved with. |
| 486 |
# We'll use this later to determine which .RData files in the _data |
| 487 |
# directory should actually be loaded (as some could be from chunks |
| 488 |
# that used to be cached / were cached under different names) |
| 489 |
shiny_prerendered_option_hook <- function(input) { |
| 490 |
function(options) { |
| 491 |
|
| 492 |
# convert chunk labels to contexts as necessary |
| 493 |
if (options$label %in% c("setup", "data", "server_start", "server")) |
| 494 |
options$context <- options$label |
| 495 |
|
| 496 |
if (identical(options$context, "data")) { |
| 497 |
data_file <- shiny_prerendered_data_file_name(options$label, |
| 498 |
options$cache > 0) |
| 499 |
data_dir <- shiny_prerendered_data_dir(input, create = TRUE) |
| 500 |
index_file <- shiny_prerendered_data_chunks_index(data_dir) |
| 501 |
conn <- file(index_file, open = "ab", encoding = "UTF-8") |
| 502 |
on.exit(close(conn), add = TRUE) |
| 503 |
write(data_file, file = conn, append = TRUE) |
| 504 |
} |
| 505 |
|
| 506 |
if (identical(options$context, "server")) { |
| 507 |
# if empty server context, set a default server function |
| 508 |
if (all(xfun::is_blank(options$code))) { |
| 509 |
options$code <- "# empty server context" |
| 510 |
} |
| 511 |
} |
| 512 |
options |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
# Evaluate hook to capture chunks with e.g. context="server" and |
| 517 |
# append their code to the appropriate shiny_prerendered_context |
| 518 |
shiny_prerendered_evaluate_hook <- function(input) { |
| 519 |
|
| 520 |
function(code, envir, ...) { |
| 521 |
|
| 522 |
# get the context (default to "render") |
| 523 |
context <- knitr::opts_current$get("context") |
| 524 |
if (is.null(context)) |
| 525 |
context <- "render" |
| 526 |
|
| 527 |
# "setup" is an alias for c("render", "server-start") |
| 528 |
if ("setup" %in% context) { |
| 529 |
context <- c(context[!context == "setup"], "render", "server-start") |
| 530 |
context <- unique(context) |
| 531 |
} |
| 532 |
|
| 533 |
# if there are server-side contexts then emit knit_meta for them |
| 534 |
for (name in context) { |
| 535 |
if (!name %in% c("render")) |
| 536 |
shiny_prerendered_chunk(name, code) |
| 537 |
} |
| 538 |
|
| 539 |
# capture and serialize data for context = "data" |
| 540 |
if ("data" %in% context) { |
| 541 |
|
| 542 |
# determine whether caching is active |
| 543 |
label <- knitr::opts_current$get("label") |
| 544 |
cache_option <- knitr::opts_current$get("cache") |
| 545 |
cache <- !is.null(cache_option) && cache_option > 0 |
| 546 |
|
| 547 |
# evaluate the chunk in a new environment parented by the default envir |
| 548 |
data_env <- new.env(parent = envir) |
| 549 |
result <- evaluate::evaluate(code, data_env, ...) |
| 550 |
|
| 551 |
# save all of the created objects then move them back into the parent |
| 552 |
data_dir <- shiny_prerendered_data_dir(input, create = TRUE) |
| 553 |
# use a special path prefix for cached chunks so we know not |
| 554 |
# to remove them at the beginning of render |
| 555 |
rdata_file <- file.path(data_dir, |
| 556 |
shiny_prerendered_data_file_name(label, cache)) |
| 557 |
save(list = ls(data_env), |
| 558 |
file = rdata_file, |
| 559 |
envir = data_env, |
| 560 |
compress = FALSE) |
| 561 |
|
| 562 |
for (name in ls(data_env)) { |
| 563 |
assign(name, get(name, envir = data_env), envir = envir) |
| 564 |
remove(list = c(name), envir = data_env) |
| 565 |
} |
| 566 |
|
| 567 |
# return results of evaluation (used for knitr cache) |
| 568 |
result |
| 569 |
} |
| 570 |
|
| 571 |
# straight evaluate if this is a render context |
| 572 |
else if ("render" %in% context) { |
| 573 |
evaluate::evaluate(code, envir, ...) |
| 574 |
} |
| 575 |
|
| 576 |
# otherwise parse so we can throw an error for invalid code |
| 577 |
else { |
| 578 |
xfun::parse_only(code) |
| 579 |
list() |
| 580 |
} |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
# Remove prerendered .RData that isn't in the cache (as data in the |
| 585 |
# cache won't necessarily be recreated during the next render) |
| 586 |
shiny_prerendered_remove_uncached_data <- function(input) { |
| 587 |
data_dir <- shiny_prerendered_data_dir(input) |
| 588 |
if (dir_exists(data_dir)) { |
| 589 |
index_file <- shiny_prerendered_data_chunks_index(data_dir) |
| 590 |
if (file.exists(index_file)) |
| 591 |
unlink(index_file) |
| 592 |
rdata_files <- list.files(data_dir, pattern = utils::glob2rx("*.RData")) |
| 593 |
cached_rdata_files <- list.files(data_dir, pattern = utils::glob2rx("*.cached.RData")) |
| 594 |
uncached_rdata_files <- setdiff(rdata_files, cached_rdata_files) |
| 595 |
unlink(file.path(data_dir, uncached_rdata_files)) |
| 596 |
} |
| 597 |
} |
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
# Extract application/shiny-prerendered script tags from an html document |
| 602 |
shiny_prerendered_extract_context <- function(html_lines, context) { |
| 603 |
|
| 604 |
# look for lines that start the context |
| 605 |
pattern <- paste0('<script type="application/shiny-prerendered" data-context="', context, '">') |
| 606 |
matches <- regmatches(html_lines, regexec(pattern, html_lines, fixed = TRUE)) |
| 607 |
|
| 608 |
# extract the code within the contexts |
| 609 |
in_context <- FALSE |
| 610 |
context_lines <- character() |
| 611 |
for (i in 1:length(matches)) { |
| 612 |
if (length(matches[[i]]) > 0) { |
| 613 |
in_context <- TRUE |
| 614 |
next |
| 615 |
} |
| 616 |
else if (in_context && identical(html_lines[[i]], "</script>")) { |
| 617 |
in_context <- FALSE |
| 618 |
} |
| 619 |
if (in_context) |
| 620 |
context_lines <- c(context_lines, html_lines[[i]]) |
| 621 |
} |
| 622 |
|
| 623 |
# unescape code, see https://github.com/rstudio/rmarkdown/issues/943 |
| 624 |
context_lines <- gsub("<\\u002f", "</", context_lines, fixed = TRUE) |
| 625 |
context_lines |
| 626 |
} |
| 627 |
|
| 628 |
shiny_prerendered_remove_contexts <- function(html_lines, contexts) { |
| 629 |
|
| 630 |
# look for lines that start the contexts |
| 631 |
pattern <- paste0('<script type="application/shiny-prerendered" data-context="') |
| 632 |
matches <- regmatches(html_lines, regexec(pattern, html_lines, fixed = TRUE)) |
| 633 |
|
| 634 |
# create a regex pattern used for matching named contexts |
| 635 |
contexts_pattern <- paste0(pattern, "(", paste(contexts, collapse = "|"), ")") |
| 636 |
|
| 637 |
# new_html_lines to return |
| 638 |
new_html_lines <- character() |
| 639 |
|
| 640 |
# ignore the code within the contexts |
| 641 |
in_context <- FALSE |
| 642 |
for (i in 1:length(matches)) { |
| 643 |
if (length(matches[[i]]) > 0 && grepl(contexts_pattern, html_lines[[i]])) { |
| 644 |
in_context = TRUE |
| 645 |
} |
| 646 |
else if (in_context && identical(html_lines[[i]], "</script>")) { |
| 647 |
in_context <- FALSE |
| 648 |
} |
| 649 |
else if (!in_context) |
| 650 |
new_html_lines <- c(new_html_lines, html_lines[[i]]) |
| 651 |
} |
| 652 |
|
| 653 |
# return |
| 654 |
new_html_lines |
| 655 |
} |
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
# Gather shiny_prerendred contexts and append them as script tags to |
| 660 |
# the passed file |
| 661 |
shiny_prerendered_append_contexts <- function(runtime, file) { |
| 662 |
|
| 663 |
# collect contexts |
| 664 |
shiny_prerendered_contexts <- knit_meta_reset(class = "shiny_prerendered") |
| 665 |
if (length(shiny_prerendered_contexts) > 0) { |
| 666 |
|
| 667 |
# validate we are in runtime: shiny_prerendered |
| 668 |
if (!is_shiny_prerendered(runtime)) { |
| 669 |
stop2("The code within this document requires server: shiny") |
| 670 |
} |
| 671 |
|
| 672 |
# open the file |
| 673 |
con <- file(file, open = "at", encoding = 'UTF-8') |
| 674 |
on.exit(close(con), add = TRUE) |
| 675 |
|
| 676 |
# track singletons |
| 677 |
singletons <- list() |
| 678 |
|
| 679 |
# append the contexts as script tags |
| 680 |
for (context in shiny_prerendered_contexts) { |
| 681 |
|
| 682 |
# resolve singletons |
| 683 |
if (isTRUE(context$singleton)) { |
| 684 |
found_singleton <- FALSE |
| 685 |
for (singleton in singletons) { |
| 686 |
if (identical(context, singleton)) { |
| 687 |
found_singleton <- TRUE |
| 688 |
break |
| 689 |
} |
| 690 |
} |
| 691 |
if (found_singleton) next |
| 692 |
singletons[[length(singletons) + 1]] <- context |
| 693 |
} |
| 694 |
|
| 695 |
# append context |
| 696 |
shiny_prerendered_append_context(con, context$name, context$code) |
| 697 |
} |
| 698 |
} |
| 699 |
} |
| 700 |
|
| 701 |
shiny_prerendered_append_context <- function(con, name, code) { |
| 702 |
lines <- c('<!--html_preserve-->', |
| 703 |
paste0('<script type="application/shiny-prerendered" ', |
| 704 |
'data-context="', name ,'">'), |
| 705 |
# escape code, see https://github.com/rstudio/rmarkdown/issues/943 |
| 706 |
gsub("</", "<\\u002f", code, fixed = TRUE), |
| 707 |
'</script>', |
| 708 |
'<!--/html_preserve-->') |
| 709 |
writeLines(lines, con = con) |
| 710 |
} |
| 711 |
|
| 712 |
|
| 713 |
# Prerendred data_dir for a given Rmd input file |
| 714 |
shiny_prerendered_data_dir <- function(input, create = FALSE) { |
| 715 |
data_dir <- paste0(xfun::sans_ext(input), "_data") |
| 716 |
if (create && !dir_exists(data_dir)) |
| 717 |
dir.create(data_dir) |
| 718 |
data_dir |
| 719 |
} |
| 720 |
|
| 721 |
|
| 722 |
# Load prerendred data into the server environment. There are two |
| 723 |
# reasons we load data based on a previously generated index file: |
| 724 |
# |
| 725 |
# (1) We don't remove all of the previously generated .RData files |
| 726 |
# at the beginning of a render. Specifically, we don't remove |
| 727 |
# .RData files that were created within a chunk w/ caching |
| 728 |
# enabled, since that .RData won't necessarily be re-created on |
| 729 |
# the next render. This means that we could be left with "stale" |
| 730 |
# .RData files from cached chunks. Reading based on the list |
| 731 |
# ensures that we only read .RData for chunks that were |
| 732 |
# included in the last rendered document. |
| 733 |
# |
| 734 |
# (2) We want to load data into the server environment in the |
| 735 |
# exact same chunk order that it appears in the document. |
| 736 |
# |
| 737 |
shiny_prerendered_data_load <- function(input_rmd, server_envir) { |
| 738 |
# check for data_dir |
| 739 |
data_dir <- shiny_prerendered_data_dir(input_rmd) |
| 740 |
if (dir_exists(data_dir)) { |
| 741 |
# read index of data files |
| 742 |
index_file <- shiny_prerendered_data_chunks_index(data_dir) |
| 743 |
if (file.exists(index_file)) { |
| 744 |
rdata_files <- read_utf8(index_file) |
| 745 |
# load each of the files in the index |
| 746 |
for (rdata_file in rdata_files) { |
| 747 |
rdata_file <- file.path(data_dir,rdata_file) |
| 748 |
if (file.exists(rdata_file)) # won't exist if the chunk has no code |
| 749 |
load(rdata_file, envir = server_envir) |
| 750 |
} |
| 751 |
} |
| 752 |
} |
| 753 |
} |
| 754 |
|
| 755 |
# File used to store names of chunks which had cache=TRUE during the last render |
| 756 |
shiny_prerendered_data_chunks_index <- function(data_dir) { |
| 757 |
file.path(data_dir, "data_chunks_index.txt") |
| 758 |
} |
| 759 |
|
| 760 |
# Form the name of a shiny_prerendered .RData file |
| 761 |
shiny_prerendered_data_file_name <- function(label, cache) { |
| 762 |
type <- ifelse(cache, ".cached", "") |
| 763 |
sprintf("%s%s.RData", label, type) |
| 764 |
} |
| 765 |
|
| 766 |
# Use me instead of html_dependency_bootstrap() in a shiny runtime to get |
| 767 |
# dynamic theming (i.e., have it work with session$setCurrentTheme()) |
| 768 |
shiny_bootstrap_lib <- function(theme) { |
| 769 |
theme <- resolve_theme(theme) |
| 770 |
if (!is_bs_theme(theme)) { |
| 771 |
return(NULL) |
| 772 |
} |
| 773 |
if (!is_available("shiny", "1.6.0")) { |
| 774 |
stop( |
| 775 |
"Using a {bslib} theme with `runtime: shiny` requires shiny 1.6.0 or higher." |
| 776 |
) |
| 777 |
} |
| 778 |
shiny::bootstrapLib(theme) |
| 779 |
} |