Sketch of save/restore of input values for specific module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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