I would like to make a plot where you can zoom in and zoom out with the keyboard arrows up and down. This is what I have done. It worked pretty well, but there is still a major problem.
library(shiny)
library(dplyr)
library(ggplot2)
ui <- fluidPage(
tags$script(
'$(document).on("keyup", function(e) {
if(e.keyCode == 38){
Shiny.onInputChange("up", Math.random());
}
if(e.keyCode == 40){
Shiny.onInputChange("down", Math.random());
}
});'
),
uiOutput("whole_page")
)
server <- function (input, output, session) {
min <- 0
max <- 1000000
view_size <- reactiveVal(max - min)
view_center <- reactiveVal(mean(c(max, min)))
position <- reactiveVal(c(min, max))
observeEvent(c(view_size(), view_center()), {
from <- (view_center() - (view_size() / 2))
to <- (view_center() + (view_size() / 2))
c(from, to) %>% position()
})
output$whole_page <- renderUI({
fluidPage(
sliderInput("slider", "range:", min = min, max= max, value = position(), step = 1),
plotOutput("plot")
)
})
output$plot <- renderPlot({
ggplot(data = tibble(pos = position())) +
geom_point(aes(x = pos, y = 0))
})
observeEvent(input$slider, {
input$slider %>% position()
})
observeEvent(position(), {
position() %>%
mean() %>%
view_center()
position() %>%
diff() %>%
view_size()
})
observeEvent(input$up, {
(view_size() / 2) %>%
view_size()
})
observeEvent(input$down, {
(view_size() * 2) %>%
view_size()
})
}
shinyApp(ui, server)
The remaining problem is that when you quickly click on the upper arrow several times, it makes the application crash, it starts to continuously switch from one zoom level to the other and you have to restart the application.
Can someone help me solve this problem and allow fast zooming?
Note: This is my first post on this forum, as I usually find the answers to my questions in the previously asked questions. This forum is really a goldmine for code-related questions.