Git Product home page Git Product logo

shinycssloaders's Introduction

shinycssloaders

⌛ Add loading animations to a Shiny output while it's recalculating

R-CMD-check CRAN version


When a Shiny output (such as a plot, table, map, etc.) is recalculating, it remains visible but gets greyed out. Using {shinycssloaders}, you can add a loading animation ("spinner") to outputs instead of greying them out. By wrapping a Shiny output in withSpinner(), a spinner will automatically appear while the output is recalculating. You can also manually trigger a spinner using showSpinner().

In addition to showing spinners on outputs, you can also use showPageSpinner() to show a full-page spinner that covers the entire page.

You can choose from one of 8 built-in animation types, and customize the colour/size. You can also use your own image instead of the built-in animations. See the demo Shiny app online for examples.

Need Shiny help? I'm available for consulting.
If you find {shinycssloaders} 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 🔗
shinyalert 🗯️ Easily create pretty popup messages (modals) in Shiny 🔗
shinyscreenshot 📷 Capture screenshots of entire pages or parts of pages in Shiny apps 🔗
timevis 📅 Create interactive timeline visualizations in R 🔗
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

Example

For interactive examples and to see some of the features, check out the demo app.

Below is a simple example of what {shinycssloaders} looks like:

demo GIF

How to use

Simply wrap a Shiny output in a call to withSpinner(). If you have %>% loaded, you can use it, for example plotOutput("myplot") %>% withSpinner().

Basic usage:

library(shiny)

ui <- fluidPage(
    actionButton("go", "Go"),
    shinycssloaders::withSpinner(
        plotOutput("plot")
    )
)
server <- function(input, output) {
    output$plot <- renderPlot({
        input$go
        Sys.sleep(1.5)
        plot(runif(10))
    })
}
shinyApp(ui, server)

Using a full-page spinner:

library(shiny)

ui <- fluidPage(
    actionButton("go", "Go"),
    plotOutput("plot")
)
server <- function(input, output) {
    observeEvent(input$go, {
      showPageSpinner()
      Sys.sleep(1)
      hidePageSpinner()
    })
    output$plot <- renderPlot({
        plot(runif(10))
    })
}
shinyApp(ui, server)

You can also use {shinycssloaders} in Rmarkdown documents, as long as they use runtime: shiny.

Installation

For most users: To install the stable CRAN version:

install.packages("shinycssloaders")

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

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

Features

8 customizable built-in spinners

You can use the type parameter to choose one of the 8 built-in animations, the color parameter to change the spinner's colour, and size to make the spinner smaller or larger (2 will make the spinner twice as large). For example, withSpinner(plotOutput("myplot"), type = 5, color = "#0dc5c1", size = 2).

Using a custom image

If you don't want to use any of the built-in spinners, you can also provide your own image (either a still image or a GIF) to use instead, using the image parameter.

Specifying the spinner height

The spinner attempts to automatically figure out the height of the output it replaces, and to vertically center itself. For some outputs (such as tables), the height is unknown, so the spinner will assume the output is 400px tall. If your output is expected to be significantly smaller or larger, you can use the proxy.height parameter to adjust this.

Manually triggering the spinner

Any Shiny output that uses withSpinner() will automatically show a spinner while it's recalculating. You can also manually show/hide an output's spinner using showSpinner()/hideSpinner().

Full-page spinner

You can also use showPageSpinner() to show a full-page spinner that will cover the entire page rather than a single Shiny output. Full page spinners support the same parameters as regular spinners, and can be removed with hidePageSpinner().

Add a message

Use the caption parameter to add a custom message under the spinner. The message can either be plain text ("Please wait") or HTML (div(strong("Loading"), br(), em("Please wait"))).

Setting spinner parameters globally

If you want all the spinners in your app to share some of the options, instead of specifying them in each call to withSpinner(), you can set them globally using R options. For example, if you want all spinners to be of a certain type and color, you can set options(spinner.type = 5, spinner.color = "#0dc5c1"). Similarly, for full-page spinners you can use page.spinner.type, page.spinner.color, etc to set default parameters instead of setting them in showPageSpinner().

Showing a spinner on top of the output

By default, the out-dated output gets hidden while the spinner is showing. You can change this behaviour to have the spinner appear on top of the old output using the hide.ui = FALSE parameter.

Sponsors 🏆

There are no sponsors yet

{shinycssloaders} is the result of many days of work, including many more to come. Show your support and become the first sponsor for {shinycssloaders}!

Credits

The 8 built-in animations are taken from https://projects.lukehaas.me/css-loaders/.

The package was originally created by Andrew Sali.

shinycssloaders's People

Contributors

andrewsali avatar daattali avatar ericnewkirk avatar steamtraen 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  avatar  avatar  avatar  avatar  avatar

shinycssloaders's Issues

Set up custom image path

Hello, let assume we have an image named mypic.gif in a folder named myfolder.
how to set up image path with image parameter in oder to use custom image ?
withSpinner(plotlyOutput("myplot"), image = "how to setup up path to custom image ?")

I tried :
withSpinner(plotlyOutput("myplot"), image = "C:/Users/john/Documents/myproject/mypic.gif")
but its doesnt work.
Some help would be appreciated

Unexpected behaviour of withSpinner() when used on valueBoxOutput()

I tried to use withSpinner() on a valueBoxOutput() object of width 3 (i.e. one quarter of my row width), however for some reason the spinner did not appear above the assigned valueBoxOutput() object. Rather, it occupied the entire row. So, with 4 value boxes in a row, I was expecting to see 4 spinners in a row -- each in the same position as my value box. However, I got 4 rows, one spinner in each row, instead.

Could you please help with this?

Page movement when spinner is hidden

Hello, I am seeing some page movement when the spinner is hidden and the page is scrolled to a certain location as seen below:

Page Moving

I think this is coming from the fact that the spinner is just hidden and not actually removed

visibility:hidden;

Is it possible to change it to display: none, or some other way to stop the spinner from being active on the page?

shinycssloaders won't disappear when using certain chart packages

Hi -

I am looking to use shinycssloaders on charts from a package I have built with htmlwidgets. The height component of the chart output needs to respond to window size so have implemented a javascript event to update a shiny variable declaring the height. When implementing this, I find the cssloaders do not disappear after the chart has resized.

This same pattern to implement responsiveness works with many other chart packages (normal plots, plotly etc).

I'm able to reproduce the problem with charts from 'dygraphs' another package built with htmlwidgets.

Run the following code, then resize the browser window,

library(dygraphs)
library(datasets)
library(dygraphs)

shinyApp(
ui = shinyUI(fluidPage(

sidebarLayout(
  sidebarPanel(
    tags$head(
      tags$script(HTML('
        $(window).resize(function(event){
        var w = $(this).width();
        var h = $(this).height();
        var obj = {width: w, height: h};
        Shiny.onInputChange("pltChange", obj);
        });
        '))
      ),
    numericInput("months", label = "Months to Predict", 
      value = 72, min = 12, max = 144, step = 12),
    selectInput("interval", label = "Prediction Interval",
      choices = c("0.80", "0.90", "0.95", "0.99"),
      selected = "0.95"),
    checkboxInput("showgrid", label = "Show Grid", value = TRUE)
  ),
  mainPanel(
    uiOutput("dygraphContainer")
  )
)

  )),

server = shinyServer( function(input,output,session){

chartHeight <- reactive({
  if(is.null(input$pltChange$height)) {
    h <- "300px"
  } else {
    h <- paste0(input$pltChange$height-100,"px")
  }
  
  h
  
})

output$dygraphContainer <- renderUI({
  
  shinycssloaders::withSpinner(
    dygraphOutput("dygraph", height=chartHeight()),
    type = 6, 
    color = "#4A4A49"
  )
  
})

predicted <- reactive({
  hw <- HoltWinters(ldeaths)
  predict(hw, n.ahead = input$months, 
    prediction.interval = TRUE,
    level = as.numeric(input$interval))
})

output$dygraph <- renderDygraph({
  
  dygraph(predicted(), main = "Predicted Deaths/Month") %>%
    dySeries(c("lwr", "fit", "upr"), label = "Deaths") %>%
    dyOptions(drawGrid = input$showgrid)
})

})
)

Prevent spinner.js console.log output

The actual CRAN version of shinycssloaders has a console.log output in spinner.js

I just saw that this line is not there anymore in the github-version. So I just wanted to ask, when you we're goign to deploy a new version to CRAN?

Global loader

Hi, is it possible to add a global loader when certain events occur? With global loader I mean one single loader for a whole page (or many plots/tables). May be these are 2 separate questions: 1) Is it possible to add a global loader for a whole page/tab? And 2) is it possible to deploy them when certain event happens?
Thanks

Show custom image when loading?

Would it not be a nice feature if users can pass their own image file to display when loading? Or is this implemented somewhere already?

Problem when combining shinycssloaders with shinyjs

This is a print screen of a case. The above plot (plot1) is "withSpinner". It is hidden by code like the following :

    observeEvent(.....
    if(nrow(plot1_df())<1){
      hide("plot1")
    }
    ......

However, the animation never dissapears! What is more, it's div lays "above" the tab panels, preventing the choice of another tab! I could do nothing but stop using "withSpinner"

image

withSpinner() removes reactive element of uploading data and selecting column names

Issue related to my post on Stack Overflow recently. In short, when uploading data to my shiny app, drop down lists should be populated with the column names of the uploaded data frame. This worked on 23/01/2020. As of 24/01/2020 the column names no longer populated the drop down lists. I found that removing withSpinner() from my ui.R fixed this issue. I know a recent update was pushed so wondering if this broke the app or if something else is going on where removing withSpinner() is allowing reactivity to work within the Shiny app.

Thanks!

withSpinner not reloading within modalDialog

First of all, thank you for all your open source Shiny contributions! I've been enjoying your packages and have learned a lot from your online videos/tutorials/posts.

I've been using withSpinner() to indicate when calculations/graphs are being updated, but noticed it only works the first time and doesn't reload within a modalDialog()

Minimum reproducible example (tested on dev version of shinycssloaders):

library(shiny)

ui <- fluidPage(
  sliderInput("slider", "Number of observations:", 1, 150, 50, 1),
  actionButton("show", "Show me the result")
)

server <- function(input, output) {
  
  # Slowly compute histogram
  output$plot <- renderPlot({
    Sys.sleep(2)
    data <- iris$Sepal.Length[seq_len(input$slider)]
    hist(data)
  })  
  
  # Show histogram in modal dialog upon clicking button
  observeEvent(input$show, {
    showModal(modalDialog(
      shinycssloaders::withSpinner(plotOutput("plot", height = 250))
    ))
  })
}

shinyApp(ui, server)

I've included this examples also in a related issue in the shiny github repo, since the plot also doesn't gray out without withSpinner() as it is supposed to. I am hoping withSpinner() can be adapted to include this scenario.

withSpinner is hidden when hosting app on port 80

Using the following code under Windows7 x64 with Chrome doesn't display a spinner when executed via source():

library(shiny)
library(shinycssloaders)

ui <- fluidPage(
  withSpinner(uiOutput("dummyid"))
)

server = function(input, output, session){
  output$dummyid <- renderUI({
    Sys.sleep(5)
    "result"
  })
}

app <- shinyApp(ui, server)
runApp(app, host ="0.0.0.0", port = 80, launch.browser = TRUE) # causes hidden spinner

screen

This however worked without problems with shinycssloaders version 0.2.0.

Warning in origRenderFunc()

I noticed there was a warning when ever the spinner loading

Warning in origRenderFunc() :
  Ignoring explicitly provided widget ID "11a455151819"; Shiny doesn't use them

Is it normal or could it be compatible with Shiny?
( I tend to use it in production)

My session info

Session info ---------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.4.0 (2017-04-21)
 system   x86_64, mingw32             
 ui       RStudio (1.0.143)           
 language (EN)                        
 collate  English_United States.1252  
 tz       Asia/Bangkok                
 date     2017-05-19                  

Packages -------------------------------------------------------------------------------------
 package         * version date       source        
 assertthat        0.2.0   2017-04-11 CRAN (R 3.4.0)
 colorspace        1.3-2   2016-12-14 CRAN (R 3.4.0)
 crosstalk         1.0.0   2016-12-21 CRAN (R 3.4.0)
 DBI               0.6-1   2017-04-01 CRAN (R 3.4.0)
 devtools          1.12.0  2016-12-05 CRAN (R 3.4.0)
 digest            0.6.12  2017-01-27 CRAN (R 3.4.0)
 dplyr           * 0.5.0   2016-06-24 CRAN (R 3.4.0)
 ggplot2         * 2.2.1   2016-12-30 CRAN (R 3.4.0)
 glue              1.0.0   2017-04-17 CRAN (R 3.4.0)
 gtable            0.2.0   2016-02-26 CRAN (R 3.4.0)
 hms               0.3     2016-11-22 CRAN (R 3.4.0)
 htmltools         0.3.6   2017-04-28 CRAN (R 3.4.0)
 htmlwidgets       0.8     2016-11-09 CRAN (R 3.4.0)
 httpuv            1.3.3   2015-08-04 CRAN (R 3.4.0)
 httr              1.2.1   2016-07-03 CRAN (R 3.4.0)
 jsonlite          1.4     2017-04-08 CRAN (R 3.4.0)
 lazyeval          0.2.0   2016-06-12 CRAN (R 3.4.0)
 magrittr          1.5     2014-11-22 CRAN (R 3.4.0)
 memoise           1.1.0   2017-04-21 CRAN (R 3.4.0)
 mime              0.5     2016-07-07 CRAN (R 3.4.0)
 munsell           0.4.3   2016-02-13 CRAN (R 3.4.0)
 plotly          * 4.6.0   2017-04-25 CRAN (R 3.4.0)
 plyr              1.8.4   2016-06-08 CRAN (R 3.4.0)
 purrr             0.2.2   2016-06-18 CRAN (R 3.4.0)
 R6                2.2.0   2016-10-05 CRAN (R 3.4.0)
 Rcpp              0.12.10 2017-03-19 CRAN (R 3.4.0)
 readr           * 1.1.0   2017-03-22 CRAN (R 3.4.0)
 reshape2        * 1.4.2   2016-10-22 CRAN (R 3.4.0)
 scales            0.4.1   2016-11-09 CRAN (R 3.4.0)
 shiny           * 1.0.3   2017-04-26 CRAN (R 3.4.0)
 shinycssloaders * 0.2.0   2017-05-12 CRAN (R 3.4.0)
 stringi           1.1.5   2017-04-07 CRAN (R 3.4.0)
 stringr           1.2.0   2017-02-18 CRAN (R 3.4.0)
 tibble            1.3.0   2017-04-01 CRAN (R 3.4.0)
 tidyr             0.6.1   2017-01-10 CRAN (R 3.4.0)
 viridisLite       0.2.0   2017-03-24 CRAN (R 3.4.0)
 withr             1.0.2   2016-06-20 CRAN (R 3.4.0)
 xtable            1.8-2   2016-02-05 CRAN (R 3.4.0)
 yaml              2.1.14  2016-11-12 CRAN (R 3.4.0)

Changed behaviour using shinycssloaders 0.3

The following code snippet was rendering the spinner just fine using shinycssloaders 0.2.0.
After updating to 0.3 the spinner is no longer rendered.

Is this change intentional?

library(shiny)
library(shinycssloaders)

ui <- fluidPage(
  withSpinner(p(), type = 6)
)

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

shinyApp(ui, server)

withspinner keeps on working with observeEvent

I understand this issue has already been resolved but i think my case is different . I have a shiny alert which checks for certain condition and if condition matches then whole report runs else report won't run. So I added observeEvent for shiny alert , but now the spinner runs even before action button is clicked. Any help is greatly appreciated , thanks again in advance.

ui <- fluidRow(box(title = "Sales Pre vs Post", status = "primary", height = "500", width = 12, solidHeader = TRUE, withSpinner(plotOutput("plot1"), type = 2)))

server <- observeEvent(input$go,{
if(as.numeric(Sys.Date() - as.Date(input$date1)) >= as.numeric(input$radio) )
{
op_sql <- eventReactive(input$go,{ script })
output$plot1 <- plots....

}
else
{
shinyalert(paste0("Ensure Intervention date is atleast ", input$radio, " days less than current date"), type = "error")}
)}

Would like to provide ids for spinners

Hello,

Is it possible for withSpinner to have an additional parameter called id with default value of NULL? And if it is NULL, it would get a random value from digest? There are cases where one would like to hide a widget and its spinner. Placing a specific id for the spinner did the trick for me.

withSpinner <- function(ui_element, type=getOption("spinner.type",default=1),color=getOption("spinner.color",default="#0275D8"),size=getOption("spinner.size",default=1),color.background=getOption("spinner.color.background"),custom.css=FALSE,proxy.height=if (grepl("height:\\s*\\d",ui_element)) NULL else "400px", id = NULL) {
  stopifnot(type %in% 1:8)
  
  if (grepl("rgb",color,fixed=TRUE)) {
    stop("Color should be given in hex format")
  }
  # each spinner will have a unique id, to allow seperate sizing - based on hashing the UI element code
  if (is.null(id)){
    id <- paste0("spinner-",digest::digest(ui_element))
  }
  ...

Display spinners inline

When placing outputs with spinners beside each other they are each on their own line.
How can they be placed horizontally?

tabPanel(title = "Sentiment", width = 12, 
    withSpinner(imageOutput(outputId = "wordcloud")), 
    withSpinner(imageOutput(outputId = "sentiment_pie")), 
    withSpinner(imageOutput(outputId = "star_rating_chart"))
)

I have tried the following but but it hides the spinner itself
tags$style(HTML("div.shiny-spinner-output-container {display: inline}")),

withSpinner prevents appendTab from working correctly

Here is an example

library(shiny)
library(DT)
library(shinycssloaders)

ui <- 
    fluidPage(
        actionButton("new_tab", label = "New Tab"),
        tabsetPanel(id = "test",
                    tabPanel("Test1", withSpinner(DTOutput("table"))))
    )

server <- function(input, output, session) {
    
    data <- reactive({
        Sys.sleep(1)
        iris
    })
    
    output$table <- renderDT({
        datatable(data())
    })
    
    observeEvent(input$new_tab, {
        id <- Sys.time()
        appendTab("test", tab = tabPanel(id, id), select = TRUE)
    })
    
}
shinyApp(ui, server)

Click on the "New Tab" button creates a new tab but the content is the same as what's in the first tab. After clicking "New Tab" a second is when it actually creates the tabs.

Removing the withSpinner call allows for normal tab creation.

Here is my sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] shinycssloaders_0.3 DT_0.11             shiny_1.4.0        

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.3        rstudioapi_0.10   magrittr_1.5      xtable_1.8-4      R6_2.4.1         
 [6] rlang_0.4.3       fastmap_1.0.1     fansi_0.4.1       tools_3.6.1       sessioninfo_1.1.1
[11] cli_2.0.1         withr_2.1.2       htmltools_0.4.0   crosstalk_1.0.0   yaml_2.2.0       
[16] digest_0.6.23     assertthat_0.2.1  crayon_1.3.4      later_1.0.0       htmlwidgets_1.5.1
[21] promises_1.1.0    glue_1.3.1        mime_0.8          compiler_3.6.1    jsonlite_1.6     
[26] httpuv_1.5.2 

withSpinner not reloading with dashboardpage

Hi,

I am using withSpinner with dashboardpage and I have the following problem.

I have two different tabitems:

the first has a selectInput object
the second has a plot depending on the first.

the loading spinner appears only the first time the plot is calculated, therefore if i go back to the first page and change the value in the selectinput when i return to the plot page the spinner does not apper.

Can someone help me?

Thankyou

Transparent background?

Hi,

The package is great for shiny apps. I'm wondering if it's possible to use transparent background so that the previous plots won't disappear entirely? Thanks!

The spinner keeps spinning when rendering a table with the same data

Hi I am new to R and shiny.
I use the spinner like below:
in the UI block:
withSpinner(tableOutput("freq_table"))

in the Server block:
observeEvent(input$button, { df_log <<- update(input$dateRange[1], input$dateRange[2]) }) output$freq_table <- renderTable({ input$button df_freq_table <- as.data.frame(table(df_log$user_id)) colnames(df_df_freq_table) <- c("user_id", "count") df_freq_table <- df_freq_table[order(-df_freq_table$count, df_freq_table$user_id),] df_freq_table })

When the date range changes, the table is rendered. But if the date range is the same, the spinner just keep spinning.
The table renders if I remove the spinner.
Could someone tell me why the spinner keeps spinning if the data is the same? Is there a way to tell the spinner that the table is updated even though the data set is the same?
Thank you

Error when deployed with shinyapps.io

This is a brilliant idea first of all, and looks very fancy, that's why I would like to include it. Locally, it works perfect, however, for some reason, after I added the package and added the lines (see below), it stopped working if I deploy it with shinyapps.io. The app runs fine locally, just wouldn't let me deploy it.

# load the library
library(shinycssloaders)

withSpinner(plotOutput("my_plot")) 
# if you have `%>%` loaded, you can do plotOutput("my_plot") %>% withSpinner()

The error message I'm getting in the log is attached down below, but I have package shinycssloaders, and I've tried downloading it from CRAN and github, but neither works.

2019-05-13T16:41:39.317482+00:00 shinyapps[890504]: Using pandoc at /opt/connect/ext/pandoc2
2019-05-13T16:41:39.538904+00:00 shinyapps[890504]: Listening on http://127.0.0.1:46817
2019-05-13T16:41:43.893648+00:00 shinyapps[890504]: Warning: Error in withSpinner: could not find function "withSpinner"
2019-05-13T16:41:43.908035+00:00 shinyapps[890504]:   68: div
2019-05-13T16:41:43.908036+00:00 shinyapps[890504]:   67: mainPanel
2019-05-13T16:41:43.908034+00:00 shinyapps[890504]:   69: tags$div
2019-05-13T16:41:43.908032+00:00 shinyapps[890504]:   70: tag

I'm sure this work because it is on their github page, but I'm not sure what I did wrong. Worst case scenario, I'll just get rid of it so it's not a huge issue, but it'd be cool if I can use it. Any help is appreciated!

EDIT
So I attached a sample code, feel free try to deploy it, did't work for me. But works fine locally (since it's a sample app, the loading spinner is extremely quick, but you'd still be able to see it).

library(shiny)
library(shinycssloaders)

ui <- fluidPage(
  actionButton("go", "Go"),
  numericInput("n", "n", 50),
  withSpinner(plotOutput("my_plot"))
)

server <- function(input, output) {
  
  randomVals <- eventReactive(input$go, {
    runif(input$n)
  })
  
  output$my_plot <- renderPlot({
    hist(randomVals())
  })
}

shinyApp(ui, server)

Tabs prevent spinner from showing during recalculation

Tabs can prevent the spinner from showing during recalculation. Here is an example:

library(shinycssloaders)

ui <- fluidPage(
  navbarPage(
    title="Menu",
    tabPanel("Tab 1",
      sliderInput(inputId = "bins", 
        label = "Number of bins:", min = 1, max = 50, value = 30)
    ),
    tabPanel("Tab 2", withSpinner(plotOutput(outputId = "distPlot"))
    )
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    Sys.sleep(3)
    x    <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    hist(x, breaks = bins, xlab = "Waiting time [min]")
  })
}

shinyApp(ui, server)

The first time Tab 2 is visited the spinner is shown. But if afterwards the slider input on Tab 1 is changed and Tab 2 visited again the spinner is not shown during recalculation.

withSpinner not compatible with rendering in server

I utilize modalDialog() in the server to have a screen pop-up with a visualization. The server includes a modalDialog(renderPlot()) call, and the plotOutput() UI element is not included/necessary. The withSpinner() function is not compatible as a wrapper to renderPlot(). For example, I cannot use modalDialog(withSpinner(renderPlot())). The following error message is produced:

Warning: Error in as.vector: cannot coerce type 'closure' to vector of type 'character'

Is there any workaround or hack to making this work?

Suggestion: Add message option

Hello,

I am really content with the Spinner options to display while rendering a page. However, I would really like to have an option to show a message in addition to the Spinner image, as the loading of the page might take some time. Other alternatives such as withProgress() (https://shiny.rstudio.com/articles/progress.html) seem to have this feature and I think this might enrich the Spinner application very much. What do you think? Did you find a workaround?

Manually start/stop the loader for an output element

Hi,

Is it possible to manually start or stop the loader for an output element using shinycssloaders ?
I tried doing this by assigning the corresponding output element with NULL.

output$element <- NULL

This works in the usual scenario. But I am using multiprocessing to fetch data for each element in parallel by using the future module, that is causing the loaders to go off sync when the elements are being rendered.

Recording of how the component & loader come up while running it sequentially (this is the expected behaviour):
sequential

Recording of how the component & loader come up while using multiprocessing:
parallel

CSS Loader Animations fail on deployment to AWS EC2 instance

What a great package! I just added it to one of my apps and successfully deployed to shinyapps.io to test, but when I deployed to the production version hosted on an AWS EC2 instance, it failed. I am not the server admin for the EC2 instance but am trying to help debug. Is there a list of dependencies(libraries and packages) available? Any previous issues encountered with deployment to non-shinyapps.io servers?

Thank you for all your work in putting this together.

How to use withSpinner with htmlTemplates?

I have to write a Shiny-App with customized UI, so i had to use htmlTemplates as UI.

Now i am wondering how to include the withSpinner function for some plots and table outputs.

None of the following works:

{{ withSpinner(plotlyOutput("plot") }}
{{ plotlyOutput("plot") %>%  withSpinner(color="green") }}

I included the following stylesheets in the HTML-head:

  <link rel="stylesheet" href="assets/spinner.css"/>
  <link rel="stylesheet" href="css-loaders/css/fallback.css"/>
  <link rel="stylesheet" href="css-loaders/css/load1.css"/>
  <style>
    #spinner-fb1379e50c4392487739d0e558462fa7, #spinner-fb1379e50c4392487739d0e558462fa7:before, #spinner-fb1379e50c4392487739d0e558462fa7:after {background: green}
    #spinner-fb1379e50c4392487739d0e558462fa7 {color: green}
    </style>
  <style>
    #spinner-fb1379e50c4392487739d0e558462fa7 {font-size: 8px}spinner-fb1379e50c4392487739d0e558462fa78
    </style>
  <style>#spinner-5cc0e652b276e0d0a0f3fbc6a51ab991, #spinner-5cc0e652b276e0d0a0f3fbc6a51ab991:before, #spinner-5cc0e652b276e0d0a0f3fbc6a51ab991:after {background: green}
  #spinner-5cc0e652b276e0d0a0f3fbc6a51ab991 {color: green}
  </style>
  <style>
    #spinner-5cc0e652b276e0d0a0f3fbc6a51ab991 {font-size: 8px}spinner-5cc0e652b276e0d0a0f3fbc6a51ab9918
  </style>

Am i missing something or is that just not possible for now?

Spinner Freezes

Just before my Shiny app completes loading the css spinner freezes for a few seconds and then renders the output. This seems to happen when there is a function call to shinyapp.js which takes about three seconds, after which the page is loaded. During those three seconds the spinner is frozen. Is there a way to remediate this issue?

Suggestion: using more unique name than "assets" for client resource path

shinycssloaders package currently adds/overwrites resource path "assets" (in R/globals.R). As this is quite generic path that Shiny apps themselves might want to use to store their assets/static content, then this package is not "compatible" with those.

Basically just a suggestion that could this be switched to more unique name, for example, shinycssloaders -- rather than assets?

Spinner doesn't show up for some output IDs

For example, an output ID of "map" breaks the spinner:

library(shiny)

ui <- fluidPage(
  withSpinner(textOutput("map"))
)

server <- function(input, output, session) {
  output$map <- renderText("test")
}

shinyApp(ui, server)

Discovered while trying to look into #17

Suggestion: remove all files and dirs from inst/css-loaders and only keep the CSS

It seems that inst/css-loaders contains the entire css spinners' github repo. But as far as I can tell, only the css files are needed and it not only bloats the repo with unnecessary files, but it also confuses potential contributors (such as myself, it took me some time to convince myself that I don't need to touch the less and sass files and use grunt)

custom.css example?

I have a graph that is really tall. I'd like to move the spinner to the top instead of the center (it gets lost in the center). I've tried:

withSpinner(plotOutput("endpointGraph", height = height, width = "100%"),
                     custom.css = "vertical-align:top")

and

withSpinner(plotOutput("endpointGraph", height = height, width = "100%"),
                     custom.css = "vertical-align: top;")

But that gives me an error "invalid argument type". Do you have any examples of how to use the custom.css argument?

Feature request: allow type=0

This is indeed just a "WIBNI" (Wouldn't It Be Nice If...), but: it would be nice to allow the spinner type to be set to zero, which would display no spinner.

using shinycssloaders in rmd document

is it possible to use shinycssloaders with shiny rmd doc? If so, what are the rules?
I'm trying this example and don't see spinner:

`

title: "shinycssloaders"
runtime: shiny

library(shiny)
library(shinycssloaders)
test_table<-data.frame(A=rnorm(200), B=rnorm(200))

# should load table with spinner
withSpinner(DT::dataTableOutput("table"))

output$table<- DT::renderDataTable({
  Sys.sleep(2)
  return(test_table)
})

`

uiOutput not working with shinycssloaders 0.3

Hi,
today I installed the tool PhyloProfile (from Bioconductor) and updated all of its dependencies including the shinycssloaders. Suddenly that tool worked incorrectly, some of the uiOutput elements couldn't be rendered and it showed no error messages, they are just empty.
When I downgrade shinycssloaders back to version 0.2.0, it worked again.
Have you ever encountered the same issue like that, or does the new version have some conflicts with other libraries?
I am attaching here the sessionInfo if it can help

> sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS  10.15.2

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
 [1] grid      stats4    parallel  stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] PhyloProfile_1.0.3     ExperimentHub_1.12.0   AnnotationHub_2.18.0   BiocFileCache_1.10.2  
 [5] dbplyr_1.4.2           zoo_1.8-7              OmaDB_2.2.0            plyr_1.8.5            
 [9] httr_1.4.1             shinyjs_1.1            shinyBS_0.61           RColorBrewer_1.1-2    
[13] gridExtra_2.3          GO.db_3.10.0           AnnotationDbi_1.48.0   ggplot2_3.2.1         
[17] GenomeInfoDbData_1.2.2 energy_1.7-7           data.table_1.12.8      colourpicker_1.0      
[21] Biostrings_2.54.0      XVector_0.26.0         IRanges_2.20.2         S4Vectors_0.24.3      
[25] bioDist_1.58.0         KernSmooth_2.23-16     Biobase_2.46.0         BiocGenerics_0.32.0   
[29] ape_5.3                shiny_1.4.0           

loaded via a namespace (and not attached):
 [1] nlme_3.1-143                  bitops_1.0-6                  matrixStats_0.55.0           
 [4] bit64_0.9-7                   GenomeInfoDb_1.22.0           tools_3.6.0                  
 [7] backports_1.1.5               R6_2.4.1                      DT_0.11                      
[10] DBI_1.1.0                     lazyeval_0.2.2                colorspace_1.4-1             
[13] withr_2.1.2                   tidyselect_0.2.5              bit_1.1-15.1                 
[16] curl_4.3                      compiler_3.6.0                graph_1.64.0                 
[19] SparseM_1.78                  xml2_1.2.2                    topGO_2.38.1                 
[22] scales_1.1.0                  rappdirs_0.3.1                digest_0.6.23                
[25] rmarkdown_2.0                 pkgconfig_2.0.3               htmltools_0.4.0              
[28] fastmap_1.0.1                 htmlwidgets_1.5.1             rlang_0.4.2                  
[31] rstudioapi_0.10               RSQLite_2.2.0                 jsonlite_1.6                 
[34] crosstalk_1.0.0               dplyr_0.8.3                   RCurl_1.98-1.1               
[37] magrittr_1.5                  Rcpp_1.0.3                    munsell_0.5.0                
[40] shinycssloaders_0.2.0         lifecycle_0.1.0               yaml_2.2.0                   
[43] zlibbioc_1.32.0               blob_1.2.0                    promises_1.1.0               
[46] crayon_1.3.4                  miniUI_0.1.1.1                lattice_0.20-38              
[49] knitr_1.27                    zeallot_0.1.0                 pillar_1.4.3                 
[52] GenomicRanges_1.38.0          boot_1.3-24                   glue_1.3.1                   
[55] BiocVersion_3.10.1            evaluate_0.14                 BiocManager_1.30.10          
[58] vctrs_0.2.1                   httpuv_1.5.2                  gtable_0.3.0                 
[61] purrr_0.3.3                   assertthat_0.2.1              xfun_0.12                    
[64] mime_0.8                      xtable_1.8-4                  later_1.0.0                  
[67] rsconnect_0.8.16              tibble_2.1.3                  memoise_1.1.0                
[70] interactiveDisplayBase_1.24.0 BiocStyle_2.14.4  

With the shinycssloaders v0.2.0 I got this (please notice the fileInput Upload input file and the two 1st variable and 2nd variable, they was rendered within a uiOutput)
image

With the v0.3.0, it became
image
Many thanks!
Vinh

Undefined event target ids cause javascript errors

Firstly, thanks for this plugin, it's super useful and the version that's currently on cran works great! But the latest GitHub source has the following issue:

Event handlers are currently attached to the document like so:

$(document).on('shiny:value shiny:error', function(event) {
  output_states[event.target.id] = 1;
  update_spinner(event.target.id);
});
}());

This code works fine as long as the event target is a div with an id (as all shiny outputs will be) but in some instances these events fire with the document as the target, which has no id, while update_spinner(id) requires id to not be undefined, as of this PR being merged: #27

This can cause a javascript error which is fatal to the app's proper functioning.

Should say, this does seem like a bug in shiny as it directly contradicts the shiny js events documentation which states that the target of these events should be an output object (https://shiny.rstudio.com/articles/js-events.html), but I'm seeing these events fire with the document as the target on multiple shiny apps. Given this behaviour, this plugin becomes unusable.

Suggestion: consolidate all CSS files into one file

Right now there's one css file per spinner type, plus a fallback css. There's no technical reason that they can't all be included in one file, and then the browser would be able to cache this one. The downside is that the file will be larger, but it's still tiny and negligible.

JavaScript error caused by unescaped selector when used with Shiny bookmark feature

Since recently, probably due to a Shiny update, I get the following JavaScript syntax error when using shinycssloaders:

Uncaught Error: Syntax error, unrecognized expression: #.bookmark
at Function.fa.error (jquery.min.js:2)
at fa.tokenize (jquery.min.js:2)
at fa.select (jquery.min.js:2)
at Function.fa [as find] (jquery.min.js:2)
at n.fn.init.find (jquery.min.js:2)
at new n.fn.init (jquery.min.js:2)
at n (jquery.min.js:2)
at show_spinner (spinner.js:5)
at update_spinner (spinner.js:23)
at HTMLDocument. (spinner.js:34)
init_shiny.js:314 Uncaught TypeError: Cannot read property 'normalCall' of undefined
at k (init_shiny.js:314)
init_shiny.js:381 Uncaught TypeError: Cannot read property 'normalCall' of undefined
at n (init_shiny.js:381)

A similar error was reported here:
rstudio/shinytest#161

So, probably it can be solved by escaping the IDs in a similar way in spinner.js.

I did not have the time to create a reproducible example, but here my session info:

R version 3.4.4 (2018-03-15)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=Norwegian Bokmål_Norway.1252  LC_CTYPE=Norwegian Bokmål_Norway.1252    LC_MONETARY=Norwegian Bokmål_Norway.1252 LC_NUMERIC=C                            
[5] LC_TIME=Norwegian Bokmål_Norway.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] RPostgres_1.1.1            DBI_1.0.0                  processanimateR_0.1.2.9000 lubridate_1.7.4            svgPanZoom_0.3.3           DiagrammeRsvg_0.1         
 [7] DiagrammeR_1.0.0           xesreadR_0.2.2             processmapR_0.3.1          eventdataR_0.2.0           edeaR_0.8.0                bupaR_0.4.0.9000          
[13] RColorBrewer_1.1-2         magrittr_1.5               fastmatch_1.1-0            Cairo_1.5-9                DT_0.4                     shinycssloaders_0.2.0     
[19] shinyBS_0.61               shinyWidgets_0.4.3         dbplyr_1.2.1               forcats_0.3.0              stringr_1.3.1              dplyr_0.7.5               
[25] purrr_0.2.5                readr_1.1.1                tidyr_0.8.1                tibble_1.4.2               ggplot2_2.2.1.9000         tidyverse_1.2.1           
[31] scales_0.5.0.9000          rlang_0.2.1                shiny_1.1.0               

loaded via a namespace (and not attached):
 [1] nlme_3.1-131.1    bit64_0.9-7       httr_1.3.1        profvis_0.3.5     tools_3.4.4       R6_2.2.2          lazyeval_0.2.1    colorspace_1.3-2  tidyselect_0.2.4  gridExtra_2.3    
[11] mnormt_1.5-5      bit_1.1-14        curl_3.2          compiler_3.4.4    cli_1.0.0         rvest_0.3.2       xml2_1.2.0        influenceR_0.1.0  plotly_4.7.1      psych_1.8.4      
[21] digest_0.6.15     foreign_0.8-69    pkgconfig_2.0.1   htmltools_0.3.6   htmlwidgets_1.2   ggthemes_3.5.0    readxl_1.1.0      rstudioapi_0.7    bindr_0.1.1       visNetwork_2.0.3 
[31] jsonlite_1.5      crosstalk_1.0.0   rgexf_0.15.3      Rcpp_0.12.17      munsell_0.4.3     viridis_0.5.1     stringi_1.1.7     yaml_2.1.19       plyr_1.8.4        shinyTime_0.2.1  
[41] blob_1.1.1        grid_3.4.4        parallel_3.4.4    promises_1.0.1    crayon_1.3.4      miniUI_0.1.1.1    lattice_0.20-35   haven_1.1.1       hms_0.4.2         pillar_1.2.3     
[51] igraph_1.2.1      reshape2_1.4.3    XML_3.98-1.11     glue_1.2.0        V8_1.5            downloader_0.4    data.table_1.11.4 modelr_0.1.2      httpuv_1.4.3      cellranger_1.1.0 
[61] gtable_0.2.0      assertthat_0.2.0  mime_0.5          xtable_1.8-2      broom_0.4.4       later_0.7.2       viridisLite_0.3.0 bindrcpp_0.2.2    Rook_1.1-1        brew_1.0-6   

Missing spinner when leafletOutput is updated through leafletProxy

Hi,
the package works great with renderLeaflet, thanks a lot! However, the spinner doesn't show up when updating the map with leafletProxy, as illustrated by the following MWE. Do you have any advice on how to overlay a loader animation over the map while it is being updated by a call to leafletProxy?

Cheers,
Andrzej

library(shiny)
library(shinycssloaders)
library(leaflet)

ui <- fluidPage(
  withSpinner(leafletOutput("map")),
  p(),
  actionButton("recalc", "New points")
)

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

  points <- eventReactive(input$recalc, {
    Sys.sleep(1)
    cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
  }, ignoreNULL = FALSE)

  output$map <- renderLeaflet({
    leaflet() %>%  setView(13, 48, 6) %>%
      addProviderTiles(providers$Stamen.TonerLite)
  })

  observe({
    leafletProxy("map") %>%
      clearMarkers() %>%
      addMarkers(data = points())
  })
}

shinyApp(ui, server)

withspinner not working with conditional UI

Hello,

Many thanks for such a great package. I am developing shiny app and wanted to use shinycssloaders.
When I use withspinner function with plotOutput it doesnt work correctly. The spinner comes up as soon as the box appears. I have actionbutton to display plot in that box. The box is created using renderUI based on checkbox selection.

`ui.R

   selectSteps <- list("step1", "step2")
   checkboxGroupInput('Steps', "Select step:", selectSteps)
   fluidRow(actionButton('RUN', 'Run')),
   fluidRow(
        column(6,uiOutput("tab1")),
        column(6,uiOutput("tab2"))`

`server.R

      hideBoxes <- reactive({
      perm.vector <- as.vector(input$Steps)
      perm.vector
       }) 
observe({
     if(input$RUN == 0) return() 
        isolate({
          output[["tab1"]] <- renderUI({
             listSteps <- hideBoxes()                             
             if("step1" %in% listSteps){                                 
                box(title = "tab1", width=12,                                
                     tabBox(                                          
                           id = "tabset1", width=12,                                 
                           tabPanel("plot1",                                              
                                 actionButton("plotclick", "Plot it"),                                                 
                                 withSpinner(plotOutput("plotit"), type = 6)))                             

      observeEvent(input$plotclick,{           
             output$plotit <- renderPlot({
                    myPlot()
         })`

Any idea what am I doing wrong here?

Thanks.

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.