Shinyのd3 networkで描画を動的に更新する(render & jQuery)

・ShinyでTimerを使うにはreactivetimer()がある
Serverの引数にsessionを渡さないといけない

・Shinyのd3 networkにはrenderPlotしても前のノードが残されて
新しいSVGのDOM領域が追加される形で描画されるという
バグっぽい挙動がある.
結局アップデートのタイミングでJavaScript(d3.js)を呼んで,

d3.select("svg")
       .remove();

することで解決した.
http://stackoverflow.com/questions/10784018/how-can-i-remove-or-replace-svg-content

・外部JavaScriptの読み込みには
wwwディレクトリを作ってそこに静的ファイルを置く
http://stackoverflow.com/questions/23599268/include-a-javascript-file-in-shiny-app

・Shiny serverからjQuery(JavaScriipt)を叩くには
Send Custom Messageを使う.
http://stackoverflow.com/questions/26003978/shiny-and-javascript-interaction-with-sessionsendcustommessage

ui.R

library(shiny)

shinyUI(fluidPage(

    # Load d3.js
    tags$head(
        tags$script(src = 'http://d3js.org/d3.v3.min.js')
    ),

    tags$script('
      Shiny.addCustomMessageHandler("deleteSVG",
        function(e){
             d3.select("svg").remove();
             console.log("removed previous svg");
      });
    '),

    # Application title
    titlePanel('d3Network Shiny Example'),
    p('This is an example of using',
    a(href = 'http://christophergandrud.github.io/d3Network/', 'd3Network'),
        'with',
        a(href = 'http://shiny.rstudio.com/', 'Shiny', 'web apps.')
    ),

    # Sidebar with a slider input for node opacity
    sidebarLayout(
        sidebarPanel(
            sliderInput('slider', label = 'Choose node opacity',
                min = 0, max = 1, step = 0.01, value = 0.5
            )
    ),

    # Show network graph
    mainPanel(
        #p(textOutput('networkPlot'))
        htmlOutput('networkPlot')
    )
  )
))

server.R

library(d3Network)

shinyServer(function(input, output,session) {
    
  Source <- c("A", "A", "A", "A", "B", "B", "C", "C", "D")
  Target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I")
  colors <- c('orange','red','blue','green','yellow')
  NetworkData <- data.frame(Source, Target)

  autoInvalidate <- reactiveTimer(2000, session)
  num <- runif(1,1,5)
  
  observe({
    autoInvalidate()
    num <- runif(1,1,5)

    session$sendCustomMessage(type = 'deleteSVG',message=list(a=1))

    output$networkPlot <- renderPrint({
        d3SimpleNetwork(NetworkData, height = 300, width = 700,
            nodeColour=colors[num])
    })
  })


})