在ShinyTree中保存和还原选择

时间:2019-09-16 08:13:58

标签: save selection shinytree

是否可以保存和恢复ShinyTree的选择?

我找到了删除选择的解决方案 R Shiny - Updating shinyTree node selections

但是我需要保存选择并稍后通过例如actionButton将其恢复

1 个答案:

答案 0 :(得分:0)

这仅适用于shinyTree。基础jsTree库的某些函数必须直接调用,并将值从JavaScript传递到R,反之亦然。

我举了一个小例子,这应该对您有帮助。

如果通过单击按钮保存选择,R会向JavaScript发送一条自定义消息,JavaScript会获取选定的ID,然后通过Shiny.setInputValue将其返回给R。

然后将选定的ID保存在reactvalues selectionRV中,但是如果需要,您可以将它们保存在文件或数据库中。

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)