Skip to content

Instantly share code, notes, and snippets.

@jcheng5

jcheng5/app.R Secret

Created October 5, 2018 19:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jcheng5/f99b1d0bdd700ac17a21d8e5918cad85 to your computer and use it in GitHub Desktop.
Sketch of save/restore of input values for specific module
library(shiny)
saveRestoreUI <- function(id) {
ns <- NS(id)
tagList(
htmltools::singleton(includeScript("restoretest.js")),
actionButton(ns("save"), "Save"),
actionButton(ns("restore"), "Restore")
)
}
saveRestore <- function(input, output, session, parent_input) {
# What is our parent namespace?
ns_str <- session$ns(NULL)
ns_str <- strsplit(ns_str, shiny::ns.sep, fixed = TRUE)
ns_str <- paste(head(ns_str[[1]], -1), collapse = shiny::ns.sep)
observeEvent(input$save, {
lst <- reactiveValuesToList(parent_input)
lst[["save-save"]] <- NULL
lst[["save-restore"]] <- NULL
saveRDS(lst, paste0(ns_str, ".rds"))
})
observeEvent(input$restore, {
lst <- readRDS(paste0(ns_str, ".rds"))
lst <- setNames(lst, NS(ns_str)(names(lst)))
session$sendCustomMessage("restoretest.restore", lst)
})
}
testUI <- function(id) {
ns <- NS(id)
tagList(
saveRestoreUI(ns("save")),
textInput(ns("txt"), "Text", "hello"),
numericInput(ns("num"), "Numeric", 5),
sliderInput(ns("slider"), "Slider", 1, 10, c(3,5)),
selectInput(ns("select"), "Select", letters, selected = c("b", "c"), multiple = TRUE),
dateRangeInput("date_range", "Date range")
)
}
test <- function(input, output, session) {
callModule(saveRestore, "save", parent_input = input)
}
ui <- fluidPage(
fluidRow(
column(6, testUI("one")),
column(6, testUI("two"))
)
)
server <- function(input, output, session) {
callModule(test, "one")
callModule(test, "two")
}
shinyApp(ui, server)
// Warning, this won't work for some inputs; only inputs that implement setValue
// and whose input$xxx values can be passed to setValue will qualify. This
// probably includes most input bindings that make use of registerInputHandler.
// Date/date range are unlikely to work, for example.
Shiny.addCustomMessageHandler("restoretest.restore", function(data) {
$.each(data, function(name, value) {
var el = document.getElementById(name);
if (!el) {
console.error("No element #" + name + " found");
}
var binding = $(el).data("shinyInputBinding");
if (!binding) {
console.error("No binding for #" + name + " found");
}
binding.setValue(el, value);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment