dreamRs / shinytreeview

Hierarchical tree input for Shiny apps
GNU General Public License v3.0
41 stars 8 forks source link

Specifying initial selection by node ID #15

Open ajirnyiqrm opened 7 months ago

ajirnyiqrm commented 7 months ago

Hi -- first, thanks for the great package!

One question: currently, the selected= argument in treecheckInput() allows to specify the initial selection by value. It works well when the leaves all have unique values, but when they do not, it would be nice to have another way to specify which nodes we want selected. For example, something like c("0.3.1.0", "0.3.1.1") (assuming no conflict) could work.

Looking briefly at the code, it might be that the functionality is already there: e.g. lines 70-72 in treeview.js have

        if (selected.length < 1) {
          selected = tree.findNodes("^" + data.selected[i] + "$", "id");
        }

But I'm not sure how to use it or what the id parameter is -- perhaps adding the same for nodeId (assuming value search and id lookups have both failed) might work?

Thank you!

pvictor commented 7 months ago

Hello,

You can create IDs into your data for each levels, and then specify to create_tree which columns contains ID. Here's an example:

library(shiny)
library(shinytreeview)

mydata <- data.frame(
  lvl_1 = c("A", "A", "A", "B", "B", "B"),
  lvl_2 = c("a", "b", "c", "a", "b", "c")
)

# Create ID for level 1
mydata$lvl_1_id <- paste0(
  "ID_", as.numeric(as.factor(mydata$lvl_1))
)

# Create ID for level 2 (including level 1 for unique ID)
mydata$lvl_2_id <- paste0(
  "ID_", 
  as.numeric(as.factor(mydata$lvl_1)),
  "_",
  as.numeric(as.factor(mydata$lvl_2))
)

ui <- fluidPage(
  treecheckInput(
    inputId = "tree",
    label = "Select value:",
    choices = make_tree(
      mydata, 
      levels = c("lvl_1", "lvl_2"),
      levels_id = c("lvl_1_id", "lvl_2_id")
    ), 
    levels = 2,
    selected = "ID_1_2",
    return_value = "id"
  ),
  verbatimTextOutput(outputId = "result")
)

server <- function(input, output, session) {
  output$result <- renderPrint({
    input$tree
  })
}

if (interactive())
  shinyApp(ui, server)

Victor