闪亮的警报/通知

Alert / notification in shiny

当用户点击下载按钮时,我想在闪亮的应用程序中有一个提醒/通知! 如果您有一个像 :

这样的操作按钮,所有示例都可以正常工作
library(shiny)
library(shinyalert)
 
ui <- fluidPage(
   useShinyalert(),  # Set up shinyalert
   actionButton("preview", "Preview")
 )
 
 server <- function(input, output, session) {
   observeEvent(input$preview, {
     # Show a modal when the button is pressed
     shinyalert("Oops!", "Something went wrong.", type = "error")
   })
 }
 
 shinyApp(ui, server)

我想为下载按钮设计类似的概念,如果我们有一个下载按钮,那么就没有 input$preview 因为我假设 downloadButton 我们有 output$preview 并且确实如此不适用于当前设置!

因此,要获得有关如何使用此弹出窗口确认下载的更全面的示例,您可以执行以下操作:

  1. 我们根据示例创建另一个操作按钮here
  2. 我们将使用 style = "visibility: hidden;"
  3. 隐藏原来的 downloadButton
  4. 我们将通过document.getElementById('downloadData').click();
  5. 监听下载事件
  6. 我们将创建一个 reactiveValues 变量来查看用户是否要下载数据
  7. 最后,我们需要重新设置response,这样就可以连续点击弹窗中的Ok按钮,否则不会再次触发,因为设置为TRUE

library(shiny)
library(shinyalert)

ui <- fluidPage(
    shinyjs::useShinyjs(),
    useShinyalert(), 
    actionButton("init", "Download", icon = icon("download")),
    downloadButton("downloadData", "Download", style = "visibility: hidden;")
)

server <- function(input, output, session) {

    global <- reactiveValues(response = FALSE)
    
    observeEvent(input$init,{
        shinyalert("Confirmation", 
                   "Do you want to download the data?", 
                   type = "success",
                   callbackR = function(x) {
                       global$response <- x
                   },
                   showCancelButton = TRUE
        )
    })
    
    observeEvent(global$response,{
        if(global$response){
            shinyjs::runjs("document.getElementById('downloadData').click();")
            global$response <- FALSE
        }
    })
    
    output$downloadData <- downloadHandler(
        filename = function() {
            paste("data-", Sys.Date(), ".csv", sep="")
        },
        content = function(file) {
            write.csv(mtcars, file)
        }
    )
}

shinyApp(ui, server)