Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[WIP] Natively Multipage Shiny Apps

License

Unknown, MIT licenses found

Licenses found

Unknown
LICENSE
MIT
LICENSE.md
NotificationsYou must be signed in to change notification settings

ColinFay/brochure

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

73 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

R build statusLifecycle: experimentalR-CMD-check

THIS IS A WORK IN PROGRESS, DO NOT USE

The goal of{brochure} is to provide a mechanism for creating nativelymulti-page{shiny} applications,i.e that can serve content onmultiple endpoints.

Disclaimer: the way you will build app with{brochure} isdifferent from the way you usually build{shiny} apps, as we no longeroperate under the single page app paradigm. Please read the “DesignPattern” of this README for more info.

Installation

You can install the dev version of{brochure} with:

remotes::install_github("ColinFay/brochure")
library(brochure)#>#> Attaching package: 'brochure'#> The following object is masked from 'package:utils':#>#>     pagelibrary(shiny)

About

You’re reading the doc about version : 0.0.0.9024

This README has been compiled on the

Sys.time()#> [1] "2023-03-27 14:00:48 CEST"

Here are the test & coverage results :

devtools::check(quiet=TRUE)#> ℹ Loading brochure#> ── R CMD check results ──────────────────────────────── brochure 0.0.0.9024 ────#> Duration: 12.1s#>#> 0 errors ✔ | 0 warnings ✔ | 0 notes ✔
covr::package_coverage()#> brochure Coverage: 42.07%#> R/brochure-fns.R: 0.00%#> R/brochureApp.R: 0.00%#> R/req_res_handlers.R: 0.00%#> R/server-side.R: 0.00%#> R/utils_page.R: 0.00%#> R/utils_req.R: 0.00%#> R/cookie.R: 93.91%#> R/golem_hook.R: 100.00%#> R/new_page.R: 100.00%#> R/utils.R: 100.00%

Minimal{brochure} App

page()

AbrochureApp is a series ofpages that are defined by anhref(the path/endpoint where the page is available), a{shiny} UI and aserver function. This is conceptually important: each page has its ownshiny session, its own UI, and its own server.

Note that the server is optional if you want to display a static page.

brochureApp(# First page  page(href="/",ui= fluidPage(      h1("This is my first page"),      plotOutput("plot")    ),server=function(input,output,session) {output$plot<- renderPlot({        plot(iris)      })    }  ),# Second page, without any server-side function  page(href="/page2",ui= fluidPage(      h1("This is my second page"),tags$p("There is no server function in this one")    )  ))

You can now navigate to /, and to /page2 inside your browser.

redirect()

Redirections can be used to redirect from one endpoint to the other:

brochureApp(  page(href="/",ui= tagList(      h1("This is my first page")    )  ),  redirect(from="/nothere",to="/"  ))

You can now navigate to /nothere, you’ll be redirected to /

A more elaborate example:

# Creating a navlinknav_links<-tags$ul(tags$li(tags$a(href="/","home"),  ),tags$li(tags$a(href="/page2","page2"),  ),tags$li(tags$a(href="/contact","contact"),  ))page_1<-function() {  page(href="/",ui=function(request) {      tagList(        h1("This is my first page"),nav_links,        plotOutput("plot")      )    },server=function(input,output,session) {output$plot<- renderPlot({        plot(mtcars)      })    }  )}page_2<-function() {  page(href="/page2",ui=function(request) {      tagList(        h1("This is my second page"),nav_links,        plotOutput("plot")      )    },server=function(input,output,session) {output$plot<- renderPlot({        plot(mtcars)      })    }  )}page_contact<-function() {  page(href="/contact",ui= tagList(      h1("Contact us"),nav_links,tags$ul(tags$li("Here"),tags$li("There")      )    )  )}brochureApp(# Pages  page_1(),  page_2(),  page_contact(),# Redirections  redirect(from="/page3",to="/page2"  ),  redirect(from="/page4",to="/"  ))

IMPORTANT NOTE all elements which are not of class"brochure_*"(brochure_page andbrochure_redirect) will be injectedas is inthe page. In other word, if you use a function that return a string, thestring will be added as is to the pages. For example, this will inject a"x" on each page. This is probablyNOT what you want to do, butcan be the source of some bugs you’ll have with your app.

brochureApp("x",  page(href="/"  ))

req_handlers &res_handlers

Sorry what?

Each page, and the global app, have areq_handlers andres_handlersparameters, that can take alist of functions.

An*_handler is a function that takes as parameter(s):

  • Forreq_handlers,req, which is the request object (see below forwhen these objects are created). For examplefunction(req){ print(req$PATH_INFO); return(req)}.

  • Forres_handlers,res, the response object, &req. For examplefunction(res, req){ print(res$content); return(res)}.

req_handlersmust returnreq &res_handlersmust returnres. Both can be potentially modified.

They can be used to register log, or to modify the objects, or any kindof things you can think of. If you are familiar withexpress.js, youcan think ofreq_handlers as what express calls “middleware”. Thesefunctions are run when R is building the HTTP response to send to thebrowser (i.e, no server code has been run yet), following this process:

  1. R receives aGET request from the browser, creating a requestobject, calledreq
  2. Thereq_handlers are run using thisreq object
  3. R creates anhttpResponse, using thisreq and how you definedthe UI
  4. Theres_handlers are run on thishttpResponse (first app levelres_handlers, then page levelres_handlers)
  5. ThehttpResponse is sent back to the browser

Note that if anyreq_handlers returns anhttpResponse object, itwill be returned to the browser immediately, without any furthercomputation. This earlyhttpResponse will not be passed to theres_handlers of the app or the page. This process can for example beused to send customhttpResponse, as shown below with thehealthcheck endpoint.

You can use formulas inside your handlers..x and..1 will bereqfor req_handlers,.x and..1 will beres &.y and..2 will bereq for res_handlers.

Design pattern side-note: you’d probably want to define the handlersoutside of the app, for better code organization (as withlog_wherebelow).

Example: Logging withreq_handlers(), and building a healthcheck point

In this app, we’ll log to the console every page and the time it iscalled, using thelog_where() function.

log_where<-function(req) {cli::cat_rule(    sprintf("%s - %s",      Sys.time(),req$PATH_INFO    )  )req}

We’ll also build anhealthcheck endpoint that simply returns ahttpResponse with the 200 HTTP code.

# Reusing the pages from beforebrochureApp(req_handlers=list(log_where  ),# Pages  page_1(),  page_2(),  page_contact(),  page(href="/healthcheck",# As this is a pure backend exchange,# We don't need a UIui= tagList(),# As this req_handler returns an httpResponse,# This response will be returned directly to the browser,# without passing through the usual shiny http dancereq_handlers=list(# If you have shiny < 1.6.0, you'll need to# do shiny:::httpResponse (triple `:`)# as it is not exported until 1.6.0.# Otherwise, see ?shiny::httpResponse~shiny::httpResponse(200,content="OK")    )  ))

If you navigate to each page, you’ll see this in the console:

Listening on http://127.0.0.1:4879── 2021-02-17 21:52:16 - / ──────────────────────────────── 2021-02-17 21:52:17 - /page2 ─────────────────────────── 2021-02-17 21:52:19 - /contact ───────────────────────

If you go to another R session, you can check that you’ve got a 200 onhealthcheck

>httr::GET("http://127.0.0.1:4879/healthcheck")Response [http://127.0.0.1:4879/healthcheck]Date:2021-02-1721:55Status:200Content-Type:text/html;charset=UTF-8Size:2B

Handling cookies usingres_handlers

res_handlers can be used to set cookies, by adding aSet-Cookieheader, using both theset_cookie() andremove_cookie() functions.

Note that you can get them from the server withget_cookies(), andparse the cookie string usingparse_cookie_string.

parse_cookie_string("a=12;session=blabla")#>        a  session#>     "12" "blabla"

In the example, we’ll also usebrochure::server_redirect("/") toredirect the user after login.

# Creating a navlinknav_links<-tags$ul(tags$li(tags$a(href="/","home"),  ),tags$li(tags$a(href="/login","login"),  ),tags$li(tags$a(href="/logout","logout"),  ))home<-function() {  page(href="/",ui= tagList(      h1("This is my first page"),tags$p("It will contain BROCHURECOOKIE depending on the last page you've visited (/login or /logout)"),      verbatimTextOutput("cookie"),nav_links    ),server=function(input,output,session) {output$cookie<- renderPrint({        parse_cookie_string(          get_cookies()        )      })    }  )}login<-function() {  page(href="/login",ui= tagList(      h1("You've just logged!"),      verbatimTextOutput("cookie"),      actionButton("redirect","Redirect to the home page"),nav_links    ),server=function(input,output,session) {output$cookie<- renderPrint({        parse_cookie_string(          get_cookies()        )      })      observeEvent(input$redirect, {# Using brochure to redirect to another page        server_redirect("/")      })    },res_handlers=list(# We'll add a cookie here~ set_cookie(.x,"BROCHURECOOKIE",12)# If you had to do it yourself# function(res, req){#   res$headers$`Set-Cookie` <- "BROCHURECOOKIE=12; HttpOnly;"#   res# }    )  )}logout<-function() {  page(href="/logout",ui= tagList(      h1("You've logged out"),nav_links,      verbatimTextOutput("cookie")    ),server=function(input,output,session) {output$cookie<- renderPrint({        parse_cookie_string(          get_cookies()        )      })    },res_handlers=list(# We'll remove the cookie here~ remove_cookie(.x,"BROCHURECOOKIE")# If you had to do it yourself# function(res, req){#   res$headers$`Set-Cookie` <- "BROCHURECOOKIE=''; Max-Age = 0;"#   res# }    )  )}brochureApp(# Pages  home(),  login(),  logout())

Design pattern

Note that every time you open a new page, anew shiny session islaunched. This is different from what you usually do when you arebuilding a{shiny} app that works as a single page application. Thisis no longer the case in{brochure}.

What that means is that there is no data persistence in R whennavigating from one page to the other. That might seem like a downside,but I believe that it will actually be for the best: it will makedevelopers think more carefully about the data flow of theirapplication.

That being said, how do we keep track of a user though pages, so that ifthey do something in a page, it’s reflected on another?

To do that, you’d need to add a form of session identifier, like acookie: this can for example be done using the{glouton} package if you wantto manage it with JS. You can also use the cookie example from before.

You’ll also need a form of backend storage (here in the example, we use{cachem}, but you can also use anexternal DB like SQLite or MongoDB).

library(glouton)# Creating a storage systemcache_system<-cachem::cache_disk(tempdir())nav_links<-tags$ul(tags$li(tags$a(href="/","home"),  ),tags$li(tags$a(href="/page2","page2"),  ))cookie_set<-function() {r<- reactiveValues()  observeEvent(TRUE,    {# Fetch the cookies using {glouton}r$cook<- fetch_cookies()# If there is no stored cookie for {brochure}, we generate itif (is.null(r$cook$brochure_cookie)) {# Generate a random idsession_id<-digest::sha1(paste(Sys.time(), sample(letters,16)))# Add this id as a cookie        add_cookie("brochure_cookie",session_id)# Store in in the reactiveValues listr$cook$brochure_cookie<-session_id      }# For debugging purpose      print(r$cook$brochure_cookie)    },once=TRUE  )return(r)}page_1<-function() {  page(href="/",ui= tagList(      h1("This is my first page"),nav_links,# The text enter on page 1 will be available on page 2, using# a session cookie and a storage system      textInput("textenter","Enter a text"),      actionButton("save","Save my text and go to page2")    ),server=function(input,output,session) {r<- cookie_set()      observeEvent(input$save, {# Use the session id to save on the cache systemcache_system$set(          paste0(r$cook$brochure_cookie,"text"          ),input$textenter        )        server_redirect("/page2")      })    }  )}page_2<-function() {  page(href="/page2",ui= tagList(      h1("This is my second page"),nav_links,# The text enter on page 1 will be available here, reading# the storage system      verbatimTextOutput("textdisplay")    ),server=function(input,output,session) {r<- cookie_set()output$textdisplay<- renderPrint({# Getting the content value based on the session cookiecache_system$get(          paste0(r$cook$brochure_cookie,"text"          )        )      })    }  )}brochureApp(# Setting {glouton} globally  use_glouton(),# Pages  page_1(),  page_2()# Redirections)

With{golem}

Fresh{golem} App

You can set up a{brochure} based app with{golem} using thebrochure::golem_hook() function.

golem::create_golem("mapmyrace",project_hook=brochure::golem_hook)

You can also use the module_template function to create a{brochure}module :

golem::add_module(name="pouet",module_template=brochure::new_page)

Adapt old app

To adapt your{golem} based application to{brochure}, here are thetwo steps to follow:

  • Remove the app_server.R file, and the top of app_ui => You’ll stillneedgolem_add_external_resources().

  • Build the pages inside separate R scripts, following the example fromthisREADME.

.├── DESCRIPTION├── NAMESPACE├── R│   ├── app_config.R│   ├── home.R ### YOUR PAGE│   ├── login.R ### YOUR PAGE│   ├── logout.R ### YOUR PAGE│   └── run_app.R ### YOUR PAGE├── dev│   ├── 01_start.R│   ├── 02_dev.R│   ├── 03_deploy.R│   └── run_dev.R├── inst│   ├── app│   │   └── www│   │       ├── favicon.ico│   └── golem-config.yml├── man│   └── run_app.Rd
  • ReplaceshinyApp withbrochureApp inrun_app(), add the externalresources, then your pages.
run_app<-function(onStart=NULL,options=list(),enableBookmarking=NULL,...) {  with_golem_options(app= brochureApp(# Putting the resources here      golem_add_external_resources(),      home(),      login(),      logout(),onStart=onStart,options=options,enableBookmarking=enableBookmarking    ),golem_opts=list(...)  )}

Previous work

Other packages that implements features that are closed to what{brochure} does:

As far as I can tell, these packages doesn’t serve the same goal as what{brochure} does, as they both still serve Single Page Applications.

About

[WIP] Natively Multipage Shiny Apps

Topics

Resources

License

Unknown, MIT licenses found

Licenses found

Unknown
LICENSE
MIT
LICENSE.md

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp