activate tabpanel from another tabpanel - r

I want when i start the application the tab panel tab2 = desactivated,
and will be activated once i click the button in the first tab panel tab1,
i tried with shinyjs and through CSS properties but i can not do that.
thanks for your help
Alex
library(shiny)
library(shinyjs)
runApp(list(
ui = bootstrapPage(
tabsetPanel(
tabPanel(title = "tab1", id="tab1",
br(),
actionButton("click", label = "View tab2 panel")),
tabPanel(title = "tab2", id="tab2")
)
),
server = function(input, output, session){
}
))

You need a bit of javascript to do this. Here's a solution using shinyjs. I also included some css to make it clear when the tab is disabled
jscode <- "
shinyjs.disableTab = function(name) {
var tab = $('.nav li a[data-value=' + name + ']');
tab.bind('click.tab', function(e) {
e.preventDefault();
return false;
});
tab.addClass('disabled');
}
shinyjs.enableTab = function(name) {
var tab = $('.nav li a[data-value=' + name + ']');
tab.unbind('click.tab');
tab.removeClass('disabled');
}
"
css <- "
.nav li a.disabled {
background-color: #aaa !important;
color: #333 !important;
cursor: not-allowed !important;
border-color: #aaa !important;
}"
library(shiny)
library(shinyjs)
runApp(list(
ui = fluidPage(
useShinyjs(),
extendShinyjs(text = jscode),
inlineCSS(css),
tabsetPanel(
id = "navbar",
tabPanel(title = "tab1", id = "tab1",
br(),
actionButton("btn", label = "View tab2 panel")),
tabPanel(title = "tab2", id = "tab2")
)
),
server = function(input, output, session) {
# disable tab2 on page load
js$disableTab("tab2")
observeEvent(input$btn, {
# enable tab2 when clicking the button
js$enableTab("tab2")
# switch to tab2
updateTabsetPanel(session, "navbar", "tab2")
})
}
))
You could also put the javascript in a separate file and use extendShinyjs(file = ...) instead of extendShinyjs(text = ...).

Looking at this 5 years later, I had to make this change to Dean's code to make it work:
extendShinyjs(text = jscode)
becomes
extendShinyjs(text = jscode, functions = c('disableTab','enableTab'))

Some small clarifications on the arguments value, id, and value working from #DeanAttali's reprex:
library("shiny")
library("shinyjs")
library("V8") ## Required for shinyjs::extendShinyjs()
## JavaScript that dis/enables the ABILITY to click the tab (without changing aesthetics)
app_jscode <-
"shinyjs.disableTab = function(name) {
var tab = $('.nav li a[data-value=' + name + ']');
tab.bind('click.tab', function(e) {
e.preventDefault();
return false;
});
tab.addClass('disabled');
}
shinyjs.enableTab = function(name) {
var tab = $('.nav li a[data-value=' + name + ']');
tab.unbind('click.tab');
tab.removeClass('disabled');
}"
## css snipit that makes it LOOK like we are/n't able click the tab (with outchanging functionality)
app_css <-
".nav li a.disabled {
background-color: #aaa !important;
color: #333 !important;
cursor: not-allowed !important;
border-color: #aaa !important;
}"
ui = fluidPage(
shinyjs::useShinyjs(),
shinyjs::extendShinyjs(text = app_jscode),
shinyjs::inlineCSS(app_css),
navbarPage(title = "Navbar title!", id = "navbarid",
tabPanel(title = "tab1", ## id and value args not needed
br(),
p("in tab 1."),
actionButton("btn", label = "toggle locked tabs")),
tabPanel(title = "tab2", ## id and value args not needed
p("in tab 2."))
)
)
server = function(input, output, session) {
## Disable tab2 on page load
js$disableTab("tab2")
observeEvent(input$btn, {
## Enable tab2 when clicking the button
shinyjs::js$enableTab("tab2") ## On a tab's title
## Switch to tab2
updateNavbarPage(session, "navbarid", "tab2") ## On navbar's id, tab's title
#### Taking it further:
## Also disable tab1 as a selection
shinyjs::js$disableTab("tab1")
})
}
shinyApp(ui = ui, server = server)

Related

How to switch external css file based on user input in rshiny?

I am looking to build a dark mode in my application. I realize we can achieve that using bs_theme(), but my application has many more settings in an external css file that do not get read when I use bs_theme().
I want to have 2 separate CSS files, one for light theme and one for dark theme. Based on the user input, the relevant theme file should be loaded in my Rshiny app. Any suggestion on how this could be done?
I'd create two different css classes in this case.
Here you'll find how to include css files (as many as you like) into a shiny app.
To switch between the classes we can use addCssClass/ removeCssClass (or toggleCssClass) from library(shinyjs):
library(shiny)
library(shinyjs)
if(!dir.exists("www")){
dir.create("www")
}
writeLines(".dark {
background-color: black;
color: white; /* text color */
}", con = "www/dark_mode.css")
writeLines(".light {
background-color: white;
color: black; /* text color */
}", con = "www/light_mode.css")
ui <- fluidPage(
useShinyjs(),
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
),
radioButtons("mode", "Select mode", choices = c("dark", "light"), selected = "light")
)
server <- function(input, output, session) {
observeEvent(input$mode, {
if(input$mode == "dark"){
addCssClass(class = "dark", selector = "body")
removeCssClass(class = "light", selector = "body")
} else {
addCssClass(class = "light", selector = "body")
removeCssClass(class = "dark", selector = "body")
}
})
}
shinyApp(ui, server)
The same can be done via Shiny.addCustomMessageHandler and some custom JS using e.g. element.classList.add("myclass"); (see this).
Edit: Apply addCssClass to inputs of different classes:
library(shiny)
library(shinyjs)
if(!dir.exists("www")){
dir.create("www")
}
writeLines(".dark {
background-color: black !important;
color: white; /* text color */
}", con = "www/dark_mode.css")
writeLines(".light {
background-color: white !important;
color: black; /* text color */
}", con = "www/light_mode.css")
ui <- fluidPage(
useShinyjs(),
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
),
radioButtons("mode", "Select mode", choices = c("dark", "light"), selected = "light"),
selectizeInput("Test", "Test Input", choices = 1:10),
actionButton("testButton", "Test Button")
)
server <- function(input, output, session) {
observeEvent(input$mode, {
applyTo <- list(".selectize-input", ".btn-default")
if(input$mode == "dark"){
lapply(applyTo, function(x){
addCssClass(class = "dark", selector = x)
removeCssClass(class = "light", selector = x)
})
} else {
lapply(applyTo, function(x){
addCssClass(class = "light", selector = x)
removeCssClass(class = "dark", selector = x)
})
}
})
}
shinyApp(ui, server)
Edit: using forEach:
library(shiny)
library(shinyjs)
if(!dir.exists("www")){
dir.create("www")
}
writeLines(".dark {
background-color: black !important;
color: white; /* text color */
}", con = "www/dark_mode.css")
writeLines(".light {
background-color: white !important;
color: black; /* text color */
}", con = "www/light_mode.css")
ui <- fluidPage(
useShinyjs(),
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "dark_mode.css"),
tags$link(rel = "stylesheet", type = "text/css", href = "light_mode.css")
),
radioButtons("mode", "Select mode", choices = c("dark", "light"), selected = "light"),
selectizeInput("Test", "Test Input", choices = 1:10),
actionButton("testButton", "Test Button")
)
server <- function(input, output, session) {
dm_classes <- paste(c(".selectize-input", ".btn-default"), collapse = ", ")
observeEvent(input$mode, {
if(input$mode == "dark"){
runjs(sprintf("document.querySelectorAll('%s').forEach(x=>x.classList.add('dark'));
document.querySelectorAll('%s').forEach(x=>x.classList.remove('light'));", dm_classes, dm_classes))
} else {
runjs(sprintf("document.querySelectorAll('%s').forEach(x=>x.classList.add('light'));
document.querySelectorAll('%s').forEach(x=>x.classList.remove('dark'));", dm_classes, dm_classes))
}
})
}
shinyApp(ui, server)
Assuming your CSS files are named darkmode.css and lightmode.css, and are placed into the www subfolder, you can use renderUI like this:
library(shiny)
ui <- fluidPage(
tags$head(
uiOutput("css")
),
radioButtons("select", "Select mode", c("dark", "light"))
)
server <- function(input, output){
output[["css"]] <- renderUI({
cssfile <- paste0(input[["select"]], "mode.css")
tags$link(rel = "stylesheet", type = "text/css", href = cssfile)
})
}
shinyApp(ui, server)

Update color of actionlink in shiny

I want to change colour of the actionLink once it is clicked. I could not find any post which will achieve this.
What I found:
R Shiny toggle text of actionLink
shiny module: update color of button
But these were of no help. Here is the sample code from the answer from the first link (by #Julien Navarre)
library(shiny)
library(shinyjs)
shinyApp(
ui = shinyUI(
fluidPage(useShinyjs(),
actionLink("button", "Show additional"),
hidden(div(id='text_div', verbatimTextOutput("text")))
)
),
server = function(input, output, session){
observeEvent(input$button, {
toggle('text_div')
output$text <- renderText({"Additional"})
if (input$button %% 2 == 1) {
txt <- "Hide Additional"
} else {
txt <- "Show Additional"
}
updateActionButton(session, "button", label = txt)
})
}
)
In this code, once the label is changed, the colour of the label should also change. For example, Show Additional link should have a green colour, whereas Hide Additional should have red colour.
I tried updateactionLink with color argument but there is no such argument.
How can I achieve this?
One way would be to use css and addClass, removeClass from {shinyjs}:
library(shiny)
library(shinyjs)
shinyApp(
ui = shinyUI(
fluidPage(useShinyjs(),
tags$head(
tags$style(HTML("
a.action-button {
color: #00ff00;
}
a.action-button.red {
color: #ff0000;
}"))
),
actionLink("button", "Show additional"),
hidden(div(id='text_div', verbatimTextOutput("text")))
)
),
server = function(input, output, session){
observeEvent(input$button, {
if (input$button %% 2 == 1) {
txt <- "Hide Additional"
shinyjs::addClass("button", "red")
} else {
txt <- "Show Additional"
shinyjs::removeClass("button", "red")
}
toggle('text_div')
output$text <- renderText({"Additional"})
updateActionButton(session, "button", label = txt)
})
}
)

How to get a notification icon on a tab in shiny

I have a tabpanelSet in a shiny application. One of the tabs contains a datatable. Id like the number of rows in the datatable to show in a nice circular icon next to the the tab header text so the user can see see the number in the datatable within the tab before clicking on the tab.
Here is the basic app. Its the 'Details' tab that I would like the circular notification icon library
library(shiny)
library(DT)
library(data.table)
ui <- fluidPage(
# Application title
titlePanel("Circular notification icon app"),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Empty"),
tabPanel("Details",
DT::dataTableOutput("iris"))
)
)
)
server <- function(input, output) {
output$iris = DT::renderDT({
datatable(iris,class = "display wrap",selection = "single",
options = list(
scrollX = TRUE,
scrollY = TRUE,
pageLength = 15,
select = "api",
dom = 'Bfrtip')
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Like this?
library(shiny)
library(DT)
library(shinyjs)
CSS <- "
#tabHeader {
display: inline-block;
}
.circle {
display: inline-block;
width: 25px;
height: 25px;
border-radius: 50%;
font-size: 12px;
color: #fff;
line-height: 25px;
text-align: center;
background: #000
}"
js <- function(nrows){
sprintf("$('#tabHeader .circle').html('%s');", nrows)
}
ui <- fluidPage(
useShinyjs(),
tags$head(
tags$style(HTML(CSS))
),
# Application title
titlePanel("Circular notification icon app"),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Empty"),
tabPanel(div(id = "tabHeader", span("Details"),
div(class = "circle")),
DTOutput("iris"))
)
)
)
server <- function(input, output) {
runjs(js(nrow(iris)))
output$iris = renderDT({
datatable(iris, class = "display wrap", selection = "single",
options = list(
scrollX = TRUE,
scrollY = TRUE,
pageLength = 15,
select = "api",
dom = 'Bfrtip')
)
})
}
# Run the application
shinyApp(ui = ui, server = server)

How to read & display time in Navbar of Shiny R Dashboard

I want to display Last Updated time in the navbar of shiny R. For that I'm storing the last updated time in csv file which I will be using to read in the server.R but I'm unable to figure out how to display that time on the rightmost side of the navbar. Any help would be highly appreciated. Thank You
shinyUI(
navbarPage(
title = 'Welcome',
tabPanel('Overview',
tabsetPanel(
tabPanel('Forward',
fluidRow(
DT::dataTableOutput("view_fwd"),width = 6
)
),
tabPanel('Reverse',
fluidRow(
DT::dataTableOutput("view_rvo"),width = 6
))
))
library(shiny)
ui <- fluidPage(
navbarPage(
title = 'Welcome',
tabPanel('Overview',
tabsetPanel(
tabPanel('Forward',
fluidRow(
DT::dataTableOutput("view_fwd"),width = 6
)
),
tabPanel('Reverse',
fluidRow(
DT::dataTableOutput("view_rvo"),width = 6
))
)),
tabPanel(tags$ul(class='nav navbar-nav',
style = "padding-left: 550px;", htmlOutput("time"))) # here you output time, need to positions on the left side by 550px
)
)
# Define server logic
server <- function(input, output) {
output$time <- renderUI({
as.character(strptime(Sys.time(), "%Y-%m-%d %H:%M:%S", tz = "EET"))
})
}
# Run the application
shinyApp(ui = ui, server = server)
With some css and Javascript you can let the time float to the right and disable click events on that tab. You would need the package shinyjs for it.
library(shiny)
library(shinyjs)
jscode <- '
shinyjs.init = function() {
$(".nav").on("click", ".disabled", function (e) {
e.preventDefault();
return false;
});
}
'
ui <- fluidPage(
tags$head(tags$style(HTML("
.navbar-nav {
float: none;
}
.navbar ul > li:nth-child(2) {
float: right;
}
.navbar ul > li:nth-child(2) {
color: black !important;
}
"))),
useShinyjs(),
extendShinyjs(text = jscode, functions = "init"),
navbarPage(
title = 'Welcome',
tabPanel('Overview',
tabsetPanel(
tabPanel('Forward',
fluidRow(
DT::dataTableOutput("view_fwd"),width = 6
)
),
tabPanel('Reverse',
fluidRow(
DT::dataTableOutput("view_rvo"),width = 6
))
)),
tabPanel(tags$ul(class='nav navbar-nav',
style = "padding-left: 5px; float: right;", htmlOutput("time")))
)
)
# Define server logic
server <- function(input, output) {
observe({
toggleClass(condition = input$foo,
class = "disabled",
selector = ".navbar ul > li:nth-child(2)")
})
output$time <- renderUI({
as.character(strptime(Sys.time(), "%Y-%m-%d %H:%M:%S", tz = "EET"))
})
}
# Run the application
shinyApp(ui = ui, server = server)

Expand/Collapse shiny box on header click

I have developed a shiny app, where we are using various box object in the ui. Currently the boxes expand/Collapse by clicking on the "+/-" sign on the right of the box header, but we need the expand/collapse on click on the header (anywhere on the box header).
Below code (sample code)
If you look at the box with chart, I want the expansion & collapse to be performed on clicking the header i.e. "Histogram box title" and not just the "+/-" sign on right side of the header:
## Only run this example in interactive R sessions
if (interactive()) {
library(shiny)
# A dashboard body with a row of infoBoxes and valueBoxes, and two rows of boxes
body <- dashboardBody(
# Boxes
fluidRow(
box(title = "Histogram box title",
status = "warning", solidHeader = TRUE, collapsible = TRUE,
plotOutput("plot", height = 250)
)
)
)
server <- function(input, output) {
output$plot <- renderPlot({
hist(rnorm(50))
})
}
shinyApp(
ui = dashboardPage(
dashboardHeader(),
dashboardSidebar(),
body
),
server = server
)
}
This is easily achievable using javascript. You just have to create a javascript function and call the same in your header code. Refer to below code for better understanding. I have provided 3 options, let me know if this works for you.
## Only run this example in interactive R sessions
if (interactive()) {
library(shiny)
# javascript code to collapse box
jscode <- "
shinyjs.collapse = function(boxid) {
$('#' + boxid).closest('.box').find('[data-widget=collapse]').click();
}
"
# A dashboard body with a row of infoBoxes and valueBoxes, and two rows of boxes
body <- dashboardBody(
# Including Javascript
useShinyjs(),
extendShinyjs(text = jscode),
# Boxes
fluidRow(
box(id="box1",title = actionLink("titleId", "Histogram box title",icon =icon("arrow-circle-up")),
status = "warning", solidHeader = TRUE, collapsible = T,
plotOutput("plot", height = 250)
),
box(id="box2",title = p("Histogram box title",
actionButton("titleBtId", "", icon = icon("arrow-circle-up"),
class = "btn-xs", title = "Update")),
status = "warning", solidHeader = TRUE, collapsible = T,
plotOutput("plot1", height = 250)
),
box(id="box3",title = actionButton("titleboxId", "Histogram box title",icon =icon("arrow-circle-up")),
status = "warning", solidHeader = TRUE, collapsible = T,
plotOutput("plot2", height = 250)
)
)
)
server <- function(input, output) {
output$plot <- renderPlot({
hist(rnorm(50))
})
output$plot1 <- renderPlot({
hist(rnorm(50))
})
output$plot2 <- renderPlot({
hist(rnorm(50))
})
observeEvent(input$titleId, {
js$collapse("box1")
})
observeEvent(input$titleBtId, {
js$collapse("box2")
})
observeEvent(input$titleboxId, {
js$collapse("box3")
})
}
shinyApp(
ui = dashboardPage(
dashboardHeader(),
dashboardSidebar(),
body
),
server = server
)
}
You can do this for all boxes in an app with a few lines of external css and javascript.
The JS triggers a click on the widget when you click on the header title. It has to be the h3 element because the widget is inside .box-header, which would cause infinite recursion.
$('.box').on('click', '.box-header h3', function() {
$(this).closest('.box')
.find('[data-widget=collapse]')
.click();
});
But then we need to make the h3 element fill the full .box-header, so get rid of the header padding (except on the right), add it to the h3, and make the h3 fill 100% of the width of the box.
.box-header {
padding: 0 10px 0 0;
}
.box-header h3 {
width: 100%;
padding: 10px;
}
I think Lisa DeBruine answer is the better one since you can click the whole header and not just the title.
Pasted it into a small example:
if (interactive()) {
body <- dashboardBody(
useShinyjs(),
tags$style(HTML("
.box-header {
padding: 0 10px 0 0;
}
.box-header h3 {
width: 100%;
padding: 10px;
}")),
fluidRow(
box(id="box1", title = "Histogram box title",
status = "warning", solidHeader = TRUE, collapsible = T,
plotOutput("plot", height = 250)
)
)
)
server <- function(input, output) {
output$plot <- renderPlot({
hist(rnorm(50))
})
runjs("
$('.box').on('click', '.box-header h3', function() {
$(this).closest('.box')
.find('[data-widget=collapse]')
.click();
});")
}
shinyApp(
ui = dashboardPage(
dashboardHeader(),
dashboardSidebar(),
body
),
server = server
)
}

Resources