You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.3KB

  1. library("knitr")
  2. library("htmltools")
  3. library("base64enc")
  4. library("markdown")
  5. render_with_widgets <- function(input_file,
  6. output_file = sub("\\.Rmd$", ".html", input_file, ignore.case = TRUE),
  7. self_contained = TRUE,
  8. deps_path = file.path(dirname(output_file), "deps"))
  9. {
  10. # Read input and convert to Markdown
  11. input <- readLines(input_file)
  12. md <- knit(text = input)
  13. # Get dependencies from knitr
  14. deps <- knit_meta()
  15. # Convert script dependencies into data URIs, and stylesheet
  16. # dependencies into inline stylesheets
  17. dep_scripts <- lapply(deps, function(x)
  18. {
  19. lapply(x$script, function(script) file.path(x$src$file, script))
  20. })
  21. dep_stylesheets <- lapply(deps, function(x)
  22. {
  23. lapply(x$stylesheet, function(stylesheet) file.path(x$src$file, stylesheet))
  24. })
  25. dep_scripts <- unique(unlist(dep_scripts))
  26. dep_stylesheets <- unique(unlist(dep_stylesheets))
  27. if (self_contained) {
  28. dep_html <- c(sapply(dep_scripts, function(script)
  29. {
  30. sprintf('<script type="text/javascript" src="%s"></script>', dataURI(file = script))
  31. }),
  32. sapply(dep_stylesheets, function(sheet)
  33. {
  34. sprintf('<style>%s</style>', paste(readLines(sheet), collapse = "\n"))
  35. })
  36. )
  37. } else {
  38. if (!dir.exists(deps_path))
  39. {
  40. dir.create(deps_path)
  41. }
  42. for (fil in c(dep_scripts, dep_stylesheets))
  43. {
  44. file.copy(fil, file.path(deps_path, basename(fil)))
  45. }
  46. dep_html <- c(sprintf('<script type="text/javascript" src="%s"></script>', file.path(deps_path, basename(dep_scripts))),
  47. sprintf('<link href="%s" type="text/css" rel="stylesheet">', file.path(deps_path, basename(dep_stylesheets))))
  48. }
  49. # Extract the <!--html_preserve--> bits
  50. preserved <- extractPreserveChunks(md)
  51. # Render the HTML, and then restore the preserved chunks
  52. html <- markdownToHTML(text = preserved$value, header = dep_html)
  53. html <- restorePreserveChunks(html, preserved$chunks)
  54. # Write the output
  55. writeLines(html, output_file)
  56. }