I have the shiny app below in which I use js to add controls to zoom and reset on a svg
file. It was working until the moment I put the output inside another UiOutput.
library(shiny)
library(shinyWidgets)
library(DiagrammeR)
library(magrittr)
js <- '
$(document).ready(function(){
var element = document.getElementById("grr");
var instance = panzoom(element);
var z = 1;
$("#zoomout").on("click", function(){
instance.smoothZoom(0, 0, 0.9);
z *= 0.9;
});
$("#zoomin").on("click", function(){
instance.smoothZoom(0, 0, 1.1);
z *= 1.1;
});
$("#reset").on("click", function(){
instance.smoothZoom(0, 0, 1/z);
z = 1;
});
$("#zoomout").on("dblclick", function(){
return false;
});
$("#zoomin").on("dblclick", function(){
return false;
});
});
'
ui <- fluidPage(
tags$head(
tags$script(src = "https://unpkg.com/[email protected]/dist/panzoom.min.js"),
tags$script(HTML(js))
),
uiOutput("main")
#grVizOutput("grr", width = "100%", height = "90vh"),
)
server <- function(input, output) {
output$main <- renderUI({
div(
grVizOutput("grr", width = "100%", height = "90vh"),
actionGroupButtons(
inputIds = c("zoomout", "zoomin", "reset"),
labels = list(icon("minus"), icon("plus"), "Reset"),
status = "primary"
)
)
})
output$grr <- renderGrViz(render_graph(
create_graph() %>%
add_n_nodes(n = 2) %>%
add_edge(
from = 1,
to = 2,
edge_data = edge_data(
value = 4.3
)
)
))
}
shinyApp(ui, server)
CodePudding user response:
That's because the elements defined in the renderUI
are not ready yet when the document is ready. A possible technique is to use an interval which will "screen" the document every 100ms, until it finds the element.
library(shiny)
library(shinyWidgets)
library(DiagrammeR)
library(magrittr)
js <- '
$(document).ready(function(){
var instance;
var myinterval = setInterval(function(){
var element = document.getElementById("grr");
if(element !== null){
clearInterval(myinterval);
instance = panzoom(element);
}
}, 100);
var z = 1;
$("body").on("click", "#zoomout", function(){
instance.smoothZoom(0, 0, 0.9);
z *= 0.9;
});
$("body").on("click", "#zoomin", function(){
instance.smoothZoom(0, 0, 1.1);
z *= 1.1;
});
$("body").on("click", "#reset", function(){
instance.smoothZoom(0, 0, 1/z);
z = 1;
});
$("body").on("dblclick", "#zoomout", function(){
return false;
});
$("body").on("dblclick", "#zoomin", function(){
return false;
});
});
'
ui <- fluidPage(
tags$head(
tags$script(src = "https://unpkg.com/[email protected]/dist/panzoom.min.js"),
tags$script(HTML(js))
),
uiOutput("main")
#grVizOutput("grr", width = "100%", height = "90vh"),
)
server <- function(input, output) {
output$main <- renderUI({
div(
grVizOutput("grr", width = "100%", height = "90vh"),
actionGroupButtons(
inputIds = c("zoomout", "zoomin", "reset"),
labels = list(icon("minus"), icon("plus"), "Reset"),
status = "primary"
)
)
})
output$grr <- renderGrViz(render_graph(
create_graph() %>%
add_n_nodes(n = 2) %>%
add_edge(
from = 1,
to = 2,
edge_data = edge_data(
value = 4.3
)
)
))
}
shinyApp(ui, server)