datastorm-open / visNetwork

R package, using vis.js library for network visualization
Other
542 stars 127 forks source link

HOWTO receive event when node is selected #464

Open kjeipta opened 10 months ago

kjeipta commented 10 months ago

https://github.com/datastorm-open/visNetwork/issues/176 Shows how to retrieve the selected node after-the-fact with an additional button press. Can you please give an example of how to process the selection of a node by a user as an event using observeEvent where the event handler accesses the position information of the selected node?

There is code in the project I am working on that added a JavaScript select handler to propagate the selected data and edge information:

    output$network <- renderVisNetwork(
      {
        visNetwork(nodes, edges, height = "800px", width = "100%") %>%
   :
   :
          visEvents(select = glue::glue("function(data) {{
                                    Shiny.setInputValue('{NS(id)('current_nodes_selection')}', data.nodes);
                                    Shiny.setInputValue('{NS(id)('current_edges_selection')}', data.edges);
                                    ;}}"))

But this seems to break other functionality like the ability to get node positions while only returning the ID of the selected nodes. This no longer works with the JavaScript event hander in place:

visNetworkProxy("network") %>% visGetPositions()
kjeipta commented 10 months ago

I sort of figured it out. I don't think this always gets the final position, but after reading through https://github.com/datastorm-open/visNetwork/blob/master/inst/htmlwidgets/visNetwork.js I don't know that it is possible to do better:

# In module UI function:
    visNetworkOutput(ns("network"), width = "100%", height = 800

# In module server function:
    observeEvent(input$network_highlight_color_id, {
      print(paste0("Selected items are:", input$network_highlight_color_id))
      rv_session[["highlighted_items"]] = input$network_highlight_color_id
      proxy <- visNetworkProxy(ns("network"))
      visGetPositions(proxy)
    })

    observeEvent(input$network_positions, {
      rv_session[["selected_positions"]] = do.call("rbind", lapply(rv_session[["highlighted_items"]], function(id) {data.frame(id=id, x=input$network_positions[[id]][["x"]], y=input$network_positions[[id]][["y"]])}))
    })

Where rv_session is a reactiveValues collection created in my app.R server function which I pass in to all of my modules.