是否可以保存和恢复闪亮树的选择?
我找到了一个解决方案删除选择 R Shiny - 更新 shinyTree 节点选择
但我需要保存选择并稍后恢复它们,例如,通过 actionButton
This is not possible with shinyTree
only. Some functions of the underlying jsTree
library have to be called directly and the values passed from JavaScript to R and vice-versa.
I made a small example, which should help you as a starting point.
If you save a selection via button-click, R sends a custom message to JavaScript, which will get the selected IDs and returns it to R via Shiny.setInputValue
.
The selected ID's are then saved in the reactiveValues selectionRV
, but you could save them in a file or database if needed.
library(shiny)
library(shinyTree)
library(shinyjs)
js <- HTML("
$(document).on('shiny:connected', function(event) {
Shiny.addCustomMessageHandler('saveselection', function(e) {
var selection = $('#tree').jstree().get_selected();
Shiny.setInputValue('treeselection', selection, {priority: 'event'});
});
})
")
## ui ####################
ui <- fluidPage(
useShinyjs(),
tags$head(tags$script(js)),
actionButton("deselect", "Deselect all"),
actionButton("savesele", "Save Selection"),
actionButton("restoresele", "Restore Selection"),
shinyTree("tree", dragAndDrop = TRUE,types= #Types is in the same format that jstree expects
"{
'#': { 'max_children' : 2, 'max_depth' : 4, 'valid_children' : ['root'] },
'root' : { 'valid_children' : ['file'] },
'default' : { 'valid_children' : ['default','file'] },
'file' : { 'icon' : 'fa fa-file', 'valid_children' : [] }
}"
)
)
## server ####################
server <- function(input, output, session) {
treeData <- reactive({
rootstrc <- structure(list(
SubListA = structure(list(
leaf1 = structure("",sttype="file",sticon="fa fa-signal"),
leaf2 = structure("",sttype="file",sticon="fa fa-signal"),
leaf3 = structure("",sttype="file",sticon="fa fa-signal")),
sttype="root",stopened=F,sticon="fa fa-signal"
),
SubListB = structure(list(
leafA = structure("",sttype="default",sticon="glyphicon glyphicon-leaf"),
leafB = structure("",sttype="default",sticon="shinyTree/icon.png"),
leafC = structure("",sttype="default",sticon="fa fa-signal")
),stopened=F,sttype="root",sticon="fa fa-signal")
),
sttype="root",stopened=F,sticon="fa fa-signal"
)
list(
root1 = rootstrc,
root2 = rootstrc,
root3 = rootstrc,
root4 = rootstrc
)
})
output$tree <- renderTree({
treeData()
})
selectionRV <- reactiveValues(list = NULL)
observeEvent(input$deselect, {
runjs("$('#tree').jstree().deselect_all()")
})
observeEvent(input$savesele, {
session$sendCustomMessage("saveselection", message)
})
observeEvent(input$restoresele, {
req(input$treeselection)
tmp <- paste0("[", paste(input$treeselection, collapse = ","), "]")
js <- sprintf("$('#tree').jstree().select_node(%s)", tmp)
runjs(js)
})
}
shinyApp(ui, server)