R Shiny - Run application in background and issue UI controls with code

Viewed 72

I am writing a vignette for my Shiny application package. At the beginning of my vignette, I source a file called screenshots.R that produces nice screenshots of my application. I am producing them like so:

webshot::appshot(mypackage::run_datepicker_app(),
                 file = "man/figures/datepicker.png", vwidth = 500, vheight = 200)

This works great and it gives me a great screenshot of what is - in this case - a couple dateInput fields. However, I'd like to be able to get a screenshot of the dateInput in use (say, with the calendar selection exposed).

Is there a way to issue commands to the application object in a script so I can get screenshots of the application in use, rather than having to do it manually?

1 Answers

Have you tried using ShinyDriver from the shinytest package?

You can use shinytest to have a headless browser run the app, interact with it, and take screenshots programmatically. If you don't have phantomJS installed, you'll need to run shinytest::installDependencies() before using ShinyDriver. All you need to do is point it to a directory containing a shiny app (in my case, the folder is 'myApp').

install.packages("shinytest")
shinytest::installDependencies()

app <- shinytest::ShinyDriver$new("myApp")
app$takeScreenshot("screenshot1.png")
button <- app$findElement("#button")
button$click()
Sys.sleep(1)
app$takeScreenshot("screenshot2.png")                
app$stop()

I am starting the app in a headless browser, taking a screenshot, finding the button with the id 'button', clicking it, and taking another screenshot, then closing the app. Navigate to specific elements using "#id", where id is just the id you gave the shiny input. You can specify a file path to a png file in the takeScreenshot calls, so that you can then use them in your code elsewhere. Note that you may need to use Sys.sleep to stop the screenshots from being taken before the UI updates.

Related