Coder Social home page Coder Social logo

daattali / shinyalert Goto Github PK

View Code? Open in Web Editor NEW
242.0 5.0 26.0 580 KB

🗯️ Easily create pretty popup messages (modals) in Shiny

Home Page: https://daattali.com/shiny/shinyalert-demo/

License: Other

R 72.83% JavaScript 18.13% CSS 9.04%
r shiny rstats r-package shiny-r

shinyalert's Introduction

shinyalert

🗯️ Easily create pretty popup messages (modals) in Shiny

Demo · by Dean Attali

R build status CRAN version


{shinyalert} lets you easily create pretty popup messages (modals) in Shiny.

Modals can contain text, images, OK/Cancel buttons, Shiny inputs, and Shiny outputs (such as plots and tables). A modal can also have a timer to close automatically, and you can specify custom code to run when a modal closes. See the demo Shiny app online for examples.

Need Shiny help? I'm available for consulting.
If you find {shinyalert} useful, please consider supporting my work! ❤

This package is part of a larger ecosystem of packages with a shared vision: solving common Shiny issues and improving Shiny apps with minimal effort, minimal code changes, and clear documentation. Other packages for your Shiny apps:

Package Description Demo
shinyjs 💡 Easily improve the user experience of your Shiny apps in seconds 🔗
shinyscreenshot 📷 Capture screenshots of entire pages or parts of pages in Shiny apps 🔗
timevis 📅 Create interactive timeline visualizations in R 🔗
shinycssloaders ⌛ Add loading animations to a Shiny output while it's recalculating 🔗
colourpicker 🎨 A colour picker tool for Shiny and for selecting colours in plots 🔗
shinybrowser 🌐 Find out information about a user's web browser in Shiny apps 🔗
shinydisconnect 🔌 Show a nice message when a Shiny app disconnects or errors 🔗
shinytip 💬 Simple flexible tooltips for Shiny apps WIP
shinymixpanel 🔍 Track user interactions with Mixpanel in Shiny apps or R scripts WIP
shinyforms 📝 Easily create questionnaire-type forms with Shiny WIP

Table of contents

Examples

Example 1: Simple modal

basic modal

Example 2: Simple input modals

input modal

Example 3: Shiny inputs/outputs in modals

Shiny inputs

Example 4: Chaining modals

chaining modals

Sponsors 🏆

There are no sponsors yet

Become the first sponsor for {shinyalert}!

Overview

{shinyalert} uses the sweetalert JavaScript library to create simple and elegant popups (modals) in Shiny.

Simply call shinyalert() with the desired arguments, such as a title and text, and a modal will show up. Here is a minimal Shiny app code that creates a modal:

library(shiny)
library(shinyalert)

ui <- fluidPage(
  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)

Installation

For most users: To install the stable CRAN version:

install.packages("shinyalert")

For advanced users: To install the latest development version from GitHub:

install.packages("remotes")
remotes::install_github("daattali/shinyalert")

Simple input modals

Usually the purpose of a modal is simply informative, to show some information to the user. However, the modal can also be used to retrieve an input from the user by setting the type = "input" parameter.

When using a type="input" modal, only a single input can be used. By default, the input will be a text input, but you can use other input types by specifying the inputType parameter (for example inputType = "number" will expose a numeric input).

Shiny inputs/outputs in modals

While simple input modals are useful for retrieving input from the user, they aren't very flexible - they only allow one input. You can include any Shiny UI code in a modal, including Shiny inputs and outputs (such as plots), by providing Shiny tags in the text parameter and setting html=TRUE. For example, the following code would produce a modal with two inputs:

shinyalert(html = TRUE, text = tagList(
  textInput("name", "What's your name?", "Dean"),
  numericInput("age", "How old are you?", 30)
))

Modal return value

Modals created with {shinyalert} have a return value when they exit.

When using a simple input modal (type="input"), the value of the modal is the value the user entered. Otherwise, the value of the modal is TRUE if the user clicked the "OK" button, and FALSE if the user dismissed the modal (either by clicking the "Cancel" button, using the Escape key, clicking outside the modal, or letting the timer run out).

The return value of the modal can be accessed via input$shinyalert (or using a different input ID if you specify the inputId parameter), as if it were a regular Shiny input. The return value can also be accessed using the modal callbacks.

Callbacks

The return value of the modal is passed as an argument to the callbackR and callbackJS functions (if a callbackR or callbackJS arguments are provided). These functions get called (in R and in JavaScript, respectively) when the modal exits.

For example, using the following {shinyalert} code will result in a modal with an input field. After the user clicks "OK", a hello message will be printed to both the R console and in a native JavaScript alert box. You don't need to provide both callback functions, but in this example both are used for demonstration.

shinyalert(
  "Enter your name", type = "input",
  callbackR = function(x) { message("Hello ", x) },
  callbackJS = "function(x) { alert('Hello ' + x); }"
)

Notice that the callbackR function accepts R code, while the callbackJS function uses JavaScript code.

Since closing the modal with the Escape key results in a return value of FALSE, the callback functions can be modified to not print anything in that case.

shinyalert(
  "Enter your name", type = "input",
  callbackR = function(x) { if(x != FALSE) message("Hello ", x) },
  callbackJS = "function(x) { if (x !== false) { alert('Hello ' + x); } }"
)

Chaining modals

It's possible to chain modals (call multiple modals one after another) by making a shinyalert() call inside a {shinyalert} callback or using the return value of a previous modal. For example:

shinyalert(
  title = "What is your name?", type = "input",
  callbackR = function(value) { shinyalert(paste("Welcome", value)) }
)

Using in Rmarkdown files

You can use {shinyalert} in Rmarkdown documents as well. This only works in interactive Rmd documents (when runtime: shiny is used in the YAML).

---
output: html_document
runtime: shiny
---

```{r}
library(shinyalert)

textInput("name", "Name")
actionButton("button", "Click me")

observeEvent(input$button, {
  shinyalert(title = "Hey", text = input$name)
})
```

Pre-loading the scripts

The first time a {shinyalert} message is shown, the required scripts are automatically inserted to the Shiny app. In real browsers (Chrome/Firefox/etc) this is not an issue, but in some contexts, such as inside RStudio's Viewer on some operating systems, this can sometimes cause the modal to appear glitchy for a brief moment until the scripts load.

If you notice this behaviour and prefer to pre-load the scripts when the Shiny app initializes, you can call useShinyalert(force=TRUE) anywhere in the UI. Note that calling useShinyalert() is NOT required.

Comparison with Shiny modals

Doesn't Shiny already have support for modals?

Yes, it does.

And Shiny's modals are just fine.

I created {shinyalert} for two reasons: first of all, I started working on it well before Shiny had modals. But I decided to keep working on it and release it even afterwards because I find {shinyalert} to be easier to use and to result in much nicer modals. There are also some extra features in {shinyalert}, such as the callback functions and the timer. But ultimately it's a matter of convenience and aesthetics.

Known issues

  • Clicking any <button> tag inside a modal will close the modal. This is due to the underlying JavaScript library having this issue. This means that, for example, using radio buttons from {shinyWidgets} will cause this bug because their radio buttons are implemented using <button>.
  • Chaining modals works fine when the modals contain only text, but when inputs or buttons are involved in chained modals, you may run into an issue such as this one or this one.

Credits

Logo design by Alfredo Hernández.

shinyalert's People

Contributors

ch0c0l8ra1n avatar daattali avatar etiennebacher avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

shinyalert's Issues

Alert slow with callback and large memory reactive

If there is a reactive object that is very large then the shinyalert modal is very slow when there is an R callback.

This is a very odd problem and I spent hours trying to create a minimal example. I find on both Linux and Windows that clicking the modal with callback will take over ten seconds to display if the allocated matrix is over a GB. But the modal without the callback is fast regardless.

Here's sample code: https://gist.github.com/dkulp2/f1a773fcf29cfccd788bc7c8b7b35189

Let me know if I can help. This has become a problem with a production app and I'm eager to try to resolve it.

An alert with a timer causes future alerts to not run

(Taken from #31)

Example:

library(shiny)

ui <- fluidPage(
    shinyalert::useShinyalert(),
    actionButton('test', 'test')
)

server <- function(input, output, session) {
    observeEvent(input$test, {
        shinyalert::shinyalert("modal 1", timer = 1000)
        shinyalert::shinyalert("modal 2")
                               
        
    })
}

shinyApp(ui, server)

[Bug] Cannot access input variable for shinyalert modal created in `callbackR`

I have a simple user interface that asks two questions and takes two user defined values as responces. I have implmented this using the latest version of shinyalert using the new features that allow input controls to be defined in the modals. An example of the process is shown here:

library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),
  
  tags$h2("Demo shinyalert"),
  tags$br(),
  fluidRow(
    column(
      width = 6,
      actionButton("shinyalert_popup",
                   "Alert Popup")
    )
  ),
  fluidRow(
    verbatimTextOutput(outputId = "return_value_1"),
    verbatimTextOutput(outputId = "return_value_2")
  )
)

server <- function(input, output, session) {
  
  observeEvent(input$shinyalert_popup, {
    shinyalert(
      title = "Input Number 1",
      text = tagList(
        "Enter a number",
        textInput(inputId = "shinyalert_value_1",
                  label = "")
      ),
      html = TRUE,
      inputId = "shinyalert_modal",
      showConfirmButton = TRUE,
      confirmButtonText = "OK",
      callbackR = function() {
        shinyalert(
          title = "Input Number 2",
          text = tagList(
            "Enter another number",
            textInput(inputId = "shinyalert_value_2",
                      label = "")
          ),
          html = TRUE,
          inputId = "shinyalert_callback",
          showConfirmButton = TRUE,
          confirmButtonText = "OK"
        )
      }
    )
  })
  
  output$return_value_1 <- renderPrint(input$shinyalert_value_1)
  output$return_value_2 <- renderPrint(input$shinyalert_value_2)
}

shinyApp(ui = ui, server = server)

The responce shows that the first input, from the id shinyalert_value_1 is captured and updates in the ui. The second input, from shinyalert_value_2, which is nested in the callbackR parameter shows a NULL when values are typed and after the modal has been closed. This indicates that the input$shinyalert_value_2 is not found in this configuration.

Validate user input for `type = "input"`

I have a requirement for a new app I am working on and I can't find a way to implment it after reading the docs, I was hoping someone could tell me if it is possible:

Basically, I need to restrict inputs a user can supply. Being able to set the inputType = "number" is helpful in this case as I don't need to validate against non-numeric values, but I would also need to limit the range of allowed values. In one case I am asking the user to supply a year so something like upper and lower limits would work (e.g. 1990 <= input <= 2020).

Is something like this possible?

Dismiss modal after CallbackR finished

Background

callbackR function is executed after modal being dismissed. One potential problem is if callbackR takes seconds to run, the Shiny apps will freeze up.

Simple example

library(shiny)

ui <- fluidPage(
  shinyalert::useShinyalert(),
  actionButton('a','Ok')
)

server <- function(input, output, session) {
  observeEvent(input$a, {
    shinyalert::shinyalert(
      'Warning',
      'Click OK to run code',
      callbackR = function(...){
        # procedure runs for 3~4 seconds
        Sys.sleep(3 + runif(1))
      }
    )
  })
}

shinyApp(ui, server)

If you dismiss the modal and immediately press the "Ok" button, the app freezes around 3 seconds before opening the modal again. This greatly affects user's experience and making callbackR less attractive.

My Solution

I modified your code a little bit, added a function called dismissalert to manually remove messages. I'll submit a PR soon, here is my forked repo. Basically I modified your JS code, and added R function dismissalert to remove arbitrary number of modals.

The working example looks like this:

library(shiny)

ui <- fluidPage(
  shinyalert::useShinyalert(),
  actionButton('a','Ok')
)

server <- function(input, output, session) {
  observeEvent(input$a, {
    shinyalert::shinyalert(
      'Warning',
      'Click OK to run code',
      callbackR = function(...){
        # procedure 1 runs for 3~4 seconds
        Sys.sleep(3 + runif(1))
        # Now dismiss modal 
        shinyalert::dismissalert() # <------------- new function to remove alerts
      }
    )

    # A second modal right after the first one, once user 
    # press OK button, pop up message and show the code is running
    # Once finished, remove all alerts.
    shinyalert::shinyalert(
      'Scheduled!',
      'R is running, please wait for the result...', 
      showConfirmButton = FALSE
    )
  })
}

shinyApp(ui, server)

Can't trigger a second shinyalert based on result of first shinyalert

In a case where I want to show a Confirm modal depending on what a user does in the first modal, the second modal never appears (or appears sporadically).

Code is below, the issue persists even when using callbackR or saving the result in a separate reactiveValue first. The code does run because the print statement shows up but in my main larger app, the modal appears only in the RStudio viewer, and it managed to appear ONCE in-browser.

library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),
  h1("Nothing to see here"),
  actionButton("action", "Click here!")
)

server <- function(input, output, session) {
  
  observeEvent(input$action, {
    shinyalert(
      "Welcome!",
      "What is your name?",
      type = "input",
      showCancelButton = TRUE
    )
  })
  
  observeEvent(input$shinyalert, {
    print(input$shinyalert)
    shinyalert(
      "Thank you for confirming your name",
      input$shinyalert,
      type = "success"
    )
  })
  
}

shinyApp(ui, server)

demo application not loading

I just noticed today that your demo shiny application is not loading due to a 502 nginx error (see screenshot below). Not a huge deal but wanted to make you aware of it.

screen shot 2018-09-14 at 8 53 29 am

Retain input state in modal

Hi @daattali just checked out the latest and greatest shinyalert after seeing your tweet, congrats 🎉

I am currently using shinyBS::bsModal instead of shinyalert::shinyalert, shiny::modalDialog, etc. because shinyBS::bsModal retains the state of my inputs. If I select a couple things from a selectInput, close the modal and then reopen, those selections are still there. This is a very important feature for my use case as I want to prevent users from having to reselect things. Is it possible to preserve the state of inputs when the modal is closed and then reopened? Below is a minimal example that doesn't preserve state:

library(shiny)

ui <- fluidPage(
  shinyalert::useShinyalert(),
  actionButton("go", "go")
)

server <- function(input, output, session) {
  observeEvent(input$go, {
    shinyalert::shinyalert(
      title = "hello",
      html = TRUE,
      text = tagList(
        selectInput("letters", "letters", letters, multiple = TRUE)
      )
    )
  })
}

shinyApp(ui, server)

Render text as HTML

Hi,
Thanks for the great package! Just wondering, is there a way to render whatever is passed to the text argument as HTML? I'm trying to put a hyperlink on the shinyalert dialog.
Cheers

issue with timer when alert is followed by session$reload()

what I would like is to see a message for 2sec then refresh the App to use the newly uploaded database

the code below does not wait 2sec before reloading and the user does not get the time to read the alert message
the only fix I found was to create an extra button to trigger the session reload

shinyalert("database uploaded", type = "success", timer=2000)
session$reload()

Suppressing shinyalert messages in textOutput

Dear Dean,

First of all thanks for the awesome package!

I've got a question about using shinyalert with an actionButton in an observeEvent -> eventReactive environment with validation. The validation checks and shinyalert are part of the same eventReactive and as such share the same renderText function which is linked to a textOutput box that displays the error messages returned by the validation checks. Clicking on the action button triggers the validation checks. If a check doesn't pass, an error message gets displayed in the textOutput. If everything passes, however, no error message from the validation checks gets displayed and shinyalert gets triggered. The idea is that the function that gets triggered by the actionButton only executes when all validation checks have passed.

The problem is that triggering shinyalert also displays one of the following messages in the textOutput that it shares with the validation checks:

__shinyalert-c341eaef213a46c68c007ead25dfba7b
__shinyalert-eec9a1d3909c446ca65b60dc35809d68
__shinyalert-b162039052b14019981d1c86f5d21e51
...
__shinyalert-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

These messages vary depending on the input entered by the user.

My question is if there is a way to suppress this output so that is doesn't show up when all validation checks have passed and the modal pops up?

I assume that the output is expected (auto generated object id's perhaps?) but I'm too much of a Shiny novice to understand where it is coming from or how to capture it. I tried to not include shinyalert in the eventReactive but I couldn't find a way to keep the validity checks working. Anyway, it would be great if there was a way to suppress or control this output.

Also, as I only started using Shiny a month ago or so I apologize in advance if I missed something obvious here and this is not actually a legitimate question.

In either case, here is a reproducible example:

library(shiny)
suppressMessages(library(shinyalert))

ui <- fluidPage(
   
   useShinyalert(),
   
   titlePanel("shinyalert reproducible example"),
   
   sidebarLayout(
      sidebarPanel(
      p("Clicking the button without changing the value results in an error messages and suppresses the modal popup. Change the value to get the popup and see the object returned by shinyalert.")
      ),
      
      mainPanel(
        numericInput("test",
                   h4("Test input"),
                   value=2700,
                   min=0),
      verbatimTextOutput("test_box"),
      
      actionButton("go","Execute")
      
      )
   )
)

server <- function(input, output) {
   v <- eventReactive(input$go, {
      
      validate(
        need(input$test != 2700, "This value can't be 2700")
      )
     
     shinyalert(
        title = "The value you entered is:",
        text = input$test,
        type = "success"
      )
   })
   
   output$test_box <- renderText({
     v()
   })
}

shinyApp(ui = ui, server = server)

Thanks a lot!

bs4Dash and shinyalert

First, I'd like to thank you very much for an awesome package.

I am experiencing a few oddities when using shinyalert inside a bs4Dash application. What follows could be reported in two distinct issues and I could do that if need be.

MathJax is not rendered

I am rendering an Rmarkdown (actually bookdown) HTML document inside shinyalert. Although the document is displayed properly inside the modal, the MathJax equations are not rendered despite the use of shiny::withMathJax().

Overall aspect of boxes changes

I am using bs4Dash::box-es inside my application and whenever I open the shinyalert containing my HTML document the font size of the box titles shrinks, horizontal scrollbars appear in my boxes and the overall layout of the app changes slightly. I must add that, to my knowledge, this behavior ONLY occurs when I include a rendered HTML document inside the shinyalert modal.

Reproducible example

Since my reproducible example involves 2 files, I created the following repository, which can be easily cloned:

https://gitlab.com/gueyenono/rmarkdown-shinyalert-mathjax

app.R

library(shiny)
library(bs4Dash)
library(rhandsontable)

shinyApp(
  ui = dashboardPage(
    title = "Basic Dashboard",
    header = dashboardHeader(),
    sidebar = dashboardSidebar(),
    controlbar = dashboardControlbar(),
    footer = dashboardFooter(),
    body = dashboardBody(
      
      box(
        title = "Car values",
        rHandsontableOutput(outputId = "data"),
        br(),
        actionButton("btn", "OK")
      )
      
    )
  ),
  server = function(input, output) {
    
    output$data <- renderRHandsontable({
      rhandsontable(mtcars)
    })
    
    observeEvent(input$btn, {
      
      shinyalert::shinyalert(
        title = "Nice modal",
        html = TRUE,
        text = div(
          withMathJax(includeHTML("www/document.html"))
        )
      )
      
    })
    
  }
)

document.Rmd (to be knit to HTML)

---
output: bookdown::html_document2
---

## Linear regression

The matrix formula on the OLS estimator is:

$$
\beta_{OLS} = (X^TX)^{-1}X^TY
$$

adjust size of shinyalert modal

I see there is a parameter for a fixed size but if I minimize my screen, the modal size is too big and the user cannot scroll down to see all the text of the modal + the OK/Cancel buttons at the bottom. Is there a way so that the size of the modal is fluid depending on the size of the shiny app or if there's a lot of text and the user can scroll down the modal?

Shinyalert does not display a message

Good afternoon. I am trying to use the shinyalert package in my application, but it is not displaying anything when it is executed. I believe I am correctly declaring the package and the useShinyalert function. can anybody help me?
The excerpts follow.

require(shinyalert) # ui.r
require(tidyverse) # server.r
require(plotly) # ui.r
require(writexl) # server.r
source('functions.R')
useShinyalert()
set_wd()
options(shiny.sanitize.errors = FALSE)
options(encoding = "UTF-8")

if (nrow(d()) != 0){

  if(input$date_range[2] >= input$date_range[1] ) {

  #d$Ano_Mes <- paste0(d$ano,"-",sprintf("%02d",d$mes))

  ggplotly(ggplot(data = d() , aes(x=Data, y = Total,group = 

Referenciamento,color=Referenciamento)) +
geom_line( size = 0.5) + geom_point( size = 2)+
scale_x_date(date_labels="%d-%m-%Y")+
scale_colour_brewer(palette = "Set1") +
labs(y = NULL, x = "Período",title =
paste0(input$justif," entre ",as.character(input$date_range[1],"%d-%m-%Y")," e ",as.character(input$date_range[2],"%d-%m-%Y"))))

  } else {

    shinyalert(title = "Datas incorretas!",type="error")

    # showModal(modalDialog(
    #   title = NULL,
    #   "Datas incorretas."))

  }

} else {

  shinyalert(title = "Não existe informação para este tipo de encaminhamento!",type="error")
  # showModal(modalDialog(
  #   title = NULL,
  #   "Não existe informação para este tipo de encaminhamento.")
  #
  # )

}

how to assing ID for shinyalert

Hi, dattali,
shinlyalert is a very good tool for shiny. However, I have a question about how to assign a specific ID for shinyalert, I saw in your readME, you said can "The return value of the modal can be accessed via input$shinyalert (or using a different input ID if you specify the inputId parameter) in the Shiny server’s code, as if it were a regular Shiny input.". however, there is no inputID or id parameter in the shinyalert function, so I don't know how to specify the ID for a shilyaler obejct?
Looking forward your reply.
Thank your very much.

Error in Shinyalert: unused arguments

Great package with shinyalert, but I'm getting errors using it now. I recently updated R (3.6.1) and RStudio (1.2.1335).

library(shiny)
library(shinyalert)

ui <- fluidPage(
useShinyalert(),
sidebarLayout(
sidebarPanel(
actionButton("test", "Test This")
),
mainPanel(
)
)
)

server <- function(input, output) {

observeEvent(input$test,{
    shinyalert(
        title = "Hello",
        text = "This is a modal",
        closeOnEsc = TRUE,
        closeOnClickOutside = FALSE,
        html = FALSE,
        type = "success",
        showConfirmButton = TRUE,
        showCancelButton = FALSE,
        confirmButtonText = "OK",
        confirmButtonCol = "#AEDEF4",
        timer = 0,
        imageUrl = "",
        animation = TRUE
    )
})

}

Run the application

shinyApp(ui = ui, server = server)

Error is: Warning: Error in shinyalert: unused arguments (title = "Hello", text = "This is a modal", closeOnEsc = TRUE, closeOnClickOutside = FALSE, html = FALSE, type = "success", showConfirmButton = TRUE, showCancelButton = FALSE, confirmButtonText = "OK", confirmButtonCol = "#AEDEF4", timer = 0, imageUrl = "", animation = TRUE)

Help is appreciated.

Extra unlabeled button when using navbarPage?

I hope this hasn't been covered, I did look through the issues and didn't see anything.

It seems that when using a navbarPage with shinyalert you get a half-sized, unlabeled button on the navbar.

Here's an example:

library(shiny)
library(shinyalert)

ui <- navbarPage(

  "test",
   tabPanel("tab1",
      sidebarPanel(),
      mainPanel())
   #,useShinyalert()
  )

server <- function(input, output) {}

shinyApp(ui = ui, server = server)

if you uncomment the useShinyalert() then you should see the button:
screenshot-127 0 0 1-6385-2018-03-07-12-15-58-379

Replace free text by closed input

Thanks for this fantastic package.

I'm using shinyalert right now to collect feedback from users and store that information for analysis purposes. Now I'd like to change the free text mode to a closed input (something like radio buttons). In the documentation of the shinyalert function I see that in the inputType argument another valid HTML input can be specified. When I set this argument to "radio" it doesn't take up the text I specify in the inputValue argument:

image

Is this possible in shinyalert or is there a workaround?

Thanks in advance.

callbackR is not respected when the alert has a timer

(Taken from #31)

Example:

library(shiny)

ui <- fluidPage(
    shinyalert::useShinyalert(),
    actionButton('test', 'test')
)

server <- function(input, output, session) {
    observeEvent(input$test, {
        shinyalert::shinyalert("modal 1",
                               timer = 1000,
                               callbackR = function() {
                                   shinyalert::shinyalert("modal 2")
                               })
        
    })
}

shinyApp(ui, server)

Possibility to customize dimensions of alert widgets

Hi,

first of all, thanks for this package! Really useful and easier to use than shiny modals.

I was just wondering if it is possible to somehow "customize" the appearence of the modal widgets, for example to change the dimensions of the icon or the font size of the messages.

I already tried changing imageHeight / imageWidth, but with no avail.

Thanks in advance,

Lorenzo

input$shinyalert can trigger even before pressing OK

Hi Dean,

I have an issue when I use more than one time a shinyAlert during a session.

The second time I use a shinyalert widget, the observeEvent based on input$shinyalert triggers when modal is opening.
It does not wait for confirmation or cancellation.

Is there a way to set back to NULL input$shinyalert when at some point when an operation is done ?

It's hard to give a reprex but here is a code.
The first browser() call is normal after I confirmed the first shinyAlert.
But I would expect that on second button press, I should arrive in browser() only if I confirm the modal, not just after modal opening.

if (interactive()) {
  library(shiny)
  library(shinyalert)
  
  shinyApp(
    ui = fluidPage(
      useShinyalert(),  # Set up shinyalert
      actionButton("btn", "Trigger modal"),
      verbatimTextOutput("input_shinyalert"),
      verbatimTextOutput("test_value")
    ),
    server = function(input, output) {
      
      observeEvent(input$btn, {
        
        shinyalert(
          title = "Do you confirm?", type = "info", showCancelButton = TRUE, closeOnEsc = FALSE
        )
        
        observeEvent(input$shinyalert, {
          
          if (input$shinyalert) {
            
            browser()
            
            output$test_value <- renderText({
              
              "test_value"
              
            })
            
          }
          
          output$input_shinyalert <- renderText({
            
            input$shinyalert
            
          })
          
        })
        
      })
      
    }
  )
}

Issues with `timer` when there are multiple modals

Bug 1:

When a modal has a timer and calls another modal in its callbackR, the modal from the callback doesn't show up

library(shiny)

ui <- fluidPage(
    shinyalert::useShinyalert(),
    actionButton('test', 'test')
)

server <- function(input, output, session) {
    observeEvent(input$test, {
        shinyalert::shinyalert("modal 1",
                               timer = 1000,
                               callbackR = function() {
                                   shinyalert::shinyalert("modal 2")
                               })
        
    })
}

shinyApp(ui, server)

Bug 2:

When a modal has a timer and there is another modal called in the same code chunk, the timer is ignored (this one might be ok because it's a bit ambiguous what should happen when two modals are called in the same code chunk - should the first one be closed before the second is shown? Or should the second be shown immediately?)

library(shiny)

ui <- fluidPage(
    shinyalert::useShinyalert(),
    actionButton('test', 'test')
)

server <- function(input, output, session) {
    observeEvent(input$test, {
        shinyalert::shinyalert("modal 1", timer = 1000)
        shinyalert::shinyalert("modal 2")
                               
        
    })
}

shinyApp(ui, server)

How to auto close Shinyalert

Hi, dattali,
First, thanks for the great tool you invented for shiny.
I want to write a loading screen through shinyalert.
The modal needs to be auto close and shows a success screen at the end.
It can be done easily by showModal.

shinyApp(
ui = basicPage(
actionButton("show", "Show modal dialog")
),
server = function(input, output) {
observeEvent(input$show, {
showModal(modalDialog(
title = "Data processing"
))
Sys.sleep(5)
removeModal()
showModal(modalDialog(
title = "Done"
))
})
}
)

But it looks quite ugly.
I try to use shinyalert package to replicate this method but It can't be done easily by me.
I can't close the first shinyalert automatically.
Here's my code.
shinyApp(
ui = basicPage(
useShinyjs(),
useShinyalert(),
actionButton("show", "Show modal dialog")
),
server = function(input, output) {
observeEvent(input$show, {
shinyalert("Data processing!", "", type = "info", inputId = "hidewhencomplete",html = T)
Sys.sleep(5)
removeModal()#cant close
hide("hidewhencomplete")#cant close
#replicate the method from close_alert but still can't close it
session <- shiny::getDefaultReactiveDomain()
session$sendCustomMessage(type = "shinyalert.close", message = "")
shinyalert("Done!", "", type = "success")
})
}
)

Thanks for your help.

Btw, I wonder if I can get a shinyalert type "loading" which showing a spinning "loading" animation,
so I can use it and show the final result instead of showing them a type = "info" when it is processing.

Different shinyalerts triggered at the same time

Hi Dean, thanks for the great package.

In my app there is a situation when 2 alerts are triggered at the same time. On my machine there is no issue whatsoever, the alert that is first in the code shows first, and when it's okay-ed, the second alert shows up.

However on my colleague's machine, the first alert appears for a split second, and the second alert takes its place.

Do you have any ideas what is causing this different behavior? It's the same in different browsers on my colleague's machine.

Run in PHP (Inline)

Hello!

I want to run this from php like:

<?php

echo exec("Rscript index.R");

?>

but, it runs as another web server? Is there an way to inline this from PHP or no?

Thanks!

PS here is a bit more:

Loading required package: methods
Warning message:
replacing previous import by ‘Rcpp::evalCpp’ when loading ‘later’ 

Attaching package: ‘shinyalert’

The following object is masked from ‘package:shiny’:

    runExample


Listening on http://127.0.0.1:6936
^C

Execution halted
[Fri Apr 17 21:21:12 2020] 127.0.0.1:34792 [200]: /sso/verify/index.php

Add "id" to access more than one shinyalert in a App

I am using shinyalrert more than once and I would prefer to use id's to refer to different alerts. The second one overwrites the first one and there is no chance to get both without storing them to a reactive value variable. It would be great if you considering adding this. Thank you.

inactive input field

Hello,

Many thanks for developing shinyalert which we really use a lot for our all bioinformatics app.

I ran into an issue :

When using a shinyalert with an input field. This input field is inactive and I cannot write in it.

When runnng the example code in my console, of course, it is working but if I include it in my code, the input field is inactivated.

The following code is running within a shinymodule and enclosed in an observeEvent (after a button pressing).

Thanks for your help,

UPDATE: Apparently, after some checks, the fact that I am running inside of a modal could be the cause of the problem.

Sylvain

        shinyalert(
            alertText, 
            type = "warning", 
            showCancelButton = TRUE, 
            showConfirmButton = TRUE,
            callbackR = function(value) {
                req(value)
                
                shinyalert(
                    
                    paste("Enter password for cluster user", clusterUsername),
                    type = "input", 
                    inputType = "password",                    
                    showCancelButton = TRUE, 
                    showConfirmButton = TRUE,
                    inputId = "password"
                ) 
            }
        )

Try to allow arbitrary HTML/inputs

I tried doing this when the package was originally released by couldn't figure it out. But I really want to be able to include any HTML/shiny inputs inside the modal, so try again!

Editing text color in the modal

Hi, thank you for developing this package. Is there any way to do some styling with the text in the modal? For example, coloring/highlighting part of the text to make it stand out to the user?

MathJax support

Extracted from #51

Thanks for the report by @gueyenono :

I am rendering an Rmarkdown (actually bookdown) HTML document inside shinyalert. Although the document is displayed properly inside the modal, the MathJax equations are not rendered despite the use of shiny::withMathJax().

Get df value from rhandsontable inside shinyalert modal

Hello,
I am rendering a rhandsontable inside a tagList that has a dropdown. When a user changes the dropdown and clicks "Ok" I want to get access to that data frame. Normally with handsontable you can do that by hot_to_r("table Id"). Is there a way I could have access to that in a similar fashion inside the tagList? So it can be availabel in the CallbackR or somewhere else?

For example if:
rhandsontable::rHandsontableOutput(ns("modalTbl"))
output$modalTbl <- rhandsontable::renderRHandsontable({....})
df can be accessed via hot_to_r(output$modalTbl)

Currently, I am not able to detect any input changes to the dropdown when exiting the modal.

shinyalert::shinyalert(
                  title = "title",
                  text = tagList(
                    rhandsontable::renderRHandsontable({
                    rhandsontable::rhandsontable(df, height = 300, rowHeaders = TRUE, selectCallback = TRUE, search = TRUE) %>%
                    rhandsontable::hot_col("Col1", colWidths = 120 ) %>%
                    rhandsontable::hot_col("Col2", readOnly = TRUE, colWidths = 150) %>%
                    rhandsontable::hot_col("Col3", readOnly = TRUE, colWidths = 175 ) %>%
                    rhandsontable::hot_col("Col4", type = "dropdown", colWidths = 175, source = c('a', 'b', 'c') )
                    })
                  ),
                  size = "m", 
                  closeOnEsc = TRUE,
                  closeOnClickOutside = FALSE,
                  html = TRUE,
                  type = "",
                  showConfirmButton = TRUE,
                  showCancelButton = TRUE,
                  confirmButtonText = "Save",
                  confirmButtonCol = "#AEDEF4",
                  timer = 0,
                  imageUrl = "",
                  animation = FALSE,
                  callbackR = function(x){
                  output$DEBUG <- renderPrint(rhandsontable::hot_to_r(output$shinyalert))
                  }
                 )

Inputs and outputs don't work correctly when a modal fires too quickly after a closed modal

Related to #46

In the following example, a modal is opened, closed, and another modal with a shiny input immediately opens. The input doesn't get bound to shiny (same thing happens with outputs).

library(shiny)

ui <- fluidPage(
  actionButton("go", "go")
)

server <- function(input, output, session) {
  observeEvent(input$go, {
    shinyalert::shinyalert("test 1")
    shinyalert::closeAlert()
    shinyalert::shinyalert("test 2", textInput("text", "text", "test"), html = TRUE)
  })
  
  observe({
    message(input$text)
  })
}

shinyApp(ui, server)

If I add a 500ms delay (either using Sys.sleep() or shinyjs::delay()) after closing the first modal but before showing the second, then the input binding works.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.