Small framework to communicate between Shiny client and server via HTTP requests.
Run communicate::example()
for a short demo.
# install.packages("remotes")
remotes::install_github("devOpifex/communicate")
Create a shiny application and "commincation channels."
Add callback functions with com
.
library(shiny)
library(communicate)
add <- \(x){
x + 2
}
ui <- fluidPage(
h1("Hello")
)
server <- \(input, output, session){
com("add", add)
}
shinyApp(ui, server)
Then use the JavaScript library to communicate.
library(shiny)
library(communicate)
add <- \(x){
x + 2
}
script <- "
$('#btn').on('click', () => {
communicate.com('add', {x: 1})
.then(res => alert(`equals: ${res}`));
})
"
ui <- fluidPage(
# import dependencies
useCommunicate(),
h1("Hello"),
tags$a("Communicate", id = "btn"),
tags$script(HTML(script))
)
server <- \(input, output, session){
com("add", add)
}
shinyApp(ui, server)
Though optional it is recommended to specify the types of the arguments of your callback function. This enables type conversion and type check when communicating from the client.
Existing types:
Character
Numeric
Integer
Date
Dataframe
Posixct
Posixlt
Character
List
Function
library(shiny)
library(communicate)
add <- \(x){
x + 2
}
script <- "
$('#btn').on('click', () => {
communicate.com('add', {x: 1})
.then(res => alert(`equals: ${res}`));
})
"
ui <- fluidPage(
# import dependencies
useCommunicate(),
h1("Hello"),
tags$a("Communicate", id = "btn"),
tags$script(HTML(script))
)
server <- \(input, output, session){
com("add", add)(x = Integer)
}
shinyApp(ui, server)
You can also specifiy callback functions' argument defaults as done below.
library(shiny)
library(communicate)
add <- \(x, y){
x + y
}
script <- "
$('#btn').on('click', () => {
communicate.com('add', {x: 1})
.then(res => alert(`equals: ${res}`));
})
"
ui <- fluidPage(
# import dependencies
useCommunicate(),
h1("Hello"),
tags$a("Communicate", id = "btn"),
tags$script(HTML(script))
)
server <- \(input, output, session){
com("add", add)(x = Integer, y = Numeric)(y = 1.1)
}
shinyApp(ui, server)
Accessible from communicate
, functions:
com
- communicate.hasCom
- check if communication channel registered.getCom
- get communication channel and its arguments.getComs
- get all communication channels registered.
You import the dependency with useCommunicate()
.
Alternatively you can install the npm package,
e.g.: if you use packer.
npm install @devopifex/communicate
Or with packer:
packer::npm_install("@devopifex/communicate")
communicate.hasCom("add")
communicate.getCom("add")
communicate.com("add", {x: 1, y: 2})
.then(data => console.log(data))
.catch(error => console.error(error))