Search code examples
rshinymutation-observers

How to correclty use MutationObserve in Shiny app


I'm trying to observe changes to css using javascript mutationObserver in Shiny. I'm using rhandsontable because we can change the width of a table element in the app, and I'm trying to pick up this change iwth the mutationObserver.

The javascript doesn't seem to be working. I'm unsure why. Nothing is logged to the console, no alert message, and shiny doesn't register the variable being set by javascript.

MutationObserver code

jsCode <- "
    const observer = new MutationObserver(
      # this function runs when something is observed.
      function(mutations){
        console.log('activated')
        var i;
        var text;
        var widthArray = [];
        text = ''
        for (i = 0; i < document.getElementsByClassName('htCore')[0].getElementsByTagName('col').length; i++) {
          text += document.getElementsByClassName('htCore')[0].getElementsByTagName('col')[i].style.width + '<br>';
          widthArray.push(document.getElementsByClassName('htCore')[0].getElementsByTagName('col')[i].style.width);
        }
        alert(text)
        Shiny.setInputValue('colWidth', widthArray);
      }
    )
    const cols = document.getElementsByClassName('htCore')[0].getElementsByTagName('col')
    observer.observe(cols, {
      attributes: true # observe when attributes of ul.bears change (width, height)
    })
"

Shiny code:

library(shiny)
library(rhandsontable)

ui <- fluidPage(
  tags$head(tags$script(HTML(jsCode))),
  rhandsontable::rHandsontableOutput("dataTable")
)
server <- function(input, output, session) {
    df = data.frame(
        company = c('a', 'b', 'c', 'd'),
        bond = c(0.2, 1, 0.3, 0),
        equity = c(0.7, 0, 0.5, 1),
        cash = c(0.1, 0, 0.2, 0),
        stringsAsFactors = FALSE
    )
  output$dataTable <- renderRHandsontable({
      rhandsontable(df, manualColumnResize = TRUE, manualRowResize = TRUE)
    })
  observeEvent(input$colWidth, {
    print(input$colWidth)
  })
}
shinyApp(ui, server)



Solution

  • This works:

    jsCode <- "
    $(document).on('shiny:connected', function(){
      setTimeout(function(){
        const observer = new MutationObserver(
          function(mutations){
            console.log('activated')
            var i;
            var text;
            var widthArray = [];
            text = ''
            for (i = 0; i < document.getElementsByClassName('htCore')[0].getElementsByTagName('col').length; i++) {
              text += document.getElementsByClassName('htCore')[0].getElementsByTagName('col')[i].style.width + '<br>';
              widthArray.push(document.getElementsByClassName('htCore')[0].getElementsByTagName('col')[i].style.width);
            }
            alert(text)
            Shiny.setInputValue('colWidth', widthArray);
          }
        )
        const cols = document.getElementsByClassName('htCore')[0].getElementsByTagName('colgroup')[0]
        observer.observe(cols, {
          attributes: true, subtree: true 
        });
      }, 500);
    });
    "