Developers often wants to show their code in a shiny app. This function creates a button that when clicked, a modal or collapse hidden element will show up to display your code.
element ID
code you want to display, in a character string or vector.
string, what programming language is the code, use shinyAce::getAceModes()
to see options
string, label to display on the button
string, title of the modal or collapse
bool, use the <span>
tag to show a little label of the
left of the button? The span text will use text from tool_tip
string, what tooltip to display when hover on the button
string, where to display the tooltip
icon, shiny::icon()
, icon of the button
string, one of "modal", "collapse"
string, one of "large", "medium", "small", only works for modal
string, color of the button
string, shape of the button, one of "rect", "circular",
other args pass to the shiny::actionButton
a shiny tagList
The modal or collapse has an ID, the ID is your button ID + "-modal" or "-collapse", like "my_button-modal"
You could update the code inside the collapse use shinyAce::updateAceEditor on server, the code block ID is button ID + "-ace", like "my_button-ace" . See examples.
if(interactive()){
library(shiny)
my_code <-
'
# load package and data
library(ggplot2)
data(mpg, package="ggplot2")
# mpg <- read.csv("http://goo.gl/uEeRGu")
# Scatterplot
theme_set(theme_bw()) # pre-set the bw theme.
g <- ggplot(mpg, aes(cty, hwy))
g + geom_jitter(width = .5, size=1) +
labs(subtitle="mpg: city vs highway mileage",
y="hwy",
x="cty",
title="Jittered Points")
'
html_code <-
'
<!DOCTYPE html>
<html>
<body>
<h2>ABC</h2>
<p id="demo">Some HTML</p>
</body>
</html>
'
ui <- fluidPage(
fluidRow(
column(
6,
h3("Display by modal"),
column(
6, h4("default"),
spsCodeBtn(id = "a", my_code)
),
column(
6, h4("change color and shape"),
spsCodeBtn(
id = "b", c(my_code, my_code),
color = "red", shape = "circular")
)
),
column(
6,
h3("Display by collapse"),
column(
6, h4("collapse"),
spsCodeBtn(id = "c", my_code, display = "collapse")
),
column(
6, h4("different programming language"),
spsCodeBtn(
id = "d", html_code,
language = "html", display = "collapse")
)
)
),
fluidRow(
column(
6,
h3("Update code"),
spsCodeBtn(
"update-code",
"# No code here",
display = "collapse"
),
actionButton("update", "change code in the left `spsCodeBtn`"),
actionButton("changeback", "change it back")
)
)
)
server <- function(input, output, session) {
observeEvent(input$update, {
shinyAce::updateAceEditor(
session, editorId = "update-code-ace",
value = "# code has changed!\n 1+1"
)
})
observeEvent(input$changeback, {
shinyAce::updateAceEditor(
session, editorId = "update-code-ace",
value = "# No code here"
)
})
}
shinyApp(ui, server)
}