ramnathv / htmlwidgets

HTML Widgets for R
http://htmlwidgets.org
Other
792 stars 205 forks source link

No Shiny reactivity #485

Closed stla closed 8 months ago

stla commented 8 months ago

Hello,

I have a widget amVennDiagram and a Shiny app like this:

library(amVennDiagram5)
library(shiny)

diagrams <- allVennDiagrams(c(2, 2, 1), output = "lists")

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      radioButtons(
        "index",
        "Diagram",
        choices = 1:9
      )
    ),
    mainPanel(
      amVennDiagramOutput("diagram")
    )
  )
)

server <- function(input, output, session) {
  output[["diagram"]] <- renderAmVennDiagram({
    i <- as.integer(input[["index"]])
    print(i)
    amVennDiagram(diagrams[[i]], theme = "material")
  })
}

shinyApp(ui, server)

When I click a radio button then diagrams[[i]] changes, but the displayed Venn diagram is not updated. I also encounter this problem with other HTML widgets. I'm using the template for the Shiny bindings.

stla commented 8 months ago

In fact the re-rendering triggers an error, and I know why.

The JS code starts with: var root = am5.Root.new(el.id);. When the re-rendering occurs, this object is not destroyed and then there is an error.

So the only solution I found is:

  factory: function (el, width, height) {
    var inShiny = HTMLWidgets.shinyMode;
    var root;
    if (inShiny) {
      Shiny.addCustomMessageHandler(el.id + "_destroy", function (x) {
        if (root) {
          root.dispose();
        }
      });
    }

    return {
      renderValue: function (x) {
        // Create root
        root = am5.Root.new(el.id);
        ......

And then I add session$sendCustomMessage ... in the renderAmVennDiagram call.