Randomized loading page image in Shiny App - css

I have a Shiny app that has several reactive tables that take time to load and have successfully modified the code I found on this website(https://www.listendata.com/2019/07/add-loader-for-shiny-r.html) to have a loading gif display when each tab is selected as the output tables generate (but not when conditional panels are generating).
I would like to randomize the image. I suspect this can be achieved with the shinyJS package but I have very little Java experience and I just can't seem to make sense of it.
library(shiny)
library(shinydashboard)
# User Interface
ui <-
dashboardPage(skin = "black",
dashboardHeader(title = "Loading Screen"),
dashboardSidebar(),
dashboardBody(
# Javasript Code
singleton(tags$head(HTML("
<script type='text/javascript'>
/* When recalculating starts, show loading screen */
$(document).on('shiny:recalculating', function(event) {
if(event.target.id === 'plot'){
$('div#divLoading').addClass('show');
}
});
/* When new value or error comes in, hide loading screen */
$(document).on('shiny:value shiny:error', function(event) {
$('div#divLoading').removeClass('show');
});
</script>"))),
# CSS Code
singleton(tags$head(HTML(paste0("
<style type='text/css'>
#divLoading
{
display : none;
}
#divLoading.show
{
display : block;
position : fixed;
z-index: 100;
background-image : url('http://northerntechmap.com/assets/img/loading-dog.gif');
background-size: auto 40%;
background-repeat : no-repeat;
background-position : center;
left : 0;
bottom : 0;
right : 0;
top : 0;
}
#loadinggif.show
{
left : 50%;
top : 50%;
position : absolute;
z-index : 101;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
width: 100%;
margin-left : -16px;
margin-top : -16px;
}
div.content {
width : 1000px;
height : 1000px;
}
</style>")))),
# HTML Code
box(tags$body(HTML("<div id='divLoading'> </div>")),
plotOutput('plot', width = "800px", height = "450px"),
actionButton('goPlot', 'Generate Plot', icon("paper-plane"),
style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
width = 12, height = 500)
))
server <- function(input, output) {
output$plot <- renderPlot({
input$goPlot
Sys.sleep(3)
plot(iris$Sepal.Length, iris$Petal.Length)
})
}
shinyApp(ui, server)

Related

Copy the background color from an action button in shiny, which is picked from a ColourPicker

I have a ColourPicker that I use to determine the background color of an action button. What I would like to do is click on the action button and have the hex code that was clicked from the ColourPicker be copied to my clipboard. The goal is to then paste that value to be the background color in a cell of a data table. Right now, I am mostly worried about the copying part.
I have a button that I can copy-button so I can copy a text value, which is easy enough, but this is not what I am trying to do.
What I would like to do is copy the hex code from the small button that is generated in my code, which can change color based on the color selected by the ColourPicker, and access just the hex code value of that button.
Do I need to reference the ID of the ColourPicker in order to access the hex code? Or could I just copy that hex code straight from the button? I haven't been able to find any packages that work with getting hex codes from objects.
For reference, this is basically what I have (much thanks again to #lz100)
library(shiny)
library(shinythemes)
library(sortable)
library(colourpicker)
library(glue)
library(png)
library(dplyr)
library(DT)
library(rclipboard)
# funcs
plate96 <- function(id) {
div(
style = "position: relative; height: 500px",
tags$style(HTML(
'
.wells {
height: 490px;
width: 750px;
overflow: hidden;
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 5%);
box-shadow: inset 0 1px 1px rgb(0 0 0 / 5%);
position: relative;
transform: translateX(50%);
}
.wells:after {
content: "";
height: 450px;
width: 690px;
border: 1px solid;
position: absolute;
transform: translate(15px, -100%);
z-index: -1;
}
.wells .corner-top {
position: absolute;
margin: -20px;
width: 43px;
height: 34px;
transform: rotate(45deg);
background-color: white;
z-index: 1;
left: 30px;
border-right: 1px solid;
}
.wells .corner-bot {
position: absolute;
margin: -20px;
width: 40px;
height: 40px;
transform: rotate(45deg);
background-color: white;
z-index: 1;
left: 35px;
bottom: 20px;
border-top: 1px solid;
}
.wells .html-widget {
transform: translateX(20px);
}
.wells thead tr th {
font-weight: 100;
}
.wells table:after {
content: "";
border: 1px solid #ccc;
position: absolute;
height: 410px;
width: 635px;
z-index: -1;
transform: translate(33px, -99%);
}
.wells table.dataTable.no-footer {
border-spacing: 3px;
border-bottom: unset;
}
.wells table.dataTable thead th {
border-bottom: unset;
}
.wells tbody tr td:not(:first-of-type) {
border-radius: 50%;
border: 1px solid black;
height: 15px;
width: 15px;
padding: 15px;
font-size: 0;
}
.wells table.dataTable.cell-border tbody tr td:first-of-type {
border: unset;
border-right: 1px solid #ccc;
font-weight: 900;
}
'
)),
div(
style = "position: absolute; left: 50%; transform: translateX(-100%);",
div(
class = "wells",
div(class = "corner-top"),
div(class = "corner-bot"),
DT::dataTableOutput(id, width = "90%", height= "100%")
)
)
)
}
renderPlate96 <- function(id, colors = rep("white", 96), byrow = TRUE) {
stopifnot(is.character(colors) && length(colors) == 96)
plate <- matrix(1:96, nrow = 8, ncol = 12, byrow = byrow, dimnames = list(LETTERS[1:8], 1:12))
colnames(plate) <- stringr::str_pad(colnames(plate), 2, "left", "0")
renderDataTable({
datatable(
plate,
options = list(dom = 't', ordering = F),
selection = list(target = 'cell'),
class = 'cell-border compact'
) %>%
formatStyle(
1:12,
cursor = 'pointer',
backgroundColor = styleEqual(1:96, colors, default = NULL)
)
})
}
# app code
ui <- fluidPage(
plate96("plate"),
tags$b("Wells Selected:"),
verbatimTextOutput("well_selected"),
rclipboardSetup(),
numericInput("num_conds",
label = h3("Enter the number of treatments/ conditions"),
min = 1,
max = 20,
value = 1),
uiOutput("cond_colors"),
htmlOutput("cond_buttons", align = 'center'),
# Add a text input
textInput("copytext", "Copy this:", "Test 1"),
# UI ouputs for the copy-to-clipboard buttons
uiOutput("clip"),
# A text input for testing the clipboard content.
textInput("paste", "Paste here:")
)
server <- function(input, output, session){
#####Number output for number of conditions#####
output$value = renderPrint({ input$num_conds })
#### Color selection for UI input####
output$cond_colors <- renderUI({
num_conds <- as.integer(input$num_conds)
lapply(1:num_conds, function(i) {
colourInput(paste0("colors", i),
label = (paste0("Select a color for condition ", i)),
show = c("both"),
value = "black",
palette = c("limited"),
)
})
})
#### Create action buttons for conditions to be selected####
output$cond_buttons <- renderUI({
num_conds = as.integer(input$num_conds)
lapply(1:num_conds, function(i) {
bg = input[[paste0("colors", i)]]
style = paste0(
collapse = " ",
glue("background-color:{bg};
color:#ffffff;
border-color:#000000")
)
label = input[[paste0("condID", i)]]
cond_buttons = actionButton(paste0("cond_buttons", i),
label = label,
style = style
)
})
})
# Add clipboard buttons
output$clip <- renderUI({
output$clip <- renderUI({
rclipButton(
inputId = "clipbtn",
label = "Test copy button",
clipText = input$copytext,
icon = icon("clipboard")
)
})
})
# Workaround for execution within RStudio version < 1.2
if (interactive()){
observeEvent(input$clipbtn, clipr::write_clip(input$copytext))
}
output$plate <- renderPlate96(
"plate",
colors = c(
rep("#eeeeee", 12),
rep("#27408b", 12),
rep("#0f8b44", 12),
rep("#9400d3", 12),
rep("#0701ff", 12),
rep("white", 36)
)
)
output$well_selected <- renderPrint({
input$plate_cells_selected
})
}
shinyApp(ui = ui, server = server)
And here is a picture to kind of explain what I am thinking. Before:
After:
You could set an input value via client-side Javascript, using Shiny.setInputValue and process this value like those provided by UI input elements.
Simple example:
library(shiny)
ui <- shiny::fluidPage(
actionButton('colored_button', 'a green button',
style = 'background-color:#00ff00'
),
actionButton('button_get_color', 'get color'),
textOutput('color_message'),
## inject client-side javascript:
tags$script('
// bind JS code to the getter button:
document.getElementById("button_get_color")
.onclick = function(){
// set input value via JS:
Shiny.setInputValue("color",
// select colored button and get its background color:
document.getElementById("colored_button")
.style.backgroundColor)
}'
)
)
server <- function(input, output) {
observeEvent(input$button_get_color,{
## do stuff, e. g.
output$color_message <- renderPrint(input$color)
})
}
shinyApp(ui, server)
Edit:
You can also use the colored button (or any page element) to set the input value: get the element by ID and have it trigger Shiny.setInputValue on click (or other mouse event)
more information on communicating via JS here
some suggestions on converting RGB to Hex

Position carousel chevrons alongside bullets

I am using R's bsplus package to build a carousel of images. I want to move the chevrons next to the bullets.
I am aware of this SO sol'n regarding how to reposition the prev/next chevrons.
I can get close (see the 'right' chevron) but when I position it where I want it (see the 'left' chevron) it's no longer clickable.
Why is this?
How can I position the chevrons next to the bullets and maintain their functionality?
R Script
library("shiny")
library("bsplus")
ui <- fluidPage(
includeCSS("/home/law/whatbank_home/tests/bullet.css"),
# Application title
titlePanel("Carousel Demo"),
uiOutput("carousel")
)
server <- shinyServer(function(input, output) {
output$carousel <- renderUI({
bs_carousel(id = "images", use_indicators = TRUE) %>%
bs_append(
content = bs_carousel_image(src = "https://placehold.it/900x500/3c8dbc/ffffff&text=Merry")
) %>%
bs_append(
content = bs_carousel_image(src = "https://placehold.it/900x500/3c8dbc/ffffff&text=Christmas")
) %>%
bs_append(
content = bs_carousel_image(src = "https://placehold.it/900x500/3c8dbc/ffffff&text=To")
) %>%
bs_append(
content = bs_carousel_image(src = "https://placehold.it/900x500/3c8dbc/ffffff&text=All")
)
})
})
# Run the application
shinyApp(ui = ui, server = server)
css
.carousel-control.left,
.carousel-control.right {
background: transparent;
}
.carousel-indicators .active {
background-color: #FCB700;
margin-bottom: 70px;
}
.carousel-indicators li {
background-color: #D8D8D8;
border: 1px solid #000;
margin-bottom: 70px;
}
.carousel-control.left .glyphicon {
left: 180px;
margin-left: 180px;
top: 183px;
margin-top: 183px;
}
.carousel-control.right .glyphicon {
right: 180px;
margin-right: 180px;
top: 160px;
margin-top: 160px;
}
You should try
.carousel-control {
width: 2%
}
In the example below, I use 2%.
library(shiny)
library(shinydashboardPlus) ### carousel() is from this package
library(DT)
jscode <-"
$(document).ready(function(){
$('#mycarousel').carousel( { interval: false } );
});"
shinyApp(
ui = dashboardPage(
header = dashboardHeader(),
sidebar = dashboardSidebar(),
body = dashboardBody(
tags$head(
tags$style(HTML("
#mycarousel {
width:900px;
height:600px;
}
.carousel-control{
color:#FF0000;
width: 2%;
}
"))
),
tags$head(tags$script(HTML(jscode))),
carousel(
id = "mycarousel",
carouselItem(
DTOutput("show_iris_dt")
),
carouselItem(
caption = "An image file",
tags$img(src = "YBS.png")
),
carouselItem(
caption = "Item 3",
tags$img(src = "http://placehold.it/900x500/39CCCC/ffffff&text=Happy+New+Year")
)
)
),
title = "Carousel Demo"
),
server = function(input, output) {
output$show_iris_dt <- renderDT({
datatable(iris)
})
}
)

Math mode in bsTooltip in shiny

I'm wondering whether these is any option to include math mode in tooltip title using bsTooltip() from shinyBS package.
Small example:
rm(list = ls())
library(shiny)
library(shinyBS)
ui <- basicPage(
headerPanel("Tooltip test"),
bsTooltip(id = "Equation", title = "\\(\\bar{X} = \\frac{1}{n}\\sum_{p = 1}^{n}X_p\\)", placement = "bottom", trigger = "hover", options = NULL),
mainPanel(
p("some text", htmlOutput("Equation", inline = TRUE))
)
)
server <- shinyServer(function(input, output,session) {
output$Equation <- renderUI({HTML("<font color='blue'><u>something which needs equation</u></font>")})
})
shinyApp(ui = ui, server = server)
The result (math mode) is not satisfactory:
No way with 'shinyBS'.
Here is a way using the qTip2 JavaScript library.
In order to use it, you have to download the files jquery.qtip.min.css and jquery.qtip.min.js, and put these two files in the www subfolder of the Shiny app.
library(shiny)
js <- "
$(document).ready(function() {
$('#Equation').qtip({
overwrite: true,
content: {
text: $('#tooltip')
},
position: {
my: 'top left',
at: 'bottom right'
},
show: {
ready: false
},
hide: {
event: 'unfocus'
},
style: {
classes: 'qtip-youtube qtip-rounded'
},
events: {
blur: function(event, api) {
api.elements.tooltip.hide();
}
}
});
});
"
library(shiny)
ui <- basicPage(
tags$head(
tags$link(rel = "stylesheet", href = "jquery.qtip.min.css"),
tags$script(src = "jquery.qtip.min.js"),
tags$script(HTML(js)),
),
withMathJax(),
headerPanel("Tooltip test"),
mainPanel(
p("some text", htmlOutput("Equation", inline = TRUE)),
div(
id = "tooltip", style = "display: none;",
HTML("$$\\int_0^1 f(x) dx = \\pi$$")
)
)
)
server <- shinyServer(function(input, output,session) {
output$Equation <-
renderUI({HTML("<font color='blue'><u>something which needs equation</u></font>")})
})
shinyApp(ui = ui, server = server)
Just to add another option, we could create our own tooltip class following the example from W3 here. Then we can use {shiny}'s withMathJax() function to render the tooltip as formula.
I usually use custom tooltips in cases where I only have a few tooltips that I want to customize. It has the advantage that it comes with no additional dependencies. The major drawbacks of this custom tooltip are that (1) it is displayed as child element and not in a separate container on the top layer like tooltips generated with javascript and that (2) you have to create css classes for each arrow direction. So if you have many tooltips pointing in different directions an additional javascript library like qTip2 should be definitely worth the dependency.
library(shiny)
ui <- fluidPage(
tags$head(
tags$style(HTML(
# tooltip implementation from:
# https://www.w3schools.com/css/tryit.asp?filename=trycss_tooltip_arrow_top
# just added a `t` to make classes unique
".ttooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.ttooltip .ttooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
top: 150%;
left: 50%;
margin-left: -60px;
}
.ttooltip .ttooltiptext::after {
content: '';
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent black transparent;
}
.ttooltip:hover .ttooltiptext {
visibility: visible;
}")
)
),
headerPanel("Tooltip test"),
mainPanel(
p("some text", htmlOutput("Equation", inline = TRUE)),
))
server <- shinyServer(function(input, output,session) {
output$Equation <- renderUI({
span(class = "ttooltip",
style = "color: blue",
"something which needs equation",
span(class = "ttooltiptext",
withMathJax("$$\\bar{X} = \\frac{1}{n}\\sum_{p = 1}$$"))
)
})
})
shinyApp(ui = ui, server = server)

Is there a way to *output* star rating in R Shiny?

Dears,
In my app, users rate some stuff.
I want to output 5-star ratings based on their ratings just like the ones in IMDB.
There are fractions in my numbers, and I want the stars to accommodate them.
I don't know Java nor JavaScript at all.
Is there something like a package for this? or what to do?
Thanks in advance.
You'll need to create two files, a css and then your app...ie:
app.R
-- www/
------ stars.css
Your stars.css file will have the rules for the HTML markup which will update based on our app after using includeCSS in the header::
.ratings {
position: relative;
vertical-align: middle;
display: inline-block;
color: #b1b1b1;
overflow: hidden;
}
.full-stars{
position: absolute;
left: 0;
top: 0;
white-space: nowrap;
overflow: hidden;
color: #fde16d;
}
.empty-stars:before,
.full-stars:before {
content: "\2605\2605\2605\2605\2605";
font-size: 44pt; /* Make this bigger or smaller to control size of stars*/
}
.empty-stars:before {
-webkit-text-stroke: 1px #848484;
}
.full-stars:before {
-webkit-text-stroke: 1px orange;
}
/* Webkit-text-stroke is not supported on firefox or IE */
/* Firefox */
#-moz-document url-prefix() {
.full-stars{
color: #ECBE24;
}
}
/* IE */
<!--[if IE]>
.full-stars{
color: #ECBE24;
}
<![endif]-->
In our app we want the final markup to appear as follows:
<div class="ratings">
<div class="empty-stars"></div>
<div class="full-stars" style="width:70%"></div>
</div>
So to do this we use a combination of UI static elements and then uiOutput, which matches a renderUI on the server side:
library(shiny)
ui <- fluidPage(
includeCSS("www/stars.css"),
sliderInput(inputId = "n_stars", label = "Ratings", min = 0, max = 5, value = 3, step = .15),
tags$div(class = "ratings",
tags$div(class = "empty-stars",
uiOutput("stars_ui")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output, session) {
output$stars_ui <- renderUI({
# to calculate our input %
n_fill <- (input$n_stars / 5) * 100
# element will look like this: <div class="full-stars" style="width:n%"></div>
style_value <- sprintf("width:%s%%", n_fill)
tags$div(class = "full-stars", style = style_value)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Our app then using the slider inpout to create the fill % of stars.
I wrote a package to solve similar problem so that others don't need to work with CSS and JS. https://github.com/shahronak47/shinyRatings
#Installation of the package from Github
#devtools::install_github('shahronak47/shinyRatings')
library(shiny)
library(shinyRatings)
ui <- fluidPage(
shinyRatings('star'),
textOutput('text')
)
server <- function(input, output, session) {
output$text <- renderText({paste("No. of stars : ", input$star)})
}
shinyApp(ui, server)

Building Shiny app with Flickity carousel

I am building an app in Shiny and would like to interface it with metafizzy's Flickity carousel. On a single page app flickity works well using the initializing code in the example below.
However, the app I am creating uses a navbar. It seems that when I initialize the carousel it works well on the first tab, but carousels on the second tab (or other) will not initialize. However, if you are on Tab 2 (for example) and resize the window, the carousel seems to initialize and all runs smoothly on that Tab, but this will turn off / hide the other carousels on the other tabs.
I am wondering if there is a way to change the script so that all carousels on all tabs will be initialized and available when the page loads? I am very new to javascript so apologies if this is a simple question.
Thank you
ui:
library(shiny)
shinyUI(tagList(
tags$head(
includeCSS("www/flickity-docs.css"),
includeCSS("www/styles.css"),
includeScript("www/flickity-docs.min.js")
),
navbarPage(' ',
position = ('fixed-top'),
collapsible = T,
# Panel 1 =====================================================
tabPanel('Page 1',
div(class = "main-carousel",
div(class = "carousel-cell",
div(class = "carousel-inner",
h2('This text on page 1.1 is appearing')
)
)
)
),
# Panel 2 =====================================================
tabPanel('Page 2',
div(class = "main-carousel",
div(class = "carousel-cell",
div(class = "carousel-inner",
h2('This text on page 2.1 is not appearing')
)
)
)
)
),
HTML(
"<script type='text/javascript'>
// selectorAll for multiple flickity
var elems = document.querySelectorAll('.main-carousel');
// loop to initialize
for ( var i=0, len = elems.length; i < len; i++ ) {
var elem = elems[i]
new Flickity( elem, {
// options
cellAlign: 'center',
wrapAround: true,
cellSelector: '.carousel-cell',
});
}
</script>"
)
)
)
server (blank for now):
server <- function(input, output, session) {
}
CSS:
.carousel-cell {
width: 100%;
height: 100px;
margin-right: 10px;
padding: 0%;
line-height:0px;
background-color: black;
display: block;
}
.carousel-cell:before {
content: normal;
}
.carousel-inner{
width: 100%;
height: 100%;
background-color: black;
color: white;
content: normal;
padding-right: 12.5%;
padding-left: 12.5%;
padding-top: 5%;
padding-bottom: 5%;
border-radius: 5px;
font-size:20px;
}

Resources