I am new to the R language. I can't figure out a solution to the problem I am currently facing. I have made a registration page for users. Whenever the user clicks the "submit" button it checks whether the specific conditions are met. If no, then an error message is displayed. Now the problem is that the error message is repeated continuously until the user enters the correct information. It also repeats each time the user clicks the button.
I want the error message to be displayed only once regardless of how many times the user clicks the "submit" button. Also, the error should not repeat when the user is filling the text fields. This might be a stupid question but I would really appreciate some help. I am sharing my code for a better understanding of the problem.
ui <- fluidPage(
tags$style(
type = "text/css",
#".shiny-output-error",
" .has-error{color: #B31B1B;}"
),
#User Account
div(id ="account", actionBttn("OPEN"," Register",
color = "success", style = "gradient", icon = icon("user"))),
)
# Define server logic
server <- function(input, output) {
#User Account
#User-Registration Button
observeEvent(input$OPEN,{
showModal(modalDialog( id = "form",
h3(strong("User Sign-Up Portal"), align = "center"),
br(),
textInput("Username", "Enter Username:", value = "", placeholder = "Username"),
textInput("Email", "Enter Email:", value = "", placeholder = "Email"),
passwordInput("Password", "Enter Password:", value = "", placeholder = "Password"),
passwordInput("rePassword", "Retype Password:", value = "", placeholder = "Retype Password"),
easyClose = TRUE,
footer=tagList(
p("Already have an account ? Click to Sign In"),actionButton('signin', 'Sign-In'),
div(style = "margin-right: 300px", actionButton('submit', 'Submit'), actionButton("refresh", "Refresh"),
modalButton('cancel'))
)
)
)
}
)
observeEvent(input$submit,{
urname <- input$Username
uemail <- input$Email
upass <- input$Password
urepass <- input$rePassword
iv <- InputValidator$new()
result = fn$dbGetQuery(con, "Select Username from register where Username = '$urname'")
iv$add_rule("Username", sv_required())
iv$add_rule("Username", ~ if (!isValidFormat(.)) "The username must contain Atleast: 8 characters \n One Upper Case Letter \n One Lower case Character \n One special Character")
iv$add_rule("Username", function(un){
if (count(result) != 0){
"Username already exists. Please enter a unique Username!"
}
})
iv$add_rule("Username", function(unl){
if (str_length(unl) >= 21){
"The Username cannot exceed 20 characters!"
}
})
result1 = fn$dbGetQuery(con, "Select Email from register where Email = '$uemail'")
iv$add_rule("Email", sv_required())
iv$add_rule("Email", ~ if (!isValidEmail(.)) "Not a valid Emai!l")
iv$add_rule("Email", function(ue){
if (count(result1) != 0){
"Email already exists. Please enter a unique Email!"
}
})
iv$add_rule("Password", sv_required())
iv$add_rule("Password", ~ if (!isValidFormat(.)) "The password must contain Atleast: 8 characters \n One Upper Case Letter \n One Lower case Character \n One special Character")
iv$add_rule("Password", function(pass){
if (str_length(pass) <= 7){
"The password should have a minimum of 8 characters!"
}
})
iv$add_rule("Password", function(pass){
if (str_length(pass) >= 13){
"The password should have a maximum of 12 characters!"
}
})
iv$add_rule("rePassword", sv_required())
iv$add_rule("rePassword", function(repass) {
if (repass != upass) {
"Your password and retype password do not match!"
}
})
iv$enable()
req(iv$is_valid())
})
I did not follow your example because it is not reproducible.
To make and event occure only once, or twice, or more, you can initialize a counter and stop the event when the counter is reached.
Here I want an alert to appear if the user submits a number >=5. Whenever the button is clicked, I increase the counter by one. The alert needs the counter to be 0 or it won't appear.
The counter is initialize at 0, so it appears once, and then it won't appear again.
library(shiny)
library(shinyWidgets)
counter <- 0 #init counter
ui <- fluidPage(
useSweetAlert(),
actionButton(
inputId = "register",
label = "register"
)
)
# Define server logic
server <- function(input, output, session) {
rv <- reactiveValues(count=0)
observeEvent(input$register, {
showModal(
modalDialog(
id = "form",
textInput("input1", "Enter a number < 5", value = ""),
actionButton(
inputId = "submit",
label = "Submit"
)
)
)
})
observeEvent(input$submit,{
req(rv$count == 0)
rv$count <- rv$count+1
if(as.numeric(input$input1)>=5){
sendSweetAlert(
session = session,
title = "Error...",
text = "The number you ented is not < 5",
type = "error"
)
}
})
}
shinyApp(ui,server)
Related
I want to put the focus and edit the first cell of my dynamic table when the user clicks a button.
the problem is that the id of the table tag is dynamic. actually, the name I put in dtoutput is a div tag, which contains neither cell nor row to position with javascrpt.
The problem is that the identification of the html tag of the table is dynamic. Actually, the name that I put in dtoutput is a div tag, and therefore its javascrpt object does not contain a cell or a row to position.
I have tried to position myself in different ways:
# tablet_list_var_dtf.cell (': eq (0)'). node (). focus ();
# tablet_list_var_dtf.cell (': eq (1)', ': eq (0)') .focus ();
# tablet_list_var_dtf.cell (': eq (' + scrollStart + ')', ': eq (0)') .focus ();
but as I say, really 'tablet_list_var_dtf' is an HTMLDivElement object and therefore it does not have node, cell, row etc ... also I cannot directly use object.focus (), it does not work.
Not only do I want to put the focus, but I want to edit the first cell, force a doubleclick event on said cell ..
I put a summary and executable code of the problem
enter code here
library(shiny)
library(DT)
library(shinyjs)
library(shinyFeedback)
# JS refocus function
jscode <- "
shinyjs.refocus = function(e_id ) {
alert(e_id);
alert(eval(tablet_list_var_dtf));
tablet_list_var_dtf.datatable.row().focus();
var scrollStart = tablet_list_var_dtf.scroller.page().start;
alert('ppp:'+scrollStart);
}"
#tablet_list_var_dtf.cell(':eq(0)').node().focus();
#tablet_list_var_dtf.cell( ':eq(1)', ':eq(0)' ).focus();
#tablet_list_var_dtf.cell( ':eq(' + scrollStart + ')', ':eq(0)' ).focus();
#table.cell(':eq(0)').focus()
#shinyjs.refocus = function(e_id) {
#document.getElementById(e_id).focus();
ui <- fluidPage(
useShinyjs(),
extendShinyjs(text = jscode, functions = c("refocus") ),
# activate shiny feedback
box(wclass = "map",
width = 12,
style = 'padding:0px;',
title = "List of DTF",
uiOutput( ("list_var_dtf"))
) ,
actionButton( ('edit_name_var_dtf'),'edit name var description'),
)
server <- function(input, output, session){
observeEvent(input$edit_name_var_dtf, {
print("edit_name_var_dtf")
js$refocus("tablet_list_var_dtf")
print('js$refocus(table)')
})
output$list_var_dtf <- renderUI({
DTOutput(("tablet_list_var_dtf"))
})
output$tablet_list_var_dtf <- renderDT(
datatable( data = mtcars,
rownames = FALSE,
options = list(
orderClasses = TRUE,
order = list(1, "desc"),
scrollX = TRUE,
scrollY = "37vh",
searchHighlight = TRUE,
scrollCollapse = T,
dom = 'ft',
paging = FALSE,
#callback = JS(jscall),
initComplete = JS("function(settings, json) {",
"$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});",
"}")
),
selection = "none" , editable = list(target = "column", disable = list(columns = c(1))))
)
}
shinyApp(ui, server)
This is the js code correct:
jscode <- " shinyjs.refocus = function(e_id){
var table = $('#DataTables_Table_0').DataTable();
var td = table.cell(':eq(0)', ':eq(0)').node();
$(td).attr('tabindex', 0); $(td).dblclick( );
}"
The problem is looking for the 'DataTables_Table_(XXX)' selector in a pivot table in shiny. So the real problem is finding the right selector for the table.
If our component id is 'table_list_var_dtf'
DTOutput('table_list_var_dtf')
you should know that this id is not really the id of the table. But the id of the div that contains the pivot table. Specifically, the table that is created dynamically starts with the name DataTables_Table_ (xxxxxx) . Where (xxxxxx) is the number of tables that have been created dynamically.
Thus, if there are only two tables on the page, the id to look for is: DataTables_Table_ 02
thankssss. jogugil...
With the Shiny selectizeInput widget, the user can type in text as well as select a value from a list of values. Is there a way in R to read the current value of the text?
(Added)
I should make it clear that I want to be able to read the text the user enters before he has made a selection. As zimia points out, after he has made a selection, the value of whatever he selected becomes available as input$input_id (assuming that the selectize input has the id "input_id").
you can just use the input$input_id. See below
ui <- fluidRow(
selectizeInput("input1","Enter Text",choices=c("A","B") ,options = list(create=TRUE)),
textOutput("output1")
)
server<- function(input, output, session){
output$output1 <- renderText({
req(input$input1)
input$input1
})
}
Shiny's selectizeInput still gives access to the internal properties, methods and callbacks of Selectize.js through "options" argument of updateSelectizeInput. Selectize.js exposes callback "onType", so you can use like that:
updateSelectizeInput(
session,
'input1',
options = list(
onType = I('
text => Shiny.setInputValue("input1_searchText", text)
'),
onBlur = I('
() => Shiny.setInputValue("input1_searchText", null)
')
)
)
and consume it with observer:
observeEvent(input$input1_searchText, {
print(input$input1_searchText)
}, ignoreNULL = FALSE
)
Please, note, that I was also interested to know when the select looses focus and hence used "onBlur" event to set the search text to NULL.
I was thinking that there would be a solution at the level of R/shiny. But I have found a solution that uses javascript.
library(shiny)
js <- '
$(document).on("keyup", function(e) {
minChars = 4;
tag1 = document.activeElement.getAttribute("id");
val1 = document.activeElement.value;
if (tag1 == "input1-selectized") {
if (Math.sign(val1.length +1 - minChars) == 1) {
obj = { "val": val1 };
Shiny.onInputChange("valueEntered", obj);
}
}
});
'
ui <- fluidRow(
tags$script(js),
selectizeInput(
"input1",
"Enter text",
choices = c("A", "B"),
options = list(create = FALSE)),
textOutput("output1")
)
server <- function(input, output, session) {
output$output1 <- renderText({
req(input$valueEntered$val)
input$valueEntered$val
})
}
shinyApp(ui = ui, server = server)
The javascript looks for text entered into the element with id "input1-selectized", and if the value is length 4 or more, sets the shiny variable "valueEntered" to an object with val = the text.
Then the observeEvent uses the shiny variable input$valueEntered to set the output text.
The reason in the javascript for using the Math.sign function rather than >, and the reason for nested if's is because for some reason, Shiny replaces infix operators such as > and && by their html equivalents, > and &&.
Note that if the selectizeInput widget has id "input1", then the corresponding text field has id "input1-selectized".
Using Shiny App and R, I want to build a dashboard where only the authenticated users can use. The structure of the app is:
Simple login page with user name box and password box, where users put user name and password
Dashboard page where only the users who are authenticated on login page can access
I looked through several examples such as:
https://github.com/treysp/shiny_password
https://github.com/aoles/shinypass
https://gist.github.com/withr/9001831
but here I want to address the problem when following the first example.
The problems I have:
When I put dashboardPage() inside output$ui <- renderUI({ }) it did not work. So I removed renderUI and assigned dashboardPage function directly to output$ui, like output$ui <- dashboardPage(). But unfortunately it still returns this:
Error in tag("section", list(...)) : objet 'user_input_authenticated' introuvable. (it's in french but it's saying that it cannot find the object).
Here are my ui.R and server.R. Other than these, you need to clone admin.R and global.R from the repository(https://github.com/treysp/shiny_password).
To create a password, please run credentials_init() and then add_users("USER NAME", "PASSWORD") with your desired user name and password. Both functions are defined in admin.R. Once you create a password, it's stored in credentials/credentials.rds and now you can use the app.
What I want to make is a simple dashboard with authentication. If anyone help me solve this it would be great. Also if there is any other solutions than these examples, please tell me. Thanks.
ui.R(same as the original one in the Github repository)
shinyUI(
uiOutput("ui")
)
server.R(modified for my custom use)
shinyServer(function(input, output, session) {
#### UI code --------------------------------------------------------------
output$ui <- dashboardPage(dashboardHeader(title = "My Page"),
dashboardSidebar(
if (user_input$authenticated == FALSE) {
NULL
} else {
sidebarMenuOutput("sideBar_menu_UI")
}
),
dashboardBody(
if (user_input$authenticated == FALSE) {
##### UI code for login page
uiOutput("uiLogin")
uiOutput("pass")
} else {
#### Your app's UI code goes here!
uiOutput("obs")
plotOutput("distPlot")
}
))
#### YOUR APP'S SERVER CODE GOES HERE ----------------------------------------
# slider input widget
output$obs <- renderUI({
sliderInput("obs", "Number of observations:",
min = 1, max = 1000, value = 500)
})
# render histogram once slider input value exists
output$distPlot <- renderPlot({
req(input$obs)
hist(rnorm(input$obs), main = "")
})
output$sideBar_menu_UI <- renderMenu({
sidebarMenu(id = "sideBar_Menu",
menuItem("Menu 1", tabName="menu1_tab", icon = icon("calendar")),
menuItem("Menu 2", tabName="menu2_tab", icon = icon("database"))
)
})
#### PASSWORD server code ----------------------------------------------------
# reactive value containing user's authentication status
# user_input <- reactiveValues(authenticated = FALSE, valid_credentials = FALSE,
# user_locked_out = FALSE, status = "")
# authenticate user by:
# 1. checking whether their user name and password are in the credentials
# data frame and on the same row (credentials are valid)
# 2. if credentials are valid, retrieve their lockout status from the data frame
# 3. if user has failed login too many times and is not currently locked out,
# change locked out status to TRUE in credentials DF and save DF to file
# 4. if user is not authenticated, determine whether the user name or the password
# is bad (username precedent over pw) or he is locked out. set status value for
# error message code below
observeEvent(input$login_button, {
credentials <- readRDS("credentials/credentials.rds")
row_username <- which(credentials$user == input$user_name)
row_password <- which(credentials$pw == digest(input$password)) # digest() makes md5 hash of password
# if user name row and password name row are same, credentials are valid
# and retrieve locked out status
if (length(row_username) == 1 &&
length(row_password) >= 1 && # more than one user may have same pw
(row_username %in% row_password)) {
user_input$valid_credentials <- TRUE
user_input$user_locked_out <- credentials$locked_out[row_username]
}
# if user is not currently locked out but has now failed login too many times:
# 1. set current lockout status to TRUE
# 2. if username is present in credentials DF, set locked out status in
# credentials DF to TRUE and save DF
if (input$login_button == num_fails_to_lockout &
user_input$user_locked_out == FALSE) {
user_input$user_locked_out <- TRUE
if (length(row_username) == 1) {
credentials$locked_out[row_username] <- TRUE
saveRDS(credentials, "credentials/credentials.rds")
}
}
# if a user has valid credentials and is not locked out, he is authenticated
if (user_input$valid_credentials == TRUE & user_input$user_locked_out == FALSE) {
user_input$authenticated <- TRUE
} else {
user_input$authenticated <- FALSE
}
# if user is not authenticated, set login status variable for error messages below
if (user_input$authenticated == FALSE) {
if (user_input$user_locked_out == TRUE) {
user_input$status <- "locked_out"
} else if (length(row_username) > 1) {
user_input$status <- "credentials_data_error"
} else if (input$user_name == "" || length(row_username) == 0) {
user_input$status <- "bad_user"
} else if (input$password == "" || length(row_password) == 0) {
user_input$status <- "bad_password"
}
}
})
# password entry UI componenets:
# username and password text fields, login button
output$uiLogin <- renderUI({
wellPanel(
textInput("user_name", "User Name:"),
passwordInput("password", "Password:"),
actionButton("login_button", "Log in")
)
})
# red error message if bad credentials
output$pass <- renderUI({
if (user_input$status == "locked_out") {
h5(strong(paste0("Your account is locked because of too many\n",
"failed login attempts. Contact administrator."), style = "color:red"), align = "center")
} else if (user_input$status == "credentials_data_error") {
h5(strong("Credentials data error - contact administrator!", style = "color:red"), align = "center")
} else if (user_input$status == "bad_user") {
h5(strong("User name not found!", style = "color:red"), align = "center")
} else if (user_input$status == "bad_password") {
h5(strong("Incorrect password!", style = "color:red"), align = "center")
} else {
""
}
})
})
A kind githubber #skhan8 just submitted a pull request demonstrating how to use shiny_password in a shinydashboard. It will be incorporated into the main repo soon.
I would like to create dynamic tabs, where each time the user clicks a button, a new tab would be created. Each tab has the same content, with a variety of widgets that the user can use to select which sets of data to be plotted.
Currently, I am using the solution here to dynamically create my tabs, but with the change that lapply is calling a function that calls tabPanel and adds content to the tabs
`
renderUI({
some_data <- # Dataframe that data is extracted goes here
createTabs <- function(tabNum, some_data)
{
tabPanel(title = paste("Map", tabNum, sep=" "),
fluidRow(
column(
width = 3,
wellPanel(
#widgets are added here
}
mTabs <- lapply(0:input$map, createTabs, some_data)
do.call(tabsetPanel, mTabs)
})
`
And the methods of for loops posted here to create the plots on each tab.
However, it seems like instead of creating a new tab, the 2 solutions above both re-create all the existing tabs. So if there are currently 10 tabs open, all 10 tabs get re-created. Unfortunately, this also resets all the user settings on each tab (in addition to slowing down the app), and extra provisions must be taken as shown here , which further slows down the app because of the large number of input objects that must be created.
I saw a solution for menu items that seems to solve this problem by simply storing all the menu items in a list, and each time a new menu item is generated, it is simply added to the list so that all the other existing items don't need to be created. Is something like this possible for tabs and rendering plots as well?
This is the code:
newTabs <- renderMenu({
menu_list <- list(
menu_vals$menu_list)
sidebarMenu(.list = menu_list)
})
menu_vals = reactiveValues(menu_list = NULL)
observeEvent(eventExpr = input$placeholder,
handlerExpr = {
menu_vals$menu_list[[input$placeholder]] <- menuSubItem(paste("Saved Simulation", length(menu_vals$menu_list) + 1, sep = " "),
tabName = paste("saved_sim", length(menu_vals$menu_list) + 1))
})
If someone can explain to me what menu_list <- list(menu_vals$menu_list) is doing , why Rstudio says it must be inside a reactive expression, and why a new list called menu_vals is created with menu_list = null, it would be greatly appreciated as well :)
Edit: I think I was able to prevent the plots from being re-created each time a new tab is created and also bypass the need for a max number of plots using
observeEvent(eventExpr = input$map,
handlerExpr = {
output[[paste0("outputComparePlot",simNum,"-",input$map)]] <- outputComparePlot(sessionEnv, config, react, input, simNum, input$map) #This function contains the call to renderPlot
})
However, I still cannot figure out how to use this for creating tabs. I tried the same method but it didnt work.
I would like to present a solution that adds a feature to shiny which should have been implemented into shiny base long ago. A function to append tabPanels to existing tabsetPanels. I already tried similar stuff here and here, but this time, I feel like this solution is way more stable and versatile.
For this feature, you need to insert 4 parts of code into your shiny app. Then you can add any set of tabPanels each having any content to an existing tabsetPanel by calling addTabToTabset. Its arguments are a tabPanel (or a list of tabPanels) and the name (id) of your target tabsetPanel. It even works for navbarPage, if you just want to add normal tabPanels.
The code which should be copy-pasted, is inside the "Important!" comments.
My comments will probably not be enough to grasp what's really happening (and why, of course). So if you want to get more into detail, please leave a message and I will try to elaborate.
Copy-Paste-Run-Play!
library(shiny)
ui <- shinyUI(fluidPage(
# Important! : JavaScript functionality to add the Tabs
tags$head(tags$script(HTML("
/* In coherence with the original Shiny way, tab names are created with random numbers.
To avoid duplicate IDs, we collect all generated IDs. */
var hrefCollection = [];
Shiny.addCustomMessageHandler('addTabToTabset', function(message){
var hrefCodes = [];
/* Getting the right tabsetPanel */
var tabsetTarget = document.getElementById(message.tabsetName);
/* Iterating through all Panel elements */
for(var i = 0; i < message.titles.length; i++){
/* Creating 6-digit tab ID and check, whether it was already assigned. */
do {
hrefCodes[i] = Math.floor(Math.random()*100000);
}
while(hrefCollection.indexOf(hrefCodes[i]) != -1);
hrefCollection = hrefCollection.concat(hrefCodes[i]);
/* Creating node in the navigation bar */
var navNode = document.createElement('li');
var linkNode = document.createElement('a');
linkNode.appendChild(document.createTextNode(message.titles[i]));
linkNode.setAttribute('data-toggle', 'tab');
linkNode.setAttribute('data-value', message.titles[i]);
linkNode.setAttribute('href', '#tab-' + hrefCodes[i]);
navNode.appendChild(linkNode);
tabsetTarget.appendChild(navNode);
};
/* Move the tabs content to where they are normally stored. Using timeout, because
it can take some 20-50 millis until the elements are created. */
setTimeout(function(){
var creationPool = document.getElementById('creationPool').childNodes;
var tabContainerTarget = document.getElementsByClassName('tab-content')[0];
/* Again iterate through all Panels. */
for(var i = 0; i < creationPool.length; i++){
var tabContent = creationPool[i];
tabContent.setAttribute('id', 'tab-' + hrefCodes[i]);
tabContainerTarget.appendChild(tabContent);
};
}, 100);
});
"))),
# End Important
tabsetPanel(id = "mainTabset",
tabPanel("InitialPanel1", "Some Text here to show this is InitialPanel1",
actionButton("goCreate", "Go create a new Tab!"),
textOutput("creationInfo")
),
tabPanel("InitialPanel2", "Some Text here to show this is InitialPanel2 and not some other Panel")
),
# Important! : 'Freshly baked' tabs first enter here.
uiOutput("creationPool", style = "display: none;")
# End Important
))
server <- function(input, output, session){
# Important! : creationPool should be hidden to avoid elements flashing before they are moved.
# But hidden elements are ignored by shiny, unless this option below is set.
output$creationPool <- renderUI({})
outputOptions(output, "creationPool", suspendWhenHidden = FALSE)
# End Important
# Important! : This is the make-easy wrapper for adding new tabPanels.
addTabToTabset <- function(Panels, tabsetName){
titles <- lapply(Panels, function(Panel){return(Panel$attribs$title)})
Panels <- lapply(Panels, function(Panel){Panel$attribs$title <- NULL; return(Panel)})
output$creationPool <- renderUI({Panels})
session$sendCustomMessage(type = "addTabToTabset", message = list(titles = titles, tabsetName = tabsetName))
}
# End Important
# From here: Just for demonstration
output$creationInfo <- renderText({
paste0("The next tab will be named NewTab", input$goCreate + 1)
})
observeEvent(input$goCreate, {
nr <- input$goCreate
newTabPanels <- list(
tabPanel(paste0("NewTab", nr),
actionButton(paste0("Button", nr), "Some new button!"),
textOutput(paste0("Text", nr))
),
tabPanel(paste0("AlsoNewTab", nr), sliderInput(paste0("Slider", nr), label = NULL, min = 0, max = 1, value = 1))
)
output[[paste0("Text", nr)]] <- renderText({
if(input[[paste0("Button", nr)]] == 0){
"Try pushing this button!"
} else {
paste("Button number", nr , "works!")
}
})
addTabToTabset(newTabPanels, "mainTabset")
})
}
shinyApp(ui, server)
Probably thanks to #k-rohde, there's now natively available in Shiny a set of methods to add/remove/append tabs in a tabset:
library(shiny)
runApp(list(
ui=fluidPage(
fluidRow(
actionLink("newTab", "Append tab"),
actionLink("removeTab", "Remove current tab")
),
tabsetPanel(id="myTabs", type="pills")
),
server=function(input, output, session){
tabIndex <- reactiveVal(0)
observeEvent(input$newTab, {
tabIndex(tabIndex() + 1)
appendTab("myTabs", tabPanel(tabIndex(), tags$p(paste("I'm tab", tabIndex()))), select=TRUE)
})
observeEvent(input$removeTab, {
removeTab("myTabs", target=input$myTabs)
})
}
))
I would like to have a shiny website that keeps the dynamic choices in the URL as output, so you can copy and share the URL.
I took this code as an example:
https://gist.github.com/amackey/6841cf03e54d021175f0
And modified it to my case, which is a webpage with a navbarPage and multiple tabs per element in the bar.
What I would like is the URL to direct the user to the right element
in the first level tabPanel, and the right tab in the second level
tabPanel.
This is, if the user has navigated to "Delta Foxtrot" and then to
"Hotel", then changed the parameters to
#beverage=Tea;milk=TRUE;sugarLumps=3;customer=mycustomer, I would
like the URL to send the user to "Delta Foxtrot" -> "Hotel", instead
of starting at the first tab of the first panel element.
Ideally I would like a working example, since everything I tried so far hasn't worked.
Any ideas?
# ui.R
library(shiny)
hashProxy <- function(inputoutputID) {
div(id=inputoutputID,class=inputoutputID,tag("div",""));
}
# Define UI for shiny d3 chatter application
shinyUI(navbarPage('URLtests', id="page", collapsable=TRUE, inverse=FALSE,
tabPanel("Alfa Bravo",
tabsetPanel(
tabPanel("Charlie",
tags$p("Nothing to see here. Everything is in the 'Delta Foxtrot' 'Hotel' tab")
)
)
)
,tabPanel("Delta Foxtrot",
tabsetPanel(
tabPanel("Golf",
tags$p("Nothing to see here. Everything is in the 'Delta Foxtrot' 'Hotel' tab")
)
,tabPanel("Hotel",
tags$p("This widget is a demonstration of how to preserve input state across sessions, using the URL hash."),
selectInput("beverage", "Choose a beverage:",
choices = c("Tea", "Coffee", "Cocoa")),
checkboxInput("milk", "Milk"),
sliderInput("sugarLumps", "Sugar Lumps:",
min=0, max=10, value=3),
textInput("customer", "Your Name:"),
includeHTML("URL.js"),
h3(textOutput("order")),
hashProxy("hash")
)
)
)
))
# server.R
library(shiny)
url_fields_to_sync <- c("beverage","milk","sugarLumps","customer");
# Define server logic required to respond to d3 requests
shinyServer(function(input, output, clientData) {
# Generate a plot of the requested variable against mpg and only
# include outliers if requested
output$order <- reactiveText(function() {
paste(input$beverage,
if(input$milk) "with milk" else ", black",
"and",
if (input$sugarLumps == 0) "no" else input$sugarLumps,
"sugar lumps",
"for",
if (input$customer == "") "next customer" else input$customer)
})
firstTime <- TRUE
output$hash <- reactiveText(function() {
newHash = paste(collapse=";",
Map(function(field) {
paste(sep="=",
field,
input[[field]])
},
url_fields_to_sync))
# the VERY FIRST time we pass the input hash up.
return(
if (!firstTime) {
newHash
} else {
if (is.null(input$hash)) {
NULL
} else {
firstTime<<-F;
isolate(input$hash)
}
}
)
})
})
# URL.js
<script type="text/javascript">
(function(){
this.countValue=0;
var changeInputsFromHash = function(newHash) {
// get hash OUTPUT
var hashVal = $(newHash).data().shinyInputBinding.getValue($(newHash))
if (hashVal == "") return
// get values encoded in hash
var keyVals = hashVal.substring(1).split(";").map(function(x){return x.split("=")})
// find input bindings corresponding to them
keyVals.map(function(x) {
var el=$("#"+x[0])
if (el.length > 0 && el.val() != x[1]) {
console.log("Attempting to update input " + x[0] + " with value " + x[1]);
if (el.attr("type") == "checkbox") {
el.prop('checked',x[1]=="TRUE")
el.change()
} else if(el.attr("type") == "radio") {
console.log("I don't know how to update radios")
} else if(el.attr("type") == "slider") {
// This case should be setValue but it's not implemented in shiny
el.slider("value",x[1])
//el.change()
} else {
el.data().shinyInputBinding.setValue(el[0],x[1])
el.change()
}
}
})
}
var HashOutputBinding = new Shiny.OutputBinding();
$.extend(HashOutputBinding, {
find: function(scope) {
return $(scope).find(".hash");
},
renderError: function(el,error) {
console.log("Shiny app failed to calculate new hash");
},
renderValue: function(el,data) {
console.log("Updated hash");
document.location.hash=data;
changeInputsFromHash(el);
}
});
Shiny.outputBindings.register(HashOutputBinding);
var HashInputBinding = new Shiny.InputBinding();
$.extend(HashInputBinding, {
find: function(scope) {
return $(scope).find(".hash");
},
getValue: function(el) {
return document.location.hash;
},
subscribe: function(el, callback) {
window.addEventListener("hashchange",
function(e) {
changeInputsFromHash(el);
callback();
}
, false);
}
});
Shiny.inputBindings.register(HashInputBinding);
})()
</script>
EDITED: I ran the example code in the answer, but couldn't get it to work. See screenshot.
UPDATE
Shiny .14 now available on CRAN supports saving app state in a URL. See this article
This answer is a more in-depth answer than my first that uses the entire sample code provided by OP. I've decided to add it as a new answer in light of the bounty. My original answer used a simplified version of this so that someone else coming to the answer wouldn't have to read through any extraneous code to find what they're looking for. Hopefully, this extended version will clear up any difficulties you're having. Parts I've added to your R code are surrounded with ### ... ###.
server.r
# server.R
library(shiny)
url_fields_to_sync <- c("beverage","milk","sugarLumps","customer");
# Define server logic required to respond to d3 requests
shinyServer(function(input, output, session) { # session is the common name for this variable, not clientData
# Generate a plot of the requested variable against mpg and only
# include outliers if requested
output$order <- reactiveText(function() {
paste(input$beverage,
if(input$milk) "with milk" else ", black",
"and",
if (input$sugarLumps == 0) "no" else input$sugarLumps,
"sugar lumps",
"for",
if (input$customer == "") "next customer" else input$customer)
})
firstTime <- TRUE
output$hash <- reactiveText(function() {
newHash = paste(collapse=";",
Map(function(field) {
paste(sep="=",
field,
input[[field]])
},
url_fields_to_sync))
# the VERY FIRST time we pass the input hash up.
return(
if (!firstTime) {
newHash
} else {
if (is.null(input$hash)) {
NULL
} else {
firstTime<<-F;
isolate(input$hash)
}
}
)
})
###
# whenever your input values change, including the navbar and tabpanels, send
# a message to the client to update the URL with the input variables.
# setURL is defined in url_handler.js
observe({
reactlist <- reactiveValuesToList(input)
reactvals <- grep("^ss-|^shiny-", names(reactlist), value=TRUE, invert=TRUE) # strip shiny related URL parameters
reactstr <- lapply(reactlist[reactvals], as.character) # handle conversion of special data types
session$sendCustomMessage(type='setURL', reactstr)
})
observe({ # this observer executes once, when the page loads
# data is a list when an entry for each variable specified
# in the URL. We'll assume the possibility of the following
# variables, which may or may not be present:
# nav= The navbar tab desired (either Alfa Bravo or Delta Foxtrot)
# tab= The desired tab within the specified nav bar tab, e.g., Golf or Hotel
# beverage= The desired beverage selection
# sugar= The desired number of sugar lumps
#
# If any of these variables aren't specified, they won't be used, and
# the tabs and inputs will remain at their default value.
data <- parseQueryString(session$clientData$url_search)
# the navbar tab and tabpanel variables are two variables
# we have to pass to the client for the update to take place
# if nav is defined, send a message to the client to set the nav tab
if (! is.null(data$page)) {
session$sendCustomMessage(type='setNavbar', data)
}
# if the tab variable is defined, send a message to client to update the tab
if (any(sapply(data[c('alfa_bravo_tabs', 'delta_foxtrot_tabs')], Negate(is.null)))) {
session$sendCustomMessage(type='setTab', data)
}
# the rest of the variables can be set with shiny's update* methods
if (! is.null(data$beverage)) { # if a variable isn't specified, it will be NULL
updateSelectInput(session, 'beverage', selected=data$beverage)
}
if (! is.null(data$sugarLumps)) {
sugar <- as.numeric(data$sugarLumps) # variables come in as character, update to numeric
updateNumericInput(session, 'sugarLumps', value=sugar)
}
})
###
})
ui.r
library(shiny)
hashProxy <- function(inputoutputID) {
div(id=inputoutputID,class=inputoutputID,tag("div",""));
}
# Define UI for shiny d3 chatter application
shinyUI(navbarPage('URLtests', id="page", collapsable=TRUE, inverse=FALSE,
tabPanel("Alfa Bravo",
tabsetPanel(
###
id='alfa_bravo_tabs', # you need to set an ID for your tabpanels
###
tabPanel("Charlie",
tags$p("Nothing to see here. Everything is in the 'Delta Foxtrot' 'Hotel' tab")
)
)
)
,tabPanel("Delta Foxtrot",
tabsetPanel(
###
id='delta_foxtrot_tabs', # you need to set an ID for your tabpanels
###
tabPanel("Golf",
tags$p("Nothing to see here. Everything is in the 'Delta Foxtrot' 'Hotel' tab")
)
,tabPanel("Hotel", id='hotel',
tags$p("This widget is a demonstration of how to preserve input state across sessions, using the URL hash."),
selectInput("beverage", "Choose a beverage:",
choices = c("Tea", "Coffee", "Cocoa")),
checkboxInput("milk", "Milk"),
sliderInput("sugarLumps", "Sugar Lumps:",
min=0, max=10, value=3),
textInput("customer", "Your Name:"),
#includeHTML("URL.js"),
###
includeHTML('url_handler.js'), # include the new script
###
h3(textOutput("order")),
hashProxy("hash")
)
)
)
))
url_handler.js
<script>
Shiny.addCustomMessageHandler('setNavbar',
function(data) {
// create a reference to the desired navbar tab. page is the
// id of the navbarPage. a:contains says look for
// the subelement that contains the contents of data.nav
var nav_ref = '#page a:contains(\"' + data.page + '\")';
$(nav_ref).tab('show');
}
)
Shiny.addCustomMessageHandler('setTab',
function(data) {
// pick the right tabpanel ID based on the value of data.nav
if (data.page == 'Alfa Bravo') {
var tabpanel_id = 'alfa_bravo_tabs';
} else {
var tabpanel_id = 'delta_foxtrot_tabs';
}
// combine this with a reference to the desired tab itself.
var tab_ref = '#' + tabpanel_id + ' a:contains(\"' + data[tabpanel_id] + '\")';
$(tab_ref).tab('show');
}
)
Shiny.addCustomMessageHandler('setURL',
function(data) {
// make each key and value URL safe (replacing spaces, etc.), then join
// them and put them in the URL
var search_terms = [];
for (var key in data) {
search_terms.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
window.history.pushState('object or string', 'Title', '/?' + search_terms.join('&'));
}
);
</script>
To test this, call runApp(port=5678) in the directory with your source files. By default, no parameters are specified in the URL, so this will default to the first navbar item and the first tab within that item. To test it with URL parameters, point your browser to: http://127.0.0.1:5678/?nav=Delta%20Foxtrot&tab=Hotel&beverage=Coffee. This should point you to the second navbar tab and the second tab in that navbar item with coffee as the selected beverage.
Here's an example demonstrating how to update the navbar selection, tabset selection, and widget selection using variables defined in the URL
ui <- navbarPage('TEST', id='page', collapsable=TRUE, inverse=FALSE,
# define a message handler that will receive the variables on the client side
# from the server and update the page accordingly.
tags$head(tags$script("
Shiny.addCustomMessageHandler('updateSelections',
function(data) {
var nav_ref = '#page a:contains(\"' + data.nav + '\")';
var tabpanel_id = data.nav == 'Alpha' ? '#alpha_tabs' : '#beta_tabs';
var tab_ref = tabpanel_id + ' a:contains(\"' + data.tab + '\")';
$(nav_ref).tab('show');
$(tab_ref).tab('show');
}
)
")),
tabPanel('Alpha',
tabsetPanel(id='alpha_tabs',
tabPanel('Tab')
)
),
tabPanel('Beta',
tabsetPanel(id='beta_tabs',
tabPanel('Golf'),
tabPanel('Hotel',
selectInput("beverage", "Choose a beverage:", choices = c("Tea", "Coffee", "Cocoa"))
)
)
)
)
server <- function(input, output, session) {
observe({
data <- parseQueryString(session$clientData$url_search)
session$sendCustomMessage(type='updateSelections', data)
updateSelectInput(session, 'beverage', selected=data$beverage)
})
}
runApp(list(ui=ui, server=server), port=5678, launch.browser=FALSE)
Point your browser to this URL after starting the app: http://127.0.0.1:5678/?nav=Beta&tab=Hotel&beverage=Coffee